]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Re-factor useless_format lint
[rust.git] / clippy_lints / src / format.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     in_macro_or_desugar, is_expn_of, last_path_segment, match_def_path, match_type, 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, LintContext, LintPass};
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     /// # let foo = "foo";
29     /// format!("foo");
30     /// format!("{}", foo);
31     /// ```
32     pub USELESS_FORMAT,
33     complexity,
34     "useless use of `format!`"
35 }
36
37 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
38
39 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessFormat {
40     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
41         let span = match is_expn_of(expr.span, "format") {
42             Some(s) if !in_macro_or_desugar(s) => s,
43             _ => return,
44         };
45
46         // Operate on the only argument of `alloc::fmt::format`.
47         if let Some(sugg) = on_new_v1(cx, expr) {
48             span_useless_format(cx, span, "consider using .to_string()", sugg);
49         } else if let Some(sugg) = on_new_v1_fmt(cx, expr) {
50             span_useless_format(cx, span, "consider using .to_string()", sugg);
51         }
52     }
53 }
54
55 fn span_useless_format<T: LintContext>(cx: &T, span: Span, help: &str, mut sugg: String) {
56     let to_replace = span.source_callsite();
57
58     // The callsite span contains the statement semicolon for some reason.
59     let snippet = snippet(cx, to_replace, "..");
60     if snippet.ends_with(';') {
61         sugg.push(';');
62     }
63
64     span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
65         db.span_suggestion(
66             to_replace,
67             help,
68             sugg,
69             Applicability::MachineApplicable, // snippet
70         );
71     });
72 }
73
74 fn on_argumentv1_new<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr, arms: &'a [Arm]) -> Option<String> {
75     if_chain! {
76         if let ExprKind::AddrOf(_, ref format_args) = expr.node;
77         if let ExprKind::Array(ref elems) = arms[0].body.node;
78         if elems.len() == 1;
79         if let ExprKind::Call(ref fun, ref args) = elems[0].node;
80         if let ExprKind::Path(ref qpath) = fun.node;
81         if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
82         if match_def_path(cx, did, &paths::FMT_ARGUMENTV1_NEW);
83         // matches `core::fmt::Display::fmt`
84         if args.len() == 2;
85         if let ExprKind::Path(ref qpath) = args[1].node;
86         if let Some(did) = resolve_node(cx, qpath, args[1].hir_id).opt_def_id();
87         if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
88         if arms[0].pats.len() == 1;
89         // check `(arg0,)` in match block
90         if let PatKind::Tuple(ref pats, None) = arms[0].pats[0].node;
91         if pats.len() == 1;
92         then {
93             if let ExprKind::Lit(ref lit) = format_args.node {
94                 if let LitKind::Str(ref s, _) = lit.node {
95                     let snip = s.as_str().replace("{{}}", "{}");
96                     let sugg = format!("\"{}\".to_string()", snip);
97                     return Some(sugg);
98                 }
99                 return None;
100             } else {
101                 let snip = snippet(cx, format_args.span, "<arg>");
102                 if let ExprKind::MethodCall(ref path, _, _) = format_args.node {
103                     if path.ident.name == sym!(to_string) {
104                         return Some(format!("{}", snip));
105                     }
106                 }
107                 return Some(format!("{}.to_string()", snip));
108             }
109         }
110     }
111     None
112 }
113
114 fn on_new_v1<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
115     if_chain! {
116         if let ExprKind::Call(ref fun, ref args) = expr.node;
117         if args.len() == 2;
118         if let ExprKind::Path(ref qpath) = fun.node;
119         if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
120         if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1);
121         // Argument 1 in `new_v1()`
122         if let ExprKind::AddrOf(_, ref arr) = args[0].node;
123         if let ExprKind::Array(ref pieces) = arr.node;
124         if pieces.len() == 1;
125         if let ExprKind::Lit(ref lit) = pieces[0].node;
126         if let LitKind::Str(ref s, _) = lit.node;
127         // Argument 2 in `new_v1()`
128         if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
129         if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
130         if arms.len() == 1;
131         if let ExprKind::Tup(ref tup) = matchee.node;
132         then {
133             // `format!("foo")` expansion contains `match () { () => [], }`
134             if tup.is_empty() {
135                 let snip = s.as_str().replace("{{}}", "{}");
136                 let sugg = format!("\"{}\".to_string()", snip);
137                 return Some(sugg);
138             } else {
139                 if s.as_str().is_empty() {
140                     return on_argumentv1_new(cx, &tup[0], arms);
141                 } else {
142                     return None;
143                 }
144             }
145         }
146     }
147     None
148 }
149
150 fn on_new_v1_fmt<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) -> Option<String> {
151     if_chain! {
152         if let ExprKind::Call(ref fun, ref args) = expr.node;
153         if args.len() == 3;
154         if let ExprKind::Path(ref qpath) = fun.node;
155         if let Some(did) = resolve_node(cx, qpath, fun.hir_id).opt_def_id();
156         if match_def_path(cx, did, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
157         if check_unformatted(&args[2]);
158         // Argument 1 in `new_v1_formatted()`
159         if let ExprKind::AddrOf(_, ref arr) = args[0].node;
160         if let ExprKind::Array(ref pieces) = arr.node;
161         if pieces.len() == 1;
162         if let ExprKind::Lit(ref lit) = pieces[0].node;
163         if let LitKind::Str(..) = lit.node;
164         // Argument 2 in `new_v1_formatted()`
165         if let ExprKind::AddrOf(_, ref arg1) = args[1].node;
166         if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.node;
167         if arms.len() == 1;
168         if let ExprKind::Tup(ref tup) = matchee.node;
169         then {
170             return on_argumentv1_new(cx, &tup[0], arms);
171         }
172     }
173     None
174 }
175
176 /// Checks if the expression matches
177 /// ```rust,ignore
178 /// &[_ {
179 ///    format: _ {
180 ///         width: _::Implied,
181 ///         precision: _::Implied,
182 ///         ...
183 ///    },
184 ///    ...,
185 /// }]
186 /// ```
187 fn check_unformatted(expr: &Expr) -> bool {
188     if_chain! {
189         if let ExprKind::AddrOf(_, ref expr) = expr.node;
190         if let ExprKind::Array(ref exprs) = expr.node;
191         if exprs.len() == 1;
192         // struct `core::fmt::rt::v1::Argument`
193         if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
194         if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
195         // struct `core::fmt::rt::v1::FormatSpec`
196         if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
197         if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
198         if let ExprKind::Path(ref precision_path) = precision_field.expr.node;
199         if last_path_segment(precision_path).ident.name == sym!(Implied);
200         if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
201         if let ExprKind::Path(ref width_qpath) = width_field.expr.node;
202         if last_path_segment(width_qpath).ident.name == sym!(Implied);
203         then {
204             return true;
205         }
206     }
207
208     false
209 }