-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
Copy pathgenerate.ts
188 lines (161 loc) · 4.6 KB
/
generate.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
import type {
CodegenOptions as BaseCodegenOptions,
BaseCodegenResult,
SimpleExpressionNode,
} from '@vue/compiler-dom'
import type { BlockIRNode, CoreHelper, RootIRNode, VaporHelper } from './ir'
import { extend, remove } from '@vue/shared'
import { genBlockContent } from './generators/block'
import { genTemplates } from './generators/template'
import {
type CodeFragment,
INDENT_END,
INDENT_START,
LF,
NEWLINE,
buildCodeFragment,
codeFragmentToString,
genCall,
} from './generators/utils'
import { setTemplateRefIdent } from './generators/templateRef'
type CustomGenOperation = (
opers: any,
context: CodegenContext,
) => CodeFragment[] | void
export type CodegenOptions = Omit<BaseCodegenOptions, 'optimizeImports'> & {
customGenOperation?: CustomGenOperation | null
}
export class CodegenContext {
options: Required<CodegenOptions>
helpers: Set<string> = new Set<string>([])
helper = (name: CoreHelper | VaporHelper) => {
this.helpers.add(name)
return `_${name}`
}
delegates: Set<string> = new Set<string>()
identifiers: Record<string, (string | SimpleExpressionNode)[]> =
Object.create(null)
seenInlineHandlerNames: Record<string, number> = Object.create(null)
block: BlockIRNode
withId<T>(
fn: () => T,
map: Record<string, string | SimpleExpressionNode | null>,
): T {
const { identifiers } = this
const ids = Object.keys(map)
for (const id of ids) {
identifiers[id] ||= []
identifiers[id].unshift(map[id] || id)
}
const ret = fn()
ids.forEach(id => remove(identifiers[id], map[id] || id))
return ret
}
enterBlock(block: BlockIRNode) {
const parent = this.block
this.block = block
return (): BlockIRNode => (this.block = parent)
}
scopeLevel: number = 0
enterScope(): [level: number, exit: () => number] {
return [this.scopeLevel++, () => this.scopeLevel--] as const
}
constructor(
public ir: RootIRNode,
options: CodegenOptions,
) {
const defaultOptions: Required<CodegenOptions> = {
mode: 'module',
prefixIdentifiers: true,
sourceMap: false,
filename: `template.vue.html`,
scopeId: null,
runtimeGlobalName: `Vue`,
runtimeModuleName: `vue`,
ssrRuntimeModuleName: 'vue/server-renderer',
ssr: false,
isTS: false,
inSSR: false,
inline: false,
bindingMetadata: {},
expressionPlugins: [],
customGenOperation: null,
}
this.options = extend(defaultOptions, options)
this.block = ir.block
}
}
export interface VaporCodegenResult extends BaseCodegenResult {
ast: RootIRNode
helpers: Set<string>
}
// IR -> JS codegen
export function generate(
ir: RootIRNode,
options: CodegenOptions = {},
): VaporCodegenResult {
const [frag, push] = buildCodeFragment()
const context = new CodegenContext(ir, options)
const { helpers } = context
const { inline, bindingMetadata } = options
const functionName = 'render'
const args = ['_ctx']
if (bindingMetadata && !inline) {
// binding optimization args
args.push('$props', '$emit', '$attrs', '$slots')
}
const signature = (options.isTS ? args.map(arg => `${arg}: any`) : args).join(
', ',
)
if (!inline) {
push(NEWLINE, `export function ${functionName}(${signature}) {`)
}
push(INDENT_START)
if (ir.hasTemplateRef) {
push(
NEWLINE,
`const ${setTemplateRefIdent} = ${context.helper('createTemplateRefSetter')}()`,
)
}
push(...genBlockContent(ir.block, context, true))
push(INDENT_END, NEWLINE)
if (!inline) {
push('}')
}
const delegates = genDelegates(context)
const templates = genTemplates(ir.template, ir.rootTemplateIndex, context)
const imports = genHelperImports(context)
const preamble = imports + templates + delegates
const newlineCount = [...preamble].filter(c => c === '\n').length
if (newlineCount && !inline) {
frag.unshift(...new Array<CodeFragment>(newlineCount).fill(LF))
}
let [code, map] = codeFragmentToString(frag, context)
if (!inline) {
code = preamble + code
}
return {
code,
ast: ir,
preamble,
map: map && map.toJSON(),
helpers,
}
}
function genDelegates({ delegates, helper }: CodegenContext) {
return delegates.size
? genCall(
helper('delegateEvents'),
...Array.from(delegates).map(v => `"${v}"`),
).join('') + '\n'
: ''
}
function genHelperImports({ helpers, helper, options }: CodegenContext) {
let imports = ''
if (helpers.size) {
imports += `import { ${[...helpers]
.map(h => `${h} as _${h}`)
.join(', ')} } from '${options.runtimeModuleName}';\n`
}
return imports
}