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