Skip to content

Commit 2bdadd8

Browse files
committed
Auto merge of #6151 - bofh69:master, r=ebroto
Preserve raw strs for: format!(s) to s.to_string() lint fixes #6142 clippy::useless_format will keep the source's string (after converting {{ and }} to { and }) when suggesting a change from format!() to .to_string() usage. Ie: | let s = format!(r#""hello {{}}""#); | ^^^^^^^^^^^^^^^^^^^^^ help: consider using `.to_string()`: `r#""hello {}""#.to_string()` changelog: [`useless_format`]: preserve raw string literals when no arguments to `format!()` are provided.
2 parents 0b86340 + 7b7ddfa commit 2bdadd8

File tree

3 files changed

+15
-4
lines changed

3 files changed

+15
-4
lines changed

clippy_lints/src/format.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::utils::paths;
22
use crate::utils::{
3-
is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet,
3+
is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet, snippet_opt,
44
span_lint_and_then,
55
};
66
use if_chain::if_chain;
@@ -132,7 +132,11 @@ fn on_new_v1<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<Strin
132132
then {
133133
// `format!("foo")` expansion contains `match () { () => [], }`
134134
if tup.is_empty() {
135-
return Some(format!("{:?}.to_string()", s.as_str()));
135+
if let Some(s_src) = snippet_opt(cx, lit.span) {
136+
// Simulate macro expansion, converting {{ and }} to { and }.
137+
let s_expand = s_src.replace("{{", "{").replace("}}", "}");
138+
return Some(format!("{}.to_string()", s_expand))
139+
}
136140
} else if s.as_str().is_empty() {
137141
return on_argumentv1_new(cx, &tup[0], arms);
138142
}

tests/ui/format.fixed

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ fn main() {
1313
"foo".to_string();
1414
"{}".to_string();
1515
"{} abc {}".to_string();
16-
"foo {}\n\" bar".to_string();
16+
r##"foo {}
17+
" bar"##.to_string();
1718

1819
"foo".to_string();
1920
format!("{:?}", "foo"); // Don't warn about `Debug`.

tests/ui/format.stderr

+7-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,13 @@ LL | / format!(
2525
LL | | r##"foo {{}}
2626
LL | | " bar"##
2727
LL | | );
28-
| |______^ help: consider using `.to_string()`: `"foo {}/n/" bar".to_string();`
28+
| |______^
29+
|
30+
help: consider using `.to_string()`
31+
|
32+
LL | r##"foo {}
33+
LL | " bar"##.to_string();
34+
|
2935

3036
error: useless use of `format!`
3137
--> $DIR/format.rs:21:5

0 commit comments

Comments
 (0)