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