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