transform.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import type { TransformOptions } from './options'
  2. import {
  3. type ArrayExpression,
  4. type CacheExpression,
  5. ConstantTypes,
  6. type DirectiveNode,
  7. type ElementNode,
  8. ElementTypes,
  9. type ExpressionNode,
  10. type JSChildNode,
  11. NodeTypes,
  12. type ParentNode,
  13. type Property,
  14. type RootNode,
  15. type SimpleExpressionNode,
  16. type TemplateChildNode,
  17. type TemplateLiteral,
  18. convertToBlock,
  19. createCacheExpression,
  20. createSimpleExpression,
  21. createVNodeCall,
  22. } from './ast'
  23. import {
  24. EMPTY_OBJ,
  25. NOOP,
  26. PatchFlags,
  27. camelize,
  28. capitalize,
  29. isArray,
  30. isString,
  31. } from '@vue/shared'
  32. import { defaultOnError, defaultOnWarn } from './errors'
  33. import {
  34. CREATE_COMMENT,
  35. FRAGMENT,
  36. TO_DISPLAY_STRING,
  37. helperNameMap,
  38. } from './runtimeHelpers'
  39. import { isVSlot } from './utils'
  40. import { cacheStatic, getSingleElementRoot } from './transforms/cacheStatic'
  41. import type { CompilerCompatOptions } from './compat/compatConfig'
  42. // There are two types of transforms:
  43. //
  44. // - NodeTransform:
  45. // Transforms that operate directly on a ChildNode. NodeTransforms may mutate,
  46. // replace or remove the node being processed.
  47. export type NodeTransform = (
  48. node: RootNode | TemplateChildNode,
  49. context: TransformContext,
  50. ) => void | (() => void) | (() => void)[]
  51. // - DirectiveTransform:
  52. // Transforms that handles a single directive attribute on an element.
  53. // It translates the raw directive into actual props for the VNode.
  54. export type DirectiveTransform = (
  55. dir: DirectiveNode,
  56. node: ElementNode,
  57. context: TransformContext,
  58. // a platform specific compiler can import the base transform and augment
  59. // it by passing in this optional argument.
  60. augmentor?: (ret: DirectiveTransformResult) => DirectiveTransformResult,
  61. ) => DirectiveTransformResult
  62. export interface DirectiveTransformResult {
  63. props: Property[]
  64. needRuntime?: boolean | symbol
  65. ssrTagParts?: TemplateLiteral['elements']
  66. }
  67. // A structural directive transform is technically also a NodeTransform;
  68. // Only v-if and v-for fall into this category.
  69. export type StructuralDirectiveTransform = (
  70. node: ElementNode,
  71. dir: DirectiveNode,
  72. context: TransformContext,
  73. ) => void | (() => void)
  74. export interface ImportItem {
  75. exp: string | ExpressionNode
  76. path: string
  77. }
  78. export interface TransformContext
  79. extends Required<Omit<TransformOptions, keyof CompilerCompatOptions>>,
  80. CompilerCompatOptions {
  81. selfName: string | null
  82. root: RootNode
  83. helpers: Map<symbol, number>
  84. components: Set<string>
  85. directives: Set<string>
  86. hoists: (JSChildNode | null)[]
  87. imports: ImportItem[]
  88. temps: number
  89. cached: (CacheExpression | null)[]
  90. identifiers: { [name: string]: number | undefined }
  91. scopes: {
  92. vFor: number
  93. vSlot: number
  94. vPre: number
  95. vOnce: number
  96. }
  97. parent: ParentNode | null
  98. // we could use a stack but in practice we've only ever needed two layers up
  99. // so this is more efficient
  100. grandParent: ParentNode | null
  101. childIndex: number
  102. currentNode: RootNode | TemplateChildNode | null
  103. inVOnce: boolean
  104. helper<T extends symbol>(name: T): T
  105. removeHelper<T extends symbol>(name: T): void
  106. helperString(name: symbol): string
  107. replaceNode(node: TemplateChildNode): void
  108. removeNode(node?: TemplateChildNode): void
  109. onNodeRemoved(): void
  110. addIdentifiers(exp: ExpressionNode | string): void
  111. removeIdentifiers(exp: ExpressionNode | string): void
  112. hoist(exp: string | JSChildNode | ArrayExpression): SimpleExpressionNode
  113. cache(exp: JSChildNode, isVNode?: boolean, inVOnce?: boolean): CacheExpression
  114. constantCache: WeakMap<TemplateChildNode, ConstantTypes>
  115. // 2.x Compat only
  116. filters?: Set<string>
  117. }
  118. export function createTransformContext(
  119. root: RootNode,
  120. {
  121. filename = '',
  122. prefixIdentifiers = false,
  123. hoistStatic = false,
  124. hmr = false,
  125. cacheHandlers = false,
  126. nodeTransforms = [],
  127. directiveTransforms = {},
  128. transformHoist = null,
  129. isBuiltInComponent = NOOP,
  130. isCustomElement = NOOP,
  131. expressionPlugins = [],
  132. scopeId = null,
  133. slotted = true,
  134. ssr = false,
  135. inSSR = false,
  136. ssrCssVars = ``,
  137. bindingMetadata = EMPTY_OBJ,
  138. inline = false,
  139. isTS = false,
  140. onError = defaultOnError,
  141. onWarn = defaultOnWarn,
  142. compatConfig,
  143. }: TransformOptions,
  144. ): TransformContext {
  145. const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/)
  146. const context: TransformContext = {
  147. // options
  148. filename,
  149. selfName: nameMatch && capitalize(camelize(nameMatch[1])),
  150. prefixIdentifiers,
  151. hoistStatic,
  152. hmr,
  153. cacheHandlers,
  154. nodeTransforms,
  155. directiveTransforms,
  156. transformHoist,
  157. isBuiltInComponent,
  158. isCustomElement,
  159. expressionPlugins,
  160. scopeId,
  161. slotted,
  162. ssr,
  163. inSSR,
  164. ssrCssVars,
  165. bindingMetadata,
  166. inline,
  167. isTS,
  168. onError,
  169. onWarn,
  170. compatConfig,
  171. // state
  172. root,
  173. helpers: new Map(),
  174. components: new Set(),
  175. directives: new Set(),
  176. hoists: [],
  177. imports: [],
  178. cached: [],
  179. constantCache: new WeakMap(),
  180. temps: 0,
  181. identifiers: Object.create(null),
  182. scopes: {
  183. vFor: 0,
  184. vSlot: 0,
  185. vPre: 0,
  186. vOnce: 0,
  187. },
  188. parent: null,
  189. grandParent: null,
  190. currentNode: root,
  191. childIndex: 0,
  192. inVOnce: false,
  193. // methods
  194. helper(name) {
  195. const count = context.helpers.get(name) || 0
  196. context.helpers.set(name, count + 1)
  197. return name
  198. },
  199. removeHelper(name) {
  200. const count = context.helpers.get(name)
  201. if (count) {
  202. const currentCount = count - 1
  203. if (!currentCount) {
  204. context.helpers.delete(name)
  205. } else {
  206. context.helpers.set(name, currentCount)
  207. }
  208. }
  209. },
  210. helperString(name) {
  211. return `_${helperNameMap[context.helper(name)]}`
  212. },
  213. replaceNode(node) {
  214. /* v8 ignore start */
  215. if (__DEV__) {
  216. if (!context.currentNode) {
  217. throw new Error(`Node being replaced is already removed.`)
  218. }
  219. if (!context.parent) {
  220. throw new Error(`Cannot replace root node.`)
  221. }
  222. }
  223. /* v8 ignore stop */
  224. context.parent!.children[context.childIndex] = context.currentNode = node
  225. },
  226. removeNode(node) {
  227. /* v8 ignore next 3 */
  228. if (__DEV__ && !context.parent) {
  229. throw new Error(`Cannot remove root node.`)
  230. }
  231. const list = context.parent!.children
  232. const removalIndex = node
  233. ? list.indexOf(node)
  234. : context.currentNode
  235. ? context.childIndex
  236. : -1
  237. /* v8 ignore next 3 */
  238. if (__DEV__ && removalIndex < 0) {
  239. throw new Error(`node being removed is not a child of current parent`)
  240. }
  241. if (!node || node === context.currentNode) {
  242. // current node removed
  243. context.currentNode = null
  244. context.onNodeRemoved()
  245. } else {
  246. // sibling node removed
  247. if (context.childIndex > removalIndex) {
  248. context.childIndex--
  249. context.onNodeRemoved()
  250. }
  251. }
  252. context.parent!.children.splice(removalIndex, 1)
  253. },
  254. onNodeRemoved: NOOP,
  255. addIdentifiers(exp) {
  256. // identifier tracking only happens in non-browser builds.
  257. if (!__BROWSER__) {
  258. if (isString(exp)) {
  259. addId(exp)
  260. } else if (exp.identifiers) {
  261. exp.identifiers.forEach(addId)
  262. } else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
  263. addId(exp.content)
  264. }
  265. }
  266. },
  267. removeIdentifiers(exp) {
  268. if (!__BROWSER__) {
  269. if (isString(exp)) {
  270. removeId(exp)
  271. } else if (exp.identifiers) {
  272. exp.identifiers.forEach(removeId)
  273. } else if (exp.type === NodeTypes.SIMPLE_EXPRESSION) {
  274. removeId(exp.content)
  275. }
  276. }
  277. },
  278. hoist(exp) {
  279. if (isString(exp)) exp = createSimpleExpression(exp)
  280. context.hoists.push(exp)
  281. const identifier = createSimpleExpression(
  282. `_hoisted_${context.hoists.length}`,
  283. false,
  284. exp.loc,
  285. ConstantTypes.CAN_CACHE,
  286. )
  287. identifier.hoisted = exp
  288. return identifier
  289. },
  290. cache(exp, isVNode = false, inVOnce = false) {
  291. const cacheExp = createCacheExpression(
  292. context.cached.length,
  293. exp,
  294. isVNode,
  295. inVOnce,
  296. )
  297. context.cached.push(cacheExp)
  298. return cacheExp
  299. },
  300. }
  301. if (__COMPAT__) {
  302. context.filters = new Set()
  303. }
  304. function addId(id: string) {
  305. const { identifiers } = context
  306. if (identifiers[id] === undefined) {
  307. identifiers[id] = 0
  308. }
  309. identifiers[id]!++
  310. }
  311. function removeId(id: string) {
  312. context.identifiers[id]!--
  313. }
  314. return context
  315. }
  316. export function transform(root: RootNode, options: TransformOptions): void {
  317. const context = createTransformContext(root, options)
  318. traverseNode(root, context)
  319. if (options.hoistStatic) {
  320. cacheStatic(root, context)
  321. }
  322. if (!options.ssr) {
  323. createRootCodegen(root, context)
  324. }
  325. // finalize meta information
  326. root.helpers = new Set([...context.helpers.keys()])
  327. root.components = [...context.components]
  328. root.directives = [...context.directives]
  329. root.imports = context.imports
  330. root.hoists = context.hoists
  331. root.temps = context.temps
  332. root.cached = context.cached
  333. root.transformed = true
  334. if (__COMPAT__) {
  335. root.filters = [...context.filters!]
  336. }
  337. }
  338. function createRootCodegen(root: RootNode, context: TransformContext) {
  339. const { helper } = context
  340. const { children } = root
  341. if (children.length === 1) {
  342. const singleElementRootChild = getSingleElementRoot(root)
  343. // if the single child is an element, turn it into a block.
  344. if (singleElementRootChild && singleElementRootChild.codegenNode) {
  345. // single element root is never hoisted so codegenNode will never be
  346. // SimpleExpressionNode
  347. const codegenNode = singleElementRootChild.codegenNode
  348. if (codegenNode.type === NodeTypes.VNODE_CALL) {
  349. convertToBlock(codegenNode, context)
  350. }
  351. root.codegenNode = codegenNode
  352. } else {
  353. // - single <slot/>, IfNode, ForNode: already blocks.
  354. // - single text node: always patched.
  355. // root codegen falls through via genNode()
  356. root.codegenNode = children[0]
  357. }
  358. } else if (children.length > 1) {
  359. // root has multiple nodes - return a fragment block.
  360. let patchFlag = PatchFlags.STABLE_FRAGMENT
  361. // check if the fragment actually contains a single valid child with
  362. // the rest being comments
  363. if (
  364. __DEV__ &&
  365. children.filter(c => c.type !== NodeTypes.COMMENT).length === 1
  366. ) {
  367. patchFlag |= PatchFlags.DEV_ROOT_FRAGMENT
  368. }
  369. root.codegenNode = createVNodeCall(
  370. context,
  371. helper(FRAGMENT),
  372. undefined,
  373. root.children,
  374. patchFlag,
  375. undefined,
  376. undefined,
  377. true,
  378. undefined,
  379. false /* isComponent */,
  380. )
  381. } else {
  382. // no children = noop. codegen will return null.
  383. }
  384. }
  385. export function traverseChildren(
  386. parent: ParentNode,
  387. context: TransformContext,
  388. ): void {
  389. let i = 0
  390. const nodeRemoved = () => {
  391. i--
  392. }
  393. for (; i < parent.children.length; i++) {
  394. const child = parent.children[i]
  395. if (isString(child)) continue
  396. context.grandParent = context.parent
  397. context.parent = parent
  398. context.childIndex = i
  399. context.onNodeRemoved = nodeRemoved
  400. traverseNode(child, context)
  401. }
  402. }
  403. export function traverseNode(
  404. node: RootNode | TemplateChildNode,
  405. context: TransformContext,
  406. ): void {
  407. context.currentNode = node
  408. // apply transform plugins
  409. const { nodeTransforms } = context
  410. const exitFns = []
  411. for (let i = 0; i < nodeTransforms.length; i++) {
  412. const onExit = nodeTransforms[i](node, context)
  413. if (onExit) {
  414. if (isArray(onExit)) {
  415. exitFns.push(...onExit)
  416. } else {
  417. exitFns.push(onExit)
  418. }
  419. }
  420. if (!context.currentNode) {
  421. // node was removed
  422. return
  423. } else {
  424. // node may have been replaced
  425. node = context.currentNode
  426. }
  427. }
  428. switch (node.type) {
  429. case NodeTypes.COMMENT:
  430. if (!context.ssr) {
  431. // inject import for the Comment symbol, which is needed for creating
  432. // comment nodes with `createVNode`
  433. context.helper(CREATE_COMMENT)
  434. }
  435. break
  436. case NodeTypes.INTERPOLATION:
  437. // no need to traverse, but we need to inject toString helper
  438. if (!context.ssr) {
  439. context.helper(TO_DISPLAY_STRING)
  440. }
  441. break
  442. // for container types, further traverse downwards
  443. case NodeTypes.IF:
  444. for (let i = 0; i < node.branches.length; i++) {
  445. traverseNode(node.branches[i], context)
  446. }
  447. break
  448. case NodeTypes.IF_BRANCH:
  449. case NodeTypes.FOR:
  450. case NodeTypes.ELEMENT:
  451. case NodeTypes.ROOT:
  452. traverseChildren(node, context)
  453. break
  454. }
  455. // exit transforms
  456. context.currentNode = node
  457. let i = exitFns.length
  458. while (i--) {
  459. exitFns[i]()
  460. }
  461. }
  462. export function createStructuralDirectiveTransform(
  463. name: string | RegExp,
  464. fn: StructuralDirectiveTransform,
  465. ): NodeTransform {
  466. const matches = isString(name)
  467. ? (n: string) => n === name
  468. : (n: string) => name.test(n)
  469. return (node, context) => {
  470. if (node.type === NodeTypes.ELEMENT) {
  471. const { props } = node
  472. // structural directive transforms are not concerned with slots
  473. // as they are handled separately in vSlot.ts
  474. if (node.tagType === ElementTypes.TEMPLATE && props.some(isVSlot)) {
  475. return
  476. }
  477. const exitFns = []
  478. for (let i = 0; i < props.length; i++) {
  479. const prop = props[i]
  480. if (prop.type === NodeTypes.DIRECTIVE && matches(prop.name)) {
  481. // structural directives are removed to avoid infinite recursion
  482. // also we remove them *before* applying so that it can further
  483. // traverse itself in case it moves the node around
  484. props.splice(i, 1)
  485. i--
  486. const onExit = fn(node, prop, context)
  487. if (onExit) exitFns.push(onExit)
  488. }
  489. }
  490. return exitFns
  491. }
  492. }
  493. }