diff --git a/cpp-linter/src/clang_tools/clang_tidy/cleanup.rs b/cpp-linter/src/clang_tools/clang_tidy/cleanup.rs new file mode 100644 index 00000000..577832a9 --- /dev/null +++ b/cpp-linter/src/clang_tools/clang_tidy/cleanup.rs @@ -0,0 +1,705 @@ +//! Cleaning up around applied clang-tidy fixes, like `clang-tidy --fix` does. +//! +//! Some clang-tidy fixes only delete an item from a list and leave its separator +//! behind. For example, `modernize-use-default-member-init` deletes the initializers +//! of `T() : a(0), b(1) {}` and leaves `T() : , {}`. `clang-tidy --fix` (and +//! `clang-apply-replacements`) clean up around the applied fixes with +//! `clang::format::cleanupAroundReplacements()`, which removes such separators. +//! This module does the same for the separators that clang-format's cleaner removes: +//! +//! | left | right | removed | +//! |------|-------|---------| +//! | `,` | `,` | the right `,` | +//! | `:` of a constructor's initializer list | `,` | the `,` | +//! | `(` | `,` | the `,` | +//! | `,` | `)` | the `,` | +//! | `,` in a constructor's initializer list | `{` | the `,` | +//! | `:` of a constructor's initializer list | `{` | the `:` | +//! | `:` of a constructor's initializer list | `=` | the `:` | +//! +//! Unlike clang-format, a separator is only removed next to an applied fix +//! (not anywhere on a line that a fix touched), and code in preprocessor directives +//! is left alone. + +use std::ops::Range; + +/// The kinds of tokens that matter to [`cleanup()`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Comma, + Colon, + LParen, + RParen, + LBrace, + RBrace, + Equal, + Semi, + /// An identifier or keyword. + Word, + /// Anything else (numbers, literals, other punctuation, preprocessor directives). + Other, +} + +#[derive(Debug, Clone)] +struct Token { + kind: Kind, + span: Range, +} + +/// Remove the separators that the applied fixes left behind in `patched`. +/// +/// `edits` are the byte ranges (in `patched`) of the applied fixes' replacement text; +/// an empty range is where a fix deleted text. +pub(super) fn cleanup(patched: Vec, edits: &[Range]) -> Vec { + if edits.is_empty() { + return patched; + } + let tokens = tokenize(&patched); + let mut deleted = vec![false; tokens.len()]; + let (all_tokens, content) = (&tokens, patched.as_slice()); + let is = |kind: Kind| move |i: usize| all_tokens[i].kind == kind; + let colon = |i: usize| is_ctor_colon(all_tokens, content, i); + let ctor_comma_at = |i: usize| { + all_tokens[i].kind == Kind::Comma && is_in_ctor_initializers(all_tokens, content, i) + }; + + // the same rules, in the same order, as clang-format's `Cleaner` + cleanup_pair( + &tokens, + &mut deleted, + edits, + is(Kind::Comma), + is(Kind::Comma), + false, + ); + cleanup_pair(&tokens, &mut deleted, edits, colon, is(Kind::Comma), false); + cleanup_pair( + &tokens, + &mut deleted, + edits, + is(Kind::LParen), + is(Kind::Comma), + false, + ); + cleanup_pair( + &tokens, + &mut deleted, + edits, + is(Kind::Comma), + is(Kind::RParen), + true, + ); + cleanup_pair( + &tokens, + &mut deleted, + edits, + ctor_comma_at, + is(Kind::LBrace), + true, + ); + cleanup_pair(&tokens, &mut deleted, edits, colon, is(Kind::LBrace), true); + cleanup_pair(&tokens, &mut deleted, edits, colon, is(Kind::Equal), true); + + if !deleted.contains(&true) { + return patched; + } + // like clang-format, delete adjacent tokens (and the space between them) at once + let mut out = Vec::with_capacity(patched.len()); + let mut cursor = 0; + let mut index = 0; + while index < tokens.len() { + if !deleted[index] { + index += 1; + continue; + } + let start = tokens[index].span.start; + while deleted.get(index + 1) == Some(&true) { + index += 1; + } + out.extend_from_slice(&patched[cursor..start]); + cursor = tokens[index].span.end; + index += 1; + } + out.extend_from_slice(&patched[cursor..]); + out +} + +/// Delete one token of each pair of adjacent (not deleted) tokens that match +/// `left` and `right`, if an applied fix touches the space between them. +/// +/// `left` is checked last, so it can be a slower check. +/// +/// If `delete_left` is false, the right token is deleted and the left token is +/// paired with the next token. +fn cleanup_pair( + tokens: &[Token], + deleted: &mut [bool], + edits: &[Range], + left: impl Fn(usize) -> bool, + right: impl Fn(usize) -> bool, + delete_left: bool, +) { + let next = |deleted: &[bool], from: usize| (from + 1..tokens.len()).find(|i| !deleted[*i]); + let Some(mut l) = (0..tokens.len()).find(|i| !deleted[*i]) else { + return; + }; + while let Some(r) = next(deleted, l) { + if right(r) && touches_fix(edits, tokens[l].span.end, tokens[r].span.start) && left(l) { + if delete_left { + deleted[l] = true; + } else { + deleted[r] = true; + continue; + } + } + l = r; + } +} + +/// Does an applied fix touch the space between `start` and `end`? +/// +/// The `edits` do not overlap and are sorted by their position. +fn touches_fix(edits: &[Range], start: usize, end: usize) -> bool { + let first = edits.partition_point(|e| e.end < start); + edits.get(first).is_some_and(|e| e.start <= end) +} + +/// Find the `(` that matches the `)` at `index`. +/// +/// Balanced braces in between are skipped (eg. `int{0}` in `T(int x = int{0})`). +fn matching_open_paren(tokens: &[Token], index: usize) -> Option { + let mut depth = 0usize; + let mut braces = 0usize; + for i in (0..=index).rev() { + match tokens[i].kind { + Kind::RBrace => braces += 1, + Kind::LBrace => braces = braces.checked_sub(1)?, + _ if braces > 0 => {} + Kind::RParen => depth += 1, + Kind::LParen => { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + Kind::Semi => return None, + _ => {} + } + } + None +} + +/// Is the token at `index` the `:` that starts a constructor's initializer list? +/// +/// That is, a `:` after the `)` that closes a function's parameters, +/// or after a `noexcept` (or `noexcept(...)`, `throw(...)`) or a `requires` clause +/// that follows them. +fn is_ctor_colon(tokens: &[Token], content: &[u8], index: usize) -> bool { + if tokens[index].kind != Kind::Colon || index == 0 { + return false; + } + let is_word = |i: usize, word: &[u8]| { + tokens[i].kind == Kind::Word && &content[tokens[i].span.clone()] == word + }; + let mut prev = index - 1; + // a function-try-block, eg. `T() try : a() {} catch (...) {}` + if is_word(prev, b"try") { + let Some(p) = prev.checked_sub(1) else { + return false; + }; + prev = p; + } + // a `requires` clause, eg. `T() requires (N > 0) : a() {}` or `T() requires C : a() {}` + if tokens[prev].kind == Kind::RParen + && let Some(open) = matching_open_paren(tokens, prev) + && open >= 2 + && is_word(open - 1, b"requires") + { + prev = open - 2; + } else if tokens[prev].kind != Kind::RParen + && let Some(clause) = (0..prev).rev().find(|i| { + matches!( + tokens[*i].kind, + Kind::RParen | Kind::Semi | Kind::LBrace | Kind::RBrace | Kind::Colon + ) || is_word(*i, b"requires") + }) + && clause >= 1 + && is_word(clause, b"requires") + { + prev = clause - 1; + } + if is_word(prev, b"noexcept") { + let Some(p) = prev.checked_sub(1) else { + return false; + }; + prev = p; + } else if tokens[prev].kind == Kind::RParen + && let Some(open) = matching_open_paren(tokens, prev) + && open >= 2 + && (is_word(open - 1, b"noexcept") || is_word(open - 1, b"throw")) + { + prev = open - 2; + } + if tokens[prev].kind != Kind::RParen { + return false; + } + // look at what precedes the matching `(` + matching_open_paren(tokens, prev) + .and_then(|open| open.checked_sub(1)) + .is_some_and(|name| { + tokens[name].kind == Kind::Word + && !matches!( + &content[tokens[name].span.clone()], + b"case" + | b"if" + | b"while" + | b"for" + | b"switch" + | b"return" + | b"sizeof" + | b"alignof" + | b"decltype" + | b"noexcept" + ) + && name + .checked_sub(1) + .is_none_or(|before| may_precede_ctor_name(tokens, content, before)) + && !is_in_case_label(tokens, content, name) + && !is_in_conditional(tokens, content, name) + }) +} + +/// Is the token at `index` in a conditional expression's branch +/// (eg. `g` in `c ? p->g() : 0` or `string` in `c ? std::string() : s`)? +/// +/// Looks back to the start of the statement for a `?`. +fn is_in_conditional(tokens: &[Token], content: &[u8], index: usize) -> bool { + tokens[..index] + .iter() + .rev() + .take_while(|t| !matches!(t.kind, Kind::Semi | Kind::LBrace | Kind::RBrace)) + .any(|t| t.kind == Kind::Other && &content[t.span.clone()] == b"?") +} + +/// Is the token at `index` in the value of a `case` label (eg. `F` in `case F(1):`)? +/// +/// That `:` ends the label, so it must stay even if a fix deletes the statement after it. +fn is_in_case_label(tokens: &[Token], content: &[u8], index: usize) -> bool { + // the `:` of conditional expressions (`c ? a : b`) between `case` and `index` + let mut open_colons = 0usize; + for token in tokens[..index].iter().rev() { + let text = &content[token.span.clone()]; + match token.kind { + Kind::Semi | Kind::LBrace | Kind::RBrace => return false, + Kind::Colon => open_colons += 1, + Kind::Other if text == b"?" => open_colons = open_colons.saturating_sub(1), + Kind::Other if text.starts_with(b"#") => return false, + Kind::Word if text == b"case" => return open_colons == 0, + _ => {} + } + } + false +} + +/// Can the token at `index` come right before a constructor's name? +/// +/// This tells `S(int x) : a(x)` apart from the `:` in `c ? f(1) : g(2)`. +fn may_precede_ctor_name(tokens: &[Token], content: &[u8], index: usize) -> bool { + let token = &tokens[index]; + match token.kind { + Kind::Semi | Kind::LBrace | Kind::RBrace | Kind::Colon | Kind::Word => true, + Kind::Other => { + let text = &content[token.span.clone()]; + matches!(text, b"::" | b">" | b">>" | b"]") || text.starts_with(b"#") + } + // a specifier with arguments, eg. `explicit(true) S()` or `__attribute__((cold)) S()` + // (not a cast, as in `c ? (int) f(1) : g(2)`) + Kind::RParen => matching_open_paren(tokens, index) + .and_then(|open| open.checked_sub(1)) + .is_some_and(|word| { + tokens[word].kind == Kind::Word + && !matches!( + &content[tokens[word].span.clone()], + b"if" + | b"while" + | b"for" + | b"switch" + | b"return" + | b"case" + | b"new" + | b"sizeof" + | b"alignof" + | b"decltype" + ) + }), + _ => false, + } +} + +/// Is the `,` at `index` a separator in a constructor's initializer list? +fn is_in_ctor_initializers(tokens: &[Token], content: &[u8], index: usize) -> bool { + let mut depth = 0usize; + for i in (0..index).rev() { + match tokens[i].kind { + Kind::RParen | Kind::RBrace => depth += 1, + Kind::LParen | Kind::LBrace => { + if depth == 0 { + return false; + } + depth -= 1; + } + Kind::Semi if depth == 0 => return false, + Kind::Colon if depth == 0 => return is_ctor_colon(tokens, content, i), + _ => {} + } + } + false +} + +/// Split C/C++ `content` into tokens, skipping whitespace and comments. +fn tokenize(content: &[u8]) -> Vec { + let mut tokens = vec![]; + let len = content.len(); + let mut i = 0; + let mut line_start = true; + while i < len { + let c = content[i]; + let start = i; + if c == b'\n' { + line_start = true; + i += 1; + continue; + } + if c.is_ascii_whitespace() { + i += 1; + continue; + } + if c == b'/' && content.get(i + 1) == Some(&b'/') { + while i < len && content[i] != b'\n' { + i += 1; + } + continue; + } + if c == b'/' && content.get(i + 1) == Some(&b'*') { + i += 2; + while i < len && !(content[i] == b'*' && content.get(i + 1) == Some(&b'/')) { + i += 1; + } + i = (i + 2).min(len); + continue; + } + let at_line_start = line_start; + line_start = false; + let kind = if c == b'#' && at_line_start { + // a preprocessor directive, including its continuation lines + while i < len && content[i] != b'\n' { + if content[i] == b'\\' && content.get(i + 1) == Some(&b'\n') { + i += 1; + } + i += 1; + } + Kind::Other + } else if c.is_ascii_alphabetic() || c == b'_' { + while i < len && (content[i].is_ascii_alphanumeric() || content[i] == b'_') { + i += 1; + } + if content[i - 1] == b'R' && content.get(i) == Some(&b'"') { + i = skip_raw_string(content, i); + Kind::Other + } else if matches!(content.get(i), Some(b'"' | b'\'')) + && matches!(&content[start..i], b"L" | b"u" | b"U" | b"u8") + { + i = skip_quoted(content, i); + Kind::Other + } else { + Kind::Word + } + } else if c.is_ascii_digit() + || (c == b'.' && content.get(i + 1).is_some_and(u8::is_ascii_digit)) + { + // numbers, including digit separators (`1'000`) and exponents (`1e+3`) + i += 1; + while i < len { + let n = content[i]; + let is_sign = + matches!(n, b'+' | b'-') && matches!(content[i - 1], b'e' | b'E' | b'p' | b'P'); + if !(n.is_ascii_alphanumeric() || matches!(n, b'.' | b'_' | b'\'') || is_sign) { + break; + } + i += 1; + } + Kind::Other + } else if c == b'"' || c == b'\'' { + i = skip_quoted(content, i); + Kind::Other + } else { + i += 1; + match c { + b',' => Kind::Comma, + b':' if content.get(i) == Some(&b':') => { + i += 1; + Kind::Other + } + b':' => Kind::Colon, + b'(' => Kind::LParen, + b')' => Kind::RParen, + b'{' => Kind::LBrace, + b'}' => Kind::RBrace, + b';' => Kind::Semi, + b'=' if content.get(i) == Some(&b'=') => { + i += 1; + Kind::Other + } + b'=' => Kind::Equal, + b'!' | b'<' | b'>' | b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' + if content.get(i) == Some(&b'=') => + { + i += 1; + Kind::Other + } + _ => Kind::Other, + } + }; + tokens.push(Token { + kind, + span: start..i, + }); + } + tokens +} + +/// Skip a string or character literal that starts (with its quote) at `start`. +/// +/// Returns the offset after the closing quote. +fn skip_quoted(content: &[u8], start: usize) -> usize { + let quote = content[start]; + let mut i = start + 1; + while i < content.len() { + match content[i] { + b'\\' => i += 2, + b'\n' => return i, + c if c == quote => return i + 1, + _ => i += 1, + } + } + content.len() +} + +/// Skip a raw string literal whose `"` is at `start` (eg. `R"x(...)x"`). +/// +/// Returns the offset after the closing `"`. +fn skip_raw_string(content: &[u8], start: usize) -> usize { + let Some(open) = content[start..].iter().position(|c| *c == b'(') else { + return content.len(); + }; + let delimiter = &content[start + 1..start + open]; + let mut closing = vec![b')']; + closing.extend_from_slice(delimiter); + closing.push(b'"'); + content[start + open..] + .windows(closing.len()) + .position(|w| w == closing.as_slice()) + .map_or(content.len(), |p| start + open + p + closing.len()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod test { + use super::cleanup; + + /// Delete each `[...]` from `marked`, then clean up around the deletions. + fn clean(marked: &str) -> String { + let mut patched = vec![]; + let mut edits = vec![]; + let mut skip = false; + for c in marked.bytes() { + match c { + b'[' => { + skip = true; + edits.push(patched.len()..patched.len()); + } + b']' => skip = false, + _ if !skip => patched.push(c), + _ => {} + } + } + String::from_utf8(cleanup(patched, &edits)).unwrap() + } + + #[test] + fn ctor_initializers() { + assert_eq!(clean("T() : [a(0)], [b(1)], [c(2)] {}"), "T() {}"); + assert_eq!(clean("T() : [a(0)], b(1) {}"), "T() : b(1) {}"); + assert_eq!(clean("T() : a(0), [b(1)] {}"), "T() : a(0) {}"); + assert_eq!(clean("T() : a{0}, [b{1}], c{2} {}"), "T() : a{0}, c{2} {}"); + assert_eq!(clean("T() noexcept : [a(0)] {}"), "T() noexcept {}"); + assert_eq!( + clean("T() noexcept(true) : [s()] {}"), + "T() noexcept(true) {}" + ); + assert_eq!( + clean("T() noexcept(sizeof(int) > 2) : a(0), [s()] {}"), + "T() noexcept(sizeof(int) > 2) : a(0) {}" + ); + assert_eq!( + clean("T() try : [s()] {} catch (...) {}"), + "T() try {} catch (...) {}" + ); + assert_eq!( + clean("T(int x = int{0}) : [s()] {}"), + "T(int x = int{0}) {}" + ); + assert_eq!( + clean("T() noexcept(noexcept(int{})) : [s()] {}"), + "T() noexcept(noexcept(int{})) {}" + ); + // a `try` block is not a constructor + assert_eq!(clean("try { f(); } [x];"), "try { f(); } ;"); + // specifiers before the name, and after the parameters + assert_eq!(clean("T() throw() : [a(0)] {}"), "T() throw() {}"); + assert_eq!( + clean("explicit(true) T(int) : [a(0)] {}"), + "explicit(true) T(int) {}" + ); + assert_eq!( + clean("__attribute__((cold)) T() : [a(0)] {}"), + "__attribute__((cold)) T() {}" + ); + assert_eq!( + clean("T(Mutex* mu) LOCK_FUNCTION(mu) : [a(0)] {}"), + "T(Mutex* mu) LOCK_FUNCTION(mu) {}" + ); + assert_eq!( + clean("T() requires (N > 0) : [a(0)] {}"), + "T() requires (N > 0) {}" + ); + assert_eq!( + clean("T() requires C : a(0), [b(0)] {}"), + "T() requires C : a(0) {}" + ); + assert_eq!( + clean("template requires C T(U) : [a(0)] {}"), + "template requires C T(U) {}" + ); + assert_eq!( + clean("T(const T&) : [x(1)]= default;"), + "T(const T&) = default;" + ); + assert_eq!( + clean("T(int v)\n : [a(v)],\n b(v) {}\n"), + "T(int v)\n : \n b(v) {}\n" + ); + } + + /// Separators in literals are not tokens, and other tokens are not separators. + #[test] + fn literals_and_operators() { + let cases = [ + ("f(R\"x(a, )x\", [b]);", "f(R\"x(a, )x\" );"), + ( + "f(u8\",\", L',', U\",\", [b]);", + "f(u8\",\", L',', U\",\" );", + ), + ("f('\\'', ',', [b]);", "f('\\'', ',' );"), + ( + "f(1e+3, 1'000, .5, 0x1p-2, [b]);", + "f(1e+3, 1'000, .5, 0x1p-2 );", + ), + ( + "x == y, x += 1, x != 2, (x, [b]);", + "x == y, x += 1, x != 2, (x );", + ), + ( + "#define M(a, b) \\\n f(a, )\nf(x, [b]);", + "#define M(a, b) \\\n f(a, )\nf(x );", + ), + ("a = x ? f(1) : [g(2)], {}", "a = x ? f(1) : , {}"), + (": [x], {}", ": , {}"), + ("S() : [a()] {}", "S() {}"), + ("S::S() : [a()] {}", "S::S() {}"), + ("#if 1\nS() : [a()] {}", "#if 1\nS() {}"), + ("\"open, [b]", "\"open, "), + ("/* open, [b]", "/* open, "), + ("\"open\nf(x, [b]);", "\"open\nf(x );"), + ("R\"x, [b]", "R\"x, "), + // these `:` are not a constructor's initializer list + ("x) : [a], {}", "x) : , {}"), + ("; x) : [a], {}", "; x) : , {}"), + ("noexcept : [a], {}", "noexcept : , {}"), + ("x : [a], {}", "x : , {}"), + ("x, f(1) : [a], {}", "x, f(1) : , {}"), + ("c ? (int) f(1) : [a], {}", "c ? (int) f(1) : , {}"), + ("if (c) f(1) : [a], {}", "if (c) f(1) : , {}"), + ("c ? new (p) T(1) : [a], {}", "c ? new (p) T(1) : , {}"), + ("x = c ? p->f() : [a], {}", "x = c ? p->f() : , {}"), + ( + "x = c ? std::string() : [a], {}", + "x = c ? std::string() : , {}", + ), + ("f(c ? p->g() : 0, [a]{1});", "f(c ? p->g() : 0, {1});"), + ("x requires : [a], {}", "x requires : , {}"), + ("case F(1):[ x = 1;] {}", "case F(1): {}"), + ("{ case ns::F(1):[ x = 1;] {} }", "{ case ns::F(1): {} }"), + ("case 0: case F(1):[ x = 1;] {}", "case 0: case F(1): {}"), + ( + "case A ? F(0) : F(1):[ x = 1;] {}", + "case A ? F(0) : F(1): {}", + ), + ( + "case 0: x = c ? 1 : 2; T() : [a()] {}", + "case 0: x = c ? 1 : 2; T() {}", + ), + // these `,` are not in a constructor's initializer list + ("x; a, [b] {}", "x; a, {}"), + ("a, [b] {}", "a, {}"), + ("R\"x(open, [b]", "R\"x(open, "), + ]; + for (marked, expected) in cases { + assert_eq!(clean(marked), expected, "{marked}"); + } + } + + /// A large initializer is not scanned again for every comma. + #[test] + fn large_initializer() { + let values = vec!["0"; 200_000].join(", "); + let source = format!("int a = {{{values}, [1]}};\nT() : [b(1)], c{{2}} {{}}\n"); + let expected = format!("int a = {{{values}, }};\nT() : c{{2}} {{}}\n"); + assert_eq!(clean(&source), expected); + } + + #[test] + fn argument_lists() { + assert_eq!( + clean("static_assert(x > 1, [\"msg\"]);"), + "static_assert(x > 1 );" + ); + assert_eq!(clean("f([a], b);"), "f( b);"); + assert_eq!(clean("f(a, [b], c);"), "f(a, c);"); + } + + #[test] + fn left_alone() { + // nothing was deleted next to these separators + assert_eq!(clean("f(a, {1}); [x];"), "f(a, {1}); ;"); + // a braced argument is not a constructor's initializer + assert_eq!(clean("f(a, [b]{1});"), "f(a, {1});"); + // `case (1): {` is not a constructor's initializer list + assert_eq!( + clean("switch (x) { case (1):[ y = 1;] {} }"), + "switch (x) { case (1): {} }" + ); + // separators in comments, strings and macros + assert_eq!(clean("f(a /* , */, [b]);"), "f(a /* , */ );"); + assert_eq!(clean("s = \",\"[ x];"), "s = \",\";"); + assert_eq!( + clean("#define M(a, b) f(a, , b)\nint [x];"), + "#define M(a, b) f(a, , b)\nint ;" + ); + // `::` is not a `:` + assert_eq!( + clean("T() : ::ns::Base(), [b(1)] {}"), + "T() : ::ns::Base() {}" + ); + } +} diff --git a/cpp-linter/src/clang_tools/clang_tidy/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/mod.rs index da47f0b5..c88e6a1b 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/mod.rs @@ -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. /// @@ -77,20 +78,22 @@ pub struct TidyNotification { /// The list of line numbers (in the analyzed file) that clang-tidy suggested fixes for. pub fixed_lines: Vec, - /// 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, } -/// 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, } @@ -98,7 +101,7 @@ 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 ) } @@ -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>, @@ -475,8 +478,8 @@ fn apply_fixes<'a>( logs: &mut Vec<(log::Level, String)>, ) -> (Vec, 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!( @@ -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; @@ -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 @@ -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::>(); + 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 @@ -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 { 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 { +) -> Option> { 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, }); @@ -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`. @@ -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( @@ -633,15 +677,32 @@ pub(super) fn patch_content( file: &Path, logs: &mut Vec<(log::Level, String)>, ) -> Vec { - // 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::>(); - 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, @@ -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. diff --git a/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs b/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs index a784b07f..3ba7f3fa 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/other_files/mod.rs @@ -22,7 +22,7 @@ use super::{ use crate::{cli::ClangParams, common_fs::FileObj, error::ClangCaptureError}; /// A text replacement in a file's original content. -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Replacement { /// The byte offset where the replaced text starts. pub offset: usize, @@ -49,6 +49,9 @@ pub struct OtherFileFix { pub path: PathBuf, /// The name of the diagnostic that suggested the fix. pub diagnostic: String, + /// Identifies the diagnostic (in the analyzed file's [`TidyFixes`]) that suggested + /// the fix. All parts of a diagnostic's fix are applied together, or not at all. + pub id: usize, /// The replacement in the other file's original content. pub replacement: Replacement, /// The notification (parsed from clang-tidy's stdout) about the diagnostic, @@ -63,10 +66,44 @@ pub struct OtherFileFix { /// The fixes that clang-tidy suggested while analyzing a file. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct TidyFixes { - /// The replacements in the analyzed file. - pub own: Vec, + /// The replacements in the analyzed file (in clang-tidy's order), + /// each with the [`OtherFileFix::id`] of the diagnostic that suggested it. + pub own: Vec<(usize, Replacement)>, /// The replacements in other files. pub others: Vec, + /// The lines (in the analyzed file) recorded as fixed in the notes about diagnostics. + /// + /// If a diagnostic's fix is not applied after all, its lines are no longer fixed. + pub fixed: Vec, +} + +/// A line (in the analyzed file) that a diagnostic's fix changes, as recorded in the +/// note about a diagnostic (see [`TidyNotification::fixed_lines`]). +/// +/// The note can be about another diagnostic, whose fix is made by this diagnostic's fix +/// (see the misc-const-correctness fixes that are skipped in [`super::apply_fixes()`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FixedLine { + /// The [`OtherFileFix::id`] of the diagnostic whose fix changes the line. + pub id: usize, + /// The note's file name, line and diagnostic. + note: (String, u32, String), + /// The fixed line. + pub line: u32, +} + +impl FixedLine { + pub(super) fn new(id: usize, note: &TidyNotification, line: u32) -> Self { + Self { + id, + note: (note.filename.clone(), note.line, note.diagnostic.clone()), + line, + } + } + + fn is_about(&self, note: &TidyNotification) -> bool { + self.note.0 == note.filename && self.note.1 == note.line && self.note.2 == note.diagnostic + } } /// Why a [`OtherFileFix`] was not applied. @@ -90,16 +127,16 @@ enum Rejection { impl Rejection { fn reason(&self) -> String { match self { - Self::NotAnalyzed => "it is not one of the analyzed files".to_string(), - Self::IgnoredByTidy => "it is ignored by `--ignore-tidy`".to_string(), + Self::NotAnalyzed => "that file is not one of the analyzed files".to_string(), + Self::IgnoredByTidy => "that file is ignored by `--ignore-tidy`".to_string(), Self::OutOfBounds { start, end, size } => format!( - "the fix seems malformed and is out of the file's bounds \ + "the change there seems malformed and is out of the file's bounds \ (bytes {start} to {end} of a {size} byte file)" ), Self::OutsideChangedLines => { - "the fix clashes with the `--lines-changed-only` constraint".to_string() + "the change there clashes with the `--lines-changed-only` constraint".to_string() } - Self::Overlaps => "the fix overlaps another fix for the same file".to_string(), + Self::Overlaps => "the change there overlaps another fix for that file".to_string(), } } } @@ -220,10 +257,20 @@ impl<'a> AnalyzedFiles<'a> { /// cached copies of those files. /// /// `tidy_fixes` holds the fixes found while analyzing the file at the paired index of -/// `files`. A fix for another file is only applied if that file is also analyzed, -/// is not ignored by `--ignore-tidy`, the fix is within the file's changed lines -/// (according to `--lines-changed-only`), and it does not overlap the file's own fixes -/// or a different fix accepted before. +/// `files` (in the order of `files`). A fix for another file is only applied if that +/// file is also analyzed, is not ignored by `--ignore-tidy`, the fix is within the +/// file's changed lines (according to `--lines-changed-only`), and it does not overlap +/// the file's own fixes or a different fix accepted before. +/// +/// A diagnostic's fix is applied as a whole, or not at all: if any part of it cannot be +/// applied to another file, none of its parts are applied (not even to the analyzed +/// file). Half a fix often breaks the code, eg. a function's definition that differs +/// from its declaration in a header. The cached copy of the analyzed file is patched +/// again without that fix, and the reason is recorded in the diagnostic's note +/// (see [`TidyNotification::skipped_fixes`]). +/// +/// A fix that is found while analyzing several files (eg. for a header that they +/// include) is applied once. /// /// Messages about each fix are added to the `logs` of the analyzed file whose /// diagnostic suggested it (at the paired index of `files`). @@ -243,60 +290,143 @@ pub fn apply_other_file_fixes( let working_dir = std::path::absolute(&clang_params.repo_root) .map_err(ClangCaptureError::UnknownWorkingDirectory)?; let mut analyzed = AnalyzedFiles::new(files, &working_dir)?; - // the replacements to apply, keyed by the index of the file they apply to + // the diagnostics whose fixes are not applied (by their ids), keyed by the index of + // the analyzed file that suggested them + let mut dropped: BTreeMap> = BTreeMap::new(); + // Most of them are known before overlapping fixes are checked, so their parts in + // an analyzed file do not keep other fixes from that file. + for (source_index, fixes) in tidy_fixes { + for parts in fixes.others.chunk_by(|a, b| a.id == b.id) { + for fix in parts { + let allowed = match analyzed.find(&fix.path) { + None => false, + Some(index) => analyzed.check(index, fix, clang_params)?.is_ok(), + }; + if !allowed { + dropped.entry(*source_index).or_default().push(fix.id); + break; + } + } + } + } + let known_dropped = dropped.clone(); + // the accepted fixes, keyed by the index of the file they apply to let mut pending: BTreeMap = BTreeMap::new(); for (source_index, fixes) in tidy_fixes { let source_name = file_name(&files[*source_index])?; - for fix in &fixes.others { - // show the path relative to the repository root, if possible - let other = fix - .path + // show a path relative to the repository root, if possible + let relative = |fix: &OtherFileFix| { + fix.path .strip_prefix(&working_dir) .unwrap_or(&fix.path) - .to_string_lossy(); - let verdict = match analyzed.find(&fix.path) { - None => Err(Rejection::NotAnalyzed), - Some(index) => analyzed.check(index, fix, clang_params)?.and_then(|line| { - pending - .entry(index) - .or_insert_with(|| Pending::new(own_fixes(tidy_fixes, index))) - .add(fix, line) - }), - }; - let message = match verdict { - Ok(()) => format!( - "Applying the fix for {} (reported in {source_name}) to {other}", - fix.diagnostic, - ), - Err(rejection) => { - let skipped = SkippedFix { - file: other.replace('\\', "/"), - reason: rejection.reason(), - }; - let message = format!( - "Not applying the fix for {} (reported in {source_name}) to {} because {}", + .to_string_lossy() + .replace('\\', "/") + }; + // the parts of one diagnostic's fix are next to each other + for parts in fixes.others.chunk_by(|a, b| a.id == b.id) { + let mut accepted = vec![]; + let mut rejected = None; + for fix in parts { + let verdict = match analyzed.find(&fix.path) { + None => Err(Rejection::NotAnalyzed), + Some(index) => analyzed.check(index, fix, clang_params)?.and_then(|line| { + let own = kept_own_fixes(tidy_fixes, &known_dropped, index); + pending + .get(&index) + .map_or_else( + || Pending::default().check(&own, fix), + |p| p.check(&own, fix), + ) + .map(|()| (index, line)) + }), + }; + match verdict { + Ok((index, line)) => accepted.push((index, line, fix)), + Err(rejection) => { + rejected = Some((fix, rejection)); + break; + } + } + } + if let Some((fix, rejection)) = rejected { + let skipped = SkippedFix { + file: relative(fix), + reason: rejection.reason(), + }; + logs[*source_index].push(( + log::Level::Info, + format!( + "Not applying the fix for {} (reported in {source_name}) because it \ + also changes {}, and {}", fix.diagnostic, skipped.file, skipped.reason, - ); - record_skipped_fix(&files[*source_index], fix, skipped)?; - message + ), + )); + record_skipped_fix(&files[*source_index], fix, skipped)?; + let ids = dropped.entry(*source_index).or_default(); + if !ids.contains(&fix.id) { + ids.push(fix.id); } - }; - logs[*source_index].push((log::Level::Info, message)); + continue; + } + for (index, line, fix) in accepted { + logs[*source_index].push(( + log::Level::Info, + format!( + "Applying the fix for {} (reported in {source_name}) to {}", + fix.diagnostic, + relative(fix), + ), + )); + pending + .entry(index) + .or_default() + .add(*source_index, fix, line); + } } } - for ( - index, - Pending { - replacements, - notes, - }, - ) in pending - { + // a line is no longer fixed if only the fixes that are not applied changed it + // (before the notes of accepted fixes from other files are merged) + for (index, fixes) in tidy_fixes { + let Some(ids) = dropped.get(index) else { + continue; + }; + let mut file = files[*index] + .lock() + .map_err(|_| ClangCaptureError::MutexPoisoned)?; + let Some(advice) = file.tidy_advice.as_mut() else { + continue; + }; + for note in &mut advice.notes { + let credits = fixes + .fixed + .iter() + .filter(|f| f.is_about(note)) + .collect::>(); + note.fixed_lines.retain(|line| { + let mut credits = credits.iter().filter(|f| f.line == *line).peekable(); + credits.peek().is_none() || credits.any(|f| !ids.contains(&f.id)) + }); + } + } + // patch the files that get fixes from other files, and the files that lose a fix + let mut indices = pending.keys().copied().collect::>(); + indices.extend(dropped.iter().filter_map(|(index, ids)| { + own_fixes(tidy_fixes, *index) + .iter() + .any(|(id, _)| ids.contains(id)) + .then_some(*index) + })); + indices.sort_unstable(); + indices.dedup(); + for index in indices { + let own = kept_own_fixes(tidy_fixes, &dropped, index); + let Pending { others, notes } = pending.remove(&index).unwrap_or_default(); + let replacements = merge_fixes(&own, &others); + let content = analyzed.content(index, clang_params)?; let mut file = files[index] .lock() .map_err(|_| ClangCaptureError::MutexPoisoned)?; if clang_params.gen_patch { - let content = analyzed.content(index, clang_params)?; let patched = patch_content(content, &replacements, &file.name, &mut logs[index]); file.patched_path = Some(write_cache(clang_params, &file.name, &patched)?); } @@ -309,9 +439,24 @@ pub fn apply_other_file_fixes( Ok(()) } +/// Get the fixes that clang-tidy suggested for the analyzed file at `index` while +/// analyzing that file, except the fixes of the `dropped` diagnostics. +fn kept_own_fixes<'a>( + tidy_fixes: &'a [(usize, TidyFixes)], + dropped: &BTreeMap>, + index: usize, +) -> Vec<&'a Replacement> { + let dropped = dropped.get(&index).map(Vec::as_slice).unwrap_or_default(); + own_fixes(tidy_fixes, index) + .iter() + .filter(|(id, _)| !dropped.contains(id)) + .map(|(_, r)| r) + .collect() +} + /// Get the fixes that clang-tidy suggested for the analyzed file at `index` /// while analyzing that file. -fn own_fixes(tidy_fixes: &[(usize, TidyFixes)], index: usize) -> &[Replacement] { +fn own_fixes(tidy_fixes: &[(usize, TidyFixes)], index: usize) -> &[(usize, Replacement)] { tidy_fixes .iter() .find(|(i, _)| *i == index) @@ -319,15 +464,44 @@ fn own_fixes(tidy_fixes: &[(usize, TidyFixes)], index: usize) -> &[Replacement] .unwrap_or_default() } +/// Combine a file's `own` fixes with the accepted fixes from `others` +/// (paired with the index of the analyzed file that suggested them). +/// +/// A fix (eg. of a header) is found once for each analyzed file that includes it, +/// so an identical replacement is only applied as often as one analyzed file +/// suggested it. +fn merge_fixes(own: &[&Replacement], others: &[(usize, Replacement)]) -> Vec { + let mut included: HashMap<&Replacement, usize> = HashMap::new(); + for replacement in own { + *included.entry(replacement).or_default() += 1; + } + let mut seen: HashMap<(usize, &Replacement), usize> = HashMap::new(); + let mut extra = vec![]; + for (source, replacement) in others { + let seen = seen.entry((*source, replacement)).or_default(); + *seen += 1; + let included = included.entry(replacement).or_default(); + if *seen > *included { + *included += 1; + extra.push(replacement); + } + } + own.iter().copied().chain(extra).cloned().collect() +} + /// Do two replacements overlap, so only one of them can be applied? /// /// Identical replacements do not overlap, because they are applied once. fn overlaps(a: &Replacement, b: &Replacement) -> bool { - let (first, second) = if a <= b { (a, b) } else { (b, a) }; + let (first, second) = if (a.offset, a.length) <= (b.offset, b.length) { + (a, b) + } else { + (b, a) + }; first != second && second.offset < first.offset + first.length } -/// Record a `skipped` part of a `fix` on the note about the fix's diagnostic in the +/// Record why a `fix` was `skipped` on the note about the fix's diagnostic in the /// analyzed `source` file, so the thread comment and PR review can mention it. /// /// Nothing is recorded if no note about the diagnostic was found. @@ -354,36 +528,37 @@ fn record_skipped_fix( Ok(()) } -/// The accepted fixes for one analyzed file. +/// The accepted fixes from other files for one analyzed file. +#[derive(Default)] struct Pending { - /// The file's own fixes, followed by the accepted fixes from other files. - replacements: Vec, + /// The accepted fixes from other files, paired with the index of the analyzed + /// file that suggested them. + others: Vec<(usize, Replacement)>, /// Copies of the notes about the diagnostics that suggested the fixes, /// with the fixed lines in the analyzed file. notes: Vec, } impl Pending { - fn new(own: &[Replacement]) -> Self { - Self { - replacements: own.to_vec(), - notes: vec![], - } - } - - /// Accept a `fix` that starts at `line`, unless it overlaps a fix accepted before - /// (or the file's own fixes, which take precedence). - fn add(&mut self, fix: &OtherFileFix, line: u32) -> Result<(), Rejection> { - if self - .replacements + /// Check that a `fix` does not overlap the file's `own` fixes (which take precedence) + /// or a fix accepted before. + fn check(&self, own: &[&Replacement], fix: &OtherFileFix) -> Result<(), Rejection> { + if own .iter() + .copied() + .chain(self.others.iter().map(|(_, r)| r)) .any(|r| overlaps(r, &fix.replacement)) { return Err(Rejection::Overlaps); } - self.replacements.push(fix.replacement.clone()); + Ok(()) + } + + /// Accept a `fix` (suggested while analyzing the file at `source`) that starts at `line`. + fn add(&mut self, source: usize, fix: &OtherFileFix, line: u32) { + self.others.push((source, fix.replacement.clone())); let Some(note) = &fix.note else { - return Ok(()); + return; }; let note = TidyNotification { fixed_lines: vec![line], @@ -397,7 +572,6 @@ impl Pending { } else { self.notes.push(note); } - Ok(()) } } diff --git a/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs b/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs index 889b020d..eec77841 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/other_files/test.rs @@ -10,7 +10,10 @@ use std::{ use clang_tools_manager::RequestedVersion; use git_bot_feedback::FileFilter; -use super::{OtherFileFix, Pending, Replacement, TidyFixes, apply_other_file_fixes, merge_note}; +use super::{ + FixedLine, OtherFileFix, Pending, Replacement, TidyFixes, apply_other_file_fixes, merge_fixes, + merge_note, +}; use crate::{ clang_tools::{ ClangTool, analyze_files, @@ -54,6 +57,7 @@ fn header_fix(workspace: &Path) -> OtherFileFix { OtherFileFix { path: workspace.join("fix.h"), diagnostic: "readability-non-const-parameter".to_string(), + id: 0, replacement: Replacement { offset: HEADER_FIX_OFFSET, length: 0, @@ -89,6 +93,7 @@ fn header_notes(file: &Arc>) -> Vec { fn header_fixes(workspace: &Path) -> TidyFixes { TidyFixes { + fixed: vec![], own: vec![], others: vec![header_fix(workspace)], } @@ -169,6 +174,45 @@ async fn fix_analyzed_header() { assert_eq!(tally_tidy_advice(&files).unwrap(), 1); } +/// clang-tidy suggests a fix for the header while analyzing the source, +/// but the header is not analyzed. No half of the fix is applied, because a definition +/// that no longer matches the declaration would break the code. +#[tokio::test] +async fn fix_not_analyzed_header() { + let tmp = workspace(); + let clang_params = Arc::new(ClangParams { + tidy_checks: "-*,readability-non-const-parameter".to_string(), + clang_tidy_command: Some(get_tidy_exe()), + repo_root: tmp.path().to_path_buf(), + gen_patch: true, + ..Default::default() + }); + let files = as_files(vec![FileObj::new(PathBuf::from("fix.cpp"))]); + let logs = analyze_files(&files, clang_params).await.unwrap(); + assert_eq!(patched(&files[0]).unwrap(), SOURCE); + assert!( + messages(&logs[0]).iter().any(|msg| { + msg.starts_with("Not applying the fix for readability-non-const-parameter") + && msg.ends_with( + "because it also changes fix.h, and that file is not one of the analyzed files", + ) + }), + "{logs:#?}" + ); + let file = files[0].lock().unwrap(); + let notes = &file.tidy_advice.as_ref().unwrap().notes; + assert_eq!(notes.len(), 1, "{notes:#?}"); + // the diagnostic is still reported, with the reason why it was not fixed + assert!(notes[0].fixed_lines.is_empty(), "{notes:#?}"); + assert_eq!( + notes[0].skipped_fixes, + vec![SkippedFix { + file: "fix.h".to_string(), + reason: "that file is not one of the analyzed files".to_string(), + }] + ); +} + #[test] fn not_analyzed() { let tmp = workspace(); @@ -184,10 +228,14 @@ fn not_analyzed() { let files = as_files(vec![source]); let mut without_note = header_fix(tmp.path()); without_note.note = None; + without_note.id = 2; + let mut again = header_fix(tmp.path()); + again.id = 1; let fixes = TidyFixes { + fixed: vec![], own: vec![], - // the same fix twice, and a fix whose diagnostic has no note - others: vec![header_fix(tmp.path()), header_fix(tmp.path()), without_note], + // the same fix of two diagnostics, and a fix whose diagnostic has no note + others: vec![header_fix(tmp.path()), again, without_note], }; let mut logs = vec![vec![]]; apply_other_file_fixes(&files, &[(0, fixes)], &clang_params, &mut logs).unwrap(); @@ -195,7 +243,9 @@ fn not_analyzed() { let messages = messages(&logs[0]); assert_eq!(messages.len(), 3); assert!(messages[0].starts_with("Not applying the fix for readability-non-const-parameter")); - assert!(messages[0].ends_with("to fix.h because it is not one of the analyzed files")); + assert!(messages[0].ends_with( + "because it also changes fix.h, and that file is not one of the analyzed files" + )); // the skipped fix is recorded once on the diagnostic's note let file = files[0].lock().unwrap(); let note = &file.tidy_advice.as_ref().unwrap().notes[0]; @@ -203,12 +253,13 @@ fn not_analyzed() { note.skipped_fixes, vec![SkippedFix { file: "fix.h".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }] ); assert_eq!( note.skipped_fixes[0].describe(), - "Part of this fix was not applied to `fix.h` because it is not one of the analyzed files." + "This fix was not applied because it also changes `fix.h`, \ + and that file is not one of the analyzed files." ); } @@ -235,7 +286,11 @@ fn ignored_by_tidy() { assert!(patched(&files[1]).is_none()); let messages = messages(&logs[0]); assert_eq!(messages.len(), 1); - assert!(messages[0].ends_with("to fix.h because it is ignored by `--ignore-tidy`")); + assert!( + messages[0].ends_with( + "because it also changes fix.h, and that file is ignored by `--ignore-tidy`" + ) + ); assert!(logs[1].is_empty()); } @@ -264,11 +319,10 @@ fn outside_changed_lines() { assert!(patched(&files[1]).is_none()); let messages = messages(&logs[0]); assert_eq!(messages.len(), 1); - assert!( - messages[0].ends_with( - "to fix.h because the fix clashes with the `--lines-changed-only` constraint" - ) - ); + assert!(messages[0].ends_with( + "because it also changes fix.h, \ + and the change there clashes with the `--lines-changed-only` constraint" + )); } #[test] @@ -286,6 +340,7 @@ fn out_of_bounds() { fix.replacement.offset = HEADER.len(); fix.replacement.length = 1; let fixes = TidyFixes { + fixed: vec![], own: vec![], others: vec![fix], }; @@ -295,7 +350,8 @@ fn out_of_bounds() { let messages = messages(&logs[0]); assert_eq!(messages.len(), 1); assert!(messages[0].ends_with(&format!( - "to fix.h because the fix seems malformed and is out of the file's bounds \ + "because it also changes fix.h, \ + and the change there seems malformed and is out of the file's bounds \ (bytes {} to {} of a {} byte file)", HEADER.len(), HEADER.len() + 1, @@ -320,11 +376,15 @@ fn merge_with_own_fixes() { FileObj::new(PathBuf::from("other.cpp")), ]); let own = TidyFixes { - own: vec![Replacement { - offset: 0, - length: 0, - text: "// fixed\n".to_string(), - }], + fixed: vec![], + own: vec![( + 0, + Replacement { + offset: 0, + length: 0, + text: "// fixed\n".to_string(), + }, + )], others: vec![], }; let tidy_fixes = [ @@ -397,6 +457,7 @@ fn remove_changed_line() { text: String::new(), }; let fixes = TidyFixes { + fixed: vec![], own: vec![], others: vec![fix], }; @@ -465,6 +526,7 @@ fn analyzed_file_missing() { fs::remove_file(tmp.path().join("fix.h")).unwrap(); fs::create_dir(tmp.path().join("fix.h")).unwrap(); let fixes = TidyFixes { + fixed: vec![], own: vec![], others: vec![fix], }; @@ -482,15 +544,16 @@ fn pending_fix_without_note() { let tmp = workspace(); let mut fix = header_fix(tmp.path()); fix.note = None; - let mut pending = Pending::new(&[]); - assert!(pending.add(&fix, 2).is_ok()); - assert_eq!(pending.replacements, vec![fix.replacement]); + let mut pending = Pending::default(); + assert!(pending.check(&[], &fix).is_ok()); + pending.add(0, &fix, 2); + assert_eq!(pending.others, vec![(0, fix.replacement)]); assert!(pending.notes.is_empty()); // fixes for the same diagnostic on different lines share a note let fix = header_fix(tmp.path()); - assert!(pending.add(&fix, 2).is_ok()); - assert!(pending.add(&fix, 3).is_ok()); + pending.add(0, &fix, 2); + pending.add(0, &fix, 3); assert_eq!(pending.notes.len(), 1); assert_eq!(pending.notes[0].fixed_lines, vec![2, 3]); } @@ -523,6 +586,7 @@ fn overlapping_fixes() { FileObj::new(PathBuf::from("other.cpp")), ]); let fixes_of = |text: &str| TidyFixes { + fixed: vec![], own: vec![], others: vec![replace_int(tmp.path(), text)], }; @@ -536,9 +600,9 @@ fn overlapping_fixes() { assert!(messages(&logs[0])[0].starts_with("Applying the fix")); let messages = messages(&logs[2]); assert_eq!(messages.len(), 1); - assert!( - messages[0].ends_with("to fix.h because the fix overlaps another fix for the same file") - ); + assert!(messages[0].ends_with( + "because it also changes fix.h, and the change there overlaps another fix for that file" + )); // the overlapping fix does not touch the patch, so it gets no fixed line let notes = header_notes(&files[1]); assert_eq!(notes.len(), 1, "{notes:#?}"); @@ -561,27 +625,253 @@ fn overlaps_own_fix() { FileObj::new(PathBuf::from("fix.h")), ]); let own = TidyFixes { - own: vec![replace_int(tmp.path(), "long").replacement], + fixed: vec![], + own: vec![(0, replace_int(tmp.path(), "long").replacement)], others: vec![], }; let mut fix = header_fix(tmp.path()); // insert inside the replaced `int` fix.replacement.offset += 1; let others = TidyFixes { + fixed: vec![], own: vec![], others: vec![fix], }; let mut logs = vec![vec![], vec![]]; apply_other_file_fixes(&files, &[(0, others), (1, own)], &clang_params, &mut logs).unwrap(); - // only the header's own fix is applied + // the header's cached copy (with its own fix, written when the header was analyzed) + // is not patched again + assert!(patched(&files[1]).is_none()); + let messages = messages(&logs[0]); + assert_eq!(messages.len(), 1); + assert!(messages[0].ends_with( + "because it also changes fix.h, and the change there overlaps another fix for that file" + )); + assert!(header_notes(&files[1]).is_empty()); +} + +/// A fix that changes the analyzed source and another file is applied as a whole, +/// or not at all. +#[test] +fn whole_fix_or_nothing() { + let tmp = workspace(); + let clang_params = ClangParams { + repo_root: tmp.path().to_path_buf(), + gen_patch: true, + ..Default::default() + }; + let mut source = FileObj::new(PathBuf::from("fix.cpp")); + let mut note = source_note(); + note.fixed_lines = vec![2]; + let mut other_note = source_note(); + other_note.line = 3; + other_note.diagnostic = "modernize-use-auto".to_string(); + other_note.fixed_lines = vec![3]; + // a diagnostic whose fix is made by the fix for the header (on line 2), + // and by the other fix (on line 3) + let mut borrowed = source_note(); + borrowed.diagnostic = "misc-const-correctness".to_string(); + borrowed.fixed_lines = vec![2, 3]; + let fixed = vec![ + FixedLine::new(0, ¬e, 2), + FixedLine::new(1, &other_note, 3), + FixedLine::new(0, &borrowed, 2), + FixedLine::new(1, &borrowed, 3), + ]; + source.tidy_advice = Some(TidyAdvice { + notes: vec![note, other_note, borrowed], + ..Default::default() + }); + // the header is not analyzed + let files = as_files(vec![source]); + let offset = SOURCE.find("int *p").unwrap(); + let fixes = TidyFixes { + fixed, + own: vec![ + // the other half of the fix for the header + ( + 0, + Replacement { + offset, + length: 0, + text: "const ".to_string(), + }, + ), + // a fix of another diagnostic + ( + 1, + Replacement { + offset: SOURCE.find("int x").unwrap(), + length: 3, + text: "auto".to_string(), + }, + ), + ], + others: vec![header_fix(tmp.path())], + }; + let mut logs = vec![vec![]]; + apply_other_file_fixes(&files, &[(0, fixes)], &clang_params, &mut logs).unwrap(); + // the source's half of the fix is not applied, but the other fix is + assert_eq!( + patched(&files[0]).unwrap(), + SOURCE.replace("int x", "auto x") + ); + let file = files[0].lock().unwrap(); + let notes = &file.tidy_advice.as_ref().unwrap().notes; + assert!(notes[0].fixed_lines.is_empty(), "{notes:#?}"); + assert_eq!(notes[0].skipped_fixes.len(), 1); + assert_eq!(notes[1].fixed_lines, vec![3]); + assert!(notes[1].skipped_fixes.is_empty()); + assert_eq!(notes[2].fixed_lines, vec![3]); +} + +/// A file's own fix that is not applied (because it is part of a fix that also changes +/// a file that is not analyzed) does not keep another file's fix for that file. +#[test] +fn dropped_own_fix_does_not_block() { + let tmp = workspace(); + let clang_params = ClangParams { + repo_root: tmp.path().to_path_buf(), + gen_patch: true, + ..Default::default() + }; + let files = as_files(vec![ + FileObj::new(PathBuf::from("fix.cpp")), + FileObj::new(PathBuf::from("fix.h")), + ]); + // the header's own fix replaces `int`, and also changes a file that is not analyzed + let mut elsewhere = replace_int(tmp.path(), "long"); + elsewhere.path = tmp.path().join("other.h"); + let header = TidyFixes { + own: vec![(0, replace_int(tmp.path(), "long").replacement)], + others: vec![elsewhere], + ..Default::default() + }; + // the source's fix for the header inserts inside the replaced `int` + let mut fix = header_fix(tmp.path()); + fix.replacement.offset += 1; + fix.replacement.text = "/**/".to_string(); + let source = TidyFixes { + others: vec![fix], + ..Default::default() + }; + let mut logs = vec![vec![], vec![]]; + apply_other_file_fixes( + &files, + &[(0, source), (1, header)], + &clang_params, + &mut logs, + ) + .unwrap(); assert_eq!( patched(&files[1]).unwrap(), - "#pragma once\nvoid set(long *p);\n" + "#pragma once\nvoid set(i/**/nt *p);\n" ); - let messages = messages(&logs[0]); - assert_eq!(messages.len(), 1); assert!( - messages[0].ends_with("to fix.h because the fix overlaps another fix for the same file") + messages(&logs[0])[0].starts_with("Applying the fix"), + "{logs:#?}" ); - assert!(header_notes(&files[1]).is_empty()); + assert!( + messages(&logs[1])[0].starts_with("Not applying the fix"), + "{logs:#?}" + ); +} + +/// A fix that two analyzed files suggest (eg. for a header both include) is applied once, +/// but a text that one analyzed file inserts twice (from two diagnostics) is inserted twice. +#[test] +fn merge_fixes_from_several_files() { + let insert = |text: &str| Replacement { + offset: 3, + length: 0, + text: text.to_string(), + }; + let own = insert("}"); + let others = [ + (0, insert("}")), + (0, insert("}")), + (2, insert("}")), + (2, insert(";")), + (3, insert(";")), + ]; + assert_eq!( + merge_fixes(&[&own], &others), + vec![insert("}"), insert("}"), insert(";")] + ); +} + +#[test] +fn overlapping_replacements() { + let fix = |offset, length, text: &str| Replacement { + offset, + length, + text: text.to_string(), + }; + let a = fix(4, 3, "x"); + for (b, expected) in [ + (fix(4, 3, "x"), false), + (fix(4, 3, "y"), true), + (fix(6, 2, ""), true), + (fix(2, 3, ""), true), + (fix(7, 1, ""), false), + (fix(1, 3, ""), false), + ] { + assert_eq!(super::overlaps(&a, &b), expected, "{b:?}"); + assert_eq!(super::overlaps(&b, &a), expected, "{b:?}"); + } +} + +/// A line stays fixed if another file's accepted fix changes it, even though the +/// analyzed file's own fix for it is not applied. +#[test] +fn accepted_fix_keeps_fixed_line() { + let tmp = workspace(); + let clang_params = ClangParams { + repo_root: tmp.path().to_path_buf(), + gen_patch: true, + ..Default::default() + }; + // a diagnostic about the header, found by analyzing the header and the source + let header_note = TidyNotification { + filename: "fix.h".to_string(), + fixed_lines: vec![2], + ..source_note() + }; + let mut header = FileObj::new(PathBuf::from("fix.h")); + header.tidy_advice = Some(TidyAdvice { + notes: vec![header_note.clone()], + ..Default::default() + }); + let files = as_files(vec![FileObj::new(PathBuf::from("fix.cpp")), header]); + // the header's own fix also changes a file that is not analyzed + let mut elsewhere = header_fix(tmp.path()); + elsewhere.path = tmp.path().join("other.h"); + let header_fixes = TidyFixes { + own: vec![(0, header_fix(tmp.path()).replacement)], + others: vec![elsewhere], + fixed: vec![FixedLine::new(0, &header_note, 2)], + }; + // the source's fix for the header is accepted + let mut fix = header_fix(tmp.path()); + fix.note = Some(TidyNotification { + fixed_lines: vec![], + ..header_note + }); + let source_fixes = TidyFixes { + others: vec![fix], + ..Default::default() + }; + let mut logs = vec![vec![], vec![]]; + apply_other_file_fixes( + &files, + &[(0, source_fixes), (1, header_fixes)], + &clang_params, + &mut logs, + ) + .unwrap(); + assert_eq!( + patched(&files[1]).unwrap(), + "#pragma once\nvoid set(const int *p);\n" + ); + assert_eq!(header_notes(&files[1])[0].fixed_lines, vec![2]); } diff --git a/cpp-linter/src/clang_tools/clang_tidy/test.rs b/cpp-linter/src/clang_tools/clang_tidy/test.rs index c54e112e..91e6d2f4 100644 --- a/cpp-linter/src/clang_tools/clang_tidy/test.rs +++ b/cpp-linter/src/clang_tools/clang_tidy/test.rs @@ -19,7 +19,7 @@ use crate::{ use super::{ CLANG_DIAGNOSTICS_URL, ClangCaptureError, CompilationUnit, ExportedFixes, FixPaths, NOTE_HEADER, OtherFileFix, Replacement, TidyAdvice, TidyNotification, apply_fixes, - run_clang_tidy, tally_tidy_advice, tidy_failure, + other_files::FixedLine, run_clang_tidy, tally_tidy_advice, tidy_failure, }; #[test] @@ -329,7 +329,7 @@ fn suggestion_help_lists_a_multi_line_fix_once() { let mut note = dummy_note("demo.cpp", vec![5, 6]); note.skipped_fixes.push(SkippedFix { file: "demo.h".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }); let advice = TidyAdvice { notes: vec![note], @@ -337,7 +337,10 @@ fn suggestion_help_lists_a_multi_line_fix_once() { }; 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); + assert_eq!( + help.matches("/m/w.png\"> This fix was not applied").count(), + 1 + ); // The note is still listed when only one of its fixed lines is in the hunk. let help = advice.get_suggestion_help(6, 8); assert_eq!(help.matches("a dummy rationale").count(), 1); @@ -350,7 +353,7 @@ fn suggestion_help_with_skipped_fixes() { let mut note = dummy_note("demo.cpp", vec![5]); note.skipped_fixes.push(SkippedFix { file: "demo.h".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }); let advice = TidyAdvice { notes: vec![note], @@ -358,8 +361,8 @@ fn suggestion_help_with_skipped_fixes() { }; let help = advice.get_suggestion_help(5, 5); assert!(help.contains( - "/m/w.png\"> Part of this fix was not applied to `demo.h` \ - because it is not one of the analyzed files.\n" + "/m/w.png\"> This fix was not applied because it also changes `demo.h`, \ + and that file is not one of the analyzed files.\n" )); } @@ -674,11 +677,27 @@ Diagnostics: Offset: 8 Length: 1 ReplacementText: 'overlap' - # out-of-bounds fix is ignored + Level: Warning + BuildDirectory: '{build_dir}' + # a fix with an out-of-bounds part is ignored, with its part for another file + - DiagnosticName: modernize-use-auto + DiagnosticMessage: + Message: 'another rationale' + FilePath: '{target}' + FileOffset: 0 + Replacements: + - FilePath: '{target}' + Offset: 0 + Length: 4 + ReplacementText: 'nope' - FilePath: '{target}' Offset: 100 Length: 1 ReplacementText: 'oob' + - FilePath: 'fix.h' + Offset: 4 + Length: 1 + ReplacementText: 'nope' Level: Warning BuildDirectory: '{build_dir}' ... @@ -695,7 +714,7 @@ fn apply_exported_fixes() { let target = tmp.path().join("demo.cpp"); let content = b"line\n int y;\n"; let fixes: ExportedFixes = serde_saphyr::from_str(&dummy_fixes(&target)).unwrap(); - assert_eq!(fixes.diagnostics.len(), 1); + assert_eq!(fixes.diagnostics.len(), 2); let mut notes = vec![dummy_note("demo.cpp", vec![])]; notes[0].line = 2; let mut logs = vec![]; @@ -707,12 +726,21 @@ fn apply_exported_fixes() { assert_eq!(messages.len(), 2, "{messages:#?}"); assert!(messages[0].contains("out of bounds")); assert!(messages[1].contains("overlaps")); + // the fix with an out-of-bounds part is not applied at all + assert!(tidy_fixes.own.iter().all(|(id, _)| *id == 0)); + assert_eq!( + tidy_fixes.fixed, + vec![FixedLine::new(0, ¬es[0], 2)], + "{:#?}", + tidy_fixes.fixed + ); // the fix for another file is not applied, but returned assert_eq!( tidy_fixes.others, vec![OtherFileFix { path: tmp.path().join("fix.h"), diagnostic: "modernize-use-auto".to_string(), + id: 0, replacement: Replacement { offset: 0, length: 4, @@ -1155,3 +1183,120 @@ fn tidy_fixes_add_const_once() { "{notes:#?}" ); } + +/// The fixes of several checks are applied to the cached copy the way +/// `clang-tidy --fix` applies them to the file. +#[test] +fn fixes_match_clang_tidy_fix() { + let cases = [ + // nested `if` statements get a closing brace each + ( + "nested.c", + "int f(int a, int b) {\n int r = 0;\n if (a)\n if (b)\n r = 1;\n return r;\n}\n", + "-*,readability-braces-around-statements", + ), + // removed initializers leave no separators behind + ( + "init.cpp", + "struct T {\n T() : a(0), b(1), c(2) {}\n int a;\n int b;\n int c;\n};\n", + "-*,modernize-use-default-member-init", + ), + ( + "partial.cpp", + "struct S {\n S();\n};\nstruct T {\n T(int v) : a(v), s() {}\n int a;\n S s;\n};\n", + "-*,readability-redundant-member-init", + ), + ( + "ctor.cpp", + "struct S {\n S();\n};\nstruct T {\n T() try : s() {} catch (...) {}\n \ + T(int x) noexcept(noexcept(int{})) : s() {}\n T(int x, int y = int{0}) : s() {}\n \ + S s;\n};\n", + "-*,readability-redundant-member-init", + ), + ( + "assert.cpp", + "static_assert(sizeof(int) >= 4, \"\");\n", + "-*,modernize-unary-static-assert", + ), + // fixes that insert text at the same offset keep clang-tidy's order + ( + "order.cpp", + "class C {\npublic:\n int get_size();\nprivate:\n int total = 0;\n};\n\ + int C::get_size() { return total; }\n", + "-*,modernize-use-trailing-return-type,readability-make-member-function-const", + ), + ]; + let tidy = get_tidy_exe(); + for (name, source, checks) in cases { + let tmp = tempfile::TempDir::with_prefix("cpp-linter-unit-tests_").unwrap(); + fs::write(tmp.path().join(name), source).unwrap(); + let mut clang_params = make_clang_params(tmp.path(), Some(tidy.clone())); + clang_params.tidy_checks = checks.to_string(); + clang_params.extra_args = vec!["-std=c++17".to_string()]; + if name.ends_with(".c") { + clang_params.extra_args.clear(); + } + clang_params.gen_patch = true; + let file = Mutex::new(FileObj::new(PathBuf::from(name))); + 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(); + // the worktree is untouched + assert_eq!(fs::read_to_string(tmp.path().join(name)).unwrap(), source); + + // let clang-tidy fix a copy + let fixed_dir = tmp.path().join("fixed"); + fs::create_dir(&fixed_dir).unwrap(); + fs::write(fixed_dir.join(name), source).unwrap(); + let mut cmd = std::process::Command::new(&tidy); + cmd.current_dir(&fixed_dir) + .args(["-checks", checks, "-fix"]) + .args( + clang_params + .extra_args + .iter() + .map(|a| format!("--extra-arg={a}")), + ) + .arg(name); + let output = cmd.output().unwrap(); + let expected = fs::read_to_string(fixed_dir.join(name)).unwrap(); + assert_ne!( + expected, + source, + "clang-tidy did not fix {name}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(patched, expected, "{name}"); + } +} + +/// Fixes that can't be applied are skipped, and the rest are kept. +#[test] +fn patch_content_skips_bad_fixes() { + use super::{other_files::Replacement, patch_content}; + let fix = |offset, length, text: &str| Replacement { + offset, + length, + text: text.to_string(), + }; + let mut logs = vec![]; + let patched = patch_content( + b"int a = 1;", + &[ + fix(8, 1, "2"), + fix(8, 1, "2"), + fix(8, 2, "3;"), + fix(9, 5, ""), + fix(usize::MAX, 1, ""), + fix(0, 0, "const "), + ], + Path::new("a.c"), + &mut logs, + ); + assert_eq!(patched, b"const int a = 2;"); + let messages = logs.iter().map(|(_, m)| m.as_str()).collect::>(); + assert_eq!(messages.len(), 3, "{messages:?}"); + assert!(messages[0].starts_with("Skipping a fix that overlaps another fix in a.c")); + assert!(messages[1].starts_with("Skipping a fix that is out of bounds of a.c")); + assert!(messages[2].starts_with("Skipping a fix that is out of bounds of a.c")); +} diff --git a/cpp-linter/src/clang_tools/mod.rs b/cpp-linter/src/clang_tools/mod.rs index 80bbb454..fbd9f70c 100644 --- a/cpp-linter/src/clang_tools/mod.rs +++ b/cpp-linter/src/clang_tools/mod.rs @@ -131,6 +131,8 @@ async fn analyze_files( tidy_fixes.push((index, fixes)); } } + // in the order of `files`, so fixes for other files are applied the same way every time + tidy_fixes.sort_by_key(|(index, _)| *index); apply_other_file_fixes(files, &tidy_fixes, &clang_params, &mut logs)?; let mut executors = JoinSet::new(); diff --git a/cpp-linter/src/common_fs.rs b/cpp-linter/src/common_fs.rs index e1e18611..63e53964 100644 --- a/cpp-linter/src/common_fs.rs +++ b/cpp-linter/src/common_fs.rs @@ -668,7 +668,7 @@ mod test { TidyNotification { skipped_fixes: vec![SkippedFix { file: "test_file.h".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }], ..note(3, vec!["line3".to_string()]) }, @@ -707,8 +707,8 @@ mod test { // The comment is shown under the line, so the code snippet is left out. assert!(!new_suggestion.suggestion.contains("line3")); assert!(!new_suggestion.suggestion.contains("test_file.cpp:3")); - let skipped = "Part of this fix was not applied to `test_file.h` \ - because it is not one of the analyzed files."; + let skipped = "This fix was not applied because it also changes `test_file.h`, \ + and that file is not one of the analyzed files."; assert!( new_suggestion .suggestion diff --git a/cpp-linter/src/rest_client/test.rs b/cpp-linter/src/rest_client/test.rs index 141ee8f1..6afa61e3 100644 --- a/cpp-linter/src/rest_client/test.rs +++ b/cpp-linter/src/rest_client/test.rs @@ -345,7 +345,7 @@ fn skipped_fix_with_pipe_stays_in_its_cell() { .skipped_fixes .push(SkippedFix { file: "a|b.h".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }); let comment = RestClient::make_comment( &files, @@ -367,9 +367,11 @@ fn tidy_comment_with_skipped_fixes() { { let mut file = files[0].lock().unwrap(); let note = &mut file.tidy_advice.as_mut().unwrap().notes[0]; + // a fix that is not applied fixes no line + note.fixed_lines.clear(); note.skipped_fixes.push(SkippedFix { file: "tests/demo/demo.hpp".to_string(), - reason: "it is not one of the analyzed files".to_string(), + reason: "that file is not one of the analyzed files".to_string(), }); } let comment = RestClient::make_comment( @@ -385,13 +387,17 @@ fn tidy_comment_with_skipped_fixes() { .unwrap(); assert!( comment.contains( - " (fixable)
clang-diagnostic-error
\"⚠\"clang-diagnostic-error
\"⚠\" \ - Part of this fix was not \ - applied to `tests/demo/demo.hpp` because it is not one of the analyzed files. |\n" + This fix was not applied \ + because it also changes `tests/demo/demo.hpp`, and that file is not one of the analyzed files. |\n" ), "{comment}" ); + assert!( + !comment.contains("(fixable)
clang-diagnostic-error"), + "{comment}" + ); assert!( comment.contains("Or apply every fix at once: this step's `fix-patch-path`"), "{comment}" diff --git a/docs/docs/pr-review-caveats.md b/docs/docs/pr-review-caveats.md index 84dbee49..860d0f3d 100644 --- a/docs/docs/pr-review-caveats.md +++ b/docs/docs/pr-review-caveats.md @@ -85,8 +85,9 @@ Request diff (the summation of file differences in a Pull Request). We have made it so clang-tidy takes advantage of any fixes provided by the compiler. Compilation errors may still prevent clang-tidy from reporting all concerns. - A clang-tidy fix can also change another file (for example, the declaration in a header). - That part of the fix is only applied if the other file is also analyzed, is not ignored by + Such a fix is only applied if the other file is also analyzed, is not ignored by `ignore-tidy`, and the change is within the file's changed lines (per [`lines-changed-only`][lines-changed-only]). - Otherwise, the review summary (and the thread comment) lists the parts that were not applied, - so they can be applied by hand. + Otherwise, no part of the fix is applied, because half a fix often breaks the code + (for example, a definition that no longer matches its declaration). + The review summary (and the thread comment) lists these fixes, so they can be applied by hand.