codegen.ts 8.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7
import { isString, isSymbol } from '@vue/shared'
import {
  CodegenResult,
  CompoundExpressionNode,
  helperNameMap,
  InterpolationNode,
  NodeTypes,
fxy060608's avatar
fxy060608 已提交
8
  RootNode,
fxy060608's avatar
fxy060608 已提交
9 10 11 12
  SimpleExpressionNode,
  TextNode,
  TO_DISPLAY_STRING,
} from '@vue/compiler-core'
13
import { Expression } from '@babel/types'
fxy060608's avatar
fxy060608 已提交
14
import { default as babelGenerate } from '@babel/generator'
15 16
import { addImportDeclaration, matchEasycom } from '@dcloudio/uni-cli-shared'
import { CodegenOptions, CodegenRootNode } from './options'
fxy060608's avatar
fxy060608 已提交
17
import { createObjectExpression } from './ast'
18

fxy060608's avatar
fxy060608 已提交
19 20 21 22 23
import {
  BindingComponentTypes,
  ImportItem,
  TransformContext,
} from './transform'
fxy060608's avatar
fxy060608 已提交
24

fxy060608's avatar
fxy060608 已提交
25 26
interface CodegenContext extends CodegenOptions {
  code: string
27
  bindingComponents: TransformContext['bindingComponents']
fxy060608's avatar
fxy060608 已提交
28 29 30 31 32 33 34
  indentLevel: number
  push(code: string, node?: CodegenNode): void
  indent(): void
  deindent(withoutNewLine?: boolean): void
  newline(): void
}

fxy060608's avatar
fxy060608 已提交
35
export function generate(
36
  ast: CodegenRootNode,
fxy060608's avatar
fxy060608 已提交
37 38
  options: CodegenOptions
): Omit<CodegenResult, 'ast'> {
fxy060608's avatar
fxy060608 已提交
39 40 41 42 43 44
  const context = createCodegenContext(ast, options)

  const { mode, push, indent, deindent, newline, prefixIdentifiers } = context

  const hasHelpers = ast.helpers.length > 0
  const useWithBlock = !prefixIdentifiers && mode !== 'module'
fxy060608's avatar
fxy060608 已提交
45
  const isSetupInlined = !!options.inline
fxy060608's avatar
fxy060608 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58

  // preambles
  // in setup() inline mode, the preamble is generated in a sub context
  // and returned separately.
  const preambleContext = isSetupInlined
    ? createCodegenContext(ast, options)
    : context
  if (mode === 'module') {
    genModulePreamble(ast, preambleContext, isSetupInlined)
  } else {
    genFunctionPreamble(ast, preambleContext)
  }

fxy060608's avatar
fxy060608 已提交
59 60 61 62 63 64 65 66 67 68
  // enter render function
  const functionName = `render`
  const args = ['_ctx', '_cache']
  if (options.bindingMetadata && !options.inline) {
    // binding optimization args
    args.push('$props', '$setup', '$data', '$options')
  }
  const signature = options.isTS
    ? args.map((arg) => `${arg}: any`).join(',')
    : args.join(', ')
fxy060608's avatar
fxy060608 已提交
69

fxy060608's avatar
fxy060608 已提交
70
  if (isSetupInlined) {
fxy060608's avatar
fxy060608 已提交
71
    push(`(${signature}) => {`)
fxy060608's avatar
fxy060608 已提交
72
  } else {
fxy060608's avatar
fxy060608 已提交
73
    push(`function ${functionName}(${signature}) {`)
fxy060608's avatar
fxy060608 已提交
74
  }
fxy060608's avatar
fxy060608 已提交
75
  indent()
fxy060608's avatar
fxy060608 已提交
76

fxy060608's avatar
fxy060608 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  if (useWithBlock) {
    push(`with (_ctx) {`)
    indent()
    if (hasHelpers) {
      push(
        `const { ${ast.helpers
          .map((s) => `${helperNameMap[s]}: _${helperNameMap[s]}`)
          .join(', ')} } = _Vue`
      )
      push(`\n`)
      newline()
    }
  }

  push(`return `)
92
  push(genBabelExpr(createObjectExpression(ast.scope.properties)))
fxy060608's avatar
fxy060608 已提交
93 94 95 96 97 98
  if (useWithBlock) {
    deindent()
    push(`}`)
  }
  deindent()
  push(`}`)
fxy060608's avatar
fxy060608 已提交
99
  return {
fxy060608's avatar
fxy060608 已提交
100 101 102 103 104 105
    code: context.code,
    preamble: isSetupInlined ? preambleContext.code : ``,
  }
}

