]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
5863eef8a26f804db9a5a5d212cfaf061ac6bfba
[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                 let mut used_visitor = LocalUsedVisitor::new(cx, canonical_id);
67                 if !used_visitor.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 !used_visitor.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 path_to_local_id(var, decl);
148         then {
149             let mut v = LocalUsedVisitor::new(cx, decl);
150
151             if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| v.check_stmt(stmt)) {
152                 return None;
153             }
154
155             return Some(value);
156         }
157     }
158
159     None
160 }