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