function createCodegenContext(
106
  ast: CodegenRootNode,
fxy060608's avatar
fxy060608 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  {
    mode = 'function',
    prefixIdentifiers = mode === 'module',
    filename = `template.vue.html`,
    scopeId = null,
    runtimeGlobalName = `Vue`,
    runtimeModuleName = `vue`,
    isTS = false,
  }: CodegenOptions
): CodegenContext {
  const context: CodegenContext = {
    mode,
    prefixIdentifiers,
    filename,
    scopeId,
    runtimeGlobalName,
    runtimeModuleName,
124
    bindingComponents: ast.bindingComponents,
fxy060608's avatar
fxy060608 已提交
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
    isTS,
    code: ``,
    indentLevel: 0,
    push(code, node) {
      context.code += code
    },
    indent() {
      newline(++context.indentLevel)
    },
    deindent(withoutNewLine = false) {
      if (withoutNewLine) {
        --context.indentLevel
      } else {
        newline(--context.indentLevel)
      }
    },
    newline() {
      newline(context.indentLevel)
    },
  }

  function newline(n: number) {
    context.push('\n' + `  `.repeat(n))
  }

  return context
}

153 154
function genComponentImports(
  bindingComponents: TransformContext['bindingComponents'],
fxy060608's avatar
fxy060608 已提交
155
  { push, newline }: CodegenContext
156
) {
fxy060608's avatar
fxy060608 已提交
157
  const tags = Object.keys(bindingComponents)
158
  const importDeclarations: string[] = []
159 160
  // 仅记录easycom和setup组件
  const components: string[] = []
fxy060608's avatar
fxy060608 已提交
161
  tags.forEach((tag) => {
162 163 164 165
    const { name, type } = bindingComponents[tag]
    if (type === BindingComponentTypes.UNKNOWN) {
      const source = matchEasycom(tag)
      if (source) {
fxy060608's avatar
fxy060608 已提交
166 167 168 169 170
        // 调整为easycom命名
        const easycomName = name.replace('component', 'easycom')
        bindingComponents[tag].name = easycomName
        components.push(easycomName)
        addImportDeclaration(importDeclarations, easycomName, source)
171
      }
172 173
    } else if (type === BindingComponentTypes.SETUP) {
      components.push(name)
174 175
    }
  })
fxy060608's avatar
fxy060608 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  if (tags.length) {
    push(
      `const __BINDING_COMPONENTS__ = '` +
        JSON.stringify(bindingComponents) +
        `'`
    )
    newline()
    importDeclarations.forEach((str) => push(str))
    if (importDeclarations.length) {
      newline()
    }
    if (components.length) {
      push(`if (!Math) {`)
      push(` Math.max.call(Max, ${components.map((name) => name).join(', ')}) `)
      push(`}`)
      newline()
    }
193 194 195
  }
}

fxy060608's avatar
fxy060608 已提交
196
function genFunctionPreamble(ast: RootNode, context: CodegenContext) {
197 198 199 200 201 202 203
  const {
    prefixIdentifiers,
    push,
    newline,
    runtimeGlobalName,
    bindingComponents,
  } = context
fxy060608's avatar
fxy060608 已提交
204 205 206 207 208 209 210 211 212 213 214
  const VueBinding = runtimeGlobalName
  const aliasHelper = (s: symbol) => `${helperNameMap[s]}: _${helperNameMap[s]}`
  if (ast.helpers.length > 0) {
    if (prefixIdentifiers) {
      push(
        `const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`
      )
    } else {
      push(`const _Vue = ${VueBinding}\n`)
    }
  }
215
  genComponentImports(bindingComponents, context)
fxy060608's avatar
fxy060608 已提交
216 217 218 219 220 221 222 223 224
  newline()
  push(`return `)
}

