]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
a85cb52f2dc6e0d4687750474fb0ca879710c2e9
[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:** This lint 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     "Checks for 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 LateLintPass for LetIfSeq {
61     fn check_block(&mut self, cx: &LateContext, block: &hir::Block) {
62         let mut it = block.stmts.iter().peekable();
63         while let Some(ref 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, ref name, None) = decl.pat.node,
69                 let Some(def) = cx.tcx.def_map.borrow().get(&decl.pat.id),
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.def_id(), cond),
73                 let Some(value) = check_assign(cx, def.def_id(), then),
74                 !used_in_expr(cx, def.def_id(), value),
75             ], {
76                 let span = codemap::mk_sp(stmt.span.lo, if_.span.hi);
77
78                 let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
79                     if let hir::ExprBlock(ref else_) = else_.node {
80                         if let Some(default) = check_assign(cx, def.def_id(), else_) {
81                             (else_.stmts.len() > 1, default)
82                         } else if let Some(ref default) = decl.init {
83                             (true, &**default)
84                         } else {
85                             continue;
86                         }
87                     } else {
88                         continue;
89                     }
90                 } else if let Some(ref default) = decl.init {
91                     (false, &**default)
92                 } else {
93                     continue;
94                 };
95
96                 let mutability = match mode {
97                     hir::BindByRef(hir::MutMutable) | hir::BindByValue(hir::MutMutable) => "<mut> ",
98                     _ => "",
99                 };
100
101                 // FIXME: this should not suggest `mut` if we can detect that the variable is not
102                 // use mutably after the `if`
103
104                 let sug = format!(
105                     "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
106                     mut=mutability,
107                     name=name.node,
108                     cond=snippet(cx, cond.span, "_"),
109                     then=if then.stmts.len() > 1 { " ..;" } else { "" },
110                     else=if default_multi_stmts { " ..;" } else { "" },
111                     value=snippet(cx, value.span, "<value>"),
112                     default=snippet(cx, default.span, "<default>"),
113                 );
114                 span_lint_and_then(cx,
115                                    USELESS_LET_IF_SEQ,
116                                    span,
117                                    "`if _ { .. } else { .. }` is an expression",
118                                    |db| {
119                                        db.span_suggestion(span,
120                                                           "it is more idiomatic to write",
121                                                           sug);
122                                        if !mutability.is_empty() {
123                                            db.note("you might not need `mut` at all");
124                                        }
125                                    });
126             }}
127         }
128     }
129 }
130
131 struct UsedVisitor<'a, 'tcx: 'a> {
132     cx: &'a LateContext<'a, 'tcx>,
133     id: hir::def_id::DefId,
134     used: bool,
135 }
136
137 impl<'a, 'tcx, 'v> hir::intravisit::Visitor<'v> for UsedVisitor<'a, 'tcx> {
138     fn visit_expr(&mut self, expr: &'v hir::Expr) {
139         if_let_chain! {[
140             let hir::ExprPath(None, _) = expr.node,
141             let Some(def) = self.cx.tcx.def_map.borrow().get(&expr.id),
142             self.id == def.def_id(),
143         ], {
144             self.used = true;
145             return;
146         }}
147         hir::intravisit::walk_expr(self, expr);
148     }
149 }
150
151 fn check_assign<'e>(cx: &LateContext, decl: hir::def_id::DefId, block: &'e hir::Block) -> Option<&'e hir::Expr> {
152     if_let_chain! {[
153         let Some(expr) = block.stmts.iter().last(),
154         let hir::StmtSemi(ref expr, _) = expr.node,
155         let hir::ExprAssign(ref var, ref value) = expr.node,
156         let hir::ExprPath(None, _) = var.node,
157         let Some(def) = cx.tcx.def_map.borrow().get(&var.id),
158         decl == def.def_id(),
159     ], {
160         let mut v = UsedVisitor {
161             cx: cx,
162             id: decl,
163             used: false,
164         };
165
166         for s in block.stmts.iter().take(block.stmts.len()-1) {
167             hir::intravisit::walk_stmt(&mut v, s);
168
169             if v.used {
170                 return None;
171             }
172         }
173
174         return Some(value);
175     }}
176
177     None
178 }
179
180 fn used_in_expr(cx: &LateContext, id: hir::def_id::DefId, expr: &hir::Expr) -> bool {
181     let mut v = UsedVisitor {
182         cx: cx,
183         id: id,
184         used: false
185     };
186     hir::intravisit::walk_expr(&mut v, expr);
187     v.used
188 }