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