Skip to content

Commit 3dbc512

Browse files
committed
Fix to_string_in_format_args false positive
1 parent 6f26383 commit 3dbc512

File tree

4 files changed

+58
-1
lines changed

4 files changed

+58
-1
lines changed

clippy_utils/src/macros.rs

+3
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,9 @@ impl<'tcx> FormatArgsExpn<'tcx> {
359359
sym::const_format_args | sym::format_args | sym::format_args_nl
360360
)
361361
})?;
362+
if !matches!(expr.kind, ExprKind::Call(..)) {
363+
return None;
364+
}
362365
let mut format_string_span: Option<Span> = None;
363366
let mut format_string_parts: Vec<Symbol> = Vec::new();
364367
let mut value_args: Vec<&Expr<'_>> = Vec::new();

tests/ui/format_args.fixed

+24
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,27 @@ fn main() {
115115
// https://github.com/rust-lang/rust-clippy/issues/7903
116116
println!("{foo}{foo:?}", foo = "foo".to_string());
117117
}
118+
119+
// https://github.com/rust-lang/rust-clippy/issues/8855
120+
mod issue_8855 {
121+
#![allow(dead_code)]
122+
123+
struct A {}
124+
125+
impl std::fmt::Display for A {
126+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
127+
write!(f, "test")
128+
}
129+
}
130+
131+
fn main() {
132+
let a = A {};
133+
let b = A {};
134+
135+
let x = format!("{} {}", a, b);
136+
dbg!(x);
137+
138+
let x = format!("{:>6} {:>6}", a, b.to_string());
139+
dbg!(x);
140+
}
141+
}

tests/ui/format_args.rs

+24
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,27 @@ fn main() {
115115
// https://github.com/rust-lang/rust-clippy/issues/7903
116116
println!("{foo}{foo:?}", foo = "foo".to_string());
117117
}
118+
119+
// https://github.com/rust-lang/rust-clippy/issues/8855
120+
mod issue_8855 {
121+
#![allow(dead_code)]
122+
123+
struct A {}
124+
125+
impl std::fmt::Display for A {
126+
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
127+
write!(f, "test")
128+
}
129+
}
130+
131+
fn main() {
132+
let a = A {};
133+
let b = A {};
134+
135+
let x = format!("{} {}", a, b.to_string());
136+
dbg!(x);
137+
138+
let x = format!("{:>6} {:>6}", a, b.to_string());
139+
dbg!(x);
140+
}
141+
}

tests/ui/format_args.stderr

+7-1
Original file line numberDiff line numberDiff line change
@@ -126,5 +126,11 @@ error: `to_string` applied to a type that implements `Display` in `println!` arg
126126
LL | println!("{foo}{bar}", bar = "bar", foo = "foo".to_string());
127127
| ^^^^^^^^^^^^ help: remove this
128128

129-
error: aborting due to 21 previous errors
129+
error: `to_string` applied to a type that implements `Display` in `format!` args
130+
--> $DIR/format_args.rs:135:38
131+
|
132+
LL | let x = format!("{} {}", a, b.to_string());
133+
| ^^^^^^^^^^^^ help: remove this
134+
135+
error: aborting due to 22 previous errors
130136

0 commit comments

Comments
 (0)