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