]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/format.rs
Merge pull request #958 from Manishearth/rustup
[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 utils::paths;
7 use utils::{is_expn_of, match_path, match_type, span_lint, walk_ptrs_ty};
8
9 /// **What it does:** This lints about use of `format!("string literal with no argument")` and
10 /// `format!("{}", foo)` where `foo` is a string.
11 ///
12 /// **Why is this bad?** There is no point of doing that. `format!("too")` can be replaced by `"foo".to_owned()` if you really need a `String`. The even worse `&format!("foo")` is often
13 /// encountered in the wild. `format!("{}", foo)` can be replaced by `foo.clone()` if `foo: String`
14 /// or `foo.to_owned()` is `foo: &str`.
15 ///
16 /// **Known problems:** None.
17 ///
18 /// **Examples:** `format!("foo")` and `format!("{}", foo)`
19 declare_lint! {
20     pub USELESS_FORMAT,
21     Warn,
22     "useless use of `format!`"
23 }
24
25 #[derive(Copy, Clone, Debug)]
26 pub struct FormatMacLint;
27
28 impl LintPass for FormatMacLint {
29     fn get_lints(&self) -> LintArray {
30         lint_array![USELESS_FORMAT]
31     }
32 }
33
34 impl LateLintPass for FormatMacLint {
35     fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
36         if let Some(span) = is_expn_of(cx, expr.span, "format") {
37             match expr.node {
38                 // `format!("{}", foo)` expansion
39                 ExprCall(ref fun, ref args) => {
40                     if_let_chain!{[
41                         let ExprPath(_, ref path) = fun.node,
42                         args.len() == 2,
43                         match_path(path, &paths::FMT_ARGUMENTS_NEWV1),
44                         // ensure the format string is `"{..}"` with only one argument and no text
45                         check_static_str(cx, &args[0]),
46                         // ensure the format argument is `{}` ie. Display with no fancy option
47                         check_arg_is_display(cx, &args[1])
48                     ], {
49                         span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
50                     }}
51                 }
52                 // `format!("foo")` expansion contains `match () { () => [], }`
53                 ExprMatch(ref matchee, _, _) => {
54                     if let ExprTup(ref tup) = matchee.node {
55                         if tup.is_empty() {
56                             span_lint(cx, USELESS_FORMAT, span, "useless use of `format!`");
57                         }
58                     }
59                 }
60                 _ => (),
61             }
62         }
63     }
64 }
65
66 /// Checks if the expressions matches
67 /// ```
68 /// { static __STATIC_FMTSTR: &[""] = _; __STATIC_FMTSTR }
69 /// ```
70 fn check_static_str(cx: &LateContext, expr: &Expr) -> bool {
71     if_let_chain! {[
72         let ExprBlock(ref block) = expr.node,
73         block.stmts.len() == 1,
74         let StmtDecl(ref decl, _) = block.stmts[0].node,
75         let DeclItem(ref decl) = decl.node,
76         let Some(NodeItem(decl)) = cx.tcx.map.find(decl.id),
77         decl.name.as_str() == "__STATIC_FMTSTR",
78         let ItemStatic(_, _, ref expr) = decl.node,
79         let ExprAddrOf(_, ref expr) = expr.node, // &[""]
80         let ExprVec(ref expr) = expr.node,
81         expr.len() == 1,
82         let ExprLit(ref lit) = expr[0].node,
83         let LitKind::Str(ref lit, _) = lit.node,
84         lit.is_empty()
85     ], {
86         return true;
87     }}
88
89     false
90 }
91
92 /// Checks if the expressions matches
93 /// ```
94 /// &match (&42,) {
95 ///     (__arg0,) => [::std::fmt::ArgumentV1::new(__arg0, ::std::fmt::Display::fmt)],
96 /// })
97 /// ```
98 fn check_arg_is_display(cx: &LateContext, expr: &Expr) -> bool {
99     if_let_chain! {[
100         let ExprAddrOf(_, ref expr) = expr.node,
101         let ExprMatch(_, ref arms, _) = expr.node,
102         arms.len() == 1,
103         arms[0].pats.len() == 1,
104         let PatKind::Tuple(ref pat, None) = arms[0].pats[0].node,
105         pat.len() == 1,
106         let ExprVec(ref exprs) = arms[0].body.node,
107         exprs.len() == 1,
108         let ExprCall(_, ref args) = exprs[0].node,
109         args.len() == 2,
110         let ExprPath(None, ref path) = args[1].node,
111         match_path(path, &paths::DISPLAY_FMT_METHOD)
112     ], {
113         let ty = walk_ptrs_ty(cx.tcx.pat_ty(&pat[0]));
114
115         return ty.sty == TypeVariants::TyStr || match_type(cx, ty, &paths::STRING);
116     }}
117
118     false
119 }