index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* @flow */
  2. import { genHandlers } from './events'
  3. import { baseWarn, pluckModuleFunction } from '../helpers'
  4. import baseDirectives from '../directives/index'
  5. import { camelize, no, extend } from 'shared/util'
  6. type TransformFunction = (el: ASTElement, code: string) => string;
  7. type DataGenFunction = (el: ASTElement) => string;
  8. type DirectiveFunction = (el: ASTElement, dir: ASTDirective, warn: Function) => boolean;
  9. export class CodegenState {
  10. options: CompilerOptions;
  11. warn: Function;
  12. transforms: Array<TransformFunction>;
  13. dataGenFns: Array<DataGenFunction>;
  14. directives: { [key: string]: DirectiveFunction };
  15. maybeComponent: (el: ASTElement) => boolean;
  16. onceId: number;
  17. staticRenderFns: Array<string>;
  18. constructor (options: CompilerOptions) {
  19. this.options = options
  20. this.warn = options.warn || baseWarn
  21. this.transforms = pluckModuleFunction(options.modules, 'transformCode')
  22. this.dataGenFns = pluckModuleFunction(options.modules, 'genData')
  23. this.directives = extend(extend({}, baseDirectives), options.directives)
  24. const isReservedTag = options.isReservedTag || no
  25. this.maybeComponent = (el: ASTElement) => !isReservedTag(el.tag)
  26. this.onceId = 0
  27. this.staticRenderFns = []
  28. }
  29. }
  30. type CodegenResult = {
  31. render: string,
  32. staticRenderFns: Array<string>
  33. };
  34. export function generate (
  35. ast: ASTElement | void,
  36. options: CompilerOptions
  37. ): CodegenResult {
  38. const state = new CodegenState(options)
  39. const code = ast ? genElement(ast, state) : '_c("div")'
  40. return {
  41. render: `with(this){return ${code}}`,
  42. staticRenderFns: state.staticRenderFns
  43. }
  44. }
  45. export function genElement (el: ASTElement, state: CodegenState): string {
  46. if (el.staticRoot && !el.staticProcessed) {
  47. return genStatic(el, state)
  48. } else if (el.once && !el.onceProcessed) {
  49. return genOnce(el, state)
  50. } else if (el.for && !el.forProcessed) {
  51. return genFor(el, state)
  52. } else if (el.if && !el.ifProcessed) {
  53. return genIf(el, state)
  54. } else if (el.tag === 'template' && !el.slotTarget) {
  55. return genChildren(el, state) || 'void 0'
  56. } else if (el.tag === 'slot') {
  57. return genSlot(el, state)
  58. } else {
  59. // component or element
  60. let code
  61. if (el.component) {
  62. code = genComponent(el.component, el, state)
  63. } else {
  64. const data = el.plain ? undefined : genData(el, state)
  65. const children = el.inlineTemplate ? null : genChildren(el, state, true)
  66. code = `_c('${el.tag}'${
  67. data ? `,${data}` : '' // data
  68. }${
  69. children ? `,${children}` : '' // children
  70. })`
  71. }
  72. // module transforms
  73. for (let i = 0; i < state.transforms.length; i++) {
  74. code = state.transforms[i](el, code)
  75. }
  76. return code
  77. }
  78. }
  79. // hoist static sub-trees out
  80. function genStatic (el: ASTElement, state: CodegenState): string {
  81. el.staticProcessed = true
  82. state.staticRenderFns.push(`with(this){return ${genElement(el, state)}}`)
  83. return `_m(${state.staticRenderFns.length - 1}${el.staticInFor ? ',true' : ''})`
  84. }
  85. // v-once
  86. function genOnce (el: ASTElement, state: CodegenState): string {
  87. el.onceProcessed = true
  88. if (el.if && !el.ifProcessed) {
  89. return genIf(el, state)
  90. } else if (el.staticInFor) {
  91. let key = ''
  92. let parent = el.parent
  93. while (parent) {
  94. if (parent.for) {
  95. key = parent.key
  96. break
  97. }
  98. parent = parent.parent
  99. }
  100. if (!key) {
  101. process.env.NODE_ENV !== 'production' && state.warn(
  102. `v-once can only be used inside v-for that is keyed. `
  103. )
  104. return genElement(el, state)
  105. }
  106. return `_o(${genElement(el, state)},${state.onceId++}${key ? `,${key}` : ``})`
  107. } else {
  108. return genStatic(el, state)
  109. }
  110. }
  111. function genIf (el: any, state: CodegenState): string {
  112. el.ifProcessed = true // avoid recursion
  113. return genIfConditions(el.ifConditions.slice(), state)
  114. }
  115. function genIfConditions (
  116. conditions: ASTIfConditions,
  117. state: CodegenState
  118. ): string {
  119. if (!conditions.length) {
  120. return '_e()'
  121. }
  122. const condition = conditions.shift()
  123. if (condition.exp) {
  124. return `(${condition.exp})?${
  125. genTernaryExp(condition.block)
  126. }:${
  127. genIfConditions(conditions, state)
  128. }`
  129. } else {
  130. return `${genTernaryExp(condition.block)}`
  131. }
  132. // v-if with v-once should generate code like (a)?_m(0):_m(1)
  133. function genTernaryExp (el) {
  134. return el.once ? genOnce(el, state) : genElement(el, state)
  135. }
  136. }
  137. function genFor (el: any, state: CodegenState): string {
  138. const exp = el.for
  139. const alias = el.alias
  140. const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  141. const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
  142. if (process.env.NODE_ENV !== 'production' &&
  143. state.maybeComponent(el) &&
  144. el.tag !== 'slot' &&
  145. el.tag !== 'template' &&
  146. !el.key
  147. ) {
  148. state.warn(
  149. `<${el.tag} v-for="${alias} in ${exp}">: component lists rendered with ` +
  150. `v-for should have explicit keys. ` +
  151. `See https://vuejs.org/guide/list.html#key for more info.`,
  152. true /* tip */
  153. )
  154. }
  155. el.forProcessed = true // avoid recursion
  156. return `_l((${exp}),` +
  157. `function(${alias}${iterator1}${iterator2}){` +
  158. `return ${genElement(el, state)}` +
  159. '})'
  160. }
  161. function genData (el: ASTElement, state: CodegenState): string {
  162. let data = '{'
  163. // directives first.
  164. // directives may mutate the el's other properties before they are generated.
  165. const dirs = genDirectives(el, state)
  166. if (dirs) data += dirs + ','
  167. // key
  168. if (el.key) {
  169. data += `key:${el.key},`
  170. }
  171. // ref
  172. if (el.ref) {
  173. data += `ref:${el.ref},`
  174. }
  175. if (el.refInFor) {
  176. data += `refInFor:true,`
  177. }
  178. // pre
  179. if (el.pre) {
  180. data += `pre:true,`
  181. }
  182. // record original tag name for components using "is" attribute
  183. if (el.component) {
  184. data += `tag:"${el.tag}",`
  185. }
  186. // module data generation functions
  187. for (let i = 0; i < state.dataGenFns.length; i++) {
  188. data += state.dataGenFns[i](el)
  189. }
  190. // attributes
  191. if (el.attrs) {
  192. data += `attrs:{${genProps(el.attrs, state)}},`
  193. }
  194. // DOM props
  195. if (el.props) {
  196. data += `domProps:{${genProps(el.props, state)}},`
  197. }
  198. // event handlers
  199. if (el.events) {
  200. data += `${genHandlers(el.events, false, state.warn)},`
  201. }
  202. if (el.nativeEvents) {
  203. data += `${genHandlers(el.nativeEvents, true, state.warn)},`
  204. }
  205. // slot target
  206. if (el.slotTarget) {
  207. data += `slot:${el.slotTarget},`
  208. }
  209. // scoped slots
  210. if (el.scopedSlots) {
  211. data += `${genScopedSlots(el.scopedSlots, state)},`
  212. }
  213. // component v-model
  214. if (el.model) {
  215. data += `model:{value:${
  216. el.model.value
  217. },callback:${
  218. el.model.callback
  219. },expression:${
  220. el.model.expression
  221. }},`
  222. }
  223. // inline-template
  224. if (el.inlineTemplate) {
  225. const inlineTemplate = genInlineTemplate(el, state)
  226. if (inlineTemplate) {
  227. data += `${inlineTemplate},`
  228. }
  229. }
  230. data = data.replace(/,$/, '') + '}'
  231. // v-bind data wrap
  232. if (el.wrapData) {
  233. data = el.wrapData(data)
  234. }
  235. return data
  236. }
  237. function genDirectives (el: ASTElement, state: CodegenState): string | void {
  238. const dirs = el.directives
  239. if (!dirs) return
  240. let res = 'directives:['
  241. let hasRuntime = false
  242. let i, l, dir, needRuntime
  243. for (i = 0, l = dirs.length; i < l; i++) {
  244. dir = dirs[i]
  245. needRuntime = true
  246. const gen: DirectiveFunction = state.directives[dir.name]
  247. if (gen) {
  248. // compile-time directive that manipulates AST.
  249. // returns true if it also needs a runtime counterpart.
  250. needRuntime = !!gen(el, dir, state.warn)
  251. }
  252. if (needRuntime) {
  253. hasRuntime = true
  254. res += `{name:"${dir.name}",rawName:"${dir.rawName}"${
  255. dir.value ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}` : ''
  256. }${
  257. dir.arg ? `,arg:"${dir.arg}"` : ''
  258. }${
  259. dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
  260. }},`
  261. }
  262. }
  263. if (hasRuntime) {
  264. return res.slice(0, -1) + ']'
  265. }
  266. }
  267. function genInlineTemplate (el: ASTElement, state: CodegenState): ?string {
  268. const ast = el.children[0]
  269. if (process.env.NODE_ENV !== 'production' && (
  270. el.children.length > 1 || ast.type !== 1
  271. )) {
  272. state.warn('Inline-template components must have exactly one child element.')
  273. }
  274. if (ast.type === 1) {
  275. const inlineRenderFns = generate(ast, state.options)
  276. return `inlineTemplate:{render:function(){${
  277. inlineRenderFns.render
  278. }},staticRenderFns:[${
  279. inlineRenderFns.staticRenderFns.map(code => `function(){${code}}`).join(',')
  280. }]}`
  281. }
  282. }
  283. function genScopedSlots (
  284. slots: { [key: string]: ASTElement },
  285. state: CodegenState
  286. ): string {
  287. return `scopedSlots:_u([${
  288. Object.keys(slots).map(key => {
  289. return genScopedSlot(key, slots[key], state)
  290. }).join(',')
  291. }])`
  292. }
  293. function genScopedSlot (
  294. key: string,
  295. el: ASTElement,
  296. state: CodegenState
  297. ): string {
  298. if (el.for && !el.forProcessed) {
  299. return genForScopedSlot(key, el, state)
  300. }
  301. return `{key:${key},fn:function(${String(el.attrsMap.scope)}){` +
  302. `return ${el.tag === 'template'
  303. ? genChildren(el, state) || 'void 0'
  304. : genElement(el, state)
  305. }}}`
  306. }
  307. function genForScopedSlot (
  308. key: string,
  309. el: any,
  310. state: CodegenState
  311. ): string {
  312. const exp = el.for
  313. const alias = el.alias
  314. const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  315. const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
  316. el.forProcessed = true // avoid recursion
  317. return `_l((${exp}),` +
  318. `function(${alias}${iterator1}${iterator2}){` +
  319. `return ${genScopedSlot(key, el, state)}` +
  320. '})'
  321. }
  322. function genChildren (
  323. el: ASTElement,
  324. state: CodegenState,
  325. checkSkip?: boolean
  326. ): string | void {
  327. const children = el.children
  328. if (children.length) {
  329. const el: any = children[0]
  330. // optimize single v-for
  331. if (children.length === 1 &&
  332. el.for &&
  333. el.tag !== 'template' &&
  334. el.tag !== 'slot'
  335. ) {
  336. return genElement(el, state)
  337. }
  338. const normalizationType = checkSkip
  339. ? getNormalizationType(children, state.maybeComponent)
  340. : 0
  341. return `[${children.map(c => genNode(c, state)).join(',')}]${
  342. normalizationType ? `,${normalizationType}` : ''
  343. }`
  344. }
  345. }
  346. // determine the normalization needed for the children array.
  347. // 0: no normalization needed
  348. // 1: simple normalization needed (possible 1-level deep nested array)
  349. // 2: full normalization needed
  350. function getNormalizationType (
  351. children: Array<ASTNode>,
  352. maybeComponent: (el: ASTElement) => boolean
  353. ): number {
  354. let res = 0
  355. for (let i = 0; i < children.length; i++) {
  356. const el: ASTNode = children[i]
  357. if (el.type !== 1) {
  358. continue
  359. }
  360. if (needsNormalization(el) ||
  361. (el.ifConditions && el.ifConditions.some(c => needsNormalization(c.block)))) {
  362. res = 2
  363. break
  364. }
  365. if (maybeComponent(el) ||
  366. (el.ifConditions && el.ifConditions.some(c => maybeComponent(c.block)))) {
  367. res = 1
  368. }
  369. }
  370. return res
  371. }
  372. function needsNormalization (el: ASTElement): boolean {
  373. return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
  374. }
  375. function genNode (node: ASTNode, state: CodegenState): string {
  376. if (node.type === 1) {
  377. return genElement(node, state)
  378. } else {
  379. return genText(node)
  380. }
  381. }
  382. function genText (text: ASTText | ASTExpression): string {
  383. return `_v(${text.type === 2
  384. ? text.expression // no need for () because already wrapped in _s()
  385. : transformSpecialNewlines(JSON.stringify(text.text))
  386. })`
  387. }
  388. function genSlot (el: ASTElement, state: CodegenState): string {
  389. const slotName = el.slotName || '"default"'
  390. const children = genChildren(el, state)
  391. let res = `_t(${slotName}${children ? `,${children}` : ''}`
  392. const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}`
  393. const bind = el.attrsMap['v-bind']
  394. if ((attrs || bind) && !children) {
  395. res += `,null`
  396. }
  397. if (attrs) {
  398. res += `,${attrs}`
  399. }
  400. if (bind) {
  401. res += `${attrs ? '' : ',null'},${bind}`
  402. }
  403. return res + ')'
  404. }
  405. // componentName is el.component, take it as argument to shun flow's pessimistic refinement
  406. function genComponent (
  407. componentName: string,
  408. el: ASTElement,
  409. state: CodegenState
  410. ): string {
  411. const children = el.inlineTemplate ? null : genChildren(el, state, true)
  412. return `_c(${componentName},${genData(el, state)}${
  413. children ? `,${children}` : ''
  414. })`
  415. }
  416. function genProps (props: Array<{ name: string, value: string }>): string {
  417. let res = ''
  418. for (let i = 0; i < props.length; i++) {
  419. const prop = props[i]
  420. res += `"${prop.name}":${transformSpecialNewlines(prop.value)},`
  421. }
  422. return res.slice(0, -1)
  423. }
  424. // #3895, #4268
  425. function transformSpecialNewlines (text: string): string {
  426. return text
  427. .replace(/\u2028/g, '\\u2028')
  428. .replace(/\u2029/g, '\\u2029')
  429. }