index.js 14 KB

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