Skip to content

Commit b2e4b88

Browse files
authored
Merge pull request #2662 from mikerite/issue_2546
Fix useless_format false negative
2 parents cefb7b0 + c7ad71c commit b2e4b88

File tree

3 files changed

+105
-19
lines changed

3 files changed

+105
-19
lines changed

clippy_lints/src/format.rs

Lines changed: 48 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ use rustc::hir::*;
22
use rustc::lint::*;
33
use rustc::ty;
44
use syntax::ast::LitKind;
5+
use syntax_pos::Span;
56
use utils::paths;
6-
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};
7+
use utils::{in_macro, is_expn_of, last_path_segment, match_def_path, match_type, opt_def_id, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty};
78

89
/// **What it does:** Checks for the use of `format!("string literal with no
910
/// argument")` and `format!("{}", foo)` where `foo` is a string.
@@ -43,20 +44,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
4344
return;
4445
}
4546
match expr.node {
47+
4648
// `format!("{}", foo)` expansion
4749
ExprCall(ref fun, ref args) => {
4850
if_chain! {
4951
if let ExprPath(ref qpath) = fun.node;
50-
if args.len() == 2;
52+
if args.len() == 3;
5153
if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
52-
if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1);
53-
// ensure the format string is `"{..}"` with only one argument and no text
54-
if check_static_str(&args[0]);
55-
// ensure the format argument is `{}` ie. Display with no fancy option
56-
// and that the argument is a string
57-
if check_arg_is_display(cx, &args[1]);
54+
if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1FORMATTED);
55+
if check_single_piece(&args[0]);
56+
if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
57+
if check_unformatted(&args[2]);
5858
then {
59-
let sugg = format!("{}.to_string()", snippet(cx, expr.span, "<expr>").into_owned());
59+
let sugg = format!("{}.to_string()", snippet(cx, format_arg, "<arg>").into_owned());
6060
span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
6161
db.span_suggestion(expr.span, "consider using .to_string()", sugg);
6262
});
@@ -79,7 +79,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
7979
}
8080

