]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/let_if_seq.rs
Merge commit 'ac0e10aa68325235069a842f47499852b2dee79e' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / let_if_seq.rs
1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::snippet;
3 use clippy_utils::{path_to_local_id, visitors::is_local_used};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_hir::{BindingAnnotation, Mutability};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10
11 declare_clippy_lint! {
12     /// ### What it does
13     /// Checks for variable declarations immediately followed by a
14     /// conditional affectation.
15     ///
16     /// ### Why is this bad?
17     /// This is not idiomatic Rust.
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     #[clippy::version = "pre 1.29.0"]
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(local) = stmt.kind;
66                 if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind;
67                 if let hir::StmtKind::Expr(if_) = expr.kind;
68                 if let hir::ExprKind::If(hir::Expr { kind: hir::ExprKind::DropTemps(cond), ..}, then, else_) = if_.kind;
69                 if !is_local_used(cx, *cond, canonical_id);
70                 if let hir::ExprKind::Block(then, _) = then.kind;
71                 if let Some(value) = check_assign(cx, canonical_id, then);
72                 if !is_local_used(cx, value, canonical_id);
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(else_) = else_ {
83                         if let hir::ExprKind::Block(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(default) = local.init {
87                                 (true, default)
88                             } else {
89                                 continue;
90                             }
91                         } else {
92                             continue;
93                         }
94                     } else if let Some(default) = local.init {
95                         (false, default)
96                     } else {
97                         continue;
98                     };
99
100                     let mutability = match mode {
101                         BindingAnnotation(_, Mutability::Mut) => "<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 {mutability}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
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                                        |diag| {
122                                            diag.span_suggestion(
123                                                 span,
124                                                 "it is more idiomatic to write",
125                                                 sug,
126                                                 Applicability::HasPlaceholders,
127                                             );
128                                            if !mutability.is_empty() {
129                                                diag.note("you might not need `mut` at all");
130                                            }
131                                        });
132                 }
133             }
134         }
135     }
136 }
137
138 fn check_assign<'tcx>(
139     cx: &LateContext<'tcx>,
140     decl: hir::HirId,
141     block: &'tcx hir::Block<'_>,
142 ) -> Option<&'tcx hir::Expr<'tcx>> {
143     if_chain! {
144         if block.expr.is_none();
145         if let Some(expr) = block.stmts.iter().last();
146         if let hir::StmtKind::Semi(expr) = expr.kind;
147         if let hir::ExprKind::Assign(var, value, _) = expr.kind;
148         if path_to_local_id(var, decl);
149         then {
150             if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| is_local_used(cx, stmt, decl)) {
151                 None
152             } else {
153                 Some(value)
154             }
155         } else {
156             None
157         }
158     }
159 }