Skip to content
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

feat(biome_js_analyze): add useSortedKeys assist rule #5079

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
51 changes: 51 additions & 0 deletions .changeset/add_the_new_js_assist_rule_use_sorted_keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
"@biomejs/biome": minor
---

Add a new JS assist rule - `useSortedKeys` which enforces ordering of a JS object properties.
This rule will consider spread/calculated keys e.g `[k]: 1` as non-sortable.
Instead, whenever it encounters a non-sortable key, it will sort all the
previous sortable keys up until the nearest non-sortable key, if one exist.
This prevents breaking the override of certain keys using spread keys.

Source: https://perfectionist.dev/rules/sort-objects

```js
// Base
// from
const obj = {
b: 1,
a: 1,
...g,
ba: 2,
ab: 1,
set aab(v) {
this._aab = v;
},
[getProp()]: 2,
aba: 2,
abc: 3,
abb: 3,
get aaa() {
return "";
},
};
// to
const obj = {
a: 1,
b: 1,
...g,
set aab(v) {
this._aab = v;
},
ab: 1,
ba: 2,
[getProp()]: 2,
get aaa() {
return "";
},
aba: 2,
abb: 3,
abc: 3,
};
```
3 changes: 2 additions & 1 deletion crates/biome_js_analyze/src/assist/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
use biome_analyze::declare_assist_group;
pub mod organize_imports;
pub mod use_sorted_attributes;
declare_assist_group! { pub Source { name : "source" , rules : [self :: organize_imports :: OrganizeImports , self :: use_sorted_attributes :: UseSortedAttributes ,] } }
pub mod use_sorted_keys;
declare_assist_group! { pub Source { name : "source" , rules : [self :: organize_imports :: OrganizeImports , self :: use_sorted_attributes :: UseSortedAttributes , self :: use_sorted_keys :: UseSortedKeys ,] } }
185 changes: 185 additions & 0 deletions crates/biome_js_analyze/src/assist/source/use_sorted_keys.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
use std::borrow::Cow;
use std::cmp::Ordering;

use biome_analyze::{context::RuleContext, declare_source_rule, Ast, Rule, RuleAction};
use biome_console::markup;
use biome_diagnostics::Applicability;
use biome_js_syntax::{AnyJsObjectMember, AnyJsObjectMemberName, JsObjectMemberList};
use biome_rowan::{AstSeparatedList, BatchMutationExt, SyntaxResult};

use crate::JsRuleAction;

declare_source_rule! {
/// Enforce ordering of a JS object properties.
///
/// This rule checks if keys of the object are sorted in a consistent way.
/// Keys are sorted in a natural order.
/// This rule will consider spread/calculated keys e.g [k]: 1 as non-sortable.
/// Instead, whenever it encounters a non-sortable key, it will sort all the
/// previous sortable keys up until the nearest non-sortable key, if one
/// exist.
/// This prevents breaking the override of certain keys using spread
/// keys.
///
/// Source: https://perfectionist.dev/rules/sort-objects
///
/// ## Examples
///
/// ```js,expect_diff
/// {
/// x: 1,
/// a: 2,
/// };
/// ```
///
/// ```js,expect_diff
/// {
/// x: 1,
/// ...f,
/// y: 4,
/// a: 2,
/// [calculated()]: true,
/// b: 3,
/// a: 1,
/// };
/// ```
///
/// ```js,expect_diff
/// {
/// get aab() {
/// return this._aab;
/// },
/// set aac(v) {
/// this._aac = v;
/// },
/// w: 1,
/// x: 1,
/// ...g,
/// get aaa() {
/// return "";
/// },
/// u: 1,
/// v: 1,
/// [getProp()]: 2,
/// o: 1,
/// p: 1,
/// q: 1,
/// }
/// ```
pub UseSortedKeys {
version: "next",
name: "useSortedKeys",
language: "js",
recommended: false,
}
}

