]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Merge pull request #1363 from hdhoang/patch-2
[rust.git] / clippy_lints / src / format.rs
1 use rustc::hir::*;
2 use rustc::hir::map::Node::NodeItem;
3 use rustc::lint::*;
4 use rustc::ty::TypeVariants;
5 use syntax::ast::LitKind;
6 use syntax::symbol::InternedString;
7 use utils::paths;
8 use utils::{is_expn_of, match_def_path, match_type, resolve_node, span_lint, walk_ptrs_ty};
9
10 /// **What it does:** Checks for the use of `format!("string literal with no
11 /// argument")` and `format!("{}", foo)` where `foo` is a string.
12 ///
13 /// **Why is this bad?** There is no point of doing that. `format!("too")` can
14 /// be replaced by `"foo".to_owned()` if you really need a `String`. The even
15 /// worse `&format!("foo")` is often encountered in the wild. `format!("{}",
16 /// foo)` can be replaced by `foo.clone()` if `foo: String` or `foo.to_owned()`
17 /// if `foo: &str`.
18 ///
19 /// **Known problems:** None.
20 ///
21 /// **Examples:**
22 /// ```rust
23 /// format!("foo")
24 /// format!("{}", foo)
25 /// ```
26 declare_lint! {
27     pub USELESS_FORMAT,
28     Warn,
29     "useless use of `format!`"
30 }
31
32 #[derive(Copy, Clone, Debug)]
33 pub struct Pass;
34
35 impl LintPass for Pass {
36     fn get_lints(&self) -> LintArray {
37         lint_array![USELESS_FORMAT]
38     }
39 }
40
41 impl LateLintPass for Pass {
42     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
43         if let Some(span) = is_expn_of(cx, expr.span, "format") {
44             match expr.node {
45                 // `format!("{}", foo)` expansion
46                 ExprCall(ref fun, ref args) => {
47                     if_let_chain!{[
48                         let ExprPath(..) = fun.node,
49                         args.len() == 2,
50                         let Some(fun) = resolve_node(cx, fun.id),
51                         match_def_path(cx, fun.def_id(), &paths::FMT_ARGUMENTS_NEWV1),
52                         // ensure the format string is `"{..}"` with only one argument and no text
53                         check_static_str(cx, &args[0]),
54                         // ensure the format argument is `{}` ie. Display with no fancy option
55                         check_arg_is_display(cx, &args[1])
56                     ], {
57                         span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
58                     }}
59                 }
60                 // `format!("foo")` expansion contains `match () { () => [], }`
61                 ExprMatch(ref matchee, _, _) => {
62                     if let ExprTup(ref tup) = matchee.node {
63                         if tup.is_empty() {
64                             span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
65                         }
66                     }
67                 }
68                 _ => (),
69             }
70         }
71     }
72 }
73
74 /// Returns the slice of format string parts in an `Arguments::new_v1` call.
75 /// Public because it's shared with a lint in print.rs.
76 pub fn get_argument_fmtstr_parts<'a, 'b>(cx: &LateContext<'a, 'b>, expr: &'a Expr)
77                                          -> Option<Vec<InternedString>> {
78     if_let_chain! {[
79         let ExprBlock(ref block) = expr.node,
80         block.stmts.len() == 1,
81         let StmtDecl(ref decl, _) = block.stmts[0].node,
82         let DeclItem(ref decl) = decl.node,
83         let Some(NodeItem(decl)) = cx.tcx.map.find(decl.id),
84         &*decl.name.as_str() == "__STATIC_FMTSTR",
85         let ItemStatic(_, _, ref expr) = decl.node,
86         let ExprAddrOf(_, ref expr) = expr.node, // &["…", "…", …]
87         let ExprArray(ref exprs) = expr.node,
88     ], {
89         let mut result = Vec::new();
90         for expr in exprs {
91             if let ExprLit(ref lit) = expr.node {
92                 if let LitKind::Str(ref lit, _) = lit.node {
93                     result.push(lit.as_str());
94                 }
95             }
96         }
97         return Some(result);
98     }}
99     None
100 }
101
102 /// Checks if the expressions matches
103 /// ```rust
104 /// { static __STATIC_FMTSTR: … = &["…", "…", …]; __STATIC_FMTSTR }
105 /// ```
106 fn check_static_str(cx: &LateContext, expr: &Expr) -> bool {
107     if let Some(expr) = get_argument_fmtstr_parts(cx, expr) {
108         expr.len() == 1 && expr[0].is_empty()
109     } else {
110         false
111     }
112 }
113
114 /// Checks if the expressions matches
115 /// ```rust
116 /// &match (&42,) {
117 ///     (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0, ::std::fmt::Display::fmt)],
118 /// })
119 /// ```
120 fn check_arg_is_display(cx: &LateContext, expr: &Expr) -> bool {
121     if_let_chain! {[
122         let ExprAddrOf(_, ref expr) = expr.node,
123         let ExprMatch(_, ref arms, _) = expr.node,
124         arms.len() == 1,
125         arms[0].pats.len() == 1,
126         let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node,
127         pat.len() == 1,
128         let ExprArray(ref exprs) = arms[0].body.node,
129         exprs.len() == 1,
130         let ExprCall(_, ref args) = exprs[0].node,
131         args.len() == 2,
132         let ExprPath(None, _) = args[1].node,
133         let Some(fun) = resolve_node(cx, args[1].id),
134         match_def_path(cx, fun.def_id(), &paths::DISPLAY_FMT_METHOD),
135     ], {
136         let ty = walk_ptrs_ty(cx.tcx.tables().pat_ty(&pat[0]));
137
138         return ty.sty == TypeVariants::TyStr || match_type(cx, ty, &paths::STRING);
139     }}
140
141     false
142 }