about summary refs log tree commit diff
diff options
context:
space:
mode:
authorbors <bors@rust-lang.org>2024-10-09 01:35:08 +0000
committerbors <bors@rust-lang.org>2024-10-09 01:35:08 +0000
commit1f8f982f222cfaacdfe2c8aa05ab535e54405a1f (patch)
tree97e2a4a91373be019ea71e560d50c56dc2a74854
parentd9c8d976cbcb3dfee324b47fa8bee57c6bb54203 (diff)
parent36c31db705031096520976e8134a98df4e44b578 (diff)
downloadrust-1f8f982f222cfaacdfe2c8aa05ab535e54405a1f.tar.gz
rust-1f8f982f222cfaacdfe2c8aa05ab535e54405a1f.zip
Auto merge of #13504 - samueltardieu:needless-raw-strings, r=Alexendoo
Check for needless raw strings in `format_args!()` template as well

changelog: [`needless_raw_strings`, `needless_raw_string_hashes`]: check `format_args!()` template as well

Fix #13503
-rw-r--r--clippy_dev/src/new_lint.rs24
-rw-r--r--clippy_lints/src/raw_strings.rs192
-rw-r--r--clippy_lints/src/rc_clone_in_vec_init.rs4
-rw-r--r--lintcheck/src/json.rs2
-rw-r--r--tests/config-metadata.rs4
-rw-r--r--tests/ui/needless_raw_string.fixed9
-rw-r--r--tests/ui/needless_raw_string.rs9
-rw-r--r--tests/ui/needless_raw_string.stderr38
-rw-r--r--tests/ui/needless_raw_string_hashes.fixed10
-rw-r--r--tests/ui/needless_raw_string_hashes.rs10
-rw-r--r--tests/ui/needless_raw_string_hashes.stderr38
11 files changed, 239 insertions, 101 deletions
diff --git a/clippy_dev/src/new_lint.rs b/clippy_dev/src/new_lint.rs
index c4d9c52a1cc..8b32dc6b888 100644
--- a/clippy_dev/src/new_lint.rs
+++ b/clippy_dev/src/new_lint.rs
@@ -207,13 +207,13 @@ pub(crate) fn get_stabilization_version() -> String {
 
 fn get_test_file_contents(lint_name: &str, msrv: bool) -> String {
     let mut test = formatdoc!(
-        r#"
+        r"
         #![warn(clippy::{lint_name})]
 
         fn main() {{
             // test code goes here
         }}
-    "#
+    "
     );
 
     if msrv {
@@ -272,23 +272,23 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
 
     result.push_str(&if enable_msrv {
         formatdoc!(
-            r#"
+            r"
             use clippy_config::msrvs::{{self, Msrv}};
             use clippy_config::Conf;
             {pass_import}
             use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
             use rustc_session::impl_lint_pass;
 
-        "#
+        "
         )
     } else {
         formatdoc!(
-            r#"
+            r"
             {pass_import}
             use rustc_lint::{{{context_import}, {pass_type}}};
             use rustc_session::declare_lint_pass;
 
-        "#
+        "
         )
     });
 
@@ -296,7 +296,7 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
 
     result.push_str(&if enable_msrv {
         formatdoc!(
-            r#"
+            r"
             pub struct {name_camel} {{
                 msrv: Msrv,
             }}
@@ -315,15 +315,15 @@ fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
 
             // TODO: Add MSRV level to `clippy_config/src/msrvs.rs` if needed.
             // TODO: Update msrv config comment in `clippy_config/src/conf.rs`
-        "#
+        "
         )
     } else {
         formatdoc!(
-            r#"
+            r"
             declare_lint_pass!({name_camel} => [{name_upper}]);
 
             impl {pass_type}{pass_lifetimes} for {name_camel} {{}}
-        "#
+        "
         )
     });
 
@@ -416,7 +416,7 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R
     } else {
         let _: fmt::Result = writedoc!(
             lint_file_contents,
-            r#"
+            r"
                 use rustc_lint::{{{context_import}, LintContext}};
 
                 use super::{name_upper};
@@ -425,7 +425,7 @@ fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::R
                 pub(super) fn check(cx: &{context_import}{pass_lifetimes}) {{
                     todo!();
                 }}
-           "#
+           "
         );
     }
 
diff --git a/clippy_lints/src/raw_strings.rs b/clippy_lints/src/raw_strings.rs
index 3c19ee3522d..23d0e768c2f 100644
--- a/clippy_lints/src/raw_strings.rs
+++ b/clippy_lints/src/raw_strings.rs
@@ -1,6 +1,6 @@
 use clippy_config::Conf;
 use clippy_utils::diagnostics::span_lint_and_then;
-use clippy_utils::source::SpanRangeExt;
+use clippy_utils::source::{SpanRangeExt, snippet_opt};
 use rustc_ast::ast::{Expr, ExprKind};
 use rustc_ast::token::LitKind;
 use rustc_errors::Applicability;
@@ -71,6 +71,23 @@ impl RawStrings {
 
 impl EarlyLintPass for RawStrings {
     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
+        if let ExprKind::FormatArgs(format_args) = &expr.kind
+            && !in_external_macro(cx.sess(), format_args.span)
+            && format_args.span.check_source_text(cx, |src| src.starts_with('r'))
+            && let Some(str) = snippet_opt(cx.sess(), format_args.span)
+            && let count_hash = str.bytes().skip(1).take_while(|b| *b == b'#').count()
+            && let Some(str) = str.get(count_hash + 2..str.len() - count_hash - 1)
+        {
+            self.check_raw_string(
+                cx,
+                str,
+                format_args.span,
+                "r",
+                u8::try_from(count_hash).unwrap(),
+                "string",
+            );
+        }
+
         if let ExprKind::Lit(lit) = expr.kind
             && let (prefix, max) = match lit.kind {
                 LitKind::StrRaw(max) => ("r", max),
@@ -81,94 +98,105 @@ impl EarlyLintPass for RawStrings {
             && !in_external_macro(cx.sess(), expr.span)
             && expr.span.check_source_text(cx, |src| src.starts_with(prefix))
         {
-            let str = lit.symbol.as_str();
-            let descr = lit.kind.descr();
-
-            if !str.contains(['\\', '"']) {
-                span_lint_and_then(
-                    cx,
-                    NEEDLESS_RAW_STRINGS,
-                    expr.span,
-                    "unnecessary raw string literal",
-                    |diag| {
-                        let (start, end) = hash_spans(expr.span, prefix.len(), 0, max);
-
-                        // BytePos: skip over the `b` in `br`, we checked the prefix appears in the source text
-                        let r_pos = expr.span.lo() + BytePos::from_usize(prefix.len() - 1);
-                        let start = start.with_lo(r_pos);
-
-                        let mut remove = vec![(start, String::new())];
-                        // avoid debug ICE from empty suggestions
-                        if !end.is_empty() {
-                            remove.push((end, String::new()));
-                        }
+            self.check_raw_string(cx, lit.symbol.as_str(), expr.span, prefix, max, lit.kind.descr());
+        }
+    }
+}
 
-                        diag.multipart_suggestion_verbose(
-                            format!("use a plain {descr} literal instead"),
-                            remove,
-                            Applicability::MachineApplicable,
-                        );
-                    },
-                );
-                if !matches!(cx.get_lint_level(NEEDLESS_RAW_STRINGS), rustc_lint::Allow) {
-                    return;
-                }
+impl RawStrings {
+    fn check_raw_string(
+        &mut self,
+        cx: &EarlyContext<'_>,
+        str: &str,
+        lit_span: Span,
+        prefix: &str,
+        max: u8,
+        descr: &str,
+    ) {
+        if !str.contains(['\\', '"']) {
+            span_lint_and_then(
+                cx,
+                NEEDLESS_RAW_STRINGS,
+                lit_span,
+                "unnecessary raw string literal",
+                |diag| {
+                    let (start, end) = hash_spans(lit_span, prefix.len(), 0, max);
+
+                    // BytePos: skip over the `b` in `br`, we checked the prefix appears in the source text
+                    let r_pos = lit_span.lo() + BytePos::from_usize(prefix.len() - 1);
+                    let start = start.with_lo(r_pos);
+
+                    let mut remove = vec![(start, String::new())];
+                    // avoid debug ICE from empty suggestions
+                    if !end.is_empty() {
+                        remove.push((end, String::new()));
+                    }
+
+                    diag.multipart_suggestion_verbose(
+                        format!("use a plain {descr} literal instead"),
+                        remove,
+                        Applicability::MachineApplicable,
+                    );
+                },
+            );
+            if !matches!(cx.get_lint_level(NEEDLESS_RAW_STRINGS), rustc_lint::Allow) {
+                return;
             }
+        }
 
-            let mut req = {
-                let mut following_quote = false;
-                let mut req = 0;
-                // `once` so a raw string ending in hashes is still checked
-                let num = str.as_bytes().iter().chain(once(&0)).try_fold(0u8, |acc, &b| {
-                    match b {
-                        b'"' if !following_quote => (following_quote, req) = (true, 1),
-                        b'#' => req += u8::from(following_quote),
-                        _ => {
-                            if following_quote {
-                                following_quote = false;
-
-                                if req == max {
-                                    return ControlFlow::Break(req);
-                                }
-
-                                return ControlFlow::Continue(acc.max(req));
+        let mut req = {
+            let mut following_quote = false;
+            let mut req = 0;
+            // `once` so a raw string ending in hashes is still checked
+            let num = str.as_bytes().iter().chain(once(&0)).try_fold(0u8, |acc, &b| {
+                match b {
+                    b'"' if !following_quote => (following_quote, req) = (true, 1),
+                    b'#' => req += u8::from(following_quote),
+                    _ => {
+                        if following_quote {
+                            following_quote = false;
+
+                            if req == max {
+                                return ControlFlow::Break(req);
                             }
-                        },
-                    }
 
-                    ControlFlow::Continue(acc)
-                });
-
-                match num {
-                    ControlFlow::Continue(num) | ControlFlow::Break(num) => num,
-                }
-            };
-            if self.allow_one_hash_in_raw_strings {
-                req = req.max(1);
-            }
-            if req < max {
-                span_lint_and_then(
-                    cx,
-                    NEEDLESS_RAW_STRING_HASHES,
-                    expr.span,
-                    "unnecessary hashes around raw string literal",
-                    |diag| {
-                        let (start, end) = hash_spans(expr.span, prefix.len(), req, max);
-
-                        let message = match max - req {
-                            _ if req == 0 => format!("remove all the hashes around the {descr} literal"),
-                            1 => format!("remove one hash from both sides of the {descr} literal"),
-                            n => format!("remove {n} hashes from both sides of the {descr} literal"),
-                        };
-
-                        diag.multipart_suggestion(
-                            message,
-                            vec![(start, String::new()), (end, String::new())],
-                            Applicability::MachineApplicable,
-                        );
+                            return ControlFlow::Continue(acc.max(req));
+                        }
                     },
-                );
+                }
+
+                ControlFlow::Continue(acc)
+            });
+
+            match num {
+                ControlFlow::Continue(num) | ControlFlow::Break(num) => num,
             }
+        };
+        if self.allow_one_hash_in_raw_strings {
+            req = req.max(1);
+        }
+        if req < max {
+            span_lint_and_then(
+                cx,
+                NEEDLESS_RAW_STRING_HASHES,
+                lit_span,
+                "unnecessary hashes around raw string literal",
+                |diag| {
+                    let (start, end) = hash_spans(lit_span, prefix.len(), req, max);
+
+                    let message = match max - req {
+                        _ if req == 0 => format!("remove all the hashes around the {descr} literal"),
+                        1 => format!("remove one hash from both sides of the {descr} literal"),
+                        n => format!("remove {n} hashes from both sides of the {descr} literal"),
+                    };
+
+                    diag.multipart_suggestion(
+                        message,
+                        vec![(start, String::new()), (end, String::new())],
+                        Applicability::MachineApplicable,
+                    );
+                },
+            );
         }
     }
 }
diff --git a/clippy_lints/src/rc_clone_in_vec_init.rs b/clippy_lints/src/rc_clone_in_vec_init.rs
index e877f5d6ed4..6bb7650a7e1 100644
--- a/clippy_lints/src/rc_clone_in_vec_init.rs
+++ b/clippy_lints/src/rc_clone_in_vec_init.rs
@@ -65,11 +65,11 @@ impl LateLintPass<'_> for RcCloneInVecInit {
 
 fn loop_init_suggestion(elem: &str, len: &str, indent: &str) -> String {
     format!(
-        r#"{{
+        r"{{
 {indent}    let mut v = Vec::with_capacity({len});
 {indent}    (0..{len}).for_each(|_| v.push({elem}));
 {indent}    v
-{indent}}}"#
+{indent}}}"
     )
 }
 
diff --git a/lintcheck/src/json.rs b/lintcheck/src/json.rs
index ee0c80aea52..3a68f2c9243 100644
--- a/lintcheck/src/json.rs
+++ b/lintcheck/src/json.rs
@@ -133,7 +133,7 @@ fn print_lint_warnings(lint: &LintWarnings, truncate_after: usize) {
     println!();
 
     print!(
-        r##"{}, {}, {}"##,
+        r"{}, {}, {}",
         count_string(name, "added", lint.added.len()),
         count_string(name, "removed", lint.removed.len()),
         count_string(name, "changed", lint.changed.len()),
diff --git a/tests/config-metadata.rs b/tests/config-metadata.rs
index 628dfc8f758..af9fe064dc7 100644
--- a/tests/config-metadata.rs
+++ b/tests/config-metadata.rs
@@ -20,7 +20,7 @@ fn book() {
 
     let configs = metadata().map(|conf| conf.to_markdown_paragraph()).join("\n");
     let expected = format!(
-        r#"<!--
+        r"<!--
 This file is generated by `cargo bless --test config-metadata`.
 Please use that command to update the file and do not edit it by hand.
 -->
@@ -33,7 +33,7 @@ and lints affected.
 ---
 
 {}
-"#,
+",
         configs.trim(),
     );
 
diff --git a/tests/ui/needless_raw_string.fixed b/tests/ui/needless_raw_string.fixed
index 1a9c601c462..ab061467488 100644
--- a/tests/ui/needless_raw_string.fixed
+++ b/tests/ui/needless_raw_string.fixed
@@ -22,3 +22,12 @@ fn main() {
     b"no hashes";
     c"no hashes";
 }
+
+fn issue_13503() {
+    println!("SELECT * FROM posts");
+    println!("SELECT * FROM posts");
+    println!(r##"SELECT * FROM "posts""##);
+
+    // Test arguments as well
+    println!("{}", "foobar".len());
+}
diff --git a/tests/ui/needless_raw_string.rs b/tests/ui/needless_raw_string.rs
index 1126ea5aa30..5be8bdeb4ad 100644
--- a/tests/ui/needless_raw_string.rs
+++ b/tests/ui/needless_raw_string.rs
@@ -22,3 +22,12 @@ fn main() {
     br"no hashes";
     cr"no hashes";
 }
+
+fn issue_13503() {
+    println!(r"SELECT * FROM posts");
+    println!(r#"SELECT * FROM posts"#);
+    println!(r##"SELECT * FROM "posts""##);
+
+    // Test arguments as well
+    println!("{}", r"foobar".len());
+}
diff --git a/tests/ui/needless_raw_string.stderr b/tests/ui/needless_raw_string.stderr
index 7d3451a03c7..5169f085573 100644
--- a/tests/ui/needless_raw_string.stderr
+++ b/tests/ui/needless_raw_string.stderr
@@ -91,5 +91,41 @@ LL -     cr"no hashes";
 LL +     c"no hashes";
    |
 
-error: aborting due to 7 previous errors
+error: unnecessary raw string literal
+  --> tests/ui/needless_raw_string.rs:27:14
+   |
+LL |     println!(r"SELECT * FROM posts");
+   |              ^^^^^^^^^^^^^^^^^^^^^^
+   |
+help: use a plain string literal instead
+   |
+LL -     println!(r"SELECT * FROM posts");
+LL +     println!("SELECT * FROM posts");
+   |
+
+error: unnecessary raw string literal
+  --> tests/ui/needless_raw_string.rs:28:14
+   |
+LL |     println!(r#"SELECT * FROM posts"#);
+   |              ^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+help: use a plain string literal instead
+   |
+LL -     println!(r#"SELECT * FROM posts"#);
+LL +     println!("SELECT * FROM posts");
+   |
+
+error: unnecessary raw string literal
+  --> tests/ui/needless_raw_string.rs:32:20
+   |
+LL |     println!("{}", r"foobar".len());
+   |                    ^^^^^^^^^
+   |
+help: use a plain string literal instead
+   |
+LL -     println!("{}", r"foobar".len());
+LL +     println!("{}", "foobar".len());
+   |
+
+error: aborting due to 10 previous errors
 
diff --git a/tests/ui/needless_raw_string_hashes.fixed b/tests/ui/needless_raw_string_hashes.fixed
index b2ad657d6b2..4c113709107 100644
--- a/tests/ui/needless_raw_string_hashes.fixed
+++ b/tests/ui/needless_raw_string_hashes.fixed
@@ -24,3 +24,13 @@ fn main() {
     r"rust";
     r"hello world";
 }
+
+fn issue_13503() {
+    println!(r"SELECT * FROM posts");
+    println!(r"SELECT * FROM posts");
+    println!(r#"SELECT * FROM "posts""#);
+    println!(r#"SELECT * FROM "posts""#);
+
+    // Test arguments as well
+    println!("{}", r"foobar".len());
+}
diff --git a/tests/ui/needless_raw_string_hashes.rs b/tests/ui/needless_raw_string_hashes.rs
index 54d8ed76d47..7b6b4e784ee 100644
--- a/tests/ui/needless_raw_string_hashes.rs
+++ b/tests/ui/needless_raw_string_hashes.rs
@@ -24,3 +24,13 @@ fn main() {
     r###"rust"###;
     r#"hello world"#;
 }
+
+fn issue_13503() {
+    println!(r"SELECT * FROM posts");
+    println!(r#"SELECT * FROM posts"#);
+    println!(r##"SELECT * FROM "posts""##);
+    println!(r##"SELECT * FROM "posts""##);
+
+    // Test arguments as well
+    println!("{}", r"foobar".len());
+}
diff --git a/tests/ui/needless_raw_string_hashes.stderr b/tests/ui/needless_raw_string_hashes.stderr
index 96864f612c0..a213ba3e743 100644
--- a/tests/ui/needless_raw_string_hashes.stderr
+++ b/tests/ui/needless_raw_string_hashes.stderr
@@ -187,5 +187,41 @@ LL -     r#"hello world"#;
 LL +     r"hello world";
    |
 
-error: aborting due to 15 previous errors
+error: unnecessary hashes around raw string literal
+  --> tests/ui/needless_raw_string_hashes.rs:30:14
+   |
+LL |     println!(r#"SELECT * FROM posts"#);
+   |              ^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+help: remove all the hashes around the string literal
+   |
+LL -     println!(r#"SELECT * FROM posts"#);
+LL +     println!(r"SELECT * FROM posts");
+   |
+
+error: unnecessary hashes around raw string literal
+  --> tests/ui/needless_raw_string_hashes.rs:31:14
+   |
+LL |     println!(r##"SELECT * FROM "posts""##);
+   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+help: remove one hash from both sides of the string literal
+   |
+LL -     println!(r##"SELECT * FROM "posts""##);
+LL +     println!(r#"SELECT * FROM "posts""#);
+   |
+
+error: unnecessary hashes around raw string literal
+  --> tests/ui/needless_raw_string_hashes.rs:32:14
+   |
+LL |     println!(r##"SELECT * FROM "posts""##);
+   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+   |
+help: remove one hash from both sides of the string literal
+   |
+LL -     println!(r##"SELECT * FROM "posts""##);
+LL +     println!(r#"SELECT * FROM "posts""#);
+   |
+
+error: aborting due to 18 previous errors