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