From b40ada91f48411fa2a9ca6e0cdafcd0919fb46a0 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:48 +0000 Subject: [PATCH 1/4] feat: find a compilation database and explain missing includes Without --database, look for compile_commands.json in the repository root and in common build folders (build, out, builddir, _build, cmake-build-debug, cmake-build-release), and warn when there is none. When clang-tidy reports an included file as not found, the comment says this usually means it does not know how the code is built. --- cpp-linter/src/clang_tools/mod.rs | 56 +++++++++++++++++++++++++++ cpp-linter/src/cli/mod.rs | 7 +++- cpp-linter/src/rest_client/comment.rs | 23 +++++++++++ cpp-linter/src/rest_client/test.rs | 22 +++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index de2d2ca4..79adce8c 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -145,6 +145,25 @@ async fn analyze_files( Ok(logs) } +/// Build folders (relative to the repository root) searched for a +/// compile_commands.json when no `--database` is given. +const DATABASE_DIRS: [&str; 6] = [ + "build", + "out", + "builddir", + "_build", + "cmake-build-debug", + "cmake-build-release", +]; + +/// Find the folder of a compile_commands.json when no `--database` is given: +/// the repository root, then the common build folders in [`DATABASE_DIRS`]. +fn find_database(repo_root: &Path) -> Option { + std::iter::once(repo_root.to_path_buf()) + .chain(DATABASE_DIRS.iter().map(|dir| repo_root.join(dir))) + .find(|dir| dir.join("compile_commands.json").is_file()) +} + /// A struct to contain the version numbers of the clang-tools used #[derive(Debug, Default)] pub struct ClangVersions { @@ -204,6 +223,26 @@ pub async fn capture_clang_tools_output( clang_versions.format_version = Some(tool_info.version); clang_params.clang_format_command = Some(tool_info.path); } + if clang_params.tidy_checks != "-*" && clang_params.database.is_none() { + match find_database(&clang_params.repo_root) { + Some(db_path) => { + log::info!( + "Using the compilation database found in {}", + db_path.to_string_lossy() + ); + clang_params.database = Some(db_path); + } + None => log::warn!( + "No compilation database found: --database is not set, and there is no \ + compile_commands.json in the repository root or in any of {}. \ + clang-tidy will guess how each file is compiled, so it may report \ + \"file not found\" errors that are not in the code. \ + Generate one (with CMake: -DCMAKE_EXPORT_COMPILE_COMMANDS=ON) \ + and pass its folder with --database.", + DATABASE_DIRS.join(", ") + ), + } + } if let Some(db_path) = &clang_params.database { let db_path = db_path.join("compile_commands.json"); match fs::read_to_string(&db_path) { @@ -622,6 +661,23 @@ mod tests { capture_clang_tools_output(&[], &version, clang_params, &rest_client, false).await } + #[test] + fn find_database_in_build_folder() { + let tmp_dir = tempfile::tempdir().unwrap(); + let root = tmp_dir.path(); + assert_eq!(find_database(root), None); + fs::create_dir(root.join("out")).unwrap(); + fs::write(root.join("out/compile_commands.json"), "[]").unwrap(); + assert_eq!(find_database(root), Some(root.join("out"))); + // "build" comes before "out" + fs::create_dir(root.join("build")).unwrap(); + fs::write(root.join("build/compile_commands.json"), "[]").unwrap(); + assert_eq!(find_database(root), Some(root.join("build"))); + // the repository root comes first + fs::write(root.join("compile_commands.json"), "[]").unwrap(); + assert_eq!(find_database(root), Some(root.to_path_buf())); + } + #[tokio::test] async fn bad_db_path() { test_db_parse("nonexistent/path").await.unwrap(); diff --git a/cpp-linter/src/cli/mod.rs b/cpp-linter/src/cli/mod.rs index 70c0e45c..c936b68a 100644 --- a/cpp-linter/src/cli/mod.rs +++ b/cpp-linter/src/cli/mod.rs @@ -470,8 +470,11 @@ pub struct TidyOptions { /// /// For example, it can be a CMake build directory in which a file named /// compile_commands.json exists (set `CMAKE_EXPORT_COMPILE_COMMANDS` to `ON`). - /// When no build path is specified, a search for compile_commands.json will be - /// attempted through all parent paths of the first input file. See [LLVM docs about + /// When no build path is specified, cpp-linter looks for a compile_commands.json + /// in the repository root and then in its `build`, `out`, `builddir`, `_build`, + /// `cmake-build-debug` and `cmake-build-release` folders, and warns if there is none. + /// Without a compilation database, clang-tidy guesses how each file is compiled and + /// often reports false "file not found" errors. See [LLVM docs about /// setup tooling](https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) /// for an example of setting up Clang Tooling on a source tree. #[cfg_attr( diff --git a/cpp-linter/src/rest_client/comment.rs b/cpp-linter/src/rest_client/comment.rs index b9c532d7..91732421 100644 --- a/cpp-linter/src/rest_client/comment.rs +++ b/cpp-linter/src/rest_client/comment.rs @@ -146,6 +146,18 @@ impl Findings { .flat_map(|file| file.tidy_notes.iter().map(move |note| (file, note))) } + /// Count the clang-tidy errors about an included file that was not found. + /// + /// These usually mean clang-tidy ran without (or with the wrong) compilation database. + fn missing_includes(&self) -> u64 { + self.tidy_notes() + .filter(|(_, note)| { + note.diagnostic == "clang-diagnostic-error" + && note.rationale.ends_with("file not found") + }) + .count() as u64 + } + /// Describe the clang-tidy notes in a few words: `1 error, 2 warnings, 1 fixable`. /// /// Also returns the status of the clang-tidy check. @@ -264,6 +276,17 @@ impl Findings { } } + let missing = self.missing_includes(); + if missing > 0 { + comment.push_str(&format!( + "\nclang-tidy could not find {}, so it likely does not know how this code \ + is built, and its other findings may be wrong too. Generate a compilation \ + database (with CMake: `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`) and pass its \ + folder as the `database` option.\n", + plural(missing, "included file") + )); + } + // "How to fix" matters most when there are many findings, so room for it is kept // before the findings are listed (if it fits at all). let how_to_fix = self.how_to_fix(ctx); diff --git a/cpp-linter/src/rest_client/test.rs b/cpp-linter/src/rest_client/test.rs index 23cbc9f2..d2324900 100644 --- a/cpp-linter/src/rest_client/test.rs +++ b/cpp-linter/src/rest_client/test.rs @@ -266,6 +266,28 @@ fn comment_names_files_from_the_repository_root() { ); } +#[test] +fn missing_includes_get_a_hint() { + let files = make_dummy_files("error"); + let comment = + RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, false, "file".into()) + .unwrap(); + assert!(!comment.contains("compilation database"), "{comment}"); + + files[0].lock().unwrap().tidy_advice.as_mut().unwrap().notes[0].rationale = + String::from("'demo.hpp' file not found"); + let comment = + RestClient::make_comment(&files, 0, 1, &dummy_versions(), None, false, "file".into()) + .unwrap(); + assert!( + comment.contains("clang-tidy could not find 1 included file, so"), + "{comment}" + ); + // the hint comes before the findings + let hint = comment.find("Generate a compilation database").unwrap(); + assert!(hint < comment.find("demo.cpp").unwrap(), "{comment}"); +} + #[test] fn skipped_fix_with_pipe_stays_in_its_cell() { let files = make_dummy_files("warning"); From 4ce36b0831ecead06d0daa630d1ecd5de3e5647c Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:32:48 +0000 Subject: [PATCH 2/4] test: cover using a found compilation database --- cpp-linter/src/clang_tools/mod.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index 79adce8c..d9aa2b88 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -678,6 +678,26 @@ mod tests { assert_eq!(find_database(root), Some(root.to_path_buf())); } + #[tokio::test] + async fn found_db_is_used() { + let tmp_dir = tempfile::tempdir().unwrap(); + fs::create_dir(tmp_dir.path().join("build")).unwrap(); + fs::write(tmp_dir.path().join("build/compile_commands.json"), "[]").unwrap(); + let clang_params = ClangParams { + repo_root: tmp_dir.path().to_path_buf(), + ..Default::default() + }; + let version = RequestedVersion::default(); + unsafe { + env::remove_var("GITHUB_ACTIONS"); + } + let rest_client = RestClient::new(&PathBuf::from(".")).unwrap(); + try_init_logger(); + capture_clang_tools_output(&[], &version, clang_params, &rest_client, false) + .await + .unwrap(); + } + #[tokio::test] async fn bad_db_path() { test_db_parse("nonexistent/path").await.unwrap(); From 56ce40084b6e923d68e580f40109435eb681f5a0 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:09:50 +0000 Subject: [PATCH 3/4] test: check the found database and a real missing-include line Move the database search into use_found_database() so a test can check which database is used, and parse a missing include exactly as clang-tidy prints it (error, not fatal error). --- cpp-linter/src/clang_tools/clang_tidy/test.rs | 20 +++++ cpp-linter/src/clang_tools/mod.rs | 77 +++++++++++-------- 2 files changed, 65 insertions(+), 32 deletions(-) diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index a9d80e8e..63c85196 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -360,6 +360,26 @@ fn parse_non_utf8_output() { assert!(matches!(err, ClangCaptureError::NonUtf8Output { .. })); } +/// A missing include, exactly as clang-tidy prints it (it reports clang's fatal +/// error as `error`), is the note that the comment counts as a missing include. +#[test] +fn parse_missing_include() { + let notes = parse_tidy_output( + b"demo.cpp:1:10: error: 'nope.h' file not found [clang-diagnostic-error]\n", + &None, + &env::current_dir().unwrap(), + ) + .unwrap(); + assert_eq!(notes.len(), 1); + assert_eq!(notes[0].severity, "error"); + assert_eq!(notes[0].diagnostic, "clang-diagnostic-error"); + assert!( + notes[0].rationale.ends_with("file not found"), + "{:?}", + notes[0].rationale + ); +} + #[test] fn parse_with_database_units() { let build_dir = env::current_dir().unwrap().join("build"); diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index d9aa2b88..0b857547 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -164,6 +164,32 @@ fn find_database(repo_root: &Path) -> Option { .find(|dir| dir.join("compile_commands.json").is_file()) } +/// Without `--database`, use a compile_commands.json found by [`find_database()`], +/// or warn that clang-tidy has to guess how each file is compiled. +fn use_found_database(clang_params: &mut ClangParams) { + if clang_params.database.is_some() { + return; + } + match find_database(&clang_params.repo_root) { + Some(db_path) => { + log::info!( + "Using the compilation database found in {}", + db_path.to_string_lossy() + ); + clang_params.database = Some(db_path); + } + None => log::warn!( + "No compilation database found: --database is not set, and there is no \ + compile_commands.json in the repository root or in any of {}. \ + clang-tidy will guess how each file is compiled, so it may report \ + \"file not found\" errors that are not in the code. \ + Generate one (with CMake: -DCMAKE_EXPORT_COMPILE_COMMANDS=ON) \ + and pass its folder with --database.", + DATABASE_DIRS.join(", ") + ), + } +} + /// A struct to contain the version numbers of the clang-tools used #[derive(Debug, Default)] pub struct ClangVersions { @@ -223,25 +249,8 @@ pub async fn capture_clang_tools_output( clang_versions.format_version = Some(tool_info.version); clang_params.clang_format_command = Some(tool_info.path); } - if clang_params.tidy_checks != "-*" && clang_params.database.is_none() { - match find_database(&clang_params.repo_root) { - Some(db_path) => { - log::info!( - "Using the compilation database found in {}", - db_path.to_string_lossy() - ); - clang_params.database = Some(db_path); - } - None => log::warn!( - "No compilation database found: --database is not set, and there is no \ - compile_commands.json in the repository root or in any of {}. \ - clang-tidy will guess how each file is compiled, so it may report \ - \"file not found\" errors that are not in the code. \ - Generate one (with CMake: -DCMAKE_EXPORT_COMPILE_COMMANDS=ON) \ - and pass its folder with --database.", - DATABASE_DIRS.join(", ") - ), - } + if clang_params.tidy_checks != "-*" { + use_found_database(&mut clang_params); } if let Some(db_path) = &clang_params.database { let db_path = db_path.join("compile_commands.json"); @@ -678,24 +687,28 @@ mod tests { assert_eq!(find_database(root), Some(root.to_path_buf())); } - #[tokio::test] - async fn found_db_is_used() { + #[test] + fn found_db_is_used() { let tmp_dir = tempfile::tempdir().unwrap(); - fs::create_dir(tmp_dir.path().join("build")).unwrap(); - fs::write(tmp_dir.path().join("build/compile_commands.json"), "[]").unwrap(); - let clang_params = ClangParams { + let mut clang_params = ClangParams { repo_root: tmp_dir.path().to_path_buf(), ..Default::default() }; - let version = RequestedVersion::default(); - unsafe { - env::remove_var("GITHUB_ACTIONS"); - } - let rest_client = RestClient::new(&PathBuf::from(".")).unwrap(); try_init_logger(); - capture_clang_tools_output(&[], &version, clang_params, &rest_client, false) - .await - .unwrap(); + // nothing found: only a warning + use_found_database(&mut clang_params); + assert_eq!(clang_params.database, None); + + fs::create_dir(tmp_dir.path().join("build")).unwrap(); + fs::write(tmp_dir.path().join("build/compile_commands.json"), "[]").unwrap(); + use_found_database(&mut clang_params); + assert_eq!(clang_params.database, Some(tmp_dir.path().join("build"))); + + // a given database is kept + let given = Some(PathBuf::from("elsewhere")); + clang_params.database = given.clone(); + use_found_database(&mut clang_params); + assert_eq!(clang_params.database, given); } #[tokio::test] From 9022c94c61cf053a9bf31e0961761d75bed3fab2 Mon Sep 17 00:00:00 2001 From: Xianpeng Shen <3353385+shenxianpeng@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:01:07 +0000 Subject: [PATCH 4/4] refactor: only warn when no compilation database is given Drop the search for compile_commands.json in build folders: a found database may be stale or belong to other sources. --- cpp-linter/src/clang_tools/mod.rs | 96 ++++++------------------------- cpp-linter/src/cli/mod.rs | 8 +-- 2 files changed, 19 insertions(+), 85 deletions(-) diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index 0b857547..c46e8155 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -145,48 +145,15 @@ async fn analyze_files( Ok(logs) } -/// Build folders (relative to the repository root) searched for a -/// compile_commands.json when no `--database` is given. -const DATABASE_DIRS: [&str; 6] = [ - "build", - "out", - "builddir", - "_build", - "cmake-build-debug", - "cmake-build-release", -]; - -/// Find the folder of a compile_commands.json when no `--database` is given: -/// the repository root, then the common build folders in [`DATABASE_DIRS`]. -fn find_database(repo_root: &Path) -> Option { - std::iter::once(repo_root.to_path_buf()) - .chain(DATABASE_DIRS.iter().map(|dir| repo_root.join(dir))) - .find(|dir| dir.join("compile_commands.json").is_file()) -} - -/// Without `--database`, use a compile_commands.json found by [`find_database()`], -/// or warn that clang-tidy has to guess how each file is compiled. -fn use_found_database(clang_params: &mut ClangParams) { - if clang_params.database.is_some() { - return; - } - match find_database(&clang_params.repo_root) { - Some(db_path) => { - log::info!( - "Using the compilation database found in {}", - db_path.to_string_lossy() - ); - clang_params.database = Some(db_path); - } - None => log::warn!( - "No compilation database found: --database is not set, and there is no \ - compile_commands.json in the repository root or in any of {}. \ - clang-tidy will guess how each file is compiled, so it may report \ - \"file not found\" errors that are not in the code. \ - Generate one (with CMake: -DCMAKE_EXPORT_COMPILE_COMMANDS=ON) \ - and pass its folder with --database.", - DATABASE_DIRS.join(", ") - ), +/// Warn that clang-tidy has to guess how each file is compiled when `--database` +/// is not given. +fn warn_without_database(clang_params: &ClangParams) { + if clang_params.database.is_none() { + log::warn!( + "--database is not set, so clang-tidy will guess how each file is compiled \ + and may report \"file not found\" errors that are not in the code. \ + Pass the folder of a compile_commands.json with --database." + ); } } @@ -250,7 +217,7 @@ pub async fn capture_clang_tools_output( clang_params.clang_format_command = Some(tool_info.path); } if clang_params.tidy_checks != "-*" { - use_found_database(&mut clang_params); + warn_without_database(&clang_params); } if let Some(db_path) = &clang_params.database { let db_path = db_path.join("compile_commands.json"); @@ -671,44 +638,13 @@ mod tests { } #[test] - fn find_database_in_build_folder() { - let tmp_dir = tempfile::tempdir().unwrap(); - let root = tmp_dir.path(); - assert_eq!(find_database(root), None); - fs::create_dir(root.join("out")).unwrap(); - fs::write(root.join("out/compile_commands.json"), "[]").unwrap(); - assert_eq!(find_database(root), Some(root.join("out"))); - // "build" comes before "out" - fs::create_dir(root.join("build")).unwrap(); - fs::write(root.join("build/compile_commands.json"), "[]").unwrap(); - assert_eq!(find_database(root), Some(root.join("build"))); - // the repository root comes first - fs::write(root.join("compile_commands.json"), "[]").unwrap(); - assert_eq!(find_database(root), Some(root.to_path_buf())); - } - - #[test] - fn found_db_is_used() { - let tmp_dir = tempfile::tempdir().unwrap(); - let mut clang_params = ClangParams { - repo_root: tmp_dir.path().to_path_buf(), - ..Default::default() - }; + fn warn_only_without_database() { try_init_logger(); - // nothing found: only a warning - use_found_database(&mut clang_params); - assert_eq!(clang_params.database, None); - - fs::create_dir(tmp_dir.path().join("build")).unwrap(); - fs::write(tmp_dir.path().join("build/compile_commands.json"), "[]").unwrap(); - use_found_database(&mut clang_params); - assert_eq!(clang_params.database, Some(tmp_dir.path().join("build"))); - - // a given database is kept - let given = Some(PathBuf::from("elsewhere")); - clang_params.database = given.clone(); - use_found_database(&mut clang_params); - assert_eq!(clang_params.database, given); + warn_without_database(&ClangParams::default()); + warn_without_database(&ClangParams { + database: Some(PathBuf::from("build")), + ..Default::default() + }); } #[tokio::test] diff --git a/cpp-linter/src/cli/mod.rs b/cpp-linter/src/cli/mod.rs index c936b68a..9c01aacd 100644 --- a/cpp-linter/src/cli/mod.rs +++ b/cpp-linter/src/cli/mod.rs @@ -470,11 +470,9 @@ pub struct TidyOptions { /// /// For example, it can be a CMake build directory in which a file named /// compile_commands.json exists (set `CMAKE_EXPORT_COMPILE_COMMANDS` to `ON`). - /// When no build path is specified, cpp-linter looks for a compile_commands.json - /// in the repository root and then in its `build`, `out`, `builddir`, `_build`, - /// `cmake-build-debug` and `cmake-build-release` folders, and warns if there is none. - /// Without a compilation database, clang-tidy guesses how each file is compiled and - /// often reports false "file not found" errors. See [LLVM docs about + /// When no build path is specified, a search for compile_commands.json will be + /// attempted through all parent paths of the first input file, and cpp-linter + /// warns that clang-tidy may report false "file not found" errors. See [LLVM docs about /// setup tooling](https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) /// for an example of setting up Clang Tooling on a source tree. #[cfg_attr(