]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
use BindingAnnotation instead of BindingMode
[rust.git] / clippy_lints / src / let_if_seq.rs
1 use rustc::lint::*;
2 use rustc::hir;
3 use rustc::hir::BindingAnnotation;
4 use syntax_pos::{Span, NO_EXPANSION};
5 use utils::{snippet, span_lint_and_then};
6
7 /// **What it does:** Checks for variable declarations immediately followed by a
8 /// conditional affectation.
9 ///
10 /// **Why is this bad?** This is not idiomatic Rust.
11 ///
12 /// **Known problems:** None.
13 ///
14 /// **Example:**
15 /// ```rust,ignore
16 /// let foo;
17 ///
18 /// if bar() {
19 ///     foo = 42;
20 /// } else {
21 ///     foo = 0;
22 /// }
23 ///
24 /// let mut baz = None;
25 ///
26 /// if bar() {
27 ///     baz = Some(42);
28 /// }
29 /// ```
30 ///
31 /// should be written
32 ///
33 /// ```rust,ignore
34 /// let foo = if bar() {
35 ///     42
36 /// } else {
37 ///     0
38 /// };
39 ///
40 /// let baz = if bar() {
41 ///     Some(42)
42 /// } else {
43 ///     None
44 /// };
45 /// ```
46 declare_lint! {
47     pub USELESS_LET_IF_SEQ,
48     Warn,
49     "unidiomatic `let mut` declaration followed by initialization in `if`"
50 }
51
52 #[derive(Copy,Clone)]
53 pub struct LetIfSeq;
54
55 impl LintPass for LetIfSeq {
56     fn get_lints(&self) -> LintArray {
57         lint_array!(USELESS_LET_IF_SEQ)
58     }
59 }
60
61 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq {
62     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
63         let mut it = block.stmts.iter().peekable();
64         while let Some(stmt) = it.next() {
65             if_let_chain! {[
66                 let Some(expr) = it.peek(),
67                 let hir::StmtDecl(ref decl, _) = stmt.node,
68                 let hir::DeclLocal(ref decl) = decl.node,
69                 let hir::PatKind::Binding(mode, def_id, ref name, None) = decl.pat.node,
70                 let hir::StmtExpr(ref if_, _) = expr.node,
71                 let hir::ExprIf(ref cond, ref then, ref else_) = if_.node,
72                 !used_in_expr(cx, def_id, cond),
73                 let hir::ExprBlock(ref then) = then.node,
74                 let Some(value) = check_assign(cx, def_id, &*then),
75                 !used_in_expr(cx, def_id, value),
76             ], {
77                 let span = Span { lo: stmt.span.lo, hi: if_.span.hi, ctxt: NO_EXPANSION };
78
79                 let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
80                     if let hir::ExprBlock(ref else_) = else_.node {
81                         if let Some(default) = check_assign(cx, def_id, else_) {
82                             (else_.stmts.len() > 1, default)
83                         } else if let Some(ref default) = decl.init {
84                             (true, &**default)
85                         } else {
86                             continue;
87                         }
88                     } else {
89                         continue;
90                     }
91                 } else if let Some(ref default) = decl.init {
92                     (false, &**default)
93                 } else {
94                     continue;
95                 };
96
97                 let mutability = match mode {
98                     BindingAnnotation::RefMut | BindingAnnotation::Mutable => "<mut> ",
99                     _ => "",
100                 };
101
102                 // FIXME: this should not suggest `mut` if we can detect that the variable is not
103                 // use mutably after the `if`
104
105                 let sug = format!(
106                     "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
107                     mut=mutability,
108                     name=name.node,
109                     cond=snippet(cx, cond.span, "_"),
110                     then=if then.stmts.len() > 1 { " ..;" } else { "" },
111                     else=if default_multi_stmts { " ..;" } else { "" },
112                     value=snippet(cx, value.span, "<value>"),
113                     default=snippet(cx, default.span, "<default>"),
114                 );
115                 span_lint_and_then(cx,
116                                    USELESS_LET_IF_SEQ,
117                                    span,
118                                    "`if _ { .. } else { .. }` is an expression",
119                                    |db| {
120                                        db.span_suggestion(span,
121                                                           "it is more idiomatic to write",
122                                                           sug);
123                                        if !mutability.is_empty() {
124                                            db.note("you might not need `mut` at all");
125                                        }
126                                    });
127             }}
128         }
129     }
130 }
131
132 struct UsedVisitor<'a, 'tcx: 'a> {
133     cx: &'a LateContext<'a, 'tcx>,
134     id: hir::def_id::DefId,
135     used: bool,
136 }
137
138 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
139     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
140         if_let_chain! {[
141             let hir::ExprPath(ref qpath) = expr.node,
142             self.id == self.cx.tables.qpath_def(qpath, expr.id).def_id(),
143         ], {
144             self.used = true;
145             return;
146         }}
147         hir::intravisit::walk_expr(self, expr);
148     }
149     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
150         hir::intravisit::NestedVisitorMap::None
151     }
152 }
153
154 fn check_assign<'a, 'tcx>(
155     cx: &LateContext<'a, 'tcx>,
156     decl: hir::def_id::DefId,
157     block: &'tcx hir::Block
158 ) -> Option<&'tcx hir::Expr> {
159     if_let_chain! {[
160         block.expr.is_none(),
161         let Some(expr) = block.stmts.iter().last(),
162         let hir::StmtSemi(ref expr, _) = expr.node,
163         let hir::ExprAssign(ref var, ref value) = expr.node,
164         let hir::ExprPath(ref qpath) = var.node,
165         decl == cx.tables.qpath_def(qpath, var.id).def_id(),
166     ], {
167         let mut v = UsedVisitor {
168             cx: cx,
169             id: decl,
170             used: false,
171         };
172
173         for s in block.stmts.iter().take(block.stmts.len()-1) {
174             hir::intravisit::walk_stmt(&mut v, s);
175
176             if v.used {
177                 return None;
178             }
179         }
180
181         return Some(value);
182     }}
183
184     None
185 }
186
187 fn used_in_expr<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, id: hir::def_id::DefId, expr: &'tcx hir::Expr) -> bool {
188     let mut v = UsedVisitor {
189         cx: cx,
190         id: id,
191         used: false,
192     };
193     hir::intravisit::walk_expr(&mut v, expr);
194     v.used
195 }