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