35187e3fb3b1430d8b754e7277b2a3bad7f59bbeb1d0ce1fd9351bd24b56557e6fe08f53049a71a454697393b5fc4250a718bf380bc595344c4d7de33be778 17 KB

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