From a7fb37c1d832bea651f29b4676a816635dc11894 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 7 Jan 2025 15:55:41 +0100 Subject: [PATCH] Correctly handle expanded macros for `literal_string_with_formatting_args` lint --- .../src/literal_string_with_formatting_args.rs | 9 +++++++++ tests/ui/{literal_string_with_formatting_args}.rs | 14 ++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 tests/ui/{literal_string_with_formatting_args}.rs diff --git a/clippy_lints/src/literal_string_with_formatting_args.rs b/clippy_lints/src/literal_string_with_formatting_args.rs index 4c8063ee6e63..c0d016ce08b0 100644 --- a/clippy_lints/src/literal_string_with_formatting_args.rs +++ b/clippy_lints/src/literal_string_with_formatting_args.rs @@ -8,6 +8,7 @@ use rustc_span::{BytePos, Span}; use clippy_utils::diagnostics::span_lint; use clippy_utils::mir::enclosing_mir; +use clippy_utils::source::snippet_opt; declare_clippy_lint! { /// ### What it does @@ -95,7 +96,15 @@ impl LateLintPass<'_> for LiteralStringWithFormattingArg { }, _ => return, }; + let Some(snippet) = snippet_opt(cx, expr.span) else { + return; + }; let fmt_str = symbol.as_str(); + // If the literal has been generated by the macro, the snippet should not contain it, + // allowing us to skip it. + if !snippet.contains(fmt_str) { + return; + } let lo = expr.span.lo(); let mut current = fmt_str; let mut diff_len = 0; diff --git a/tests/ui/{literal_string_with_formatting_args}.rs b/tests/ui/{literal_string_with_formatting_args}.rs new file mode 100644 index 000000000000..8a06d0c7b360 --- /dev/null +++ b/tests/ui/{literal_string_with_formatting_args}.rs @@ -0,0 +1,14 @@ +// Regression test for . +// The `dbg` macro generates a literal with the name of the current file, so +// we need to ensure the lint is not emitted in this case. + +#![crate_name = "foo"] +#![allow(unused)] +#![warn(clippy::literal_string_with_formatting_args)] + +fn another_bad() { + let literal_string_with_formatting_args = 0; + dbg!("something"); +} + +fn main() {}