Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 55 additions & 5 deletions crates/oxc_linter/src/rules/eslint/no_compare_neg_zero.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use oxc_ast::{ast::Expression, AstKind};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use oxc_span::{GetSpan, Span};
use oxc_syntax::operator::{BinaryOperator, UnaryOperator};

use crate::{context::LintContext, rule::Rule, AstNode};
Expand Down Expand Up @@ -29,7 +29,8 @@ declare_oxc_lint!(
/// if (x === -0) {}
/// ```
NoCompareNegZero,
correctness
correctness,
conditional_suggestion_fix
);

impl Rule for NoCompareNegZero {
Expand All @@ -39,8 +40,41 @@ impl Rule for NoCompareNegZero {
};
if Self::should_check(expr.operator) {
let op = expr.operator.as_str();
if is_neg_zero(&expr.left) || is_neg_zero(&expr.right) {
ctx.diagnostic(no_compare_neg_zero_diagnostic(op, expr.span));
let is_left_neg_zero = is_neg_zero(&expr.left);
let is_right_neg_zero = is_neg_zero(&expr.right);
if is_left_neg_zero || is_right_neg_zero {
if expr.operator == BinaryOperator::StrictEquality {
ctx.diagnostic_with_suggestion(
no_compare_neg_zero_diagnostic(op, expr.span),
|fixer| {
// replace `x === -0` with `Object.is(x, -0)`
let value = if is_left_neg_zero {
ctx.source_range(expr.right.span())
} else {
ctx.source_range(expr.left.span())
};
fixer.replace(expr.span, format!("Object.is({value}, -0)"))
},
);
} else {
// <https://tc39.es/ecma262/#%E2%84%9D>
// <https://tc39.es/ecma262/#sec-numeric-types-number-lessThan>
// The mathematical value of +0𝔽 and -0𝔽 is the mathematical value 0.
// It's safe to replace -0 with 0
ctx.diagnostic_with_fix(
no_compare_neg_zero_diagnostic(op, expr.span),
|fixer| {
let start = if is_left_neg_zero {
expr.left.span().start
} else {
expr.right.span().start
};
let end = start + 1;
let span = Span::new(start, end);
fixer.delete(&span)
},
);
}
}
}
}
Expand Down Expand Up @@ -117,5 +151,21 @@ fn test() {
("-0n <= x", None),
];

Tester::new(NoCompareNegZero::NAME, pass, fail).test_and_snapshot();
let fix = vec![
("x === -0", "Object.is(x, -0)", None),
("-0 === x", "Object.is(x, -0)", None),
("x == -0", "x == 0", None),
("-0 == x", "0 == x", None),
("x > -0", "x > 0", None),
("-0 > x", "0 > x", None),
("x >= -0", "x >= 0", None),
("-0 >= x", "0 >= x", None),
("x < -0", "x < 0", None),
("-0 < x", "0 < x", None),
("x <= -0", "x <= 0", None),
("-0 <= x", "0 <= x", None),
("-0n <= x", "0n <= x", None),
];

Tester::new(NoCompareNegZero::NAME, pass, fail).expect_fix(fix).test_and_snapshot();
}