Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions cpp-linter/src/clang_tools/clang_tidy/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
25 changes: 25 additions & 0 deletions cpp-linter/src/clang_tools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,18 @@ async fn analyze_files(
Ok(logs)
}

/// 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."
);
}
}

/// A struct to contain the version numbers of the clang-tools used
#[derive(Debug, Default)]
pub struct ClangVersions {
Expand Down Expand Up @@ -204,6 +216,9 @@ 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 != "-*" {
warn_without_database(&clang_params);
}
if let Some(db_path) = &clang_params.database {
let db_path = db_path.join("compile_commands.json");
match fs::read_to_string(&db_path) {
Expand Down Expand Up @@ -622,6 +637,16 @@ mod tests {
capture_clang_tools_output(&[], &version, clang_params, &rest_client, false).await
}

#[test]
fn warn_only_without_database() {
try_init_logger();
warn_without_database(&ClangParams::default());
warn_without_database(&ClangParams {
database: Some(PathBuf::from("build")),
..Default::default()
});
}

#[tokio::test]
async fn bad_db_path() {
test_db_parse("nonexistent/path").await.unwrap();
Expand Down
3 changes: 2 additions & 1 deletion cpp-linter/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,8 @@ 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
/// 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(
Expand Down
23 changes: 23 additions & 0 deletions cpp-linter/src/rest_client/comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Comment thread
shenxianpeng marked this conversation as resolved.
Resolved
})
.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.
Expand Down Expand Up @@ -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);
Expand Down
22 changes: 22 additions & 0 deletions cpp-linter/src/rest_client/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down