From 5fc465352fbda8f3adceb891b17b338362f5177c Mon Sep 17 00:00:00 2001 From: Don Isaac Date: Sat, 10 Aug 2024 18:18:29 -0400 Subject: [PATCH] fix(linter/no-unused-vars): do not delete function expressions when fixing --- .../eslint/no_unused_vars/fixers/fix_vars.rs | 9 +++++++- .../rules/eslint/no_unused_vars/tests/oxc.rs | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs index 6a728f95c7b951..cc00a86ad9c8cb 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/fixers/fix_vars.rs @@ -1,4 +1,7 @@ -use oxc_ast::{ast::VariableDeclarator, AstKind}; +use oxc_ast::{ + ast::{Expression, VariableDeclarator}, + AstKind, +}; use oxc_semantic::{AstNode, AstNodeId}; use oxc_span::CompactStr; use regex::Regex; @@ -20,6 +23,10 @@ impl NoUnusedVars { decl: &VariableDeclarator<'a>, decl_id: AstNodeId, ) -> RuleFix<'a> { + if decl.init.as_ref().is_some_and(Expression::is_function) { + return fixer.noop(); + } + let Some(AstKind::VariableDeclaration(declaration)) = symbol.nodes().parent_node(decl_id).map(AstNode::kind) else { diff --git a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs index daed9201cbfe30..17b79051ee4495 100644 --- a/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs +++ b/crates/oxc_linter/src/rules/eslint/no_unused_vars/tests/oxc.rs @@ -89,6 +89,20 @@ fn test_vars_simple() { None, FixKind::DangerousSuggestion, ), + // function expressions do not get changed + (r"const foo = () => {}", r"const foo = () => {}", None, FixKind::DangerousSuggestion), + ( + r"const foo = function() {}", + r"const foo = function() {}", + None, + FixKind::DangerousSuggestion, + ), + ( + r"const foo = function foo() {}", + r"const foo = function foo() {}", + None, + FixKind::DangerousSuggestion, + ), // vars with references get renamed ("let x = 1; x = 2;", "let _x = 1; _x = 2;", None, FixKind::DangerousFix), ( @@ -279,8 +293,10 @@ fn test_vars_destructure() { ]; let fix = vec![ + // single destructure ("const { a } = obj;", "", None, FixKind::DangerousSuggestion), ("const [a] = arr;", "", None, FixKind::DangerousSuggestion), + // multi destructure ( "const { a, b } = obj; f(b)", "const { b } = obj; f(b)", @@ -313,6 +329,13 @@ fn test_vars_destructure() { None, FixKind::DangerousSuggestion, ), + // multi destructure with rename + ( + "const { a: foo, b: bar } = obj; f(bar)", + "const { b: bar } = obj; f(bar)", + None, + FixKind::DangerousSuggestion, + ), // renaming // ( // "let a = 1; a = 2;",