feat(editor): Rearrange Code for TypeScript and JavaScript classes (#7607)

Rearrange Code orders the methods of TypeScript, TSX, JavaScript and JSX classes: the constructor, static methods, then instance methods, each public, protected, then private. Fields and static blocks before the first method stay put; methods move with their decorators and comments; adjacent overloads and accessor pairs move as one block. Classes where moving could change behaviour (fields or static blocks among methods, computed names, decorators naming other methods, region markers) are left alone.

Closes #7599
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-03 05:53:04 +08:00
1 джерело af2e515d0f
коміт 41f4e22b29
6 files changed
+306 -25

No files matched your search

+2 -2
Переглянути файл
@@ -236,8 +236,8 @@ pub async fn doc_python_facts(host: &Host, window: &str, doc: DocId) -> IdeResul
blocking(move || Ok(syntax.python_facts(&snap.language, &snap.text))).await
}
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python
/// for now); none when they already are or the language has no arrangement.
/// Rearrange Code: the edits that put the document's class members in arrangement order (Python,
/// TypeScript and JavaScript); none when they already are or the language has no arrangement.
#[command(trust = always)]
pub async fn doc_rearrange(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<TextEdit>> {
let project = host.project(window)?;
+292 -19
Переглянути файл
@@ -1,10 +1,18 @@
//! Rearrange Code: class members in arrangement order. Python only for now: within each class,
//! `__new__` / `__init__` / `__post_init__`, other dunder methods, public, `_protected`, then
//! `__private` methods, each group in its original order. The docstring and class attributes
//! before the first method stay put; a method moves with its decorators and the comment lines
//! directly above it; definitions sharing a name (property accessors, `@overload` stubs) move
//! together. A class is left alone when moving could change it: other statements or standalone
//! comments among its methods, or a decorator, default or annotation naming another method.
//! Rearrange Code: class members in arrangement order, each group in its original order.
//!
//! Python: within each class, `__new__` / `__init__` / `__post_init__`, other dunder methods,
//! public, `_protected`, then `__private` methods. The docstring and class attributes before the
//! first method stay put; a method moves with its decorators and the comment lines directly above
//! it; definitions sharing a name (property accessors, `@overload` stubs) move together. A class is
//! left alone when moving could change it: other statements or standalone comments among its
//! methods, or a decorator, default or annotation naming another method.
//!
//! TypeScript and JavaScript: the constructor, then static methods, then instance methods, each
//! public, protected, then private (`private` or `#name`). Fields and static blocks before the
//! first method stay put, since their initializers run in order. A method moves with its
//! decorators and the comments directly above it; overload signatures and a getter/setter pair
//! move together. A class is left alone when a field, static block or index signature sits among
//! its methods, a method name is computed (evaluated in order), or a decorator names another method.
use crate::{LanguageId, Syntax};
use std::ops::Range;
@@ -14,8 +22,10 @@ impl Syntax {
/// `text` with its class members rearranged; `None` when nothing moves, the text has syntax
/// errors, or the language has no arrangement.
pub fn rearranged(&self, lang: &LanguageId, text: &str) -> Option<String> {
self.analyze(lang, text, |g, tree, text| {
(g.spec.name == "python").then(|| python_rearranged(tree.root_node(), text)).flatten()
self.analyze(lang, text, |g, tree, text| match g.spec.name {
"python" => rearranged_classes(tree.root_node(), text, Arrangement::Python),
"typescript" | "tsx" | "javascript" => rearranged_classes(tree.root_node(), text, Arrangement::Script),
_ => None,
})
}
}
@@ -29,9 +39,16 @@ struct Change {
order: Vec<usize>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Arrangement {
Python,
/// TypeScript, TSX and JavaScript.
Script,
}
/// Every class of the parsed `text` rearranged in one pass: a moved method carries the classes
/// rearranged inside it.
fn python_rearranged(root: Node, text: &str) -> Option<String> {
fn rearranged_classes(root: Node, text: &str, arrangement: Arrangement) -> Option<String> {
if root.has_error() {
return None;
}
@@ -40,14 +57,15 @@ fn python_rearranged(root: Node, text: &str) -> Option<String> {
'walk: loop {
let node = cursor.node();
// An empty block (`if x:` with nothing under it) is an error the parser lets through.
if node.kind() == "block" && node.named_child_count() == 0 {
if arrangement == Arrangement::Python && node.kind() == "block" && node.named_child_count() == 0 {
return None;
}
if node.kind() == "class_definition"
&& let Some(change) = class_change(node, text)
{
changes.push(change);
}
let change = match (arrangement, node.kind()) {
(Arrangement::Python, "class_definition") => class_change(node, text),
(Arrangement::Script, "class_body") => script_class_change(node, text),
_ => None,
};
changes.extend(change);
if cursor.goto_first_child() {
continue;
}
@@ -147,10 +165,12 @@ fn directly_above(above: &[Node], node: Node, text: &str) -> bool {
})
}
/// A comment that marks a position rather than describing a method (`# region`, `# fmt: off`).
/// A comment that marks a position rather than describing a method (`# region`, `//#region`,
/// `# fmt: off`, `// prettier-ignore`).
fn is_marker(comment: Node, text: &str) -> bool {
let body = text[comment.byte_range()].trim_start_matches('#').trim_start();
["region", "endregion", "fmt:", "yapf:", "isort:", "<editor-fold", "</editor-fold"]
let body = text[comment.byte_range()].trim_start_matches(['#', '/', '*']).trim_start();
let body = body.strip_prefix('#').unwrap_or(body);
["region", "endregion", "fmt:", "yapf:", "isort:", "<editor-fold", "</editor-fold", "prettier-ignore"]
.iter()
.any(|m| body.starts_with(m))
}
@@ -272,6 +292,153 @@ fn class_change(class: Node, text: &str) -> Option<Change> {
Some(Change { region: methods[0].start..methods.last()?.end, methods, gaps, order })
}
/// A TypeScript / JavaScript class member that moves: a method, an overload signature or an
/// abstract method.
fn is_script_method(member: Node) -> bool {
matches!(member.kind(), "method_definition" | "method_signature" | "abstract_method_signature")
}
/// Arrangement group of a TypeScript / JavaScript method, and its name; `None` for a computed name.
fn script_group<'a>(member: Node, text: &'a str) -> Option<(u8, bool, &'a str)> {
let name = member.child_by_field_name("name")?;
if !matches!(name.kind(), "property_identifier" | "private_property_identifier" | "string" | "number") {
return None;
}
let name = &text[name.byte_range()];
let mut cursor = member.walk();
let mut is_static = false;
let mut visibility = 0;
for child in member.children(&mut cursor) {
match child.kind() {
"static" => is_static = true,
"accessibility_modifier" => {
visibility = match &text[child.byte_range()] {
"protected" => 1,
"private" => 2,
_ => 0,
}
}
_ => {}
}
}
if name.starts_with('#') {
visibility = 2;
}
let group = match (name, is_static) {
("constructor", false) => 0,
(_, true) => 1 + visibility,
(_, false) => 4 + visibility,
};
Some((group, is_static, name))
}
/// Whether the comments and decorators `attached` lead into `member`: each on the line right above
/// the next (a decorator may share its line), the first one starting its line.
fn leads_into(attached: &[Node], member: Node, text: &str) -> bool {
let mut next = member;
for prev in attached.iter().rev() {
let same_line = prev.kind() == "decorator" && prev.end_position().row == next.start_position().row;
if !same_line && prev.end_position().row + 1 != next.start_position().row {
return false;
}
next = *prev;
}
starts_line(next, text)
}
/// The methods of a TypeScript / JavaScript class body in arrangement order; `None` when they
/// already are or moving them could change the class.
fn script_class_change(body: Node, text: &str) -> Option<Change> {
let mut cursor = body.walk();
let members: Vec<Node> = body.named_children(&mut cursor).collect();
let first = members.iter().position(|m| is_script_method(*m))?;
if members.iter().any(|m| m.kind() == "comment" && is_marker(*m, text)) {
return None;
}
let attachable = |m: &Node| matches!(m.kind(), "comment" | "decorator");
let mut lead = first;
while lead > 0 && attachable(&members[lead - 1]) && leads_into(&members[lead - 1..first], members[first], text) {
lead -= 1;
}
// (member, group, static, name, first line, decorators)
let column = members[lead].start_position().column;
let mut methods = Vec::new();
let mut attached: Vec<Node> = members[lead..first].to_vec();
let mut previous_row = None;
for member in &members[first..] {
// A comment after a member on its last line is part of that member's lines.
if member.kind() == "comment" && previous_row == Some(member.start_position().row) {
continue;
}
if attachable(member) {
attached.push(*member);
continue;
}
previous_row = Some(member.end_position().row);
// A field, static block or index signature among the methods stays where it is: leave the class.
if !is_script_method(*member) {
return None;
}
let (group, is_static, name) = script_group(*member, text)?;
let head = attached.first().copied().unwrap_or(*member);
if head.start_position().column != column || !leads_into(&attached, *member, text) {
return None;
}
let mut cursor = member.walk();
let mut decorators: Vec<Node> = attached.iter().copied().filter(|n| n.kind() == "decorator").collect();
decorators.extend(member.children(&mut cursor).filter(|c| c.kind() == "decorator"));
methods.push((*member, group, is_static, name, head, decorators));
attached.clear();
}
if !attached.is_empty() {
return None;
}
// Decorators run while the class is defined: one naming another method stays below it.
for (_, _, _, name, _, decorators) in &methods {
let others: Vec<&str> = methods.iter().map(|m| m.3).filter(|n| n != name).collect();
let names_other = decorators.iter().any(|d| {
any_in(*d, |n| {
matches!(n.kind(), "identifier" | "property_identifier") && others.contains(&&text[n.byte_range()])
})
});
if names_other {
return None;
}
}
// Adjacent overloads and accessor pairs are one block, spacing inside it kept.
let mut blocks: Vec<(u8, bool, &str, Range<usize>)> = Vec::new();
for (member, group, is_static, name, head, _) in &methods {
let range = line_start(text, head.start_byte())..line_end(text, member.end_byte());
match blocks.last_mut() {
Some(last) if last.1 == *is_static && last.2 == *name => last.3.end = range.end,
_ => blocks.push((*group, *is_static, name, range)),
}
}
// Same-named blocks elsewhere join the first one.
let mut units: Vec<(u8, bool, &str, Vec<usize>)> = Vec::new();
for (i, (group, is_static, name, _)) in blocks.iter().enumerate() {
match units.iter_mut().find(|u| u.1 == *is_static && u.2 == *name) {
Some(unit) => unit.3.push(i),
None => units.push((*group, *is_static, name, vec![i])),
}
}
units.sort_by_key(|u| u.0);
let order: Vec<usize> = units.into_iter().flat_map(|u| u.3).collect();
if order.iter().enumerate().all(|(i, &m)| i == m) {
return None;
}
let ranges: Vec<Range<usize>> = blocks.into_iter().map(|b| b.3).collect();
let mut gaps = Vec::new();
for pair in ranges.windows(2) {
// Only blank lines between methods; anything else stays with the class.
if pair[0].end > pair[1].start || !text[pair[0].end..pair[1].start].trim().is_empty() {
return None;
}
gaps.push(pair[0].end..pair[1].start);
}
Some(Change { region: ranges[0].start..ranges.last()?.end, methods: ranges, gaps, order })
}
#[cfg(test)]
mod tests {
use super::*;
@@ -397,4 +564,110 @@ mod tests {
// Linear: well under a second in release builds; a reparse per class took minutes.
assert!(started.elapsed().as_secs() < 30);
}
fn script(lang: &str, text: &str) -> Option<String> {
Syntax::default().rearranged(&LanguageId::new(lang), text)
}
#[test]
fn typescript_methods_follow_constructor_static_then_instance_by_visibility() {
let text = r#"class Store {
private items: string[] = [];
static count = 0;
@log()
private load(): void {}
// Adds one.
add(item: string): void;
add(items: string[]): void;
add(x: string | string[]) {}
protected get size() { return 1; }
protected set size(v: number) {}
static create(): Store { return new Store(); }
#secret() {}
constructor(readonly name: string) {}
private static reset() {}
}
"#;
let expected = r#"class Store {
private items: string[] = [];
static count = 0;
constructor(readonly name: string) {}
static create(): Store { return new Store(); }
private static reset() {}
// Adds one.
add(item: string): void;
add(items: string[]): void;
add(x: string | string[]) {}
protected get size() { return 1; }
protected set size(v: number) {}
@log()
private load(): void {}
#secret() {}
}
"#;
assert_eq!(script("typescript", text).as_deref(), Some(expected));
assert_eq!(script("typescript", expected), None);
}
#[test]
fn javascript_and_jsx_classes_are_rearranged_too() {
let text = "class A {\n #p() {}\n render() { return <div />; }\n static of() {}\n constructor() {}\n}\n";
let expected =
"class A {\n constructor() {}\n static of() {}\n render() { return <div />; }\n #p() {}\n}\n";
assert_eq!(script("javascript", text).as_deref(), Some(expected));
assert_eq!(script("javascriptreact", text).as_deref(), Some(expected));
let tsx = "const A = class {\n b() { return <B />; }\n constructor() {}\n};\n";
let tsx_expected = "const A = class {\n constructor() {}\n b() { return <B />; }\n};\n";
assert_eq!(script("typescriptreact", tsx).as_deref(), Some(tsx_expected));
}
#[test]
fn script_classes_that_could_change_are_left_alone() {
for text in [
// A field among the methods: its initializer runs in order.
"class A {\n b() {}\n x = 1;\n constructor() {}\n}\n",
// A static block among the methods.
"class A {\n b() {}\n static {}\n constructor() {}\n}\n",
// A computed name is evaluated in order.
"class A {\n [key]() {}\n constructor() {}\n}\n",
// A decorator naming another method.
"class A {\n @bind(A.prototype.b) a() {}\n constructor() {}\n b() {}\n}\n",
// A region marker.
"class A {\n // #region helpers\n b() {}\n // #endregion\n constructor() {}\n}\n",
// Two members on one line.
"class A {\n b() {} constructor() {}\n}\n",
// A syntax error anywhere in the file.
"class A {\n b() {}\n constructor() {}\n}\nlet = ;\n",
] {
assert_eq!(script("typescript", text), None, "{text}");
}
}
#[test]
fn decorators_on_the_method_line_and_trailing_comments_move_with_their_method() {
let text = "class A {\n @log b() {} // second\n constructor() {}\n}\n";
let expected = "class A {\n constructor() {}\n @log b() {} // second\n}\n";
assert_eq!(script("typescript", text).as_deref(), Some(expected));
assert_eq!(script("javascript", text).as_deref(), Some(expected));
}
#[test]
fn static_and_instance_methods_with_one_name_stay_separate() {
let text = "class A {\n of() {}\n static of() {}\n}\n";
assert_eq!(script("typescript", text).as_deref(), Some("class A {\n static of() {}\n of() {}\n}\n"));
}
}
+4
Переглянути файл
@@ -91,6 +91,10 @@ With **Automatic**, a JavaScript or TypeScript file below the tool's own configu
The **Imports** tab sets how the TypeScript server writes the imports it adds (auto-import, quick fixes, moving files): **Import paths** (shortest, relative, non-relative through `paths` / `baseUrl`, or relative within the project), **Import path ending** (automatic, `./components`, `./components/index` or `./components/index.js`), **Do not auto-import from** (globs such as `**/index.ts` to keep barrel files out) and **Do not auto-import specifiers matching** (regular expressions for the import path, such as `^node:`). Like the other tabs, they are saved per project, separately for JavaScript and TypeScript, and apply to a running server without a restart.
### Rearrange Code
**Rearrange Code** (Find Action, or the Code menu) orders the methods of every class in a JavaScript, TypeScript, JSX or TSX file: the constructor, static methods, then instance methods, each public, protected, then private (`private` or a `#name`), each group in its original order. Fields and static blocks before the first method stay put, since their initializers run in order. A method moves with its decorators and the comments directly above it, and overload signatures and a getter/setter pair move together. A class is left as it is when moving could change it: a field, static block or index signature among its methods, a computed method name, a decorator that names another of its methods, or a `// #region` marker. Files with syntax errors are not rearranged. Running it again changes nothing, and **Undo** reverts it in one step.
### Biome lint
In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too.
+4
Переглянути файл
@@ -92,6 +92,10 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript
**导入** 标签页决定 TypeScript 服务器添加导入(自动导入、快速修复、移动文件)时的写法:**导入路径**(最短、相对路径、通过 `paths` / `baseUrl` 的非相对路径,或项目内使用相对路径)、**导入路径结尾**(自动、`./components`、`./components/index` 或 `./components/index.js`)、**不从以下位置自动导入**(glob,例如用 `**/index.ts` 排除 barrel 文件)和 **不自动导入匹配以下表达式的路径**(匹配导入路径的正则表达式,例如 `^node:`)。和其他标签页一样,它们按项目保存,JavaScript 和 TypeScript 分开设置,修改后无需重启服务器即可生效。
### 重新排列代码
**重新排列代码**(在查找操作或代码菜单中)对 JavaScript、TypeScript、JSX 或 TSX 文件中每个类的方法排序:构造函数,静态方法,然后是实例方法;静态方法和实例方法内部依次为公开、受保护、私有(`private` 或 `#name`),同组内保持原有顺序。第一个方法之前的字段和静态块不动,因为它们的初始化按顺序执行。方法连同装饰器和紧贴其上方的注释一起移动,重载签名以及 getter/setter 对一起移动。移动可能改变类的行为时,类保持不变:方法之间夹有字段、静态块或索引签名,方法名是计算属性,装饰器引用了本类的其他方法,或者有 `// #region` 标记。有语法错误的文件不会重新排列。再次运行不会产生变化,**撤销**一步即可还原。
### Biome 检查
在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。
+2 -2
Переглянути файл
@@ -761,8 +761,8 @@ export const commands = {
/** Python class facts for the inheritance inspections: tree-sitter, no language server. */
docPythonFacts: (doc: DocId) => typedError<PythonFacts, IdeError>(__TAURI_INVOKE("doc_python_facts", { doc })),
/**
* Rearrange Code: the edits that put the document's class members in arrangement order (Python
* for now); none when they already are or the language has no arrangement.
* Rearrange Code: the edits that put the document's class members in arrangement order (Python,
* TypeScript and JavaScript); none when they already are or the language has no arrangement.
*/
docRearrange: (doc: DocId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("doc_rearrange", { doc })),
/** Load Changes from Disk: discards the buffer's unsaved changes and reads its file again. */
+2 -2
Переглянути файл
@@ -162,7 +162,7 @@ const optimizeImports = async (v: EditorView) => {
});
};
/** Rearrange Code: class members in arrangement order (Python), as one undo step. */
/** Rearrange Code: class members in arrangement order (Python, TypeScript, JavaScript), as one undo step. */
async function rearrange(view: EditorView) {
const doc = docOf(view);
if (!doc || doc.readOnly) return;
@@ -404,7 +404,7 @@ export function registerLspActions(): () => void {
keywords: ["stylelint", "lint", "css", "fix all"],
}),
editorAction("code.rearrange", "Rearrange Code", "Code", rearrange, {
when: `${EDITOR_WHEN} && editorLangId == python`,
when: `${EDITOR_WHEN} && (editorLangId == python || editorLangId == typescript || editorLangId == typescriptreact || editorLangId == javascript || editorLangId == javascriptreact)`,
keywords: ["arrange", "sort", "members", "methods", "order"],
}),
editorAction("code.optimizeImports", "Optimize Imports", "Code", optimizeImports, {