Skip to content
Open
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
705 changes: 705 additions & 0 deletions cpp-linter/src/clang_tools/clang_tidy/cleanup.rs

Large diffs are not rendered by default.

144 changes: 104 additions & 40 deletions cpp-linter/src/clang_tools/clang_tidy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ use crate::{
markdown::{self, Status},
};

mod cleanup;
pub mod other_files;
use other_files::{OtherFileFix, Replacement, TidyFixes};
use other_files::{FixedLine, OtherFileFix, Replacement, TidyFixes};

/// Used to deserialize a json compilation database's translation unit.
///
Expand Down Expand Up @@ -77,28 +78,30 @@ pub struct TidyNotification {
/// The list of line numbers (in the analyzed file) that clang-tidy suggested fixes for.
pub fixed_lines: Vec<u32>,

/// The parts of the diagnostic's fix that were not applied to other files
/// (eg. a header that is not one of the analyzed files).
/// Why the diagnostic's fix was not applied: it also changes another file where it
/// cannot be applied (eg. a header that is not one of the analyzed files).
///
/// Users have to apply these parts themselves, so they are mentioned in the
/// thread comment and PR review.
/// Half a fix often breaks the code (eg. a function's definition that no longer
/// matches its declaration), so no part of such a fix is applied. Users have to
/// apply the fix themselves, so this is mentioned in the thread comment and PR review.
pub skipped_fixes: Vec<SkippedFix>,
}

/// A part of a clang-tidy fix that was not applied to another file.
/// A clang-tidy fix that was not applied, because it also changes another file
/// where it cannot be applied.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkippedFix {
/// The other file's path (relative to the repository root, if possible).
pub file: String,
/// Why the fix was not applied to the other file.
/// Why the fix cannot be applied to the other file.
pub reason: String,
}

