]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[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
10 declare_clippy_lint! {
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     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     fn name(&self) -> &'static str {
64         "LetIfSeq"
65     }
66 }
67
68 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq {
69     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
70         let mut it = block.stmts.iter().peekable();
71         while let Some(stmt) = it.next() {
72             if_chain! {
73                 if let Some(expr) = it.peek();
74                 if let hir::StmtKind::Local(ref local) = stmt.node;
75                 if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.node;
76                 if let hir::StmtKind::Expr(ref if_) = expr.node;
77                 if let hir::ExprKind::If(ref cond, ref then, ref else_) = if_.node;
78                 if !used_in_expr(cx, canonical_id, cond);
79                 if let hir::ExprKind::Block(ref then, _) = then.node;
80                 if let Some(value) = check_assign(cx, canonical_id, &*then);
81                 if !used_in_expr(cx, canonical_id, value);
82                 then {
83                     let span = stmt.span.to(if_.span);
84
85                     let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
86                         if let hir::ExprKind::Block(ref else_, _) = else_.node {
87                             if let Some(default) = check_assign(cx, canonical_id, else_) {
88                                 (else_.stmts.len() > 1, default)
89                             } else if let Some(ref default) = local.init {
90                                 (true, &**default)
91                             } else {
92                                 continue;
93                             }
94                         } else {
95                             continue;
96                         }
97                     } else if let Some(ref default) = local.init {
98                         (false, &**default)
99                     } else {
100                         continue;
101                     };
102
103                     let mutability = match mode {
104                         BindingAnnotation::RefMut | BindingAnnotation::Mutable => "<mut> ",
105                         _ => "",
106                     };
107
108                     // FIXME: this should not suggest `mut` if we can detect that the variable is not
109                     // use mutably after the `if`
110
111                     let sug = format!(
112                         "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
113                         mut=mutability,
114                         name=ident.name,
115                         cond=snippet(cx, cond.span, "_"),
116                         then=if then.stmts.len() > 1 { " ..;" } else { "" },
117                         else=if default_multi_stmts { " ..;" } else { "" },
118                         value=snippet(cx, value.span, "<value>"),
119                         default=snippet(cx, default.span, "<default>"),
120                     );
121                     span_lint_and_then(cx,
122                                        USELESS_LET_IF_SEQ,
123                                        span,
124                                        "`if _ { .. } else { .. }` is an expression",
125                                        |db| {
126                                            db.span_suggestion(
127                                                 span,
128                                                 "it is more idiomatic to write",
129                                                 sug,
130                                                 Applicability::HasPlaceholders,
131                                             );
132                                            if !mutability.is_empty() {
133                                                db.note("you might not need `mut` at all");
134                                            }
135                                        });
136                 }
137             }
138         }
139     }
140 }
141
142 struct UsedVisitor<'a, 'tcx: 'a> {
143     cx: &'a LateContext<'a, 'tcx>,
144     id: hir::HirId,
145     used: bool,
146 }
147
148 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
149     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
150         if_chain! {
151             if let hir::ExprKind::Path(ref qpath) = expr.node;
152             if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
153             if self.id == self.cx.tcx.hir().node_to_hir_id(local_id);
154             then {
155                 self.used = true;
156                 return;
157             }
158         }
159         hir::intravisit::walk_expr(self, expr);
160     }
161     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
162         hir::intravisit::NestedVisitorMap::None
163     }
164 }
165
166 fn check_assign<'a, 'tcx>(
167     cx: &LateContext<'a, 'tcx>,
168     decl: hir::HirId,
169     block: &'tcx hir::Block,
170 ) -> Option<&'tcx hir::Expr> {
171     if_chain! {
172         if block.expr.is_none();
173         if let Some(expr) = block.stmts.iter().last();
174         if let hir::StmtKind::Semi(ref expr) = expr.node;
175         if let hir::ExprKind::Assign(ref var, ref value) = expr.node;
176         if let hir::ExprKind::Path(ref qpath) = var.node;
177         if let Def::Local(local_id) = cx.tables.qpath_def(qpath, var.hir_id);
178         if decl == cx.tcx.hir().node_to_hir_id(local_id);
179         then {
180             let mut v = UsedVisitor {
181                 cx,
182                 id: decl,
183                 used: false,
184             };
185
186             for s in block.stmts.iter().take(block.stmts.len()-1) {
187                 hir::intravisit::walk_stmt(&mut v, s);
188
189                 if v.used {
190                     return None;
191                 }
192             }
193
194             return Some(value);
195         }
196     }
197
198     None
199 }
200
201 fn used_in_expr<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, id: hir::HirId, expr: &'tcx hir::Expr) -> bool {
202     let mut v = UsedVisitor { cx, id, used: false };
203     hir::intravisit::walk_expr(&mut v, expr);
204     v.used
205 }