]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
Auto merge of #6278 - ThibsG:DerefAddrOf, r=llogiq
[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_errors::Applicability;
4 use rustc_hir as hir;
5 use rustc_hir::def::Res;
6 use rustc_hir::intravisit;
7 use rustc_hir::BindingAnnotation;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::hir::map::Map;
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     nursery,
54     "unidiomatic `let mut` declaration followed by initialization in `if`"
55 }
56
57 declare_lint_pass!(LetIfSeq => [USELESS_LET_IF_SEQ]);
58
59 impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
60     fn check_block(&mut self, cx: &LateContext<'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.typeck_results().node_type(canonical_id).is_freeze(
77                         cx.tcx.at(span),
78                         cx.param_env,
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                                        |diag| {
123                                            diag.span_suggestion(
124                                                 span,
125                                                 "it is more idiomatic to write",
126                                                 sug,
127                                                 Applicability::HasPlaceholders,
128                                             );
129                                            if !mutability.is_empty() {
130                                                diag.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<'tcx>,
141     id: hir::HirId,
142     used: bool,
143 }
144
145 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
146     type Map = Map<'tcx>;
147
148     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'_>) {
149         if_chain! {
150             if let hir::ExprKind::Path(ref qpath) = expr.kind;
151             if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id);
152             if self.id == local_id;
153             then {
154                 self.used = true;
155                 return;
156             }
157         }
158         intravisit::walk_expr(self, expr);
159     }
160     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
161         intravisit::NestedVisitorMap::None
162     }
163 }
164
165 fn check_assign<'tcx>(
166     cx: &LateContext<'tcx>,
167     decl: hir::HirId,
168     block: &'tcx hir::Block<'_>,
169 ) -> Option<&'tcx hir::Expr<'tcx>> {
170     if_chain! {
171         if block.expr.is_none();
172         if let Some(expr) = block.stmts.iter().last();
173         if let hir::StmtKind::Semi(ref expr) = expr.kind;
174         if let hir::ExprKind::Assign(ref var, ref value, _) = expr.kind;
175         if let hir::ExprKind::Path(ref qpath) = var.kind;
176         if let Res::Local(local_id) = qpath_res(cx, qpath, var.hir_id);
177         if decl == local_id;
178         then {
179             let mut v = UsedVisitor {
180                 cx,
181                 id: decl,
182                 used: false,
183             };
184
185             for s in block.stmts.iter().take(block.stmts.len()-1) {
186                 intravisit::walk_stmt(&mut v, s);
187
188                 if v.used {
189                     return None;
190                 }
191             }
192
193             return Some(value);
194         }
195     }
196
197     None
198 }
199
200 fn used_in_expr<'tcx>(cx: &LateContext<'tcx>, id: hir::HirId, expr: &'tcx hir::Expr<'_>) -> bool {
201     let mut v = UsedVisitor { cx, id, used: false };
202     intravisit::walk_expr(&mut v, expr);
203     v.used
204 }