]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Fix useless_format false positive
[rust.git] / clippy_lints / src / format.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::paths;
3 use clippy_utils::source::{snippet, snippet_opt};
4 use clippy_utils::sugg::Sugg;
5 use clippy_utils::ty::is_type_diagnostic_item;
6 use clippy_utils::{is_expn_of, last_path_segment, match_def_path, match_function_call};
7 use if_chain::if_chain;
8 use rustc_ast::ast::LitKind;
9 use rustc_errors::Applicability;
10 use rustc_hir::{Arm, BorrowKind, Expr, ExprKind, MatchSource, PatKind};
11 use rustc_lint::{LateContext, LateLintPass, LintContext};
12 use rustc_session::{declare_lint_pass, declare_tool_lint};
13 use rustc_span::source_map::Span;
14 use rustc_span::sym;
15 use rustc_span::symbol::kw;
16
17 declare_clippy_lint! {
18     /// **What it does:** Checks for the use of `format!("string literal with no
19     /// argument")` and `format!("{}", foo)` where `foo` is a string.
20     ///
21     /// **Why is this bad?** There is no point of doing that. `format!("foo")` can
22     /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
23     /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
24     /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
25     /// if `foo: &str`.
26     ///
27     /// **Known problems:** None.
28     ///
29     /// **Examples:**
30     /// ```rust
31     ///
32     /// // Bad
33     /// let foo = "foo";
34     /// format!("{}", foo);
35     ///
36     /// // Good
37     /// foo.to_owned();
38     /// ```
39     pub USELESS_FORMAT,
40     complexity,
41     "useless use of `format!`"
42 }
43
44 declare_lint_pass!(UselessFormat => [USELESS_FORMAT]);
45
46 impl<'tcx> LateLintPass<'tcx> for UselessFormat {
47     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
48         let span = match is_expn_of(expr.span, "format") {
49             Some(s) if !s.from_expansion() => s,
50             _ => return,
51         };
52
53         // Operate on the only argument of `alloc::fmt::format`.
54         if let Some(sugg) = on_new_v1(cx, expr) {
55             span_useless_format(cx, span, "consider using `.to_string()`", sugg);
56         } else if let Some(sugg) = on_new_v1_fmt(cx, expr) {
57             span_useless_format(cx, span, "consider using `.to_string()`", sugg);
58         }
59     }
60 }
61
62 fn span_useless_format<T: LintContext>(cx: &T, span: Span, help: &str, mut sugg: String) {
63     let to_replace = span.source_callsite();
64
65     // The callsite span contains the statement semicolon for some reason.
66     let snippet = snippet(cx, to_replace, "..");
67     if snippet.ends_with(';') {
68         sugg.push(';');
69     }
70
71     span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |diag| {
72         diag.span_suggestion(
73             to_replace,
74             help,
75             sugg,
76             Applicability::MachineApplicable, // snippet
77         );
78     });
79 }
80
81 fn on_argumentv1_new<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) -> Option<String> {
82     if_chain! {
83         if let ExprKind::AddrOf(BorrowKind::Ref, _, format_args) = expr.kind;
84         if let ExprKind::Array(elems) = arms[0].body.kind;
85         if elems.len() == 1;
86         if let Some(args) = match_function_call(cx, &elems[0], &paths::FMT_ARGUMENTV1_NEW);
87         // matches `core::fmt::Display::fmt`
88         if args.len() == 2;
89         if let ExprKind::Path(ref qpath) = args[1].kind;
90         if let Some(did) = cx.qpath_res(qpath, args[1].hir_id).opt_def_id();
91         if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD);
92         // check `(arg0,)` in match block
93         if let PatKind::Tuple(pats, None) = arms[0].pat.kind;
94         if pats.len() == 1;
95         then {
96             let ty = cx.typeck_results().pat_ty(pats[0]).peel_refs();
97             if *ty.kind() != rustc_middle::ty::Str && !is_type_diagnostic_item(cx, ty, sym::string_type) {
98                 return None;
99             }
100             if let ExprKind::Lit(ref lit) = format_args.kind {
101                 if let LitKind::Str(ref s, _) = lit.node {
102                     return Some(format!("{:?}.to_string()", s.as_str()));
103                 }
104             } else {
105                 let sugg = Sugg::hir(cx, format_args, "<arg>");
106                 if let ExprKind::MethodCall(path, _, _, _) = format_args.kind {
107                     if path.ident.name == sym!(to_string) {
108                         return Some(format!("{}", sugg));
109                     }
110                 } else if let ExprKind::Binary(..) = format_args.kind {
111                     return Some(format!("{}", sugg));
112                 }
113                 return Some(format!("{}.to_string()", sugg.maybe_par()));
114             }
115         }
116     }
117     None
118 }
119
120 fn on_new_v1<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
121     if_chain! {
122         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1);
123         if args.len() == 2;
124         // Argument 1 in `new_v1()`
125         if let ExprKind::AddrOf(BorrowKind::Ref, _, arr) = args[0].kind;
126         if let ExprKind::Array(pieces) = arr.kind;
127         if pieces.len() == 1;
128         if let ExprKind::Lit(ref lit) = pieces[0].kind;
129         if let LitKind::Str(ref s, _) = lit.node;
130         // Argument 2 in `new_v1()`
131         if let ExprKind::AddrOf(BorrowKind::Ref, _, arg1) = args[1].kind;
132         if let ExprKind::Match(matchee, arms, MatchSource::Normal) = arg1.kind;
133         if arms.len() == 1;
134         if let ExprKind::Tup(tup) = matchee.kind;
135         then {
136             // `format!("foo")` expansion contains `match () { () => [], }`
137             if tup.is_empty() {
138                 if let Some(s_src) = snippet_opt(cx, lit.span) {
139                     // Simulate macro expansion, converting {{ and }} to { and }.
140                     let s_expand = s_src.replace("{{", "{").replace("}}", "}");
141                     return Some(format!("{}.to_string()", s_expand));
142                 }
143             } else if s.as_str().is_empty() {
144                 return on_argumentv1_new(cx, &tup[0], arms);
145             }
146         }
147     }
148     None
149 }
150
151 fn on_new_v1_fmt<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<String> {
152     if_chain! {
153         if let Some(args) = match_function_call(cx, expr, &paths::FMT_ARGUMENTS_NEW_V1_FORMATTED);
154         if args.len() == 3;
155         if check_unformatted(&args[2]);
156         // Argument 1 in `new_v1_formatted()`
157         if let ExprKind::AddrOf(BorrowKind::Ref, _, arr) = args[0].kind;
158         if let ExprKind::Array(pieces) = arr.kind;
159         if pieces.len() == 1;
160         if let ExprKind::Lit(ref lit) = pieces[0].kind;
161         if let LitKind::Str(symbol, _) = lit.node;
162         if symbol == kw::Empty;
163         // Argument 2 in `new_v1_formatted()`
164         if let ExprKind::AddrOf(BorrowKind::Ref, _, arg1) = args[1].kind;
165         if let ExprKind::Match(matchee, arms, MatchSource::Normal) = arg1.kind;
166         if arms.len() == 1;
167         if let ExprKind::Tup(tup) = matchee.kind;
168         then {
169             return on_argumentv1_new(cx, &tup[0], arms);
170         }
171     }
172     None
173 }
174
175 /// Checks if the expression matches
176 /// ```rust,ignore
177 /// &[_ {
178 ///    format: _ {
179 ///         width: _::Implied,
180 ///         precision: _::Implied,
181 ///         ...
182 ///    },
183 ///    ...,
184 /// }]
185 /// ```
186 fn check_unformatted(expr: &Expr<'_>) -> bool {
187     if_chain! {
188         if let ExprKind::AddrOf(BorrowKind::Ref, _, expr) = expr.kind;
189         if let ExprKind::Array(exprs) = expr.kind;
190         if exprs.len() == 1;
191         // struct `core::fmt::rt::v1::Argument`
192         if let ExprKind::Struct(_, fields, _) = exprs[0].kind;
193         if let Some(format_field) = fields.iter().find(|f| f.ident.name == sym::format);
194         // struct `core::fmt::rt::v1::FormatSpec`
195         if let ExprKind::Struct(_, fields, _) = format_field.expr.kind;
196         if let Some(precision_field) = fields.iter().find(|f| f.ident.name == sym::precision);
197         if let ExprKind::Path(ref precision_path) = precision_field.expr.kind;
198         if last_path_segment(precision_path).ident.name == sym::Implied;
199         if let Some(width_field) = fields.iter().find(|f| f.ident.name == sym::width);
200         if let ExprKind::Path(ref width_qpath) = width_field.expr.kind;
201         if last_path_segment(width_qpath).ident.name == sym::Implied;
202         then {
203             return true;
204         }
205     }
206
207     false
208 }