8181
/// Checks if the expressions matches `&[""]`
82-
fn check_static_str(expr: &Expr) -> bool {
82+
fn check_single_piece(expr: &Expr) -> bool {
8383
if_chain! {
8484
if let ExprAddrOf(_, ref expr) = expr.node; // &[""]
8585
if let ExprArray(ref exprs) = expr.node; // [""]
@@ -96,15 +96,17 @@ fn check_static_str(expr: &Expr) -> bool {
9696

9797
/// Checks if the expressions matches
9898
/// ```rust,ignore
99-
/// &match (&42,) {
99+
/// &match (&"arg",) {
100100
/// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
101101
/// ::std::fmt::Display::fmt)],
102102
/// }
103103
/// ```
104-
fn check_arg_is_display(cx: &LateContext, expr: &Expr) -> bool {
104+
/// and that type of `__arg0` is `&str` or `String`
105+
/// then returns the span of first element of the matched tuple
106+
fn get_single_string_arg(cx: &LateContext, expr: &Expr) -> Option<Span> {
105107
if_chain! {
106108
if let ExprAddrOf(_, ref expr) = expr.node;
107-
if let ExprMatch(_, ref arms, _) = expr.node;
109+
if let ExprMatch(ref match_expr, ref arms, _) = expr.node;
108110
if arms.len() == 1;
109111
if arms[0].pats.len() == 1;
110112
if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
@@ -118,8 +120,40 @@ fn check_arg_is_display(cx: &LateContext, expr: &Expr) -> bool {
118120
if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
119121
then {
120122
let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
123+
if ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING) {
124+
if let ExprTup(ref values) = match_expr.node {
125+
return Some(values[0].span);
126+
}
127+
}
128+
}
129+
}
130+
131+
None
132+
}
121133

122-
return ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING);
134+
/// Checks if the expression matches
135+
/// ```rust,ignore
136+
/// &[_ {
137+
/// format: _ {
138+
/// width: _::Implied,
139+
/// ...
140+
/// },
141+
/// ...,
142+
/// }]
143+
/// ```
144+
fn check_unformatted(expr: &Expr) -> bool {
145+
if_chain! {
146+
if let ExprAddrOf(_, ref expr) = expr.node;
147+
if let ExprArray(ref exprs) = expr.node;
148+
if exprs.len() == 1;
149+
if let ExprStruct(_, ref fields, _) = exprs[0].node;
150+
if let Some(format_field) = fields.iter().find(|f| f.name.node == "format");
151+
if let ExprStruct(_, ref fields, _) = format_field.expr.node;
152+
if let Some(align_field) = fields.iter().find(|f| f.name.node == "width");
153+
if let ExprPath(ref qpath) = align_field.expr.node;
154+
if last_path_segment(qpath).name == "Implied";
155+
then {
156+
return true;
123157
}
124158
}
125159

tests/ui/format.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,19 @@ fn main() {
1212
format!("foo");
1313

1414
format!("{}", "foo");
15-
format!("{:?}", "foo"); // we only want to warn about `{}`
16-
format!("{:+}", "foo"); // we only want to warn about `{}`
15+
format!("{:?}", "foo"); // don't warn about debug
16+
format!("{:8}", "foo");
17+
format!("{:+}", "foo"); // warn when the format makes no difference
18+
format!("{:<}", "foo"); // warn when the format makes no difference
1719
format!("foo {}", "bar");
1820
format!("{} bar", "foo");
1921

2022
let arg: String = "".to_owned();
2123
format!("{}", arg);
22-
format!("{:?}", arg); // we only want to warn about `{}`
23-
format!("{:+}", arg); // we only want to warn about `{}`
24+
format!("{:?}", arg); // don't warn about debug
25+
format!("{:8}", arg);
26+
format!("{:+}", arg); // warn when the format makes no difference
27+
format!("{:<}", arg); // warn when the format makes no difference
2428
format!("foo {}", arg);
2529
format!("{} bar", arg);
2630

tests/ui/format.stderr

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,53 @@ error: useless use of `format!`
66
|
77
= note: `-D useless-format` implied by `-D warnings`
88

9-
error: aborting due to previous error
9+
error: useless use of `format!`
10+
--> $DIR/format.rs:14:5
11+
|
12+
14 | format!("{}", "foo");
13+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `"foo".to_string()`
14+
|
15+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
16+
17+
error: useless use of `format!`
18+
--> $DIR/format.rs:17:5
19+
|
20+
17 | format!("{:+}", "foo"); // warn when the format makes no difference
21+
| ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `"foo".to_string()`
22+
|
23+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
24+
25+
error: useless use of `format!`
26+
--> $DIR/format.rs:18:5
27+
|
28+
18 | format!("{:<}", "foo"); // warn when the format makes no difference
29+
| ^^^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `"foo".to_string()`
30+
|
31+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
32+
33+
error: useless use of `format!`
34+
--> $DIR/format.rs:23:5
35+
|
36+
23 | format!("{}", arg);
37+
| ^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `arg.to_string()`
38+
|
39+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
40+
41+
error: useless use of `format!`
42+
--> $DIR/format.rs:26:5
43+
|
44+
26 | format!("{:+}", arg); // warn when the format makes no difference
45+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `arg.to_string()`
46+
|
47+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
48+
49+
error: useless use of `format!`
50+
--> $DIR/format.rs:27:5
51+
|
52+
27 | format!("{:<}", arg); // warn when the format makes no difference
53+
| ^^^^^^^^^^^^^^^^^^^^^ help: consider using .to_string(): `arg.to_string()`
54+
|
55+
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)
56+
57+
error: aborting due to 7 previous errors
1058

0 commit comments

Comments
 (0)