index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. import { genHandlers } from './events'
  2. import baseDirectives from '../directives/index'
  3. import { camelize, no, extend, capitalize } from 'shared/util'
  4. import { baseWarn, pluckModuleFunction } from '../helpers'
  5. import { emptySlotScopeToken } from '../parser/index'
  6. import {
  7. ASTAttr,
  8. ASTDirective,
  9. ASTElement,
  10. ASTExpression,
  11. ASTIfConditions,
  12. ASTNode,
  13. ASTText,
  14. CompilerOptions
  15. } from 'types/compiler'
  16. import { BindingMetadata, BindingTypes } from 'sfc/types'
  17. type TransformFunction = (el: ASTElement, code: string) => string
  18. type DataGenFunction = (el: ASTElement) => string
  19. type DirectiveFunction = (
  20. el: ASTElement,
  21. dir: ASTDirective,
  22. warn: Function
  23. ) => boolean
  24. export class CodegenState {
  25. options: CompilerOptions
  26. warn: Function
  27. transforms: Array<TransformFunction>
  28. dataGenFns: Array<DataGenFunction>
  29. directives: { [key: string]: DirectiveFunction }
  30. maybeComponent: (el: ASTElement) => boolean
  31. onceId: number
  32. staticRenderFns: Array<string>
  33. pre: boolean
  34. constructor(options: CompilerOptions) {
  35. this.options = options
  36. this.warn = options.warn || baseWarn
  37. this.transforms = pluckModuleFunction(options.modules, 'transformCode')
  38. this.dataGenFns = pluckModuleFunction(options.modules, 'genData')
  39. this.directives = extend(extend({}, baseDirectives), options.directives)
  40. const isReservedTag = options.isReservedTag || no
  41. this.maybeComponent = (el: ASTElement) =>
  42. !!el.component || !isReservedTag(el.tag)
  43. this.onceId = 0
  44. this.staticRenderFns = []
  45. this.pre = false
  46. }
  47. }
  48. export type CodegenResult = {
  49. render: string
  50. staticRenderFns: Array<string>
  51. }
  52. export function generate(
  53. ast: ASTElement | void,
  54. options: CompilerOptions
  55. ): CodegenResult {
  56. const state = new CodegenState(options)
  57. // fix #11483, Root level <script> tags should not be rendered.
  58. const code = ast
  59. ? ast.tag === 'script'
  60. ? 'null'
  61. : genElement(ast, state)
  62. : '_c("div")'
  63. return {
  64. render: `with(this){return ${code}}`,
  65. staticRenderFns: state.staticRenderFns
  66. }
  67. }
  68. export function genElement(el: ASTElement, state: CodegenState): string {
  69. if (el.parent) {
  70. el.pre = el.pre || el.parent.pre
  71. }
  72. if (el.staticRoot && !el.staticProcessed) {
  73. return genStatic(el, state)
  74. } else if (el.once && !el.onceProcessed) {
  75. return genOnce(el, state)
  76. } else if (el.for && !el.forProcessed) {
  77. return genFor(el, state)
  78. } else if (el.if && !el.ifProcessed) {
  79. return genIf(el, state)
  80. } else if (el.tag === 'template' && !el.slotTarget && !state.pre) {
  81. return genChildren(el, state) || 'void 0'
  82. } else if (el.tag === 'slot') {
  83. return genSlot(el, state)
  84. } else {
  85. // component or element
  86. let code
  87. if (el.component) {
  88. code = genComponent(el.component, el, state)
  89. } else {
  90. let data
  91. const maybeComponent = state.maybeComponent(el)
  92. if (!el.plain || (el.pre && maybeComponent)) {
  93. data = genData(el, state)
  94. }
  95. let tag: string | undefined
  96. // check if this is a component in <script setup>
  97. const bindings = state.options.bindings
  98. if (maybeComponent && bindings && bindings.__isScriptSetup !== false) {
  99. tag = checkBindingType(bindings, el.tag)
  100. }
  101. if (!tag) tag = `'${el.tag}'`
  102. const children = el.inlineTemplate ? null : genChildren(el, state, true)
  103. code = `_c(${tag}${
  104. data ? `,${data}` : '' // data
  105. }${
  106. children ? `,${children}` : '' // children
  107. })`
  108. }
  109. // module transforms
  110. for (let i = 0; i < state.transforms.length; i++) {
  111. code = state.transforms[i](el, code)
  112. }
  113. return code
  114. }
  115. }
  116. function checkBindingType(bindings: BindingMetadata, key: string) {
  117. const camelName = camelize(key)
  118. const PascalName = capitalize(camelName)
  119. const checkType = (type) => {
  120. if (bindings[key] === type) {
  121. return key
  122. }
  123. if (bindings[camelName] === type) {
  124. return camelName
  125. }
  126. if (bindings[PascalName] === type) {
  127. return PascalName
  128. }
  129. }
  130. const fromConst =
  131. checkType(BindingTypes.SETUP_CONST) ||
  132. checkType(BindingTypes.SETUP_REACTIVE_CONST)
  133. if (fromConst) {
  134. return fromConst
  135. }
  136. const fromMaybeRef =
  137. checkType(BindingTypes.SETUP_LET) ||
  138. checkType(BindingTypes.SETUP_REF) ||
  139. checkType(BindingTypes.SETUP_MAYBE_REF)
  140. if (fromMaybeRef) {
  141. return fromMaybeRef
  142. }
  143. }
  144. // hoist static sub-trees out
  145. function genStatic(el: ASTElement, state: CodegenState): string {
  146. el.staticProcessed = true
  147. // Some elements (templates) need to behave differently inside of a v-pre
  148. // node. All pre nodes are static roots, so we can use this as a location to
  149. // wrap a state change and reset it upon exiting the pre node.
  150. const originalPreState = state.pre
  151. if (el.pre) {
  152. state.pre = el.pre
  153. }
  154. state.staticRenderFns.push(`with(this){return ${genElement(el, state)}}`)
  155. state.pre = originalPreState
  156. return `_m(${state.staticRenderFns.length - 1}${
  157. el.staticInFor ? ',true' : ''
  158. })`
  159. }
  160. // v-once
  161. function genOnce(el: ASTElement, state: CodegenState): string {
  162. el.onceProcessed = true
  163. if (el.if && !el.ifProcessed) {
  164. return genIf(el, state)
  165. } else if (el.staticInFor) {
  166. let key = ''
  167. let parent = el.parent
  168. while (parent) {
  169. if (parent.for) {
  170. key = parent.key!
  171. break
  172. }
  173. parent = parent.parent
  174. }
  175. if (!key) {
  176. __DEV__ &&
  177. state.warn(
  178. `v-once can only be used inside v-for that is keyed. `,
  179. el.rawAttrsMap['v-once']
  180. )
  181. return genElement(el, state)
  182. }
  183. return `_o(${genElement(el, state)},${state.onceId++},${key})`
  184. } else {
  185. return genStatic(el, state)
  186. }
  187. }
  188. export function genIf(
  189. el: any,
  190. state: CodegenState,
  191. altGen?: Function,
  192. altEmpty?: string
  193. ): string {
  194. el.ifProcessed = true // avoid recursion
  195. return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)
  196. }
  197. function genIfConditions(
  198. conditions: ASTIfConditions,
  199. state: CodegenState,
  200. altGen?: Function,
  201. altEmpty?: string
  202. ): string {
  203. if (!conditions.length) {
  204. return altEmpty || '_e()'
  205. }
  206. const condition = conditions.shift()!
  207. if (condition.exp) {
  208. return `(${condition.exp})?${genTernaryExp(
  209. condition.block
  210. )}:${genIfConditions(conditions, state, altGen, altEmpty)}`
  211. } else {
  212. return `${genTernaryExp(condition.block)}`
  213. }
  214. // v-if with v-once should generate code like (a)?_m(0):_m(1)
  215. function genTernaryExp(el) {
  216. return altGen
  217. ? altGen(el, state)
  218. : el.once
  219. ? genOnce(el, state)
  220. : genElement(el, state)
  221. }
  222. }
  223. export function genFor(
  224. el: any,
  225. state: CodegenState,
  226. altGen?: Function,
  227. altHelper?: string
  228. ): string {
  229. const exp = el.for
  230. const alias = el.alias
  231. const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  232. const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
  233. if (
  234. __DEV__ &&
  235. state.maybeComponent(el) &&
  236. el.tag !== 'slot' &&
  237. el.tag !== 'template' &&
  238. !el.key
  239. ) {
  240. state.warn(
  241. `<${el.tag} v-for="${alias} in ${exp}">: component lists rendered with ` +
  242. `v-for should have explicit keys. ` +
  243. `See https://v2.vuejs.org/v2/guide/list.html#key for more info.`,
  244. el.rawAttrsMap['v-for'],
  245. true /* tip */
  246. )
  247. }
  248. el.forProcessed = true // avoid recursion
  249. return (
  250. `${altHelper || '_l'}((${exp}),` +
  251. `function(${alias}${iterator1}${iterator2}){` +
  252. `return ${(altGen || genElement)(el, state)}` +
  253. '})'
  254. )
  255. }
  256. export function genData(el: ASTElement, state: CodegenState): string {
  257. let data = '{'
  258. // directives first.
  259. // directives may mutate the el's other properties before they are generated.
  260. const dirs = genDirectives(el, state)
  261. if (dirs) data += dirs + ','
  262. // key
  263. if (el.key) {
  264. data += `key:${el.key},`
  265. }
  266. // ref
  267. if (el.ref) {
  268. data += `ref:${el.ref},`
  269. }
  270. if (el.refInFor) {
  271. data += `refInFor:true,`
  272. }
  273. // pre
  274. if (el.pre) {
  275. data += `pre:true,`
  276. }
  277. // record original tag name for components using "is" attribute
  278. if (el.component) {
  279. data += `tag:"${el.tag}",`
  280. }
  281. // module data generation functions
  282. for (let i = 0; i < state.dataGenFns.length; i++) {
  283. data += state.dataGenFns[i](el)
  284. }
  285. // attributes
  286. if (el.attrs) {
  287. data += `attrs:${genProps(el.attrs)},`
  288. }
  289. // DOM props
  290. if (el.props) {
  291. data += `domProps:${genProps(el.props)},`
  292. }
  293. // event handlers
  294. if (el.events) {
  295. data += `${genHandlers(el.events, false)},`
  296. }
  297. if (el.nativeEvents) {
  298. data += `${genHandlers(el.nativeEvents, true)},`
  299. }
  300. // slot target
  301. // only for non-scoped slots
  302. if (el.slotTarget && !el.slotScope) {
  303. data += `slot:${el.slotTarget},`
  304. }
  305. // scoped slots
  306. if (el.scopedSlots) {
  307. data += `${genScopedSlots(el, el.scopedSlots, state)},`
  308. }
  309. // component v-model
  310. if (el.model) {
  311. data += `model:{value:${el.model.value},callback:${el.model.callback},expression:${el.model.expression}},`
  312. }
  313. // inline-template
  314. if (el.inlineTemplate) {
  315. const inlineTemplate = genInlineTemplate(el, state)
  316. if (inlineTemplate) {
  317. data += `${inlineTemplate},`
  318. }
  319. }
  320. data = data.replace(/,$/, '') + '}'
  321. // v-bind dynamic argument wrap
  322. // v-bind with dynamic arguments must be applied using the same v-bind object
  323. // merge helper so that class/style/mustUseProp attrs are handled correctly.
  324. if (el.dynamicAttrs) {
  325. data = `_b(${data},"${el.tag}",${genProps(el.dynamicAttrs)})`
  326. }
  327. // v-bind data wrap
  328. if (el.wrapData) {
  329. data = el.wrapData(data)
  330. }
  331. // v-on data wrap
  332. if (el.wrapListeners) {
  333. data = el.wrapListeners(data)
  334. }
  335. return data
  336. }
  337. function genDirectives(el: ASTElement, state: CodegenState): string | void {
  338. const dirs = el.directives
  339. if (!dirs) return
  340. let res = 'directives:['
  341. let hasRuntime = false
  342. let i, l, dir, needRuntime
  343. for (i = 0, l = dirs.length; i < l; i++) {
  344. dir = dirs[i]
  345. needRuntime = true
  346. const gen: DirectiveFunction = state.directives[dir.name]
  347. if (gen) {
  348. // compile-time directive that manipulates AST.
  349. // returns true if it also needs a runtime counterpart.
  350. needRuntime = !!gen(el, dir, state.warn)
  351. }
  352. if (needRuntime) {
  353. hasRuntime = true
  354. res += `{name:"${dir.name}",rawName:"${dir.rawName}"${
  355. dir.value
  356. ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}`
  357. : ''
  358. }${dir.arg ? `,arg:${dir.isDynamicArg ? dir.arg : `"${dir.arg}"`}` : ''}${
  359. dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
  360. }},`
  361. }
  362. }
  363. if (hasRuntime) {
  364. return res.slice(0, -1) + ']'
  365. }
  366. }
  367. function genInlineTemplate(
  368. el: ASTElement,
  369. state: CodegenState
  370. ): string | undefined {
  371. const ast = el.children[0]
  372. if (__DEV__ && (el.children.length !== 1 || ast.type !== 1)) {
  373. state.warn(
  374. 'Inline-template components must have exactly one child element.',
  375. { start: el.start }
  376. )
  377. }
  378. if (ast && ast.type === 1) {
  379. const inlineRenderFns = generate(ast, state.options)
  380. return `inlineTemplate:{render:function(){${
  381. inlineRenderFns.render
  382. }},staticRenderFns:[${inlineRenderFns.staticRenderFns
  383. .map(code => `function(){${code}}`)
  384. .join(',')}]}`
  385. }
  386. }
  387. function genScopedSlots(
  388. el: ASTElement,
  389. slots: { [key: string]: ASTElement },
  390. state: CodegenState
  391. ): string {
  392. // by default scoped slots are considered "stable", this allows child
  393. // components with only scoped slots to skip forced updates from parent.
  394. // but in some cases we have to bail-out of this optimization
  395. // for example if the slot contains dynamic names, has v-if or v-for on them...
  396. let needsForceUpdate =
  397. el.for ||
  398. Object.keys(slots).some(key => {
  399. const slot = slots[key]
  400. return (
  401. slot.slotTargetDynamic || slot.if || slot.for || containsSlotChild(slot) // is passing down slot from parent which may be dynamic
  402. )
  403. })
  404. // #9534: if a component with scoped slots is inside a conditional branch,
  405. // it's possible for the same component to be reused but with different
  406. // compiled slot content. To avoid that, we generate a unique key based on
  407. // the generated code of all the slot contents.
  408. let needsKey = !!el.if
  409. // OR when it is inside another scoped slot or v-for (the reactivity may be
  410. // disconnected due to the intermediate scope variable)
  411. // #9438, #9506
  412. // TODO: this can be further optimized by properly analyzing in-scope bindings
  413. // and skip force updating ones that do not actually use scope variables.
  414. if (!needsForceUpdate) {
  415. let parent = el.parent
  416. while (parent) {
  417. if (
  418. (parent.slotScope && parent.slotScope !== emptySlotScopeToken) ||
  419. parent.for
  420. ) {
  421. needsForceUpdate = true
  422. break
  423. }
  424. if (parent.if) {
  425. needsKey = true
  426. }
  427. parent = parent.parent
  428. }
  429. }
  430. const generatedSlots = Object.keys(slots)
  431. .map(key => genScopedSlot(slots[key], state))
  432. .join(',')
  433. return `scopedSlots:_u([${generatedSlots}]${
  434. needsForceUpdate ? `,null,true` : ``
  435. }${
  436. !needsForceUpdate && needsKey ? `,null,false,${hash(generatedSlots)}` : ``
  437. })`
  438. }
  439. function hash(str) {
  440. let hash = 5381
  441. let i = str.length
  442. while (i) {
  443. hash = (hash * 33) ^ str.charCodeAt(--i)
  444. }
  445. return hash >>> 0
  446. }
  447. function containsSlotChild(el: ASTNode): boolean {
  448. if (el.type === 1) {
  449. if (el.tag === 'slot') {
  450. return true
  451. }
  452. return el.children.some(containsSlotChild)
  453. }
  454. return false
  455. }
  456. function genScopedSlot(el: ASTElement, state: CodegenState): string {
  457. const isLegacySyntax = el.attrsMap['slot-scope']
  458. if (el.if && !el.ifProcessed && !isLegacySyntax) {
  459. return genIf(el, state, genScopedSlot, `null`)
  460. }
  461. if (el.for && !el.forProcessed) {
  462. return genFor(el, state, genScopedSlot)
  463. }
  464. const slotScope =
  465. el.slotScope === emptySlotScopeToken ? `` : String(el.slotScope)
  466. const fn =
  467. `function(${slotScope}){` +
  468. `return ${
  469. el.tag === 'template'
  470. ? el.if && isLegacySyntax
  471. ? `(${el.if})?${genChildren(el, state) || 'undefined'}:undefined`
  472. : genChildren(el, state) || 'undefined'
  473. : genElement(el, state)
  474. }}`
  475. // reverse proxy v-slot without scope on this.$slots
  476. const reverseProxy = slotScope ? `` : `,proxy:true`
  477. return `{key:${el.slotTarget || `"default"`},fn:${fn}${reverseProxy}}`
  478. }
  479. export function genChildren(
  480. el: ASTElement,
  481. state: CodegenState,
  482. checkSkip?: boolean,
  483. altGenElement?: Function,
  484. altGenNode?: Function
  485. ): string | void {
  486. const children = el.children
  487. if (children.length) {
  488. const el: any = children[0]
  489. // optimize single v-for
  490. if (
  491. children.length === 1 &&
  492. el.for &&
  493. el.tag !== 'template' &&
  494. el.tag !== 'slot'
  495. ) {
  496. const normalizationType = checkSkip
  497. ? state.maybeComponent(el)
  498. ? `,1`
  499. : `,0`
  500. : ``
  501. return `${(altGenElement || genElement)(el, state)}${normalizationType}`
  502. }
  503. const normalizationType = checkSkip
  504. ? getNormalizationType(children, state.maybeComponent)
  505. : 0
  506. const gen = altGenNode || genNode
  507. return `[${children.map(c => gen(c, state)).join(',')}]${
  508. normalizationType ? `,${normalizationType}` : ''
  509. }`
  510. }
  511. }
  512. // determine the normalization needed for the children array.
  513. // 0: no normalization needed
  514. // 1: simple normalization needed (possible 1-level deep nested array)
  515. // 2: full normalization needed
  516. function getNormalizationType(
  517. children: Array<ASTNode>,
  518. maybeComponent: (el: ASTElement) => boolean
  519. ): number {
  520. let res = 0
  521. for (let i = 0; i < children.length; i++) {
  522. const el: ASTNode = children[i]
  523. if (el.type !== 1) {
  524. continue
  525. }
  526. if (
  527. needsNormalization(el) ||
  528. (el.ifConditions &&
  529. el.ifConditions.some(c => needsNormalization(c.block)))
  530. ) {
  531. res = 2
  532. break
  533. }
  534. if (
  535. maybeComponent(el) ||
  536. (el.ifConditions && el.ifConditions.some(c => maybeComponent(c.block)))
  537. ) {
  538. res = 1
  539. }
  540. }
  541. return res
  542. }
  543. function needsNormalization(el: ASTElement): boolean {
  544. return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
  545. }
  546. function genNode(node: ASTNode, state: CodegenState): string {
  547. if (node.type === 1) {
  548. return genElement(node, state)
  549. } else if (node.type === 3 && node.isComment) {
  550. return genComment(node)
  551. } else {
  552. return genText(node)
  553. }
  554. }
  555. export function genText(text: ASTText | ASTExpression): string {
  556. return `_v(${
  557. text.type === 2
  558. ? text.expression // no need for () because already wrapped in _s()
  559. : transformSpecialNewlines(JSON.stringify(text.text))
  560. })`
  561. }
  562. export function genComment(comment: ASTText): string {
  563. return `_e(${JSON.stringify(comment.text)})`
  564. }
  565. function genSlot(el: ASTElement, state: CodegenState): string {
  566. const slotName = el.slotName || '"default"'
  567. const children = genChildren(el, state)
  568. let res = `_t(${slotName}${children ? `,function(){return ${children}}` : ''}`
  569. const attrs =
  570. el.attrs || el.dynamicAttrs
  571. ? genProps(
  572. (el.attrs || []).concat(el.dynamicAttrs || []).map(attr => ({
  573. // slot props are camelized
  574. name: camelize(attr.name),
  575. value: attr.value,
  576. dynamic: attr.dynamic
  577. }))
  578. )
  579. : null
  580. const bind = el.attrsMap['v-bind']
  581. if ((attrs || bind) && !children) {
  582. res += `,null`
  583. }
  584. if (attrs) {
  585. res += `,${attrs}`
  586. }
  587. if (bind) {
  588. res += `${attrs ? '' : ',null'},${bind}`
  589. }
  590. return res + ')'
  591. }
  592. // componentName is el.component, take it as argument to shun flow's pessimistic refinement
  593. function genComponent(
  594. componentName: string,
  595. el: ASTElement,
  596. state: CodegenState
  597. ): string {
  598. const children = el.inlineTemplate ? null : genChildren(el, state, true)
  599. return `_c(${componentName},${genData(el, state)}${
  600. children ? `,${children}` : ''
  601. })`
  602. }
  603. function genProps(props: Array<ASTAttr>): string {
  604. let staticProps = ``
  605. let dynamicProps = ``
  606. for (let i = 0; i < props.length; i++) {
  607. const prop = props[i]
  608. const value = transformSpecialNewlines(prop.value)
  609. if (prop.dynamic) {
  610. dynamicProps += `${prop.name},${value},`
  611. } else {
  612. staticProps += `"${prop.name}":${value},`
  613. }
  614. }
  615. staticProps = `{${staticProps.slice(0, -1)}}`
  616. if (dynamicProps) {
  617. return `_d(${staticProps},[${dynamicProps.slice(0, -1)}])`
  618. } else {
  619. return staticProps
  620. }
  621. }
  622. // #3895, #4268
  623. function transformSpecialNewlines(text: string): string {
  624. return text.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
  625. }