diff --git a/clippy_lints/src/format.rs b/clippy_lints/src/format.rs index ceba8278fb0..1df6b9294d7 100644 --- a/clippy_lints/src/format.rs +++ b/clippy_lints/src/format.rs @@ -1,5 +1,7 @@ use crate::utils::paths; -use crate::utils::{is_expn_of, last_path_segment, match_def_path, resolve_node, snippet, span_lint_and_then}; +use crate::utils::{ + is_expn_of, last_path_segment, match_def_path, match_type, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty, +}; use if_chain::if_chain; use rustc::hir::*; use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass}; @@ -87,6 +89,10 @@ fn on_argumentv1_new<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, arm if let PatKind::Tuple(ref pats, None) = arms[0].pats[0].node; if pats.len() == 1; then { + let ty = walk_ptrs_ty(cx.tables.pat_ty(&pats[0])); + if ty.sty != rustc::ty::Str && !match_type(cx, ty, &paths::STRING) { + return None; + } if let ExprKind::Lit(ref lit) = format_args.node { if let LitKind::Str(ref s, _) = lit.node { return Some(format!("{:?}.to_string()", s.as_str())); @@ -97,6 +103,8 @@ fn on_argumentv1_new<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, arm if path.ident.name == sym!(to_string) { return Some(format!("{}", snip)); } + } else if let ExprKind::Binary(..) = format_args.node { + return Some(format!("{}", snip)); } return Some(format!("{}.to_string()", snip)); } diff --git a/tests/ui/format.fixed b/tests/ui/format.fixed index 401a1c533fe..6e100230a3a 100644 --- a/tests/ui/format.fixed +++ b/tests/ui/format.fixed @@ -60,4 +60,8 @@ fn main() { 42.to_string(); let x = std::path::PathBuf::from("/bar/foo/qux"); x.display().to_string(); + + // False positive + let a = "foo".to_string(); + let _ = Some(a + "bar"); } diff --git a/tests/ui/format.rs b/tests/ui/format.rs index 1cbc15cfcec..1fae6603ac0 100644 --- a/tests/ui/format.rs +++ b/tests/ui/format.rs @@ -63,4 +63,8 @@ fn main() { format!("{}", 42.to_string()); let x = std::path::PathBuf::from("/bar/foo/qux"); format!("{}", x.display().to_string()); + + // False positive + let a = "foo".to_string(); + let _ = Some(format!("{}", a + "bar")); } diff --git a/tests/ui/format.stderr b/tests/ui/format.stderr index 433a0e705ac..9736f34b03b 100644 --- a/tests/ui/format.stderr +++ b/tests/ui/format.stderr @@ -75,5 +75,11 @@ error: useless use of `format!` LL | format!("{}", x.display().to_string()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `x.display().to_string();` -error: aborting due to 12 previous errors +error: useless use of `format!` + --> $DIR/format.rs:69:18 + | +LL | let _ = Some(format!("{}", a + "bar")); + | ^^^^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `a + "bar"` + +error: aborting due to 13 previous errors