fix(linter): no-unused-expressions false positive with arrow fn expressions (#7585)

fixes https://github.com/oxc-project/oxc/issues/7584
This commit is contained in:
Cameron 2024-12-03 01:48:50 +00:00 committed by GitHub
parent 810671a4a0
commit 3dc46a80c9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 26 additions and 1 deletions

View file

@ -58,7 +58,9 @@ impl Rule for NoUnusedExpressions {
return;
};
if self.is_disallowed(&expression_stmt.expression) {
if self.is_disallowed(&expression_stmt.expression)
&& !is_parent_arrow_function_expression(node, ctx)
{
ctx.diagnostic(no_unused_expressions_diagnostic(expression_stmt.span));
}
}
@ -89,6 +91,20 @@ impl Rule for NoUnusedExpressions {
}
}
fn is_parent_arrow_function_expression<'a>(node: &AstNode<'a>, ctx: &LintContext<'a>) -> bool {
let Some(parent) = ctx.nodes().parent_node(node.id()) else { return false };
let AstKind::FunctionBody(_) = parent.kind() else { return false };
let Some(grand_parent) = ctx.nodes().parent_node(parent.id()) else { return false };
let AstKind::ArrowFunctionExpression(arrow_function_expression) = grand_parent.kind() else {
return false;
};
arrow_function_expression.expression
}
impl NoUnusedExpressions {
fn is_disallowed(&self, expr: &Expression) -> bool {
match expr {
@ -265,6 +281,7 @@ fn test() {
"foo ? import('./foo') : import('./bar');",
Some(serde_json::json!([{ "allowTernary": true }])),
),
("const _func = (value: number) => value + 1;", None),
];
let fail = vec![
@ -411,6 +428,7 @@ fn test() {
",
None,
),
("const _func = (value: number) => { value + 1; }", None),
];
Tester::new(NoUnusedExpressions::NAME, NoUnusedExpressions::CATEGORY, pass, fail)

View file

@ -200,3 +200,10 @@ source: crates/oxc_linter/src/tester.rs
4 │
╰────
help: Consider removing this expression
⚠ typescript-eslint(no-unused-expressions): Disallow unused expressions
╭─[no_unused_expressions.tsx:1:36]
1 │ const _func = (value: number) => { value + 1; }
· ──────────
╰────
help: Consider removing this expression