impl SkippedFix {
/// Describe the skipped fix in a sentence (in markdown).
pub fn describe(&self) -> String {
format!(
"Part of this fix was not applied to `{}` because {}.",
"This fix was not applied because it also changes `{}`, and {}.",
self.file, self.reason
)
}
Expand Down Expand Up @@ -466,7 +469,7 @@ fn offset_to_line(content: &[u8], offset: usize) -> u32 {
/// after all files are analyzed; see [`other_files::apply_other_file_fixes()`].
///
/// Each diagnostic's `fixed_lines` (in the original `content`) are recorded in the
/// matching `notes`.
/// matching `notes`, and in [`TidyFixes::fixed`] (in case the fix is not applied after all).
fn apply_fixes<'a>(
fixes: &'a ExportedFixes,
paths: &mut FixPaths<'a>,
Expand All @@ -475,8 +478,8 @@ fn apply_fixes<'a>(
logs: &mut Vec<(log::Level, String)>,
) -> (Vec<u8>, TidyFixes) {
let mut tidy_fixes = TidyFixes::default();
for diag in &fixes.diagnostics {
if is_redundant_pointee_fix(diag, &fixes.diagnostics) {
for (id, diag) in fixes.diagnostics.iter().enumerate() {
if let Some(supplier) = pointee_fix_supplier(diag, &fixes.diagnostics) {
logs.push((
log::Level::Info,
format!(
Expand All @@ -492,14 +495,21 @@ fn apply_fixes<'a>(
.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);
if !note.fixed_lines.contains(&line) {
note.fixed_lines.push(line);
}
// only if the other fix is applied
tidy_fixes.fixed.push(FixedLine::new(supplier, note, line));
}
continue;
}
let first_other = tidy_fixes.others.len();
let fixed_lines = collect_diagnostic_fixes(diag, paths, content, &mut tidy_fixes, logs);
let Some(fixed_lines) =
collect_diagnostic_fixes(id, diag, paths, content, &mut tidy_fixes, logs)
else {
continue;
};
let other_fixes = &mut tidy_fixes.others[first_other..];
if fixed_lines.is_empty() && other_fixes.is_empty() {
continue;
Expand All @@ -511,6 +521,7 @@ fn apply_fixes<'a>(
if !note.fixed_lines.contains(&line) {
note.fixed_lines.push(line);
}
tidy_fixes.fixed.push(FixedLine::new(id, note, line));
}
for fix in other_fixes {
// the fixed lines in the other file are recorded once the fix is applied
Expand All @@ -520,13 +531,21 @@ fn apply_fixes<'a>(
});
}
}
let patched = patch_content(content, &tidy_fixes.own, paths.target, logs);
let own = tidy_fixes
.own
.iter()
.map(|(_, r)| r.clone())
.collect::<Vec<_>>();
let patched = patch_content(content, &own, paths.target, logs);
(patched, tidy_fixes)
}

/// Is `diag` a misc-const-correctness fix that a readability-non-const-parameter fix
/// (in `all`) also makes?
///
/// Returns the index (in `all`) of the readability-non-const-parameter diagnostic
/// that makes the same fix.
///
/// 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
Expand All @@ -537,39 +556,49 @@ fn apply_fixes<'a>(
/// 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 {
fn pointee_fix_supplier(diag: &ExportedDiagnostic, all: &[ExportedDiagnostic]) -> Option<usize> {
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"
})
})
if diag.diagnostic_name != "misc-const-correctness"
|| !msg.message.starts_with("pointee of variable ")
|| msg.replacements.is_empty()
{
return None;
}
all.iter().position(|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`].
///
/// The `id` identifies the diagnostic in the [`TidyFixes`].
///
/// Returns the lines (in the analyzed file's `content`) that this diagnostic fixes.
/// Returns [`None`] if a replacement is out of bounds of the analyzed file;
/// then no part of the diagnostic's fix is kept, because half a fix can break the code.
fn collect_diagnostic_fixes<'a>(
id: usize,
diag: &'a ExportedDiagnostic,
paths: &mut FixPaths<'a>,
content: &[u8],
tidy_fixes: &mut TidyFixes,
logs: &mut Vec<(log::Level, String)>,
) -> Vec<u32> {
) -> Option<Vec<u32>> {
let build_dir = diag.build_directory.as_str();
let mut fixed_lines = vec![];
let (mut own, mut others) = (vec![], vec![]);
for replacement in &diag.diagnostic_message.replacements {
if let Some(other) = paths.other_file(build_dir, &replacement.file_path) {
tidy_fixes.others.push(OtherFileFix {
others.push(OtherFileFix {
path: other,
diagnostic: diag.diagnostic_name.clone(),
id,
replacement: Replacement::from(replacement),
note: None,
});
Expand All @@ -582,19 +611,23 @@ fn collect_diagnostic_fixes<'a>(
if !fixed_lines.contains(&line) {
fixed_lines.push(line);
}
tidy_fixes.own.push(Replacement::from(replacement));
own.push((id, Replacement::from(replacement)));
} else {
logs.push((
log::Level::Warn,
format!(
"Skipping a fix for {} that is out of bounds of {}: {replacement:?}",
"Skipping the fix for {} because a part of it is out of bounds of {}: \
{replacement:?}",
diag.diagnostic_name,
paths.target.to_string_lossy(),
),
));
return None;
}
}
fixed_lines
tidy_fixes.own.extend(own);
tidy_fixes.others.extend(others);
Some(fixed_lines)
}

/// Find the notification (parsed from stdout) that matches a `diag`.
Expand Down Expand Up @@ -624,7 +657,18 @@ fn find_note<'a, 'n>(
})
}

/// Apply the given `replacements` onto a file's original `content`.
/// Apply the given `replacements` onto a file's original `content`,
/// the way `clang-tidy --fix` does.
///
/// The `replacements` are applied in their given order (clang-tidy's order),
/// except that they are sorted by offset (an insertion before a replacement at the same
/// offset). So, when several fixes insert text at the same offset, every text is
/// inserted, in clang-tidy's order (eg. a `}` for each of the nested `if` statements
/// that readability-braces-around-statements adds braces to). An identical replacement
/// of text is only applied once. A replacement that overlaps another is not applied.
///
/// Afterward, the separators that the applied fixes left behind are removed
/// (see [`cleanup::cleanup()`]).
///
/// The `file` is only used in log messages.
pub(super) fn patch_content(
Expand All @@ -633,15 +677,32 @@ pub(super) fn patch_content(
file: &Path,
logs: &mut Vec<(log::Level, String)>,
) -> Vec<u8> {
// clang-tidy already discards conflicting fixes before exporting them,
// but be defensive about duplicates and overlaps anyway.
// Duplicates are expected when several translation units fix the same header.
let mut replacements = replacements.iter().collect::<Vec<_>>();
replacements.sort();
replacements.dedup();
// a stable sort keeps clang-tidy's order of fixes at the same offset
replacements.sort_by_key(|r| (r.offset, r.length > 0));
let mut patched = Vec::with_capacity(content.len());
// the ranges of the applied fixes' text in `patched`
let mut edits = vec![];
let mut cursor = 0;
let mut last: Option<&Replacement> = None;
for replacement in replacements {
if replacement.length > 0 && last == Some(replacement) {
continue;
}
if replacement
.offset
.checked_add(replacement.length)
.is_none_or(|end| end > content.len())
{
logs.push((
log::Level::Warn,
format!(
"Skipping a fix that is out of bounds of {}: {replacement:?}",
file.to_string_lossy(),
),
));
continue;
}
if replacement.offset < cursor {
logs.push((
log::Level::Warn,
Expand All @@ -653,11 +714,14 @@ pub(super) fn patch_content(
continue;
}
patched.extend_from_slice(&content[cursor..replacement.offset]);
let start = patched.len();
patched.extend_from_slice(replacement.text.as_bytes());
edits.push(start..patched.len());
cursor = replacement.offset + replacement.length;
last = Some(replacement);
}
patched.extend_from_slice(&content[cursor..]);
patched
cleanup::cleanup(patched, &edits)
}

/// Write the `patched` content of a `file` to the cache.
Expand Down
Loading