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
53 changes: 53 additions & 0 deletions cpp-linter/src/clang_tools/clang_tidy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,8 @@ struct ExportedDiagnostic {
#[derive(Deserialize, Debug, Default)]
#[serde(rename_all = "PascalCase")]
struct ExportedMessage {
#[serde(default)]
message: String,
#[serde(default)]
file_path: String,
#[serde(default)]
Expand Down Expand Up @@ -474,6 +476,28 @@ fn apply_fixes<'a>(
) -> (Vec<u8>, TidyFixes) {
let mut tidy_fixes = TidyFixes::default();
for diag in &fixes.diagnostics {
if is_redundant_pointee_fix(diag, &fixes.diagnostics) {
logs.push((
log::Level::Info,
format!(
"Skipping the fix of {} that readability-non-const-parameter also makes: {}",
diag.diagnostic_name, diag.diagnostic_message.message,
),
));
// readability-non-const-parameter inserts its `const` where this diagnostic points,
// so this diagnostic is fixed (on that line) too.
let own_line = paths
.other_file(&diag.build_directory, &diag.diagnostic_message.file_path)
.is_none()
.then(|| offset_to_line(content, diag.diagnostic_message.file_offset));
if let Some(line) = own_line
&& let Some(note) = find_note(diag, paths, content, notes)
&& !note.fixed_lines.contains(&line)
{
note.fixed_lines.push(line);
}
continue;
}
let first_other = tidy_fixes.others.len();
let fixed_lines = collect_diagnostic_fixes(diag, paths, content, &mut tidy_fixes, logs);
let other_fixes = &mut tidy_fixes.others[first_other..];
Expand All @@ -500,6 +524,35 @@ fn apply_fixes<'a>(
(patched, tidy_fixes)
}

/// Is `diag` a misc-const-correctness fix that a readability-non-const-parameter fix
/// (in `all`) also makes?
///
/// For a pointer parameter that is only read, both checks make what it points to
/// `const`: misc-const-correctness as `int const *p` and readability-non-const-parameter
/// as `const int *p`. Applying both makes `const int const *p`, which GCC rejects
/// (duplicate `const`). The fix of readability-non-const-parameter is kept,
/// because it also fixes every other declaration of the function, and it does not
/// change a macro that the parameter's type uses (eg. `int PTR p`).
///
/// Both diagnostics are about the same parameter if readability-non-const-parameter
/// inserts `const` where the misc-const-correctness diagnostic points
/// (the start of that parameter's declaration).
fn is_redundant_pointee_fix(diag: &ExportedDiagnostic, all: &[ExportedDiagnostic]) -> bool {
let msg = &diag.diagnostic_message;
diag.diagnostic_name == "misc-const-correctness"
&& msg.message.starts_with("pointee of variable ")
&& !msg.replacements.is_empty()
&& all.iter().any(|other| {
other.diagnostic_name == "readability-non-const-parameter"
&& other.diagnostic_message.replacements.iter().any(|fix| {
fix.file_path == msg.file_path
&& fix.offset == msg.file_offset
&& fix.length == 0
&& fix.replacement_text.trim() == "const"
})
})
}

/// Sort the replacements of one `diag` into [`TidyFixes::own`] or [`TidyFixes::others`].
///
/// Returns the lines (in the analyzed file's `content`) that this diagnostic fixes.
Expand Down
145 changes: 145 additions & 0 deletions cpp-linter/src/clang_tools/clang_tidy/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1010,3 +1010,148 @@ fn tidy_with_matching_database() {
assert!(!advice.failed);
assert_eq!(advice.notes.len(), 1);
}

/// A diagnostic of `name` at `offset` that inserts each `(offset, text)` of `fixes`.
fn insert_diag(name: &str, message: &str, offset: usize, fixes: &[(usize, &str)]) -> String {
let mut yml = format!(
" - DiagnosticName: {name}\n DiagnosticMessage:\n \
Message: \"{message}\"\n FilePath: 'demo.cpp'\n \
FileOffset: {offset}\n Replacements:\n"
);
for (offset, text) in fixes {
yml.push_str(&format!(
" - FilePath: 'demo.cpp'\n Offset: {offset}\n \
Length: 0\n ReplacementText: '{text}'\n"
));
}
yml
}

/// misc-const-correctness and readability-non-const-parameter both make what a
/// pointer parameter points to `const`, but only one of them is applied.
#[test]
fn pointee_made_const_once() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("demo.cpp");
let content = b"int get(int *p);\nint get(int *p) {\n return *p;\n}\n";
// as exported by clang-tidy 23 (for `p` on line 2)
let pointee = insert_diag(
"misc-const-correctness",
"pointee of variable 'p' of type 'int *' can be declared 'const'",
25,
&[(12, " const"), (29, " const")],
);
let parameter = insert_diag(
"readability-non-const-parameter",
"pointer parameter 'p' can be pointer to const",
30,
&[(8, "const "), (25, "const ")],
);
// the pointer itself can be `const` too (option WarnPointersAsValues)
let pointer = insert_diag(
"misc-const-correctness",
"variable 'p' of type 'int *' can be declared 'const'",
25,
&[(30, "const ")],
);
let build_dir = tmp.path().to_string_lossy();
let apply = |diagnostics: &[&String]| {
let yml = format!(
"---\nMainSourceFile: 'demo.cpp'\nDiagnostics:\n{}...\n",
diagnostics
.iter()
.map(|diag| format!("{diag} BuildDirectory: '{build_dir}'\n"))
.collect::<String>()
);
let fixes: ExportedFixes = serde_saphyr::from_str(&yml).unwrap();
let mut notes =
["misc-const-correctness", "readability-non-const-parameter"].map(|diagnostic| {
TidyNotification {
line: 2,
diagnostic: diagnostic.to_string(),
..dummy_note("demo.cpp", vec![])
}
});
let mut logs = vec![];
let mut paths = FixPaths::new(&target, tmp.path());
let (patched, _) = apply_fixes(&fixes, &mut paths, content, &mut notes, &mut logs);
(String::from_utf8(patched).unwrap(), logs, notes)
};

let (patched, logs, notes) = apply(&[&pointee, &parameter]);
// the skipped diagnostic is still fixed on its line, by the other fix
assert_eq!(notes[0].fixed_lines, vec![2]);
assert_eq!(notes[1].fixed_lines, vec![1, 2]);
assert_eq!(
patched,
"int get(const int *p);\nint get(const int *p) {\n return *p;\n}\n"
);
assert_eq!(logs.len(), 1, "{logs:#?}");

let (patched, logs, _) = apply(&[&pointee, &parameter, &pointer]);
assert_eq!(
patched,
"int get(const int *p);\nint get(const int *const p) {\n return *p;\n}\n"
);
assert_eq!(logs.len(), 1, "{logs:#?}");
assert_eq!(logs[0].0, log::Level::Info);
assert!(
logs[0]
.1
.contains("readability-non-const-parameter also makes"),
"{logs:#?}"
);

// without readability-non-const-parameter, misc-const-correctness is applied
// (clang-tidy inserts its `const` right before the `*`)
let (patched, logs, _) = apply(&[&pointee]);
assert_eq!(
patched,
"int get(int const*p);\nint get(int const*p) {\n return *p;\n}\n"
);
assert!(logs.is_empty(), "{logs:#?}");

// readability-non-const-parameter about another parameter does not matter
let other = insert_diag(
"readability-non-const-parameter",
"pointer parameter 'q' can be pointer to const",
30,
&[(8, "const ")],
);
let (patched, logs, _) = apply(&[&pointee, &other]);
assert_eq!(
patched,
"int get(const int const*p);\nint get(int const*p) {\n return *p;\n}\n"
);
assert!(logs.is_empty(), "{logs:#?}");
}

/// The fixes of misc-const-correctness and readability-non-const-parameter for the
/// same parameter make it `const` only once, even if the pointer is a macro.
#[test]
fn tidy_fixes_add_const_once() {
let tmp_workspace = tempfile::TempDir::with_prefix("cpp-linter-unit-tests_").unwrap();
let source = "int get(int *p);\nint get(int *p) {\n return *p;\n}\n\
#define PTR *\nint deref(int PTR q) { return *q; }\n";
fs::write(tmp_workspace.path().join("demo.cpp"), source).unwrap();
let mut clang_params = make_clang_params(tmp_workspace.path(), Some(get_tidy_exe()));
clang_params.tidy_checks =
"-*,misc-const-correctness,readability-non-const-parameter".to_string();
clang_params.gen_patch = true;
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 patched = fs::read_to_string(file.patched_path.as_ref().unwrap()).unwrap();
assert_eq!(
patched,
source
.replace("(int *p)", "(const int *p)")
.replace("(int PTR q)", "(const int PTR q)")
);
// the skipped diagnostic is still fixed (by the other fix), eg. for the PR review
let notes = &file.tidy_advice.as_ref().unwrap().notes;
assert!(
notes.iter().all(|note| !note.fixed_lines.is_empty()),
"{notes:#?}"
);
}
1 change: 1 addition & 0 deletions cspell.config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ words:
- peekable
- pipx
- pkgs
- pointee
- posargs
- positionals
- posix
Expand Down