]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/redundant_else.rs
Rollup merge of #93508 - CraftSpider:jsondocck-runtest-output, r=Mark-Simulacrum
[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, LintContext};
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     #[clippy::version = "1.50.0"]
40     pub REDUNDANT_ELSE,
41     pedantic,
42     "`else` branch that can be removed without changing semantics"
43 }
44
45 declare_lint_pass!(RedundantElse => [REDUNDANT_ELSE]);
46
47 impl EarlyLintPass for RedundantElse {
48     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &Stmt) {
49         if in_external_macro(cx.sess(), stmt.span) {
50             return;
51         }
52         // Only look at expressions that are a whole statement
53         let expr: &Expr = match &stmt.kind {
54             StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
55             _ => return,
56         };
57         // if else
58         let (mut then, mut els): (&Block, &Expr) = match &expr.kind {
59             ExprKind::If(_, then, Some(els)) => (then, els),
60             _ => return,
61         };
62         loop {
63             if !BreakVisitor::default().check_block(then) {
64                 // then block does not always break
65                 return;
66             }
67             match &els.kind {
68                 // else if else
69                 ExprKind::If(_, next_then, Some(next_els)) => {
70                     then = next_then;
71                     els = next_els;
72                     continue;
73                 },
74                 // else if without else
75                 ExprKind::If(..) => return,
76                 // done
77                 _ => break,
78             }
79         }
80         span_lint_and_help(
81             cx,
82             REDUNDANT_ELSE,
83             els.span,
84             "redundant else block",
85             None,
86             "remove the `else` block and move the contents out",
87         );
88     }
89 }
90
91 /// Call `check` functions to check if an expression always breaks control flow
92 #[derive(Default)]
93 struct BreakVisitor {
94     is_break: bool,
95 }
96
97 impl<'ast> Visitor<'ast> for BreakVisitor {
98     fn visit_block(&mut self, block: &'ast Block) {
99         self.is_break = match block.stmts.as_slice() {
100             [.., last] => self.check_stmt(last),
101             _ => false,
102         };
103     }
104
105     fn visit_expr(&mut self, expr: &'ast Expr) {
106         self.is_break = match expr.kind {
107             ExprKind::Break(..) | ExprKind::Continue(..) | ExprKind::Ret(..) => true,
108             ExprKind::Match(_, ref arms) => arms.iter().all(|arm| self.check_expr(&arm.body)),
109             ExprKind::If(_, ref then, Some(ref els)) => self.check_block(then) && self.check_expr(els),
110             ExprKind::If(_, _, None)
111             // ignore loops for simplicity
112             | ExprKind::While(..) | ExprKind::ForLoop(..) | ExprKind::Loop(..) => false,
113             _ => {
114                 walk_expr(self, expr);
115                 return;
116             },
117         };
118     }
119 }
120
121 impl BreakVisitor {
122     fn check<T>(&mut self, item: T, visit: fn(&mut Self, T)) -> bool {
123         visit(self, item);
124         std::mem::replace(&mut self.is_break, false)
125     }
126
127     fn check_block(&mut self, block: &Block) -> bool {
128         self.check(block, Self::visit_block)
129     }
130
131     fn check_expr(&mut self, expr: &Expr) -> bool {
132         self.check(expr, Self::visit_expr)
133     }
134
135     fn check_stmt(&mut self, stmt: &Stmt) -> bool {
136         self.check(stmt, Self::visit_stmt)
137     }
138 }