index.js 17 KB

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