]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Merge branch 'macro-use' into HEAD
[rust.git] / clippy_lints / src / format.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
5 use rustc::ty;
6 use syntax::ast::LitKind;
7 use syntax_pos::Span;
8 use crate::utils::paths;
9 use crate::utils::{in_macro, is_expn_of, last_path_segment, match_def_path, match_type, opt_def_id, resolve_node, snippet, span_lint_and_then, walk_ptrs_ty};
10
11 /// **What it does:** Checks for the use of `format!("string literal with no
12 /// argument")` and `format!("{}", foo)` where `foo` is a string.
13 ///
14 /// **Why is this bad?** There is no point of doing that. `format!("too")` can
15 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
16 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
17 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
18 /// if `foo: &str`.
19 ///
20 /// **Known problems:** None.
21 ///
22 /// **Examples:**
23 /// ```rust
24 /// format!("foo")
25 /// format!("{}", foo)
26 /// ```
27 declare_clippy_lint! {
28     pub USELESS_FORMAT,
29     complexity,
30     "useless use of `format!`"
31 }
32
33 #[derive(Copy, Clone, Debug)]
34 pub struct Pass;
35
36 impl LintPass for Pass {
37     fn get_lints(&self) -> LintArray {
38         lint_array![USELESS_FORMAT]
39     }
40 }
41
42 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
43     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
44         if let Some(span) = is_expn_of(expr.span, "format") {
45             if in_macro(span) {
46                 return;
47             }
48             match expr.node {
49
50                 // `format!("{}", foo)` expansion
51                 ExprKind::Call(ref fun, ref args) => {
52                     if_chain! {
53                         if let ExprKind::Path(ref qpath) = fun.node;
54                         if args.len() == 3;
55                         if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
56                         if match_def_path(cx.tcx, fun_def_id, &paths::FMT_ARGUMENTS_NEWV1FORMATTED);
57                         if check_single_piece(&args[0]);
58                         if let Some(format_arg) = get_single_string_arg(cx, &args[1]);
59                         if check_unformatted(&args[2]);
60                         then {
61                             let sugg = format!("{}.to_string()", snippet(cx, format_arg, "<arg>").into_owned());
62                             span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
63                                 db.span_suggestion(expr.span, "consider using .to_string()", sugg);
64                             });
65                         }
66                     }
67                 },
68                 // `format!("foo")` expansion contains `match () { () => [], }`
69                 ExprKind::Match(ref matchee, _, _) => if let ExprKind::Tup(ref tup) = matchee.node {
70                     if tup.is_empty() {
71                         let sugg = format!("{}.to_string()", snippet(cx, expr.span, "<expr>").into_owned());
72                         span_lint_and_then(cx, USELESS_FORMAT, span, "useless use of `format!`", |db| {
73                             db.span_suggestion(span, "consider using .to_string()", sugg);
74                         });
75                     }
76                 },
77                 _ => (),
78             }
79         }
80     }
81 }
82
83 /// Checks if the expressions matches `&[""]`
84 fn check_single_piece(expr: &Expr) -> bool {
85     if_chain! {
86         if let ExprKind::AddrOf(_, ref expr) = expr.node; // &[""]
87         if let ExprKind::Array(ref exprs) = expr.node; // [""]
88         if exprs.len() == 1;
89         if let ExprKind::Lit(ref lit) = exprs[0].node;
90         if let LitKind::Str(ref lit, _) = lit.node;
91         then {
92             return lit.as_str().is_empty();
93         }
94     }
95
96     false
97 }
98
99 /// Checks if the expressions matches
100 /// ```rust,ignore
101 /// &match (&"arg",) {
102 /// (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0,
103 /// ::std::fmt::Display::fmt)],
104 /// }
105 /// ```
106 /// and that type of `__arg0` is `&str` or `String`
107 /// then returns the span of first element of the matched tuple
108 fn get_single_string_arg(cx: &LateContext, expr: &Expr) -> Option<Span> {
109     if_chain! {
110         if let ExprKind::AddrOf(_, ref expr) = expr.node;
111         if let ExprKind::Match(ref match_expr, ref arms, _) = expr.node;
112         if arms.len() == 1;
113         if arms[0].pats.len() == 1;
114         if let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node;
115         if pat.len() == 1;
116         if let ExprKind::Array(ref exprs) = arms[0].body.node;
117         if exprs.len() == 1;
118         if let ExprKind::Call(_, ref args) = exprs[0].node;
119         if args.len() == 2;
120         if let ExprKind::Path(ref qpath) = args[1].node;
121         if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, args[1].hir_id));
122         if match_def_path(cx.tcx, fun_def_id, &paths::DISPLAY_FMT_METHOD);
123         then {
124             let ty = walk_ptrs_ty(cx.tables.pat_ty(&pat[0]));
125             if ty.sty == ty::TyStr || match_type(cx, ty, &paths::STRING) {
126                 if let ExprKind::Tup(ref values) = match_expr.node {
127                     return Some(values[0].span);
128                 }
129             }
130         }
131     }
132
133     None
134 }
135
136 /// Checks if the expression matches
137 /// ```rust,ignore
138 /// &[_ {
139 ///    format: _ {
140 ///         width: _::Implied,
141 ///         ...
142 ///    },
143 ///    ...,
144 /// }]
145 /// ```
146 fn check_unformatted(expr: &Expr) -> bool {
147     if_chain! {
148         if let ExprKind::AddrOf(_, ref expr) = expr.node;
149         if let ExprKind::Array(ref exprs) = expr.node;
150         if exprs.len() == 1;
151         if let ExprKind::Struct(_, ref fields, _) = exprs[0].node;
152         if let Some(format_field) = fields.iter().find(|f| f.ident.name == "format");
153         if let ExprKind::Struct(_, ref fields, _) = format_field.expr.node;
154         if let Some(align_field) = fields.iter().find(|f| f.ident.name == "width");
155         if let ExprKind::Path(ref qpath) = align_field.expr.node;
156         if last_path_segment(qpath).ident.name == "Implied";
157         then {
158             return true;
159         }
160     }
161
162     false
163 }