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