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