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