Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve raw strs for: format!(s) to s.to_string() lint #6151

Merged
merged 1 commit into from
Oct 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions clippy_lints/src/format.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down
3 changes: 2 additions & 1 deletion tests/ui/format.fixed
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
8 changes: 7 additions & 1 deletion tests/ui/format.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down