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