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