codegen.ts 8.4 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 17
import { addImportDeclaration, matchEasycom } from '@dcloudio/uni-cli-shared'
import { CodegenOptions, CodegenRootNode } from './options'

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

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

fxy060608's avatar
fxy060608 已提交
34
export function generate(
35
  ast: CodegenRootNode,
fxy060608's avatar
fxy060608 已提交
36 37
  options: CodegenOptions
): Omit<CodegenResult, 'ast'> {
fxy060608's avatar
fxy060608 已提交
38 39 40 41 42 43
  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 已提交
44
  const isSetupInlined = !!options.inline
fxy060608's avatar
fxy060608 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57

  // 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 已提交
58 59 60 61 62 63 64 65 66 67
  // 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 已提交
68

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

fxy060608's avatar
fxy060608 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  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 `)
fxy060608's avatar
fxy060608 已提交
91
  push(genBabelExpr(ast.renderData))
fxy060608's avatar
fxy060608 已提交
92 93 94 95 96 97
  if (useWithBlock) {
    deindent()
    push(`}`)
  }
  deindent()
  push(`}`)
fxy060608's avatar
fxy060608 已提交
98
  return {
fxy060608's avatar
fxy060608 已提交
99 100 101 102 103 104
    code: context.code,
    preamble: isSetupInlined ? preambleContext.code : ``,
  }
}

function createCodegenContext(
105
  ast: CodegenRootNode,
fxy060608's avatar
fxy060608 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  {
    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,
123
    bindingComponents: ast.bindingComponents,
fxy060608's avatar
fxy060608 已提交
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
    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
}

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

fxy060608's avatar
fxy060608 已提交
195
function genFunctionPreamble(ast: RootNode, context: CodegenContext) {
196 197 198 199 200 201 202
  const {
    prefixIdentifiers,
    push,
    newline,
    runtimeGlobalName,
    bindingComponents,
  } = context
fxy060608's avatar
fxy060608 已提交
203 204 205 206 207 208 209 210 211 212 213
  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`)
    }
  }
214
  genComponentImports(bindingComponents, context)
fxy060608's avatar
fxy060608 已提交
215 216 217 218 219 220 221 222 223
  newline()
  push(`return `)
}

function genModulePreamble(
  ast: RootNode,
  context: CodegenContext,
  inline?: boolean
) {
224
  const { push, newline, runtimeModuleName, bindingComponents } = context
fxy060608's avatar
fxy060608 已提交
225 226 227 228 229 230 231
  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 已提交
232 233 234 235 236

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

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

fxy060608's avatar
fxy060608 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
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 已提交
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
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 已提交
286 287 288 289 290 291 292 293 294
export function genBabelExpr(expr: Expression) {
  return babelGenerate(expr, {
    concise: true,
    jsescOption: {
      quotes: 'single',
    },
  }).code
}

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

function genNode(
fxy060608's avatar
fxy060608 已提交
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
  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 已提交
349
  genExpr(node.content, context)
fxy060608's avatar
fxy060608 已提交
350 351 352 353 354 355 356 357 358 359 360 361
  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 已提交
362
      genExpr(child, context)
fxy060608's avatar
fxy060608 已提交
363 364 365
    }
  }
}