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