compiler-core.cjs.prod.js 155 KB

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