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