]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/format.rs
Rollup merge of #73771 - alexcrichton:ignore-unstable, r=estebank,GuillaumeGomez
[rust.git] / src / tools / clippy / 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<'tcx> LateLintPass<'tcx> for UselessFormat {
44     fn check_expr(&mut self, cx: &LateContext<'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<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) -> Option<String> {
79     if_chain! {
80         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref format_args) = expr.kind;
81         if let ExprKind::Array(ref elems) = arms[0].body.kind;
82         if elems.len() == 1;
83         if let Some(args) = match_function_call(cx, &elems[0], &paths::FMT_ARGUMENTV1_NEW);
84         // matches `core::fmt::Display::fmt`
85         if args.len() == 2;
86         if let ExprKind::Path(ref qpath) = args[1].kind;
87         if let Some(did) = cx.qpath_res(qpath, args[1].hir_id).opt_def_id();
88         if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
89         // check `(arg0,)` in match block
90         if let PatKind::Tuple(ref pats, None) = arms[0].pat.kind;
91         if pats.len() == 1;
92         then {
93             let ty = walk_ptrs_ty(cx.tables().pat_ty(&pats[0]));
94             if ty.kind != rustc_middle::ty::Str && !is_type_diagnostic_item(cx, ty, sym!(string_type)) {
95                 return None;
96             }
97             if let ExprKind::Lit(ref lit) = format_args.kind {
98                 if let LitKind::Str(ref s, _) = lit.node {
99                     return Some(format!("{:?}.to_string()", s.as_str()));
100                 }
101             } else {
102                 let snip = snippet(cx, format_args.span, "<arg>");
103                 if let ExprKind::MethodCall(ref path, _, _, _) = format_args.kind {
104                     if path.ident.name == sym!(to_string) {
105                         return Some(format!("{}", snip));
106                     }
107                 } else if let ExprKind::Binary(..) = format_args.kind {
108                     return Some(format!("{}", snip));
109                 }
110                 return Some(format!("{}.to_string()", snip));
111             }
112         }
113     }
114     None
115 }
116
117 fn on_new_v1<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
118     if_chain! {
119         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1);
120         if args.len() == 2;
121         // Argument 1 in `new_v1()`
122         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arr) = args[0].kind;
123         if let ExprKind::Array(ref pieces) = arr.kind;
124         if pieces.len() == 1;
125         if let ExprKind::Lit(ref lit) = pieces[0].kind;
126         if let LitKind::Str(ref s, _) = lit.node;
127         // Argument 2 in `new_v1()`
128         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg1) = args[1].kind;
129         if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.kind;
130         if arms.len() == 1;
131         if let ExprKind::Tup(ref tup) = matchee.kind;
132         then {
133             // `format!("foo")` expansion contains `match () { () => [], }`
134             if tup.is_empty() {
135                 return Some(format!("{:?}.to_string()", s.as_str()));
136             } else if s.as_str().is_empty() {
137                 return on_argumentv1_new(cx, &tup[0], arms);
138             }
139         }
140     }
141     None
142 }
143
144 fn on_new_v1_fmt<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
145     if_chain! {
146         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
147         if args.len() == 3;
148         if check_unformatted(&args[2]);
149         // Argument 1 in `new_v1_formatted()`
150         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arr) = args[0].kind;
151         if let ExprKind::Array(ref pieces) = arr.kind;
152         if pieces.len() == 1;
153         if let ExprKind::Lit(ref lit) = pieces[0].kind;
154         if let LitKind::Str(..) = lit.node;
155         // Argument 2 in `new_v1_formatted()`
156         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref arg1) = args[1].kind;
157         if let ExprKind::Match(ref matchee, ref arms, MatchSource::Normal) = arg1.kind;
158         if arms.len() == 1;
159         if let ExprKind::Tup(ref tup) = matchee.kind;
160         then {
161             return on_argumentv1_new(cx, &tup[0], arms);
162         }
163     }
164     None
165 }
166
167 /// Checks if the expression matches
168 /// ```rust,ignore
169 /// &[_ {
170 ///    format: _ {
171 ///         width: _::Implied,
172 ///         precision: _::Implied,
173 ///         ...
174 ///    },
175 ///    ...,
176 /// }]
177 /// ```
178 fn check_unformatted(expr: &Expr<'_>) -> bool {
179     if_chain! {
180         if let ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) = expr.kind;
181         if let ExprKind::Array(ref exprs) = expr.kind;
182         if exprs.len() == 1;
183         // struct `core::fmt::rt::v1::Argument`
184         if let ExprKind::Struct(_, ref fields, _) = exprs[0].kind;
185         if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym!(format));
186         // struct `core::fmt::rt::v1::FormatSpec`
187         if let ExprKind::Struct(_, ref fields, _) = format_field.expr.kind;
188         if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym!(precision));
189         if let ExprKind::Path(ref precision_path) = precision_field.expr.kind;
190         if last_path_segment(precision_path).ident.name == sym!(Implied);
191         if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym!(width));
192         if let ExprKind::Path(ref width_qpath) = width_field.expr.kind;
193         if last_path_segment(width_qpath).ident.name == sym!(Implied);
194         then {
195             return true;
196         }
197     }
198
199     false
200 }