]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
fix format does not parse escaped braces error
[rust.git] / clippy_lints / src / format.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     in_macro, is_expn_of, last_path_segment, match_def_path, match_type, resolve_node, snippet, span_lint_and_then,
4     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_tool_lint, lint_array};
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 #[derive(Copy, Clone, Debug)]
38 pub struct Pass;
39
40 impl LintPass for Pass {
41     fn get_lints(&self) -> LintArray {
42         lint_array![USELESS_FORMAT]
43     }
44
45     fn name(&self) -> &'static str {
46         "UselessFormat"
47     }
48 }
49
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
51     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
52         if let Some(span) = is_expn_of(expr.span, "format") {
53             if in_macro(span) {
54                 return;
55             }
56             match expr.node {
57                 // `format!("{}", foo)` expansion
58                 ExprKind::Call(ref fun, ref args) => {
59                     if_chain! {
60                         if let ExprKind::Path(ref qpath) = fun.node;
61                         if let Some(fun_def_id) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
62                         let new_v1 = match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1);
63                         let new_v1_fmt = match_def_path(
64                             cx.tcx,
65                             fun_def_id,
66                             &paths::FMT_ARGUMENTS_NEWV1FORMATTED
67                         );
68                         if new_v1 || new_v1_fmt;
69                         if check_single_piece(&args[0]);
70                         if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
71                         if new_v1 || check_unformatted(&args[2]);
72                         if let ExprKind::AddrOf(_, ref format_arg) = format_arg.node;
73                         then {
74                             let (message, sugg) = if_chain! {
75                                 if let ExprKind::MethodCall(ref path, _, _) = format_arg.node;
76                                 if path.ident.as_interned_str() == "to_string";
77                                 then {
78                                     ("`to_string()` is enough",
79                                     snippet(cx, format_arg.span, "<arg>").to_string())
80                                 } else {
81                                     ("consider using .to_string()",
82                                     format!("{}.to_string()", snippet(cx, format_arg.span, "<arg>")))
83                                 }
84                             };
85
86                             span_useless_format(cx, span, message, sugg);
87                         }
88                     }
89                 },
90                 // `format!("foo")` expansion contains `match () { () => [], }`
91                 ExprKind::Match(ref matchee, _, _) => {
92                     if let ExprKind::Tup(ref tup) = matchee.node {
93                         if tup.is_empty() {
94                             let actual_snippet = snippet(cx, expr.span, "<expr>").to_string();
95                             let actual_snippet = actual_snippet.replace("{{}}", "{}");
96                             let sugg = format!("{}.to_string()", actual_snippet);
97                             span_useless_format(cx, span, "consider using .to_string()", sugg);
98                         }
99                     }
100                 },
101                 _ => (),
102             }
103         }
104     }
105 }
106
107 fn span_useless_format<'a, 'tcx: 'a, T: LintContext<'tcx>>(cx: &'a T, span: Span, help: &str, mut sugg: String) {
108     let to_replace = span.source_callsite();
109
110     // The callsite span contains the statement semicolon for some reason.
111     let snippet = snippet(cx, to_replace, "..");
112     if snippet.ends_with(';') {
113         sugg.push(';');
114     }
115
116     span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
117         db.span_suggestion(
118             to_replace,
119             help,
120             sugg,
121             Applicability::MachineApplicable, // snippet
122         );
123     });
124 }
125
126 /// Checks if the expressions matches `&[""]`
127 fn check_single_piece(expr: &Expr) -> bool {
128     if_chain! {
129         if let ExprKind::AddrOf(_, ref expr) = expr.node; // &[""]
130         if let ExprKind::Array(ref exprs) = expr.node; // [""]
131         if exprs.len() == 1;
132         if let ExprKind::Lit(ref lit) = exprs[0].node;
133         if let LitKind::Str(ref lit, _) = lit.node;
134         then {
135             return lit.as_str().is_empty();
136         }
137     }
138
139     false
140 }
141
142 /// Checks if the expressions matches
143 /// ```rust,ignore
144 /// &match (&"arg",) {
145 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
146 /// ::std::fmt::Display::fmt)],
147 /// }
148 /// ```
149 /// and that the type of `__arg0` is `&str` or `String`,
150 /// then returns the span of first element of the matched tuple.
151 fn get_single_string_arg<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<&'a Expr> {
152     if_chain! {
153         if let ExprKind::AddrOf(_, ref expr) = expr.node;
154         if let ExprKind::Match(ref match_expr, ref arms, _) = expr.node;
155         if arms.len() == 1;
156         if arms[0].pats.len() == 1;
157         if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
158         if pat.len() == 1;
159         if let ExprKind::Array(ref exprs) = arms[0].body.node;
160         if exprs.len() == 1;
161         if let ExprKind::Call(_, ref args) = exprs[0].node;
162         if args.len() == 2;
163         if let ExprKind::Path(ref qpath) = args[1].node;
164         if let Some(fun_def_id) = resolve_node(cx, qpath, args[1].hir_id).opt_def_id();
165         if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
166         then {
167             let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
168             if ty.sty == ty::Str || match_type(cx, ty, &paths::STRING) {
169                 if let ExprKind::Tup(ref values) = match_expr.node {
170                     return Some(&values[0]);
171                 }
172             }
173         }
174     }
175
176     None
177 }
178
179 /// Checks if the expression matches
180 /// ```rust,ignore
181 /// &[_ {
182 ///    format: _ {
183 ///         width: _::Implied,
184 ///         ...
185 ///    },
186 ///    ...,
187 /// }]
188 /// ```
189 fn check_unformatted(expr: &Expr) -> bool {
190     if_chain! {
191         if let ExprKind::AddrOf(_, ref expr) = expr.node;
192         if let ExprKind::Array(ref exprs) = expr.node;
193         if exprs.len() == 1;
194         if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
195         if let Some(format_field) = fields.iter().find(|f| f.ident.name == "format");
196         if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
197         if let Some(width_field) = fields.iter().find(|f| f.ident.name == "width");
198         if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
199         if last_path_segment(width_qpath).ident.name == "Implied";
200         if let Some(precision_field) = fields.iter().find(|f| f.ident.name == "precision");
201         if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
202         if last_path_segment(precision_path).ident.name == "Implied";
203         then {
204             return true;
205         }
206     }
207
208     false
209 }