This repository was archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 653
feat(rome_js_analyze): useIsNan
rule
#4059
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
182 changes: 182 additions & 0 deletions
182
crates/rome_js_analyze/src/analyzers/nursery/use_is_nan.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.", | ||
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
58
crates/rome_js_analyze/tests/specs/nursery/useIsNan/invalid.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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