]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
Auto merge of #79328 - c410-f3r:hir-if, r=matthewjasper
[rust.git] / clippy_lints / src / let_if_seq.rs
1 use crate::utils::{qpath_res, snippet, span_lint_and_then, visitors::LocalUsedVisitor};
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::BindingAnnotation;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
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     nursery,
52     "unidiomatic `let mut` declaration followed by initialization in `if`"
53 }
54
55 declare_lint_pass!(LetIfSeq => [USELESS_LET_IF_SEQ]);
56
57 impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
58     fn check_block(&mut self, cx: &LateContext<'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.kind;
64                 if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind;
65                 if let hir::StmtKind::Expr(ref if_) = expr.kind;
66                 if let hir::ExprKind::If(ref cond, ref then, ref else_) = if_.kind;
67                 if !LocalUsedVisitor::new(canonical_id).check_expr(cond);
68                 if let hir::ExprKind::Block(ref then, _) = then.kind;
69                 if let Some(value) = check_assign(cx, canonical_id, &*then);
70                 if !LocalUsedVisitor::new(canonical_id).check_expr(value);
71                 then {
72                     let span = stmt.span.to(if_.span);
73
74                     let has_interior_mutability = !cx.typeck_results().node_type(canonical_id).is_freeze(
75                         cx.tcx.at(span),
76                         cx.param_env,
77                     );
78                     if has_interior_mutability { return; }
79
80                     let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
81                         if let hir::ExprKind::Block(ref else_, _) = else_.kind {
82                             if let Some(default) = check_assign(cx, canonical_id, else_) {
83                                 (else_.stmts.len() > 1, default)
84                             } else if let Some(ref default) = local.init {
85                                 (true, &**default)
86                             } else {
87                                 continue;
88                             }
89                         } else {
90                             continue;
91                         }
92                     } else if let Some(ref default) = local.init {
93                         (false, &**default)
94                     } else {
95                         continue;
96                     };
97
98                     let mutability = match mode {
99                         BindingAnnotation::RefMut | BindingAnnotation::Mutable => "<mut> ",
100                         _ => "",
101                     };
102
103                     // FIXME: this should not suggest `mut` if we can detect that the variable is not
104                     // use mutably after the `if`
105
106                     let sug = format!(
107                         "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
108                         mut=mutability,
109                         name=ident.name,
110                         cond=snippet(cx, cond.span, "_"),
111                         then=if then.stmts.len() > 1 { " ..;" } else { "" },
112                         else=if default_multi_stmts { " ..;" } else { "" },
113                         value=snippet(cx, value.span, "<value>"),
114                         default=snippet(cx, default.span, "<default>"),
115                     );
116                     span_lint_and_then(cx,
117                                        USELESS_LET_IF_SEQ,
118                                        span,
119                                        "`if _ { .. } else { .. }` is an expression",
120                                        |diag| {
121                                            diag.span_suggestion(
122                                                 span,
123                                                 "it is more idiomatic to write",
124                                                 sug,
125                                                 Applicability::HasPlaceholders,
126                                             );
127                                            if !mutability.is_empty() {
128                                                diag.note("you might not need `mut` at all");
129                                            }
130                                        });
131                 }
132             }
133         }
134     }
135 }
136
137 fn check_assign<'tcx>(
138     cx: &LateContext<'tcx>,
139     decl: hir::HirId,
140     block: &'tcx hir::Block<'_>,
141 ) -> Option<&'tcx hir::Expr<'tcx>> {
142     if_chain! {
143         if block.expr.is_none();
144         if let Some(expr) = block.stmts.iter().last();
145         if let hir::StmtKind::Semi(ref expr) = expr.kind;
146         if let hir::ExprKind::Assign(ref var, ref value, _) = expr.kind;
147         if let hir::ExprKind::Path(ref qpath) = var.kind;
148         if let Res::Local(local_id) = qpath_res(cx, qpath, var.hir_id);
149         if decl == local_id;
150         then {
151             let mut v = LocalUsedVisitor::new(decl);
152
153             if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| v.check_stmt(stmt)) {
154                 return None;
155             }
156
157             return Some(value);
158         }
159     }
160
161     None
162 }