]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Auto merge of #73756 - Manishearth:rollup-aehswb2, r=Manishearth
[rust.git] / clippy_lints / src / format.rs
1 use crate::utils::paths;
2 use crate::utils::{
3     is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet,
4     span_lint_and_then, walk_ptrs_ty,
5 };
6 use if_chain::if_chain;
7 use rustc_ast::ast::LitKind;
8 use rustc_errors::Applicability;
9 use rustc_hir::{Arm, BorrowKind, Expr, ExprKind, MatchSource, PatKind};
10 use rustc_lint::{LateContext, LateLintPass, LintContext};
11 use rustc_session::{declare_lint_pass, declare_tool_lint};
12 use rustc_span::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     ///
29     /// // Bad
30     /// # let foo = "foo";
31     /// format!("{}", foo);
32     ///
33     /// // Good
34     /// format!("foo");
35     /// ```
36     pub USELESS_FORMAT,
37     complexity,
38     "useless use of `format!`"
39 }
40
41 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
42
43 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessFormat {
44     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
45         let span = match is_expn_of(expr.span, "format") {
46             Some(s) if !s.from_expansion() => s,
47             _ => return,
48         };
49
50         // Operate on the only argument of `alloc::fmt::format`.
51         if let Some(sugg) = on_new_v1(cx, expr) {
52             span_useless_format(cx, span, "consider using `.to_string()`", sugg);
53         } else if let Some(sugg) = on_new_v1_fmt(cx, expr) {
54             span_useless_format(cx, span, "consider using `.to_string()`", sugg);
55         }
56     }
57 }
58
59 fn span_useless_format<T: LintContext>(cx: &T, span: Span, help: &str, mut sugg: String) {
60     let to_replace = span.source_callsite();
61
62     // The callsite span contains the statement semicolon for some reason.
63     let snippet = snippet(cx, to_replace, "..");
64     if snippet.ends_with(';') {
65         sugg.push(';');
66     }
67
68     span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |diag| {
69         diag.span_suggestion(
70             to_replace,
71             help,
72             sugg,
73             Applicability::MachineApplicable, // snippet
74         );
75     });
76 }
77
78 fn on_argumentv1_new<'a, 'tcx>(
79     cx: &LateContext<'a, 'tcx>,
80     expr: &'tcx Expr<'_>,
81     arms: &'tcx [Arm<'_>],
82 ) -> Option<String> {
83     if_chain! {
84         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref format_args) = expr.kind;
85         if let ExprKind::Array(ref elems) = arms[0].body.kind;
86         if elems.len() == 1;
87         if let Some(args) = match_function_call(cx, &elems[0], &paths::FMT_ARGUMENTV1_NEW);
88         // matches `core::fmt::Display::fmt`
89         if args.len() == 2;
90         if let ExprKind::Path(ref qpath) = args[1].kind;
91         if let Some(did) = cx.tables().qpath_res(qpath, args[1].hir_id).opt_def_id();
92         if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
93         // check `(arg0,)` in match block
94         if let PatKind::Tuple(ref pats, None) = arms[0].pat.kind;
95         if pats.len() == 1;
96         then {
97             let ty = walk_ptrs_ty(cx.tables().pat_ty(&pats[0]));
98             if ty.kind != rustc_middle::ty::Str && !is_type_diagnostic_item(cx, ty, sym!(string_type)) {
99                 return None;
100             }
101             if let ExprKind::Lit(ref lit) = format_args.kind {
102                 if let LitKind::Str(ref s, _) = lit.node {
103                     return Some(format!("{:?}.to_string()", s.as_str()));
104                 }
105             } else {
106                 let snip = snippet(cx, format_args.span, "<arg>");
107                 if let ExprKind::MethodCall(ref path, _, _, _) = format_args.kind {
108                     if path.ident.name == sym!(to_string) {
109                         return Some(format!("{}", snip));
110                     }
111                 } else if let ExprKind::Binary(..) = format_args.kind {
112                     return Some(format!("{}", snip));
113                 }
114                 return Some(format!("{}.to_string()", snip));
115             }
116         }
117     }
118     None
119 }
120
121 fn on_new_v1<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
122     if_chain! {
123         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1);
124         if args.len() == 2;
125         // Argument 1 in `new_v1()`
126         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arr) = args[0].kind;
127         if let ExprKind::Array(ref pieces) = arr.kind;
128         if pieces.len() == 1;
129         if let ExprKind::Lit(ref lit) = pieces[0].kind;
130         if let LitKind::Str(ref s, _) = lit.node;
131         // Argument 2 in `new_v1()`
132         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg1) = args[1].kind;
133         if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.kind;
134         if arms.len() == 1;
135         if let ExprKind::Tup(ref tup) = matchee.kind;
136         then {
137             // `format!("foo")` expansion contains `match () { () => [], }`
138             if tup.is_empty() {
139                 return Some(format!("{:?}.to_string()", s.as_str()));
140             } else if s.as_str().is_empty() {
141                 return on_argumentv1_new(cx, &tup[0], arms);
142             }
143         }
144     }
145     None
146 }
147
148 fn on_new_v1_fmt<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
149     if_chain! {
150         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
151         if args.len() == 3;
152         if check_unformatted(&args[2]);
153         // Argument 1 in `new_v1_formatted()`
154         if let ExprKind::AddrOf(BorrowKind::Ref, _, 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(BorrowKind::Ref, _, 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(BorrowKind::Ref, _, 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 }