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