Skip to content

Commit

Permalink
fix(linter): panic in no-else-return (#6648)
Browse files Browse the repository at this point in the history
closes #6636
  • Loading branch information
shulaoda authored Oct 18, 2024
1 parent f4cdc56 commit a668397
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
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]
1if(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]
1function foo1() { if (true) { return x; } else { return y; } }
Expand Down

0 comments on commit a668397

Please sign in to comment.