]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Auto merge of #4109 - Manishearth:backport-merge, r=phansch
[rust.git] / clippy_lints / src / format.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     in_macro_or_desugar, is_expn_of, last_path_segment, match_def_path, match_type, resolve_node, snippet,
4     span_lint_and_then, walk_ptrs_ty,
5 };
6 use if_chain::if_chain;
7 use rustc::hir::*;
8 use rustc::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
9 use rustc::ty;
10 use rustc::{declare_lint_pass, declare_tool_lint};
11 use rustc_errors::Applicability;
12 use syntax::ast::LitKind;
13 use syntax::source_map::Span;
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks for the use of `format!("string literal with no
17     /// argument")` and `format!("{}", foo)` where `foo` is a string.
18     ///
19     /// **Why is this bad?** There is no point of doing that. `format!("foo")` can
20     /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
21     /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
22     /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
23     /// if `foo: &str`.
24     ///
25     /// **Known problems:** None.
26     ///
27     /// **Examples:**
28     /// ```rust
29     /// format!("foo")
30     /// format!("{}", foo)
31     /// ```
32     pub USELESS_FORMAT,
33     complexity,
34     "useless use of `format!`"
35 }
36
37 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
38
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessFormat {
40     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
41         if let Some(span) = is_expn_of(expr.span, "format") {
42             if in_macro_or_desugar(span) {
43                 return;
44             }
45             match expr.node {
46                 // `format!("{}", foo)` expansion
47                 ExprKind::Call(ref fun, ref args) => {
48                     if_chain! {
49                         if let ExprKind::Path(ref qpath) = fun.node;
50                         if let Some(fun_def_id) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
51                         let new_v1 = match_def_path(cx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1);
52                         let new_v1_fmt = match_def_path(cx,
53                             fun_def_id,
54                             &paths::FMT_ARGUMENTS_NEWV1FORMATTED
55                         );
56                         if new_v1 || new_v1_fmt;
57                         if check_single_piece(&args[0]);
58                         if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
59                         if new_v1 || check_unformatted(&args[2]);
60                         if let ExprKind::AddrOf(_, ref format_arg) = format_arg.node;
61                         then {
62                             let (message, sugg) = if_chain! {
63                                 if let ExprKind::MethodCall(ref path, _, _) = format_arg.node;
64                                 if path.ident.as_interned_str() == "to_string";
65                                 then {
66                                     ("`to_string()` is enough",
67                                     snippet(cx, format_arg.span, "<arg>").to_string())
68                                 } else {
69                                     ("consider using .to_string()",
70                                     format!("{}.to_string()", snippet(cx, format_arg.span, "<arg>")))
71                                 }
72                             };
73
74                             span_useless_format(cx, span, message, sugg);
75                         }
76                     }
77                 },
78                 // `format!("foo")` expansion contains `match () { () => [], }`
79                 ExprKind::Match(ref matchee, _, _) => {
80                     if let ExprKind::Tup(ref tup) = matchee.node {
81                         if tup.is_empty() {
82                             let actual_snippet = snippet(cx, expr.span, "<expr>").to_string();
83                             let actual_snippet = actual_snippet.replace("{{}}", "{}");
84                             let sugg = format!("{}.to_string()", actual_snippet);
85                             span_useless_format(cx, span, "consider using .to_string()", sugg);
86                         }
87                     }
88                 },
89                 _ => (),
90             }
91         }
92     }
93 }
94
95 fn span_useless_format<'a, 'tcx: 'a, T: LintContext<'tcx>>(cx: &'a T, span: Span, help: &str, mut sugg: String) {
96     let to_replace = span.source_callsite();
97
98     // The callsite span contains the statement semicolon for some reason.
99     let snippet = snippet(cx, to_replace, "..");
100     if snippet.ends_with(';') {
101         sugg.push(';');
102     }
103
104     span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
105         db.span_suggestion(
106             to_replace,
107             help,
108             sugg,
109             Applicability::MachineApplicable, // snippet
110         );
111     });
112 }
113
114 /// Checks if the expressions matches `&[""]`
115 fn check_single_piece(expr: &Expr) -> bool {
116     if_chain! {
117         if let ExprKind::AddrOf(_, ref expr) = expr.node; // &[""]
118         if let ExprKind::Array(ref exprs) = expr.node; // [""]
119         if exprs.len() == 1;
120         if let ExprKind::Lit(ref lit) = exprs[0].node;
121         if let LitKind::Str(ref lit, _) = lit.node;
122         then {
123             return lit.as_str().is_empty();
124         }
125     }
126
127     false
128 }
129
130 /// Checks if the expressions matches
131 /// ```rust,ignore
132 /// &match (&"arg",) {
133 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
134 /// ::std::fmt::Display::fmt)],
135 /// }
136 /// ```
137 /// and that the type of `__arg0` is `&str` or `String`,
138 /// then returns the span of first element of the matched tuple.
139 fn get_single_string_arg<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<&'a Expr> {
140     if_chain! {
141         if let ExprKind::AddrOf(_, ref expr) = expr.node;
142         if let ExprKind::Match(ref match_expr, ref arms, _) = expr.node;
143         if arms.len() == 1;
144         if arms[0].pats.len() == 1;
145         if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
146         if pat.len() == 1;
147         if let ExprKind::Array(ref exprs) = arms[0].body.node;
148         if exprs.len() == 1;
149         if let ExprKind::Call(_, ref args) = exprs[0].node;
150         if args.len() == 2;
151         if let ExprKind::Path(ref qpath) = args[1].node;
152         if let Some(fun_def_id) = resolve_node(cx, qpath, args[1].hir_id).opt_def_id();
153         if match_def_path(cx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
154         then {
155             let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
156             if ty.sty == ty::Str || match_type(cx, ty, &paths::STRING) {
157                 if let ExprKind::Tup(ref values) = match_expr.node {
158                     return Some(&values[0]);
159                 }
160             }
161         }
162     }
163
164     None
165 }
166
167 /// Checks if the expression matches
168 /// ```rust,ignore
169 /// &[_ {
170 ///    format: _ {
171 ///         width: _::Implied,
172 ///         ...
173 ///    },
174 ///    ...,
175 /// }]
176 /// ```
177 fn check_unformatted(expr: &Expr) -> bool {
178     if_chain! {
179         if let ExprKind::AddrOf(_, ref expr) = expr.node;
180         if let ExprKind::Array(ref exprs) = expr.node;
181         if exprs.len() == 1;
182         if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
183         if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
184         if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
185         if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
186         if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
187         if last_path_segment(width_qpath).ident.name == sym!(Implied);
188         if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
189         if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
190         if last_path_segment(precision_path).ident.name == sym!(Implied);
191         then {
192             return true;
193         }
194     }
195
196     false
197 }