From ff98e3f9f50ca14e2fe96da0b36f6ac05476970a Mon Sep 17 00:00:00 2001 From: Philipp Hansch Date: Thu, 5 Apr 2018 07:52:26 +0200 Subject: [PATCH] Fix useless_format false positive with macros Clippy was issuing a warning when `format!` was used inside a macro. That's a problem because macros have different syntax and can be outside the control of the user. This skips the `useless_format` check if the `format!` call is inside a macro. --- clippy_lints/src/format.rs | 5 ++++- tests/ui/format.rs | 9 +++++++++ tests/ui/format.stderr | 12 ++++++------ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/clippy_lints/src/format.rs b/clippy_lints/src/format.rs index 7136eff3274..2b5b79db980 100644 --- a/clippy_lints/src/format.rs +++ b/clippy_lints/src/format.rs @@ -3,7 +3,7 @@ use rustc::lint::*; use rustc::ty; use syntax::ast::LitKind; use utils::paths; -use utils::{is_expn_of, match_def_path, match_type, opt_def_id, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty}; +use utils::{in_macro, is_expn_of, match_def_path, match_type, opt_def_id, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty}; /// **What it does:** Checks for the use of `format!("string literal with no /// argument")` and `format!("{}", foo)` where `foo` is a string. @@ -39,6 +39,9 @@ impl LintPass for Pass { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { if let Some(span) = is_expn_of(expr.span, "format") { + if in_macro(span) { + return; + } match expr.node { // `format!("{}", foo)` expansion ExprCall(ref fun, ref args) => { diff --git a/tests/ui/format.rs b/tests/ui/format.rs index e9379d0a05b..ac97bd24ea1 100644 --- a/tests/ui/format.rs +++ b/tests/ui/format.rs @@ -2,6 +2,12 @@ #![warn(useless_format)] +struct Foo(pub String); + +macro_rules! foo { + ($($t:tt)*) => (Foo(format!($($t)*))) +} + fn main() { format!("foo"); @@ -31,4 +37,7 @@ fn main() { println!("foo {}", "foo"); println!("{}", 42); println!("foo {}", 42); + + // A format! inside a macro should not trigger a warning + foo!("should not warn"); } diff --git a/tests/ui/format.stderr b/tests/ui/format.stderr index f08f0696e23..8c36d9a830c 100644 --- a/tests/ui/format.stderr +++ b/tests/ui/format.stderr @@ -1,10 +1,10 @@ error: useless use of `format!` - --> $DIR/format.rs:6:5 - | -6 | format!("foo"); - | ^^^^^^^^^^^^^^^ help: consider using .to_string(): `"foo".to_string()` - | - = note: `-D useless-format` implied by `-D warnings` + --> $DIR/format.rs:12:5 + | +12 | format!("foo"); + | ^^^^^^^^^^^^^^^ help: consider using .to_string(): `"foo".to_string()` + | + = note: `-D useless-format` implied by `-D warnings` error: aborting due to previous error