Skip to content

Commit d29bbb2

Browse files
authored
refactor(linter): simplify implementation of eslint/no-lonely-if (#11550)
1 parent d41fb13 commit d29bbb2

File tree

1 file changed

+13
-18
lines changed

1 file changed

+13
-18
lines changed

crates/oxc_linter/src/rules/eslint/no_lonely_if.rs

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
use crate::{AstNode, context::LintContext, rule::Rule};
22
use oxc_ast::AstKind;
3-
use oxc_ast::ast::{Statement, Statement::BlockStatement};
3+
use oxc_ast::ast::{IfStatement, Statement};
44
use oxc_diagnostics::OxcDiagnostic;
55
use oxc_macros::declare_oxc_lint;
66
use oxc_span::Span;
77

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);
910
OxcDiagnostic::warn("Unexpected `if` as the only statement in an `else` block")
1011
.with_help("Consider using `else if` instead.")
1112
.with_label(span)
@@ -90,34 +91,28 @@ impl Rule for NoLonelyIf {
9091
return;
9192
};
9293

93-
let Some(ref alternate) = if_stmt.alternate else {
94+
let Some(Statement::BlockStatement(alternate_block)) = &if_stmt.alternate else {
9495
return;
9596
};
9697

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 {
10699
return;
107100
};
108101

109102
if let Some(AstKind::IfStatement(_)) = ctx.nodes().parent_kind(node.id()) {
110103
return;
111104
}
112105

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));
117113
}
118114
}
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+
_ => {}
121116
}
122117
}
123118
}

0 commit comments

Comments
 (0)