-
-
Notifications
You must be signed in to change notification settings - Fork 722
feat: sort interface members #7553
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
Open
hamirmahal
wants to merge
3
commits into
biomejs:main
Choose a base branch
from
hamirmahal:feat/sort-interface-members
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+652
−50
Open
Changes from all commits
Commits
Show all changes
3 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
Some comments aren't visible on the classic Files Changed page.
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
16 changes: 16 additions & 0 deletions
16
crates/biome_cli/src/execute/migrate/eslint_any_rule_to_biome.rs
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
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
204 changes: 204 additions & 0 deletions
204
crates/biome_js_analyze/src/lint/nursery/use_sorted_interface_members.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,204 @@ | ||
use biome_analyze::{ | ||
Ast, FixKind, Rule, RuleAction, RuleDiagnostic, RuleSource, context::RuleContext, | ||
declare_lint_rule, | ||
}; | ||
|
||
use biome_console::markup; | ||
use biome_deserialize::TextRange; | ||
use biome_js_factory::make; | ||
use biome_js_syntax::{ | ||
AnyJsObjectMemberName, AnyTsTypeMember, TsInterfaceDeclaration, TsTypeMemberList, | ||
}; | ||
|
||
use crate::JsRuleAction; | ||
use biome_rowan::{AstNode, AstNodeList, BatchMutationExt}; | ||
use biome_string_case::comparable_token::ComparableToken; | ||
declare_lint_rule! { | ||
/// Sort interface members by key. | ||
/// | ||
/// Interface members are sorted according to their names. The rule distinguishes between | ||
/// two types of members: | ||
/// | ||
/// **Sortable members** - Members with explicit, fixed names that can be alphabetically sorted: | ||
/// - Property signatures: `property: type` | ||
/// - Method signatures: `method(): type` | ||
/// - Getter signatures: `get property(): type` | ||
/// - Setter signatures: `set property(value: type): void` | ||
/// | ||
/// **Non-sortable members** - Members without fixed names or with dynamic/computed names: | ||
/// - Call signatures: `(): type` (represents the interface as a callable function) | ||
/// - Construct signatures: `new (): type` (represents the interface as a constructor) | ||
/// - Index signatures: `[key: string]: type` (represents dynamic property access) | ||
/// | ||
/// The rule sorts all sortable members alphabetically and places them first, | ||
/// followed by non-sortable members in their original order. Non-sortable members | ||
/// cannot be meaningfully sorted by name since they represent different interface | ||
/// contracts rather than named properties or methods. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ## Invalid | ||
/// | ||
/// ```ts,expect_diagnostic | ||
/// interface MixedMembers { | ||
/// z: string; | ||
/// a: number; | ||
/// (): void; // Call signature | ||
/// y: boolean; | ||
/// new (): MixedMembers; // Construct signature | ||
/// b: string; | ||
/// [key: string]: any; // Index signature | ||
/// } | ||
/// ``` | ||
/// | ||
/// ## Valid | ||
/// | ||
/// ```ts | ||
/// interface MixedMembers { | ||
/// a: number; | ||
/// b: string; | ||
/// y: boolean; | ||
/// z: string; | ||
/// (): void; // Non-sortable members remain in original order | ||
/// new (): MixedMembers; | ||
/// [key: string]: any; | ||
/// } | ||
/// ``` | ||
/// | ||
pub UseSortedInterfaceMembers { | ||
version: "next", | ||
name: "useSortedInterfaceMembers", | ||
language: "ts", | ||
recommended: false, | ||
sources: &[RuleSource::EslintPerfectionist("sort-interfaces").inspired()], | ||
fix_kind: FixKind::Safe, | ||
} | ||
} | ||
impl Rule for UseSortedInterfaceMembers { | ||
hamirmahal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
type Query = Ast<TsInterfaceDeclaration>; | ||
type State = (); | ||
type Signals = Option<Self::State>; | ||
type Options = (); | ||
fn run(ctx: &RuleContext<Self>) -> Self::Signals { | ||
let interface = ctx.query(); | ||
let body = interface.members(); | ||
let comparator = ComparableToken::ascii_nat_cmp; | ||
|
||
if is_interface_members_sorted(&body, comparator) { | ||
None | ||
} else { | ||
Some(()) | ||
} | ||
} | ||
fn diagnostic(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<RuleDiagnostic> { | ||
let interface = ctx.query(); | ||
let body = interface.members(); | ||
|
||
Some(RuleDiagnostic::new( | ||
rule_category!(), | ||
body.range(), | ||
markup! { | ||
"The interface members are not sorted by key." | ||
}, | ||
)) | ||
} | ||
fn action(ctx: &RuleContext<Self>, (): &Self::State) -> Option<JsRuleAction> { | ||
let interface = ctx.query(); | ||
let list = interface.members(); | ||
let mut mutation = ctx.root().begin(); | ||
let comparator = ComparableToken::ascii_nat_cmp; | ||
let new_list = sort_interface_members(&list, comparator); | ||
mutation.replace_node(list, new_list); | ||
|
||
Some(RuleAction::new( | ||
ctx.metadata().action_category(ctx.category(), ctx.group()), | ||
ctx.metadata().applicability(), | ||
markup! { "Sort the interface members by key." }, | ||
mutation, | ||
)) | ||
} | ||
fn text_range(ctx: &RuleContext<Self>, _state: &Self::State) -> Option<TextRange> { | ||
Some(ctx.query().range()) | ||
} | ||
} | ||
fn get_type_member_name(member: &AnyTsTypeMember) -> Option<AnyJsObjectMemberName> { | ||
match member { | ||
// Property signatures have names | ||
AnyTsTypeMember::TsPropertySignatureTypeMember(prop) => prop.name().ok(), | ||
AnyTsTypeMember::TsMethodSignatureTypeMember(method) => method.name().ok(), | ||
AnyTsTypeMember::TsGetterSignatureTypeMember(getter) => getter.name().ok(), | ||
AnyTsTypeMember::TsSetterSignatureTypeMember(setter) => setter.name().ok(), | ||
// Call signatures, construct signatures, and index signatures don't have sortable names | ||
_ => None, | ||
} | ||
} | ||
fn is_interface_members_sorted( | ||
list: &TsTypeMemberList, | ||
comparator: impl Fn(&ComparableToken, &ComparableToken) -> std::cmp::Ordering, | ||
) -> bool { | ||
use std::cmp::Ordering; | ||
let mut prev_key: Option<ComparableToken> = None; | ||
let mut saw_non_sortable = false; | ||
|
||
for member in list.iter() { | ||
if let Some(name) = get_type_member_name(&member) | ||
&& let Some(token_text) = name.name() | ||
{ | ||
if saw_non_sortable { | ||
// sortable member found after a non-sortable | ||
return false; | ||
} | ||
|
||
let current = ComparableToken::new(token_text); | ||
|
||
if let Some(prev) = &prev_key | ||
&& comparator(prev, ¤t) == Ordering::Greater | ||
{ | ||
return false; | ||
} | ||
|
||
prev_key = Some(current); | ||
|
||
continue; | ||
} | ||
|
||
// Non-sortable member | ||
saw_non_sortable = true; | ||
} | ||
true | ||
} | ||
fn sort_interface_members( | ||
list: &TsTypeMemberList, | ||
comparator: impl Fn(&ComparableToken, &ComparableToken) -> std::cmp::Ordering, | ||
) -> TsTypeMemberList { | ||
let mut sortable_members = Vec::new(); | ||
let mut non_sortable_members = Vec::new(); | ||
|
||
// Separate sortable from non-sortable members | ||
for member in list.iter() { | ||
if let Some(name) = get_type_member_name(&member) { | ||
if let Some(token_text) = name.name() { | ||
sortable_members.push((member, ComparableToken::new(token_text))); | ||
} else { | ||
// Name exists but is not sortable (computed/dynamic) | ||
non_sortable_members.push(member); | ||
} | ||
} else { | ||
// No name (call signatures, construct signatures, index signatures) | ||
non_sortable_members.push(member); | ||
} | ||
} | ||
|
||
// Sort the sortable members | ||
sortable_members.sort_by(|(_, a), (_, b)| comparator(a, b)); | ||
|
||
// Combine: all sortable members first, then all non-sortable members | ||
let mut new_members: Vec<AnyTsTypeMember> = sortable_members | ||
.into_iter() | ||
.map(|(member, _)| member) | ||
.collect(); | ||
|
||
new_members.extend(non_sortable_members); | ||
|
||
make::ts_type_member_list(new_members) | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
11 changes: 11 additions & 0 deletions
11
...s/biome_js_analyze/tests/specs/nursery/useSortedInterfaceMembers/multiple_non_sortable.ts
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,11 @@ | ||
interface MultipleNonSortableInterface { | ||
zProperty: string; | ||
aProperty: number; | ||
new (): any; // Construct signature | ||
(): void; // Call signature | ||
yMethod(): boolean; | ||
[index: number]: string; // Index signature with number | ||
bMethod(): string; | ||
[key: string]: any; // Index signature with string | ||
cField: object; | ||
} |
63 changes: 63 additions & 0 deletions
63
...me_js_analyze/tests/specs/nursery/useSortedInterfaceMembers/multiple_non_sortable.ts.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,63 @@ | ||
--- | ||
source: crates/biome_js_analyze/tests/spec_tests.rs | ||
expression: multiple_non_sortable.ts | ||
--- | ||
# Input | ||
```ts | ||
interface MultipleNonSortableInterface { | ||
zProperty: string; | ||
aProperty: number; | ||
new (): any; // Construct signature | ||
(): void; // Call signature | ||
yMethod(): boolean; | ||
[index: number]: string; // Index signature with number | ||
bMethod(): string; | ||
[key: string]: any; // Index signature with string | ||
cField: object; | ||
} | ||
|
||
``` | ||
|
||
# Diagnostics | ||
``` | ||
multiple_non_sortable.ts:2:2 lint/nursery/useSortedInterfaceMembers FIXABLE ━━━━━━━━━━━━━━━━━━━━━━ | ||
|
||
i The interface members are not sorted by key. | ||
|
||
1 │ interface MultipleNonSortableInterface { | ||
> 2 │ zProperty: string; | ||
│ ^^^^^^^^^^^^^^^^^^ | ||
> 3 │ aProperty: number; | ||
> 4 │ new (): any; // Construct signature | ||
... | ||
> 9 │ [key: string]: any; // Index signature with string | ||
> 10 │ cField: object; | ||
│ ^^^^^^^^^^^^^^^ | ||
11 │ } | ||
12 │ | ||
|
||
i Safe fix: Sort the interface members by key. | ||
|
||
1 1 │ interface MultipleNonSortableInterface { | ||
2 │ - → zProperty:·string; | ||
3 │ - → aProperty:·number; | ||
4 │ - → new·():·any;··//·Construct·signature | ||
2 │ + → aProperty:·number; | ||
3 │ + → bMethod():·string; | ||
4 │ + → cField:·object; | ||
5 │ + → yMethod():·boolean; | ||
6 │ + → zProperty:·string; | ||
7 │ + → new·():·any;··//·Construct·signature | ||
5 8 │ (): void; // Call signature | ||
6 │ - → yMethod():·boolean; | ||
7 │ - → [index:·number]:·string;··//·Index·signature·with·number | ||
8 │ - → bMethod():·string; | ||
9 │ - → [key:·string]:·any;··//·Index·signature·with·string | ||
10 │ - → cField:·object; | ||
9 │ + → [index:·number]:·string;··//·Index·signature·with·number | ||
10 │ + → [key:·string]:·any; | ||
11 11 │ } | ||
12 12 │ | ||
|
||
|
||
``` |
7 changes: 7 additions & 0 deletions
7
...e_js_analyze/tests/specs/nursery/useSortedInterfaceMembers/sortable_after_non_sortable.ts
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,7 @@ | ||
interface BadlyOrderedInterface { | ||
aProperty: string; | ||
[index: number]: any; // Non-sortable index signature | ||
bProperty: number; // This should trigger an error - sortable after non-sortable | ||
(): void; // Call signature | ||
cProperty: boolean; // This should also trigger an error | ||
} |
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.
Fix incorrect TextRange import (compile error)
TextRange comes from biome_rowan, not biome_deserialize.
Apply this diff:
📝 Committable suggestion
🤖 Prompt for AI Agents
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.
All checks have passed
without this suggestion.