-
-
Notifications
You must be signed in to change notification settings - Fork 723
feat(linter): add unicorn/no-array-sort rule
#14117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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
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
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 oxc_ast::{ | ||
| AstKind, | ||
| ast::{Argument, ArrayExpressionElement, Expression}, | ||
| }; | ||
| use oxc_diagnostics::OxcDiagnostic; | ||
| use oxc_macros::declare_oxc_lint; | ||
| use oxc_span::Span; | ||
| use serde_json::Value; | ||
|
|
||
| use crate::{AstNode, context::LintContext, rule::Rule}; | ||
|
|
||
| fn no_array_sort_diagnostic(span: Span) -> OxcDiagnostic { | ||
| OxcDiagnostic::warn("Use `Array#toSorted()` instead of `Array#sort()`.") | ||
| .with_help("`Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original.") | ||
| .with_label(span) | ||
| } | ||
|
|
||
| #[derive(Debug, Clone)] | ||
| pub struct NoArraySort { | ||
| allow_expression_statement: bool, | ||
| } | ||
|
|
||
| impl Default for NoArraySort { | ||
| fn default() -> Self { | ||
| Self { allow_expression_statement: true } | ||
| } | ||
| } | ||
|
|
||
| declare_oxc_lint!( | ||
| /// ### What it does | ||
| /// | ||
| /// Prefer using `Array#toSorted()` over `Array#sort()`. | ||
| /// | ||
| /// ### Why is this bad? | ||
| /// | ||
| /// `Array#sort()` modifies the original array in place, which can lead to unintended side effects—especially | ||
| /// when the original array is used elsewhere in the code. | ||
| /// | ||
| /// ### Examples | ||
| /// | ||
| /// Examples of **incorrect** code for this rule: | ||
| /// ```js | ||
| /// const sorted = [...array].sort(); | ||
| /// ``` | ||
| /// | ||
| /// Examples of **correct** code for this rule: | ||
| /// ```js | ||
| /// const sorted = [...array].toSorted(); | ||
| /// ``` | ||
| /// | ||
| /// ### Options | ||
| /// | ||
| /// #### allowExpressionStatement | ||
| /// | ||
| /// `{ type: boolean, default: true }` | ||
| /// | ||
| /// This rule allows `array.sort()` as an expression statement by default, | ||
| /// Pass allowExpressionStatement: false to forbid `Array#sort()` even if it's an expression statement. | ||
| /// | ||
| /// Examples of **incorrect** code for this rule with the `{ "allowExpressionStatement": false }` option: | ||
| /// ```js | ||
| /// array.sort(); | ||
| /// ``` | ||
| NoArraySort, | ||
| unicorn, | ||
| suspicious, | ||
| fix, | ||
| ); | ||
|
|
||
| impl Rule for NoArraySort { | ||
| fn from_configuration(value: Value) -> Self { | ||
| Self { | ||
| allow_expression_statement: value | ||
| .get(0) | ||
| .and_then(|v| v.get("allowExpressionStatement")) | ||
| .and_then(Value::as_bool) | ||
| .unwrap_or(true), | ||
| } | ||
| } | ||
|
|
||
| fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { | ||
| let AstKind::CallExpression(call_expr) = node.kind() else { | ||
| return; | ||
| }; | ||
| if call_expr.optional { | ||
| return; | ||
| } | ||
| if call_expr.arguments.len() > 1 { | ||
| return; | ||
| } | ||
| if call_expr.arguments.len() == 1 | ||
| && matches!(call_expr.arguments[0], Argument::SpreadElement(_)) | ||
| { | ||
| return; | ||
| } | ||
| let Some(member_expr) = call_expr.callee.get_member_expr() else { | ||
| return; | ||
| }; | ||
| let Some((span, static_property_name)) = member_expr.static_property_info() else { | ||
| return; | ||
| }; | ||
| if static_property_name != "sort" { | ||
| return; | ||
| } | ||
|
|
||
| let is_spread = match member_expr.object() { | ||
| Expression::ArrayExpression(array) => { | ||
| array.elements.len() == 1 | ||
| && matches!(array.elements[0], ArrayExpressionElement::SpreadElement(_)) | ||
| } | ||
| _ => false, | ||
| }; | ||
|
|
||
| if self.allow_expression_statement && !is_spread { | ||
| let parent = ctx.nodes().parent_node(node.id()); | ||
| let parent_is_expression_statement = match parent.kind() { | ||
| AstKind::ExpressionStatement(_) => true, | ||
| AstKind::ChainExpression(_) => { | ||
| let grand_parent = ctx.nodes().parent_node(parent.id()); | ||
| matches!(grand_parent.kind(), AstKind::ExpressionStatement(_)) | ||
| } | ||
| _ => false, | ||
| }; | ||
| if parent_is_expression_statement { | ||
| return; | ||
| } | ||
| } | ||
|
|
||
| ctx.diagnostic_with_fix(no_array_sort_diagnostic(span), |fixer| { | ||
| fixer.replace(span, "toSorted") | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn test() { | ||
| use crate::tester::Tester; | ||
|
|
||
| let pass = vec![ | ||
| ("sorted = [...array].toSorted()", None), | ||
| ("sorted = array.toSorted()", None), | ||
| ("sorted = [...array].sort", None), | ||
| ("sorted = [...array].sort?.()", None), | ||
| ("array.sort()", None), | ||
| ("array.sort?.()", None), | ||
| ("array?.sort()", None), | ||
| ("if (true) array.sort()", None), | ||
| ("sorted = array.sort(...[])", None), | ||
| ("sorted = array.sort(...[compareFn])", None), | ||
| ("sorted = array.sort(compareFn, extraArgument)", None), | ||
| ]; | ||
|
|
||
| let fail = vec![ | ||
| ("sorted = [...array].sort()", None), | ||
| ("sorted = [...array]?.sort()", None), | ||
| ("sorted = array.sort()", None), | ||
| ("sorted = array?.sort()", None), | ||
| ("sorted = [...array].sort(compareFn)", None), | ||
| ("sorted = [...array]?.sort(compareFn)", None), | ||
| ("sorted = array.sort(compareFn)", None), | ||
| ("sorted = array?.sort(compareFn)", None), | ||
| ("array.sort()", Some(serde_json::json!([{"allowExpressionStatement": false}]))), | ||
| ("array?.sort()", Some(serde_json::json!([{"allowExpressionStatement": false}]))), | ||
| ("[...array].sort()", Some(serde_json::json!([{"allowExpressionStatement": false}]))), | ||
| ("sorted = [...(0, array)].sort()", None), | ||
| ]; | ||
|
|
||
| let fix = vec![ | ||
| ("sorted = [...array].sort()", "sorted = [...array].toSorted()", None), | ||
| ("sorted = [...array]?.sort()", "sorted = [...array]?.toSorted()", None), | ||
| ( | ||
| "a.sort()", | ||
| "a.toSorted()", | ||
| Some(serde_json::json!([{"allowExpressionStatement": false}])), | ||
| ), | ||
| ("sorted = array?.sort()", "sorted = array?.toSorted()", None), | ||
| ]; | ||
|
|
||
| Tester::new(NoArraySort::NAME, NoArraySort::PLUGIN, pass, fail) | ||
| .expect_fix(fix) | ||
| .test_and_snapshot(); | ||
| } | ||
86 changes: 86 additions & 0 deletions
86
crates/oxc_linter/src/snapshots/unicorn_no_array_sort.snap
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,86 @@ | ||
| --- | ||
| source: crates/oxc_linter/src/tester.rs | ||
| --- | ||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:21] | ||
| 1 │ sorted = [...array].sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:22] | ||
| 1 │ sorted = [...array]?.sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:16] | ||
| 1 │ sorted = array.sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:17] | ||
| 1 │ sorted = array?.sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:21] | ||
| 1 │ sorted = [...array].sort(compareFn) | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:22] | ||
| 1 │ sorted = [...array]?.sort(compareFn) | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:16] | ||
| 1 │ sorted = array.sort(compareFn) | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:17] | ||
| 1 │ sorted = array?.sort(compareFn) | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:7] | ||
| 1 │ array.sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:8] | ||
| 1 │ array?.sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:12] | ||
| 1 │ [...array].sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. | ||
|
|
||
| ⚠ eslint-plugin-unicorn(no-array-sort): Use `Array#toSorted()` instead of `Array#sort()`. | ||
| ╭─[no_array_sort.tsx:1:26] | ||
| 1 │ sorted = [...(0, array)].sort() | ||
| · ──── | ||
| ╰──── | ||
| help: `Array#sort()` mutates the original array. Use `Array#toSorted()` to return a new sorted array without modifying the original. |
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.
Uh oh!
There was an error while loading. Please reload this page.