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