-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathtransform.ts
755 lines (717 loc) · 19.8 KB
/
transform.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import { EMPTY_OBJ, NOOP, extend, hasOwn, isArray, isString } from '@vue/shared'
import {
type ArrowFunctionExpression,
type BlockStatement,
type ConditionalExpression,
type Identifier,
type ObjectExpression,
type ObjectProperty,
type ReturnStatement,
type SpreadElement,
callExpression,
identifier,
isCallExpression,
isConditionalExpression,
isIdentifier,
isObjectExpression,
isObjectProperty,
isSpreadElement,
objectExpression,
spreadElement,
} from '@babel/types'
import {
type CacheExpression,
type CompilerError,
type DirectiveNode,
type ElementNode,
type ExpressionNode,
type JSChildNode,
NodeTypes,
type ParentNode,
type Property,
type RootNode,
TO_DISPLAY_STRING,
type TemplateChildNode,
helperNameMap,
locStub,
} from '@vue/compiler-core'
import { findMiniProgramUsingComponents } from '@dcloudio/uni-cli-shared'
import type {
MiniProgramComponentsType,
MiniProgramFilterOptions,
} from '@dcloudio/uni-cli-shared'
import IdentifierGenerator from './identifier'
import type {
CodegenRootNode,
CodegenRootScope,
CodegenScope,
CodegenVForScope,
CodegenVForScopeInit,
CodegenVIfScope,
CodegenVIfScopeInit,
TransformOptions,
} from './options'
import { EXTEND } from './runtimeHelpers'
import { createObjectExpression } from './ast'
import { SCOPED_SLOT_IDENTIFIER } from './transforms/utils'
import { genBabelExpr } from './codegen'
export interface ImportItem {
exp: string | ExpressionNode
path: string
}
export type NodeTransform = (
node: RootNode | TemplateChildNode,
context: TransformContext
) => void | (() => void) | (() => void)[]
export type DirectiveTransform = (
dir: DirectiveNode,
node: ElementNode,
context: TransformContext,
augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult
) => DirectiveTransformResult
interface DirectiveTransformResult {
props: Property[]
needRuntime?: boolean | symbol
}
export interface ErrorHandlingOptions {
onWarn?: (warning: CompilerError) => void
onError?: (error: CompilerError) => void
}
export const enum BindingComponentTypes {
SELF = 'self',
SETUP = 'setup',
UNKNOWN = 'unknown',
}
export interface TransformContext
extends Required<Omit<TransformOptions, 'filename' | 'root'>> {
selfName: string | null
currentNode: RootNode | TemplateChildNode | null
parent: ParentNode | null
childIndex: number
helpers: Map<symbol, number>
components: Set<string>
imports: ImportItem[]
autoImportFilters: Array<Omit<MiniProgramFilterOptions, 'code'>>
bindingComponents: Record<
string,
{ type: BindingComponentTypes; name: string }
>
identifiers: { [name: string]: number | undefined }
cached: number
scopes: {
vFor: number
vueId: number
}
scope: CodegenRootScope
currentScope: CodegenScope
currentVueId: string
vueIds: string[]
inVOnce: boolean
inVFor: boolean
helper<T extends symbol>(name: T): T
removeHelper<T extends symbol>(name: T): void
helperString(name: symbol): string
replaceNode(node: TemplateChildNode): void
removeNode(node?: TemplateChildNode): void
onNodeRemoved(): void
addIdentifiers(exp: ExpressionNode | string): void
removeIdentifiers(exp: ExpressionNode | string): void
popScope(): CodegenScope | undefined
getScopeIndex(scope: CodegenScope): number
addVIfScope(initScope: CodegenVIfScopeInit): CodegenVIfScope
addVForScope(initScope: CodegenVForScopeInit): CodegenVForScope
cache<T extends JSChildNode>(exp: T, isVNode?: boolean): CacheExpression | T
isMiniProgramComponent(name: string): MiniProgramComponentsType | undefined
rootNode: TemplateChildNode | null
elementRefIndex: number
}
export function isRootScope(scope: CodegenScope): scope is CodegenRootScope {
return !isVIfScope(scope) && !isVForScope(scope)
}
export function isVIfScope(scope: CodegenScope): scope is CodegenVIfScope {
return (
!!(scope as CodegenVIfScope).condition ||
(scope as CodegenVIfScope).name === 'else'
)
}
export function isVForScope(scope: CodegenScope): scope is CodegenVForScope {
return !!(scope as CodegenVForScope).source
}
export function isScopedSlotVFor({ source }: CodegenVForScope) {
if (source.type !== NodeTypes.COMPOUND_EXPRESSION) {
return false
}
const first = source.children[0] as ExpressionNode
return (
first.type === NodeTypes.SIMPLE_EXPRESSION &&
first.content.includes(SCOPED_SLOT_IDENTIFIER)
)
}
export function transform(root: CodegenRootNode, options: TransformOptions) {
const context = createTransformContext(root, options)
findRootNode(root, context)
traverseNode(root, context)
root.renderData = createRenderDataExpr(context.scope.properties, context)
// finalize meta information
root.helpers = new Set([...context.helpers.keys()])
root.components = [...context.components]
root.imports = context.imports
root.cached = context.cached
return context
}
function findRootNode(root: RootNode, context: TransformContext) {
const children = root.children.filter(
(node) => node.type === NodeTypes.ELEMENT && node.tag !== 'template'
)
if (children.length === 1) {
context.rootNode = children[0]
}
}
export function traverseNode(
node: RootNode | TemplateChildNode,
context: TransformContext
) {
context.currentNode = node
// apply transform plugins
const { nodeTransforms } = context
const exitFns: Array<() => void> = []
for (let i = 0; i < nodeTransforms.length; i++) {
const onExit = nodeTransforms[i](node, context as any)
if (onExit) {
if (isArray(onExit)) {
exitFns.push(...onExit)
} else {
exitFns.push(onExit)
}
}
if (!context.currentNode) {
// node was removed
return
} else {
// node may have been replaced
node = context.currentNode
}
}
switch (node.type) {
case NodeTypes.COMMENT:
// context.helper(CREATE_COMMENT)
break
case NodeTypes.INTERPOLATION:
context.helper(TO_DISPLAY_STRING)
break
// for container types, further traverse downwards
case NodeTypes.IF:
for (let i = 0; i < node.branches.length; i++) {
traverseNode(node.branches[i], context)
}
break
case NodeTypes.IF_BRANCH:
case NodeTypes.FOR:
case NodeTypes.ELEMENT:
case NodeTypes.ROOT:
traverseChildren(node, context)
break
}
// exit transforms
context.currentNode = node
let i = exitFns.length
while (i--) {
exitFns[i]()
}
}
export function traverseChildren(
parent: ParentNode,
context: TransformContext
) {
let i = 0
const nodeRemoved = () => {
i--
}
for (; i < parent.children.length; i++) {
const child = parent.children[i]
if (isString(child)) continue
context.parent = parent
context.childIndex = i
context.onNodeRemoved = nodeRemoved
traverseNode(child, context)
}
}
function defaultOnError(error: CompilerError) {
throw error
}
function defaultOnWarn(msg: CompilerError) {
console.warn(`[Vue warn] ${msg.message}`)
}
export function createTransformContext(
rootNode: RootNode,
{
isX = false,
root = '',
filename = '',
isTS = false,
inline = false,
hashId = null,
scopeId = null,
filters = [],
bindingCssVars = [],
bindingMetadata = EMPTY_OBJ,
cacheHandlers = false,
prefixIdentifiers = false,
skipTransformIdentifier = false,
renderDataSpread = false,
nodeTransforms = [],
directiveTransforms = {},
miniProgram = {
class: {
array: true,
},
slot: {
fallbackContent: false,
dynamicSlotNames: true,
},
directive: '',
},
isBuiltInComponent = NOOP,
isCustomElement = NOOP,
expressionPlugins = [],
onError = defaultOnError,
onWarn = defaultOnWarn,
}: TransformOptions
): TransformContext {
const rootScope: CodegenRootScope = {
id: new IdentifierGenerator(),
identifiers: [],
properties: [],
parent: null,
}
function findVIfParentScope(): CodegenVForScope | CodegenRootScope {
for (let i = scopes.length - 1; i >= 0; i--) {
const scope = scopes[i]
if (isVForScope(scope) || isRootScope(scope)) {
return scope
}
}
return rootScope
}
function createScope(
id: IdentifierGenerator,
initScope: CodegenVIfScopeInit | CodegenVForScopeInit
) {
return extend(
{
id,
properties: [],
parent: scopes[scopes.length - 1],
get identifiers() {
return Object.keys(identifiers)
},
},
initScope
)
}
const vueIds: string[] = []
const identifiers = Object.create(null)
const scopes: CodegenScope[] = [rootScope]
const miniProgramComponents = findMiniProgramUsingComponents({
filename,
componentsDir: miniProgram.component?.dir,
inputDir: root,
})
// const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/)
const context: TransformContext = {
// options
// 暂不提供根据文件名生成递归组件
isX,
selfName: '', //nameMatch && capitalize(camelize(nameMatch[1])),
miniProgram,
isTS,
inline,
hashId,
scopeId,
filters,
autoImportFilters: [],
bindingCssVars,
bindingMetadata,
cacheHandlers,
prefixIdentifiers,
nodeTransforms,
directiveTransforms,
expressionPlugins,
skipTransformIdentifier,
renderDataSpread,
isBuiltInComponent,
isCustomElement,
onError,
onWarn,
// state
parent: null,
childIndex: 0,
helpers: new Map(),
components: new Set(),
imports: [],
bindingComponents: Object.create(null),
cached: 0,
identifiers,
scope: rootScope,
scopes: {
vFor: 0,
vueId: 0,
},
get currentScope() {
return scopes[scopes.length - 1]
},
currentNode: rootNode,
vueIds,
get currentVueId() {
return vueIds[vueIds.length - 1]
},
inVOnce: false,
get inVFor() {
let parent: CodegenScope | null = scopes[scopes.length - 1]
while (parent) {
if (isVForScope(parent) && !isScopedSlotVFor(parent)) {
return true
}
parent = parent.parent
}
return false
},
// methods
getScopeIndex(scope: CodegenScope) {
return scopes.indexOf(scope)
},
popScope() {
return scopes.pop()
},
addVIfScope(initScope) {
const vIfScope = createScope(
scopes[scopes.length - 1].id,
extend(initScope, { parentScope: findVIfParentScope() })
) as unknown as CodegenVIfScope
scopes.push(vIfScope)
return vIfScope
},
addVForScope(initScope) {
const vForScope = createScope(
new IdentifierGenerator(),
initScope
) as CodegenVForScope
scopes.push(vForScope)
return vForScope
},
helper(name) {
const count = context.helpers.get(name) || 0
context.helpers.set(name, count + 1)
return name
},
removeHelper(name) {
const count = context.helpers.get(name)
if (count) {
const currentCount = count - 1
if (!currentCount) {
context.helpers.delete(name)
} else {
context.helpers.set(name, currentCount)
}
}
},
helperString(name) {
return `_${helperNameMap[context.helper(name)]}`
},
replaceNode(node) {
context.parent!.children[context.childIndex] = context.currentNode = node
},
removeNode(node) {
if (!context.parent) {
throw new Error(`Cannot remove root node.`)
}
const list = context.parent!.children
const removalIndex = node
? list.indexOf(node)
: context.currentNode
? context.childIndex
: -1
/* istanbul ignore if */
if (removalIndex < 0) {
throw new Error(`node being removed is not a child of current parent`)
}
if (!node || node === context.currentNode) {
// current node removed
context.currentNode = null
context.onNodeRemoved()
} else {
// sibling node removed
if (context.childIndex > removalIndex) {
context.childIndex--
context.onNodeRemoved()
}
}
context.parent!.children.splice(removalIndex, 1)
},
onNodeRemoved: () => {},
addIdentifiers(exp) {
if (isString(exp)) {
addId(exp)
} else if (exp.identifiers) {
exp.identifiers.forEach(addId)
} else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
addId(exp.content)
}
},
removeIdentifiers(exp) {
if (isString(exp)) {
removeId(exp)
} else if (exp.identifiers) {
exp.identifiers.forEach(removeId)
} else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
removeId(exp.content)
}
},
cache(exp, isVNode = false) {
return createCacheExpression(context.cached++, exp, isVNode)
},
isMiniProgramComponent(name) {
return miniProgramComponents[name]
},
rootNode: null,
elementRefIndex: 0,
}
function addId(id: string) {
const { identifiers } = context
if (identifiers[id] === undefined) {
identifiers[id] = 0
}
identifiers[id]!++
}
function removeId(id: string) {
context.identifiers[id]!--
}
return context
}
function createCacheExpression(
index: number,
value: JSChildNode,
isVNode: boolean = false
): CacheExpression {
return {
type: NodeTypes.JS_CACHE_EXPRESSION,
index,
value,
isVNode,
loc: locStub,
}
}
export declare type StructuralDirectiveTransform = (
node: ElementNode,
dir: DirectiveNode,
context: TransformContext
) => void | (() => void)
export function createStructuralDirectiveTransform(
name: string | RegExp,
fn: StructuralDirectiveTransform
): NodeTransform {
const matches = isString(name)
? (n: string) => n === name
: (n: string) => name.test(n)
return (node, context) => {
if (node.type === NodeTypes.ELEMENT) {
const { props } = node
// structural directive transforms are not concerned with slots
// as they are handled separately in vSlot.ts
// if (node.tagType === ElementTypes.TEMPLATE && props.some(isVSlot)) {
// return
// }
const exitFns: Array<() => void> = []
for (let i = 0; i < props.length; i++) {
const prop = props[i]
if (prop.type === NodeTypes.DIRECTIVE && matches(prop.name)) {
// structural directives are removed to avoid infinite recursion
// also we remove them *before* applying so that it can further
// traverse itself in case it moves the node around
props.splice(i, 1)
i--
const onExit = fn(node, prop, context)
if (onExit) exitFns.push(onExit)
}
}
return exitFns
}
}
}
function createRenderDataExpr(
properties: (ObjectProperty | SpreadElement)[],
context: TransformContext
) {
const objExpr = createObjectExpression(properties)
if (!hasSpreadElement(objExpr)) {
return objExpr
}
// filters: ['test']
// v-if="text.aa()"
if (context.filters.length) {
transformFilterObjectSpreadExpr(objExpr, context)
}
if (context.renderDataSpread) {
return objExpr
}
return transformObjectSpreadExpr(objExpr, context)
}
function hasSpreadElement(expr: ObjectExpression): boolean {
return expr.properties.some((prop) => {
if (isSpreadElement(prop)) {
return true
} else {
const returnStatement = parseReturnStatement(prop as ObjectProperty)
if (returnStatement) {
return hasSpreadElement(returnStatement.argument as ObjectExpression)
}
}
})
}
// 目前硬编码识别 _f,应该读取 context.helperString
const returnObjExprMap = {
_f: 1, // _f(_ctx.items,()=>{return {}})
_w: 0, // _w(()=>{return {}})
}
function parseReturnStatement(prop: ObjectProperty) {
if (
isObjectProperty(prop) &&
isCallExpression(prop.value) &&
isIdentifier(prop.value.callee)
) {
const { name } = prop.value.callee as Identifier
if (hasOwn(returnObjExprMap, name)) {
return (
(
prop.value.arguments[
returnObjExprMap[name]
] as ArrowFunctionExpression
).body as BlockStatement
).body[0] as ReturnStatement
}
}
}
function transformObjectPropertyExpr(
prop: ObjectProperty,
context: TransformContext
) {
// vFor,withScopedSlot
const returnStatement = parseReturnStatement(prop)
if (returnStatement) {
const objExpr = returnStatement.argument as ObjectExpression
if (hasSpreadElement(objExpr)) {
returnStatement.argument = transformObjectSpreadExpr(objExpr, context)
}
}
return prop
}
function transformObjectSpreadExpr(
objExpr: ObjectExpression,
context: TransformContext
) {
const properties = objExpr.properties as (ObjectProperty | SpreadElement)[]
const args: (ObjectExpression | ConditionalExpression)[] = []
let objExprProperties: ObjectProperty[] = []
properties.forEach((prop) => {
if (isObjectProperty(prop)) {
objExprProperties.push(transformObjectPropertyExpr(prop, context))
} else {
if (objExprProperties.length) {
args.push(objectExpression(objExprProperties))
}
args.push(
transformConditionalExpression(
prop.argument as ConditionalExpression,
context
)
)
objExprProperties = []
}
})
if (objExprProperties.length) {
args.push(objectExpression(objExprProperties))
}
if (args.length === 1) {
return args[0] as ObjectExpression
}
return callExpression(identifier(context.helperString(EXTEND)), args)
}
function transformConditionalExpression(
expr: ConditionalExpression,
context: TransformContext
) {
const { consequent, alternate } = expr
if (isObjectExpression(consequent) && hasSpreadElement(consequent)) {
expr.consequent = transformObjectSpreadExpr(consequent, context)
}
if (isObjectExpression(alternate)) {
if (hasSpreadElement(alternate)) {
expr.alternate = transformObjectSpreadExpr(alternate, context)
}
} else if (isConditionalExpression(alternate)) {
transformConditionalExpression(alternate, context)
}
return expr
}
function transformFilterObjectSpreadExpr(
objExpr: ObjectExpression,
context: TransformContext
) {
const properties = objExpr.properties as (ObjectProperty | SpreadElement)[]
properties.forEach((prop) => {
if (isObjectProperty(prop)) {
transformFilterObjectPropertyExpr(prop, context)
} else {
prop.argument = transformFilterConditionalExpression(
prop.argument as ConditionalExpression,
context
)
}
})
}
function transformFilterObjectPropertyExpr(
prop: ObjectProperty,
context: TransformContext
) {
// vFor, withScopedSlot
const returnStatement = parseReturnStatement(prop)
if (returnStatement) {
const objExpr = returnStatement.argument as ObjectExpression
if (hasSpreadElement(objExpr)) {
transformFilterObjectSpreadExpr(objExpr, context)
}
}
}
function transformFilterConditionalExpression(
expr: ConditionalExpression,
context: TransformContext
) {
const { test, consequent, alternate } = expr
if (isObjectExpression(consequent) && hasSpreadElement(consequent)) {
transformFilterObjectSpreadExpr(consequent, context)
}
if (isObjectExpression(alternate)) {
if (hasSpreadElement(alternate)) {
transformFilterObjectSpreadExpr(alternate, context)
}
} else if (isConditionalExpression(alternate)) {
expr.alternate = transformFilterConditionalExpression(alternate, context)
}
const testCode = genBabelExpr(test)
// filter test
if (context.filters.find((filter) => testCode.includes(filter + '.'))) {
// test.aa() ? {a:1} : {b:2} => {...{a:1},...{b:2}}
const properties: SpreadElement[] = []
if (!isObjectExpression(consequent) || consequent.properties.length) {
properties.push(spreadElement(consequent))
}
if (
!isObjectExpression(expr.alternate) ||
expr.alternate.properties.length
) {
properties.push(spreadElement(expr.alternate))
}
return objectExpression(properties)
}
return expr
}