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