impl Rule for UseSortedKeys {
type Query = Ast<JsObjectMemberList>;
type State = Vec<Vec<ObjectMember>>;
type Signals = Option<Self::State>;
type Options = ();

fn run(ctx: &RuleContext<Self>) -> Self::Signals {
let mut members = vec![];
let mut groups = vec![];

let get_name =
|name: SyntaxResult<AnyJsObjectMemberName>| Some(name.ok()?.name()?.text().to_string());

for element in ctx.query().elements() {
if let Ok(element) = element.node() {
match element {
AnyJsObjectMember::JsSpread(_) | AnyJsObjectMember::JsBogusMember(_) => {
// Keep the spread order because it's not safe to change order of it.
// Logic here is similar to /crates/biome_js_analyze/src/assists/source/use_sorted_attributes.rs
groups.push(members.clone());
members.clear();
members.push(ObjectMember::new(element.clone(), None));
}
AnyJsObjectMember::JsPropertyObjectMember(member) => {
members.push(ObjectMember::new(element.clone(), get_name(member.name())));
}
AnyJsObjectMember::JsGetterObjectMember(member) => {
members.push(ObjectMember::new(element.clone(), get_name(member.name())));
}
AnyJsObjectMember::JsSetterObjectMember(member) => {
members.push(ObjectMember::new(element.clone(), get_name(member.name())));
}
AnyJsObjectMember::JsMethodObjectMember(member) => {
members.push(ObjectMember::new(element.clone(), get_name(member.name())));
}
AnyJsObjectMember::JsShorthandPropertyObjectMember(member) => {
let name = member
.name()
.ok()
.map(|name| Some(name.name().ok()?.text().to_string()))
.unwrap_or_default();

members.push(ObjectMember::new(element.clone(), name));
}
}
}
}

if !members.is_empty() {
groups.push(members);
}

Some(groups)
}

fn action(ctx: &RuleContext<Self>, state: &Self::State) -> Option<JsRuleAction> {
let mut sorted_state = state.clone();

for group in sorted_state.iter_mut() {
group.sort();
}

if sorted_state == *state {
return None;
}

let mut mutation = ctx.root().begin();

for (unsorted, sorted) in state.iter().flatten().zip(sorted_state.iter().flatten()) {
mutation.replace_node(unsorted.member.clone(), sorted.member.clone());
}

Some(RuleAction::new(
rule_action_category!(),
Applicability::Always,
markup! { "Sort the object properties." },
mutation,
))
}
}

#[derive(PartialEq, Eq, Clone)]
pub struct ObjectMember {
member: AnyJsObjectMember,
name: Option<String>,
}

impl ObjectMember {
fn new(member: AnyJsObjectMember, name: Option<String>) -> Self {
ObjectMember { member, name }
}
}

impl Ord for ObjectMember {
fn cmp(&self, other: &Self) -> Ordering {
// If some doesn't have a name (e.g spread/calculated property) - keep the order.
let (Some(self_name), Some(other_name)) = (&self.name, &other.name) else {
return Ordering::Equal;
};

natord::compare(self_name, other_name)
}
}

impl PartialOrd for ObjectMember {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
2 changes: 2 additions & 0 deletions crates/biome_js_analyze/src/options.rs

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

20 changes: 20 additions & 0 deletions crates/biome_js_analyze/tests/specs/source/useSortedKeys/sorted.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const obj = {
get aab() {
return this._aab;
},
set aac(v) {
this._aac = v;
},
w: 1,
x: 1,
...g,
get aaa() {
return "";
},
u: 1,
v: 1,
[getProp()]: 2,
o: 1,
p: 1,
q: 1,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: sorted.js
---
# Input
```js
const obj = {
get aab() {
return this._aab;
},
set aac(v) {
this._aac = v;
},
w: 1,
x: 1,
...g,
get aaa() {
return "";
},
u: 1,
v: 1,
[getProp()]: 2,
o: 1,
p: 1,
q: 1,
};

```
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const obj = {
b: 1,
a: 1,
...g,
ba: 2,
ab: 1,
set aab(v) {
this._aab = v;
},
[getProp()]: 2,
aba: 2,
abc: 3,
abb: 3,
get aaa() {
return "";
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
source: crates/biome_js_analyze/tests/spec_tests.rs
expression: unsorted.js
---
# Input
```js
const obj = {
b: 1,
a: 1,
...g,
ba: 2,
ab: 1,
set aab(v) {
this._aab = v;
},
[getProp()]: 2,
aba: 2,
abc: 3,
abb: 3,
get aaa() {
return "";
},
};

```

# Actions
```diff
@@ -1,17 +1,17 @@
const obj = {
+ a: 1,
b: 1,
- a: 1,
...g,
- ba: 2,
- ab: 1,
set aab(v) {
this._aab = v;
},
+ ab: 1,
+ ba: 2,
[getProp()]: 2,
- aba: 2,
- abc: 3,
- abb: 3,
get aaa() {
return "";
},
+ aba: 2,
+ abb: 3,
+ abc: 3,
};

```
Loading