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