/
ast.ts
336 lines (309 loc) · 8.69 KB
/
ast.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { babelParse as _babelParse, walkIdentifiers } from '@vue/compiler-sfc'
// @ts-ignore error in node CJS (volar tsconfig)
import { walk } from 'estree-walker'
import {
type CallExpression,
type Function,
type Literal,
type Node,
type ObjectExpression,
type ObjectMethod,
type ObjectProperty,
type Program,
type TemplateLiteral,
} from '@babel/types'
import { type ParserOptions, type ParserPlugin } from '@babel/parser'
import { type MagicStringBase } from 'magic-string-ast'
import { isTs } from './lang'
import { REGEX_LANG_JSX } from './constants'
export function babelParse(
code: string,
lang?: string,
options: ParserOptions = {}
): Program {
const plugins: ParserPlugin[] = [...(options.plugins || [])]
if (isTs(lang)) {
plugins.push(['typescript', { dts: lang === 'dts' }])
if (REGEX_LANG_JSX.test(lang!)) plugins.push('jsx')
if (!plugins.includes('decorators')) plugins.push('decorators-legacy')
} else {
plugins.push('jsx')
}
const { program } = _babelParse(code, {
sourceType: 'module',
plugins,
...options,
})
return program
}
export function isCallOf(
node: Node | null | undefined,
test: string | string[] | ((id: string) => boolean)
): node is CallExpression {
return !!(
node &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
(typeof test === 'string'
? node.callee.name === test
: Array.isArray(test)
? test.includes(node.callee.name)
: test(node.callee.name))
)
}
export function checkInvalidScopeReference(
node: Node | undefined,
method: string,
setupBindings: string[]
) {
if (!node) return
walkIdentifiers(node, (id) => {
if (setupBindings.includes(id.name))
throw new SyntaxError(
`\`${method}()\` in <script setup> cannot reference locally ` +
`declared variables (${id.name}) because it will be hoisted outside of the ` +
`setup() function.`
)
})
}
export function isStaticExpression(
node: Node,
options: Partial<
Record<
'object' | 'fn' | 'objectMethod' | 'array' | 'unary' | 'regex',
boolean
> & {
magicComment?: string
}
> = {}
): boolean {
const { magicComment, fn, object, objectMethod, array, unary, regex } =
options
// magic comment
if (
magicComment &&
node.leadingComments?.some(
(comment) => comment.value.trim() === magicComment
)
)
return true
else if (fn && isFunctionType(node)) return true
switch (node.type) {
case 'UnaryExpression': // !true
return !!unary && isStaticExpression(node.argument, options)
case 'LogicalExpression': // 1 > 2
case 'BinaryExpression': // 1 + 2
return (
isStaticExpression(node.left, options) &&
isStaticExpression(node.right, options)
)
case 'ConditionalExpression': // 1 ? 2 : 3
return (
isStaticExpression(node.test, options) &&
isStaticExpression(node.consequent, options) &&
isStaticExpression(node.alternate, options)
)
case 'SequenceExpression': // (1, 2)
case 'TemplateLiteral': // `123`
return node.expressions.every((expr) => isStaticExpression(expr, options))
case 'ArrayExpression': // [1, 2]
return (
!!array &&
node.elements.every(
(element) => element && isStaticExpression(element, options)
)
)
case 'ObjectExpression': // { foo: 1 }
return (
!!object &&
node.properties.every((prop) => {
if (prop.type === 'SpreadElement') {
return (
prop.argument.type === 'ObjectExpression' &&
isStaticExpression(prop.argument, options)
)
} else if (!isLiteralType(prop.key) && prop.computed) {
return false
} else if (
prop.type === 'ObjectProperty' &&
!isStaticExpression(prop.value, options)
) {
return false
}
if (prop.type === 'ObjectMethod' && !objectMethod) {
return false
}
return true
})
)
case 'ParenthesizedExpression': // (1)
case 'TSNonNullExpression': // 1!
case 'TSAsExpression': // 1 as number
case 'TSTypeAssertion': // (<number>2)
case 'TSSatisfiesExpression': // 1 satisfies number
return isStaticExpression(node.expression, options)
case 'RegExpLiteral':
return !!regex
}
if (isLiteralType(node)) return true
return false
}
export function isLiteralType(node: Node): node is Literal {
return node.type.endsWith('Literal')
}
export function resolveTemplateLiteral(node: TemplateLiteral) {
return node.quasis.reduce((prev, curr, idx) => {
if (node.expressions[idx]) {
return (
prev +
curr.value.cooked +
resolveLiteral(node.expressions[idx] as Literal)
)
}
return prev + curr.value.cooked
}, '')
}
export function resolveLiteral(
node: Literal
): string | number | boolean | null | RegExp | bigint {
switch (node.type) {
case 'TemplateLiteral':
return resolveTemplateLiteral(node)
case 'NullLiteral':
return null
case 'BigIntLiteral':
return BigInt(node.value)
case 'RegExpLiteral':
return new RegExp(node.pattern, node.flags)
case 'BooleanLiteral':
case 'NumericLiteral':
case 'StringLiteral':
return node.value
}
return undefined as never
}
export function isStaticObjectKey(node: ObjectExpression): boolean {
return node.properties.every((prop) => {
if (prop.type === 'SpreadElement') {
return (
prop.argument.type === 'ObjectExpression' &&
isStaticObjectKey(prop.argument)
)
}
return !prop.computed || isLiteralType(prop.key)
})
}
/**
* @param node must be a static expression, SpreadElement is not supported
*/
export function resolveObjectExpression(node: ObjectExpression) {
const maps: Record<string | number, ObjectMethod | ObjectProperty> = {}
for (const property of node.properties) {
if (property.type === 'SpreadElement') {
if (property.argument.type !== 'ObjectExpression')
// not supported
return undefined
Object.assign(maps, resolveObjectExpression(property.argument)!)
} else {
const key = resolveObjectKey(property.key, property.computed, false)
maps[key] = property
}
}
return maps
}
export function resolveObjectKey(
node: Node,
computed?: boolean,
raw?: true
): string
export function resolveObjectKey(
node: Node,
computed: boolean | undefined,
raw: false
): string | number
export function resolveObjectKey(node: Node, computed = false, raw = true) {
switch (node.type) {
case 'StringLiteral':
case 'NumericLiteral':
return raw ? node.extra!.raw : node.value
case 'Identifier':
if (!computed) return raw ? `'${node.name}'` : node.name
// break omitted intentionally
default:
throw new SyntaxError(`Unexpected node type: ${node.type}`)
}
}
export function walkAST<T = Node>(
node: T,
options: {
enter?: (
this: {
skip: () => void
remove: () => void
replace: (node: T) => void
},
node: T,
parent: T,
key: string,
index: number
) => void
leave?: (
this: {
skip: () => void
remove: () => void
replace: (node: T) => void
},
node: T,
parent: T,
key: string,
index: number
) => void
}
): T {
return walk(node as any, options as any) as any
}
export function isFunctionType(node: Node): node is Function {
return /Function(?:Expression|Declaration)$|Method$/.test(node.type)
}
export const TS_NODE_TYPES = [
'TSAsExpression', // foo as number
'TSTypeAssertion', // (<number>foo)
'TSNonNullExpression', // foo!
'TSInstantiationExpression', // foo<string>
'TSSatisfiesExpression', // foo satisfies T
]
export function unwrapTSNode(node: Node): Node {
if (TS_NODE_TYPES.includes(node.type)) {
return unwrapTSNode((node as any).expression)
} else {
return node
}
}
const importedMap = new WeakMap<MagicStringBase, Set<string>>()
export const HELPER_PREFIX = '__MACROS_'
export function importHelperFn(
s: MagicStringBase,
offset: number,
local: string,
from = 'vue',
isDefault = false
) {
const imported = isDefault ? 'default' : local
const cacheKey = `${from}@${imported}`
if (!importedMap.get(s)?.has(cacheKey)) {
s.appendLeft(
offset,
`\nimport ${
isDefault
? HELPER_PREFIX + local
: `{ ${imported} as ${HELPER_PREFIX + local} }`
} from ${JSON.stringify(from)};`
)
if (!importedMap.has(s)) {
importedMap.set(s, new Set([cacheKey]))
} else {
importedMap.get(s)!.add(cacheKey)
}
}
return `${HELPER_PREFIX}${local}`
}