codegen.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. /* @flow */
  2. import { genHandlers } from './events'
  3. import { baseWarn, pluckModuleFunction } from './helpers'
  4. import baseDirectives from './directives/index'
  5. import { no } from 'shared/util'
  6. // configurable state
  7. let warn
  8. let transforms
  9. let dataGenFns
  10. let platformDirectives
  11. let isPlatformReservedTag
  12. let staticRenderFns
  13. let currentOptions
  14. export function generate (
  15. ast: ASTElement | void,
  16. options: CompilerOptions
  17. ): {
  18. render: string,
  19. staticRenderFns: Array<string>
  20. } {
  21. // save previous staticRenderFns so generate calls can be nested
  22. const prevStaticRenderFns: Array<string> = staticRenderFns
  23. const currentStaticRenderFns: Array<string> = staticRenderFns = []
  24. currentOptions = options
  25. warn = options.warn || baseWarn
  26. transforms = pluckModuleFunction(options.modules, 'transformCode')
  27. dataGenFns = pluckModuleFunction(options.modules, 'genData')
  28. platformDirectives = options.directives || {}
  29. isPlatformReservedTag = options.isReservedTag || no
  30. const code = ast ? genElement(ast) : '_h(_e("div"))'
  31. staticRenderFns = prevStaticRenderFns
  32. return {
  33. render: `with(this){return ${code}}`,
  34. staticRenderFns: currentStaticRenderFns
  35. }
  36. }
  37. function genElement (el: ASTElement): string {
  38. if (el.staticRoot && !el.staticProcessed) {
  39. // hoist static sub-trees out
  40. el.staticProcessed = true
  41. staticRenderFns.push(`with(this){return ${genElement(el)}}`)
  42. return `_m(${staticRenderFns.length - 1})`
  43. } else if (el.for && !el.forProcessed) {
  44. return genFor(el)
  45. } else if (el.if && !el.ifProcessed) {
  46. return genIf(el)
  47. } else if (el.tag === 'template' && !el.slotTarget) {
  48. return genChildren(el) || 'void 0'
  49. } else if (el.tag === 'slot') {
  50. return genSlot(el)
  51. } else {
  52. // component or element
  53. let code
  54. if (el.component) {
  55. code = genComponent(el)
  56. } else {
  57. const data = genData(el)
  58. // if the element is potentially a component,
  59. // wrap its children as a thunk.
  60. const children = !el.inlineTemplate
  61. ? genChildren(el, !el.ns && !isPlatformReservedTag(el.tag) /* asThunk */)
  62. : null
  63. code = `_h(_e('${el.tag}'${
  64. data ? `,${data}` : el.ns ? ',void 0' : '' // data
  65. }${
  66. el.ns ? `,'${el.ns}'` : '' // namespace
  67. })${
  68. children ? `,${children}` : '' // children
  69. })`
  70. }
  71. // module transforms
  72. for (let i = 0; i < transforms.length; i++) {
  73. code = transforms[i](el, code)
  74. }
  75. // check keep-alive
  76. if (el.component && el.keepAlive) {
  77. code = `_h(_e("KeepAlive",{props:{child:${code}}}))`
  78. }
  79. return code
  80. }
  81. }
  82. function genIf (el: ASTElement): string {
  83. const exp = el.if
  84. el.ifProcessed = true // avoid recursion
  85. return `(${exp})?${genElement(el)}:${genElse(el)}`
  86. }
  87. function genElse (el: ASTElement): string {
  88. return el.elseBlock
  89. ? genElement(el.elseBlock)
  90. : 'void 0'
  91. }
  92. function genFor (el: ASTElement): string {
  93. const exp = el.for
  94. const alias = el.alias
  95. const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  96. const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
  97. el.forProcessed = true // avoid recursion
  98. return `(${exp})&&_l((${exp}),` +
  99. `function(${alias}${iterator1}${iterator2}){` +
  100. `return ${genElement(el)}` +
  101. '})'
  102. }
  103. function genData (el: ASTElement): string | void {
  104. if (el.plain) {
  105. return
  106. }
  107. let data = '{'
  108. // directives first.
  109. // directives may mutate the el's other properties before they are generated.
  110. const dirs = genDirectives(el)
  111. if (dirs) data += dirs + ','
  112. // key
  113. if (el.key) {
  114. data += `key:${el.key},`
  115. }
  116. // ref
  117. if (el.ref) {
  118. data += `ref:${el.ref},`
  119. }
  120. if (el.refInFor) {
  121. data += `refInFor:true,`
  122. }
  123. // record original tag name for components using "is" attribute
  124. if (el.component) {
  125. data += `tag:"${el.tag}",`
  126. }
  127. // slot target
  128. if (el.slotTarget) {
  129. data += `slot:${el.slotTarget},`
  130. }
  131. // module data generation functions
  132. for (let i = 0; i < dataGenFns.length; i++) {
  133. data += dataGenFns[i](el)
  134. }
  135. // v-show, used to avoid transition being applied
  136. // since v-show takes it over
  137. if (el.attrsMap['v-show']) {
  138. data += 'show:true,'
  139. }
  140. // props
  141. if (el.props) {
  142. data += `props:{${genProps(el.props)}},`
  143. }
  144. // attributes
  145. if (el.attrs) {
  146. data += `attrs:{${genProps(el.attrs)}},`
  147. }
  148. // static attributes
  149. if (el.staticAttrs) {
  150. data += `staticAttrs:{${genProps(el.staticAttrs)}},`
  151. }
  152. // hooks
  153. if (el.hooks) {
  154. data += `hook:{${genHooks(el.hooks)}},`
  155. }
  156. // event handlers
  157. if (el.events) {
  158. data += `${genHandlers(el.events)},`
  159. }
  160. // inline-template
  161. if (el.inlineTemplate) {
  162. const ast = el.children[0]
  163. if (process.env.NODE_ENV !== 'production' && (
  164. el.children.length > 1 || ast.type !== 1
  165. )) {
  166. warn('Inline-template components must have exactly one child element.')
  167. }
  168. if (ast.type === 1) {
  169. const inlineRenderFns = generate(ast, currentOptions)
  170. data += `inlineTemplate:{render:function(){${
  171. inlineRenderFns.render
  172. }},staticRenderFns:[${
  173. inlineRenderFns.staticRenderFns.map(code => `function(){${code}}`).join(',')
  174. }]}`
  175. }
  176. }
  177. return data.replace(/,$/, '') + '}'
  178. }
  179. function genDirectives (el: ASTElement): string | void {
  180. const dirs = el.directives
  181. if (!dirs) return
  182. let res = 'directives:['
  183. let hasRuntime = false
  184. let i, l, dir, needRuntime
  185. for (i = 0, l = dirs.length; i < l; i++) {
  186. dir = dirs[i]
  187. needRuntime = true
  188. const gen = platformDirectives[dir.name] || baseDirectives[dir.name]
  189. if (gen) {
  190. // compile-time directive that manipulates AST.
  191. // returns true if it also needs a runtime counterpart.
  192. needRuntime = !!gen(el, dir, warn)
  193. }
  194. if (needRuntime) {
  195. hasRuntime = true
  196. res += `{name:"${dir.name}"${
  197. dir.value ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}` : ''
  198. }${
  199. dir.arg ? `,arg:"${dir.arg}"` : ''
  200. }${
  201. dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
  202. }},`
  203. }
  204. }
  205. if (hasRuntime) {
  206. return res.slice(0, -1) + ']'
  207. }
  208. }
  209. function genChildren (el: ASTElement, asThunk?: boolean): string | void {
  210. if (!el.children.length) {
  211. return
  212. }
  213. const code = '[' + el.children.map(genNode).join(',') + ']'
  214. return asThunk
  215. ? `function(){return ${code}}`
  216. : code
  217. }
  218. function genNode (node: ASTNode) {
  219. if (node.type === 1) {
  220. return genElement(node)
  221. } else {
  222. return genText(node)
  223. }
  224. }
  225. function genText (text: ASTText | ASTExpression): string {
  226. return text.type === 2
  227. ? text.expression // no need for () because already wrapped in _s()
  228. : JSON.stringify(text.text)
  229. }
  230. function genSlot (el: ASTElement): string {
  231. const slot = `$slots[${el.slotName || '"default"'}]`
  232. const children = genChildren(el)
  233. return children
  234. ? `(${slot}||${children})`
  235. : slot
  236. }
  237. function genComponent (el: ASTElement): string {
  238. const children = genChildren(el, true)
  239. return `_h(_e(${el.component},${genData(el)})${
  240. children ? `,${children}` : ''
  241. })`
  242. }
  243. function genProps (props: Array<{ name: string, value: string }>): string {
  244. let res = ''
  245. for (let i = 0; i < props.length; i++) {
  246. const prop = props[i]
  247. res += `"${prop.name}":${prop.value},`
  248. }
  249. return res.slice(0, -1)
  250. }
  251. function genHooks (hooks: { [key: string]: Array<string> }): string {
  252. let res = ''
  253. for (const key in hooks) {
  254. res += `"${key}":function(n1,n2){${hooks[key].join(';')}},`
  255. }
  256. return res.slice(0, -1)
  257. }