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