]> git.lizzy.rs Git - rust.git/commitdiff
Preserve raw strs for: format!(s) to s.to_string() lint
authorSebastian Andersson <sebastian@bittr.nu>
Fri, 9 Oct 2020 18:23:03 +0000 (20:23 +0200)
committerSebastian Andersson <sebastian@bittr.nu>
Fri, 9 Oct 2020 18:23:03 +0000 (20:23 +0200)
Ie:
|     let s = format!(r#""hello""#);
|             ^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `r#""hello""#.to_string()`

clippy_lints/src/format.rs
tests/ui/format.fixed
tests/ui/format.stderr

index d6541010bca2326691b8b3e961f14f2bdb77db3f..26da058598e4ff996ff872cc16e22e7fbdc48b77 100644 (file)
@@ -1,6 +1,6 @@
 use crate::utils::paths;
 use crate::utils::{
-    is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet,
+    is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet, snippet_opt,
     span_lint_and_then,
 };
 use if_chain::if_chain;
@@ -132,7 +132,11 @@ fn on_new_v1<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<Strin
         then {
             // `format!("foo")` expansion contains `match () { () => [], }`
             if tup.is_empty() {
-                return Some(format!("{:?}.to_string()", s.as_str()));
+                if let Some(s_src) = snippet_opt(cx, lit.span) {
+                    // Simulate macro expansion, converting {{ and }} to { and }.
+                    let s_expand = s_src.replace("{{", "{").replace("}}", "}");
+                    return Some(format!("{}.to_string()", s_expand))
+                }
             } else if s.as_str().is_empty() {
                 return on_argumentv1_new(cx, &tup[0], arms);
             }
index 306514769990d82edde8ff07ebe1780c625cb061..740a22a07d747c5dc409fea811cf27afb96e5468 100644 (file)
@@ -13,7 +13,8 @@ fn main() {
     "foo".to_string();
     "{}".to_string();
     "{} abc {}".to_string();
-    "foo {}\n\" bar".to_string();
+    r##"foo {}
+" bar"##.to_string();
 
     "foo".to_string();
     format!("{:?}", "foo"); // Don't warn about `Debug`.
index 9734492154e8009fca62c7e5a2903cb649507c00..96df7f37f779232dd03fc305b86845381317ef69 100644 (file)
@@ -25,7 +25,13 @@ LL | /     format!(
 LL | |         r##"foo {{}}
 LL | | " bar"##
 LL | |     );
-   | |______^ help: consider using `.to_string()`: `"foo {}/n/" bar".to_string();`
+   | |______^
+   |
+help: consider using `.to_string()`
+   |
+LL |     r##"foo {}
+LL | " bar"##.to_string();
+   |
 
 error: useless use of `format!`
   --> $DIR/format.rs:21:5