compiler-core.cjs.js 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var shared = require('@vue/shared');
  4. var sourceMap = require('source-map');
  5. var parser = require('@babel/parser');
  6. var estreeWalker = require('estree-walker');
  7. function defaultOnError(error) {
  8. throw error;
  9. }
  10. function createCompilerError(code, loc, messages, additionalMessage) {
  11. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  12. ;
  13. const error = new SyntaxError(String(msg));
  14. error.code = code;
  15. error.loc = loc;
  16. return error;
  17. }
  18. const errorMessages = {
  19. // parse errors
  20. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  21. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  22. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  23. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  24. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  25. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  26. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  27. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  28. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  29. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  30. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  31. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  32. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  33. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  34. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  35. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  36. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  37. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  38. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  39. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  40. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  41. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  42. // Vue-specific parse errors
  43. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  44. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  45. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  46. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  47. 'Note that dynamic directive argument cannot contain spaces.',
  48. // transform errors
  49. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  50. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  51. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  52. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  53. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  54. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  55. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  56. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  57. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  58. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  59. `When there are multiple named slots, all slots should use <template> ` +
  60. `syntax to avoid scope ambiguity.`,
  61. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  62. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  63. `default slot. These children will be ignored.`,
  64. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  65. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  66. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  67. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  68. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  69. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  70. // generic errors
  71. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  72. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  73. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  74. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  75. };
  76. const FRAGMENT = Symbol( `Fragment` );
  77. const TELEPORT = Symbol( `Teleport` );
  78. const SUSPENSE = Symbol( `Suspense` );
  79. const KEEP_ALIVE = Symbol( `KeepAlive` );
  80. const BASE_TRANSITION = Symbol( `BaseTransition` );
  81. const OPEN_BLOCK = Symbol( `openBlock` );
  82. const CREATE_BLOCK = Symbol( `createBlock` );
  83. const CREATE_VNODE = Symbol( `createVNode` );
  84. const CREATE_COMMENT = Symbol( `createCommentVNode` );
  85. const CREATE_TEXT = Symbol( `createTextVNode` );
  86. const CREATE_STATIC = Symbol( `createStaticVNode` );
  87. const RESOLVE_COMPONENT = Symbol( `resolveComponent` );
  88. const RESOLVE_DYNAMIC_COMPONENT = Symbol( `resolveDynamicComponent` );
  89. const RESOLVE_DIRECTIVE = Symbol( `resolveDirective` );
  90. const WITH_DIRECTIVES = Symbol( `withDirectives` );
  91. const RENDER_LIST = Symbol( `renderList` );
  92. const RENDER_SLOT = Symbol( `renderSlot` );
  93. const CREATE_SLOTS = Symbol( `createSlots` );
  94. const TO_DISPLAY_STRING = Symbol( `toDisplayString` );
  95. const MERGE_PROPS = Symbol( `mergeProps` );
  96. const TO_HANDLERS = Symbol( `toHandlers` );
  97. const CAMELIZE = Symbol( `camelize` );
  98. const CAPITALIZE = Symbol( `capitalize` );
  99. const TO_HANDLER_KEY = Symbol( `toHandlerKey` );
  100. const SET_BLOCK_TRACKING = Symbol( `setBlockTracking` );
  101. const PUSH_SCOPE_ID = Symbol( `pushScopeId` );
  102. const POP_SCOPE_ID = Symbol( `popScopeId` );
  103. const WITH_SCOPE_ID = Symbol( `withScopeId` );
  104. const WITH_CTX = Symbol( `withCtx` );
  105. // Name mapping for runtime helpers that need to be imported from 'vue' in
  106. // generated code. Make sure these are correctly exported in the runtime!
  107. // Using `any` here because TS doesn't allow symbols as index type.
  108. const helperNameMap = {
  109. [FRAGMENT]: `Fragment`,
  110. [TELEPORT]: `Teleport`,
  111. [SUSPENSE]: `Suspense`,
  112. [KEEP_ALIVE]: `KeepAlive`,
  113. [BASE_TRANSITION]: `BaseTransition`,
  114. [OPEN_BLOCK]: `openBlock`,
  115. [CREATE_BLOCK]: `createBlock`,
  116. [CREATE_VNODE]: `createVNode`,
  117. [CREATE_COMMENT]: `createCommentVNode`,
  118. [CREATE_TEXT]: `createTextVNode`,
  119. [CREATE_STATIC]: `createStaticVNode`,
  120. [RESOLVE_COMPONENT]: `resolveComponent`,
  121. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  122. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  123. [WITH_DIRECTIVES]: `withDirectives`,
  124. [RENDER_LIST]: `renderList`,
  125. [RENDER_SLOT]: `renderSlot`,
  126. [CREATE_SLOTS]: `createSlots`,
  127. [TO_DISPLAY_STRING]: `toDisplayString`,
  128. [MERGE_PROPS]: `mergeProps`,
  129. [TO_HANDLERS]: `toHandlers`,
  130. [CAMELIZE]: `camelize`,
  131. [CAPITALIZE]: `capitalize`,
  132. [TO_HANDLER_KEY]: `toHandlerKey`,
  133. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  134. [PUSH_SCOPE_ID]: `pushScopeId`,
  135. [POP_SCOPE_ID]: `popScopeId`,
  136. [WITH_SCOPE_ID]: `withScopeId`,
  137. [WITH_CTX]: `withCtx`
  138. };
  139. function registerRuntimeHelpers(helpers) {
  140. Object.getOwnPropertySymbols(helpers).forEach(s => {
  141. helperNameMap[s] = helpers[s];
  142. });
  143. }
  144. // AST Utilities ---------------------------------------------------------------
  145. // Some expressions, e.g. sequence and conditional expressions, are never
  146. // associated with template nodes, so their source locations are just a stub.
  147. // Container types like CompoundExpression also don't need a real location.
  148. const locStub = {
  149. source: '',
  150. start: { line: 1, column: 1, offset: 0 },
  151. end: { line: 1, column: 1, offset: 0 }
  152. };
  153. function createRoot(children, loc = locStub) {
  154. return {
  155. type: 0 /* ROOT */,
  156. children,
  157. helpers: [],
  158. components: [],
  159. directives: [],
  160. hoists: [],
  161. imports: [],
  162. cached: 0,
  163. temps: 0,
  164. codegenNode: undefined,
  165. loc
  166. };
  167. }
  168. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  169. if (context) {
  170. if (isBlock) {
  171. context.helper(OPEN_BLOCK);
  172. context.helper(CREATE_BLOCK);
  173. }
  174. else {
  175. context.helper(CREATE_VNODE);
  176. }
  177. if (directives) {
  178. context.helper(WITH_DIRECTIVES);
  179. }
  180. }
  181. return {
  182. type: 13 /* VNODE_CALL */,
  183. tag,
  184. props,
  185. children,
  186. patchFlag,
  187. dynamicProps,
  188. directives,
  189. isBlock,
  190. disableTracking,
  191. loc
  192. };
  193. }
  194. function createArrayExpression(elements, loc = locStub) {
  195. return {
  196. type: 17 /* JS_ARRAY_EXPRESSION */,
  197. loc,
  198. elements
  199. };
  200. }
  201. function createObjectExpression(properties, loc = locStub) {
  202. return {
  203. type: 15 /* JS_OBJECT_EXPRESSION */,
  204. loc,
  205. properties
  206. };
  207. }
  208. function createObjectProperty(key, value) {
  209. return {
  210. type: 16 /* JS_PROPERTY */,
  211. loc: locStub,
  212. key: shared.isString(key) ? createSimpleExpression(key, true) : key,
  213. value
  214. };
  215. }
  216. function createSimpleExpression(content, isStatic, loc = locStub, isConstant = false) {
  217. return {
  218. type: 4 /* SIMPLE_EXPRESSION */,
  219. loc,
  220. isConstant,
  221. content,
  222. isStatic
  223. };
  224. }
  225. function createInterpolation(content, loc) {
  226. return {
  227. type: 5 /* INTERPOLATION */,
  228. loc,
  229. content: shared.isString(content)
  230. ? createSimpleExpression(content, false, loc)
  231. : content
  232. };
  233. }
  234. function createCompoundExpression(children, loc = locStub) {
  235. return {
  236. type: 8 /* COMPOUND_EXPRESSION */,
  237. loc,
  238. children
  239. };
  240. }
  241. function createCallExpression(callee, args = [], loc = locStub) {
  242. return {
  243. type: 14 /* JS_CALL_EXPRESSION */,
  244. loc,
  245. callee,
  246. arguments: args
  247. };
  248. }
  249. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  250. return {
  251. type: 18 /* JS_FUNCTION_EXPRESSION */,
  252. params,
  253. returns,
  254. newline,
  255. isSlot,
  256. loc
  257. };
  258. }
  259. function createConditionalExpression(test, consequent, alternate, newline = true) {
  260. return {
  261. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  262. test,
  263. consequent,
  264. alternate,
  265. newline,
  266. loc: locStub
  267. };
  268. }
  269. function createCacheExpression(index, value, isVNode = false) {
  270. return {
  271. type: 20 /* JS_CACHE_EXPRESSION */,
  272. index,
  273. value,
  274. isVNode,
  275. loc: locStub
  276. };
  277. }
  278. function createBlockStatement(body) {
  279. return {
  280. type: 21 /* JS_BLOCK_STATEMENT */,
  281. body,
  282. loc: locStub
  283. };
  284. }
  285. function createTemplateLiteral(elements) {
  286. return {
  287. type: 22 /* JS_TEMPLATE_LITERAL */,
  288. elements,
  289. loc: locStub
  290. };
  291. }
  292. function createIfStatement(test, consequent, alternate) {
  293. return {
  294. type: 23 /* JS_IF_STATEMENT */,
  295. test,
  296. consequent,
  297. alternate,
  298. loc: locStub
  299. };
  300. }
  301. function createAssignmentExpression(left, right) {
  302. return {
  303. type: 24 /* JS_ASSIGNMENT_EXPRESSION */,
  304. left,
  305. right,
  306. loc: locStub
  307. };
  308. }
  309. function createSequenceExpression(expressions) {
  310. return {
  311. type: 25 /* JS_SEQUENCE_EXPRESSION */,
  312. expressions,
  313. loc: locStub
  314. };
  315. }
  316. function createReturnStatement(returns) {
  317. return {
  318. type: 26 /* JS_RETURN_STATEMENT */,
  319. returns,
  320. loc: locStub
  321. };
  322. }
  323. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  324. const isBuiltInType = (tag, expected) => tag === expected || tag === shared.hyphenate(expected);
  325. function isCoreComponent(tag) {
  326. if (isBuiltInType(tag, 'Teleport')) {
  327. return TELEPORT;
  328. }
  329. else if (isBuiltInType(tag, 'Suspense')) {
  330. return SUSPENSE;
  331. }
  332. else if (isBuiltInType(tag, 'KeepAlive')) {
  333. return KEEP_ALIVE;
  334. }
  335. else if (isBuiltInType(tag, 'BaseTransition')) {
  336. return BASE_TRANSITION;
  337. }
  338. }
  339. const nonIdentifierRE = /^\d|[^\$\w]/;
  340. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  341. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  342. const isMemberExpression = (path) => {
  343. if (!path)
  344. return false;
  345. return memberExpRE.test(path.trim());
  346. };
  347. function getInnerRange(loc, offset, length) {
  348. const source = loc.source.substr(offset, length);
  349. const newLoc = {
  350. source,
  351. start: advancePositionWithClone(loc.start, loc.source, offset),
  352. end: loc.end
  353. };
  354. if (length != null) {
  355. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  356. }
  357. return newLoc;
  358. }
  359. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  360. return advancePositionWithMutation(shared.extend({}, pos), source, numberOfCharacters);
  361. }
  362. // advance by mutation without cloning (for performance reasons), since this
  363. // gets called a lot in the parser
  364. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  365. let linesCount = 0;
  366. let lastNewLinePos = -1;
  367. for (let i = 0; i < numberOfCharacters; i++) {
  368. if (source.charCodeAt(i) === 10 /* newline char code */) {
  369. linesCount++;
  370. lastNewLinePos = i;
  371. }
  372. }
  373. pos.offset += numberOfCharacters;
  374. pos.line += linesCount;
  375. pos.column =
  376. lastNewLinePos === -1
  377. ? pos.column + numberOfCharacters
  378. : numberOfCharacters - lastNewLinePos;
  379. return pos;
  380. }
  381. function assert(condition, msg) {
  382. /* istanbul ignore if */
  383. if (!condition) {
  384. throw new Error(msg || `unexpected compiler condition`);
  385. }
  386. }
  387. function findDir(node, name, allowEmpty = false) {
  388. for (let i = 0; i < node.props.length; i++) {
  389. const p = node.props[i];
  390. if (p.type === 7 /* DIRECTIVE */ &&
  391. (allowEmpty || p.exp) &&
  392. (shared.isString(name) ? p.name === name : name.test(p.name))) {
  393. return p;
  394. }
  395. }
  396. }
  397. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  398. for (let i = 0; i < node.props.length; i++) {
  399. const p = node.props[i];
  400. if (p.type === 6 /* ATTRIBUTE */) {
  401. if (dynamicOnly)
  402. continue;
  403. if (p.name === name && (p.value || allowEmpty)) {
  404. return p;
  405. }
  406. }
  407. else if (p.name === 'bind' &&
  408. (p.exp || allowEmpty) &&
  409. isBindKey(p.arg, name)) {
  410. return p;
  411. }
  412. }
  413. }
  414. function isBindKey(arg, name) {
  415. return !!(arg && isStaticExp(arg) && arg.content === name);
  416. }
  417. function hasDynamicKeyVBind(node) {
  418. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  419. p.name === 'bind' &&
  420. (!p.arg || // v-bind="obj"
  421. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  422. !p.arg.isStatic) // v-bind:[foo]
  423. );
  424. }
  425. function isText(node) {
  426. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  427. }
  428. function isVSlot(p) {
  429. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  430. }
  431. function isTemplateNode(node) {
  432. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  433. }
  434. function isSlotOutlet(node) {
  435. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  436. }
  437. function injectProp(node, prop, context) {
  438. let propsWithInjection;
  439. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  440. if (props == null || shared.isString(props)) {
  441. propsWithInjection = createObjectExpression([prop]);
  442. }
  443. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  444. // merged props... add ours
  445. // only inject key to object literal if it's the first argument so that
  446. // if doesn't override user provided keys
  447. const first = props.arguments[0];
  448. if (!shared.isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  449. first.properties.unshift(prop);
  450. }
  451. else {
  452. if (props.callee === TO_HANDLERS) {
  453. // #2366
  454. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  455. createObjectExpression([prop]),
  456. props
  457. ]);
  458. }
  459. else {
  460. props.arguments.unshift(createObjectExpression([prop]));
  461. }
  462. }
  463. !propsWithInjection && (propsWithInjection = props);
  464. }
  465. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  466. let alreadyExists = false;
  467. // check existing key to avoid overriding user provided keys
  468. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  469. const propKeyName = prop.key.content;
  470. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  471. p.key.content === propKeyName);
  472. }
  473. if (!alreadyExists) {
  474. props.properties.unshift(prop);
  475. }
  476. propsWithInjection = props;
  477. }
  478. else {
  479. // single v-bind with expression, return a merged replacement
  480. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  481. createObjectExpression([prop]),
  482. props
  483. ]);
  484. }
  485. if (node.type === 13 /* VNODE_CALL */) {
  486. node.props = propsWithInjection;
  487. }
  488. else {
  489. node.arguments[2] = propsWithInjection;
  490. }
  491. }
  492. function toValidAssetId(name, type) {
  493. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  494. }
  495. // Check if a node contains expressions that reference current context scope ids
  496. function hasScopeRef(node, ids) {
  497. if (!node || Object.keys(ids).length === 0) {
  498. return false;
  499. }
  500. switch (node.type) {
  501. case 1 /* ELEMENT */:
  502. for (let i = 0; i < node.props.length; i++) {
  503. const p = node.props[i];
  504. if (p.type === 7 /* DIRECTIVE */ &&
  505. (hasScopeRef(p.arg, ids) || hasScopeRef(p.exp, ids))) {
  506. return true;
  507. }
  508. }
  509. return node.children.some(c => hasScopeRef(c, ids));
  510. case 11 /* FOR */:
  511. if (hasScopeRef(node.source, ids)) {
  512. return true;
  513. }
  514. return node.children.some(c => hasScopeRef(c, ids));
  515. case 9 /* IF */:
  516. return node.branches.some(b => hasScopeRef(b, ids));
  517. case 10 /* IF_BRANCH */:
  518. if (hasScopeRef(node.condition, ids)) {
  519. return true;
  520. }
  521. return node.children.some(c => hasScopeRef(c, ids));
  522. case 4 /* SIMPLE_EXPRESSION */:
  523. return (!node.isStatic &&
  524. isSimpleIdentifier(node.content) &&
  525. !!ids[node.content]);
  526. case 8 /* COMPOUND_EXPRESSION */:
  527. return node.children.some(c => shared.isObject(c) && hasScopeRef(c, ids));
  528. case 5 /* INTERPOLATION */:
  529. case 12 /* TEXT_CALL */:
  530. return hasScopeRef(node.content, ids);
  531. case 2 /* TEXT */:
  532. case 3 /* COMMENT */:
  533. return false;
  534. default:
  535. return false;
  536. }
  537. }
  538. // The default decoder only provides escapes for characters reserved as part of
  539. // the template syntax, and is only used if the custom renderer did not provide
  540. // a platform-specific decoder.
  541. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  542. const decodeMap = {
  543. gt: '>',
  544. lt: '<',
  545. amp: '&',
  546. apos: "'",
  547. quot: '"'
  548. };
  549. const defaultParserOptions = {
  550. delimiters: [`{{`, `}}`],
  551. getNamespace: () => 0 /* HTML */,
  552. getTextMode: () => 0 /* DATA */,
  553. isVoidTag: shared.NO,
  554. isPreTag: shared.NO,
  555. isCustomElement: shared.NO,
  556. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  557. onError: defaultOnError,
  558. comments: false
  559. };
  560. function baseParse(content, options = {}) {
  561. const context = createParserContext(content, options);
  562. const start = getCursor(context);
  563. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  564. }
  565. function createParserContext(content, rawOptions) {
  566. const options = shared.extend({}, defaultParserOptions);
  567. for (const key in rawOptions) {
  568. // @ts-ignore
  569. options[key] = rawOptions[key] || defaultParserOptions[key];
  570. }
  571. return {
  572. options,
  573. column: 1,
  574. line: 1,
  575. offset: 0,
  576. originalSource: content,
  577. source: content,
  578. inPre: false,
  579. inVPre: false
  580. };
  581. }
  582. function parseChildren(context, mode, ancestors) {
  583. const parent = last(ancestors);
  584. const ns = parent ? parent.ns : 0 /* HTML */;
  585. const nodes = [];
  586. while (!isEnd(context, mode, ancestors)) {
  587. const s = context.source;
  588. let node = undefined;
  589. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  590. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  591. // '{{'
  592. node = parseInterpolation(context, mode);
  593. }
  594. else if (mode === 0 /* DATA */ && s[0] === '<') {
  595. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  596. if (s.length === 1) {
  597. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  598. }
  599. else if (s[1] === '!') {
  600. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  601. if (startsWith(s, '<!--')) {
  602. node = parseComment(context);
  603. }
  604. else if (startsWith(s, '<!DOCTYPE')) {
  605. // Ignore DOCTYPE by a limitation.
  606. node = parseBogusComment(context);
  607. }
  608. else if (startsWith(s, '<![CDATA[')) {
  609. if (ns !== 0 /* HTML */) {
  610. node = parseCDATA(context, ancestors);
  611. }
  612. else {
  613. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  614. node = parseBogusComment(context);
  615. }
  616. }
  617. else {
  618. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  619. node = parseBogusComment(context);
  620. }
  621. }
  622. else if (s[1] === '/') {
  623. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  624. if (s.length === 2) {
  625. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  626. }
  627. else if (s[2] === '>') {
  628. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  629. advanceBy(context, 3);
  630. continue;
  631. }
  632. else if (/[a-z]/i.test(s[2])) {
  633. emitError(context, 23 /* X_INVALID_END_TAG */);
  634. parseTag(context, 1 /* End */, parent);
  635. continue;
  636. }
  637. else {
  638. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  639. node = parseBogusComment(context);
  640. }
  641. }
  642. else if (/[a-z]/i.test(s[1])) {
  643. node = parseElement(context, ancestors);
  644. }
  645. else if (s[1] === '?') {
  646. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  647. node = parseBogusComment(context);
  648. }
  649. else {
  650. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  651. }
  652. }
  653. }
  654. if (!node) {
  655. node = parseText(context, mode);
  656. }
  657. if (shared.isArray(node)) {
  658. for (let i = 0; i < node.length; i++) {
  659. pushNode(nodes, node[i]);
  660. }
  661. }
  662. else {
  663. pushNode(nodes, node);
  664. }
  665. }
  666. // Whitespace management for more efficient output
  667. // (same as v2 whitespace: 'condense')
  668. let removedWhitespace = false;
  669. if (mode !== 2 /* RAWTEXT */) {
  670. for (let i = 0; i < nodes.length; i++) {
  671. const node = nodes[i];
  672. if (!context.inPre && node.type === 2 /* TEXT */) {
  673. if (!/[^\t\r\n\f ]/.test(node.content)) {
  674. const prev = nodes[i - 1];
  675. const next = nodes[i + 1];
  676. // If:
  677. // - the whitespace is the first or last node, or:
  678. // - the whitespace is adjacent to a comment, or:
  679. // - the whitespace is between two elements AND contains newline
  680. // Then the whitespace is ignored.
  681. if (!prev ||
  682. !next ||
  683. prev.type === 3 /* COMMENT */ ||
  684. next.type === 3 /* COMMENT */ ||
  685. (prev.type === 1 /* ELEMENT */ &&
  686. next.type === 1 /* ELEMENT */ &&
  687. /[\r\n]/.test(node.content))) {
  688. removedWhitespace = true;
  689. nodes[i] = null;
  690. }
  691. else {
  692. // Otherwise, condensed consecutive whitespace inside the text
  693. // down to a single space
  694. node.content = ' ';
  695. }
  696. }
  697. else {
  698. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  699. }
  700. }
  701. }
  702. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  703. // remove leading newline per html spec
  704. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  705. const first = nodes[0];
  706. if (first && first.type === 2 /* TEXT */) {
  707. first.content = first.content.replace(/^\r?\n/, '');
  708. }
  709. }
  710. }
  711. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  712. }
  713. function pushNode(nodes, node) {
  714. if (node.type === 2 /* TEXT */) {
  715. const prev = last(nodes);
  716. // Merge if both this and the previous node are text and those are
  717. // consecutive. This happens for cases like "a < b".
  718. if (prev &&
  719. prev.type === 2 /* TEXT */ &&
  720. prev.loc.end.offset === node.loc.start.offset) {
  721. prev.content += node.content;
  722. prev.loc.end = node.loc.end;
  723. prev.loc.source += node.loc.source;
  724. return;
  725. }
  726. }
  727. nodes.push(node);
  728. }
  729. function parseCDATA(context, ancestors) {
  730. advanceBy(context, 9);
  731. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  732. if (context.source.length === 0) {
  733. emitError(context, 6 /* EOF_IN_CDATA */);
  734. }
  735. else {
  736. advanceBy(context, 3);
  737. }
  738. return nodes;
  739. }
  740. function parseComment(context) {
  741. const start = getCursor(context);
  742. let content;
  743. // Regular comment.
  744. const match = /--(\!)?>/.exec(context.source);
  745. if (!match) {
  746. content = context.source.slice(4);
  747. advanceBy(context, context.source.length);
  748. emitError(context, 7 /* EOF_IN_COMMENT */);
  749. }
  750. else {
  751. if (match.index <= 3) {
  752. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  753. }
  754. if (match[1]) {
  755. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  756. }
  757. content = context.source.slice(4, match.index);
  758. // Advancing with reporting nested comments.
  759. const s = context.source.slice(0, match.index);
  760. let prevIndex = 1, nestedIndex = 0;
  761. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  762. advanceBy(context, nestedIndex - prevIndex + 1);
  763. if (nestedIndex + 4 < s.length) {
  764. emitError(context, 16 /* NESTED_COMMENT */);
  765. }
  766. prevIndex = nestedIndex + 1;
  767. }
  768. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  769. }
  770. return {
  771. type: 3 /* COMMENT */,
  772. content,
  773. loc: getSelection(context, start)
  774. };
  775. }
  776. function parseBogusComment(context) {
  777. const start = getCursor(context);
  778. const contentStart = context.source[1] === '?' ? 1 : 2;
  779. let content;
  780. const closeIndex = context.source.indexOf('>');
  781. if (closeIndex === -1) {
  782. content = context.source.slice(contentStart);
  783. advanceBy(context, context.source.length);
  784. }
  785. else {
  786. content = context.source.slice(contentStart, closeIndex);
  787. advanceBy(context, closeIndex + 1);
  788. }
  789. return {
  790. type: 3 /* COMMENT */,
  791. content,
  792. loc: getSelection(context, start)
  793. };
  794. }
  795. function parseElement(context, ancestors) {
  796. // Start tag.
  797. const wasInPre = context.inPre;
  798. const wasInVPre = context.inVPre;
  799. const parent = last(ancestors);
  800. const element = parseTag(context, 0 /* Start */, parent);
  801. const isPreBoundary = context.inPre && !wasInPre;
  802. const isVPreBoundary = context.inVPre && !wasInVPre;
  803. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  804. return element;
  805. }
  806. // Children.
  807. ancestors.push(element);
  808. const mode = context.options.getTextMode(element, parent);
  809. const children = parseChildren(context, mode, ancestors);
  810. ancestors.pop();
  811. element.children = children;
  812. // End tag.
  813. if (startsWithEndTagOpen(context.source, element.tag)) {
  814. parseTag(context, 1 /* End */, parent);
  815. }
  816. else {
  817. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  818. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  819. const first = children[0];
  820. if (first && startsWith(first.loc.source, '<!--')) {
  821. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  822. }
  823. }
  824. }
  825. element.loc = getSelection(context, element.loc.start);
  826. if (isPreBoundary) {
  827. context.inPre = false;
  828. }
  829. if (isVPreBoundary) {
  830. context.inVPre = false;
  831. }
  832. return element;
  833. }
  834. const isSpecialTemplateDirective = /*#__PURE__*/ shared.makeMap(`if,else,else-if,for,slot`);
  835. /**
  836. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  837. */
  838. function parseTag(context, type, parent) {
  839. // Tag open.
  840. const start = getCursor(context);
  841. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  842. const tag = match[1];
  843. const ns = context.options.getNamespace(tag, parent);
  844. advanceBy(context, match[0].length);
  845. advanceSpaces(context);
  846. // save current state in case we need to re-parse attributes with v-pre
  847. const cursor = getCursor(context);
  848. const currentSource = context.source;
  849. // Attributes.
  850. let props = parseAttributes(context, type);
  851. // check <pre> tag
  852. if (context.options.isPreTag(tag)) {
  853. context.inPre = true;
  854. }
  855. // check v-pre
  856. if (!context.inVPre &&
  857. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  858. context.inVPre = true;
  859. // reset context
  860. shared.extend(context, cursor);
  861. context.source = currentSource;
  862. // re-parse attrs and filter out v-pre itself
  863. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  864. }
  865. // Tag close.
  866. let isSelfClosing = false;
  867. if (context.source.length === 0) {
  868. emitError(context, 9 /* EOF_IN_TAG */);
  869. }
  870. else {
  871. isSelfClosing = startsWith(context.source, '/>');
  872. if (type === 1 /* End */ && isSelfClosing) {
  873. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  874. }
  875. advanceBy(context, isSelfClosing ? 2 : 1);
  876. }
  877. let tagType = 0 /* ELEMENT */;
  878. const options = context.options;
  879. if (!context.inVPre && !options.isCustomElement(tag)) {
  880. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  881. if (options.isNativeTag && !hasVIs) {
  882. if (!options.isNativeTag(tag))
  883. tagType = 1 /* COMPONENT */;
  884. }
  885. else if (hasVIs ||
  886. isCoreComponent(tag) ||
  887. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  888. /^[A-Z]/.test(tag) ||
  889. tag === 'component') {
  890. tagType = 1 /* COMPONENT */;
  891. }
  892. if (tag === 'slot') {
  893. tagType = 2 /* SLOT */;
  894. }
  895. else if (tag === 'template' &&
  896. props.some(p => {
  897. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  898. })) {
  899. tagType = 3 /* TEMPLATE */;
  900. }
  901. }
  902. return {
  903. type: 1 /* ELEMENT */,
  904. ns,
  905. tag,
  906. tagType,
  907. props,
  908. isSelfClosing,
  909. children: [],
  910. loc: getSelection(context, start),
  911. codegenNode: undefined // to be created during transform phase
  912. };
  913. }
  914. function parseAttributes(context, type) {
  915. const props = [];
  916. const attributeNames = new Set();
  917. while (context.source.length > 0 &&
  918. !startsWith(context.source, '>') &&
  919. !startsWith(context.source, '/>')) {
  920. if (startsWith(context.source, '/')) {
  921. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  922. advanceBy(context, 1);
  923. advanceSpaces(context);
  924. continue;
  925. }
  926. if (type === 1 /* End */) {
  927. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  928. }
  929. const attr = parseAttribute(context, attributeNames);
  930. if (type === 0 /* Start */) {
  931. props.push(attr);
  932. }
  933. if (/^[^\t\r\n\f />]/.test(context.source)) {
  934. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  935. }
  936. advanceSpaces(context);
  937. }
  938. return props;
  939. }
  940. function parseAttribute(context, nameSet) {
  941. // Name.
  942. const start = getCursor(context);
  943. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  944. const name = match[0];
  945. if (nameSet.has(name)) {
  946. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  947. }
  948. nameSet.add(name);
  949. if (name[0] === '=') {
  950. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  951. }
  952. {
  953. const pattern = /["'<]/g;
  954. let m;
  955. while ((m = pattern.exec(name))) {
  956. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  957. }
  958. }
  959. advanceBy(context, name.length);
  960. // Value
  961. let value = undefined;
  962. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  963. advanceSpaces(context);
  964. advanceBy(context, 1);
  965. advanceSpaces(context);
  966. value = parseAttributeValue(context);
  967. if (!value) {
  968. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  969. }
  970. }
  971. const loc = getSelection(context, start);
  972. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  973. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  974. const dirName = match[1] ||
  975. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  976. let arg;
  977. if (match[2]) {
  978. const isSlot = dirName === 'slot';
  979. const startOffset = name.indexOf(match[2]);
  980. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  981. let content = match[2];
  982. let isStatic = true;
  983. if (content.startsWith('[')) {
  984. isStatic = false;
  985. if (!content.endsWith(']')) {
  986. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  987. }
  988. content = content.substr(1, content.length - 2);
  989. }
  990. else if (isSlot) {
  991. // #1241 special case for v-slot: vuetify relies extensively on slot
  992. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  993. // supports such usage so we are keeping it consistent with 2.x.
  994. content += match[3] || '';
  995. }
  996. arg = {
  997. type: 4 /* SIMPLE_EXPRESSION */,
  998. content,
  999. isStatic,
  1000. isConstant: isStatic,
  1001. loc
  1002. };
  1003. }
  1004. if (value && value.isQuoted) {
  1005. const valueLoc = value.loc;
  1006. valueLoc.start.offset++;
  1007. valueLoc.start.column++;
  1008. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  1009. valueLoc.source = valueLoc.source.slice(1, -1);
  1010. }
  1011. return {
  1012. type: 7 /* DIRECTIVE */,
  1013. name: dirName,
  1014. exp: value && {
  1015. type: 4 /* SIMPLE_EXPRESSION */,
  1016. content: value.content,
  1017. isStatic: false,
  1018. // Treat as non-constant by default. This can be potentially set to
  1019. // true by `transformExpression` to make it eligible for hoisting.
  1020. isConstant: false,
  1021. loc: value.loc
  1022. },
  1023. arg,
  1024. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  1025. loc
  1026. };
  1027. }
  1028. return {
  1029. type: 6 /* ATTRIBUTE */,
  1030. name,
  1031. value: value && {
  1032. type: 2 /* TEXT */,
  1033. content: value.content,
  1034. loc: value.loc
  1035. },
  1036. loc
  1037. };
  1038. }
  1039. function parseAttributeValue(context) {
  1040. const start = getCursor(context);
  1041. let content;
  1042. const quote = context.source[0];
  1043. const isQuoted = quote === `"` || quote === `'`;
  1044. if (isQuoted) {
  1045. // Quoted value.
  1046. advanceBy(context, 1);
  1047. const endIndex = context.source.indexOf(quote);
  1048. if (endIndex === -1) {
  1049. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  1050. }
  1051. else {
  1052. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  1053. advanceBy(context, 1);
  1054. }
  1055. }
  1056. else {
  1057. // Unquoted
  1058. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  1059. if (!match) {
  1060. return undefined;
  1061. }
  1062. const unexpectedChars = /["'<=`]/g;
  1063. let m;
  1064. while ((m = unexpectedChars.exec(match[0]))) {
  1065. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  1066. }
  1067. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  1068. }
  1069. return { content, isQuoted, loc: getSelection(context, start) };
  1070. }
  1071. function parseInterpolation(context, mode) {
  1072. const [open, close] = context.options.delimiters;
  1073. const closeIndex = context.source.indexOf(close, open.length);
  1074. if (closeIndex === -1) {
  1075. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  1076. return undefined;
  1077. }
  1078. const start = getCursor(context);
  1079. advanceBy(context, open.length);
  1080. const innerStart = getCursor(context);
  1081. const innerEnd = getCursor(context);
  1082. const rawContentLength = closeIndex - open.length;
  1083. const rawContent = context.source.slice(0, rawContentLength);
  1084. const preTrimContent = parseTextData(context, rawContentLength, mode);
  1085. const content = preTrimContent.trim();
  1086. const startOffset = preTrimContent.indexOf(content);
  1087. if (startOffset > 0) {
  1088. advancePositionWithMutation(innerStart, rawContent, startOffset);
  1089. }
  1090. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  1091. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  1092. advanceBy(context, close.length);
  1093. return {
  1094. type: 5 /* INTERPOLATION */,
  1095. content: {
  1096. type: 4 /* SIMPLE_EXPRESSION */,
  1097. isStatic: false,
  1098. // Set `isConstant` to false by default and will decide in transformExpression
  1099. isConstant: false,
  1100. content,
  1101. loc: getSelection(context, innerStart, innerEnd)
  1102. },
  1103. loc: getSelection(context, start)
  1104. };
  1105. }
  1106. function parseText(context, mode) {
  1107. const endTokens = ['<', context.options.delimiters[0]];
  1108. if (mode === 3 /* CDATA */) {
  1109. endTokens.push(']]>');
  1110. }
  1111. let endIndex = context.source.length;
  1112. for (let i = 0; i < endTokens.length; i++) {
  1113. const index = context.source.indexOf(endTokens[i], 1);
  1114. if (index !== -1 && endIndex > index) {
  1115. endIndex = index;
  1116. }
  1117. }
  1118. const start = getCursor(context);
  1119. const content = parseTextData(context, endIndex, mode);
  1120. return {
  1121. type: 2 /* TEXT */,
  1122. content,
  1123. loc: getSelection(context, start)
  1124. };
  1125. }
  1126. /**
  1127. * Get text data with a given length from the current location.
  1128. * This translates HTML entities in the text data.
  1129. */
  1130. function parseTextData(context, length, mode) {
  1131. const rawText = context.source.slice(0, length);
  1132. advanceBy(context, length);
  1133. if (mode === 2 /* RAWTEXT */ ||
  1134. mode === 3 /* CDATA */ ||
  1135. rawText.indexOf('&') === -1) {
  1136. return rawText;
  1137. }
  1138. else {
  1139. // DATA or RCDATA containing "&"". Entity decoding required.
  1140. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  1141. }
  1142. }
  1143. function getCursor(context) {
  1144. const { column, line, offset } = context;
  1145. return { column, line, offset };
  1146. }
  1147. function getSelection(context, start, end) {
  1148. end = end || getCursor(context);
  1149. return {
  1150. start,
  1151. end,
  1152. source: context.originalSource.slice(start.offset, end.offset)
  1153. };
  1154. }
  1155. function last(xs) {
  1156. return xs[xs.length - 1];
  1157. }
  1158. function startsWith(source, searchString) {
  1159. return source.startsWith(searchString);
  1160. }
  1161. function advanceBy(context, numberOfCharacters) {
  1162. const { source } = context;
  1163. advancePositionWithMutation(context, source, numberOfCharacters);
  1164. context.source = source.slice(numberOfCharacters);
  1165. }
  1166. function advanceSpaces(context) {
  1167. const match = /^[\t\r\n\f ]+/.exec(context.source);
  1168. if (match) {
  1169. advanceBy(context, match[0].length);
  1170. }
  1171. }
  1172. function getNewPosition(context, start, numberOfCharacters) {
  1173. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  1174. }
  1175. function emitError(context, code, offset, loc = getCursor(context)) {
  1176. if (offset) {
  1177. loc.offset += offset;
  1178. loc.column += offset;
  1179. }
  1180. context.options.onError(createCompilerError(code, {
  1181. start: loc,
  1182. end: loc,
  1183. source: ''
  1184. }));
  1185. }
  1186. function isEnd(context, mode, ancestors) {
  1187. const s = context.source;
  1188. switch (mode) {
  1189. case 0 /* DATA */:
  1190. if (startsWith(s, '</')) {
  1191. //TODO: probably bad performance
  1192. for (let i = ancestors.length - 1; i >= 0; --i) {
  1193. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  1194. return true;
  1195. }
  1196. }
  1197. }
  1198. break;
  1199. case 1 /* RCDATA */:
  1200. case 2 /* RAWTEXT */: {
  1201. const parent = last(ancestors);
  1202. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  1203. return true;
  1204. }
  1205. break;
  1206. }
  1207. case 3 /* CDATA */:
  1208. if (startsWith(s, ']]>')) {
  1209. return true;
  1210. }
  1211. break;
  1212. }
  1213. return !s;
  1214. }
  1215. function startsWithEndTagOpen(source, tag) {
  1216. return (startsWith(source, '</') &&
  1217. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  1218. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  1219. }
  1220. function hoistStatic(root, context) {
  1221. walk(root, context, new Map(),
  1222. // Root node is unfortunately non-hoistable due to potential parent
  1223. // fallthrough attributes.
  1224. isSingleElementRoot(root, root.children[0]));
  1225. }
  1226. function isSingleElementRoot(root, child) {
  1227. const { children } = root;
  1228. return (children.length === 1 &&
  1229. child.type === 1 /* ELEMENT */ &&
  1230. !isSlotOutlet(child));
  1231. }
  1232. function walk(node, context, resultCache, doNotHoistNode = false) {
  1233. let hasHoistedNode = false;
  1234. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  1235. // static bindings with expressions. These expressions are guaranteed to be
  1236. // constant so they are still eligible for hoisting, but they are only
  1237. // available at runtime and therefore cannot be evaluated ahead of time.
  1238. // This is only a concern for pre-stringification (via transformHoist by
  1239. // @vue/compiler-dom), but doing it here allows us to perform only one full
  1240. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  1241. // stringficiation threshold is met.
  1242. let hasRuntimeConstant = false;
  1243. const { children } = node;
  1244. for (let i = 0; i < children.length; i++) {
  1245. const child = children[i];
  1246. // only plain elements & text calls are eligible for hoisting.
  1247. if (child.type === 1 /* ELEMENT */ &&
  1248. child.tagType === 0 /* ELEMENT */) {
  1249. let staticType;
  1250. if (!doNotHoistNode &&
  1251. (staticType = getStaticType(child, resultCache)) > 0) {
  1252. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1253. hasRuntimeConstant = true;
  1254. }
  1255. child.codegenNode.patchFlag =
  1256. -1 /* HOISTED */ + ( ` /* HOISTED */` );
  1257. child.codegenNode = context.hoist(child.codegenNode);
  1258. hasHoistedNode = true;
  1259. continue;
  1260. }
  1261. else {
  1262. // node may contain dynamic children, but its props may be eligible for
  1263. // hoisting.
  1264. const codegenNode = child.codegenNode;
  1265. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1266. const flag = getPatchFlag(codegenNode);
  1267. if ((!flag ||
  1268. flag === 512 /* NEED_PATCH */ ||
  1269. flag === 1 /* TEXT */) &&
  1270. !hasNonHoistableProps(child)) {
  1271. const props = getNodeProps(child);
  1272. if (props) {
  1273. codegenNode.props = context.hoist(props);
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. else if (child.type === 12 /* TEXT_CALL */) {
  1280. const staticType = getStaticType(child.content, resultCache);
  1281. if (staticType > 0) {
  1282. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1283. hasRuntimeConstant = true;
  1284. }
  1285. child.codegenNode = context.hoist(child.codegenNode);
  1286. hasHoistedNode = true;
  1287. }
  1288. }
  1289. // walk further
  1290. if (child.type === 1 /* ELEMENT */) {
  1291. walk(child, context, resultCache);
  1292. }
  1293. else if (child.type === 11 /* FOR */) {
  1294. // Do not hoist v-for single child because it has to be a block
  1295. walk(child, context, resultCache, child.children.length === 1);
  1296. }
  1297. else if (child.type === 9 /* IF */) {
  1298. for (let i = 0; i < child.branches.length; i++) {
  1299. // Do not hoist v-if single child because it has to be a block
  1300. walk(child.branches[i], context, resultCache, child.branches[i].children.length === 1);
  1301. }
  1302. }
  1303. }
  1304. if (!hasRuntimeConstant && hasHoistedNode && context.transformHoist) {
  1305. context.transformHoist(children, context, node);
  1306. }
  1307. }
  1308. function getStaticType(node, resultCache = new Map()) {
  1309. switch (node.type) {
  1310. case 1 /* ELEMENT */:
  1311. if (node.tagType !== 0 /* ELEMENT */) {
  1312. return 0 /* NOT_STATIC */;
  1313. }
  1314. const cached = resultCache.get(node);
  1315. if (cached !== undefined) {
  1316. return cached;
  1317. }
  1318. const codegenNode = node.codegenNode;
  1319. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  1320. return 0 /* NOT_STATIC */;
  1321. }
  1322. const flag = getPatchFlag(codegenNode);
  1323. if (!flag && !hasNonHoistableProps(node)) {
  1324. // element self is static. check its children.
  1325. let returnType = 1 /* FULL_STATIC */;
  1326. for (let i = 0; i < node.children.length; i++) {
  1327. const childType = getStaticType(node.children[i], resultCache);
  1328. if (childType === 0 /* NOT_STATIC */) {
  1329. resultCache.set(node, 0 /* NOT_STATIC */);
  1330. return 0 /* NOT_STATIC */;
  1331. }
  1332. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1333. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1334. }
  1335. }
  1336. // check if any of the props contain runtime constants
  1337. if (returnType !== 2 /* HAS_RUNTIME_CONSTANT */) {
  1338. for (let i = 0; i < node.props.length; i++) {
  1339. const p = node.props[i];
  1340. if (p.type === 7 /* DIRECTIVE */ &&
  1341. p.name === 'bind' &&
  1342. p.exp &&
  1343. (p.exp.type === 8 /* COMPOUND_EXPRESSION */ ||
  1344. p.exp.isRuntimeConstant)) {
  1345. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1346. }
  1347. }
  1348. }
  1349. // only svg/foreignObject could be block here, however if they are
  1350. // stati then they don't need to be blocks since there will be no
  1351. // nested updates.
  1352. if (codegenNode.isBlock) {
  1353. codegenNode.isBlock = false;
  1354. }
  1355. resultCache.set(node, returnType);
  1356. return returnType;
  1357. }
  1358. else {
  1359. resultCache.set(node, 0 /* NOT_STATIC */);
  1360. return 0 /* NOT_STATIC */;
  1361. }
  1362. case 2 /* TEXT */:
  1363. case 3 /* COMMENT */:
  1364. return 1 /* FULL_STATIC */;
  1365. case 9 /* IF */:
  1366. case 11 /* FOR */:
  1367. case 10 /* IF_BRANCH */:
  1368. return 0 /* NOT_STATIC */;
  1369. case 5 /* INTERPOLATION */:
  1370. case 12 /* TEXT_CALL */:
  1371. return getStaticType(node.content, resultCache);
  1372. case 4 /* SIMPLE_EXPRESSION */:
  1373. return node.isConstant
  1374. ? node.isRuntimeConstant
  1375. ? 2 /* HAS_RUNTIME_CONSTANT */
  1376. : 1 /* FULL_STATIC */
  1377. : 0 /* NOT_STATIC */;
  1378. case 8 /* COMPOUND_EXPRESSION */:
  1379. let returnType = 1 /* FULL_STATIC */;
  1380. for (let i = 0; i < node.children.length; i++) {
  1381. const child = node.children[i];
  1382. if (shared.isString(child) || shared.isSymbol(child)) {
  1383. continue;
  1384. }
  1385. const childType = getStaticType(child, resultCache);
  1386. if (childType === 0 /* NOT_STATIC */) {
  1387. return 0 /* NOT_STATIC */;
  1388. }
  1389. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  1390. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  1391. }
  1392. }
  1393. return returnType;
  1394. default:
  1395. return 0 /* NOT_STATIC */;
  1396. }
  1397. }
  1398. /**
  1399. * Even for a node with no patch flag, it is possible for it to contain
  1400. * non-hoistable expressions that refers to scope variables, e.g. compiler
  1401. * injected keys or cached event handlers. Therefore we need to always check the
  1402. * codegenNode's props to be sure.
  1403. */
  1404. function hasNonHoistableProps(node) {
  1405. const props = getNodeProps(node);
  1406. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  1407. const { properties } = props;
  1408. for (let i = 0; i < properties.length; i++) {
  1409. const { key, value } = properties[i];
  1410. if (key.type !== 4 /* SIMPLE_EXPRESSION */ ||
  1411. !key.isStatic ||
  1412. (value.type !== 4 /* SIMPLE_EXPRESSION */ ||
  1413. (!value.isStatic && !value.isConstant))) {
  1414. return true;
  1415. }
  1416. }
  1417. }
  1418. return false;
  1419. }
  1420. function getNodeProps(node) {
  1421. const codegenNode = node.codegenNode;
  1422. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1423. return codegenNode.props;
  1424. }
  1425. }
  1426. function getPatchFlag(node) {
  1427. const flag = node.patchFlag;
  1428. return flag ? parseInt(flag, 10) : undefined;
  1429. }
  1430. function createTransformContext(root, { prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = shared.NOOP, isCustomElement = shared.NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = {}, onError = defaultOnError }) {
  1431. const context = {
  1432. // options
  1433. prefixIdentifiers,
  1434. hoistStatic,
  1435. cacheHandlers,
  1436. nodeTransforms,
  1437. directiveTransforms,
  1438. transformHoist,
  1439. isBuiltInComponent,
  1440. isCustomElement,
  1441. expressionPlugins,
  1442. scopeId,
  1443. ssr,
  1444. ssrCssVars,
  1445. bindingMetadata,
  1446. onError,
  1447. // state
  1448. root,
  1449. helpers: new Set(),
  1450. components: new Set(),
  1451. directives: new Set(),
  1452. hoists: [],
  1453. imports: new Set(),
  1454. temps: 0,
  1455. cached: 0,
  1456. identifiers: Object.create(null),
  1457. scopes: {
  1458. vFor: 0,
  1459. vSlot: 0,
  1460. vPre: 0,
  1461. vOnce: 0
  1462. },
  1463. parent: null,
  1464. currentNode: root,
  1465. childIndex: 0,
  1466. // methods
  1467. helper(name) {
  1468. context.helpers.add(name);
  1469. return name;
  1470. },
  1471. helperString(name) {
  1472. return `_${helperNameMap[context.helper(name)]}`;
  1473. },
  1474. replaceNode(node) {
  1475. /* istanbul ignore if */
  1476. {
  1477. if (!context.currentNode) {
  1478. throw new Error(`Node being replaced is already removed.`);
  1479. }
  1480. if (!context.parent) {
  1481. throw new Error(`Cannot replace root node.`);
  1482. }
  1483. }
  1484. context.parent.children[context.childIndex] = context.currentNode = node;
  1485. },
  1486. removeNode(node) {
  1487. if ( !context.parent) {
  1488. throw new Error(`Cannot remove root node.`);
  1489. }
  1490. const list = context.parent.children;
  1491. const removalIndex = node
  1492. ? list.indexOf(node)
  1493. : context.currentNode
  1494. ? context.childIndex
  1495. : -1;
  1496. /* istanbul ignore if */
  1497. if ( removalIndex < 0) {
  1498. throw new Error(`node being removed is not a child of current parent`);
  1499. }
  1500. if (!node || node === context.currentNode) {
  1501. // current node removed
  1502. context.currentNode = null;
  1503. context.onNodeRemoved();
  1504. }
  1505. else {
  1506. // sibling node removed
  1507. if (context.childIndex > removalIndex) {
  1508. context.childIndex--;
  1509. context.onNodeRemoved();
  1510. }
  1511. }
  1512. context.parent.children.splice(removalIndex, 1);
  1513. },
  1514. onNodeRemoved: () => { },
  1515. addIdentifiers(exp) {
  1516. // identifier tracking only happens in non-browser builds.
  1517. {
  1518. if (shared.isString(exp)) {
  1519. addId(exp);
  1520. }
  1521. else if (exp.identifiers) {
  1522. exp.identifiers.forEach(addId);
  1523. }
  1524. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1525. addId(exp.content);
  1526. }
  1527. }
  1528. },
  1529. removeIdentifiers(exp) {
  1530. {
  1531. if (shared.isString(exp)) {
  1532. removeId(exp);
  1533. }
  1534. else if (exp.identifiers) {
  1535. exp.identifiers.forEach(removeId);
  1536. }
  1537. else if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  1538. removeId(exp.content);
  1539. }
  1540. }
  1541. },
  1542. hoist(exp) {
  1543. context.hoists.push(exp);
  1544. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, true);
  1545. identifier.hoisted = exp;
  1546. return identifier;
  1547. },
  1548. cache(exp, isVNode = false) {
  1549. return createCacheExpression(++context.cached, exp, isVNode);
  1550. }
  1551. };
  1552. function addId(id) {
  1553. const { identifiers } = context;
  1554. if (identifiers[id] === undefined) {
  1555. identifiers[id] = 0;
  1556. }
  1557. identifiers[id]++;
  1558. }
  1559. function removeId(id) {
  1560. context.identifiers[id]--;
  1561. }
  1562. return context;
  1563. }
  1564. function transform(root, options) {
  1565. const context = createTransformContext(root, options);
  1566. traverseNode(root, context);
  1567. if (options.hoistStatic) {
  1568. hoistStatic(root, context);
  1569. }
  1570. if (!options.ssr) {
  1571. createRootCodegen(root, context);
  1572. }
  1573. // finalize meta information
  1574. root.helpers = [...context.helpers];
  1575. root.components = [...context.components];
  1576. root.directives = [...context.directives];
  1577. root.imports = [...context.imports];
  1578. root.hoists = context.hoists;
  1579. root.temps = context.temps;
  1580. root.cached = context.cached;
  1581. }
  1582. function createRootCodegen(root, context) {
  1583. const { helper } = context;
  1584. const { children } = root;
  1585. if (children.length === 1) {
  1586. const child = children[0];
  1587. // if the single child is an element, turn it into a block.
  1588. if (isSingleElementRoot(root, child) && child.codegenNode) {
  1589. // single element root is never hoisted so codegenNode will never be
  1590. // SimpleExpressionNode
  1591. const codegenNode = child.codegenNode;
  1592. if (codegenNode.type === 13 /* VNODE_CALL */) {
  1593. codegenNode.isBlock = true;
  1594. helper(OPEN_BLOCK);
  1595. helper(CREATE_BLOCK);
  1596. }
  1597. root.codegenNode = codegenNode;
  1598. }
  1599. else {
  1600. // - single <slot/>, IfNode, ForNode: already blocks.
  1601. // - single text node: always patched.
  1602. // root codegen falls through via genNode()
  1603. root.codegenNode = child;
  1604. }
  1605. }
  1606. else if (children.length > 1) {
  1607. // root has multiple nodes - return a fragment block.
  1608. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, `${64 /* STABLE_FRAGMENT */} /* ${shared.PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  1609. }
  1610. else ;
  1611. }
  1612. function traverseChildren(parent, context) {
  1613. let i = 0;
  1614. const nodeRemoved = () => {
  1615. i--;
  1616. };
  1617. for (; i < parent.children.length; i++) {
  1618. const child = parent.children[i];
  1619. if (shared.isString(child))
  1620. continue;
  1621. context.parent = parent;
  1622. context.childIndex = i;
  1623. context.onNodeRemoved = nodeRemoved;
  1624. traverseNode(child, context);
  1625. }
  1626. }
  1627. function traverseNode(node, context) {
  1628. context.currentNode = node;
  1629. // apply transform plugins
  1630. const { nodeTransforms } = context;
  1631. const exitFns = [];
  1632. for (let i = 0; i < nodeTransforms.length; i++) {
  1633. const onExit = nodeTransforms[i](node, context);
  1634. if (onExit) {
  1635. if (shared.isArray(onExit)) {
  1636. exitFns.push(...onExit);
  1637. }
  1638. else {
  1639. exitFns.push(onExit);
  1640. }
  1641. }
  1642. if (!context.currentNode) {
  1643. // node was removed
  1644. return;
  1645. }
  1646. else {
  1647. // node may have been replaced
  1648. node = context.currentNode;
  1649. }
  1650. }
  1651. switch (node.type) {
  1652. case 3 /* COMMENT */:
  1653. if (!context.ssr) {
  1654. // inject import for the Comment symbol, which is needed for creating
  1655. // comment nodes with `createVNode`
  1656. context.helper(CREATE_COMMENT);
  1657. }
  1658. break;
  1659. case 5 /* INTERPOLATION */:
  1660. // no need to traverse, but we need to inject toString helper
  1661. if (!context.ssr) {
  1662. context.helper(TO_DISPLAY_STRING);
  1663. }
  1664. break;
  1665. // for container types, further traverse downwards
  1666. case 9 /* IF */:
  1667. for (let i = 0; i < node.branches.length; i++) {
  1668. traverseNode(node.branches[i], context);
  1669. }
  1670. break;
  1671. case 10 /* IF_BRANCH */:
  1672. case 11 /* FOR */:
  1673. case 1 /* ELEMENT */:
  1674. case 0 /* ROOT */:
  1675. traverseChildren(node, context);
  1676. break;
  1677. }
  1678. // exit transforms
  1679. context.currentNode = node;
  1680. let i = exitFns.length;
  1681. while (i--) {
  1682. exitFns[i]();
  1683. }
  1684. }
  1685. function createStructuralDirectiveTransform(name, fn) {
  1686. const matches = shared.isString(name)
  1687. ? (n) => n === name
  1688. : (n) => name.test(n);
  1689. return (node, context) => {
  1690. if (node.type === 1 /* ELEMENT */) {
  1691. const { props } = node;
  1692. // structural directive transforms are not concerned with slots
  1693. // as they are handled separately in vSlot.ts
  1694. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  1695. return;
  1696. }
  1697. const exitFns = [];
  1698. for (let i = 0; i < props.length; i++) {
  1699. const prop = props[i];
  1700. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  1701. // structural directives are removed to avoid infinite recursion
  1702. // also we remove them *before* applying so that it can further
  1703. // traverse itself in case it moves the node around
  1704. props.splice(i, 1);
  1705. i--;
  1706. const onExit = fn(node, prop, context);
  1707. if (onExit)
  1708. exitFns.push(onExit);
  1709. }
  1710. }
  1711. return exitFns;
  1712. }
  1713. };
  1714. }
  1715. const PURE_ANNOTATION = `/*#__PURE__*/`;
  1716. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap: sourceMap$1 = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  1717. const context = {
  1718. mode,
  1719. prefixIdentifiers,
  1720. sourceMap: sourceMap$1,
  1721. filename,
  1722. scopeId,
  1723. optimizeImports,
  1724. runtimeGlobalName,
  1725. runtimeModuleName,
  1726. ssr,
  1727. source: ast.loc.source,
  1728. code: ``,
  1729. column: 1,
  1730. line: 1,
  1731. offset: 0,
  1732. indentLevel: 0,
  1733. pure: false,
  1734. map: undefined,
  1735. helper(key) {
  1736. return `_${helperNameMap[key]}`;
  1737. },
  1738. push(code, node) {
  1739. context.code += code;
  1740. if ( context.map) {
  1741. if (node) {
  1742. let name;
  1743. if (node.type === 4 /* SIMPLE_EXPRESSION */ && !node.isStatic) {
  1744. const content = node.content.replace(/^_ctx\./, '');
  1745. if (content !== node.content && isSimpleIdentifier(content)) {
  1746. name = content;
  1747. }
  1748. }
  1749. addMapping(node.loc.start, name);
  1750. }
  1751. advancePositionWithMutation(context, code);
  1752. if (node && node.loc !== locStub) {
  1753. addMapping(node.loc.end);
  1754. }
  1755. }
  1756. },
  1757. indent() {
  1758. newline(++context.indentLevel);
  1759. },
  1760. deindent(withoutNewLine = false) {
  1761. if (withoutNewLine) {
  1762. --context.indentLevel;
  1763. }
  1764. else {
  1765. newline(--context.indentLevel);
  1766. }
  1767. },
  1768. newline() {
  1769. newline(context.indentLevel);
  1770. }
  1771. };
  1772. function newline(n) {
  1773. context.push('\n' + ` `.repeat(n));
  1774. }
  1775. function addMapping(loc, name) {
  1776. context.map.addMapping({
  1777. name,
  1778. source: context.filename,
  1779. original: {
  1780. line: loc.line,
  1781. column: loc.column - 1 // source-map column is 0 based
  1782. },
  1783. generated: {
  1784. line: context.line,
  1785. column: context.column - 1
  1786. }
  1787. });
  1788. }
  1789. if ( sourceMap$1) {
  1790. // lazy require source-map implementation, only in non-browser builds
  1791. context.map = new sourceMap.SourceMapGenerator();
  1792. context.map.setSourceContent(filename, context.source);
  1793. }
  1794. return context;
  1795. }
  1796. function generate(ast, options = {}) {
  1797. const context = createCodegenContext(ast, options);
  1798. if (options.onContextCreated)
  1799. options.onContextCreated(context);
  1800. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  1801. const hasHelpers = ast.helpers.length > 0;
  1802. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  1803. const genScopeId = scopeId != null && mode === 'module';
  1804. // preambles
  1805. if ( mode === 'module') {
  1806. genModulePreamble(ast, context, genScopeId);
  1807. }
  1808. else {
  1809. genFunctionPreamble(ast, context);
  1810. }
  1811. // binding optimizations
  1812. const optimizeSources = options.bindingMetadata
  1813. ? `, $props, $setup, $data, $options`
  1814. : ``;
  1815. // enter render function
  1816. if (!ssr) {
  1817. if (genScopeId) {
  1818. push(`const render = ${PURE_ANNOTATION}_withId(`);
  1819. }
  1820. push(`function render(_ctx, _cache${optimizeSources}) {`);
  1821. }
  1822. else {
  1823. if (genScopeId) {
  1824. push(`const ssrRender = ${PURE_ANNOTATION}_withId(`);
  1825. }
  1826. push(`function ssrRender(_ctx, _push, _parent, _attrs${optimizeSources}) {`);
  1827. }
  1828. indent();
  1829. if (useWithBlock) {
  1830. push(`with (_ctx) {`);
  1831. indent();
  1832. // function mode const declarations should be inside with block
  1833. // also they should be renamed to avoid collision with user properties
  1834. if (hasHelpers) {
  1835. push(`const { ${ast.helpers
  1836. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  1837. .join(', ')} } = _Vue`);
  1838. push(`\n`);
  1839. newline();
  1840. }
  1841. }
  1842. // generate asset resolution statements
  1843. if (ast.components.length) {
  1844. genAssets(ast.components, 'component', context);
  1845. if (ast.directives.length || ast.temps > 0) {
  1846. newline();
  1847. }
  1848. }
  1849. if (ast.directives.length) {
  1850. genAssets(ast.directives, 'directive', context);
  1851. if (ast.temps > 0) {
  1852. newline();
  1853. }
  1854. }
  1855. if (ast.temps > 0) {
  1856. push(`let `);
  1857. for (let i = 0; i < ast.temps; i++) {
  1858. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  1859. }
  1860. }
  1861. if (ast.components.length || ast.directives.length || ast.temps) {
  1862. push(`\n`);
  1863. newline();
  1864. }
  1865. // generate the VNode tree expression
  1866. if (!ssr) {
  1867. push(`return `);
  1868. }
  1869. if (ast.codegenNode) {
  1870. genNode(ast.codegenNode, context);
  1871. }
  1872. else {
  1873. push(`null`);
  1874. }
  1875. if (useWithBlock) {
  1876. deindent();
  1877. push(`}`);
  1878. }
  1879. deindent();
  1880. push(`}`);
  1881. if (genScopeId) {
  1882. push(`)`);
  1883. }
  1884. return {
  1885. ast,
  1886. code: context.code,
  1887. // SourceMapGenerator does have toJSON() method but it's not in the types
  1888. map: context.map ? context.map.toJSON() : undefined
  1889. };
  1890. }
  1891. function genFunctionPreamble(ast, context) {
  1892. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  1893. const VueBinding = ssr
  1894. ? `require(${JSON.stringify(runtimeModuleName)})`
  1895. : runtimeGlobalName;
  1896. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  1897. // Generate const declaration for helpers
  1898. // In prefix mode, we place the const declaration at top so it's done
  1899. // only once; But if we not prefixing, we place the declaration inside the
  1900. // with block so it doesn't incur the `in` check cost for every helper access.
  1901. if (ast.helpers.length > 0) {
  1902. if ( prefixIdentifiers) {
  1903. push(`const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n`);
  1904. }
  1905. else {
  1906. // "with" mode.
  1907. // save Vue in a separate variable to avoid collision
  1908. push(`const _Vue = ${VueBinding}\n`);
  1909. // in "with" mode, helpers are declared inside the with block to avoid
  1910. // has check cost, but hoists are lifted out of the function - we need
  1911. // to provide the helper here.
  1912. if (ast.hoists.length) {
  1913. const staticHelpers = [
  1914. CREATE_VNODE,
  1915. CREATE_COMMENT,
  1916. CREATE_TEXT,
  1917. CREATE_STATIC
  1918. ]
  1919. .filter(helper => ast.helpers.includes(helper))
  1920. .map(aliasHelper)
  1921. .join(', ');
  1922. push(`const { ${staticHelpers} } = _Vue\n`);
  1923. }
  1924. }
  1925. }
  1926. // generate variables for ssr helpers
  1927. if ( ast.ssrHelpers && ast.ssrHelpers.length) {
  1928. // ssr guarantees prefixIdentifier: true
  1929. push(`const { ${ast.ssrHelpers
  1930. .map(aliasHelper)
  1931. .join(', ')} } = require("@vue/server-renderer")\n`);
  1932. }
  1933. genHoists(ast.hoists, context);
  1934. newline();
  1935. push(`return `);
  1936. }
  1937. function genModulePreamble(ast, context, genScopeId) {
  1938. const { push, helper, newline, scopeId, optimizeImports, runtimeModuleName } = context;
  1939. if (genScopeId) {
  1940. ast.helpers.push(WITH_SCOPE_ID);
  1941. if (ast.hoists.length) {
  1942. ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID);
  1943. }
  1944. }
  1945. // generate import statements for helpers
  1946. if (ast.helpers.length) {
  1947. if (optimizeImports) {
  1948. // when bundled with webpack with code-split, calling an import binding
  1949. // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`,
  1950. // incurring both payload size increase and potential perf overhead.
  1951. // therefore we assign the imports to variables (which is a constant ~50b
  1952. // cost per-component instead of scaling with template size)
  1953. push(`import { ${ast.helpers
  1954. .map(s => helperNameMap[s])
  1955. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  1956. push(`\n// Binding optimization for webpack code-split\nconst ${ast.helpers
  1957. .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`)
  1958. .join(', ')}\n`);
  1959. }
  1960. else {
  1961. push(`import { ${ast.helpers
  1962. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  1963. .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n`);
  1964. }
  1965. }
  1966. if (ast.ssrHelpers && ast.ssrHelpers.length) {
  1967. push(`import { ${ast.ssrHelpers
  1968. .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`)
  1969. .join(', ')} } from "@vue/server-renderer"\n`);
  1970. }
  1971. if (ast.imports.length) {
  1972. genImports(ast.imports, context);
  1973. newline();
  1974. }
  1975. if (genScopeId) {
  1976. push(`const _withId = ${PURE_ANNOTATION}${helper(WITH_SCOPE_ID)}("${scopeId}")`);
  1977. newline();
  1978. }
  1979. genHoists(ast.hoists, context);
  1980. newline();
  1981. push(`export `);
  1982. }
  1983. function genAssets(assets, type, { helper, push, newline }) {
  1984. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  1985. for (let i = 0; i < assets.length; i++) {
  1986. const id = assets[i];
  1987. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  1988. if (i < assets.length - 1) {
  1989. newline();
  1990. }
  1991. }
  1992. }
  1993. function genHoists(hoists, context) {
  1994. if (!hoists.length) {
  1995. return;
  1996. }
  1997. context.pure = true;
  1998. const { push, newline, helper, scopeId, mode } = context;
  1999. const genScopeId = scopeId != null && mode !== 'function';
  2000. newline();
  2001. // push scope Id before initializing hoisted vnodes so that these vnodes
  2002. // get the proper scopeId as well.
  2003. if (genScopeId) {
  2004. push(`${helper(PUSH_SCOPE_ID)}("${scopeId}")`);
  2005. newline();
  2006. }
  2007. hoists.forEach((exp, i) => {
  2008. if (exp) {
  2009. push(`const _hoisted_${i + 1} = `);
  2010. genNode(exp, context);
  2011. newline();
  2012. }
  2013. });
  2014. if (genScopeId) {
  2015. push(`${helper(POP_SCOPE_ID)}()`);
  2016. newline();
  2017. }
  2018. context.pure = false;
  2019. }
  2020. function genImports(importsOptions, context) {
  2021. if (!importsOptions.length) {
  2022. return;
  2023. }
  2024. importsOptions.forEach(imports => {
  2025. context.push(`import `);
  2026. genNode(imports.exp, context);
  2027. context.push(` from '${imports.path}'`);
  2028. context.newline();
  2029. });
  2030. }
  2031. function isText$1(n) {
  2032. return (shared.isString(n) ||
  2033. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  2034. n.type === 2 /* TEXT */ ||
  2035. n.type === 5 /* INTERPOLATION */ ||
  2036. n.type === 8 /* COMPOUND_EXPRESSION */);
  2037. }
  2038. function genNodeListAsArray(nodes, context) {
  2039. const multilines = nodes.length > 3 ||
  2040. ( nodes.some(n => shared.isArray(n) || !isText$1(n)));
  2041. context.push(`[`);
  2042. multilines && context.indent();
  2043. genNodeList(nodes, context, multilines);
  2044. multilines && context.deindent();
  2045. context.push(`]`);
  2046. }
  2047. function genNodeList(nodes, context, multilines = false, comma = true) {
  2048. const { push, newline } = context;
  2049. for (let i = 0; i < nodes.length; i++) {
  2050. const node = nodes[i];
  2051. if (shared.isString(node)) {
  2052. push(node);
  2053. }
  2054. else if (shared.isArray(node)) {
  2055. genNodeListAsArray(node, context);
  2056. }
  2057. else {
  2058. genNode(node, context);
  2059. }
  2060. if (i < nodes.length - 1) {
  2061. if (multilines) {
  2062. comma && push(',');
  2063. newline();
  2064. }
  2065. else {
  2066. comma && push(', ');
  2067. }
  2068. }
  2069. }
  2070. }
  2071. function genNode(node, context) {
  2072. if (shared.isString(node)) {
  2073. context.push(node);
  2074. return;
  2075. }
  2076. if (shared.isSymbol(node)) {
  2077. context.push(context.helper(node));
  2078. return;
  2079. }
  2080. switch (node.type) {
  2081. case 1 /* ELEMENT */:
  2082. case 9 /* IF */:
  2083. case 11 /* FOR */:
  2084. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  2085. `Apply appropriate transforms first.`);
  2086. genNode(node.codegenNode, context);
  2087. break;
  2088. case 2 /* TEXT */:
  2089. genText(node, context);
  2090. break;
  2091. case 4 /* SIMPLE_EXPRESSION */:
  2092. genExpression(node, context);
  2093. break;
  2094. case 5 /* INTERPOLATION */:
  2095. genInterpolation(node, context);
  2096. break;
  2097. case 12 /* TEXT_CALL */:
  2098. genNode(node.codegenNode, context);
  2099. break;
  2100. case 8 /* COMPOUND_EXPRESSION */:
  2101. genCompoundExpression(node, context);
  2102. break;
  2103. case 3 /* COMMENT */:
  2104. genComment(node, context);
  2105. break;
  2106. case 13 /* VNODE_CALL */:
  2107. genVNodeCall(node, context);
  2108. break;
  2109. case 14 /* JS_CALL_EXPRESSION */:
  2110. genCallExpression(node, context);
  2111. break;
  2112. case 15 /* JS_OBJECT_EXPRESSION */:
  2113. genObjectExpression(node, context);
  2114. break;
  2115. case 17 /* JS_ARRAY_EXPRESSION */:
  2116. genArrayExpression(node, context);
  2117. break;
  2118. case 18 /* JS_FUNCTION_EXPRESSION */:
  2119. genFunctionExpression(node, context);
  2120. break;
  2121. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  2122. genConditionalExpression(node, context);
  2123. break;
  2124. case 20 /* JS_CACHE_EXPRESSION */:
  2125. genCacheExpression(node, context);
  2126. break;
  2127. // SSR only types
  2128. case 21 /* JS_BLOCK_STATEMENT */:
  2129. genNodeList(node.body, context, true, false);
  2130. break;
  2131. case 22 /* JS_TEMPLATE_LITERAL */:
  2132. genTemplateLiteral(node, context);
  2133. break;
  2134. case 23 /* JS_IF_STATEMENT */:
  2135. genIfStatement(node, context);
  2136. break;
  2137. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  2138. genAssignmentExpression(node, context);
  2139. break;
  2140. case 25 /* JS_SEQUENCE_EXPRESSION */:
  2141. genSequenceExpression(node, context);
  2142. break;
  2143. case 26 /* JS_RETURN_STATEMENT */:
  2144. genReturnStatement(node, context);
  2145. break;
  2146. /* istanbul ignore next */
  2147. case 10 /* IF_BRANCH */:
  2148. // noop
  2149. break;
  2150. default:
  2151. {
  2152. assert(false, `unhandled codegen node type: ${node.type}`);
  2153. // make sure we exhaust all possible types
  2154. const exhaustiveCheck = node;
  2155. return exhaustiveCheck;
  2156. }
  2157. }
  2158. }
  2159. function genText(node, context) {
  2160. context.push(JSON.stringify(node.content), node);
  2161. }
  2162. function genExpression(node, context) {
  2163. const { content, isStatic } = node;
  2164. context.push(isStatic ? JSON.stringify(content) : content, node);
  2165. }
  2166. function genInterpolation(node, context) {
  2167. const { push, helper, pure } = context;
  2168. if (pure)
  2169. push(PURE_ANNOTATION);
  2170. push(`${helper(TO_DISPLAY_STRING)}(`);
  2171. genNode(node.content, context);
  2172. push(`)`);
  2173. }
  2174. function genCompoundExpression(node, context) {
  2175. for (let i = 0; i < node.children.length; i++) {
  2176. const child = node.children[i];
  2177. if (shared.isString(child)) {
  2178. context.push(child);
  2179. }
  2180. else {
  2181. genNode(child, context);
  2182. }
  2183. }
  2184. }
  2185. function genExpressionAsPropertyKey(node, context) {
  2186. const { push } = context;
  2187. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  2188. push(`[`);
  2189. genCompoundExpression(node, context);
  2190. push(`]`);
  2191. }
  2192. else if (node.isStatic) {
  2193. // only quote keys if necessary
  2194. const text = isSimpleIdentifier(node.content)
  2195. ? node.content
  2196. : JSON.stringify(node.content);
  2197. push(text, node);
  2198. }
  2199. else {
  2200. push(`[${node.content}]`, node);
  2201. }
  2202. }
  2203. function genComment(node, context) {
  2204. {
  2205. const { push, helper, pure } = context;
  2206. if (pure) {
  2207. push(PURE_ANNOTATION);
  2208. }
  2209. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  2210. }
  2211. }
  2212. function genVNodeCall(node, context) {
  2213. const { push, helper, pure } = context;
  2214. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  2215. if (directives) {
  2216. push(helper(WITH_DIRECTIVES) + `(`);
  2217. }
  2218. if (isBlock) {
  2219. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  2220. }
  2221. if (pure) {
  2222. push(PURE_ANNOTATION);
  2223. }
  2224. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  2225. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  2226. push(`)`);
  2227. if (isBlock) {
  2228. push(`)`);
  2229. }
  2230. if (directives) {
  2231. push(`, `);
  2232. genNode(directives, context);
  2233. push(`)`);
  2234. }
  2235. }
  2236. function genNullableArgs(args) {
  2237. let i = args.length;
  2238. while (i--) {
  2239. if (args[i] != null)
  2240. break;
  2241. }
  2242. return args.slice(0, i + 1).map(arg => arg || `null`);
  2243. }
  2244. // JavaScript
  2245. function genCallExpression(node, context) {
  2246. const { push, helper, pure } = context;
  2247. const callee = shared.isString(node.callee) ? node.callee : helper(node.callee);
  2248. if (pure) {
  2249. push(PURE_ANNOTATION);
  2250. }
  2251. push(callee + `(`, node);
  2252. genNodeList(node.arguments, context);
  2253. push(`)`);
  2254. }
  2255. function genObjectExpression(node, context) {
  2256. const { push, indent, deindent, newline } = context;
  2257. const { properties } = node;
  2258. if (!properties.length) {
  2259. push(`{}`, node);
  2260. return;
  2261. }
  2262. const multilines = properties.length > 1 ||
  2263. (
  2264. properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  2265. push(multilines ? `{` : `{ `);
  2266. multilines && indent();
  2267. for (let i = 0; i < properties.length; i++) {
  2268. const { key, value } = properties[i];
  2269. // key
  2270. genExpressionAsPropertyKey(key, context);
  2271. push(`: `);
  2272. // value
  2273. genNode(value, context);
  2274. if (i < properties.length - 1) {
  2275. // will only reach this if it's multilines
  2276. push(`,`);
  2277. newline();
  2278. }
  2279. }
  2280. multilines && deindent();
  2281. push(multilines ? `}` : ` }`);
  2282. }
  2283. function genArrayExpression(node, context) {
  2284. genNodeListAsArray(node.elements, context);
  2285. }
  2286. function genFunctionExpression(node, context) {
  2287. const { push, indent, deindent, scopeId, mode } = context;
  2288. const { params, returns, body, newline, isSlot } = node;
  2289. // slot functions also need to push scopeId before rendering its content
  2290. const genScopeId = isSlot && scopeId != null && mode !== 'function';
  2291. if (genScopeId) {
  2292. push(`_withId(`);
  2293. }
  2294. else if (isSlot) {
  2295. push(`_${helperNameMap[WITH_CTX]}(`);
  2296. }
  2297. push(`(`, node);
  2298. if (shared.isArray(params)) {
  2299. genNodeList(params, context);
  2300. }
  2301. else if (params) {
  2302. genNode(params, context);
  2303. }
  2304. push(`) => `);
  2305. if (newline || body) {
  2306. push(`{`);
  2307. indent();
  2308. }
  2309. if (returns) {
  2310. if (newline) {
  2311. push(`return `);
  2312. }
  2313. if (shared.isArray(returns)) {
  2314. genNodeListAsArray(returns, context);
  2315. }
  2316. else {
  2317. genNode(returns, context);
  2318. }
  2319. }
  2320. else if (body) {
  2321. genNode(body, context);
  2322. }
  2323. if (newline || body) {
  2324. deindent();
  2325. push(`}`);
  2326. }
  2327. if (genScopeId || isSlot) {
  2328. push(`)`);
  2329. }
  2330. }
  2331. function genConditionalExpression(node, context) {
  2332. const { test, consequent, alternate, newline: needNewline } = node;
  2333. const { push, indent, deindent, newline } = context;
  2334. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  2335. const needsParens = !isSimpleIdentifier(test.content);
  2336. needsParens && push(`(`);
  2337. genExpression(test, context);
  2338. needsParens && push(`)`);
  2339. }
  2340. else {
  2341. push(`(`);
  2342. genNode(test, context);
  2343. push(`)`);
  2344. }
  2345. needNewline && indent();
  2346. context.indentLevel++;
  2347. needNewline || push(` `);
  2348. push(`? `);
  2349. genNode(consequent, context);
  2350. context.indentLevel--;
  2351. needNewline && newline();
  2352. needNewline || push(` `);
  2353. push(`: `);
  2354. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  2355. if (!isNested) {
  2356. context.indentLevel++;
  2357. }
  2358. genNode(alternate, context);
  2359. if (!isNested) {
  2360. context.indentLevel--;
  2361. }
  2362. needNewline && deindent(true /* without newline */);
  2363. }
  2364. function genCacheExpression(node, context) {
  2365. const { push, helper, indent, deindent, newline } = context;
  2366. push(`_cache[${node.index}] || (`);
  2367. if (node.isVNode) {
  2368. indent();
  2369. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  2370. newline();
  2371. }
  2372. push(`_cache[${node.index}] = `);
  2373. genNode(node.value, context);
  2374. if (node.isVNode) {
  2375. push(`,`);
  2376. newline();
  2377. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  2378. newline();
  2379. push(`_cache[${node.index}]`);
  2380. deindent();
  2381. }
  2382. push(`)`);
  2383. }
  2384. function genTemplateLiteral(node, context) {
  2385. const { push, indent, deindent } = context;
  2386. push('`');
  2387. const l = node.elements.length;
  2388. const multilines = l > 3;
  2389. for (let i = 0; i < l; i++) {
  2390. const e = node.elements[i];
  2391. if (shared.isString(e)) {
  2392. push(e.replace(/(`|\$|\\)/g, '\\$1'));
  2393. }
  2394. else {
  2395. push('${');
  2396. if (multilines)
  2397. indent();
  2398. genNode(e, context);
  2399. if (multilines)
  2400. deindent();
  2401. push('}');
  2402. }
  2403. }
  2404. push('`');
  2405. }
  2406. function genIfStatement(node, context) {
  2407. const { push, indent, deindent } = context;
  2408. const { test, consequent, alternate } = node;
  2409. push(`if (`);
  2410. genNode(test, context);
  2411. push(`) {`);
  2412. indent();
  2413. genNode(consequent, context);
  2414. deindent();
  2415. push(`}`);
  2416. if (alternate) {
  2417. push(` else `);
  2418. if (alternate.type === 23 /* JS_IF_STATEMENT */) {
  2419. genIfStatement(alternate, context);
  2420. }
  2421. else {
  2422. push(`{`);
  2423. indent();
  2424. genNode(alternate, context);
  2425. deindent();
  2426. push(`}`);
  2427. }
  2428. }
  2429. }
  2430. function genAssignmentExpression(node, context) {
  2431. genNode(node.left, context);
  2432. context.push(` = `);
  2433. genNode(node.right, context);
  2434. }
  2435. function genSequenceExpression(node, context) {
  2436. context.push(`(`);
  2437. genNodeList(node.expressions, context);
  2438. context.push(`)`);
  2439. }
  2440. function genReturnStatement({ returns }, context) {
  2441. context.push(`return `);
  2442. if (shared.isArray(returns)) {
  2443. genNodeListAsArray(returns, context);
  2444. }
  2445. else {
  2446. genNode(returns, context);
  2447. }
  2448. }
  2449. const isLiteralWhitelisted = /*#__PURE__*/ shared.makeMap('true,false,null,this');
  2450. const transformExpression = (node, context) => {
  2451. if (node.type === 5 /* INTERPOLATION */) {
  2452. node.content = processExpression(node.content, context);
  2453. }
  2454. else if (node.type === 1 /* ELEMENT */) {
  2455. // handle directives on element
  2456. for (let i = 0; i < node.props.length; i++) {
  2457. const dir = node.props[i];
  2458. // do not process for v-on & v-for since they are special handled
  2459. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  2460. const exp = dir.exp;
  2461. const arg = dir.arg;
  2462. // do not process exp if this is v-on:arg - we need special handling
  2463. // for wrapping inline statements.
  2464. if (exp &&
  2465. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  2466. !(dir.name === 'on' && arg)) {
  2467. dir.exp = processExpression(exp, context,
  2468. // slot args must be processed as function params
  2469. dir.name === 'slot');
  2470. }
  2471. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  2472. dir.arg = processExpression(arg, context);
  2473. }
  2474. }
  2475. }
  2476. }
  2477. };
  2478. // Important: since this function uses Node.js only dependencies, it should
  2479. // always be used with a leading !false check so that it can be
  2480. // tree-shaken from the browser build.
  2481. function processExpression(node, context,
  2482. // some expressions like v-slot props & v-for aliases should be parsed as
  2483. // function params
  2484. asParams = false,
  2485. // v-on handler values may contain multiple statements
  2486. asRawStatements = false) {
  2487. if (!context.prefixIdentifiers || !node.content.trim()) {
  2488. return node;
  2489. }
  2490. const { bindingMetadata } = context;
  2491. const prefix = (raw) => {
  2492. const source = shared.hasOwn(bindingMetadata, raw)
  2493. ? `$` + bindingMetadata[raw]
  2494. : `_ctx`;
  2495. return `${source}.${raw}`;
  2496. };
  2497. // fast path if expression is a simple identifier.
  2498. const rawExp = node.content;
  2499. // bail on parens to prevent any possible function invocations.
  2500. const bailConstant = rawExp.indexOf(`(`) > -1;
  2501. if (isSimpleIdentifier(rawExp)) {
  2502. if (!asParams &&
  2503. !context.identifiers[rawExp] &&
  2504. !shared.isGloballyWhitelisted(rawExp) &&
  2505. !isLiteralWhitelisted(rawExp)) {
  2506. node.content = prefix(rawExp);
  2507. }
  2508. else if (!context.identifiers[rawExp] && !bailConstant) {
  2509. // mark node constant for hoisting unless it's referring a scope variable
  2510. node.isConstant = true;
  2511. }
  2512. return node;
  2513. }
  2514. let ast;
  2515. // exp needs to be parsed differently:
  2516. // 1. Multiple inline statements (v-on, with presence of `;`): parse as raw
  2517. // exp, but make sure to pad with spaces for consistent ranges
  2518. // 2. Expressions: wrap with parens (for e.g. object expressions)
  2519. // 3. Function arguments (v-for, v-slot): place in a function argument position
  2520. const source = asRawStatements
  2521. ? ` ${rawExp} `
  2522. : `(${rawExp})${asParams ? `=>{}` : ``}`;
  2523. try {
  2524. ast = parser.parse(source, {
  2525. plugins: [...context.expressionPlugins, ...shared.babelParserDefaultPlugins]
  2526. }).program;
  2527. }
  2528. catch (e) {
  2529. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, e.message));
  2530. return node;
  2531. }
  2532. const ids = [];
  2533. const knownIds = Object.create(context.identifiers);
  2534. const isDuplicate = (node) => ids.some(id => id.start === node.start);
  2535. estreeWalker.walk(ast, {
  2536. enter(node, parent) {
  2537. if (node.type === 'Identifier') {
  2538. if (!isDuplicate(node)) {
  2539. const needPrefix = shouldPrefix(node, parent);
  2540. if (!knownIds[node.name] && needPrefix) {
  2541. if (isPropertyShorthand(node, parent)) {
  2542. // property shorthand like { foo }, we need to add the key since we
  2543. // rewrite the value
  2544. node.prefix = `${node.name}: `;
  2545. }
  2546. node.name = prefix(node.name);
  2547. ids.push(node);
  2548. }
  2549. else if (!isStaticPropertyKey(node, parent)) {
  2550. // The identifier is considered constant unless it's pointing to a
  2551. // scope variable (a v-for alias, or a v-slot prop)
  2552. if (!(needPrefix && knownIds[node.name]) && !bailConstant) {
  2553. node.isConstant = true;
  2554. }
  2555. // also generate sub-expressions for other identifiers for better
  2556. // source map support. (except for property keys which are static)
  2557. ids.push(node);
  2558. }
  2559. }
  2560. }
  2561. else if (isFunction(node)) {
  2562. // walk function expressions and add its arguments to known identifiers
  2563. // so that we don't prefix them
  2564. node.params.forEach(p => estreeWalker.walk(p, {
  2565. enter(child, parent) {
  2566. if (child.type === 'Identifier' &&
  2567. // do not record as scope variable if is a destructured key
  2568. !isStaticPropertyKey(child, parent) &&
  2569. // do not record if this is a default value
  2570. // assignment of a destructured variable
  2571. !(parent &&
  2572. parent.type === 'AssignmentPattern' &&
  2573. parent.right === child)) {
  2574. const { name } = child;
  2575. if (node.scopeIds && node.scopeIds.has(name)) {
  2576. return;
  2577. }
  2578. if (name in knownIds) {
  2579. knownIds[name]++;
  2580. }
  2581. else {
  2582. knownIds[name] = 1;
  2583. }
  2584. (node.scopeIds || (node.scopeIds = new Set())).add(name);
  2585. }
  2586. }
  2587. }));
  2588. }
  2589. },
  2590. leave(node) {
  2591. if (node !== ast.body[0].expression && node.scopeIds) {
  2592. node.scopeIds.forEach((id) => {
  2593. knownIds[id]--;
  2594. if (knownIds[id] === 0) {
  2595. delete knownIds[id];
  2596. }
  2597. });
  2598. }
  2599. }
  2600. });
  2601. // We break up the compound expression into an array of strings and sub
  2602. // expressions (for identifiers that have been prefixed). In codegen, if
  2603. // an ExpressionNode has the `.children` property, it will be used instead of
  2604. // `.content`.
  2605. const children = [];
  2606. ids.sort((a, b) => a.start - b.start);
  2607. ids.forEach((id, i) => {
  2608. // range is offset by -1 due to the wrapping parens when parsed
  2609. const start = id.start - 1;
  2610. const end = id.end - 1;
  2611. const last = ids[i - 1];
  2612. const leadingText = rawExp.slice(last ? last.end - 1 : 0, start);
  2613. if (leadingText.length || id.prefix) {
  2614. children.push(leadingText + (id.prefix || ``));
  2615. }
  2616. const source = rawExp.slice(start, end);
  2617. children.push(createSimpleExpression(id.name, false, {
  2618. source,
  2619. start: advancePositionWithClone(node.loc.start, source, start),
  2620. end: advancePositionWithClone(node.loc.start, source, end)
  2621. }, id.isConstant /* isConstant */));
  2622. if (i === ids.length - 1 && end < rawExp.length) {
  2623. children.push(rawExp.slice(end));
  2624. }
  2625. });
  2626. let ret;
  2627. if (children.length) {
  2628. ret = createCompoundExpression(children, node.loc);
  2629. }
  2630. else {
  2631. ret = node;
  2632. ret.isConstant = !bailConstant;
  2633. }
  2634. ret.identifiers = Object.keys(knownIds);
  2635. return ret;
  2636. }
  2637. const isFunction = (node) => {
  2638. return /Function(?:Expression|Declaration)$|Method$/.test(node.type);
  2639. };
  2640. const isStaticProperty = (node) => node &&
  2641. (node.type === 'ObjectProperty' || node.type === 'ObjectMethod') &&
  2642. !node.computed;
  2643. const isPropertyShorthand = (node, parent) => {
  2644. return (isStaticProperty(parent) &&
  2645. parent.value === node &&
  2646. parent.key.type === 'Identifier' &&
  2647. parent.key.name === node.name &&
  2648. parent.key.start === node.start);
  2649. };
  2650. const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node;
  2651. function shouldPrefix(identifier, parent) {
  2652. if (!(isFunction(parent) &&
  2653. // not id of a FunctionDeclaration
  2654. (parent.id === identifier ||
  2655. // not a params of a function
  2656. parent.params.includes(identifier))) &&
  2657. // not a key of Property
  2658. !isStaticPropertyKey(identifier, parent) &&
  2659. // not a property of a MemberExpression
  2660. !((parent.type === 'MemberExpression' ||
  2661. parent.type === 'OptionalMemberExpression') &&
  2662. parent.property === identifier &&
  2663. !parent.computed) &&
  2664. // not in an Array destructure pattern
  2665. !(parent.type === 'ArrayPattern') &&
  2666. // skip whitelisted globals
  2667. !shared.isGloballyWhitelisted(identifier.name) &&
  2668. // special case for webpack compilation
  2669. identifier.name !== `require` &&
  2670. // is a special keyword but parsed as identifier
  2671. identifier.name !== `arguments`) {
  2672. return true;
  2673. }
  2674. }
  2675. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  2676. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  2677. // #1587: We need to dynamically increment the key based on the current
  2678. // node's sibling nodes, since chained v-if/else branches are
  2679. // rendered at the same depth
  2680. const siblings = context.parent.children;
  2681. let i = siblings.indexOf(ifNode);
  2682. let key = 0;
  2683. while (i-- >= 0) {
  2684. const sibling = siblings[i];
  2685. if (sibling && sibling.type === 9 /* IF */) {
  2686. key += sibling.branches.length;
  2687. }
  2688. }
  2689. // Exit callback. Complete the codegenNode when all children have been
  2690. // transformed.
  2691. return () => {
  2692. if (isRoot) {
  2693. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  2694. }
  2695. else {
  2696. // attach this branch's codegen node to the v-if root.
  2697. const parentCondition = getParentCondition(ifNode.codegenNode);
  2698. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  2699. }
  2700. };
  2701. });
  2702. });
  2703. // target-agnostic transform used for both Client and SSR
  2704. function processIf(node, dir, context, processCodegen) {
  2705. if (dir.name !== 'else' &&
  2706. (!dir.exp || !dir.exp.content.trim())) {
  2707. const loc = dir.exp ? dir.exp.loc : node.loc;
  2708. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  2709. dir.exp = createSimpleExpression(`true`, false, loc);
  2710. }
  2711. if ( context.prefixIdentifiers && dir.exp) {
  2712. // dir.exp can only be simple expression because vIf transform is applied
  2713. // before expression transform.
  2714. dir.exp = processExpression(dir.exp, context);
  2715. }
  2716. if (dir.name === 'if') {
  2717. const branch = createIfBranch(node, dir);
  2718. const ifNode = {
  2719. type: 9 /* IF */,
  2720. loc: node.loc,
  2721. branches: [branch]
  2722. };
  2723. context.replaceNode(ifNode);
  2724. if (processCodegen) {
  2725. return processCodegen(ifNode, branch, true);
  2726. }
  2727. }
  2728. else {
  2729. // locate the adjacent v-if
  2730. const siblings = context.parent.children;
  2731. const comments = [];
  2732. let i = siblings.indexOf(node);
  2733. while (i-- >= -1) {
  2734. const sibling = siblings[i];
  2735. if ( sibling && sibling.type === 3 /* COMMENT */) {
  2736. context.removeNode(sibling);
  2737. comments.unshift(sibling);
  2738. continue;
  2739. }
  2740. if (sibling &&
  2741. sibling.type === 2 /* TEXT */ &&
  2742. !sibling.content.trim().length) {
  2743. context.removeNode(sibling);
  2744. continue;
  2745. }
  2746. if (sibling && sibling.type === 9 /* IF */) {
  2747. // move the node to the if node's branches
  2748. context.removeNode();
  2749. const branch = createIfBranch(node, dir);
  2750. if ( comments.length) {
  2751. branch.children = [...comments, ...branch.children];
  2752. }
  2753. // check if user is forcing same key on different branches
  2754. {
  2755. const key = branch.userKey;
  2756. if (key) {
  2757. sibling.branches.forEach(({ userKey }) => {
  2758. if (isSameKey(userKey, key)) {
  2759. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  2760. }
  2761. });
  2762. }
  2763. }
  2764. sibling.branches.push(branch);
  2765. const onExit = processCodegen && processCodegen(sibling, branch, false);
  2766. // since the branch was removed, it will not be traversed.
  2767. // make sure to traverse here.
  2768. traverseNode(branch, context);
  2769. // call on exit
  2770. if (onExit)
  2771. onExit();
  2772. // make sure to reset currentNode after traversal to indicate this
  2773. // node has been removed.
  2774. context.currentNode = null;
  2775. }
  2776. else {
  2777. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  2778. }
  2779. break;
  2780. }
  2781. }
  2782. }
  2783. function createIfBranch(node, dir) {
  2784. return {
  2785. type: 10 /* IF_BRANCH */,
  2786. loc: node.loc,
  2787. condition: dir.name === 'else' ? undefined : dir.exp,
  2788. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  2789. ? node.children
  2790. : [node],
  2791. userKey: findProp(node, `key`)
  2792. };
  2793. }
  2794. function createCodegenNodeForBranch(branch, keyIndex, context) {
  2795. if (branch.condition) {
  2796. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  2797. // make sure to pass in asBlock: true so that the comment node call
  2798. // closes the current block.
  2799. createCallExpression(context.helper(CREATE_COMMENT), [
  2800. '"v-if"' ,
  2801. 'true'
  2802. ]));
  2803. }
  2804. else {
  2805. return createChildrenCodegenNode(branch, keyIndex, context);
  2806. }
  2807. }
  2808. function createChildrenCodegenNode(branch, keyIndex, context) {
  2809. const { helper } = context;
  2810. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, true));
  2811. const { children } = branch;
  2812. const firstChild = children[0];
  2813. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  2814. if (needFragmentWrapper) {
  2815. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  2816. // optimize away nested fragments when child is a ForNode
  2817. const vnodeCall = firstChild.codegenNode;
  2818. injectProp(vnodeCall, keyProperty, context);
  2819. return vnodeCall;
  2820. }
  2821. else {
  2822. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, `${64 /* STABLE_FRAGMENT */} /* ${shared.PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true, false, branch.loc);
  2823. }
  2824. }
  2825. else {
  2826. const vnodeCall = firstChild
  2827. .codegenNode;
  2828. // Change createVNode to createBlock.
  2829. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  2830. vnodeCall.isBlock = true;
  2831. helper(OPEN_BLOCK);
  2832. helper(CREATE_BLOCK);
  2833. }
  2834. // inject branch key
  2835. injectProp(vnodeCall, keyProperty, context);
  2836. return vnodeCall;
  2837. }
  2838. }
  2839. function isSameKey(a, b) {
  2840. if (!a || a.type !== b.type) {
  2841. return false;
  2842. }
  2843. if (a.type === 6 /* ATTRIBUTE */) {
  2844. if (a.value.content !== b.value.content) {
  2845. return false;
  2846. }
  2847. }
  2848. else {
  2849. // directive
  2850. const exp = a.exp;
  2851. const branchExp = b.exp;
  2852. if (exp.type !== branchExp.type) {
  2853. return false;
  2854. }
  2855. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  2856. (exp.isStatic !== branchExp.isStatic ||
  2857. exp.content !== branchExp.content)) {
  2858. return false;
  2859. }
  2860. }
  2861. return true;
  2862. }
  2863. function getParentCondition(node) {
  2864. while (true) {
  2865. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2866. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  2867. node = node.alternate;
  2868. }
  2869. else {
  2870. return node;
  2871. }
  2872. }
  2873. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  2874. node = node.value;
  2875. }
  2876. }
  2877. }
  2878. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  2879. const { helper } = context;
  2880. return processFor(node, dir, context, forNode => {
  2881. // create the loop render function expression now, and add the
  2882. // iterator on exit after all children have been traversed
  2883. const renderExp = createCallExpression(helper(RENDER_LIST), [
  2884. forNode.source
  2885. ]);
  2886. const keyProp = findProp(node, `key`);
  2887. const keyProperty = keyProp
  2888. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  2889. ? createSimpleExpression(keyProp.value.content, true)
  2890. : keyProp.exp)
  2891. : null;
  2892. if ( context.prefixIdentifiers && keyProperty) {
  2893. // #2085 process :key expression needs to be processed in order for it
  2894. // to behave consistently for <template v-for> and <div v-for>.
  2895. // In the case of `<template v-for>`, the node is discarded and never
  2896. // traversed so its key expression won't be processed by the normal
  2897. // transforms.
  2898. keyProperty.value = processExpression(keyProperty.value, context);
  2899. }
  2900. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  2901. forNode.source.isConstant;
  2902. const fragmentFlag = isStableFragment
  2903. ? 64 /* STABLE_FRAGMENT */
  2904. : keyProp
  2905. ? 128 /* KEYED_FRAGMENT */
  2906. : 256 /* UNKEYED_FRAGMENT */;
  2907. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${shared.PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  2908. return () => {
  2909. // finish the codegen now that all children have been traversed
  2910. let childBlock;
  2911. const isTemplate = isTemplateNode(node);
  2912. const { children } = forNode;
  2913. // check <template v-for> key placement
  2914. if ( isTemplate) {
  2915. node.children.some(c => {
  2916. if (c.type === 1 /* ELEMENT */) {
  2917. const key = findProp(c, 'key');
  2918. if (key) {
  2919. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  2920. return true;
  2921. }
  2922. }
  2923. });
  2924. }
  2925. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  2926. const slotOutlet = isSlotOutlet(node)
  2927. ? node
  2928. : isTemplate &&
  2929. node.children.length === 1 &&
  2930. isSlotOutlet(node.children[0])
  2931. ? node.children[0] // api-extractor somehow fails to infer this
  2932. : null;
  2933. if (slotOutlet) {
  2934. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  2935. childBlock = slotOutlet.codegenNode;
  2936. if (isTemplate && keyProperty) {
  2937. // <template v-for="..." :key="..."><slot/></template>
  2938. // we need to inject the key to the renderSlot() call.
  2939. // the props for renderSlot is passed as the 3rd argument.
  2940. injectProp(childBlock, keyProperty, context);
  2941. }
  2942. }
  2943. else if (needFragmentWrapper) {
  2944. // <template v-for="..."> with text or multi-elements
  2945. // should generate a fragment block for each loop
  2946. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${64 /* STABLE_FRAGMENT */} /* ${shared.PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  2947. }
  2948. else {
  2949. // Normal element v-for. Directly use the child's codegenNode
  2950. // but mark it as a block.
  2951. childBlock = children[0]
  2952. .codegenNode;
  2953. if (isTemplate && keyProperty) {
  2954. injectProp(childBlock, keyProperty, context);
  2955. }
  2956. childBlock.isBlock = !isStableFragment;
  2957. if (childBlock.isBlock) {
  2958. helper(OPEN_BLOCK);
  2959. helper(CREATE_BLOCK);
  2960. }
  2961. }
  2962. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  2963. };
  2964. });
  2965. });
  2966. // target-agnostic transform used for both Client and SSR
  2967. function processFor(node, dir, context, processCodegen) {
  2968. if (!dir.exp) {
  2969. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  2970. return;
  2971. }
  2972. const parseResult = parseForExpression(
  2973. // can only be simple expression because vFor transform is applied
  2974. // before expression transform.
  2975. dir.exp, context);
  2976. if (!parseResult) {
  2977. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  2978. return;
  2979. }
  2980. const { addIdentifiers, removeIdentifiers, scopes } = context;
  2981. const { source, value, key, index } = parseResult;
  2982. const forNode = {
  2983. type: 11 /* FOR */,
  2984. loc: dir.loc,
  2985. source,
  2986. valueAlias: value,
  2987. keyAlias: key,
  2988. objectIndexAlias: index,
  2989. parseResult,
  2990. children: isTemplateNode(node) ? node.children : [node]
  2991. };
  2992. context.replaceNode(forNode);
  2993. // bookkeeping
  2994. scopes.vFor++;
  2995. if ( context.prefixIdentifiers) {
  2996. // scope management
  2997. // inject identifiers to context
  2998. value && addIdentifiers(value);
  2999. key && addIdentifiers(key);
  3000. index && addIdentifiers(index);
  3001. }
  3002. const onExit = processCodegen && processCodegen(forNode);
  3003. return () => {
  3004. scopes.vFor--;
  3005. if ( context.prefixIdentifiers) {
  3006. value && removeIdentifiers(value);
  3007. key && removeIdentifiers(key);
  3008. index && removeIdentifiers(index);
  3009. }
  3010. if (onExit)
  3011. onExit();
  3012. };
  3013. }
  3014. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  3015. // This regex doesn't cover the case if key or index aliases have destructuring,
  3016. // but those do not make sense in the first place, so this works in practice.
  3017. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  3018. const stripParensRE = /^\(|\)$/g;
  3019. function parseForExpression(input, context) {
  3020. const loc = input.loc;
  3021. const exp = input.content;
  3022. const inMatch = exp.match(forAliasRE);
  3023. if (!inMatch)
  3024. return;
  3025. const [, LHS, RHS] = inMatch;
  3026. const result = {
  3027. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  3028. value: undefined,
  3029. key: undefined,
  3030. index: undefined
  3031. };
  3032. if ( context.prefixIdentifiers) {
  3033. result.source = processExpression(result.source, context);
  3034. }
  3035. let valueContent = LHS.trim()
  3036. .replace(stripParensRE, '')
  3037. .trim();
  3038. const trimmedOffset = LHS.indexOf(valueContent);
  3039. const iteratorMatch = valueContent.match(forIteratorRE);
  3040. if (iteratorMatch) {
  3041. valueContent = valueContent.replace(forIteratorRE, '').trim();
  3042. const keyContent = iteratorMatch[1].trim();
  3043. let keyOffset;
  3044. if (keyContent) {
  3045. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  3046. result.key = createAliasExpression(loc, keyContent, keyOffset);
  3047. if ( context.prefixIdentifiers) {
  3048. result.key = processExpression(result.key, context, true);
  3049. }
  3050. }
  3051. if (iteratorMatch[2]) {
  3052. const indexContent = iteratorMatch[2].trim();
  3053. if (indexContent) {
  3054. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  3055. ? keyOffset + keyContent.length
  3056. : trimmedOffset + valueContent.length));
  3057. if ( context.prefixIdentifiers) {
  3058. result.index = processExpression(result.index, context, true);
  3059. }
  3060. }
  3061. }
  3062. }
  3063. if (valueContent) {
  3064. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  3065. if ( context.prefixIdentifiers) {
  3066. result.value = processExpression(result.value, context, true);
  3067. }
  3068. }
  3069. return result;
  3070. }
  3071. function createAliasExpression(range, content, offset) {
  3072. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  3073. }
  3074. function createForLoopParams({ value, key, index }) {
  3075. const params = [];
  3076. if (value) {
  3077. params.push(value);
  3078. }
  3079. if (key) {
  3080. if (!value) {
  3081. params.push(createSimpleExpression(`_`, false));
  3082. }
  3083. params.push(key);
  3084. }
  3085. if (index) {
  3086. if (!key) {
  3087. if (!value) {
  3088. params.push(createSimpleExpression(`_`, false));
  3089. }
  3090. params.push(createSimpleExpression(`__`, false));
  3091. }
  3092. params.push(index);
  3093. }
  3094. return params;
  3095. }
  3096. const defaultFallback = createSimpleExpression(`undefined`, false);
  3097. // A NodeTransform that:
  3098. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  3099. // by transformExpression. This is only applied in non-browser builds with
  3100. // { prefixIdentifiers: true }.
  3101. // 2. Track v-slot depths so that we know a slot is inside another slot.
  3102. // Note the exit callback is executed before buildSlots() on the same node,
  3103. // so only nested slots see positive numbers.
  3104. const trackSlotScopes = (node, context) => {
  3105. if (node.type === 1 /* ELEMENT */ &&
  3106. (node.tagType === 1 /* COMPONENT */ ||
  3107. node.tagType === 3 /* TEMPLATE */)) {
  3108. // We are only checking non-empty v-slot here
  3109. // since we only care about slots that introduce scope variables.
  3110. const vSlot = findDir(node, 'slot');
  3111. if (vSlot) {
  3112. const slotProps = vSlot.exp;
  3113. if ( context.prefixIdentifiers) {
  3114. slotProps && context.addIdentifiers(slotProps);
  3115. }
  3116. context.scopes.vSlot++;
  3117. return () => {
  3118. if ( context.prefixIdentifiers) {
  3119. slotProps && context.removeIdentifiers(slotProps);
  3120. }
  3121. context.scopes.vSlot--;
  3122. };
  3123. }
  3124. }
  3125. };
  3126. // A NodeTransform that tracks scope identifiers for scoped slots with v-for.
  3127. // This transform is only applied in non-browser builds with { prefixIdentifiers: true }
  3128. const trackVForSlotScopes = (node, context) => {
  3129. let vFor;
  3130. if (isTemplateNode(node) &&
  3131. node.props.some(isVSlot) &&
  3132. (vFor = findDir(node, 'for'))) {
  3133. const result = (vFor.parseResult = parseForExpression(vFor.exp, context));
  3134. if (result) {
  3135. const { value, key, index } = result;
  3136. const { addIdentifiers, removeIdentifiers } = context;
  3137. value && addIdentifiers(value);
  3138. key && addIdentifiers(key);
  3139. index && addIdentifiers(index);
  3140. return () => {
  3141. value && removeIdentifiers(value);
  3142. key && removeIdentifiers(key);
  3143. index && removeIdentifiers(index);
  3144. };
  3145. }
  3146. }
  3147. };
  3148. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  3149. // Instead of being a DirectiveTransform, v-slot processing is called during
  3150. // transformElement to build the slots object for a component.
  3151. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  3152. context.helper(WITH_CTX);
  3153. const { children, loc } = node;
  3154. const slotsProperties = [];
  3155. const dynamicSlots = [];
  3156. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  3157. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  3158. // since it likely uses a scope variable.
  3159. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  3160. // with `prefixIdentifiers: true`, this can be further optimized to make
  3161. // it dynamic only when the slot actually uses the scope variables.
  3162. if ( !context.ssr && context.prefixIdentifiers) {
  3163. hasDynamicSlots = hasScopeRef(node, context.identifiers);
  3164. }
  3165. // 1. Check for slot with slotProps on component itself.
  3166. // <Comp v-slot="{ prop }"/>
  3167. const onComponentSlot = findDir(node, 'slot', true);
  3168. if (onComponentSlot) {
  3169. const { arg, exp } = onComponentSlot;
  3170. if (arg && !isStaticExp(arg)) {
  3171. hasDynamicSlots = true;
  3172. }
  3173. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  3174. }
  3175. // 2. Iterate through children and check for template slots
  3176. // <template v-slot:foo="{ prop }">
  3177. let hasTemplateSlots = false;
  3178. let hasNamedDefaultSlot = false;
  3179. const implicitDefaultChildren = [];
  3180. const seenSlotNames = new Set();
  3181. for (let i = 0; i < children.length; i++) {
  3182. const slotElement = children[i];
  3183. let slotDir;
  3184. if (!isTemplateNode(slotElement) ||
  3185. !(slotDir = findDir(slotElement, 'slot', true))) {
  3186. // not a <template v-slot>, skip.
  3187. if (slotElement.type !== 3 /* COMMENT */) {
  3188. implicitDefaultChildren.push(slotElement);
  3189. }
  3190. continue;
  3191. }
  3192. if (onComponentSlot) {
  3193. // already has on-component slot - this is incorrect usage.
  3194. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  3195. break;
  3196. }
  3197. hasTemplateSlots = true;
  3198. const { children: slotChildren, loc: slotLoc } = slotElement;
  3199. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  3200. // check if name is dynamic.
  3201. let staticSlotName;
  3202. if (isStaticExp(slotName)) {
  3203. staticSlotName = slotName ? slotName.content : `default`;
  3204. }
  3205. else {
  3206. hasDynamicSlots = true;
  3207. }
  3208. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  3209. // check if this slot is conditional (v-if/v-for)
  3210. let vIf;
  3211. let vElse;
  3212. let vFor;
  3213. if ((vIf = findDir(slotElement, 'if'))) {
  3214. hasDynamicSlots = true;
  3215. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  3216. }
  3217. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  3218. // find adjacent v-if
  3219. let j = i;
  3220. let prev;
  3221. while (j--) {
  3222. prev = children[j];
  3223. if (prev.type !== 3 /* COMMENT */) {
  3224. break;
  3225. }
  3226. }
  3227. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  3228. // remove node
  3229. children.splice(i, 1);
  3230. i--;
  3231. // attach this slot to previous conditional
  3232. let conditional = dynamicSlots[dynamicSlots.length - 1];
  3233. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  3234. conditional = conditional.alternate;
  3235. }
  3236. conditional.alternate = vElse.exp
  3237. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  3238. : buildDynamicSlot(slotName, slotFunction);
  3239. }
  3240. else {
  3241. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  3242. }
  3243. }
  3244. else if ((vFor = findDir(slotElement, 'for'))) {
  3245. hasDynamicSlots = true;
  3246. const parseResult = vFor.parseResult ||
  3247. parseForExpression(vFor.exp, context);
  3248. if (parseResult) {
  3249. // Render the dynamic slots as an array and add it to the createSlot()
  3250. // args. The runtime knows how to handle it appropriately.
  3251. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  3252. parseResult.source,
  3253. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  3254. ]));
  3255. }
  3256. else {
  3257. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  3258. }
  3259. }
  3260. else {
  3261. // check duplicate static names
  3262. if (staticSlotName) {
  3263. if (seenSlotNames.has(staticSlotName)) {
  3264. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  3265. continue;
  3266. }
  3267. seenSlotNames.add(staticSlotName);
  3268. if (staticSlotName === 'default') {
  3269. hasNamedDefaultSlot = true;
  3270. }
  3271. }
  3272. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  3273. }
  3274. }
  3275. if (!onComponentSlot) {
  3276. if (!hasTemplateSlots) {
  3277. // implicit default slot (on component)
  3278. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  3279. }
  3280. else if (implicitDefaultChildren.length) {
  3281. // implicit default slot (mixed with named slots)
  3282. if (hasNamedDefaultSlot) {
  3283. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  3284. }
  3285. else {
  3286. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  3287. }
  3288. }
  3289. }
  3290. const slotFlag = hasDynamicSlots
  3291. ? 2 /* DYNAMIC */
  3292. : hasForwardedSlots(node.children)
  3293. ? 3 /* FORWARDED */
  3294. : 1 /* STABLE */;
  3295. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  3296. // 2 = compiled but dynamic = can skip normalization, but must run diff
  3297. // 1 = compiled and static = can skip normalization AND diff as optimized
  3298. createSimpleExpression('' + slotFlag, false))), loc);
  3299. if (dynamicSlots.length) {
  3300. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  3301. slots,
  3302. createArrayExpression(dynamicSlots)
  3303. ]);
  3304. }
  3305. return {
  3306. slots,
  3307. hasDynamicSlots
  3308. };
  3309. }
  3310. function buildDynamicSlot(name, fn) {
  3311. return createObjectExpression([
  3312. createObjectProperty(`name`, name),
  3313. createObjectProperty(`fn`, fn)
  3314. ]);
  3315. }
  3316. function hasForwardedSlots(children) {
  3317. for (let i = 0; i < children.length; i++) {
  3318. const child = children[i];
  3319. if (child.type === 1 /* ELEMENT */) {
  3320. if (child.tagType === 2 /* SLOT */ ||
  3321. (child.tagType === 0 /* ELEMENT */ &&
  3322. hasForwardedSlots(child.children))) {
  3323. return true;
  3324. }
  3325. }
  3326. }
  3327. return false;
  3328. }
  3329. // some directive transforms (e.g. v-model) may return a symbol for runtime
  3330. // import, which should be used instead of a resolveDirective call.
  3331. const directiveImportMap = new WeakMap();
  3332. // generate a JavaScript AST for this element's codegen
  3333. const transformElement = (node, context) => {
  3334. if (!(node.type === 1 /* ELEMENT */ &&
  3335. (node.tagType === 0 /* ELEMENT */ ||
  3336. node.tagType === 1 /* COMPONENT */))) {
  3337. return;
  3338. }
  3339. // perform the work on exit, after all child expressions have been
  3340. // processed and merged.
  3341. return function postTransformElement() {
  3342. const { tag, props } = node;
  3343. const isComponent = node.tagType === 1 /* COMPONENT */;
  3344. // The goal of the transform is to create a codegenNode implementing the
  3345. // VNodeCall interface.
  3346. const vnodeTag = isComponent
  3347. ? resolveComponentType(node, context)
  3348. : `"${tag}"`;
  3349. const isDynamicComponent = shared.isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  3350. let vnodeProps;
  3351. let vnodeChildren;
  3352. let vnodePatchFlag;
  3353. let patchFlag = 0;
  3354. let vnodeDynamicProps;
  3355. let dynamicPropNames;
  3356. let vnodeDirectives;
  3357. let shouldUseBlock =
  3358. // dynamic component may resolve to plain elements
  3359. isDynamicComponent ||
  3360. vnodeTag === TELEPORT ||
  3361. vnodeTag === SUSPENSE ||
  3362. (!isComponent &&
  3363. // <svg> and <foreignObject> must be forced into blocks so that block
  3364. // updates inside get proper isSVG flag at runtime. (#639, #643)
  3365. // This is technically web-specific, but splitting the logic out of core
  3366. // leads to too much unnecessary complexity.
  3367. (tag === 'svg' ||
  3368. tag === 'foreignObject' ||
  3369. // #938: elements with dynamic keys should be forced into blocks
  3370. findProp(node, 'key', true)));
  3371. // props
  3372. if (props.length > 0) {
  3373. const propsBuildResult = buildProps(node, context);
  3374. vnodeProps = propsBuildResult.props;
  3375. patchFlag = propsBuildResult.patchFlag;
  3376. dynamicPropNames = propsBuildResult.dynamicPropNames;
  3377. const directives = propsBuildResult.directives;
  3378. vnodeDirectives =
  3379. directives && directives.length
  3380. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  3381. : undefined;
  3382. }
  3383. // children
  3384. if (node.children.length > 0) {
  3385. if (vnodeTag === KEEP_ALIVE) {
  3386. // Although a built-in component, we compile KeepAlive with raw children
  3387. // instead of slot functions so that it can be used inside Transition
  3388. // or other Transition-wrapping HOCs.
  3389. // To ensure correct updates with block optimizations, we need to:
  3390. // 1. Force keep-alive into a block. This avoids its children being
  3391. // collected by a parent block.
  3392. shouldUseBlock = true;
  3393. // 2. Force keep-alive to always be updated, since it uses raw children.
  3394. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3395. if ( node.children.length > 1) {
  3396. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  3397. start: node.children[0].loc.start,
  3398. end: node.children[node.children.length - 1].loc.end,
  3399. source: ''
  3400. }));
  3401. }
  3402. }
  3403. const shouldBuildAsSlots = isComponent &&
  3404. // Teleport is not a real component and has dedicated runtime handling
  3405. vnodeTag !== TELEPORT &&
  3406. // explained above.
  3407. vnodeTag !== KEEP_ALIVE;
  3408. if (shouldBuildAsSlots) {
  3409. const { slots, hasDynamicSlots } = buildSlots(node, context);
  3410. vnodeChildren = slots;
  3411. if (hasDynamicSlots) {
  3412. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  3413. }
  3414. }
  3415. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  3416. const child = node.children[0];
  3417. const type = child.type;
  3418. // check for dynamic text children
  3419. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  3420. type === 8 /* COMPOUND_EXPRESSION */;
  3421. if (hasDynamicTextChild && !getStaticType(child)) {
  3422. patchFlag |= 1 /* TEXT */;
  3423. }
  3424. // pass directly if the only child is a text node
  3425. // (plain / interpolation / expression)
  3426. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  3427. vnodeChildren = child;
  3428. }
  3429. else {
  3430. vnodeChildren = node.children;
  3431. }
  3432. }
  3433. else {
  3434. vnodeChildren = node.children;
  3435. }
  3436. }
  3437. // patchFlag & dynamicPropNames
  3438. if (patchFlag !== 0) {
  3439. {
  3440. if (patchFlag < 0) {
  3441. // special flags (negative and mutually exclusive)
  3442. vnodePatchFlag = patchFlag + ` /* ${shared.PatchFlagNames[patchFlag]} */`;
  3443. }
  3444. else {
  3445. // bitwise flags
  3446. const flagNames = Object.keys(shared.PatchFlagNames)
  3447. .map(Number)
  3448. .filter(n => n > 0 && patchFlag & n)
  3449. .map(n => shared.PatchFlagNames[n])
  3450. .join(`, `);
  3451. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  3452. }
  3453. }
  3454. if (dynamicPropNames && dynamicPropNames.length) {
  3455. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  3456. }
  3457. }
  3458. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  3459. };
  3460. };
  3461. function resolveComponentType(node, context, ssr = false) {
  3462. const { tag } = node;
  3463. // 1. dynamic component
  3464. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  3465. if (isProp) {
  3466. const exp = isProp.type === 6 /* ATTRIBUTE */
  3467. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  3468. : isProp.exp;
  3469. if (exp) {
  3470. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  3471. exp
  3472. ]);
  3473. }
  3474. }
  3475. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  3476. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  3477. if (builtIn) {
  3478. // built-ins are simply fallthroughs / have special handling during ssr
  3479. // no we don't need to import their runtime equivalents
  3480. if (!ssr)
  3481. context.helper(builtIn);
  3482. return builtIn;
  3483. }
  3484. // 3. user component (from setup bindings)
  3485. if (context.bindingMetadata[tag] === 'setup') {
  3486. return `$setup[${JSON.stringify(tag)}]`;
  3487. }
  3488. // 4. user component (resolve)
  3489. context.helper(RESOLVE_COMPONENT);
  3490. context.components.add(tag);
  3491. return toValidAssetId(tag, `component`);
  3492. }
  3493. function buildProps(node, context, props = node.props, ssr = false) {
  3494. const { tag, loc: elementLoc } = node;
  3495. const isComponent = node.tagType === 1 /* COMPONENT */;
  3496. let properties = [];
  3497. const mergeArgs = [];
  3498. const runtimeDirectives = [];
  3499. // patchFlag analysis
  3500. let patchFlag = 0;
  3501. let hasRef = false;
  3502. let hasClassBinding = false;
  3503. let hasStyleBinding = false;
  3504. let hasHydrationEventBinding = false;
  3505. let hasDynamicKeys = false;
  3506. let hasVnodeHook = false;
  3507. const dynamicPropNames = [];
  3508. const analyzePatchFlag = ({ key, value }) => {
  3509. if (isStaticExp(key)) {
  3510. const name = key.content;
  3511. const isEventHandler = shared.isOn(name);
  3512. if (!isComponent &&
  3513. isEventHandler &&
  3514. // omit the flag for click handlers because hydration gives click
  3515. // dedicated fast path.
  3516. name.toLowerCase() !== 'onclick' &&
  3517. // omit v-model handlers
  3518. name !== 'onUpdate:modelValue' &&
  3519. // omit onVnodeXXX hooks
  3520. !shared.isReservedProp(name)) {
  3521. hasHydrationEventBinding = true;
  3522. }
  3523. if (isEventHandler && shared.isReservedProp(name)) {
  3524. hasVnodeHook = true;
  3525. }
  3526. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  3527. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  3528. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  3529. getStaticType(value) > 0)) {
  3530. // skip if the prop is a cached handler or has constant value
  3531. return;
  3532. }
  3533. if (name === 'ref') {
  3534. hasRef = true;
  3535. }
  3536. else if (name === 'class' && !isComponent) {
  3537. hasClassBinding = true;
  3538. }
  3539. else if (name === 'style' && !isComponent) {
  3540. hasStyleBinding = true;
  3541. }
  3542. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  3543. dynamicPropNames.push(name);
  3544. }
  3545. }
  3546. else {
  3547. hasDynamicKeys = true;
  3548. }
  3549. };
  3550. for (let i = 0; i < props.length; i++) {
  3551. // static attribute
  3552. const prop = props[i];
  3553. if (prop.type === 6 /* ATTRIBUTE */) {
  3554. const { loc, name, value } = prop;
  3555. if (name === 'ref') {
  3556. hasRef = true;
  3557. }
  3558. // skip :is on <component>
  3559. if (name === 'is' && tag === 'component') {
  3560. continue;
  3561. }
  3562. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc)));
  3563. }
  3564. else {
  3565. // directives
  3566. const { name, arg, exp, loc } = prop;
  3567. const isBind = name === 'bind';
  3568. const isOn = name === 'on';
  3569. // skip v-slot - it is handled by its dedicated transform.
  3570. if (name === 'slot') {
  3571. if (!isComponent) {
  3572. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  3573. }
  3574. continue;
  3575. }
  3576. // skip v-once - it is handled by its dedicated transform.
  3577. if (name === 'once') {
  3578. continue;
  3579. }
  3580. // skip v-is and :is on <component>
  3581. if (name === 'is' ||
  3582. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  3583. continue;
  3584. }
  3585. // skip v-on in SSR compilation
  3586. if (isOn && ssr) {
  3587. continue;
  3588. }
  3589. // special case for v-bind and v-on with no argument
  3590. if (!arg && (isBind || isOn)) {
  3591. hasDynamicKeys = true;
  3592. if (exp) {
  3593. if (properties.length) {
  3594. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3595. properties = [];
  3596. }
  3597. if (isBind) {
  3598. mergeArgs.push(exp);
  3599. }
  3600. else {
  3601. // v-on="obj" -> toHandlers(obj)
  3602. mergeArgs.push({
  3603. type: 14 /* JS_CALL_EXPRESSION */,
  3604. loc,
  3605. callee: context.helper(TO_HANDLERS),
  3606. arguments: [exp]
  3607. });
  3608. }
  3609. }
  3610. else {
  3611. context.onError(createCompilerError(isBind
  3612. ? 33 /* X_V_BIND_NO_EXPRESSION */
  3613. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  3614. }
  3615. continue;
  3616. }
  3617. const directiveTransform = context.directiveTransforms[name];
  3618. if (directiveTransform) {
  3619. // has built-in directive transform.
  3620. const { props, needRuntime } = directiveTransform(prop, node, context);
  3621. !ssr && props.forEach(analyzePatchFlag);
  3622. properties.push(...props);
  3623. if (needRuntime) {
  3624. runtimeDirectives.push(prop);
  3625. if (shared.isSymbol(needRuntime)) {
  3626. directiveImportMap.set(prop, needRuntime);
  3627. }
  3628. }
  3629. }
  3630. else {
  3631. // no built-in transform, this is a user custom directive.
  3632. runtimeDirectives.push(prop);
  3633. }
  3634. }
  3635. }
  3636. let propsExpression = undefined;
  3637. // has v-bind="object" or v-on="object", wrap with mergeProps
  3638. if (mergeArgs.length) {
  3639. if (properties.length) {
  3640. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  3641. }
  3642. if (mergeArgs.length > 1) {
  3643. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  3644. }
  3645. else {
  3646. // single v-bind with nothing else - no need for a mergeProps call
  3647. propsExpression = mergeArgs[0];
  3648. }
  3649. }
  3650. else if (properties.length) {
  3651. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  3652. }
  3653. // patchFlag analysis
  3654. if (hasDynamicKeys) {
  3655. patchFlag |= 16 /* FULL_PROPS */;
  3656. }
  3657. else {
  3658. if (hasClassBinding) {
  3659. patchFlag |= 2 /* CLASS */;
  3660. }
  3661. if (hasStyleBinding) {
  3662. patchFlag |= 4 /* STYLE */;
  3663. }
  3664. if (dynamicPropNames.length) {
  3665. patchFlag |= 8 /* PROPS */;
  3666. }
  3667. if (hasHydrationEventBinding) {
  3668. patchFlag |= 32 /* HYDRATE_EVENTS */;
  3669. }
  3670. }
  3671. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  3672. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  3673. patchFlag |= 512 /* NEED_PATCH */;
  3674. }
  3675. return {
  3676. props: propsExpression,
  3677. directives: runtimeDirectives,
  3678. patchFlag,
  3679. dynamicPropNames
  3680. };
  3681. }
  3682. // Dedupe props in an object literal.
  3683. // Literal duplicated attributes would have been warned during the parse phase,
  3684. // however, it's possible to encounter duplicated `onXXX` handlers with different
  3685. // modifiers. We also need to merge static and dynamic class / style attributes.
  3686. // - onXXX handlers / style: merge into array
  3687. // - class: merge into single expression with concatenation
  3688. function dedupeProperties(properties) {
  3689. const knownProps = new Map();
  3690. const deduped = [];
  3691. for (let i = 0; i < properties.length; i++) {
  3692. const prop = properties[i];
  3693. // dynamic keys are always allowed
  3694. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  3695. deduped.push(prop);
  3696. continue;
  3697. }
  3698. const name = prop.key.content;
  3699. const existing = knownProps.get(name);
  3700. if (existing) {
  3701. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  3702. mergeAsArray(existing, prop);
  3703. }
  3704. // unexpected duplicate, should have emitted error during parse
  3705. }
  3706. else {
  3707. knownProps.set(name, prop);
  3708. deduped.push(prop);
  3709. }
  3710. }
  3711. return deduped;
  3712. }
  3713. function mergeAsArray(existing, incoming) {
  3714. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  3715. existing.value.elements.push(incoming.value);
  3716. }
  3717. else {
  3718. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  3719. }
  3720. }
  3721. function buildDirectiveArgs(dir, context) {
  3722. const dirArgs = [];
  3723. const runtime = directiveImportMap.get(dir);
  3724. if (runtime) {
  3725. dirArgs.push(context.helperString(runtime));
  3726. }
  3727. else {
  3728. // inject statement for resolving directive
  3729. context.helper(RESOLVE_DIRECTIVE);
  3730. context.directives.add(dir.name);
  3731. dirArgs.push(toValidAssetId(dir.name, `directive`));
  3732. }
  3733. const { loc } = dir;
  3734. if (dir.exp)
  3735. dirArgs.push(dir.exp);
  3736. if (dir.arg) {
  3737. if (!dir.exp) {
  3738. dirArgs.push(`void 0`);
  3739. }
  3740. dirArgs.push(dir.arg);
  3741. }
  3742. if (Object.keys(dir.modifiers).length) {
  3743. if (!dir.arg) {
  3744. if (!dir.exp) {
  3745. dirArgs.push(`void 0`);
  3746. }
  3747. dirArgs.push(`void 0`);
  3748. }
  3749. const trueExpression = createSimpleExpression(`true`, false, loc);
  3750. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  3751. }
  3752. return createArrayExpression(dirArgs, dir.loc);
  3753. }
  3754. function stringifyDynamicPropNames(props) {
  3755. let propsNamesString = `[`;
  3756. for (let i = 0, l = props.length; i < l; i++) {
  3757. propsNamesString += JSON.stringify(props[i]);
  3758. if (i < l - 1)
  3759. propsNamesString += ', ';
  3760. }
  3761. return propsNamesString + `]`;
  3762. }
  3763. const transformSlotOutlet = (node, context) => {
  3764. if (isSlotOutlet(node)) {
  3765. const { children, loc } = node;
  3766. const { slotName, slotProps } = processSlotOutlet(node, context);
  3767. const slotArgs = [
  3768. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  3769. slotName
  3770. ];
  3771. if (slotProps) {
  3772. slotArgs.push(slotProps);
  3773. }
  3774. if (children.length) {
  3775. if (!slotProps) {
  3776. slotArgs.push(`{}`);
  3777. }
  3778. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  3779. }
  3780. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  3781. }
  3782. };
  3783. function processSlotOutlet(node, context) {
  3784. let slotName = `"default"`;
  3785. let slotProps = undefined;
  3786. // check for <slot name="xxx" OR :name="xxx" />
  3787. const name = findProp(node, 'name');
  3788. if (name) {
  3789. if (name.type === 6 /* ATTRIBUTE */ && name.value) {
  3790. // static name
  3791. slotName = JSON.stringify(name.value.content);
  3792. }
  3793. else if (name.type === 7 /* DIRECTIVE */ && name.exp) {
  3794. // dynamic name
  3795. slotName = name.exp;
  3796. }
  3797. }
  3798. const propsWithoutName = name
  3799. ? node.props.filter(p => p !== name)
  3800. : node.props;
  3801. if (propsWithoutName.length > 0) {
  3802. const { props, directives } = buildProps(node, context, propsWithoutName);
  3803. slotProps = props;
  3804. if (directives.length) {
  3805. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  3806. }
  3807. }
  3808. return {
  3809. slotName,
  3810. slotProps
  3811. };
  3812. }
  3813. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  3814. const transformOn = (dir, node, context, augmentor) => {
  3815. const { loc, modifiers, arg } = dir;
  3816. if (!dir.exp && !modifiers.length) {
  3817. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  3818. }
  3819. let eventName;
  3820. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3821. if (arg.isStatic) {
  3822. const rawName = arg.content;
  3823. // for all event listeners, auto convert it to camelCase. See issue #2249
  3824. eventName = createSimpleExpression(shared.toHandlerKey(shared.camelize(rawName)), true, arg.loc);
  3825. }
  3826. else {
  3827. // #2388
  3828. eventName = createCompoundExpression([
  3829. `${context.helperString(TO_HANDLER_KEY)}(`,
  3830. arg,
  3831. `)`
  3832. ]);
  3833. }
  3834. }
  3835. else {
  3836. // already a compound expression.
  3837. eventName = arg;
  3838. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  3839. eventName.children.push(`)`);
  3840. }
  3841. // handler processing
  3842. let exp = dir.exp;
  3843. if (exp && !exp.content.trim()) {
  3844. exp = undefined;
  3845. }
  3846. let isCacheable = context.cacheHandlers && !exp;
  3847. if (exp) {
  3848. const isMemberExp = isMemberExpression(exp.content);
  3849. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  3850. const hasMultipleStatements = exp.content.includes(`;`);
  3851. // process the expression since it's been skipped
  3852. if ( context.prefixIdentifiers) {
  3853. isInlineStatement && context.addIdentifiers(`$event`);
  3854. exp = processExpression(exp, context, false, hasMultipleStatements);
  3855. isInlineStatement && context.removeIdentifiers(`$event`);
  3856. // with scope analysis, the function is hoistable if it has no reference
  3857. // to scope variables.
  3858. isCacheable =
  3859. context.cacheHandlers &&
  3860. // #1541 bail if this is a member exp handler passed to a component -
  3861. // we need to use the original function to preserve arity,
  3862. // e.g. <transition> relies on checking cb.length to determine
  3863. // transition end handling. Inline function is ok since its arity
  3864. // is preserved even when cached.
  3865. !(isMemberExp && node.tagType === 1 /* COMPONENT */) &&
  3866. // bail if the function references closure variables (v-for, v-slot)
  3867. // it must be passed fresh to avoid stale values.
  3868. !hasScopeRef(exp, context.identifiers);
  3869. // If the expression is optimizable and is a member expression pointing
  3870. // to a function, turn it into invocation (and wrap in an arrow function
  3871. // below) so that it always accesses the latest value when called - thus
  3872. // avoiding the need to be patched.
  3873. if (isCacheable && isMemberExp) {
  3874. if (exp.type === 4 /* SIMPLE_EXPRESSION */) {
  3875. exp.content += `(...args)`;
  3876. }
  3877. else {
  3878. exp.children.push(`(...args)`);
  3879. }
  3880. }
  3881. }
  3882. if (isInlineStatement || (isCacheable && isMemberExp)) {
  3883. // wrap inline statement in a function expression
  3884. exp = createCompoundExpression([
  3885. `${isInlineStatement ? `$event` : `(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  3886. exp,
  3887. hasMultipleStatements ? `}` : `)`
  3888. ]);
  3889. }
  3890. }
  3891. let ret = {
  3892. props: [
  3893. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  3894. ]
  3895. };
  3896. // apply extended compiler augmentor
  3897. if (augmentor) {
  3898. ret = augmentor(ret);
  3899. }
  3900. if (isCacheable) {
  3901. // cache handlers so that it's always the same handler being passed down.
  3902. // this avoids unnecessary re-renders when users use inline handlers on
  3903. // components.
  3904. ret.props[0].value = context.cache(ret.props[0].value);
  3905. }
  3906. return ret;
  3907. };
  3908. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  3909. // codegen for the entire props object. This transform here is only for v-bind
  3910. // *with* args.
  3911. const transformBind = (dir, node, context) => {
  3912. const { exp, modifiers, loc } = dir;
  3913. const arg = dir.arg;
  3914. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  3915. arg.children.unshift(`(`);
  3916. arg.children.push(`) || ""`);
  3917. }
  3918. else if (!arg.isStatic) {
  3919. arg.content = `${arg.content} || ""`;
  3920. }
  3921. // .prop is no longer necessary due to new patch behavior
  3922. // .sync is replaced by v-model:arg
  3923. if (modifiers.includes('camel')) {
  3924. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  3925. if (arg.isStatic) {
  3926. arg.content = shared.camelize(arg.content);
  3927. }
  3928. else {
  3929. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  3930. }
  3931. }
  3932. else {
  3933. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  3934. arg.children.push(`)`);
  3935. }
  3936. }
  3937. if (!exp ||
  3938. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  3939. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  3940. return {
  3941. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  3942. };
  3943. }
  3944. return {
  3945. props: [createObjectProperty(arg, exp)]
  3946. };
  3947. };
  3948. // Merge adjacent text nodes and expressions into a single expression
  3949. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  3950. const transformText = (node, context) => {
  3951. if (node.type === 0 /* ROOT */ ||
  3952. node.type === 1 /* ELEMENT */ ||
  3953. node.type === 11 /* FOR */ ||
  3954. node.type === 10 /* IF_BRANCH */) {
  3955. // perform the transform on node exit so that all expressions have already
  3956. // been processed.
  3957. return () => {
  3958. const children = node.children;
  3959. let currentContainer = undefined;
  3960. let hasText = false;
  3961. for (let i = 0; i < children.length; i++) {
  3962. const child = children[i];
  3963. if (isText(child)) {
  3964. hasText = true;
  3965. for (let j = i + 1; j < children.length; j++) {
  3966. const next = children[j];
  3967. if (isText(next)) {
  3968. if (!currentContainer) {
  3969. currentContainer = children[i] = {
  3970. type: 8 /* COMPOUND_EXPRESSION */,
  3971. loc: child.loc,
  3972. children: [child]
  3973. };
  3974. }
  3975. // merge adjacent text node into current
  3976. currentContainer.children.push(` + `, next);
  3977. children.splice(j, 1);
  3978. j--;
  3979. }
  3980. else {
  3981. currentContainer = undefined;
  3982. break;
  3983. }
  3984. }
  3985. }
  3986. }
  3987. if (!hasText ||
  3988. // if this is a plain element with a single text child, leave it
  3989. // as-is since the runtime has dedicated fast path for this by directly
  3990. // setting textContent of the element.
  3991. // for component root it's always normalized anyway.
  3992. (children.length === 1 &&
  3993. (node.type === 0 /* ROOT */ ||
  3994. (node.type === 1 /* ELEMENT */ &&
  3995. node.tagType === 0 /* ELEMENT */)))) {
  3996. return;
  3997. }
  3998. // pre-convert text nodes into createTextVNode(text) calls to avoid
  3999. // runtime normalization.
  4000. for (let i = 0; i < children.length; i++) {
  4001. const child = children[i];
  4002. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  4003. const callArgs = [];
  4004. // createTextVNode defaults to single whitespace, so if it is a
  4005. // single space the code could be an empty call to save bytes.
  4006. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  4007. callArgs.push(child);
  4008. }
  4009. // mark dynamic text with flag so it gets patched inside a block
  4010. if (!context.ssr && child.type !== 2 /* TEXT */) {
  4011. callArgs.push(`${1 /* TEXT */} /* ${shared.PatchFlagNames[1 /* TEXT */]} */`);
  4012. }
  4013. children[i] = {
  4014. type: 12 /* TEXT_CALL */,
  4015. content: child,
  4016. loc: child.loc,
  4017. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  4018. };
  4019. }
  4020. }
  4021. };
  4022. }
  4023. };
  4024. const seen = new WeakSet();
  4025. const transformOnce = (node, context) => {
  4026. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  4027. if (seen.has(node)) {
  4028. return;
  4029. }
  4030. seen.add(node);
  4031. context.helper(SET_BLOCK_TRACKING);
  4032. return () => {
  4033. const cur = context.currentNode;
  4034. if (cur.codegenNode) {
  4035. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  4036. }
  4037. };
  4038. }
  4039. };
  4040. const transformModel = (dir, node, context) => {
  4041. const { exp, arg } = dir;
  4042. if (!exp) {
  4043. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  4044. return createTransformProps();
  4045. }
  4046. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : exp.loc.source;
  4047. if (!isMemberExpression(expString)) {
  4048. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  4049. return createTransformProps();
  4050. }
  4051. if (
  4052. context.prefixIdentifiers &&
  4053. isSimpleIdentifier(expString) &&
  4054. context.identifiers[expString]) {
  4055. context.onError(createCompilerError(42 /* X_V_MODEL_ON_SCOPE_VARIABLE */, exp.loc));
  4056. return createTransformProps();
  4057. }
  4058. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  4059. const eventName = arg
  4060. ? isStaticExp(arg)
  4061. ? `onUpdate:${arg.content}`
  4062. : createCompoundExpression(['"onUpdate:" + ', arg])
  4063. : `onUpdate:modelValue`;
  4064. const props = [
  4065. // modelValue: foo
  4066. createObjectProperty(propName, dir.exp),
  4067. // "onUpdate:modelValue": $event => (foo = $event)
  4068. createObjectProperty(eventName, createCompoundExpression([`$event => (`, exp, ` = $event)`]))
  4069. ];
  4070. // cache v-model handler if applicable (when it doesn't refer any scope vars)
  4071. if (
  4072. context.prefixIdentifiers &&
  4073. context.cacheHandlers &&
  4074. !hasScopeRef(exp, context.identifiers)) {
  4075. props[1].value = context.cache(props[1].value);
  4076. }
  4077. // modelModifiers: { foo: true, "bar-baz": true }
  4078. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  4079. const modifiers = dir.modifiers
  4080. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  4081. .join(`, `);
  4082. const modifiersKey = arg
  4083. ? isStaticExp(arg)
  4084. ? `${arg.content}Modifiers`
  4085. : createCompoundExpression([arg, ' + "Modifiers"'])
  4086. : `modelModifiers`;
  4087. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, true)));
  4088. }
  4089. return createTransformProps(props);
  4090. };
  4091. function createTransformProps(props = []) {
  4092. return { props };
  4093. }
  4094. function getBaseTransformPreset(prefixIdentifiers) {
  4095. return [
  4096. [
  4097. transformOnce,
  4098. transformIf,
  4099. transformFor,
  4100. ...( prefixIdentifiers
  4101. ? [
  4102. // order is important
  4103. trackVForSlotScopes,
  4104. transformExpression
  4105. ]
  4106. : []),
  4107. transformSlotOutlet,
  4108. transformElement,
  4109. trackSlotScopes,
  4110. transformText
  4111. ],
  4112. {
  4113. on: transformOn,
  4114. bind: transformBind,
  4115. model: transformModel
  4116. }
  4117. ];
  4118. }
  4119. // we name it `baseCompile` so that higher order compilers like
  4120. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  4121. function baseCompile(template, options = {}) {
  4122. const onError = options.onError || defaultOnError;
  4123. const isModuleMode = options.mode === 'module';
  4124. const prefixIdentifiers = (options.prefixIdentifiers === true || isModuleMode);
  4125. if (!prefixIdentifiers && options.cacheHandlers) {
  4126. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  4127. }
  4128. if (options.scopeId && !isModuleMode) {
  4129. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  4130. }
  4131. const ast = shared.isString(template) ? baseParse(template, options) : template;
  4132. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  4133. transform(ast, shared.extend({}, options, {
  4134. prefixIdentifiers,
  4135. nodeTransforms: [
  4136. ...nodeTransforms,
  4137. ...(options.nodeTransforms || []) // user transforms
  4138. ],
  4139. directiveTransforms: shared.extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  4140. )
  4141. }));
  4142. return generate(ast, shared.extend({}, options, {
  4143. prefixIdentifiers
  4144. }));
  4145. }
  4146. const noopDirectiveTransform = () => ({ props: [] });
  4147. exports.generateCodeFrame = shared.generateCodeFrame;
  4148. exports.BASE_TRANSITION = BASE_TRANSITION;
  4149. exports.CAMELIZE = CAMELIZE;
  4150. exports.CAPITALIZE = CAPITALIZE;
  4151. exports.CREATE_BLOCK = CREATE_BLOCK;
  4152. exports.CREATE_COMMENT = CREATE_COMMENT;
  4153. exports.CREATE_SLOTS = CREATE_SLOTS;
  4154. exports.CREATE_STATIC = CREATE_STATIC;
  4155. exports.CREATE_TEXT = CREATE_TEXT;
  4156. exports.CREATE_VNODE = CREATE_VNODE;
  4157. exports.FRAGMENT = FRAGMENT;
  4158. exports.KEEP_ALIVE = KEEP_ALIVE;
  4159. exports.MERGE_PROPS = MERGE_PROPS;
  4160. exports.OPEN_BLOCK = OPEN_BLOCK;
  4161. exports.POP_SCOPE_ID = POP_SCOPE_ID;
  4162. exports.PUSH_SCOPE_ID = PUSH_SCOPE_ID;
  4163. exports.RENDER_LIST = RENDER_LIST;
  4164. exports.RENDER_SLOT = RENDER_SLOT;
  4165. exports.RESOLVE_COMPONENT = RESOLVE_COMPONENT;
  4166. exports.RESOLVE_DIRECTIVE = RESOLVE_DIRECTIVE;
  4167. exports.RESOLVE_DYNAMIC_COMPONENT = RESOLVE_DYNAMIC_COMPONENT;
  4168. exports.SET_BLOCK_TRACKING = SET_BLOCK_TRACKING;
  4169. exports.SUSPENSE = SUSPENSE;
  4170. exports.TELEPORT = TELEPORT;
  4171. exports.TO_DISPLAY_STRING = TO_DISPLAY_STRING;
  4172. exports.TO_HANDLERS = TO_HANDLERS;
  4173. exports.TO_HANDLER_KEY = TO_HANDLER_KEY;
  4174. exports.WITH_CTX = WITH_CTX;
  4175. exports.WITH_DIRECTIVES = WITH_DIRECTIVES;
  4176. exports.WITH_SCOPE_ID = WITH_SCOPE_ID;
  4177. exports.advancePositionWithClone = advancePositionWithClone;
  4178. exports.advancePositionWithMutation = advancePositionWithMutation;
  4179. exports.assert = assert;
  4180. exports.baseCompile = baseCompile;
  4181. exports.baseParse = baseParse;
  4182. exports.buildProps = buildProps;
  4183. exports.buildSlots = buildSlots;
  4184. exports.createArrayExpression = createArrayExpression;
  4185. exports.createAssignmentExpression = createAssignmentExpression;
  4186. exports.createBlockStatement = createBlockStatement;
  4187. exports.createCacheExpression = createCacheExpression;
  4188. exports.createCallExpression = createCallExpression;
  4189. exports.createCompilerError = createCompilerError;
  4190. exports.createCompoundExpression = createCompoundExpression;
  4191. exports.createConditionalExpression = createConditionalExpression;
  4192. exports.createForLoopParams = createForLoopParams;
  4193. exports.createFunctionExpression = createFunctionExpression;
  4194. exports.createIfStatement = createIfStatement;
  4195. exports.createInterpolation = createInterpolation;
  4196. exports.createObjectExpression = createObjectExpression;
  4197. exports.createObjectProperty = createObjectProperty;
  4198. exports.createReturnStatement = createReturnStatement;
  4199. exports.createRoot = createRoot;
  4200. exports.createSequenceExpression = createSequenceExpression;
  4201. exports.createSimpleExpression = createSimpleExpression;
  4202. exports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;
  4203. exports.createTemplateLiteral = createTemplateLiteral;
  4204. exports.createTransformContext = createTransformContext;
  4205. exports.createVNodeCall = createVNodeCall;
  4206. exports.findDir = findDir;
  4207. exports.findProp = findProp;
  4208. exports.generate = generate;
  4209. exports.getBaseTransformPreset = getBaseTransformPreset;
  4210. exports.getInnerRange = getInnerRange;
  4211. exports.hasDynamicKeyVBind = hasDynamicKeyVBind;
  4212. exports.hasScopeRef = hasScopeRef;
  4213. exports.helperNameMap = helperNameMap;
  4214. exports.injectProp = injectProp;
  4215. exports.isBindKey = isBindKey;
  4216. exports.isBuiltInType = isBuiltInType;
  4217. exports.isCoreComponent = isCoreComponent;
  4218. exports.isMemberExpression = isMemberExpression;
  4219. exports.isSimpleIdentifier = isSimpleIdentifier;
  4220. exports.isSlotOutlet = isSlotOutlet;
  4221. exports.isStaticExp = isStaticExp;
  4222. exports.isTemplateNode = isTemplateNode;
  4223. exports.isText = isText;
  4224. exports.isVSlot = isVSlot;
  4225. exports.locStub = locStub;
  4226. exports.noopDirectiveTransform = noopDirectiveTransform;
  4227. exports.processExpression = processExpression;
  4228. exports.processFor = processFor;
  4229. exports.processIf = processIf;
  4230. exports.processSlotOutlet = processSlotOutlet;
  4231. exports.registerRuntimeHelpers = registerRuntimeHelpers;
  4232. exports.resolveComponentType = resolveComponentType;
  4233. exports.toValidAssetId = toValidAssetId;
  4234. exports.trackSlotScopes = trackSlotScopes;
  4235. exports.trackVForSlotScopes = trackVForSlotScopes;
  4236. exports.transform = transform;
  4237. exports.transformBind = transformBind;
  4238. exports.transformElement = transformElement;
  4239. exports.transformExpression = transformExpression;
  4240. exports.transformModel = transformModel;
  4241. exports.transformOn = transformOn;
  4242. exports.traverseNode = traverseNode;