|
1 | 1 | use crate::{AstNode, context::LintContext, rule::Rule}; |
2 | 2 | use oxc_ast::AstKind; |
3 | | -use oxc_ast::ast::{Statement, Statement::BlockStatement}; |
| 3 | +use oxc_ast::ast::{IfStatement, Statement}; |
4 | 4 | use oxc_diagnostics::OxcDiagnostic; |
5 | 5 | use oxc_macros::declare_oxc_lint; |
6 | 6 | use oxc_span::Span; |
7 | 7 |
|
8 | | -fn no_lonely_if_diagnostic(span: Span) -> OxcDiagnostic { |
| 8 | +fn no_lonely_if_diagnostic(lonely_if: &IfStatement) -> OxcDiagnostic { |
| 9 | + let span = Span::sized(lonely_if.span.start, 2); |
9 | 10 | OxcDiagnostic::warn("Unexpected `if` as the only statement in an `else` block") |
10 | 11 | .with_help("Consider using `else if` instead.") |
11 | 12 | .with_label(span) |
@@ -90,34 +91,28 @@ impl Rule for NoLonelyIf { |
90 | 91 | return; |
91 | 92 | }; |
92 | 93 |
|
93 | | - let Some(ref alternate) = if_stmt.alternate else { |
| 94 | + let Some(Statement::BlockStatement(alternate_block)) = &if_stmt.alternate else { |
94 | 95 | return; |
95 | 96 | }; |
96 | 97 |
|
97 | | - let BlockStatement(b) = alternate else { |
98 | | - return; |
99 | | - }; |
100 | | - |
101 | | - if b.body.len() != 1 { |
102 | | - return; |
103 | | - } |
104 | | - |
105 | | - let Some(only_stmt) = b.body.first() else { |
| 98 | + let [only_stmt] = alternate_block.body.as_slice() else { |
106 | 99 | return; |
107 | 100 | }; |
108 | 101 |
|
109 | 102 | if let Some(AstKind::IfStatement(_)) = ctx.nodes().parent_kind(node.id()) { |
110 | 103 | return; |
111 | 104 | } |
112 | 105 |
|
113 | | - if let Statement::BlockStatement(inner_block) = only_stmt { |
114 | | - if inner_block.body.len() == 1 { |
115 | | - if let Some(Statement::IfStatement(lonely_if)) = inner_block.body.first() { |
116 | | - ctx.diagnostic(no_lonely_if_diagnostic(Span::sized(lonely_if.span.start, 2))); |
| 106 | + match only_stmt { |
| 107 | + Statement::IfStatement(lonely_if) => { |
| 108 | + ctx.diagnostic(no_lonely_if_diagnostic(lonely_if)); |
| 109 | + } |
| 110 | + Statement::BlockStatement(inner_block) => { |
| 111 | + if let [Statement::IfStatement(lonely_if)] = inner_block.body.as_slice() { |
| 112 | + ctx.diagnostic(no_lonely_if_diagnostic(lonely_if)); |
117 | 113 | } |
118 | 114 | } |
119 | | - } else if let Statement::IfStatement(lonely_if) = only_stmt { |
120 | | - ctx.diagnostic(no_lonely_if_diagnostic(Span::sized(lonely_if.span.start, 2))); |
| 115 | + _ => {} |
121 | 116 | } |
122 | 117 | } |
123 | 118 | } |
|
0 commit comments