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