Open History to see the last commit
1import { is, walk } from 'yuku-ast'
2import { unwrapExpression } from '@tanstack/router-utils'
3import type {
4 CallExpression,
5 Node,
6 Program,
7 VariableDeclarator,
8} from '@yuku-toolchain/types'
9import type { StartCompilerTransformContext } from '../types'
10β
11/** JavaScript line terminators, as counted by editors and parsers. */
12const lineTerminator = /\r\n|[\n\r\u2028\u2029]/
13β
14export function sourcePosition(code: string, offset: number) {
15 const lines = code.slice(0, offset).split(lineTerminator)
16 return { line: lines.length, column: lines[lines.length - 1]!.length }
17}
18β
19export function codeFrameError(
20 code: string,
21 node: Pick<Node, 'start' | 'end'>,
22 message: string,
23) {
24 const start = sourcePosition(code, node.start)
25 const lines = code.split(lineTerminator)
26 const frame = lines
27 .slice(Math.max(0, start.line - 2), start.line + 1)
28 .map((line, index) => {
29 const number = Math.max(1, start.line - 1) + index
30 return `${number} | ${line}${number === start.line ? `\n | ${' '.repeat(start.column)}^ ${message}` : ''}`
31 })
32 .join('\n')
33 return new Error(frame)
34}
35β
36/** Keep semantic module IDs intact; this is only for physical-file matching. */
37export function cleanId(id: string): string {
38 if (id.startsWith('\0')) {
39 id = id.slice(1)
40 }
41 const queryIndex = id.indexOf('?')
42 return queryIndex === -1 ? id : id.substring(0, queryIndex)
43}
44β
45/** Output-tree edits use native node identity; semantic queries use the source module. */
46export function createAstEditor(ast: Program) {
47 const parents = new WeakMap<Node, { parent: Node; key: string }>()
48 const replaced = new WeakSet<Node>()
49 function indexSubtree(root: Node) {
50 walk(root, {
51 enter(node, context) {
52 if (context.parent && context.key) {
53 parents.set(node, { parent: context.parent, key: context.key })
54 }
55 },
56 })
57 }
58 indexSubtree(ast)
59 return {
60 parentOf(node: Node): Node | null {
61 return parents.get(node)?.parent ?? null
62 },
63 replaceNode(node: Node, replacement: Node): void {
64 const position = parents.get(node)
65 if (!position) {
66 throw new Error('Cannot replace a node outside the output tree')
67 }
68 const record = position.parent as unknown as Record<string, unknown>
69 const field = record[position.key]
70 if (Array.isArray(field)) {
71 const index = field.indexOf(node)
72 if (index < 0) {
73 throw new Error('Cannot replace a detached output node')
74 }
75 field[index] = replacement
76 } else {
77 record[position.key] = replacement
78 }
79 parents.set(replacement, position)
80 indexSubtree(replacement)
81 replaced.add(node)
82 },
83 /** Whether `replaceNode` removed `node` or one of its ancestors. */
84 isReplaced(node: Node): boolean {
85 for (
86 let current: Node | undefined = node;
87 current;
88 current = parents.get(current)?.parent
89 ) {
90 if (replaced.has(current)) {
91 return true
92 }
93 }
94 return false
95 },
96 }
97}
98β
99export function getVariableDeclarator(
100 node: Node,
101 parentOf: (node: Node) => Node | null,
102): VariableDeclarator | null {
103 let parent = parentOf(node)
104 while (
105 parent &&
106 is.oneOf(parent, [
107 'ChainExpression',
108 'ParenthesizedExpression',
109 'TSAsExpression',
110 'TSSatisfiesExpression',
111 'TSNonNullExpression',
112 'TSTypeAssertion',
113 ])
114 ) {
115 node = parent
116 parent = parentOf(node)
117 }
118 return is.VariableDeclarator(parent) && parent.init === node ? parent : null
119}
120β
121export function stripMethodCall(
122 call: CallExpression,
123 context: StartCompilerTransformContext,
124): void {
125 const callee = is.Expression(call.callee)
126 ? unwrapExpression(call.callee)
127 : call.callee
128 if (is.MemberExpression(callee)) {
129 context.replaceNode(call, callee.object)
130 }
131}