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