@ryuugg/stanza 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +163 -0
  3. package/package.json +63 -0
  4. package/src/cli.ts +820 -0
  5. package/src/compile/darwin-arm64.ts +3 -0
  6. package/src/compile/darwin-x64.ts +3 -0
  7. package/src/compile/linux-arm64-musl.ts +3 -0
  8. package/src/compile/linux-arm64.ts +3 -0
  9. package/src/compile/linux-x64-musl.ts +3 -0
  10. package/src/compile/linux-x64.ts +3 -0
  11. package/src/compiled.ts +6 -0
  12. package/src/engine/attach.ts +62 -0
  13. package/src/engine/directives.ts +154 -0
  14. package/src/engine/doc.ts +93 -0
  15. package/src/engine/edits.ts +79 -0
  16. package/src/engine/explain.ts +333 -0
  17. package/src/engine/gaps.ts +329 -0
  18. package/src/engine/hunks.ts +320 -0
  19. package/src/engine/index.ts +254 -0
  20. package/src/engine/model.ts +102 -0
  21. package/src/engine/rules.ts +103 -0
  22. package/src/engine/types.ts +37 -0
  23. package/src/files.ts +822 -0
  24. package/src/gitignore.ts +279 -0
  25. package/src/hook.ts +282 -0
  26. package/src/languages/index.ts +32 -0
  27. package/src/languages/javascript/ast.ts +199 -0
  28. package/src/languages/javascript/braces.ts +374 -0
  29. package/src/languages/javascript/config/biome.ts +112 -0
  30. package/src/languages/javascript/config/eslint.ts +128 -0
  31. package/src/languages/javascript/config/evaluate.ts +278 -0
  32. package/src/languages/javascript/config/find.ts +108 -0
  33. package/src/languages/javascript/config/glob.ts +150 -0
  34. package/src/languages/javascript/config/index.ts +48 -0
  35. package/src/languages/javascript/config/layers.ts +425 -0
  36. package/src/languages/javascript/config/module.ts +326 -0
  37. package/src/languages/javascript/config/oxlint.ts +170 -0
  38. package/src/languages/javascript/config/width.ts +715 -0
  39. package/src/languages/javascript/entry.ts +39 -0
  40. package/src/languages/javascript/facts.ts +268 -0
  41. package/src/languages/javascript/index.ts +20 -0
  42. package/src/languages/javascript/lists.ts +49 -0
  43. package/src/languages/javascript/oracle.ts +191 -0
  44. package/src/languages/javascript/parse.ts +58 -0
  45. package/src/languages/javascript/scan.ts +68 -0
  46. package/src/languages/language.ts +109 -0
  47. package/src/launcher +21 -0
  48. package/src/native-file.d.ts +4 -0
  49. package/src/step.ts +108 -0
  50. package/src/usage.ts +30 -0
