Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(linter): panic in no-else-return #6648

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions crates/oxc_linter/src/rules/eslint/no_else_return.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,14 @@ fn left_offset_for_whitespace(ctx: &LintContext, position: u32) -> u32 {
return position;
}

let chars = ctx.source_text()[..(position as usize)].chars().rev();
let offset = chars.take_while(|c| c.is_whitespace()).count();
let mut offset = 0;
for c in ctx.source_text()[..(position as usize)].chars().rev() {
if !c.is_whitespace() {
break;
}
offset += c.len_utf8();
}

debug_assert!(offset < u32::MAX as usize);
offset as u32
}
Expand Down Expand Up @@ -423,6 +429,7 @@ fn test() {
];

let fail = vec![
("if(0)return;else r", None),
("function foo1() { if (true) { return x; } else { return y; } }", None),
("function foo2() { if (true) { var x = bar; return x; } else { var y = baz; return y; } }", None),
("function foo3() { if (true) return x; else return y; }", None),
Expand Down Expand Up @@ -514,6 +521,7 @@ fn test() {
];

let fix = vec![
("if(0)return;else r", "if(0)return; r", None),
("function foo1() { if (true) { return x; } else { return y; } }", "function foo1() { if (true) { return x; } return y; }", None),
("function foo1() { if(true){ return x; }else{ return y; } }", "function foo1() { if(true){ return x; } return y; }", None),
("function foo2() { if (true) { var x = bar; return x; } else { var y = baz; return y; } }", "function foo2() { if (true) { var x = bar; return x; } var y = baz; return y; }", None),
Expand Down
9 changes: 9 additions & 0 deletions crates/oxc_linter/src/snapshots/no_else_return.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
---
source: crates/oxc_linter/src/tester.rs
---
⚠ eslint(no-else-return): Unnecessary 'else' after 'return'.
╭─[no_else_return.tsx:1:6]
1 │ if(0)return;else r
· ───┬─────┬──
· │ ╰── Making this `else` block unnecessary.
· ╰── This consequent block always returns,
╰────
help: Remove the `else` block, moving its contents outside of the `if` statement.

⚠ eslint(no-else-return): Unnecessary 'else' after 'return'.
╭─[no_else_return.tsx:1:31]
1 │ function foo1() { if (true) { return x; } else { return y; } }
Expand Down
Loading