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
81 changes: 79 additions & 2 deletions cpp-linter/src/clang_tools/clang_tidy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,17 @@ impl TidyNotification {
}

/// A struct to hold notification from clang-tidy about a single file
#[derive(Debug, Clone)]
#[derive(Debug, Clone, Default)]
pub struct TidyAdvice {
/// A list of notifications parsed from clang-tidy stdout.
pub notes: Vec<TidyNotification>,

/// Is `true` if clang-tidy did not analyze the file (see [`tidy_failure()`]).
///
/// Such a file has no [`TidyAdvice::notes`], but it still counts as a failed
/// clang-tidy check, so an out-of-date or empty compilation database does not
/// pass silently.
pub failed: bool,
}

impl TidyAdvice {
Expand Down Expand Up @@ -328,6 +335,9 @@ pub fn tally_tidy_advice(files: &[Arc<Mutex<FileObj>>]) -> Result<u64, String> {
for file in files {
let file = file.lock().map_err(|e| e.to_string())?;
if let Some(advice) = &file.tidy_advice {
if advice.failed {
total += 1;
}
for tidy_note in &advice.notes {
let file_path = PathBuf::from(&tidy_note.filename);
if file_path == file.name {
Expand Down Expand Up @@ -703,6 +713,52 @@ fn read_exported_fixes(fixes_path: &Path) -> Result<ExportedFixes, ClangCaptureE
})
}

/// Find out whether clang-tidy failed to analyze a file, from how it exited.
///
/// Returns the part of clang-tidy's `stderr` that explains the failure, or [`None`]
/// if clang-tidy analyzed the file.
///
/// clang-tidy exits with an error and reports nothing when it crashes, for example
/// when the compilation database names a build directory that does not exist
/// ("LLVM ERROR: Cannot chdir into ..."). It exits successfully but skips the file
/// when the compilation database has no entry to compile it with (for example an
/// empty `compile_commands.json`). Either way, the file was not checked.
///
/// A non-zero exit with notes is not a failure: clang-tidy also exits with an error
/// when it reports compiler errors. Neither is "no checks enabled", which is how a
/// `.clang-tidy` file turns clang-tidy off for some folders.
pub(crate) fn tidy_failure(
success: bool,
stderr: &str,
notes: &[TidyNotification],
) -> Option<String> {
let skipped = stderr.contains("Compile command not found.");
let crashed = !success
&& notes.is_empty()
&& !stderr
.lines()
.any(|line| line.trim() == "Error: no checks enabled.");
if !skipped && !crashed {
return None;
}
// Leave out a crash's stack dump.
let reason = stderr
.lines()
.map(str::trim_end)
.filter(|line| !line.is_empty())
.take_while(|line| {
!line.starts_with("PLEASE submit a bug report") && !line.starts_with("Stack dump:")
})
.take(10)
.collect::<Vec<_>>()
.join("\n");
Some(if reason.is_empty() {
String::from("clang-tidy exited with an error and reported nothing")
} else {
reason
})
}

/// Run clang-tidy, then parse and return it's output.
///
/// clang-tidy is not allowed to modify any files.
Expand Down Expand Up @@ -776,6 +832,24 @@ pub fn run_clang_tidy(
&clang_params.database_json,
&clang_params.repo_root,
)?;
if let Some(reason) = tidy_failure(
output.status.success(),
&String::from_utf8_lossy(&output.stderr),
&notes,
) {
logs.push((
log::Level::Warn,
format!(
"clang-tidy did not analyze {file_name}; counting it as a failed check:\n{reason}"
),
));
remove_file_if_exists(&fixes_path)?;
file.tidy_advice = Some(TidyAdvice {
failed: true,
..Default::default()
});
return Ok((logs, TidyFixes::default()));
}

let fixes = read_exported_fixes(&fixes_path)?;
let working_dir = std::path::absolute(&clang_params.repo_root)
Expand All @@ -787,7 +861,10 @@ pub fn run_clang_tidy(
if clang_params.gen_patch {
file.patched_path = Some(write_cache(clang_params, &file.name, &patched)?);
}
file.tidy_advice = Some(TidyAdvice { notes });
file.tidy_advice = Some(TidyAdvice {
notes,
failed: false,
});
Ok((logs, tidy_fixes))
}

Expand Down
4 changes: 1 addition & 3 deletions cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,9 +301,7 @@ pub fn apply_other_file_fixes(
file.patched_path = Some(write_cache(clang_params, &file.name, &patched)?);
}
let name = file.name.to_string_lossy().replace('\\', "/");
let advice = file
.tidy_advice
.get_or_insert_with(|| TidyAdvice { notes: vec![] });
let advice = file.tidy_advice.get_or_insert_with(TidyAdvice::default);
for note in notes {
merge_note(&mut advice.notes, note, &name);
}
Expand Down
1 change: 1 addition & 0 deletions cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ fn not_analyzed() {
let mut source = FileObj::new(PathBuf::from("fix.cpp"));
source.tidy_advice = Some(TidyAdvice {
notes: vec![source_note()],
..Default::default()
});
let files = as_files(vec![source]);
let mut without_note = header_fix(tmp.path());
Expand Down
155 changes: 152 additions & 3 deletions cpp-linter/src/clang_tools/clang_tidy/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ use crate::{

use super::{
CLANG_DIAGNOSTICS_URL, ClangCaptureError, CompilationUnit, ExportedFixes, FixPaths,
NOTE_HEADER, OtherFileFix, Replacement, TidyNotification, apply_fixes, run_clang_tidy,
NOTE_HEADER, OtherFileFix, Replacement, TidyAdvice, TidyNotification, apply_fixes,
run_clang_tidy, tally_tidy_advice, tidy_failure,
};

#[test]
Expand Down Expand Up @@ -285,6 +286,7 @@ fn tally_counts_matching_notes() {
// does not match the file name -> not counted
dummy_note("other.cpp", vec![]),
],
..Default::default()
});
let files = vec![Arc::new(Mutex::new(file))];
assert_eq!(tally_tidy_advice(&files).unwrap(), 1);
Expand All @@ -296,6 +298,7 @@ fn suggestion_help_with_and_without_fixes() {

let advice = TidyAdvice {
notes: vec![dummy_note("demo.cpp", vec![5])],
..Default::default()
};
// A fixed line within the range yields the severity, the diagnostic and the rationale.
let help = advice.get_suggestion_help(1, 10);
Expand Down Expand Up @@ -328,7 +331,10 @@ fn suggestion_help_lists_a_multi_line_fix_once() {
file: "demo.h".to_string(),
reason: "it is not one of the analyzed files".to_string(),
});
let advice = TidyAdvice { notes: vec![note] };
let advice = TidyAdvice {
notes: vec![note],
..Default::default()
};
let help = advice.get_suggestion_help(1, 10);
assert_eq!(help.matches("a dummy rationale").count(), 1);
assert_eq!(help.matches("/m/w.png\"> Part of this fix").count(), 1);
Expand All @@ -346,7 +352,10 @@ fn suggestion_help_with_skipped_fixes() {
file: "demo.h".to_string(),
reason: "it is not one of the analyzed files".to_string(),
});
let advice = TidyAdvice { notes: vec![note] };
let advice = TidyAdvice {
notes: vec![note],
..Default::default()
};
let help = advice.get_suggestion_help(5, 5);
assert!(help.contains(
"/m/w.png\"> Part of this fix was not applied to `demo.h` \
Expand Down Expand Up @@ -861,3 +870,143 @@ Diagnostics:
assert!(tidy_fixes.others.is_empty());
assert_eq!(notes[0].fixed_lines, vec![2]);
}

#[test]
fn tidy_failure_reasons() {
// a crash: the stack dump is left out
let crash = "LLVM ERROR: Cannot chdir into \"/gone/build\"!\n\
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/\n\
Stack dump:\n0.\tProgram arguments: clang-tidy demo.cpp\n";
assert_eq!(
tidy_failure(false, crash, &[]).unwrap(),
"LLVM ERROR: Cannot chdir into \"/gone/build\"!"
);
// a file without an entry in the compilation database is skipped
let skipped = "Skipping /repo/demo.cpp. Compile command not found.\n";
assert_eq!(
tidy_failure(true, skipped, &[]).unwrap(),
"Skipping /repo/demo.cpp. Compile command not found."
);
// an error exit without any explanation
assert_eq!(
tidy_failure(false, "", &[]).unwrap(),
"clang-tidy exited with an error and reported nothing"
);
// compiler errors make clang-tidy exit with an error, but they are findings
let compiler_errors = "1 error generated.\nError while processing demo.cpp.\n";
assert!(tidy_failure(false, compiler_errors, &[dummy_note("demo.cpp", vec![])]).is_none());
// a .clang-tidy file can turn off all checks for some folders
assert!(tidy_failure(false, "Error: no checks enabled.\n", &[]).is_none());
// but not a crash that only mentions those words
let crash = "LLVM ERROR: Cannot chdir into \"/gone/no checks enabled/build\"!\n";
assert!(tidy_failure(false, crash, &[]).is_some());
// a normal run, with or without a summary
assert!(tidy_failure(true, "", &[]).is_none());
assert!(tidy_failure(true, "2 warnings generated.\n", &[]).is_none());
}

#[test]
fn tally_counts_failed_files() {
let mut failed = FileObj::new(PathBuf::from("demo.cpp"));
failed.tidy_advice = Some(TidyAdvice {
failed: true,
..Default::default()
});
let mut found = FileObj::new(PathBuf::from("demo.cpp"));
found.tidy_advice = Some(TidyAdvice {
notes: vec![dummy_note("demo.cpp", vec![])],
..Default::default()
});
let files = [failed, found].map(|file| Arc::new(Mutex::new(file)));
assert_eq!(tally_tidy_advice(&files).unwrap(), 2);
}

#[cfg(unix)]
#[test]
fn tidy_crash_counts_as_failed() {
let tmp_workspace = crate::test_common::setup_tmp_workspace();
let tools_dir = tempfile::tempdir().unwrap();
let fake_tidy = crate::test_common::make_fake_tool(
tools_dir.path(),
"clang-tidy",
r#"printf 'LLVM ERROR: Cannot chdir into "/gone/build"!\nStack dump:\n0. clang-tidy\n' >&2; exit 134"#,
);
let mut clang_params = make_clang_params(tmp_workspace.path(), Some(fake_tidy));
clang_params.gen_patch = true;
let file = Mutex::new(FileObj::new(PathBuf::from("demo/demo.cpp")));
let mut file = file.lock().unwrap();
let (logs, fixes) = run_clang_tidy(&mut file, &clang_params).unwrap();
let advice = file.tidy_advice.as_ref().unwrap();
assert!(advice.failed);
assert!(advice.notes.is_empty());
assert!(fixes.own.is_empty() && fixes.others.is_empty());
let (level, msg) = logs.last().unwrap();
assert_eq!(*level, log::Level::Warn);
assert!(msg.starts_with("clang-tidy did not analyze demo/demo.cpp"));
assert!(msg.ends_with("LLVM ERROR: Cannot chdir into \"/gone/build\"!"));
}

/// Make a workspace with `demo.cpp` and a compilation database (`build/compile_commands.json`).
fn workspace_with_database(database: &str) -> (tempfile::TempDir, ClangParams) {
let tmp_workspace = tempfile::TempDir::with_prefix("cpp-linter-unit-tests_").unwrap();
fs::write(
tmp_workspace.path().join("demo.cpp"),
"int main() { return 0; }\n",
)
.unwrap();
let build = tmp_workspace.path().join("build");
fs::create_dir(&build).unwrap();
fs::write(build.join("compile_commands.json"), database).unwrap();
let mut clang_params = make_clang_params(tmp_workspace.path(), Some(get_tidy_exe()));
clang_params.database = Some(build);
(tmp_workspace, clang_params)
}

/// A compilation database that was made in another folder (eg. on another machine).
#[test]
fn tidy_with_database_from_another_folder() {
let missing = env::temp_dir().join("cpp-linter-unit-tests-missing-build-dir");
assert!(!missing.exists());
let database = serde_json::json!([{
"directory": missing,
"command": "c++ -c demo.cpp",
"file": missing.join("demo.cpp"),
}])
.to_string();
let (_tmp_workspace, clang_params) = workspace_with_database(&database);
let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp")));
let mut file = file.lock().unwrap();
run_clang_tidy(&mut file, &clang_params).unwrap();
assert!(file.tidy_advice.as_ref().unwrap().failed);
}

/// A compilation database without any entries (eg. a header-only CMake project).
#[test]
fn tidy_with_empty_database() {
let (_tmp_workspace, clang_params) = workspace_with_database("[]");
let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp")));
let mut file = file.lock().unwrap();
run_clang_tidy(&mut file, &clang_params).unwrap();
assert!(file.tidy_advice.as_ref().unwrap().failed);
}

/// A compilation database that matches the checkout is used as usual.
#[test]
fn tidy_with_matching_database() {
let (tmp_workspace, mut clang_params) = workspace_with_database("[]");
let database = serde_json::json!([{
"directory": tmp_workspace.path(),
"command": "c++ -c demo.cpp",
"file": tmp_workspace.path().join("demo.cpp"),
}])
.to_string();
let build = clang_params.database.clone().unwrap();
fs::write(build.join("compile_commands.json"), database).unwrap();
clang_params.tidy_checks = "-*,modernize-use-trailing-return-type".to_string();
let file = Mutex::new(FileObj::new(PathBuf::from("demo.cpp")));
let mut file = file.lock().unwrap();
run_clang_tidy(&mut file, &clang_params).unwrap();
let advice = file.tidy_advice.as_ref().unwrap();
assert!(!advice.failed);
assert_eq!(advice.notes.len(), 1);
}
Loading