Skip to content

Commit

Permalink
fix(linter): remove unsafe fixer of no-useless-spread (#6655)
Browse files Browse the repository at this point in the history
closes #6618

---------

Co-authored-by: Boshen <[email protected]>
shulaoda and Boshen authored Oct 28, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent 14f36ce commit 7aa496a
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions crates/oxc_linter/src/rules/unicorn/no_useless_spread/mod.rs
Original file line number Diff line number Diff line change
@@ -143,7 +143,7 @@ declare_oxc_lint!(
/// ```
NoUselessSpread,
correctness,
conditional_fix
fix_dangerous
);

impl Rule for NoUselessSpread {
@@ -380,26 +380,43 @@ fn check_useless_clone<'a>(
is_array: bool,
spread_elem: &SpreadElement<'a>,
ctx: &LintContext<'a>,
) -> bool {
) {
let span = Span::new(spread_elem.span.start, spread_elem.span.start + 3);
let target = spread_elem.argument.get_inner_expression();

// already diagnosed by first check
if matches!(target, Expression::ArrayExpression(_) | Expression::ObjectExpression(_)) {
return false;
return;
}

let hint = target.const_eval();
let hint_matches_expr = if is_array { hint.is_array() } else { hint.is_object() };
if hint_matches_expr {
let name = diagnostic_name(ctx, target);

// `[...new Array(1)]` -> `new Array(1).fill()`
if let Expression::NewExpression(new_expr) = target {
let is_array_constructor = new_expr
.callee
.without_parentheses()
.get_identifier_reference()
.is_some_and(|id| id.name == "Array");

if is_array_constructor && new_expr.arguments.len() == 1 {
ctx.diagnostic_with_fix(clone(span, is_array, name), |fixer| {
fixer.replace(
array_or_obj_span,
format!("{}.fill()", fixer.source_range(spread_elem.argument.span())),
)
});
return;
}
}

ctx.diagnostic_with_fix(clone(span, is_array, name), |fixer| {
fix_by_removing_array_spread(fixer, &array_or_obj_span, spread_elem)
});
return true;
}
false
}

fn diagnostic_name<'a>(ctx: &LintContext<'a>, expr: &Expression<'a>) -> Option<&'a str> {
@@ -725,6 +742,7 @@ fn test() {
// useless clones - simple arrays
("[...foo.map(x => !!x)]", "foo.map(x => !!x)"),
("[...new Array()]", "new Array()"),
("[...new Array(3)]", "new Array(3).fill()"),
("[...new Array(1, 2, 3)]", "new Array(1, 2, 3)"),
// useless clones - complex
(r"[...await Promise.all(foo)]", r"await Promise.all(foo)"),

0 comments on commit 7aa496a

Please sign in to comment.