+
Skip to content
This repository was archived by the owner on Aug 31, 2023. It is now read-only.

feat(rome_js_analyze): useIsNan rule #4059

Merged
merged 4 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions crates/rome_diagnostics_categories/src/categories.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ define_dategories! {
"lint/nursery/useEnumInitializers":"https://docs.rome.tools/lint/rules/useEnumInitializers",
"lint/nursery/useExhaustiveDependencies": "https://docs.rome.tools/lint/rules/useExhaustiveDependencies",
"lint/nursery/useExponentiationOperator": "https://docs.rome.tools/lint/rules/useExponentiationOperator",
"lint/nursery/useIsNan": "https://docs.rome.tools/lint/rules/useIsNan",
"lint/nursery/useNumericLiterals": "https://docs.rome.tools/lint/rules/useNumericLiterals",
"lint/nursery/useValidForDirection": "https://docs.rome.tools/lint/rules/useValidForDirection",
"lint/nursery/useHookAtTopLevel": "https://docs.rome.tools/lint/rules/useHookAtTopLevel",
Expand Down
3 changes: 2 additions & 1 deletion crates/rome_js_analyze/src/analyzers/nursery.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

182 changes: 182 additions & 0 deletions crates/rome_js_analyze/src/analyzers/nursery/use_is_nan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use rome_analyze::context::RuleContext;
use rome_analyze::{declare_rule, Ast, Rule, RuleDiagnostic};
use rome_js_syntax::{
AnyJsExpression, JsBinaryExpression, JsCaseClause, JsSwitchStatement, TextRange,
};
use rome_rowan::{declare_node_union, AstNode};

declare_rule! {
/// Require calls to `isNaN()` when checking for `NaN`.
///
/// In JavaScript, `NaN` is a special value of the `Number` type. It’s used to represent any of the "not-a-number" values represented by the double-precision 64-bit format as specified by the IEEE Standard for Binary Floating-Point Arithmetic.
///
/// Because `NaN` is unique in JavaScript by not being equal to anything, including itself, the results of comparisons to `NaN` are confusing:
/// - `NaN` === `NaN` or `NaN` == `NaN` evaluate to false
/// - `NaN` !== `NaN` or `NaN` != `NaN` evaluate to true
///
/// Therefore, use `Number.isNaN()` or global `isNaN()` functions to test whether a value is `NaN`.
///
/// Source: [use-isnan](https://eslint.org/docs/latest/rules/use-isnan).
///
/// ## Examples
///
/// ### Invalid
///
/// ```js,expect_diagnostic
/// 123 == NaN
/// ```
///
/// ```js,expect_diagnostic
/// 123 != NaN
/// ```
///
/// ```js,expect_diagnostic
/// switch(foo) { case (NaN): break; }
/// ```
///
/// ```js,expect_diagnostic
/// Number.NaN == "abc"
/// ```
///
/// ### Valid
///
/// ```js
/// if (isNaN(123) !== true) {}
///
/// foo(Number.NaN / 2)
///
/// switch(foo) {}
/// ```
///
pub(crate) UseIsNan {
version: "next",
name: "useIsNan",
recommended: true,
}
}

declare_node_union! {
pub(crate) UseIsNanQuery = JsBinaryExpression | JsCaseClause | JsSwitchStatement
}

enum Message {
BinaryExpression,
CaseClause,
SwitchCase,
}

pub struct RuleState {
range: TextRange,
message_id: Message,
}

impl Message {
fn as_str(&self) -> &str {
match self {
Self::BinaryExpression => "Use the isNaN function to compare with NaN.",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to compare against NaN.

Note: I am not a native speaker. So any native feel free to jump in and confirm this.

Copy link
Contributor Author

@kaioduarte kaioduarte Dec 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took that one from ESLint. I just checked it on Grammarly, and it didn't complain :P

Self::CaseClause => "'case NaN' can never match. Use Number.isNaN before the switch.",
Self::SwitchCase => "'switch(NaN)' can never match a case clause. Use Number.isNaN instead of the switch."
}
}
}

impl Rule for UseIsNan {
type Query = Ast<UseIsNanQuery>;
type State = RuleState;
type Signals = Option<Self::State>;
type Options = ();

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let node = ctx.query();

match node {
UseIsNanQuery::JsBinaryExpression(bin_expr) => {
if bin_expr.is_comparison_operator()
&& (has_nan(&bin_expr.left().ok()?)? || has_nan(&bin_expr.right().ok()?)?)
{
return Some(RuleState {
message_id: Message::BinaryExpression,
range: bin_expr.range(),
});
}
}
UseIsNanQuery::JsCaseClause(case_clause) => {
let test = case_clause.test().ok()?;

if has_nan(&test)? {
return Some(RuleState {
message_id: Message::CaseClause,
range: test.range(),
});
}
}
UseIsNanQuery::JsSwitchStatement(switch_stmt) => {
let discriminant = switch_stmt.discriminant().ok()?;

if has_nan(&discriminant)? {
return Some(RuleState {
message_id: Message::SwitchCase,
range: discriminant.range(),
});
}
}
}

None
}

fn diagnostic(_: &RuleContext<Self>, state: &Self::State) -> Option<RuleDiagnostic> {
Some(RuleDiagnostic::new(
rule_category!(),
state.range,
state.message_id.as_str(),
))
}
}

