]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/let_if_seq.rs
formatting fix
[rust.git] / clippy_lints / src / let_if_seq.rs
1 use crate::utils::{snippet, span_lint_and_then};
2 use if_chain::if_chain;
3 use rustc::hir;
4 use rustc::hir::def::Def;
5 use rustc::hir::BindingAnnotation;
6 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use rustc::{declare_tool_lint, lint_array};
8 use rustc_errors::Applicability;
9 use syntax::ast;
10
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 declare_clippy_lint! {
51     pub USELESS_LET_IF_SEQ,
52     style,
53     "unidiomatic `let mut` declaration followed by initialization in `if`"
54 }
55
56 #[derive(Copy, Clone)]
57 pub struct LetIfSeq;
58
59 impl LintPass for LetIfSeq {
60     fn get_lints(&self) -> LintArray {
61         lint_array!(USELESS_LET_IF_SEQ)
62     }
63 }
64
65 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq {
66     fn check_block(&mut self, cx: &LateContext<'a, 'tcx>, block: &'tcx hir::Block) {
67         let mut it = block.stmts.iter().peekable();
68         while let Some(stmt) = it.next() {
69             if_chain! {
70                 if let Some(expr) = it.peek();
71                 if let hir::StmtKind::Decl(ref decl, _) = stmt.node;
72                 if let hir::DeclKind::Local(ref decl) = decl.node;
73                 if let hir::PatKind::Binding(mode, canonical_id, ident, None) = decl.pat.node;
74                 if let hir::StmtKind::Expr(ref if_, _) = expr.node;
75                 if let hir::ExprKind::If(ref cond, ref then, ref else_) = if_.node;
76                 if !used_in_expr(cx, canonical_id, cond);
77                 if let hir::ExprKind::Block(ref then, _) = then.node;
78                 if let Some(value) = check_assign(cx, canonical_id, &*then);
79                 if !used_in_expr(cx, canonical_id, value);
80                 then {
81                     let span = stmt.span.to(if_.span);
82
83                     let (default_multi_stmts, default) = if let Some(ref else_) = *else_ {
84                         if let hir::ExprKind::Block(ref else_, _) = else_.node {
85                             if let Some(default) = check_assign(cx, canonical_id, else_) {
86                                 (else_.stmts.len() > 1, default)
87                             } else if let Some(ref default) = decl.init {
88                                 (true, &**default)
89                             } else {
90                                 continue;
91                             }
92                         } else {
93                             continue;
94                         }
95                     } else if let Some(ref default) = decl.init {
96                         (false, &**default)
97                     } else {
98                         continue;
99                     };
100
101                     let mutability = match mode {
102                         BindingAnnotation::RefMut | BindingAnnotation::Mutable => "<mut> ",
103                         _ => "",
104                     };
105
106                     // FIXME: this should not suggest `mut` if we can detect that the variable is not
107                     // use mutably after the `if`
108
109                     let sug = format!(
110                         "let {mut}{name} = if {cond} {{{then} {value} }} else {{{else} {default} }};",
111                         mut=mutability,
112                         name=ident.name,
113                         cond=snippet(cx, cond.span, "_"),
114                         then=if then.stmts.len() > 1 { " ..;" } else { "" },
115                         else=if default_multi_stmts { " ..;" } else { "" },
116                         value=snippet(cx, value.span, "<value>"),
117                         default=snippet(cx, default.span, "<default>"),
118                     );
119                     span_lint_and_then(cx,
120                                        USELESS_LET_IF_SEQ,
121                                        span,
122                                        "`if _ { .. } else { .. }` is an expression",
123                                        |db| {
124                                            db.span_suggestion_with_applicability(
125                                                 span,
126                                                 "it is more idiomatic to write",
127                                                 sug,
128                                                 Applicability::HasPlaceholders,
129                                             );
130                                            if !mutability.is_empty() {
131                                                db.note("you might not need `mut` at all");
132                                            }
133                                        });
134                 }
135             }
136         }
137     }
138 }
139
140 struct UsedVisitor<'a, 'tcx: 'a> {
141     cx: &'a LateContext<'a, 'tcx>,
142     id: ast::NodeId,
143     used: bool,
144 }
145
146 impl<'a, 'tcx> hir::intravisit::Visitor<'tcx> for UsedVisitor<'a, 'tcx> {
147     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
148         if_chain! {
149             if let hir::ExprKind::Path(ref qpath) = expr.node;
150             if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
151             if self.id == local_id;
152             then {
153                 self.used = true;
154                 return;
155             }
156         }
157         hir::intravisit::walk_expr(self, expr);
158     }
159     fn nested_visit_map<'this>(&'this mut self) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> {
160         hir::intravisit::NestedVisitorMap::None
161     }
162 }
163
164 fn check_assign<'a, 'tcx>(
165     cx: &LateContext<'a, 'tcx>,
166     decl: ast::NodeId,
167     block: &'tcx hir::Block,
168 ) -> Option<&'tcx hir::Expr> {
169     if_chain! {
170         if block.expr.is_none();
171         if let Some(expr) = block.stmts.iter().last();
172         if let hir::StmtKind::Semi(ref expr, _) = expr.node;
173         if let hir::ExprKind::Assign(ref var, ref value) = expr.node;
174         if let hir::ExprKind::Path(ref qpath) = var.node;
175         if let Def::Local(local_id) = cx.tables.qpath_def(qpath, var.hir_id);
176         if decl == local_id;
177         then {
178             let mut v = UsedVisitor {
179                 cx,
180                 id: decl,
181                 used: false,
182             };
183
184             for s in block.stmts.iter().take(block.stmts.len()-1) {
185                 hir::intravisit::walk_stmt(&mut v, s);
186
187                 if v.used {
188                     return None;
189                 }
190             }
191
192             return Some(value);
193         }
194     }
195
196     None
197 }
198
199 fn used_in_expr<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, id: ast::NodeId, expr: &'tcx hir::Expr) -> bool {
200     let mut v = UsedVisitor { cx, id, used: false };
201     hir::intravisit::walk_expr(&mut v, expr);
202     v.used
203 }