@@ -0,0 +1,39 @@
1
+ import type { Entry } from "../language.ts";
2
+
3
+ const directories = new Set([
4
+ "node_modules",
5
+ "dist",
6
+ "build",
7
+ ".git",
8
+ ".next",
9
+ "out",
10
+ "coverage",
11
+ "migrations",
12
+ "drizzle",
13
+ ]);
14
+
15
+ function generatedName(name: string): boolean {
16
+ return (
17
+ name.endsWith(".gen.ts") ||
18
+ name.endsWith(".gen.tsx") ||
19
+ name.includes(".generated.") ||
20
+ name.endsWith(".min.js")
21
+ );
22
+ }
23
+
24
+ function skipsName(name: string, keepGenerated: boolean): boolean {
25
+ return (
26
+ name.endsWith(".d.ts") ||
27
+ name.endsWith(".d.mts") ||
28
+ name.endsWith(".d.cts") ||
29
+ (!keepGenerated && generatedName(name))
30
+ );
31
+ }
32
+
33
+ export const entry: Entry = {
34
+ id: "javascript",
35
+ extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"],
36
+ directories,
37
+ skipsName,
38
+ load: () => (require("./index.ts") as typeof import("./index.ts")).language,
39
+ };
@@ -0,0 +1,268 @@
1
+ import type { Node, Statement, SwitchCase } from "oxc-parser";
2
+ import { boundNames, children, declared, references } from "./ast.ts";
3
+ import { lineAt, source } from "../../engine/doc.ts";
4
+ import type { Binding, Doc, Item, Kind, Path } from "../../engine/model.ts";
5
+ import type { Layout } from "../language.ts";
6
+
7
+ const KINDS: Record<string, Kind> = {
8
+ VariableDeclaration: "declaration",
9
+ IfStatement: "if",
10
+ ForStatement: "loop",
11
+ ForInStatement: "loop",
12
+ ForOfStatement: "loop",
13
+ WhileStatement: "loop",
14
+ DoWhileStatement: "loop",
15
+ SwitchStatement: "switch",
16
+ SwitchCase: "case",
17
+ TryStatement: "try",
18
+ FunctionDeclaration: "function",
19
+ ReturnStatement: "return",
20
+ ThrowStatement: "throw",
21
+ BreakStatement: "break",
22
+ ContinueStatement: "continue",
23
+ };
24
+
25
+ const WORDS: Record<string, string> = {
26
+ IfStatement: "if",
27
+ ReturnStatement: "return",
28
+ SwitchStatement: "switch",
29
+ ForStatement: "for",
30
+ ForInStatement: "for",
31
+ ForOfStatement: "for",
32
+ WhileStatement: "while",
33
+ DoWhileStatement: "do",
34
+ TryStatement: "try",
35
+ FunctionDeclaration: "function",
36
+ };
37
+
38
+ const JUMPS: Record<string, string> = {
39
+ ReturnStatement: "return",
40
+ ThrowStatement: "throw",
41
+ ContinueStatement: "continue",
42
+ BreakStatement: "break",
43
+ };
44
+
45
+ function kindOf(node: Statement | SwitchCase): Kind {
46
+ if (node.type === "ExpressionStatement")
47
+ return node.expression.type === "AssignmentExpression" ? "assignment" : "expression";
48
+
49
+ return KINDS[node.type] ?? "other";
50
+ }
51
+
52
+ function unwrapPath(node: Node): Node {
53
+ let current = node;
54
+ while (
55
+ current.type === "ChainExpression" ||
56
+ current.type === "TSNonNullExpression" ||
57
+ current.type === "TSAsExpression" ||
58
+ current.type === "TSSatisfiesExpression" ||
59
+ current.type === "TSTypeAssertion" ||
60
+ current.type === "ParenthesizedExpression"
61
+ )
62
+ current = current.expression;
63
+
64
+ return current;
65
+ }
66
+
67
+ type Member = Node & { type: "MemberExpression" };
68
+
69
+ function spine(outer: Member): { members: Member[]; base: Node } {
70
+ const members = [outer];
71
+
72
+ let base = unwrapPath(outer.object);
73
+ while (base.type === "MemberExpression") {
74
+ members.push(base);
75
+ base = unwrapPath(base.object);
76
+ }
77
+
78
+ return { members, base };
79
+ }
80
+
81
+ function memberSegment(doc: Doc, member: Member): string {
82
+ const { computed, property } = member;
83
+ if (computed) return `[${source(doc, property)}]`;
84
+ if (property.type === "PrivateIdentifier") return `#${property.name}`;
85
+ return property.name;
86
+ }
87
+
88
+ function headName(base: Node): string | undefined {
89
+ if (base.type === "Identifier") return base.name;
90
+ if (base.type === "ThisExpression") return "this";
91
+ if (base.type === "Super") return "super";
92
+ return undefined;
93
+ }
94
+
95
+ function memberPath(doc: Doc, outer: Member): Path | undefined {
96
+ const { members, base } = spine(outer);
97
+ const head = headName(base);
98
+ if (head === undefined) return undefined;
99
+
100
+ return [head, ...members.map((member) => memberSegment(doc, member)).reverse()];
101
+ }
102
+
103
+ function spineReads(doc: Doc, members: Member[], base: Node, path: Path): boolean {
104
+ const first = members.length - (path.length - 1);
105
+ if (first < 0 || headName(base) !== path[0]) return false;
106
+
107
+ return members
108
+ .slice(first)
109
+ .every((member, index) => memberSegment(doc, member) === path[path.length - 1 - index]);
110
+ }
111
+
112
+ function readsPath(doc: Doc, root: Node, path: Path): boolean {
113
+ const stack = [root];
114
+ while (stack.length > 0) {
115
+ const node = stack.pop()!;
116
+ if (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") continue;
117
+ if (node.type === "FunctionDeclaration" && node !== root) continue;
118
+ if (path[0] !== "this" && path[0] !== "super" && declared(node).includes(path[0])) {
119
+ if (node.type === "SwitchStatement") stack.push(node.discriminant);
120
+ continue;
121
+ }
122
+
123
+ if (node.type !== "MemberExpression") {
124
+ for (const [, child] of children(node).toReversed()) stack.push(child);
125
+ continue;
126
+ }
127
+
128
+ const { members, base } = spine(node);
129
+ if (spineReads(doc, members, base, path)) return true;
130
+
131
+ stack.push(base);
132
+ for (const member of members) if (member.computed) stack.push(member.property);
133
+ }
134
+
135
+ return false;
136
+ }
137
+
138
+ function guardOf(node: Statement | SwitchCase): { jump: string | null } | null {
139
+ if (node.type !== "IfStatement" || node.alternate) return null;
140
+
141
+ const { consequent } = node;
142
+ if (consequent.type !== "BlockStatement") return { jump: JUMPS[consequent.type] ?? null };
143
+ if (consequent.body.length !== 1) return null;
144
+
145
+ return { jump: JUMPS[consequent.body[0]!.type] ?? null };
146
+ }
147
+
148
+ function bindsOf(doc: Doc, node: Statement | SwitchCase): Binding | null {
149
+ if (node.type === "VariableDeclaration") return boundNames(node);
150
+ if (node.type !== "ExpressionStatement" || node.expression.type !== "AssignmentExpression")
151
+ return null;
152
+
153
+ const target = node.expression.left;
154
+ const member = unwrapPath(target);
155
+ return member.type === "MemberExpression"
156
+ ? (memberPath(doc, member) ?? null)
157
+ : boundNames(target);
158
+ }
159
+
160
+ function joinedText(doc: Doc, node: Node): string | null {
161
+ if (lineAt(doc, node.start) === lineAt(doc, node.end - 1)) return source(doc, node).trim();
162
+
163
+ const body =
164
+ node.type === "IfStatement" && !node.alternate
165
+ ? node.consequent
166
+ : node.type === "ForStatement" ||
167
+ node.type === "ForInStatement" ||
168
+ node.type === "ForOfStatement" ||
169
+ node.type === "WhileStatement"
170
+ ? node.body
171
+ : null;
172
+
173
+ if (!body || body.type === "BlockStatement") return null;
174
+
175
+ const header = doc.text.slice(node.start, body.start);
176
+ const lines = header.split(/\r?\n/);
177
+ if (lines.length > 2 || (lines.length === 2 && lines[1]!.trim() !== "")) return null;
178
+
179
+ let before = body.start;
180
+ while (before > node.start && /\s/.test(doc.text[before - 1]!)) before--;
181
+
182
+ if (doc.comments.some((comment) => comment.end === before && comment.start >= node.start))
183
+ return null;
184
+
185
+ const joined = joinedText(doc, body);
186
+ return joined === null
187
+ ? null
188
+ : `${lines[0]!.trimEnd()}${body.type === "EmptyStatement" ? "" : " "}${joined}`;
189
+ }
190
+
191
+ function joinedColumns(doc: Doc, node: Node, width: Layout): number | null {
192
+ if (lineAt(doc, node.start) === lineAt(doc, node.end - 1)) return null;
193
+
194
+ const joined = joinedText(doc, node);
195
+ if (joined === null) return null;
196
+
197
+ const lineStart = doc.lineStarts[lineAt(doc, node.start) - 1]!;
198
+ const prefix = doc.text.slice(lineStart, node.start);
199
+
200
+ let columns = 0;
201
+ for (const char of prefix + joined)
202
+ columns += char === "\t" ? width.tab - (columns % width.tab) : Bun.stringWidth(char);
203
+
204
+ return columns;
205
+ }
206
+
207
+ function operation(doc: Doc, node: Node): string | null {
208
+ if (node.type !== "ExpressionStatement") return null;
209
+
210
+ const expression = node.expression;
211
+ if (expression.type === "CallExpression") return `call:${source(doc, expression.callee)}`;
212
+ if (expression.type === "AssignmentExpression") return `assign:${source(doc, expression.left)}`;
213
+
214
+ return null;
215
+ }
216
+
217
+ function repeatsOperation(doc: Doc, root: Node, expected: string): boolean {
218
+ const stack = [root];
219
+ while (stack.length > 0) {
220
+ const node = stack.pop()!;
221
+ if (
222
+ node.type === "FunctionExpression" ||
223
+ node.type === "ArrowFunctionExpression" ||
224
+ node.type === "FunctionDeclaration"
225
+ )
226
+ continue;
227
+
228
+ if (node.type === "ExpressionStatement") {
229
+ if (operation(doc, node) === expected) return true;
230
+ continue;
231
+ }
232
+
233
+ for (const [, child] of children(node).toReversed()) stack.push(child);
234
+ }
235
+
236
+ return false;
237
+ }
238
+
239
+ export function facts(
240
+ doc: Doc,
241
+ node: Statement | SwitchCase,
242
+ width: Layout,
243
+ ): Item<Statement | SwitchCase> {
244
+ const finalizer = node.type === "TryStatement" ? node.finalizer : null;
245
+ const joined = joinedColumns(doc, node, width);
246
+ return {
247
+ node,
248
+ start: node.start,
249
+ end: node.end,
250
+ kind: kindOf(node),
251
+ word: WORDS[node.type] ?? null,
252
+ binds: bindsOf(doc, node),
253
+ declaration:
254
+ node.type === "VariableDeclaration"
255
+ ? { keyword: node.kind, letLike: node.kind === "let" }
256
+ : null,
257
+ guard: guardOf(node),
258
+ compact:
259
+ lineAt(doc, node.start) === lineAt(doc, node.end - 1) ||
260
+ (joined !== null && joined <= width.columns),
261
+ joined,
262
+ caseBody: node.type === "SwitchCase" && node.consequent.length > 0,
263
+ operation: operation(doc, node),
264
+ references: (names) => references(node, names),
265
+ readsPath: (path) => readsPath(doc, node, path),
266
+ finallyRepeats: (expected) => finalizer !== null && repeatsOperation(doc, finalizer, expected),
267
+ };
268
+ }
@@ -0,0 +1,20 @@
1
+ import type { Language } from "../language.ts";
2
+ import { braceDecisions, bracesSetting } from "./config/index.ts";
3
+ import { formatterWidth } from "./config/width.ts";
4
+ import { parse, rejection } from "./parse.ts";
5
+ import { scan } from "./scan.ts";
6
+
7
+ export const language: Language = {
8
+ parse(path, text) {
9
+ const parsed = parse(path, text);
10
+ const error = parsed.errors[0];
11
+ return {
12
+ comments: parsed.comments,
13
+ error: error ? { start: error.labels[0]?.start ?? 0, message: error.message } : undefined,
14
+ rejection: (text) => rejection(text, parsed),
15
+ scan: (doc, width) => scan(doc, parsed.program, width),
16
+ };
17
+ },
18
+ config: { setting: bracesSetting, decisions: braceDecisions, width: formatterWidth },
19
+ oracle: () => (require("./oracle.ts") as typeof import("./oracle.ts")).oracle,
20
+ };
@@ -0,0 +1,49 @@
1
+ import type { Node, Statement, SwitchCase } from "oxc-parser";
2
+ import { attach } from "../../engine/attach.ts";
3
+ import { lineAt, nextToken } from "../../engine/doc.ts";
4
+ import { facts } from "./facts.ts";
5
+ import type { Doc, StatementList } from "../../engine/model.ts";
6
+ import type { Layout } from "../language.ts";
7
+
8
+ export type List = StatementList<Statement | SwitchCase>;
9
+
10
+ export function listAt(doc: Doc, node: Node, width: Layout): List | undefined {
11
+ if (node.type === "BlockStatement" || node.type === "StaticBlock") {
12
+ const start =
13
+ node.type === "StaticBlock" ? nextToken(doc, node.start + "static".length) : node.start;
14
+
15
+ return {
16
+ kind: "block",
17
+ start,
18
+ end: node.end,
19
+ openLine: lineAt(doc, start),
20
+ closeLine: lineAt(doc, node.end - 1),
21
+ stmts: attach(
22
+ doc,
23
+ node.body.map((stmt) => facts(doc, stmt, width)),
24
+ start + 1,
25
+ node.end - 1,
26
+ ),
27
+ };
28
+ }
29
+
30
+ if (node.type === "SwitchStatement" || node.type === "SwitchCase") {
31
+ const nodes = node.type === "SwitchStatement" ? node.cases : node.consequent;
32
+ const opener =
33
+ node.type === "SwitchCase" ? (node.test?.end ?? node.start) : node.discriminant.end;
34
+
35
+ return {
36
+ kind: node.type === "SwitchStatement" ? "switch" : "block",
37
+ start: node.start,
38
+ end: node.end,
39
+ openLine: null,
40
+ closeLine: null,
41
+ stmts: attach(
42
+ doc,
43
+ nodes.map((stmt) => facts(doc, stmt, width)),
44
+ opener,
45
+ node.end,
46
+ ),
47
+ };
48
+ }
49
+ }
@@ -0,0 +1,191 @@
1
+ import type { BlockStatement, Node } from "oxc-parser";
2
+ import type { Comment } from "../../engine/model.ts";
3
+ import type { Region } from "../../engine/directives.ts";
4
+ import type { Oracle, OracleStatement } from "../language.ts";
5
+ import { children, walk } from "./ast.ts";
6
+ import { controlledBlocks } from "./braces.ts";
7
+ import { parse, type Parsed } from "./parse.ts";
8
+
9
+ const POSITION_KEYS = new Set(["start", "end", "range", "loc"]);
10
+
11
+ type Range = { start: number; end: number };
12
+ type Statement = { node: Node; parent: Node | null };
13
+
14
+ const ENCLOSING = new Set([
15
+ "BlockStatement",
16
+ "StaticBlock",
17
+ "SwitchStatement",
18
+ "SwitchCase",
19
+ "ClassBody",
20
+ "TSModuleBlock",
21
+ ]);
22
+
23
+ const INTERIORS = new Set(["BlockStatement", "StaticBlock", "ClassBody", "TSModuleBlock"]);
24
+
25
+ const STATEMENT_ARRAYS = new Set([
26
+ "Program:body",
27
+ "BlockStatement:body",
28
+ "StaticBlock:body",
29
+ "SwitchStatement:cases",
30
+ "SwitchCase:consequent",
31
+ "TSModuleBlock:body",
32
+ ]);
33
+
34
+ function shape(parsed: Parsed, blocks: BlockStatement[]): string | undefined {
35
+ if (parsed.errors.length > 0) return undefined;
36
+
37
+ const flattened = new Set(blocks.filter((block) => block.body.length === 1));
38
+ return JSON.stringify(parsed.program, (key, value) => {
39
+ if (POSITION_KEYS.has(key)) return undefined;
40
+ if (typeof value === "bigint") return `${value}n`;
41
+ return flattened.has(value) ? value.body[0] : value;
42
+ });
43
+ }
44
+
45
+ function container(program: Node, comment: Comment): Region {
46
+ let enclosing: Node = program;
47
+ walk(program, (node) => {
48
+ if (ENCLOSING.has(node.type) && node.start < comment.start && comment.end <= node.end)
49
+ if (node.end - node.start < enclosing.end - enclosing.start) enclosing = node;
50
+ });
51
+
52
+ return { start: enclosing.start, end: enclosing.end };
53
+ }
54
+
55
+ function controlledRanges(node: Node): Range[] {
56
+ const ranges: Range[] = [];
57
+ function body(child: Node): void {
58
+ ranges.push(
59
+ child.type === "BlockStatement"
60
+ ? { start: child.start + 1, end: child.end - 1 }
61
+ : { start: child.start, end: child.end },
62
+ );
63
+ }
64
+
65
+ function chain(current: Node): void {
66
+ switch (current.type) {
67
+ case "LabeledStatement":
68
+ chain(current.body);
69
+ break;
70
+
71
+ case "IfStatement":
72
+ body(current.consequent);
73
+
74
+ if (current.alternate?.type === "IfStatement") chain(current.alternate);
75
+ else if (current.alternate) body(current.alternate);
76
+
77
+ break;
78
+
79
+ case "ForStatement":
80
+ case "ForInStatement":
81
+ case "ForOfStatement":
82
+ case "WhileStatement":
83
+ case "DoWhileStatement":
84
+ case "WithStatement":
85
+ body(current.body);
86
+ }
87
+ }
88
+
89
+ chain(node);
90
+ return ranges;
91
+ }
92
+
93
+ function statementSkeleton(text: string, statement: Statement): string {
94
+ const ranges = controlledRanges(statement.node);
95
+
96
+ walk(statement.node, (node) => {
97
+ if (ranges.some((range) => range.start <= node.start && node.end <= range.end)) return;
98
+ if (INTERIORS.has(node.type)) ranges.push({ start: node.start + 1, end: node.end - 1 });
99
+ else if (node.type === "SwitchStatement")
100
+ ranges.push({ start: node.discriminant.end, end: node.end - 1 });
101
+ });
102
+
103
+ const outermost = ranges
104
+ .sort((left, right) => left.start - right.start || right.end - left.end)
105
+ .filter(
106
+ (range, index, all) =>
107
+ !all.slice(0, index).some((prior) => prior.start <= range.start && range.end <= prior.end),
108
+ );
109
+
110
+ let cursor = statement.node.start;
111
+ let result = "";
112
+ for (const range of outermost) {
113
+ result += text.slice(cursor, range.start) + "\0";
114
+ cursor = range.end;
115
+ }
116
+
117
+ return result + text.slice(cursor, statement.node.end);
118
+ }
119
+
120
+ function edgeAbove(parent: Node): number | undefined {
121
+ if (parent.type === "BlockStatement" || parent.type === "StaticBlock") return parent.start;
122
+ if (parent.type === "SwitchStatement") return parent.discriminant.end;
123
+ }
124
+
125
+ function edgeBelow(parent: Node): number | undefined {
126
+ if (["BlockStatement", "StaticBlock", "SwitchStatement"].includes(parent.type)) return parent.end;
127
+ }
128
+
129
+ function gaps(text: string, statement: Statement): [string | undefined, string | undefined] {
130
+ if (!statement.parent) return [undefined, undefined];
131
+
132
+ const entry = children(statement.parent).find(([, child]) => child === statement.node);
133
+ if (!entry || !STATEMENT_ARRAYS.has(`${statement.parent.type}:${entry[0]}`))
134
+ return [undefined, undefined];
135
+
136
+ const siblings = children(statement.parent)
137
+ .filter(([key]) => key === entry[0])
138
+ .map(([, child]) => child);
139
+
140
+ const index = siblings.indexOf(statement.node);
141
+ const previous = siblings[index - 1];
142
+ const next = siblings[index + 1];
143
+
144
+ const above = previous?.end ?? edgeAbove(statement.parent);
145
+ const below = next?.start ?? edgeBelow(statement.parent);
146
+ return [
147
+ above === undefined ? undefined : text.slice(above, statement.node.start),
148
+ below === undefined ? undefined : text.slice(statement.node.end, below),
149
+ ];
150
+ }
151
+
152
+ function statementAfter(program: Node, text: string, offset: number): OracleStatement | undefined {
153
+ let next: Statement | undefined;
154
+ walk(program, (node, parent) => {
155
+ if (
156
+ node.start < offset ||
157
+ (node.type !== "SwitchCase" && !/(Statement|Declaration)$/.test(node.type))
158
+ )
159
+ return;
160
+
161
+ if (!next || node.start < next.node.start) next = { node, parent };
162
+ });
163
+
164
+ if (!next) return undefined;
165
+
166
+ const statement = next;
167
+ return {
168
+ start: statement.node.start,
169
+ clause: statement.node.type === "SwitchCase",
170
+ skeleton: () => statementSkeleton(text, statement),
171
+ gaps: () => gaps(text, statement),
172
+ };
173
+ }
174
+
175
+ export const oracle: Oracle = {
176
+ side(path, text) {
177
+ const parsed = parse(path, text);
178
+ const blocks = [...controlledBlocks(parsed.program).keys()];
179
+ return {
180
+ comments: parsed.comments,
181
+ blocks: blocks.map((block) => ({
182
+ start: block.start,
183
+ end: block.end,
184
+ single: block.body.length === 1,
185
+ })),
186
+ shape: () => shape(parsed, blocks),
187
+ container: (comment) => container(parsed.program, comment),
188
+ statementAfter: (offset) => statementAfter(parsed.program, text, offset),
189
+ };
190
+ },
191
+ };
@@ -0,0 +1,58 @@
1
+ import {
2
+ parseSync,
3
+ type Comment,
4
+ type Node,
5
+ type OxcError,
6
+ type ParserOptions,
7
+ type Program,
8
+ } from "oxc-parser";
9
+ import { extname } from "node:path";
10
+ import type { Rejection } from "../language.ts";
11
+ import { walk } from "./ast.ts";
12
+
13
+ export interface Parsed {
14
+ program: Program;
15
+ comments: Comment[];
16
+ errors: OxcError[];
17
+ }
18
+
19
+ const javascript: Record<string, ParserOptions> = {
20
+ ".js": { lang: "jsx" },
21
+ ".mjs": { lang: "jsx", sourceType: "module" },
22
+ ".cjs": { lang: "jsx", sourceType: "commonjs" },
23
+ };
24
+
25
+ const loneCr = /\r(?!\n)/g;
26
+
27
+ export function parse(path: string, text: string): Parsed {
28
+ const result = parseSync(path, text, javascript[extname(path)]);
29
+ return { program: result.program, comments: result.comments, errors: result.errors };
30
+ }
31
+
32
+ function crLineEnding(text: string, program: Program): number | undefined {
33
+ if (text.search(loneCr) < 0) return undefined;
34
+
35
+ const quasis: Node[] = [];
36
+ walk(program, (node) => {
37
+ if (node.type === "TemplateElement") quasis.push(node);
38
+ });
39
+
40
+ quasis.sort((a, b) => a.start - b.start);
41
+
42
+ let index = 0;
43
+ for (const { index: offset } of text.matchAll(loneCr)) {
44
+ while (index < quasis.length && quasis[index]!.end <= offset) index++;
45
+ if (index === quasis.length || offset < quasis[index]!.start) return offset;
46
+ }
47
+
48
+ return undefined;
49
+ }
50
+
51
+ export function rejection(text: string, parsed: Parsed): Rejection | undefined {
52
+ const error = parsed.errors[0];
53
+ if (error) return { start: error.labels[0]?.start ?? 0, message: error.message };
54
+
55
+ const cr = crLineEnding(text, parsed.program);
56
+ if (cr !== undefined)
57
+ return { start: cr, message: "CR line endings are not supported, left untouched" };
58
+ }
@@ -0,0 +1,68 @@
1
+ import type { Node, Program } from "oxc-parser";
2
+ import { freeze, ignored, marks, within, type Region } from "../../engine/directives.ts";
3
+ import type { Doc } from "../../engine/model.ts";
4
+ import type { Layout, Scan } from "../language.ts";
5
+ import { braceScan, controlledBlocks } from "./braces.ts";
6
+ import { listAt, type List } from "./lists.ts";
7
+
8
+ const CONTAINERS = new Set([
9
+ "BlockStatement",
10
+ "StaticBlock",
11
+ "SwitchStatement",
12
+ "SwitchCase",
13
+ "ClassBody",
14
+ "TSModuleBlock",
15
+ ]);
16
+
17
+ export function scan(doc: Doc, program: Program, width: Layout): Scan {
18
+ const marked = marks(doc);
19
+ const containers: Region[] = [];
20
+ const escaped = new Set<Node>();
21
+
22
+ const lists: List[] = [];
23
+ const chains = new Map<Node, Node>();
24
+ const frozenOwners = new Set<Node>();
25
+
26
+ const owners = controlledBlocks(program, (node, parent) => {
27
+ const list = listAt(doc, node, width);
28
+ if (list) lists.push(list);
29
+
30
+ if (marked.length > 0)
31
+ if (
32
+ parent !== null &&
33
+ (escaped.has(parent) || node.start < parent.start || parent.end < node.end)
34
+ )
35
+ escaped.add(node);
36
+ else if (CONTAINERS.has(node.type)) containers.push({ start: node.start, end: node.end });
37
+
38
+ if (node.type === "IfStatement")
39
+ chains.set(
40
+ node,
41
+ parent?.type === "IfStatement" && parent.alternate === node
42
+ ? (chains.get(parent) ?? parent)
43
+ : node,
44
+ );
45
+
46
+ if (
47
+ (node.type.endsWith("Statement") && ignored(doc, node.start)) ||
48
+ (parent !== null &&
49
+ frozenOwners.has(parent) &&
50
+ ((parent.type === "IfStatement" && parent.alternate === node) ||
51
+ parent.type === "LabeledStatement"))
52
+ )
53
+ frozenOwners.add(node);
54
+ });
55
+
56
+ const { lists: active, frozen } = freeze(doc, marked, lists, containers);
57
+ const blocks = [...owners]
58
+ .filter(
59
+ ([block, owner]) =>
60
+ !frozenOwners.has(owner) &&
61
+ !frozenOwners.has(block) &&
62
+ !within(frozen, block.start) &&
63
+ !within(frozen, block.end - 1),
64
+ )
65
+ .map(([block]) => block);
66
+
67
+ return { lists: active, frozen, braces: braceScan(doc, blocks, owners, chains) };
68
+ }