]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_else.rs
Auto merge of #91284 - t6:freebsd-riscv64, r=Amanieu
[rust.git] / src / tools / clippy / clippy_lints / src / redundant_else.rs
1 use clippy_utils::diagnostics::span_lint_and_help;
2 use rustc_ast::ast::{Block, Expr, ExprKind, Stmt, StmtKind};
3 use rustc_ast::visit::{walk_expr, Visitor};
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_middle::lint::in_external_macro;
6 use rustc_session::{declare_lint_pass, declare_tool_lint};
7
8 declare_clippy_lint! {
9     /// ### What it does
10     /// Checks for `else` blocks that can be removed without changing semantics.
11     ///
12     /// ### Why is this bad?
13     /// The `else` block adds unnecessary indentation and verbosity.
14     ///
15     /// ### Known problems
16     /// Some may prefer to keep the `else` block for clarity.
17     ///
18     /// ### Example
19     /// ```rust
20     /// fn my_func(count: u32) {
21     ///     if count == 0 {
22     ///         print!("Nothing to do");
23     ///         return;
24     ///     } else {
25     ///         print!("Moving on...");
26     ///     }
27     /// }
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// fn my_func(count: u32) {
32     ///     if count == 0 {
33     ///         print!("Nothing to do");
34     ///         return;
35     ///     }
36     ///     print!("Moving on...");
37     /// }
38     /// ```
39     pub REDUNDANT_ELSE,
40     pedantic,
41     "`else` branch that can be removed without changing semantics"
42 }
43
44 declare_lint_pass!(RedundantElse => [REDUNDANT_ELSE]);
45
46 impl EarlyLintPass for RedundantElse {
47     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &Stmt) {
48         if in_external_macro(cx.sess, stmt.span) {
49             return;
50         }
51         // Only look at expressions that are a whole statement
52         let expr: &Expr = match &stmt.kind {
53             StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
54             _ => return,
55         };
56         // if else
57         let (mut then, mut els): (&Block, &Expr) = match &expr.kind {
58             ExprKind::If(_, then, Some(els)) => (then, els),
59             _ => return,
60         };
61         loop {
62             if !BreakVisitor::default().check_block(then) {
63                 // then block does not always break
64                 return;
65             }
66             match &els.kind {
67                 // else if else
68                 ExprKind::If(_, next_then, Some(next_els)) => {
69                     then = next_then;
70                     els = next_els;
71                     continue;
72                 },
73                 // else if without else
74                 ExprKind::If(..) => return,
75                 // done
76                 _ => break,
77             }
78         }
79         span_lint_and_help(
80             cx,
81             REDUNDANT_ELSE,
82             els.span,
83             "redundant else block",
84             None,
85             "remove the `else` block and move the contents out",
86         );
87     }
88 }
89
90 /// Call `check` functions to check if an expression always breaks control flow
91 #[derive(Default)]
92 struct BreakVisitor {
93     is_break: bool,
94 }
95
96 impl<'ast> Visitor<'ast> for BreakVisitor {
97     fn visit_block(&mut self, block: &'ast Block) {
98         self.is_break = match block.stmts.as_slice() {
99             [.., last] => self.check_stmt(last),
100             _ => false,
101         };
102     }
103
104     fn visit_expr(&mut self, expr: &'ast Expr) {
105         self.is_break = match expr.kind {
106             ExprKind::Break(..) | ExprKind::Continue(..) | ExprKind::Ret(..) => true,
107             ExprKind::Match(_, ref arms) => arms.iter().all(|arm| self.check_expr(&arm.body)),
108             ExprKind::If(_, ref then, Some(ref els)) => self.check_block(then) && self.check_expr(els),
109             ExprKind::If(_, _, None)
110             // ignore loops for simplicity
111             | ExprKind::While(..) | ExprKind::ForLoop(..) | ExprKind::Loop(..) => false,
112             _ => {
113                 walk_expr(self, expr);
114                 return;
115             },
116         };
117     }
118 }
119
120 impl BreakVisitor {
121     fn check<T>(&mut self, item: T, visit: fn(&mut Self, T)) -> bool {
122         visit(self, item);
123         std::mem::replace(&mut self.is_break, false)
124     }
125
126     fn check_block(&mut self, block: &Block) -> bool {
127         self.check(block, Self::visit_block)
128     }
129
130     fn check_expr(&mut self, expr: &Expr) -> bool {
131         self.check(expr, Self::visit_expr)
132     }
133
134     fn check_stmt(&mut self, stmt: &Stmt) -> bool {
135         self.check(stmt, Self::visit_stmt)
136     }
137 }