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