Skip to content

Commit

Permalink
fix(linter): no-unused-expressions false positive with arrow fn expre…
Browse files Browse the repository at this point in the history
…ssions
  • Loading branch information
camc314 committed Dec 2, 2024
1 parent 33e5a49 commit 011a017
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
20 changes: 19 additions & 1 deletion crates/oxc_linter/src/rules/typescript/no_unused_expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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![
Expand Down Expand Up @@ -411,6 +428,7 @@ fn test() {
",
None,
),
("const _func = (value: number) => { value + 1; }", None),
];

Tester::new(NoUnusedExpressions::NAME, NoUnusedExpressions::CATEGORY, pass, fail)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 011a017

Please sign in to comment.