]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
Rustup
[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 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_lint! {
48     pub USELESS_LET_IF_SEQ,
49     Warn,
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_let_chain! {[
67                 let Some(expr) = it.peek(),
68                 let hir::StmtDecl(ref decl, _) = stmt.node,
69                 let hir::DeclLocal(ref decl) = decl.node,
70                 let hir::PatKind::Binding(mode, canonical_id, ref name, None) = decl.pat.node,
71                 let hir::StmtExpr(ref if_, _) = expr.node,
72                 let hir::ExprIf(ref cond, ref then, ref else_) = if_.node,
73                 !used_in_expr(cx, canonical_id, cond),
74                 let hir::ExprBlock(ref then) = then.node,
75                 let Some(value) = check_assign(cx, canonical_id, &*then),
76                 !used_in_expr(cx, canonical_id, value),
77             ], {
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 struct UsedVisitor<'a, 'tcx: 'a> {
134     cx: &'a LateContext<'a, 'tcx>,
135     id: ast::NodeId,
136     used: bool,
137 }
138
139 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
140     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
141         if_let_chain! {[
142             let hir::ExprPath(ref qpath) = expr.node,
143             let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id),
144             self.id == local_id,
145         ], {
146             self.used = true;
147             return;
148         }}
149         hir::intravisit::walk_expr(self, expr);
150     }
151     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
152         hir::intravisit::NestedVisitorMap::None
153     }
154 }
155
156 fn check_assign<'a, 'tcx>(
157     cx: &LateContext<'a, 'tcx>,
158     decl: ast::NodeId,
159     block: &'tcx hir::Block,
160 ) -> Option<&'tcx hir::Expr> {
161     if_let_chain! {[
162         block.expr.is_none(),
163         let Some(expr) = block.stmts.iter().last(),
164         let hir::StmtSemi(ref expr, _) = expr.node,
165         let hir::ExprAssign(ref var, ref value) = expr.node,
166         let hir::ExprPath(ref qpath) = var.node,
167         let Def::Local(local_id) = cx.tables.qpath_def(qpath, var.hir_id),
168         decl == local_id,
169     ], {
170         let mut v = UsedVisitor {
171             cx: cx,
172             id: decl,
173             used: false,
174         };
175
176         for s in block.stmts.iter().take(block.stmts.len()-1) {
177             hir::intravisit::walk_stmt(&mut v, s);
178
179             if v.used {
180                 return None;
181             }
182         }
183
184         return Some(value);
185     }}
186
187     None
188 }
189
190 fn used_in_expr<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, id: ast::NodeId, expr: &'tcx hir::Expr) -> bool {
191     let mut v = UsedVisitor {
192         cx: cx,
193         id: id,
194         used: false,
195     };
196     hir::intravisit::walk_expr(&mut v, expr);
197     v.used
198 }