/// Checks whether an expression has `NaN`, `Number.NaN`, or `Number['NaN']`.
fn has_nan(expr: &AnyJsExpression) -> Option<bool> {
Some(match expr.clone().omit_parentheses() {
AnyJsExpression::JsIdentifierExpression(id_expr) => {
id_expr.name().ok()?.value_token().ok()?.text_trimmed() == "NaN"
}
AnyJsExpression::JsStaticMemberExpression(member_expr) => {
let is_number_object = member_expr
.object()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?
.text_trimmed()
== "Number";
let is_nan = member_expr
.member()
.ok()?
.as_js_name()?
.value_token()
.ok()?
.text_trimmed()
== "NaN";

is_number_object && is_nan
}
AnyJsExpression::JsComputedMemberExpression(member_expr) => {
let is_number_object = member_expr
.object()
.ok()?
.as_js_identifier_expression()?
.name()
.ok()?
.value_token()
.ok()?
.text_trimmed()
== "Number";
let is_member_nan = member_expr.member().ok()?.is_string_constant("NaN");

is_number_object && is_member_nan
}
_ => false,
})
}
58 changes: 58 additions & 0 deletions crates/rome_js_analyze/tests/specs/nursery/useIsNan/invalid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
123 == NaN;
123 === NaN;
NaN === "abc";
NaN == "abc";
123 != NaN;
123 !== NaN;
NaN !== "abc";
NaN != "abc";
NaN < "abc";
"abc" < NaN;
NaN > "abc";
"abc" > NaN;
NaN <= "abc";
"abc" <= NaN;
NaN >= "abc";
"abc" >= NaN;
123 == Number.NaN;
123 === Number.NaN;
Number.NaN === "abc";
Number.NaN == "abc";
123 != Number.NaN;
123 !== Number.NaN;
Number.NaN !== "abc";
Number.NaN != "abc";
Number.NaN < "abc";
"abc" < Number.NaN;
Number.NaN > "abc";
"abc" > Number.NaN;
Number.NaN <= "abc";
"abc" <= Number.NaN;
Number.NaN >= "abc";
"abc" >= Number.NaN;
x === Number?.NaN;
x === Number['NaN'];

// switch-case
switch(NaN) { case foo: break; }
switch(NaN) {}
switch(foo) { case NaN: break; }
switch(NaN) { default: break; }
switch(NaN) { case foo: break; default: break; }
switch(foo) { case NaN: }
switch(foo) { case (NaN): break; }
switch(foo) { case bar: break; case NaN: break; default: break; }
switch(foo) { case bar: case NaN: default: break; }
switch(foo) { case bar: break; case NaN: break; case baz: break; case NaN: break; }
switch(NaN) { case NaN: break; }
switch(foo) { case Number.NaN: break; }
switch(Number.NaN) { case foo: break; }
switch(Number.NaN) {}
switch(Number.NaN) { default: break; }
switch(Number.NaN) { case foo: break; default: break; }
switch(foo) { case Number.NaN: }
switch(foo) { case (Number.NaN): break; }
switch(foo) { case bar: break; case Number.NaN: break; default: break; }
switch(foo) { case bar: case Number.NaN: default: break; }
switch(foo) { case bar: break; case NaN: break; case baz: break; case Number.NaN: break; }
switch(Number.NaN) { case Number.NaN: break; }
Loading
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载