]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
Auto merge of #78399 - vn-ki:gsgdt-graphviz, r=oli-obk
[rust.git] / clippy_lints / src / let_if_seq.rs
1 use crate::utils::visitors::LocalUsedVisitor;
2 use crate::utils::{higher, qpath_res, snippet, span_lint_and_then};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir as hir;
6 use rustc_hir::def::Res;
7 use rustc_hir::BindingAnnotation;
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:** Checks for variable declarations immediately followed by a
13     /// conditional affectation.
14     ///
15     /// **Why is this bad?** This is not idiomatic Rust.
16     ///
17     /// **Known problems:** None.
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     pub USELESS_LET_IF_SEQ,
52     nursery,
53     "unidiomatic `let mut` declaration followed by initialization in `if`"
54 }
55
56 declare_lint_pass!(LetIfSeq => [USELESS_LET_IF_SEQ]);
57
58 impl<'tcx> LateLintPass<'tcx> for LetIfSeq {
59     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
60         let mut it = block.stmts.iter().peekable();
61         while let Some(stmt) = it.next() {
62             if_chain! {
63                 if let Some(expr) = it.peek();
64                 if let hir::StmtKind::Local(ref local) = stmt.kind;
65                 if let hir::PatKind::Binding(mode, canonical_id, ident, None) = local.pat.kind;
66                 if let hir::StmtKind::Expr(ref if_) = expr.kind;
67                 if let Some((ref cond, ref then, ref else_)) = higher::if_block(&if_);
68                 if !LocalUsedVisitor::new(canonical_id).check_expr(cond);
69                 if let hir::ExprKind::Block(ref then, _) = then.kind;
70                 if let Some(value) = check_assign(cx, canonical_id, &*then);
71                 if !LocalUsedVisitor::new(canonical_id).check_expr(value);
72                 then {
73                     let span = stmt.span.to(if_.span);
74
75                     let has_interior_mutability = !cx.typeck_results().node_type(canonical_id).is_freeze(
76                         cx.tcx.at(span),
77                         cx.param_env,
78                     );
79                     if has_interior_mutability { return; }
80
81                     let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
82                         if let hir::ExprKind::Block(ref else_, _) = else_.kind {
83                             if let Some(default) = check_assign(cx, canonical_id, else_) {
84                                 (else_.stmts.len() > 1, default)
85                             } else if let Some(ref default) = local.init {
86                                 (true, &**default)
87                             } else {
88                                 continue;
89                             }
90                         } else {
91                             continue;
92                         }
93                     } else if let Some(ref default) = local.init {
94                         (false, &**default)
95                     } else {
96                         continue;
97                     };
98
99                     let mutability = match mode {
100                         BindingAnnotation::RefMut | BindingAnnotation::Mutable => "<mut> ",
101                         _ => "",
102                     };
103
104                     // FIXME: this should not suggest `mut` if we can detect that the variable is not
105                     // use mutably after the `if`
106
107                     let sug = format!(
108                         "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
109                         mut=mutability,
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(ref expr) = expr.kind;
147         if let hir::ExprKind::Assign(ref var, ref value, _) = expr.kind;
148         if let hir::ExprKind::Path(ref qpath) = var.kind;
149         if let Res::Local(local_id) = qpath_res(cx, qpath, var.hir_id);
150         if decl == local_id;
151         then {
152             let mut v = LocalUsedVisitor::new(decl);
153
154             if block.stmts.iter().take(block.stmts.len()-1).any(|stmt| v.check_stmt(stmt)) {
155                 return None;
156             }
157
158             return Some(value);
159         }
160     }
161
162     None
163 }