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