function genModulePreamble(
  ast: RootNode,
  context: CodegenContext,
  inline?: boolean
) {
225
  const { push, newline, runtimeModuleName, bindingComponents } = context
fxy060608's avatar
fxy060608 已提交
226 227 228 229 230 231 232
  if (ast.helpers.length) {
    push(
      `import { ${ast.helpers
        .map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`)
        .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`
    )
  }
fxy060608's avatar
fxy060608 已提交
233 234 235 236 237

  if (ast.imports.length) {
    genImports(ast.imports, context)
  }

238
  genComponentImports(bindingComponents, context)
fxy060608's avatar
fxy060608 已提交
239 240 241
  newline()
  if (!inline) {
    push(`export `)
fxy060608's avatar
fxy060608 已提交
242 243 244
  }
}

fxy060608's avatar
fxy060608 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
function genImports(
  importsOptions: ImportItem[],
  { push, newline }: CodegenContext
) {
  if (!importsOptions.length) {
    return
  }
  importsOptions.forEach((imports) => {
    push(`import `)
    push(genExpr(imports.exp))
    push(` from '${imports.path}'`)
    newline()
  })
}

fxy060608's avatar
fxy060608 已提交
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
type CodegenNode =
  | SimpleExpressionNode
  | CompoundExpressionNode
  | InterpolationNode
  | TextNode
  | string
  | symbol

interface GenNodeContext {
  code: string
  helper(key: symbol): string
  push(code: string, node?: CodegenNode): void
}

function createGenNodeContext() {
  const context: GenNodeContext = {
    code: '',
    helper(key) {
      return `_${helperNameMap[key]}`
    },
    push(code) {
      context.code += code
    },
  }
  return context
}

fxy060608's avatar
fxy060608 已提交
287 288 289 290 291 292 293 294 295
export function genBabelExpr(expr: Expression) {
  return babelGenerate(expr, {
    concise: true,
    jsescOption: {
      quotes: 'single',
    },
  }).code
}

fxy060608's avatar
fxy060608 已提交
296 297 298 299 300 301 302 303
export function genExpr(
  node: CodegenNode | symbol | string,
  context?: GenNodeContext
) {
  return genNode(node, context).code
}

function genNode(
fxy060608's avatar
fxy060608 已提交
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
  node: CodegenNode | symbol | string,
  context?: GenNodeContext
) {
  if (!context) {
    context = createGenNodeContext()
  }
  if (isString(node)) {
    context.push(node)
    return context
  }
  if (isSymbol(node)) {
    context.push(context.helper(node))
    return context
  }
  switch (node.type) {
    case NodeTypes.TEXT:
      genText(node, context)
      break
    case NodeTypes.SIMPLE_EXPRESSION:
      genExpression(node, context)
      break
    case NodeTypes.INTERPOLATION:
      genInterpolation(node, context)
      break
    case NodeTypes.COMPOUND_EXPRESSION:
      genCompoundExpression(node, context)
      break
  }
  return context
}

function genText(
  node: TextNode | SimpleExpressionNode,
  context: GenNodeContext
) {
  context.push(JSON.stringify(node.content), node)
}

function genExpression(node: SimpleExpressionNode, context: GenNodeContext) {
  const { content, isStatic } = node
  context.push(isStatic ? JSON.stringify(content) : content, node)
}

function genInterpolation(node: InterpolationNode, context: GenNodeContext) {
  const { push, helper } = context
  push(`${helper(TO_DISPLAY_STRING)}(`)
fxy060608's avatar
fxy060608 已提交
350
  genExpr(node.content, context)
fxy060608's avatar
fxy060608 已提交
351 352 353 354 355 356 357 358 359 360 361 362
  push(`)`)
}

function genCompoundExpression(
  node: CompoundExpressionNode,
  context: GenNodeContext
) {
  for (let i = 0; i < node.children!.length; i++) {
    const child = node.children![i]
    if (isString(child)) {
      context.push(child)
    } else {
fxy060608's avatar
fxy060608 已提交
363
      genExpr(child, context)
fxy060608's avatar
fxy060608 已提交
364 365 366
    }
  }
}