Parser.cpp 194 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  6. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "Parser.h"
  11. #include <AK/Array.h>
  12. #include <AK/CharacterTypes.h>
  13. #include <AK/HashTable.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <AK/StdLibExtras.h>
  16. #include <AK/TemporaryChange.h>
  17. #include <LibJS/Runtime/RegExpObject.h>
  18. #include <LibRegex/Regex.h>
  19. namespace JS {
  20. class ScopePusher {
  21. private:
  22. ScopePusher(Parser& parser, ScopeNode* node, bool is_top_level)
  23. : m_parser(parser)
  24. , m_is_top_level(is_top_level)
  25. {
  26. m_parent_scope = exchange(m_parser.m_state.current_scope_pusher, this);
  27. VERIFY(node || (m_parent_scope && !is_top_level));
  28. if (!node)
  29. m_node = m_parent_scope->m_node;
  30. else
  31. m_node = node;
  32. VERIFY(m_node);
  33. if (!is_top_level)
  34. m_top_level_scope = m_parent_scope->m_top_level_scope;
  35. else
  36. m_top_level_scope = this;
  37. }
  38. public:
  39. static ScopePusher function_scope(Parser& parser, FunctionBody& function_body, Vector<FunctionDeclaration::Parameter> const& parameters)
  40. {
  41. ScopePusher scope_pusher(parser, &function_body, true);
  42. scope_pusher.m_function_parameters = parameters;
  43. for (auto& parameter : parameters) {
  44. parameter.binding.visit(
  45. [&](FlyString const& name) {
  46. scope_pusher.m_forbidden_lexical_names.set(name);
  47. },
  48. [&](NonnullRefPtr<BindingPattern> const& binding_pattern) {
  49. binding_pattern->for_each_bound_name([&](auto const& name) {
  50. scope_pusher.m_forbidden_lexical_names.set(name);
  51. });
  52. });
  53. }
  54. return scope_pusher;
  55. }
  56. static ScopePusher program_scope(Parser& parser, Program& program)
  57. {
  58. return ScopePusher(parser, &program, true);
  59. }
  60. static ScopePusher block_scope(Parser& parser, ScopeNode& node)
  61. {
  62. return ScopePusher(parser, &node, false);
  63. }
  64. static ScopePusher for_loop_scope(Parser& parser, RefPtr<ASTNode> const& init)
  65. {
  66. ScopePusher scope_pusher(parser, nullptr, false);
  67. if (init && is<VariableDeclaration>(*init)) {
  68. auto& variable_declaration = static_cast<VariableDeclaration const&>(*init);
  69. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  70. variable_declaration.for_each_bound_name([&](auto const& name) {
  71. scope_pusher.m_forbidden_var_names.set(name);
  72. });
  73. }
  74. }
  75. return scope_pusher;
  76. }
  77. static ScopePusher catch_scope(Parser& parser, RefPtr<BindingPattern> const& pattern, FlyString const& parameter)
  78. {
  79. ScopePusher scope_pusher(parser, nullptr, false);
  80. if (pattern) {
  81. pattern->for_each_bound_name([&](auto const& name) {
  82. scope_pusher.m_forbidden_var_names.set(name);
  83. });
  84. } else if (!parameter.is_empty()) {
  85. scope_pusher.m_var_names.set(parameter);
  86. }
  87. return scope_pusher;
  88. }
  89. static ScopePusher static_init_block_scope(Parser& parser, ScopeNode& node)
  90. {
  91. return ScopePusher(parser, &node, true);
  92. }
  93. static ScopePusher class_field_scope(Parser& parser)
  94. {
  95. return ScopePusher(parser, nullptr, false);
  96. }
  97. void add_declaration(NonnullRefPtr<Declaration> declaration)
  98. {
  99. if (declaration->is_lexical_declaration()) {
  100. declaration->for_each_bound_name([&](auto const& name) {
  101. if (m_var_names.contains(name) || m_forbidden_lexical_names.contains(name) || m_function_names.contains(name))
  102. throw_identifier_declared(name, declaration);
  103. if (m_lexical_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  104. throw_identifier_declared(name, declaration);
  105. });
  106. m_node->add_lexical_declaration(move(declaration));
  107. } else if (!declaration->is_function_declaration()) {
  108. declaration->for_each_bound_name([&](auto const& name) {
  109. ScopePusher* pusher = this;
  110. while (true) {
  111. if (pusher->m_lexical_names.contains(name)
  112. || pusher->m_function_names.contains(name)
  113. || pusher->m_forbidden_var_names.contains(name))
  114. throw_identifier_declared(name, declaration);
  115. pusher->m_var_names.set(name);
  116. if (pusher->m_is_top_level)
  117. break;
  118. VERIFY(pusher->m_parent_scope != nullptr);
  119. pusher = pusher->m_parent_scope;
  120. }
  121. VERIFY(pusher->m_is_top_level && pusher->m_node);
  122. pusher->m_node->add_var_scoped_declaration(declaration);
  123. });
  124. VERIFY(m_top_level_scope);
  125. m_top_level_scope->m_node->add_var_scoped_declaration(move(declaration));
  126. } else {
  127. if (m_is_top_level && m_parser.m_program_type == Program::Type::Script) {
  128. declaration->for_each_bound_name([&](auto const& name) {
  129. m_var_names.set(name);
  130. });
  131. m_node->add_var_scoped_declaration(move(declaration));
  132. } else {
  133. VERIFY(is<FunctionDeclaration>(*declaration));
  134. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  135. auto& function_name = function_declaration.name();
  136. if (m_var_names.contains(function_name) || m_lexical_names.contains(function_name))
  137. throw_identifier_declared(function_name, declaration);
  138. if (function_declaration.kind() != FunctionKind::Normal || m_parser.m_state.strict_mode) {
  139. if (m_function_names.contains(function_name))
  140. throw_identifier_declared(function_name, declaration);
  141. m_lexical_names.set(function_name);
  142. m_node->add_lexical_declaration(move(declaration));
  143. return;
  144. }
  145. m_function_names.set(function_name);
  146. if (!m_lexical_names.contains(function_name))
  147. m_functions_to_hoist.append(static_ptr_cast<FunctionDeclaration>(declaration));
  148. m_node->add_lexical_declaration(move(declaration));
  149. }
  150. }
  151. }
  152. ScopePusher const* last_function_scope() const
  153. {
  154. for (auto scope_ptr = this; scope_ptr; scope_ptr = scope_ptr->m_parent_scope) {
  155. if (scope_ptr->m_function_parameters.has_value())
  156. return scope_ptr;
  157. }
  158. return nullptr;
  159. }
  160. Vector<FunctionDeclaration::Parameter> const& function_parameters() const
  161. {
  162. return *m_function_parameters;
  163. }
  164. ScopePusher* parent_scope() { return m_parent_scope; }
  165. ScopePusher const* parent_scope() const { return m_parent_scope; }
  166. [[nodiscard]] bool has_declaration(StringView name) const
  167. {
  168. return m_lexical_names.contains(name) || m_var_names.contains(name) || !m_functions_to_hoist.find_if([&name](auto& function) { return function->name() == name; }).is_end();
  169. }
  170. bool contains_direct_call_to_eval() const { return m_contains_direct_call_to_eval; }
  171. bool contains_access_to_arguments_object() const { return m_contains_access_to_arguments_object; }
  172. void set_contains_direct_call_to_eval() { m_contains_direct_call_to_eval = true; }
  173. void set_contains_access_to_arguments_object() { m_contains_access_to_arguments_object = true; }
  174. ~ScopePusher()
  175. {
  176. VERIFY(m_is_top_level || m_parent_scope);
  177. if (!m_contains_access_to_arguments_object) {
  178. for (auto& it : m_identifier_and_argument_index_associations) {
  179. for (auto& identifier : it.value) {
  180. if (!has_declaration(identifier.string()))
  181. identifier.set_lexically_bound_function_argument_index(it.key);
  182. }
  183. }
  184. }
  185. for (size_t i = 0; i < m_functions_to_hoist.size(); i++) {
  186. auto const& function_declaration = m_functions_to_hoist[i];
  187. if (m_lexical_names.contains(function_declaration.name()) || m_forbidden_var_names.contains(function_declaration.name()))
  188. continue;
  189. if (m_is_top_level)
  190. m_node->add_hoisted_function(move(m_functions_to_hoist[i]));
  191. else
  192. m_parent_scope->m_functions_to_hoist.append(move(m_functions_to_hoist[i]));
  193. }
  194. if (m_parent_scope && !m_function_parameters.has_value()) {
  195. m_parent_scope->m_contains_access_to_arguments_object |= m_contains_access_to_arguments_object;
  196. m_parent_scope->m_contains_direct_call_to_eval |= m_contains_direct_call_to_eval;
  197. }
  198. VERIFY(m_parser.m_state.current_scope_pusher == this);
  199. m_parser.m_state.current_scope_pusher = m_parent_scope;
  200. }
  201. void associate_identifier_with_argument_index(NonnullRefPtr<Identifier> identifier, size_t index)
  202. {
  203. m_identifier_and_argument_index_associations.ensure(index).append(move(identifier));
  204. }
  205. void set_contains_await_expression()
  206. {
  207. m_contains_await_expression = true;
  208. }
  209. bool contains_await_expression() const
  210. {
  211. return m_contains_await_expression;
  212. }
  213. private:
  214. void throw_identifier_declared(FlyString const& name, NonnullRefPtr<Declaration> const& declaration)
  215. {
  216. m_parser.syntax_error(String::formatted("Identifier '{}' already declared", name), declaration->source_range().start);
  217. }
  218. Parser& m_parser;
  219. ScopeNode* m_node { nullptr };
  220. bool m_is_top_level { false };
  221. ScopePusher* m_parent_scope { nullptr };
  222. ScopePusher* m_top_level_scope { nullptr };
  223. HashTable<FlyString> m_lexical_names;
  224. HashTable<FlyString> m_var_names;
  225. HashTable<FlyString> m_function_names;
  226. HashTable<FlyString> m_forbidden_lexical_names;
  227. HashTable<FlyString> m_forbidden_var_names;
  228. NonnullRefPtrVector<FunctionDeclaration> m_functions_to_hoist;
  229. Optional<Vector<FunctionDeclaration::Parameter>> m_function_parameters;
  230. HashMap<size_t, NonnullRefPtrVector<Identifier>> m_identifier_and_argument_index_associations;
  231. bool m_contains_access_to_arguments_object { false };
  232. bool m_contains_direct_call_to_eval { false };
  233. bool m_contains_await_expression { false };
  234. };
  235. class OperatorPrecedenceTable {
  236. public:
  237. constexpr OperatorPrecedenceTable()
  238. : m_token_precedence()
  239. {
  240. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  241. auto& op = m_operator_precedence[i];
  242. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  243. }
  244. }
  245. constexpr int get(TokenType token) const
  246. {
  247. int p = m_token_precedence[static_cast<size_t>(token)];
  248. if (p == 0) {
  249. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  250. VERIFY_NOT_REACHED();
  251. return -1;
  252. }
  253. return p;
  254. }
  255. private:
  256. int m_token_precedence[cs_num_of_js_tokens];
  257. struct OperatorPrecedence {
  258. TokenType token;
  259. int precedence;
  260. };
  261. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  262. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  263. { TokenType::Period, 20 },
  264. { TokenType::BracketOpen, 20 },
  265. { TokenType::ParenOpen, 20 },
  266. { TokenType::QuestionMarkPeriod, 20 },
  267. { TokenType::New, 19 },
  268. { TokenType::PlusPlus, 18 },
  269. { TokenType::MinusMinus, 18 },
  270. { TokenType::ExclamationMark, 17 },
  271. { TokenType::Tilde, 17 },
  272. { TokenType::Typeof, 17 },
  273. { TokenType::Void, 17 },
  274. { TokenType::Delete, 17 },
  275. { TokenType::Await, 17 },
  276. { TokenType::DoubleAsterisk, 16 },
  277. { TokenType::Asterisk, 15 },
  278. { TokenType::Slash, 15 },
  279. { TokenType::Percent, 15 },
  280. { TokenType::Plus, 14 },
  281. { TokenType::Minus, 14 },
  282. { TokenType::ShiftLeft, 13 },
  283. { TokenType::ShiftRight, 13 },
  284. { TokenType::UnsignedShiftRight, 13 },
  285. { TokenType::LessThan, 12 },
  286. { TokenType::LessThanEquals, 12 },
  287. { TokenType::GreaterThan, 12 },
  288. { TokenType::GreaterThanEquals, 12 },
  289. { TokenType::In, 12 },
  290. { TokenType::Instanceof, 12 },
  291. { TokenType::EqualsEquals, 11 },
  292. { TokenType::ExclamationMarkEquals, 11 },
  293. { TokenType::EqualsEqualsEquals, 11 },
  294. { TokenType::ExclamationMarkEqualsEquals, 11 },
  295. { TokenType::Ampersand, 10 },
  296. { TokenType::Caret, 9 },
  297. { TokenType::Pipe, 8 },
  298. { TokenType::DoubleQuestionMark, 7 },
  299. { TokenType::DoubleAmpersand, 6 },
  300. { TokenType::DoublePipe, 5 },
  301. { TokenType::QuestionMark, 4 },
  302. { TokenType::Equals, 3 },
  303. { TokenType::PlusEquals, 3 },
  304. { TokenType::MinusEquals, 3 },
  305. { TokenType::DoubleAsteriskEquals, 3 },
  306. { TokenType::AsteriskEquals, 3 },
  307. { TokenType::SlashEquals, 3 },
  308. { TokenType::PercentEquals, 3 },
  309. { TokenType::ShiftLeftEquals, 3 },
  310. { TokenType::ShiftRightEquals, 3 },
  311. { TokenType::UnsignedShiftRightEquals, 3 },
  312. { TokenType::AmpersandEquals, 3 },
  313. { TokenType::CaretEquals, 3 },
  314. { TokenType::PipeEquals, 3 },
  315. { TokenType::DoubleAmpersandEquals, 3 },
  316. { TokenType::DoublePipeEquals, 3 },
  317. { TokenType::DoubleQuestionMarkEquals, 3 },
  318. { TokenType::Yield, 2 },
  319. { TokenType::Comma, 1 },
  320. };
  321. };
  322. constexpr OperatorPrecedenceTable g_operator_precedence;
  323. Parser::ParserState::ParserState(Lexer l, Program::Type program_type)
  324. : lexer(move(l))
  325. {
  326. if (program_type == Program::Type::Module)
  327. lexer.disallow_html_comments();
  328. current_token = lexer.next();
  329. }
  330. Parser::Parser(Lexer lexer, Program::Type program_type)
  331. : m_state(move(lexer), program_type)
  332. , m_program_type(program_type)
  333. {
  334. }
  335. Associativity Parser::operator_associativity(TokenType type) const
  336. {
  337. switch (type) {
  338. case TokenType::Period:
  339. case TokenType::BracketOpen:
  340. case TokenType::ParenOpen:
  341. case TokenType::QuestionMarkPeriod:
  342. case TokenType::Asterisk:
  343. case TokenType::Slash:
  344. case TokenType::Percent:
  345. case TokenType::Plus:
  346. case TokenType::Minus:
  347. case TokenType::ShiftLeft:
  348. case TokenType::ShiftRight:
  349. case TokenType::UnsignedShiftRight:
  350. case TokenType::LessThan:
  351. case TokenType::LessThanEquals:
  352. case TokenType::GreaterThan:
  353. case TokenType::GreaterThanEquals:
  354. case TokenType::In:
  355. case TokenType::Instanceof:
  356. case TokenType::EqualsEquals:
  357. case TokenType::ExclamationMarkEquals:
  358. case TokenType::EqualsEqualsEquals:
  359. case TokenType::ExclamationMarkEqualsEquals:
  360. case TokenType::Typeof:
  361. case TokenType::Void:
  362. case TokenType::Delete:
  363. case TokenType::Await:
  364. case TokenType::Ampersand:
  365. case TokenType::Caret:
  366. case TokenType::Pipe:
  367. case TokenType::DoubleQuestionMark:
  368. case TokenType::DoubleAmpersand:
  369. case TokenType::DoublePipe:
  370. case TokenType::Comma:
  371. return Associativity::Left;
  372. default:
  373. return Associativity::Right;
  374. }
  375. }
  376. bool Parser::parse_directive(ScopeNode& body)
  377. {
  378. bool found_use_strict = false;
  379. while (!done() && match(TokenType::StringLiteral)) {
  380. // It cannot be a labelled function since we hit a string literal.
  381. auto statement = parse_statement(AllowLabelledFunction::No);
  382. body.append(statement);
  383. VERIFY(is<ExpressionStatement>(*statement));
  384. auto& expression = static_cast<ExpressionStatement const&>(*statement).expression();
  385. if (!is<StringLiteral>(expression))
  386. break;
  387. auto& string_literal = static_cast<StringLiteral const&>(expression);
  388. if (string_literal.is_use_strict_directive()) {
  389. found_use_strict = true;
  390. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  391. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  392. break;
  393. }
  394. }
  395. m_state.string_legacy_octal_escape_sequence_in_scope = false;
  396. return found_use_strict;
  397. }
  398. NonnullRefPtr<Program> Parser::parse_program(bool starts_in_strict_mode)
  399. {
  400. auto rule_start = push_start();
  401. auto program = adopt_ref(*new Program({ m_filename, rule_start.position(), position() }, m_program_type));
  402. ScopePusher program_scope = ScopePusher::program_scope(*this, *program);
  403. if (m_program_type == Program::Type::Script)
  404. parse_script(program, starts_in_strict_mode);
  405. else
  406. parse_module(program);
  407. program->source_range().end = position();
  408. return program;
  409. }
  410. void Parser::parse_script(Program& program, bool starts_in_strict_mode)
  411. {
  412. bool strict_before = m_state.strict_mode;
  413. if (starts_in_strict_mode)
  414. m_state.strict_mode = true;
  415. bool has_use_strict = parse_directive(program);
  416. if (m_state.strict_mode || has_use_strict) {
  417. program.set_strict_mode();
  418. m_state.strict_mode = true;
  419. }
  420. parse_statement_list(program, AllowLabelledFunction::Yes);
  421. if (!done()) {
  422. expected("statement or declaration");
  423. consume();
  424. }
  425. m_state.strict_mode = strict_before;
  426. }
  427. void Parser::parse_module(Program& program)
  428. {
  429. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  430. TemporaryChange await_expression_valid_rollback(m_state.await_expression_is_valid, true);
  431. // Since strict mode is already enabled we skip any directive parsing.
  432. while (!done()) {
  433. parse_statement_list(program, AllowLabelledFunction::Yes);
  434. if (done())
  435. break;
  436. if (match_export_or_import()) {
  437. VERIFY(m_state.current_token.type() == TokenType::Export || m_state.current_token.type() == TokenType::Import);
  438. if (m_state.current_token.type() == TokenType::Export)
  439. program.append_export(parse_export_statement(program));
  440. else
  441. program.append_import(parse_import_statement(program));
  442. } else {
  443. expected("statement or declaration");
  444. consume();
  445. }
  446. }
  447. VERIFY(m_state.current_scope_pusher);
  448. if (m_state.current_scope_pusher->contains_await_expression())
  449. program.set_has_top_level_await();
  450. for (auto& export_statement : program.exports()) {
  451. if (export_statement.has_statement())
  452. continue;
  453. for (auto& entry : export_statement.entries()) {
  454. if (entry.is_module_request())
  455. return;
  456. auto const& exported_name = entry.local_or_import_name;
  457. bool found = false;
  458. program.for_each_lexically_declared_name([&](auto const& name) {
  459. if (name == exported_name) {
  460. found = true;
  461. return IterationDecision::Break;
  462. }
  463. return IterationDecision::Continue;
  464. });
  465. if (found)
  466. continue;
  467. program.for_each_var_declared_name([&](auto const& name) {
  468. if (name == exported_name) {
  469. found = true;
  470. return IterationDecision::Break;
  471. }
  472. return IterationDecision::Continue;
  473. });
  474. if (!found)
  475. syntax_error(String::formatted("'{}' is not declared", exported_name));
  476. }
  477. }
  478. }
  479. NonnullRefPtr<Declaration> Parser::parse_declaration()
  480. {
  481. auto rule_start = push_start();
  482. if (m_state.current_token.type() == TokenType::Async && next_token().type() == TokenType::Function)
  483. return parse_function_node<FunctionDeclaration>();
  484. switch (m_state.current_token.type()) {
  485. case TokenType::Class:
  486. return parse_class_declaration();
  487. case TokenType::Function:
  488. return parse_function_node<FunctionDeclaration>();
  489. case TokenType::Let:
  490. case TokenType::Const:
  491. return parse_variable_declaration();
  492. default:
  493. expected("declaration");
  494. consume();
  495. return create_ast_node<ErrorDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() });
  496. }
  497. }
  498. NonnullRefPtr<Statement> Parser::parse_statement(AllowLabelledFunction allow_labelled_function)
  499. {
  500. auto rule_start = push_start();
  501. auto type = m_state.current_token.type();
  502. switch (type) {
  503. case TokenType::CurlyOpen:
  504. return parse_block_statement();
  505. case TokenType::Return:
  506. return parse_return_statement();
  507. case TokenType::Var: {
  508. auto declaration = parse_variable_declaration();
  509. m_state.current_scope_pusher->add_declaration(declaration);
  510. return declaration;
  511. }
  512. case TokenType::For:
  513. return parse_for_statement();
  514. case TokenType::If:
  515. return parse_if_statement();
  516. case TokenType::Throw:
  517. return parse_throw_statement();
  518. case TokenType::Try:
  519. return parse_try_statement();
  520. case TokenType::Break:
  521. return parse_break_statement();
  522. case TokenType::Continue:
  523. return parse_continue_statement();
  524. case TokenType::Switch:
  525. return parse_switch_statement();
  526. case TokenType::Do:
  527. return parse_do_while_statement();
  528. case TokenType::While:
  529. return parse_while_statement();
  530. case TokenType::With:
  531. if (m_state.strict_mode)
  532. syntax_error("'with' statement not allowed in strict mode");
  533. return parse_with_statement();
  534. case TokenType::Debugger:
  535. return parse_debugger_statement();
  536. case TokenType::Semicolon:
  537. consume();
  538. return create_ast_node<EmptyStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  539. case TokenType::Slash:
  540. case TokenType::SlashEquals:
  541. m_state.current_token = m_state.lexer.force_slash_as_regex();
  542. [[fallthrough]];
  543. default:
  544. if (match_invalid_escaped_keyword())
  545. syntax_error("Keyword must not contain escaped characters");
  546. if (match_identifier_name()) {
  547. auto result = try_parse_labelled_statement(allow_labelled_function);
  548. if (!result.is_null())
  549. return result.release_nonnull();
  550. }
  551. if (match_expression()) {
  552. if (match(TokenType::Async)) {
  553. auto lookahead_token = next_token();
  554. if (lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator())
  555. syntax_error("Async function declaration not allowed in single-statement context");
  556. } else if (match(TokenType::Function) || match(TokenType::Class)) {
  557. syntax_error(String::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name()));
  558. } else if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen) {
  559. syntax_error(String::formatted("let followed by [ is not allowed in single-statement context"));
  560. }
  561. auto expr = parse_expression(0);
  562. consume_or_insert_semicolon();
  563. return create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expr));
  564. }
  565. expected("statement");
  566. consume();
  567. return create_ast_node<ErrorStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  568. }
  569. }
  570. bool Parser::match_invalid_escaped_keyword() const
  571. {
  572. if (m_state.current_token.type() != TokenType::EscapedKeyword)
  573. return false;
  574. auto token_value = m_state.current_token.value();
  575. if (token_value == "await"sv)
  576. return m_program_type == Program::Type::Module || m_state.await_expression_is_valid;
  577. if (token_value == "async"sv)
  578. return false;
  579. if (token_value == "yield"sv)
  580. return m_state.in_generator_function_context;
  581. if (m_state.strict_mode)
  582. return true;
  583. return token_value != "let"sv;
  584. }
  585. static constexpr AK::Array<StringView, 9> strict_reserved_words = { "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield" };
  586. static bool is_strict_reserved_word(StringView str)
  587. {
  588. return any_of(strict_reserved_words, [&str](StringView word) {
  589. return word == str;
  590. });
  591. }
  592. static bool is_simple_parameter_list(Vector<FunctionNode::Parameter> const& parameters)
  593. {
  594. return all_of(parameters, [](FunctionNode::Parameter const& parameter) {
  595. return !parameter.is_rest && parameter.default_value.is_null() && parameter.binding.has<FlyString>();
  596. });
  597. }
  598. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens, bool is_async)
  599. {
  600. if (is_async)
  601. VERIFY(match(TokenType::Async));
  602. if (!expect_parens && !is_async) {
  603. // NOTE: This is a fast path where we try to fail early in case this can't possibly
  604. // be a match. The idea is to avoid the expensive parser state save/load mechanism.
  605. // The logic is duplicated below in the "real" !expect_parens branch.
  606. if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
  607. return nullptr;
  608. auto token = next_token();
  609. if (token.trivia_contains_line_terminator())
  610. return nullptr;
  611. if (token.type() != TokenType::Arrow)
  612. return nullptr;
  613. }
  614. save_state();
  615. auto rule_start = (expect_parens && !is_async)
  616. // Someone has consumed the opening parenthesis for us! Start there.
  617. ? RulePosition { *this, m_rule_starts.last() }
  618. // We've not encountered one yet, so the rule start is actually here.
  619. : push_start();
  620. ArmedScopeGuard state_rollback_guard = [&] {
  621. load_state();
  622. };
  623. auto function_kind = FunctionKind::Normal;
  624. if (is_async) {
  625. consume(TokenType::Async);
  626. function_kind = FunctionKind::Async;
  627. if (m_state.current_token.trivia_contains_line_terminator())
  628. return nullptr;
  629. // Since we have async it can be followed by paren open in the expect_parens case
  630. // so we also consume that token.
  631. if (expect_parens) {
  632. VERIFY(match(TokenType::ParenOpen));
  633. consume(TokenType::ParenOpen);
  634. }
  635. }
  636. Vector<FunctionNode::Parameter> parameters;
  637. i32 function_length = -1;
  638. if (expect_parens) {
  639. // We have parens around the function parameters and can re-use the same parsing
  640. // logic used for regular functions: multiple parameters, default values, rest
  641. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  642. // check if it's about a wrong token (something like duplicate parameter name must
  643. // not abort), know parsing failed and rollback the parser state.
  644. auto previous_syntax_errors = m_state.errors.size();
  645. TemporaryChange in_async_context(m_state.await_expression_is_valid, is_async || m_state.await_expression_is_valid);
  646. parameters = parse_formal_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction | (is_async ? FunctionNodeParseOptions::IsAsyncFunction : 0));
  647. if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  648. return nullptr;
  649. if (!match(TokenType::ParenClose))
  650. return nullptr;
  651. consume();
  652. } else {
  653. // No parens - this must be an identifier followed by arrow. That's it.
  654. if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
  655. return nullptr;
  656. auto token = consume_identifier_reference();
  657. if (m_state.strict_mode && token.value().is_one_of("arguments"sv, "eval"sv))
  658. syntax_error("BindingIdentifier may not be 'arguments' or 'eval' in strict mode");
  659. if (is_async && token.value() == "await"sv)
  660. syntax_error("'await' is a reserved identifier in async functions");
  661. parameters.append({ FlyString { token.value() }, {} });
  662. }
  663. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  664. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  665. if (m_state.current_token.trivia_contains_line_terminator())
  666. return nullptr;
  667. if (!match(TokenType::Arrow))
  668. return nullptr;
  669. consume();
  670. if (function_length == -1)
  671. function_length = parameters.size();
  672. auto old_labels_in_scope = move(m_state.labels_in_scope);
  673. ScopeGuard guard([&]() {
  674. m_state.labels_in_scope = move(old_labels_in_scope);
  675. });
  676. bool contains_direct_call_to_eval = false;
  677. auto function_body_result = [&]() -> RefPtr<FunctionBody> {
  678. TemporaryChange change(m_state.in_arrow_function_context, true);
  679. TemporaryChange async_context_change(m_state.await_expression_is_valid, is_async);
  680. TemporaryChange in_class_static_init_block_change(m_state.in_class_static_init_block, false);
  681. if (match(TokenType::CurlyOpen)) {
  682. // Parse a function body with statements
  683. consume(TokenType::CurlyOpen);
  684. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  685. consume(TokenType::CurlyClose);
  686. return body;
  687. }
  688. if (match_expression()) {
  689. // Parse a function body which returns a single expression
  690. // FIXME: We synthesize a block with a return statement
  691. // for arrow function bodies which are a single expression.
  692. // Esprima generates a single "ArrowFunctionExpression"
  693. // with a "body" property.
  694. auto return_block = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  695. ScopePusher function_scope = ScopePusher::function_scope(*this, return_block, parameters);
  696. auto return_expression = parse_expression(2);
  697. return_block->append<ReturnStatement>({ m_filename, rule_start.position(), position() }, move(return_expression));
  698. if (m_state.strict_mode)
  699. return_block->set_strict_mode();
  700. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  701. return return_block;
  702. }
  703. // Invalid arrow function body
  704. return nullptr;
  705. }();
  706. if (function_body_result.is_null())
  707. return nullptr;
  708. state_rollback_guard.disarm();
  709. discard_saved_state();
  710. auto body = function_body_result.release_nonnull();
  711. if (body->in_strict_mode()) {
  712. for (auto& parameter : parameters) {
  713. parameter.binding.visit(
  714. [&](FlyString const& name) {
  715. check_identifier_name_for_assignment_validity(name, true);
  716. },
  717. [&](auto const&) {});
  718. }
  719. }
  720. auto function_start_offset = rule_start.position().offset;
  721. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  722. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  723. return create_ast_node<FunctionExpression>(
  724. { m_state.current_token.filename(), rule_start.position(), position() }, "", move(source_text),
  725. move(body), move(parameters), function_length, function_kind, body->in_strict_mode(),
  726. /* might_need_arguments_object */ false, contains_direct_call_to_eval, /* is_arrow_function */ true);
  727. }
  728. RefPtr<LabelledStatement> Parser::try_parse_labelled_statement(AllowLabelledFunction allow_function)
  729. {
  730. {
  731. // NOTE: This is a fast path where we try to fail early to avoid the expensive save_state+load_state.
  732. if (next_token().type() != TokenType::Colon)
  733. return {};
  734. }
  735. save_state();
  736. auto rule_start = push_start();
  737. ArmedScopeGuard state_rollback_guard = [&] {
  738. load_state();
  739. };
  740. if (m_state.current_token.value() == "yield"sv && (m_state.strict_mode || m_state.in_generator_function_context)) {
  741. return {};
  742. }
  743. if (m_state.current_token.value() == "await"sv && (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)) {
  744. return {};
  745. }
  746. auto identifier = [&] {
  747. if (m_state.current_token.value() == "await"sv) {
  748. return consume().value();
  749. }
  750. return consume_identifier_reference().value();
  751. }();
  752. if (!match(TokenType::Colon))
  753. return {};
  754. consume(TokenType::Colon);
  755. if (!match_statement())
  756. return {};
  757. state_rollback_guard.disarm();
  758. discard_saved_state();
  759. if (m_state.strict_mode && identifier == "let"sv) {
  760. syntax_error("Strict mode reserved word 'let' is not allowed in label", rule_start.position());
  761. return {};
  762. }
  763. if (match(TokenType::Function) && (allow_function == AllowLabelledFunction::No || m_state.strict_mode)) {
  764. syntax_error("Not allowed to declare a function here");
  765. return {};
  766. }
  767. if (m_state.labels_in_scope.contains(identifier))
  768. syntax_error(String::formatted("Label '{}' has already been declared", identifier));
  769. RefPtr<Statement> labelled_item;
  770. auto is_iteration_statement = false;
  771. if (match(TokenType::Function)) {
  772. m_state.labels_in_scope.set(identifier, {});
  773. auto function_declaration = parse_function_node<FunctionDeclaration>();
  774. VERIFY(m_state.current_scope_pusher);
  775. m_state.current_scope_pusher->add_declaration(function_declaration);
  776. if (function_declaration->kind() == FunctionKind::Generator)
  777. syntax_error("Generator functions cannot be defined in labelled statements");
  778. if (function_declaration->kind() == FunctionKind::Async)
  779. syntax_error("Async functions cannot be defined in labelled statements");
  780. labelled_item = move(function_declaration);
  781. } else {
  782. m_state.labels_in_scope.set(identifier, {});
  783. labelled_item = parse_statement(allow_function);
  784. // Extract the innermost statement from a potentially nested chain of LabelledStatements.
  785. auto statement = labelled_item;
  786. while (is<LabelledStatement>(*statement))
  787. statement = static_cast<LabelledStatement&>(*statement).labelled_item();
  788. if (is<IterationStatement>(*statement))
  789. is_iteration_statement = true;
  790. }
  791. if (!is_iteration_statement) {
  792. if (auto entry = m_state.labels_in_scope.find(identifier); entry != m_state.labels_in_scope.end() && entry->value.has_value())
  793. syntax_error("labelled continue statement cannot use non iterating statement", m_state.labels_in_scope.get(identifier).value());
  794. }
  795. m_state.labels_in_scope.remove(identifier);
  796. return create_ast_node<LabelledStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier, labelled_item.release_nonnull());
  797. }
  798. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  799. {
  800. // Optimization which skips the save/load state.
  801. if (next_token().type() != TokenType::Period)
  802. return {};
  803. save_state();
  804. auto rule_start = push_start();
  805. ArmedScopeGuard state_rollback_guard = [&] {
  806. load_state();
  807. };
  808. consume(TokenType::New);
  809. consume(TokenType::Period);
  810. if (!match(TokenType::Identifier))
  811. return {};
  812. // The string 'target' cannot have escapes so we check original value.
  813. if (consume().original_value() != "target"sv)
  814. return {};
  815. state_rollback_guard.disarm();
  816. discard_saved_state();
  817. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::NewTarget);
  818. }
  819. RefPtr<MetaProperty> Parser::try_parse_import_meta_expression()
  820. {
  821. // Optimization which skips the save/load state.
  822. if (next_token().type() != TokenType::Period)
  823. return {};
  824. save_state();
  825. auto rule_start = push_start();
  826. ArmedScopeGuard state_rollback_guard = [&] {
  827. load_state();
  828. };
  829. consume(TokenType::Import);
  830. consume(TokenType::Period);
  831. if (!match(TokenType::Identifier))
  832. return {};
  833. // The string 'meta' cannot have escapes so we check original value.
  834. if (consume().original_value() != "meta"sv)
  835. return {};
  836. state_rollback_guard.disarm();
  837. discard_saved_state();
  838. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::ImportMeta);
  839. }
  840. NonnullRefPtr<ImportCall> Parser::parse_import_call()
  841. {
  842. auto rule_start = push_start();
  843. // We use the extended definition:
  844. // ImportCall[Yield, Await]:
  845. // import(AssignmentExpression[+In, ?Yield, ?Await] ,opt)
  846. // import(AssignmentExpression[+In, ?Yield, ?Await] ,AssignmentExpression[+In, ?Yield, ?Await] ,opt)
  847. // From https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  848. consume(TokenType::Import);
  849. consume(TokenType::ParenOpen);
  850. auto argument = parse_expression(2);
  851. RefPtr<Expression> options;
  852. if (match(TokenType::Comma)) {
  853. consume(TokenType::Comma);
  854. if (!match(TokenType::ParenClose)) {
  855. options = parse_expression(2);
  856. // Second optional comma
  857. if (match(TokenType::Comma))
  858. consume(TokenType::Comma);
  859. }
  860. }
  861. consume(TokenType::ParenClose);
  862. return create_ast_node<ImportCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), move(options));
  863. }
  864. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  865. {
  866. auto rule_start = push_start();
  867. return create_ast_node<ClassDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_class_expression(true));
  868. }
  869. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  870. {
  871. auto rule_start = push_start();
  872. // Classes are always in strict mode.
  873. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  874. consume(TokenType::Class);
  875. NonnullRefPtrVector<ClassElement> elements;
  876. RefPtr<Expression> super_class;
  877. RefPtr<FunctionExpression> constructor;
  878. HashTable<FlyString> found_private_names;
  879. String class_name = expect_class_name || match_identifier() || match(TokenType::Yield) || match(TokenType::Await)
  880. ? consume_identifier_reference().value().to_string()
  881. : "";
  882. check_identifier_name_for_assignment_validity(class_name, true);
  883. if (m_state.in_class_static_init_block && class_name == "await"sv)
  884. syntax_error("Identifier must not be a reserved word in modules ('await')");
  885. if (match(TokenType::Extends)) {
  886. consume();
  887. auto [expression, should_continue_parsing] = parse_primary_expression();
  888. // Basically a (much) simplified parse_secondary_expression().
  889. for (;;) {
  890. if (match(TokenType::TemplateLiteralStart)) {
  891. auto template_literal = parse_template_literal(true);
  892. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  893. continue;
  894. }
  895. if (match(TokenType::BracketOpen) || match(TokenType::Period) || match(TokenType::ParenOpen)) {
  896. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  897. expression = parse_secondary_expression(move(expression), precedence);
  898. continue;
  899. }
  900. break;
  901. }
  902. super_class = move(expression);
  903. (void)should_continue_parsing;
  904. }
  905. consume(TokenType::CurlyOpen);
  906. HashTable<StringView> referenced_private_names;
  907. HashTable<StringView>* outer_referenced_private_names = m_state.referenced_private_names;
  908. m_state.referenced_private_names = &referenced_private_names;
  909. ScopeGuard restore_private_name_table = [&] {
  910. m_state.referenced_private_names = outer_referenced_private_names;
  911. };
  912. while (!done() && !match(TokenType::CurlyClose)) {
  913. RefPtr<Expression> property_key;
  914. bool is_static = false;
  915. bool is_constructor = false;
  916. bool is_generator = false;
  917. bool is_async = false;
  918. auto method_kind = ClassMethod::Kind::Method;
  919. if (match(TokenType::Semicolon)) {
  920. consume();
  921. continue;
  922. }
  923. auto function_start = position();
  924. if (match(TokenType::Async)) {
  925. auto lookahead_token = next_token();
  926. if (lookahead_token.type() != TokenType::Semicolon && lookahead_token.type() != TokenType::CurlyClose
  927. && !lookahead_token.trivia_contains_line_terminator()) {
  928. consume();
  929. is_async = true;
  930. }
  931. }
  932. if (match(TokenType::Asterisk)) {
  933. consume();
  934. is_generator = true;
  935. }
  936. StringView name;
  937. if (match_property_key() || match(TokenType::PrivateIdentifier)) {
  938. if (!is_generator && !is_async && m_state.current_token.original_value() == "static"sv) {
  939. if (match(TokenType::Identifier)) {
  940. consume();
  941. is_static = true;
  942. function_start = position();
  943. if (match(TokenType::Async)) {
  944. consume();
  945. is_async = true;
  946. }
  947. if (match(TokenType::Asterisk)) {
  948. consume();
  949. is_generator = true;
  950. }
  951. }
  952. }
  953. if (match(TokenType::Identifier)) {
  954. auto identifier_name = m_state.current_token.original_value();
  955. if (identifier_name == "get"sv) {
  956. method_kind = ClassMethod::Kind::Getter;
  957. consume();
  958. } else if (identifier_name == "set"sv) {
  959. method_kind = ClassMethod::Kind::Setter;
  960. consume();
  961. }
  962. }
  963. if (match_property_key() || match(TokenType::PrivateIdentifier)) {
  964. switch (m_state.current_token.type()) {
  965. case TokenType::Identifier:
  966. name = consume().value();
  967. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  968. break;
  969. case TokenType::PrivateIdentifier:
  970. name = consume().value();
  971. if (name == "#constructor")
  972. syntax_error("Private property with name '#constructor' is not allowed");
  973. if (method_kind != ClassMethod::Kind::Method) {
  974. // It is a Syntax Error if PrivateBoundIdentifiers of ClassElementList contains any duplicate entries,
  975. // unless the name is used once for a getter and once for a setter and in no other entries,
  976. // and the getter and setter are either both static or both non-static.
  977. for (auto& element : elements) {
  978. auto private_name = element.private_bound_identifier();
  979. if (!private_name.has_value() || private_name.value() != name)
  980. continue;
  981. if (element.class_element_kind() != ClassElement::ElementKind::Method
  982. || element.is_static() != is_static) {
  983. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  984. break;
  985. }
  986. VERIFY(is<ClassMethod>(element));
  987. auto& class_method_element = static_cast<ClassMethod const&>(element);
  988. if (class_method_element.kind() == ClassMethod::Kind::Method || class_method_element.kind() == method_kind) {
  989. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  990. break;
  991. }
  992. }
  993. found_private_names.set(name);
  994. } else if (found_private_names.set(name) != AK::HashSetResult::InsertedNewEntry) {
  995. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  996. }
  997. property_key = create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  998. break;
  999. case TokenType::StringLiteral: {
  1000. auto string_literal = parse_string_literal(consume());
  1001. name = string_literal->value();
  1002. property_key = move(string_literal);
  1003. break;
  1004. }
  1005. default:
  1006. property_key = parse_property_key();
  1007. break;
  1008. }
  1009. // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors
  1010. // ClassElement : static MethodDefinition
  1011. // It is a Syntax Error if PropName of MethodDefinition is "prototype".
  1012. if (is_static && name == "prototype"sv)
  1013. syntax_error("Classes may not have a static property named 'prototype'");
  1014. } else if ((match(TokenType::ParenOpen) || match(TokenType::Equals) || match(TokenType::Semicolon) || match(TokenType::CurlyClose)) && (is_static || is_async || method_kind != ClassMethod::Kind::Method)) {
  1015. switch (method_kind) {
  1016. case ClassMethod::Kind::Method:
  1017. if (is_async) {
  1018. name = "async";
  1019. is_async = false;
  1020. } else {
  1021. VERIFY(is_static);
  1022. name = "static";
  1023. is_static = false;
  1024. }
  1025. break;
  1026. case ClassMethod::Kind::Getter:
  1027. name = "get";
  1028. method_kind = ClassMethod::Kind::Method;
  1029. break;
  1030. case ClassMethod::Kind::Setter:
  1031. name = "set";
  1032. method_kind = ClassMethod::Kind::Method;
  1033. break;
  1034. }
  1035. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  1036. } else if (match(TokenType::CurlyOpen) && is_static) {
  1037. auto static_start = push_start();
  1038. consume(TokenType::CurlyOpen);
  1039. auto static_init_block = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  1040. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  1041. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  1042. TemporaryChange function_context_rollback(m_state.in_function_context, false);
  1043. TemporaryChange generator_function_context_rollback(m_state.in_generator_function_context, false);
  1044. TemporaryChange async_function_context_rollback(m_state.await_expression_is_valid, false);
  1045. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, true);
  1046. TemporaryChange class_static_init_block_rollback(m_state.in_class_static_init_block, true);
  1047. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, true);
  1048. ScopePusher static_init_scope = ScopePusher::static_init_block_scope(*this, *static_init_block);
  1049. parse_statement_list(static_init_block);
  1050. consume(TokenType::CurlyClose);
  1051. elements.append(create_ast_node<StaticInitializer>({ m_state.current_token.filename(), static_start.position(), position() }, move(static_init_block), static_init_scope.contains_direct_call_to_eval()));
  1052. continue;
  1053. } else {
  1054. expected("property key");
  1055. }
  1056. // Constructor may be a StringLiteral or an Identifier.
  1057. if (!is_static && name == "constructor"sv) {
  1058. if (method_kind != ClassMethod::Kind::Method)
  1059. syntax_error("Class constructor may not be an accessor");
  1060. if (!constructor.is_null())
  1061. syntax_error("Classes may not have more than one constructor");
  1062. if (is_generator)
  1063. syntax_error("Class constructor may not be a generator");
  1064. if (is_async)
  1065. syntax_error("Class constructor may not be async");
  1066. is_constructor = true;
  1067. }
  1068. }
  1069. if (match(TokenType::ParenOpen)) {
  1070. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1071. if (!super_class.is_null() && !is_static && is_constructor)
  1072. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  1073. if (method_kind == ClassMethod::Kind::Getter)
  1074. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1075. if (method_kind == ClassMethod::Kind::Setter)
  1076. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1077. if (is_generator)
  1078. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1079. if (is_async)
  1080. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1081. auto function = parse_function_node<FunctionExpression>(parse_options, function_start);
  1082. if (is_constructor) {
  1083. constructor = move(function);
  1084. } else if (!property_key.is_null()) {
  1085. elements.append(create_ast_node<ClassMethod>({ m_state.current_token.filename(), rule_start.position(), position() }, property_key.release_nonnull(), move(function), method_kind, is_static));
  1086. } else {
  1087. syntax_error("No key for class method");
  1088. }
  1089. } else if (is_generator || is_async) {
  1090. expected("ParenOpen");
  1091. consume();
  1092. } else if (property_key.is_null()) {
  1093. expected("property key");
  1094. consume();
  1095. } else {
  1096. if (name == "constructor"sv)
  1097. syntax_error("Class cannot have field named 'constructor'");
  1098. RefPtr<Expression> initializer;
  1099. bool contains_direct_call_to_eval = false;
  1100. if (match(TokenType::Equals)) {
  1101. consume();
  1102. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, true);
  1103. TemporaryChange field_initializer_rollback(m_state.in_class_field_initializer, true);
  1104. auto class_field_scope = ScopePusher::class_field_scope(*this);
  1105. initializer = parse_expression(2);
  1106. contains_direct_call_to_eval = class_field_scope.contains_direct_call_to_eval();
  1107. }
  1108. elements.append(create_ast_node<ClassField>({ m_state.current_token.filename(), rule_start.position(), position() }, property_key.release_nonnull(), move(initializer), contains_direct_call_to_eval, is_static));
  1109. consume_or_insert_semicolon();
  1110. }
  1111. }
  1112. consume(TokenType::CurlyClose);
  1113. if (constructor.is_null()) {
  1114. auto constructor_body = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1115. if (!super_class.is_null()) {
  1116. // Set constructor to the result of parsing the source text
  1117. // constructor(... args){ super (...args);}
  1118. auto super_call = create_ast_node<SuperCall>(
  1119. { m_state.current_token.filename(), rule_start.position(), position() },
  1120. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  1121. // NOTE: While the JS approximation above doesn't do `return super(...args)`, the
  1122. // abstract closure is expected to capture and return the result, so we do need a
  1123. // return statement here to create the correct completion.
  1124. constructor_body->append(create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  1125. constructor = create_ast_node<FunctionExpression>(
  1126. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1127. move(constructor_body), Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Normal,
  1128. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1129. } else {
  1130. constructor = create_ast_node<FunctionExpression>(
  1131. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1132. move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Normal,
  1133. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1134. }
  1135. }
  1136. // We could be in a subclass defined within the main class so must move all non declared private names to outer.
  1137. for (auto& private_name : referenced_private_names) {
  1138. if (found_private_names.contains(private_name))
  1139. continue;
  1140. if (outer_referenced_private_names)
  1141. outer_referenced_private_names->set(private_name);
  1142. else // FIXME: Make these error appear in the appropriate places.
  1143. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", private_name));
  1144. }
  1145. auto function_start_offset = rule_start.position().offset;
  1146. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  1147. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  1148. return create_ast_node<ClassExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(class_name), move(source_text), move(constructor), move(super_class), move(elements));
  1149. }
  1150. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  1151. {
  1152. auto rule_start = push_start();
  1153. if (match_unary_prefixed_expression())
  1154. return { parse_unary_prefixed_expression() };
  1155. auto try_arrow_function_parse_or_fail = [this](Position const& position, bool expect_paren, bool is_async = false) -> RefPtr<FunctionExpression> {
  1156. if (try_parse_arrow_function_expression_failed_at_position(position))
  1157. return nullptr;
  1158. auto arrow_function = try_parse_arrow_function_expression(expect_paren, is_async);
  1159. if (arrow_function)
  1160. return arrow_function;
  1161. set_try_parse_arrow_function_expression_failed_at_position(position, true);
  1162. return nullptr;
  1163. };
  1164. switch (m_state.current_token.type()) {
  1165. case TokenType::ParenOpen: {
  1166. auto paren_position = position();
  1167. consume(TokenType::ParenOpen);
  1168. if ((match(TokenType::ParenClose) || match_identifier() || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))) {
  1169. if (auto arrow_function_result = try_arrow_function_parse_or_fail(paren_position, true))
  1170. return { arrow_function_result.release_nonnull(), false };
  1171. }
  1172. auto expression = parse_expression(0);
  1173. consume(TokenType::ParenClose);
  1174. if (is<FunctionExpression>(*expression)) {
  1175. auto& function = static_cast<FunctionExpression&>(*expression);
  1176. if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv)
  1177. syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start);
  1178. if (function.kind() == FunctionKind::Async && function.name() == "await"sv)
  1179. syntax_error("function is not allowed to be called 'await' in this context", function.source_range().start);
  1180. }
  1181. return { move(expression) };
  1182. }
  1183. case TokenType::This:
  1184. consume();
  1185. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1186. case TokenType::Class:
  1187. return { parse_class_expression(false) };
  1188. case TokenType::Super:
  1189. consume();
  1190. if (!m_state.allow_super_property_lookup)
  1191. syntax_error("'super' keyword unexpected here");
  1192. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1193. case TokenType::EscapedKeyword:
  1194. if (match_invalid_escaped_keyword())
  1195. syntax_error("Keyword must not contain escaped characters");
  1196. [[fallthrough]];
  1197. case TokenType::Identifier: {
  1198. read_as_identifier:;
  1199. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false))
  1200. return { arrow_function_result.release_nonnull(), false };
  1201. auto string = m_state.current_token.value();
  1202. // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`)
  1203. if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string)))
  1204. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string));
  1205. return { parse_identifier() };
  1206. }
  1207. case TokenType::NumericLiteral:
  1208. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  1209. case TokenType::BigIntLiteral:
  1210. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1211. case TokenType::BoolLiteral:
  1212. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  1213. case TokenType::StringLiteral:
  1214. return { parse_string_literal(consume()) };
  1215. case TokenType::NullLiteral:
  1216. consume();
  1217. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1218. case TokenType::CurlyOpen:
  1219. return { parse_object_expression() };
  1220. case TokenType::Async: {
  1221. auto lookahead_token = next_token();
  1222. // No valid async function (arrow or not) can have a line terminator after the async since asi would kick in.
  1223. if (lookahead_token.trivia_contains_line_terminator())
  1224. goto read_as_identifier;
  1225. if (lookahead_token.type() == TokenType::Function)
  1226. return { parse_function_node<FunctionExpression>() };
  1227. if (lookahead_token.type() == TokenType::ParenOpen) {
  1228. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), true, true))
  1229. return { arrow_function_result.release_nonnull(), false };
  1230. } else if (lookahead_token.is_identifier_name()) {
  1231. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false, true))
  1232. return { arrow_function_result.release_nonnull(), false };
  1233. }
  1234. goto read_as_identifier;
  1235. }
  1236. case TokenType::Function:
  1237. return { parse_function_node<FunctionExpression>() };
  1238. case TokenType::BracketOpen:
  1239. return { parse_array_expression() };
  1240. case TokenType::RegexLiteral:
  1241. return { parse_regexp_literal() };
  1242. case TokenType::TemplateLiteralStart:
  1243. return { parse_template_literal(false) };
  1244. case TokenType::New: {
  1245. auto new_start = position();
  1246. auto new_target_result = try_parse_new_target_expression();
  1247. if (!new_target_result.is_null()) {
  1248. if (!m_state.in_function_context && !m_state.in_class_static_init_block)
  1249. syntax_error("'new.target' not allowed outside of a function", new_start);
  1250. return { new_target_result.release_nonnull() };
  1251. }
  1252. return { parse_new_expression() };
  1253. }
  1254. case TokenType::Import: {
  1255. auto lookahead_token = next_token();
  1256. if (lookahead_token.type() == TokenType::ParenOpen)
  1257. return { parse_import_call() };
  1258. if (lookahead_token.type() == TokenType::Period) {
  1259. if (auto import_meta = try_parse_import_meta_expression()) {
  1260. if (m_program_type != Program::Type::Module)
  1261. syntax_error("import.meta is only allowed in modules");
  1262. return { import_meta.release_nonnull() };
  1263. }
  1264. } else {
  1265. consume();
  1266. expected("import.meta or import call");
  1267. }
  1268. break;
  1269. }
  1270. case TokenType::Yield:
  1271. if (!m_state.in_generator_function_context)
  1272. goto read_as_identifier;
  1273. return { parse_yield_expression(), false };
  1274. case TokenType::Await:
  1275. if (!m_state.await_expression_is_valid)
  1276. goto read_as_identifier;
  1277. return { parse_await_expression() };
  1278. case TokenType::PrivateIdentifier:
  1279. if (next_token().type() != TokenType::In)
  1280. syntax_error("Cannot have a private identifier in expression if not followed by 'in'");
  1281. if (!is_private_identifier_valid())
  1282. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1283. return { create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1284. default:
  1285. if (match_identifier_name())
  1286. goto read_as_identifier;
  1287. break;
  1288. }
  1289. expected("primary expression");
  1290. consume();
  1291. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1292. }
  1293. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  1294. {
  1295. auto rule_start = push_start();
  1296. auto pattern = consume().value();
  1297. // Remove leading and trailing slash.
  1298. pattern = pattern.substring_view(1, pattern.length() - 2);
  1299. auto flags = String::empty();
  1300. auto parsed_flags = RegExpObject::default_flags;
  1301. if (match(TokenType::RegexFlags)) {
  1302. auto flags_start = position();
  1303. flags = consume().value();
  1304. auto parsed_flags_or_error = regex_flags_from_string(flags);
  1305. if (parsed_flags_or_error.is_error())
  1306. syntax_error(parsed_flags_or_error.release_error(), flags_start);
  1307. else
  1308. parsed_flags = parsed_flags_or_error.release_value();
  1309. }
  1310. auto parsed_pattern = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode));
  1311. auto parsed_regex = Regex<ECMA262>::parse_pattern(parsed_pattern, parsed_flags);
  1312. if (parsed_regex.error != regex::Error::NoError)
  1313. syntax_error(String::formatted("RegExp compile error: {}", Regex<ECMA262>(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position());
  1314. SourceRange range { m_state.current_token.filename(), rule_start.position(), position() };
  1315. return create_ast_node<RegExpLiteral>(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_string(), move(flags));
  1316. }
  1317. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  1318. {
  1319. auto rule_start = push_start();
  1320. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  1321. auto associativity = operator_associativity(m_state.current_token.type());
  1322. switch (m_state.current_token.type()) {
  1323. case TokenType::PlusPlus: {
  1324. consume();
  1325. auto rhs_start = position();
  1326. auto rhs = parse_expression(precedence, associativity);
  1327. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1328. // other engines throw ReferenceError for ++foo()
  1329. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1330. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1331. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1332. auto& identifier = static_cast<Identifier&>(*rhs);
  1333. auto& name = identifier.string();
  1334. check_identifier_name_for_assignment_validity(name);
  1335. }
  1336. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  1337. }
  1338. case TokenType::MinusMinus: {
  1339. consume();
  1340. auto rhs_start = position();
  1341. auto rhs = parse_expression(precedence, associativity);
  1342. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1343. // other engines throw ReferenceError for --foo()
  1344. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1345. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1346. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1347. auto& identifier = static_cast<Identifier&>(*rhs);
  1348. auto& name = identifier.string();
  1349. check_identifier_name_for_assignment_validity(name);
  1350. }
  1351. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  1352. }
  1353. case TokenType::ExclamationMark:
  1354. consume();
  1355. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  1356. case TokenType::Tilde:
  1357. consume();
  1358. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  1359. case TokenType::Plus:
  1360. consume();
  1361. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  1362. case TokenType::Minus:
  1363. consume();
  1364. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  1365. case TokenType::Typeof:
  1366. consume();
  1367. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  1368. case TokenType::Void:
  1369. consume();
  1370. // FIXME: This check is really hiding the fact that we don't deal with different expressions correctly.
  1371. if (match(TokenType::Yield) && m_state.in_generator_function_context)
  1372. syntax_error("'yield' is not an identifier in generator function context");
  1373. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  1374. case TokenType::Delete: {
  1375. consume();
  1376. auto rhs_start = position();
  1377. auto rhs = parse_expression(precedence, associativity);
  1378. if (is<Identifier>(*rhs) && m_state.strict_mode) {
  1379. syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start);
  1380. }
  1381. if (is<MemberExpression>(*rhs)) {
  1382. auto& member_expression = static_cast<MemberExpression const&>(*rhs);
  1383. if (member_expression.ends_in_private_name())
  1384. syntax_error("Private fields cannot be deleted");
  1385. }
  1386. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, move(rhs));
  1387. }
  1388. default:
  1389. expected("primary expression");
  1390. consume();
  1391. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1392. }
  1393. }
  1394. NonnullRefPtr<Expression> Parser::parse_property_key()
  1395. {
  1396. auto rule_start = push_start();
  1397. if (match(TokenType::StringLiteral)) {
  1398. return parse_string_literal(consume());
  1399. } else if (match(TokenType::NumericLiteral)) {
  1400. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  1401. } else if (match(TokenType::BigIntLiteral)) {
  1402. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1403. } else if (match(TokenType::BracketOpen)) {
  1404. consume(TokenType::BracketOpen);
  1405. auto result = parse_expression(2);
  1406. consume(TokenType::BracketClose);
  1407. return result;
  1408. } else {
  1409. if (!match_identifier_name())
  1410. expected("IdentifierName");
  1411. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1412. }
  1413. }
  1414. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  1415. {
  1416. auto rule_start = push_start();
  1417. consume(TokenType::CurlyOpen);
  1418. NonnullRefPtrVector<ObjectProperty> properties;
  1419. ObjectProperty::Type property_type;
  1420. Optional<SourceRange> invalid_object_literal_property_range;
  1421. auto skip_to_next_property = [&] {
  1422. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  1423. consume();
  1424. };
  1425. // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate
  1426. // entries for "__proto__" and at least two of those entries were obtained from productions of
  1427. // the form PropertyDefinition : PropertyKey : AssignmentExpression .
  1428. bool has_direct_proto_property = false;
  1429. while (!done() && !match(TokenType::CurlyClose)) {
  1430. property_type = ObjectProperty::Type::KeyValue;
  1431. RefPtr<Expression> property_name;
  1432. RefPtr<Expression> property_value;
  1433. FunctionKind function_kind { FunctionKind::Normal };
  1434. if (match(TokenType::TripleDot)) {
  1435. consume();
  1436. property_name = parse_expression(4);
  1437. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, nullptr, ObjectProperty::Type::Spread, false));
  1438. if (!match(TokenType::Comma))
  1439. break;
  1440. consume(TokenType::Comma);
  1441. continue;
  1442. }
  1443. auto type = m_state.current_token.type();
  1444. auto function_start = position();
  1445. if (match(TokenType::Async)) {
  1446. auto lookahead_token = next_token();
  1447. if (lookahead_token.type() != TokenType::ParenOpen && lookahead_token.type() != TokenType::Colon
  1448. && lookahead_token.type() != TokenType::Comma && lookahead_token.type() != TokenType::CurlyClose
  1449. && lookahead_token.type() != TokenType::Async
  1450. && !lookahead_token.trivia_contains_line_terminator()) {
  1451. consume(TokenType::Async);
  1452. function_kind = FunctionKind::Async;
  1453. }
  1454. }
  1455. if (match(TokenType::Asterisk)) {
  1456. consume();
  1457. property_type = ObjectProperty::Type::KeyValue;
  1458. property_name = parse_property_key();
  1459. VERIFY(function_kind == FunctionKind::Normal || function_kind == FunctionKind::Async);
  1460. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  1461. } else if (match_identifier()) {
  1462. auto identifier = consume();
  1463. if (identifier.original_value() == "get"sv && match_property_key()) {
  1464. property_type = ObjectProperty::Type::Getter;
  1465. property_name = parse_property_key();
  1466. } else if (identifier.original_value() == "set"sv && match_property_key()) {
  1467. property_type = ObjectProperty::Type::Setter;
  1468. property_name = parse_property_key();
  1469. } else {
  1470. property_name = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1471. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1472. }
  1473. } else {
  1474. property_name = parse_property_key();
  1475. }
  1476. bool is_proto = (type == TokenType::StringLiteral || type == TokenType::Identifier) && is<StringLiteral>(*property_name) && static_cast<StringLiteral const&>(*property_name).value() == "__proto__";
  1477. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  1478. if (!match(TokenType::ParenOpen)) {
  1479. expected("'(' for object getter or setter property");
  1480. skip_to_next_property();
  1481. continue;
  1482. }
  1483. }
  1484. if (match(TokenType::Equals)) {
  1485. // Not a valid object literal, but a valid assignment target
  1486. consume();
  1487. // Parse the expression and throw it away
  1488. auto expression = parse_expression(2);
  1489. if (!invalid_object_literal_property_range.has_value())
  1490. invalid_object_literal_property_range = expression->source_range();
  1491. } else if (match(TokenType::ParenOpen)) {
  1492. VERIFY(property_name);
  1493. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1494. if (property_type == ObjectProperty::Type::Getter)
  1495. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1496. if (property_type == ObjectProperty::Type::Setter)
  1497. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1498. if (function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator)
  1499. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1500. if (function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator)
  1501. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1502. auto function = parse_function_node<FunctionExpression>(parse_options, function_start);
  1503. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, function, property_type, true));
  1504. } else if (match(TokenType::Colon)) {
  1505. if (!property_name) {
  1506. expected("a property name");
  1507. skip_to_next_property();
  1508. continue;
  1509. }
  1510. consume();
  1511. if (is_proto) {
  1512. if (has_direct_proto_property)
  1513. syntax_error("Property name '__proto__' must not appear more than once in object literal");
  1514. has_direct_proto_property = true;
  1515. }
  1516. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, parse_expression(2), property_type, false));
  1517. } else if (property_name && property_value) {
  1518. if (m_state.strict_mode && is<StringLiteral>(*property_name)) {
  1519. auto& string_literal = static_cast<StringLiteral const&>(*property_name);
  1520. if (is_strict_reserved_word(string_literal.value()))
  1521. syntax_error(String::formatted("'{}' is a reserved keyword", string_literal.value()));
  1522. }
  1523. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, *property_value, property_type, false));
  1524. } else {
  1525. expected("a property");
  1526. skip_to_next_property();
  1527. continue;
  1528. }
  1529. if (!match(TokenType::Comma))
  1530. break;
  1531. consume(TokenType::Comma);
  1532. }
  1533. consume(TokenType::CurlyClose);
  1534. return create_ast_node<ObjectExpression>(
  1535. { m_state.current_token.filename(), rule_start.position(), position() },
  1536. move(properties),
  1537. move(invalid_object_literal_property_range));
  1538. }
  1539. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  1540. {
  1541. auto rule_start = push_start();
  1542. consume(TokenType::BracketOpen);
  1543. Vector<RefPtr<Expression>> elements;
  1544. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  1545. RefPtr<Expression> expression;
  1546. if (match(TokenType::TripleDot)) {
  1547. consume(TokenType::TripleDot);
  1548. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  1549. } else if (match_expression()) {
  1550. expression = parse_expression(2);
  1551. }
  1552. elements.append(expression);
  1553. if (!match(TokenType::Comma))
  1554. break;
  1555. consume(TokenType::Comma);
  1556. }
  1557. consume(TokenType::BracketClose);
  1558. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  1559. }
  1560. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(const Token& token, bool in_template_literal)
  1561. {
  1562. auto rule_start = push_start();
  1563. auto status = Token::StringValueStatus::Ok;
  1564. auto string = token.string_value(status);
  1565. if (status != Token::StringValueStatus::Ok) {
  1566. String message;
  1567. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  1568. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  1569. if (in_template_literal)
  1570. message = "Octal escape sequence not allowed in template literal";
  1571. else if (m_state.strict_mode)
  1572. message = "Octal escape sequence in string literal not allowed in strict mode";
  1573. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  1574. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  1575. message = String::formatted("Malformed {} escape sequence", type);
  1576. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  1577. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  1578. } else {
  1579. VERIFY_NOT_REACHED();
  1580. }
  1581. if (!message.is_empty())
  1582. syntax_error(message, Position { token.line_number(), token.line_column() });
  1583. }
  1584. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  1585. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  1586. }
  1587. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  1588. {
  1589. auto rule_start = push_start();
  1590. consume(TokenType::TemplateLiteralStart);
  1591. NonnullRefPtrVector<Expression> expressions;
  1592. NonnullRefPtrVector<Expression> raw_strings;
  1593. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  1594. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  1595. expressions.append(string_literal);
  1596. if (is_tagged)
  1597. raw_strings.append(string_literal);
  1598. };
  1599. if (!match(TokenType::TemplateLiteralString))
  1600. append_empty_string();
  1601. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  1602. if (match(TokenType::TemplateLiteralString)) {
  1603. auto token = consume();
  1604. expressions.append(parse_string_literal(token, true));
  1605. if (is_tagged)
  1606. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.raw_template_value()));
  1607. } else if (match(TokenType::TemplateLiteralExprStart)) {
  1608. consume(TokenType::TemplateLiteralExprStart);
  1609. if (match(TokenType::TemplateLiteralExprEnd)) {
  1610. syntax_error("Empty template literal expression block");
  1611. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1612. }
  1613. expressions.append(parse_expression(0));
  1614. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1615. syntax_error("Unterminated template literal");
  1616. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1617. }
  1618. consume(TokenType::TemplateLiteralExprEnd);
  1619. if (!match(TokenType::TemplateLiteralString))
  1620. append_empty_string();
  1621. } else {
  1622. expected("Template literal string or expression");
  1623. break;
  1624. }
  1625. }
  1626. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1627. syntax_error("Unterminated template literal");
  1628. } else {
  1629. consume(TokenType::TemplateLiteralEnd);
  1630. }
  1631. if (is_tagged)
  1632. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  1633. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1634. }
  1635. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, const Vector<TokenType>& forbidden)
  1636. {
  1637. auto rule_start = push_start();
  1638. auto [expression, should_continue_parsing] = parse_primary_expression();
  1639. auto check_for_invalid_object_property = [&](auto& expression) {
  1640. if (is<ObjectExpression>(*expression)) {
  1641. if (auto range = static_cast<ObjectExpression&>(*expression).invalid_property_range(); range.has_value())
  1642. syntax_error("Invalid property in object literal", range->start);
  1643. }
  1644. };
  1645. if (is<Identifier>(*expression) && m_state.current_scope_pusher) {
  1646. auto identifier_instance = static_ptr_cast<Identifier>(expression);
  1647. auto function_scope = m_state.current_scope_pusher->last_function_scope();
  1648. auto function_parent_scope = function_scope ? function_scope->parent_scope() : nullptr;
  1649. bool has_not_been_declared_as_variable = true;
  1650. for (auto scope = m_state.current_scope_pusher; scope != function_parent_scope; scope = scope->parent_scope()) {
  1651. if (scope->has_declaration(identifier_instance->string())) {
  1652. has_not_been_declared_as_variable = false;
  1653. break;
  1654. }
  1655. }
  1656. if (has_not_been_declared_as_variable) {
  1657. if (identifier_instance->string() == "arguments"sv)
  1658. m_state.current_scope_pusher->set_contains_access_to_arguments_object();
  1659. }
  1660. }
  1661. while (match(TokenType::TemplateLiteralStart)) {
  1662. auto template_literal = parse_template_literal(true);
  1663. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1664. }
  1665. if (should_continue_parsing) {
  1666. while (match_secondary_expression(forbidden)) {
  1667. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  1668. if (new_precedence < min_precedence)
  1669. break;
  1670. if (new_precedence == min_precedence && associativity == Associativity::Left)
  1671. break;
  1672. check_for_invalid_object_property(expression);
  1673. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  1674. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  1675. while (match(TokenType::TemplateLiteralStart) && !is<UpdateExpression>(*expression)) {
  1676. auto template_literal = parse_template_literal(true);
  1677. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1678. }
  1679. }
  1680. }
  1681. if (is<SuperExpression>(*expression))
  1682. syntax_error("'super' keyword unexpected here");
  1683. check_for_invalid_object_property(expression);
  1684. if (is<CallExpression>(*expression) && m_state.current_scope_pusher) {
  1685. auto& callee = static_ptr_cast<CallExpression>(expression)->callee();
  1686. if (is<Identifier>(callee)) {
  1687. auto& identifier_instance = static_cast<Identifier const&>(callee);
  1688. if (identifier_instance.string() == "eval"sv) {
  1689. bool has_not_been_declared_as_variable = true;
  1690. for (auto scope = m_state.current_scope_pusher; scope; scope = scope->parent_scope()) {
  1691. if (scope->has_declaration(identifier_instance.string())) {
  1692. has_not_been_declared_as_variable = false;
  1693. break;
  1694. }
  1695. }
  1696. if (has_not_been_declared_as_variable)
  1697. m_state.current_scope_pusher->set_contains_direct_call_to_eval();
  1698. }
  1699. }
  1700. }
  1701. if (match(TokenType::Comma) && min_precedence <= 1) {
  1702. NonnullRefPtrVector<Expression> expressions;
  1703. expressions.append(expression);
  1704. while (match(TokenType::Comma)) {
  1705. consume();
  1706. expressions.append(parse_expression(2));
  1707. }
  1708. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  1709. }
  1710. return expression;
  1711. }
  1712. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1713. {
  1714. auto rule_start = push_start();
  1715. switch (m_state.current_token.type()) {
  1716. case TokenType::Plus:
  1717. consume();
  1718. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  1719. case TokenType::PlusEquals:
  1720. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  1721. case TokenType::Minus:
  1722. consume();
  1723. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  1724. case TokenType::MinusEquals:
  1725. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  1726. case TokenType::Asterisk:
  1727. consume();
  1728. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  1729. case TokenType::AsteriskEquals:
  1730. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  1731. case TokenType::Slash:
  1732. consume();
  1733. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  1734. case TokenType::SlashEquals:
  1735. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  1736. case TokenType::Percent:
  1737. consume();
  1738. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  1739. case TokenType::PercentEquals:
  1740. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  1741. case TokenType::DoubleAsterisk:
  1742. consume();
  1743. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  1744. case TokenType::DoubleAsteriskEquals:
  1745. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  1746. case TokenType::GreaterThan:
  1747. consume();
  1748. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  1749. case TokenType::GreaterThanEquals:
  1750. consume();
  1751. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1752. case TokenType::LessThan:
  1753. consume();
  1754. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  1755. case TokenType::LessThanEquals:
  1756. consume();
  1757. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1758. case TokenType::EqualsEqualsEquals:
  1759. consume();
  1760. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyEquals, move(lhs), parse_expression(min_precedence, associativity));
  1761. case TokenType::ExclamationMarkEqualsEquals:
  1762. consume();
  1763. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyInequals, move(lhs), parse_expression(min_precedence, associativity));
  1764. case TokenType::EqualsEquals:
  1765. consume();
  1766. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyEquals, move(lhs), parse_expression(min_precedence, associativity));
  1767. case TokenType::ExclamationMarkEquals:
  1768. consume();
  1769. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyInequals, move(lhs), parse_expression(min_precedence, associativity));
  1770. case TokenType::In:
  1771. consume();
  1772. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1773. case TokenType::Instanceof:
  1774. consume();
  1775. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  1776. case TokenType::Ampersand:
  1777. consume();
  1778. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  1779. case TokenType::AmpersandEquals:
  1780. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  1781. case TokenType::Pipe:
  1782. consume();
  1783. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  1784. case TokenType::PipeEquals:
  1785. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  1786. case TokenType::Caret:
  1787. consume();
  1788. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  1789. case TokenType::CaretEquals:
  1790. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  1791. case TokenType::ShiftLeft:
  1792. consume();
  1793. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  1794. case TokenType::ShiftLeftEquals:
  1795. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  1796. case TokenType::ShiftRight:
  1797. consume();
  1798. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  1799. case TokenType::ShiftRightEquals:
  1800. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  1801. case TokenType::UnsignedShiftRight:
  1802. consume();
  1803. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  1804. case TokenType::UnsignedShiftRightEquals:
  1805. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  1806. case TokenType::ParenOpen:
  1807. return parse_call_expression(move(lhs));
  1808. case TokenType::Equals:
  1809. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  1810. case TokenType::Period:
  1811. consume();
  1812. if (match(TokenType::PrivateIdentifier)) {
  1813. if (!is_private_identifier_valid())
  1814. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1815. else if (is<SuperExpression>(*lhs))
  1816. syntax_error(String::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value()));
  1817. return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()));
  1818. } else if (!match_identifier_name()) {
  1819. expected("IdentifierName");
  1820. }
  1821. return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()));
  1822. case TokenType::BracketOpen: {
  1823. consume(TokenType::BracketOpen);
  1824. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1825. consume(TokenType::BracketClose);
  1826. return expression;
  1827. }
  1828. case TokenType::PlusPlus:
  1829. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1830. // other engines throw ReferenceError for foo()++
  1831. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1832. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1833. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1834. auto& identifier = static_cast<Identifier&>(*lhs);
  1835. auto& name = identifier.string();
  1836. check_identifier_name_for_assignment_validity(name);
  1837. }
  1838. consume();
  1839. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1840. case TokenType::MinusMinus:
  1841. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1842. // other engines throw ReferenceError for foo()--
  1843. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1844. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1845. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1846. auto& identifier = static_cast<Identifier&>(*lhs);
  1847. auto& name = identifier.string();
  1848. check_identifier_name_for_assignment_validity(name);
  1849. }
  1850. consume();
  1851. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1852. case TokenType::DoubleAmpersand:
  1853. consume();
  1854. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1855. case TokenType::DoubleAmpersandEquals:
  1856. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1857. case TokenType::DoublePipe:
  1858. consume();
  1859. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1860. case TokenType::DoublePipeEquals:
  1861. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1862. case TokenType::DoubleQuestionMark:
  1863. consume();
  1864. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1865. case TokenType::DoubleQuestionMarkEquals:
  1866. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1867. case TokenType::QuestionMark:
  1868. return parse_conditional_expression(move(lhs));
  1869. case TokenType::QuestionMarkPeriod:
  1870. // FIXME: This should allow `(new Foo)?.bar', but as our parser strips parenthesis,
  1871. // we can't really tell if `lhs' was parenthesized at this point.
  1872. if (is<NewExpression>(lhs.ptr())) {
  1873. syntax_error("'new' cannot be used with optional chaining", position());
  1874. consume();
  1875. return lhs;
  1876. }
  1877. return parse_optional_chain(move(lhs));
  1878. default:
  1879. expected("secondary expression");
  1880. consume();
  1881. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1882. }
  1883. }
  1884. bool Parser::is_private_identifier_valid() const
  1885. {
  1886. VERIFY(match(TokenType::PrivateIdentifier));
  1887. if (!m_state.referenced_private_names)
  1888. return false;
  1889. // We might not have hit the declaration yet so class will check this in the end
  1890. m_state.referenced_private_names->set(m_state.current_token.value());
  1891. return true;
  1892. }
  1893. RefPtr<BindingPattern> Parser::synthesize_binding_pattern(Expression const& expression)
  1894. {
  1895. VERIFY(is<ArrayExpression>(expression) || is<ObjectExpression>(expression));
  1896. // Clear any syntax error that has occurred in the range that 'expression' spans.
  1897. m_state.errors.remove_all_matching([range = expression.source_range()](auto const& error) {
  1898. return error.position.has_value() && range.contains(*error.position);
  1899. });
  1900. // Make a parser and parse the source for this expression as a binding pattern.
  1901. // NOTE: There's currently a fundamental problem that we pass the *next* (a.k.a. `current_token`)
  1902. // token's position to most nodes' SourceRange when using `rule_start.position(), position()`.
  1903. // This means that `source` will contain the subsequent token's trivia, if any (which is fine).
  1904. auto source_start_offset = expression.source_range().start.offset;
  1905. auto source_end_offset = expression.source_range().end.offset;
  1906. auto source = m_state.lexer.source().substring_view(source_start_offset, source_end_offset - source_start_offset);
  1907. Lexer lexer { source, m_state.lexer.filename(), expression.source_range().start.line, expression.source_range().start.column };
  1908. Parser parser { lexer };
  1909. parser.m_state.strict_mode = m_state.strict_mode;
  1910. parser.m_state.allow_super_property_lookup = m_state.allow_super_property_lookup;
  1911. parser.m_state.allow_super_constructor_call = m_state.allow_super_constructor_call;
  1912. parser.m_state.in_function_context = m_state.in_function_context;
  1913. parser.m_state.in_formal_parameter_context = m_state.in_formal_parameter_context;
  1914. parser.m_state.in_generator_function_context = m_state.in_generator_function_context;
  1915. parser.m_state.await_expression_is_valid = m_state.await_expression_is_valid;
  1916. parser.m_state.in_arrow_function_context = m_state.in_arrow_function_context;
  1917. parser.m_state.in_break_context = m_state.in_break_context;
  1918. parser.m_state.in_continue_context = m_state.in_continue_context;
  1919. parser.m_state.string_legacy_octal_escape_sequence_in_scope = m_state.string_legacy_octal_escape_sequence_in_scope;
  1920. parser.m_state.in_class_field_initializer = m_state.in_class_field_initializer;
  1921. parser.m_state.in_class_static_init_block = m_state.in_class_static_init_block;
  1922. parser.m_state.referenced_private_names = m_state.referenced_private_names;
  1923. auto result = parser.parse_binding_pattern(AllowDuplicates::Yes, AllowMemberExpressions::Yes);
  1924. if (parser.has_errors())
  1925. m_state.errors.extend(parser.errors());
  1926. return result;
  1927. }
  1928. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1929. {
  1930. auto rule_start = push_start();
  1931. VERIFY(match(TokenType::Equals)
  1932. || match(TokenType::PlusEquals)
  1933. || match(TokenType::MinusEquals)
  1934. || match(TokenType::AsteriskEquals)
  1935. || match(TokenType::SlashEquals)
  1936. || match(TokenType::PercentEquals)
  1937. || match(TokenType::DoubleAsteriskEquals)
  1938. || match(TokenType::AmpersandEquals)
  1939. || match(TokenType::PipeEquals)
  1940. || match(TokenType::CaretEquals)
  1941. || match(TokenType::ShiftLeftEquals)
  1942. || match(TokenType::ShiftRightEquals)
  1943. || match(TokenType::UnsignedShiftRightEquals)
  1944. || match(TokenType::DoubleAmpersandEquals)
  1945. || match(TokenType::DoublePipeEquals)
  1946. || match(TokenType::DoubleQuestionMarkEquals));
  1947. consume();
  1948. if (assignment_op == AssignmentOp::Assignment) {
  1949. if (is<ArrayExpression>(*lhs) || is<ObjectExpression>(*lhs)) {
  1950. auto binding_pattern = synthesize_binding_pattern(*lhs);
  1951. if (binding_pattern) {
  1952. auto rhs = parse_expression(min_precedence, associativity);
  1953. return create_ast_node<AssignmentExpression>(
  1954. { m_state.current_token.filename(), rule_start.position(), position() },
  1955. assignment_op,
  1956. binding_pattern.release_nonnull(),
  1957. move(rhs));
  1958. }
  1959. }
  1960. }
  1961. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1962. syntax_error("Invalid left-hand side in assignment");
  1963. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1964. auto name = static_cast<const Identifier&>(*lhs).string();
  1965. check_identifier_name_for_assignment_validity(name);
  1966. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1967. syntax_error("Cannot assign to function call");
  1968. }
  1969. auto rhs = parse_expression(min_precedence, associativity);
  1970. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1971. }
  1972. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1973. {
  1974. auto identifier_start = position();
  1975. auto token = consume_identifier();
  1976. if (m_state.in_class_field_initializer && token.value() == "arguments"sv)
  1977. syntax_error("'arguments' is not allowed in class field initializer");
  1978. return create_ast_node<Identifier>(
  1979. { m_state.current_token.filename(), identifier_start, position() },
  1980. token.value());
  1981. }
  1982. Vector<CallExpression::Argument> Parser::parse_arguments()
  1983. {
  1984. Vector<CallExpression::Argument> arguments;
  1985. consume(TokenType::ParenOpen);
  1986. while (match_expression() || match(TokenType::TripleDot)) {
  1987. if (match(TokenType::TripleDot)) {
  1988. consume();
  1989. arguments.append({ parse_expression(2), true });
  1990. } else {
  1991. arguments.append({ parse_expression(2), false });
  1992. }
  1993. if (!match(TokenType::Comma))
  1994. break;
  1995. consume();
  1996. }
  1997. consume(TokenType::ParenClose);
  1998. return arguments;
  1999. }
  2000. NonnullRefPtr<Expression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  2001. {
  2002. auto rule_start = push_start();
  2003. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  2004. syntax_error("'super' keyword unexpected here");
  2005. auto arguments = parse_arguments();
  2006. if (is<SuperExpression>(*lhs))
  2007. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  2008. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  2009. }
  2010. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  2011. {
  2012. auto rule_start = push_start();
  2013. consume(TokenType::New);
  2014. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod });
  2015. if (is<ImportCall>(*callee))
  2016. syntax_error("Cannot call new on dynamic import", callee->source_range().start);
  2017. Vector<CallExpression::Argument> arguments;
  2018. if (match(TokenType::ParenOpen)) {
  2019. consume(TokenType::ParenOpen);
  2020. while (match_expression() || match(TokenType::TripleDot)) {
  2021. if (match(TokenType::TripleDot)) {
  2022. consume();
  2023. arguments.append({ parse_expression(2), true });
  2024. } else {
  2025. arguments.append({ parse_expression(2), false });
  2026. }
  2027. if (!match(TokenType::Comma))
  2028. break;
  2029. consume();
  2030. }
  2031. consume(TokenType::ParenClose);
  2032. }
  2033. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  2034. }
  2035. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  2036. {
  2037. auto rule_start = push_start();
  2038. if (m_state.in_formal_parameter_context)
  2039. syntax_error("'Yield' expression is not allowed in formal parameters of generator function");
  2040. consume(TokenType::Yield);
  2041. RefPtr<Expression> argument;
  2042. bool yield_from = false;
  2043. if (!m_state.current_token.trivia_contains_line_terminator()) {
  2044. if (match(TokenType::Asterisk)) {
  2045. consume();
  2046. yield_from = true;
  2047. }
  2048. if (yield_from || match_expression() || match(TokenType::Class))
  2049. argument = parse_expression(2);
  2050. }
  2051. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  2052. }
  2053. NonnullRefPtr<AwaitExpression> Parser::parse_await_expression()
  2054. {
  2055. auto rule_start = push_start();
  2056. if (m_state.in_formal_parameter_context)
  2057. syntax_error("'Await' expression is not allowed in formal parameters of an async function");
  2058. consume(TokenType::Await);
  2059. auto precedence = g_operator_precedence.get(TokenType::Await);
  2060. auto associativity = operator_associativity(TokenType::Await);
  2061. auto argument = parse_expression(precedence, associativity);
  2062. m_state.current_scope_pusher->set_contains_await_expression();
  2063. return create_ast_node<AwaitExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument));
  2064. }
  2065. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  2066. {
  2067. auto rule_start = push_start();
  2068. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  2069. syntax_error("'return' not allowed outside of a function");
  2070. consume(TokenType::Return);
  2071. // Automatic semicolon insertion: terminate statement when return is followed by newline
  2072. if (m_state.current_token.trivia_contains_line_terminator())
  2073. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2074. if (match_expression()) {
  2075. auto expression = parse_expression(0);
  2076. consume_or_insert_semicolon();
  2077. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2078. }
  2079. consume_or_insert_semicolon();
  2080. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2081. }
  2082. void Parser::parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions)
  2083. {
  2084. while (!done()) {
  2085. if (match_declaration()) {
  2086. auto declaration = parse_declaration();
  2087. VERIFY(m_state.current_scope_pusher);
  2088. m_state.current_scope_pusher->add_declaration(declaration);
  2089. output_node.append(move(declaration));
  2090. } else if (match_statement()) {
  2091. output_node.append(parse_statement(allow_labelled_functions));
  2092. } else {
  2093. break;
  2094. }
  2095. }
  2096. }
  2097. // FunctionBody, https://tc39.es/ecma262/#prod-FunctionBody
  2098. NonnullRefPtr<FunctionBody> Parser::parse_function_body(Vector<FunctionDeclaration::Parameter> const& parameters, FunctionKind function_kind, bool& contains_direct_call_to_eval)
  2099. {
  2100. auto rule_start = push_start();
  2101. auto function_body = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  2102. ScopePusher function_scope = ScopePusher::function_scope(*this, function_body, parameters); // FIXME <-
  2103. auto has_use_strict = parse_directive(function_body);
  2104. bool previous_strict_mode = m_state.strict_mode;
  2105. if (has_use_strict) {
  2106. m_state.strict_mode = true;
  2107. function_body->set_strict_mode();
  2108. if (!is_simple_parameter_list(parameters))
  2109. syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");
  2110. } else if (previous_strict_mode) {
  2111. function_body->set_strict_mode();
  2112. }
  2113. parse_statement_list(function_body);
  2114. // If we're parsing the function body standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2115. // Otherwise, we need a closing curly bracket (which is consumed elsewhere). If we get neither, it's an error.
  2116. if (!match(TokenType::Eof) && !match(TokenType::CurlyClose))
  2117. expected(Token::name(TokenType::CurlyClose));
  2118. // If the function contains 'use strict' we need to check the parameters (again).
  2119. if (function_body->in_strict_mode() || function_kind != FunctionKind::Normal) {
  2120. Vector<StringView> parameter_names;
  2121. for (auto& parameter : parameters) {
  2122. parameter.binding.visit(
  2123. [&](FlyString const& parameter_name) {
  2124. check_identifier_name_for_assignment_validity(parameter_name, function_body->in_strict_mode());
  2125. if (function_kind == FunctionKind::Generator && parameter_name == "yield"sv)
  2126. syntax_error("Parameter name 'yield' not allowed in this context");
  2127. if (function_kind == FunctionKind::Async && parameter_name == "await"sv)
  2128. syntax_error("Parameter name 'await' not allowed in this context");
  2129. for (auto& previous_name : parameter_names) {
  2130. if (previous_name == parameter_name) {
  2131. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name));
  2132. }
  2133. }
  2134. parameter_names.append(parameter_name);
  2135. },
  2136. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2137. binding->for_each_bound_name([&](auto& bound_name) {
  2138. if (function_kind == FunctionKind::Generator && bound_name == "yield"sv)
  2139. syntax_error("Parameter name 'yield' not allowed in this context");
  2140. if (function_kind == FunctionKind::Async && bound_name == "await"sv)
  2141. syntax_error("Parameter name 'await' not allowed in this context");
  2142. for (auto& previous_name : parameter_names) {
  2143. if (previous_name == bound_name) {
  2144. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", bound_name));
  2145. break;
  2146. }
  2147. }
  2148. parameter_names.append(bound_name);
  2149. });
  2150. });
  2151. }
  2152. }
  2153. m_state.strict_mode = previous_strict_mode;
  2154. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  2155. return function_body;
  2156. }
  2157. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  2158. {
  2159. auto rule_start = push_start();
  2160. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2161. ScopePusher block_scope = ScopePusher::block_scope(*this, block);
  2162. consume(TokenType::CurlyOpen);
  2163. parse_statement_list(block);
  2164. consume(TokenType::CurlyClose);
  2165. return block;
  2166. }
  2167. template<typename FunctionNodeType>
  2168. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options, Optional<Position> const& function_start)
  2169. {
  2170. auto rule_start = function_start.has_value()
  2171. ? RulePosition { *this, *function_start }
  2172. : push_start();
  2173. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  2174. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  2175. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  2176. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  2177. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  2178. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, false);
  2179. TemporaryChange might_need_arguments_object_rollback(m_state.function_might_need_arguments_object, false);
  2180. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  2181. FunctionKind function_kind;
  2182. if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0 && (parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2183. function_kind = FunctionKind::AsyncGenerator;
  2184. else if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0)
  2185. function_kind = FunctionKind::Generator;
  2186. else if ((parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2187. function_kind = FunctionKind::Async;
  2188. else
  2189. function_kind = FunctionKind::Normal;
  2190. String name;
  2191. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  2192. if (function_kind == FunctionKind::Normal && match(TokenType::Async) && !next_token().trivia_contains_line_terminator()) {
  2193. function_kind = FunctionKind::Async;
  2194. consume(TokenType::Async);
  2195. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  2196. }
  2197. consume(TokenType::Function);
  2198. if (match(TokenType::Asterisk)) {
  2199. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  2200. consume(TokenType::Asterisk);
  2201. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  2202. }
  2203. if (FunctionNodeType::must_have_name() || match_identifier())
  2204. name = consume_identifier().value();
  2205. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  2206. name = consume().value();
  2207. check_identifier_name_for_assignment_validity(name);
  2208. if (function_kind == FunctionKind::AsyncGenerator && (name == "await"sv || name == "yield"sv))
  2209. syntax_error(String::formatted("async generator function is not allowed to be called '{}'", name));
  2210. if (m_state.in_class_static_init_block && name == "await"sv)
  2211. syntax_error("'await' is a reserved word");
  2212. }
  2213. TemporaryChange class_static_initializer_rollback(m_state.in_class_static_init_block, false);
  2214. TemporaryChange generator_change(m_state.in_generator_function_context, function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator);
  2215. TemporaryChange async_change(m_state.await_expression_is_valid, function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator);
  2216. consume(TokenType::ParenOpen);
  2217. i32 function_length = -1;
  2218. auto parameters = parse_formal_parameters(function_length, parse_options);
  2219. consume(TokenType::ParenClose);
  2220. if (function_length == -1)
  2221. function_length = parameters.size();
  2222. TemporaryChange function_context_rollback(m_state.in_function_context, true);
  2223. auto old_labels_in_scope = move(m_state.labels_in_scope);
  2224. ScopeGuard guard([&]() {
  2225. m_state.labels_in_scope = move(old_labels_in_scope);
  2226. });
  2227. consume(TokenType::CurlyOpen);
  2228. bool contains_direct_call_to_eval = false;
  2229. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  2230. consume(TokenType::CurlyClose);
  2231. auto has_strict_directive = body->in_strict_mode();
  2232. if (has_strict_directive)
  2233. check_identifier_name_for_assignment_validity(name, true);
  2234. auto function_start_offset = rule_start.position().offset;
  2235. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  2236. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  2237. return create_ast_node<FunctionNodeType>(
  2238. { m_state.current_token.filename(), rule_start.position(), position() },
  2239. name, move(source_text), move(body), move(parameters), function_length,
  2240. function_kind, has_strict_directive, m_state.function_might_need_arguments_object,
  2241. contains_direct_call_to_eval);
  2242. }
  2243. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  2244. {
  2245. auto rule_start = push_start();
  2246. bool has_default_parameter = false;
  2247. bool has_rest_parameter = false;
  2248. TemporaryChange formal_parameter_context_change { m_state.in_formal_parameter_context, true };
  2249. Vector<FunctionNode::Parameter> parameters;
  2250. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  2251. if (auto pattern = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No))
  2252. return pattern.release_nonnull();
  2253. auto token = consume_identifier();
  2254. auto parameter_name = token.value();
  2255. check_identifier_name_for_assignment_validity(parameter_name);
  2256. for (auto& parameter : parameters) {
  2257. bool has_same_name = parameter.binding.visit(
  2258. [&](FlyString const& name) {
  2259. return name == parameter_name;
  2260. },
  2261. [&](NonnullRefPtr<BindingPattern> const& bindings) {
  2262. bool found_duplicate = false;
  2263. bindings->for_each_bound_name([&](auto& bound_name) {
  2264. if (bound_name == parameter_name)
  2265. found_duplicate = true;
  2266. });
  2267. return found_duplicate;
  2268. });
  2269. if (!has_same_name)
  2270. continue;
  2271. String message;
  2272. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  2273. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  2274. else if (m_state.strict_mode)
  2275. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  2276. else if (has_default_parameter || match(TokenType::Equals))
  2277. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  2278. else if (has_rest_parameter)
  2279. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  2280. if (!message.is_empty())
  2281. syntax_error(message, Position { token.line_number(), token.line_column() });
  2282. break;
  2283. }
  2284. return FlyString { token.value() };
  2285. };
  2286. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) {
  2287. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  2288. syntax_error("Getter function must have no arguments");
  2289. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  2290. syntax_error("Setter function must have one argument");
  2291. auto is_rest = false;
  2292. if (match(TokenType::TripleDot)) {
  2293. consume();
  2294. has_rest_parameter = true;
  2295. function_length = parameters.size();
  2296. is_rest = true;
  2297. }
  2298. auto parameter = consume_identifier_or_binding_pattern();
  2299. RefPtr<Expression> default_value;
  2300. if (match(TokenType::Equals)) {
  2301. consume();
  2302. if (is_rest)
  2303. syntax_error("Rest parameter may not have a default initializer");
  2304. TemporaryChange change(m_state.in_function_context, true);
  2305. has_default_parameter = true;
  2306. function_length = parameters.size();
  2307. default_value = parse_expression(2);
  2308. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  2309. if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  2310. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  2311. }
  2312. parameters.append({ move(parameter), default_value, is_rest });
  2313. if (!match(TokenType::Comma) || is_rest)
  2314. break;
  2315. consume(TokenType::Comma);
  2316. }
  2317. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  2318. syntax_error("Setter function must have one argument");
  2319. // If we're parsing the parameters standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2320. // Otherwise, we need a closing parenthesis (which is consumed elsewhere). If we get neither, it's an error.
  2321. if (!match(TokenType::Eof) && !match(TokenType::ParenClose))
  2322. expected(Token::name(TokenType::ParenClose));
  2323. return parameters;
  2324. }
  2325. static constexpr AK::Array<StringView, 36> s_reserved_words = { "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with" };
  2326. RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates allow_duplicates, Parser::AllowMemberExpressions allow_member_expressions)
  2327. {
  2328. auto rule_start = push_start();
  2329. TokenType closing_token;
  2330. bool is_object = true;
  2331. if (match(TokenType::BracketOpen)) {
  2332. consume();
  2333. closing_token = TokenType::BracketClose;
  2334. is_object = false;
  2335. } else if (match(TokenType::CurlyOpen)) {
  2336. consume();
  2337. closing_token = TokenType::CurlyClose;
  2338. } else {
  2339. return {};
  2340. }
  2341. Vector<BindingPattern::BindingEntry> entries;
  2342. while (!match(closing_token)) {
  2343. if (!is_object && match(TokenType::Comma)) {
  2344. consume();
  2345. entries.append(BindingPattern::BindingEntry {});
  2346. continue;
  2347. }
  2348. auto is_rest = false;
  2349. if (match(TokenType::TripleDot)) {
  2350. consume();
  2351. is_rest = true;
  2352. }
  2353. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  2354. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  2355. RefPtr<Expression> initializer = {};
  2356. if (is_object) {
  2357. bool needs_alias = false;
  2358. if (allow_member_expressions == AllowMemberExpressions::Yes && is_rest) {
  2359. auto expression_position = position();
  2360. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2361. if (is<MemberExpression>(*expression))
  2362. alias = static_ptr_cast<MemberExpression>(expression);
  2363. else if (is<Identifier>(*expression))
  2364. name = static_ptr_cast<Identifier>(expression);
  2365. else
  2366. syntax_error("Invalid destructuring assignment target", expression_position);
  2367. } else if (match_identifier_name() || match(TokenType::StringLiteral) || match(TokenType::NumericLiteral)) {
  2368. if (match(TokenType::StringLiteral) || match(TokenType::NumericLiteral))
  2369. needs_alias = true;
  2370. if (match(TokenType::StringLiteral)) {
  2371. auto token = consume(TokenType::StringLiteral);
  2372. auto string_literal = parse_string_literal(token);
  2373. name = create_ast_node<Identifier>(
  2374. { m_state.current_token.filename(), rule_start.position(), position() },
  2375. string_literal->value());
  2376. } else {
  2377. name = create_ast_node<Identifier>(
  2378. { m_state.current_token.filename(), rule_start.position(), position() },
  2379. consume().value());
  2380. }
  2381. } else if (match(TokenType::BracketOpen)) {
  2382. consume();
  2383. auto expression = parse_expression(0);
  2384. name = move(expression);
  2385. consume(TokenType::BracketClose);
  2386. } else {
  2387. expected("identifier or computed property name");
  2388. return {};
  2389. }
  2390. if (!is_rest && match(TokenType::Colon)) {
  2391. consume();
  2392. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2393. auto expression_position = position();
  2394. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2395. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2396. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2397. alias = synthesized_binding_pattern.release_nonnull();
  2398. else
  2399. syntax_error("Invalid destructuring assignment target", expression_position);
  2400. } else if (is<MemberExpression>(*expression)) {
  2401. alias = static_ptr_cast<MemberExpression>(expression);
  2402. } else if (is<Identifier>(*expression)) {
  2403. alias = static_ptr_cast<Identifier>(expression);
  2404. } else {
  2405. syntax_error("Invalid destructuring assignment target", expression_position);
  2406. }
  2407. } else if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  2408. auto binding_pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2409. if (!binding_pattern)
  2410. return {};
  2411. alias = binding_pattern.release_nonnull();
  2412. } else if (match_identifier_name()) {
  2413. alias = create_ast_node<Identifier>(
  2414. { m_state.current_token.filename(), rule_start.position(), position() },
  2415. consume().value());
  2416. } else {
  2417. expected("identifier or binding pattern");
  2418. return {};
  2419. }
  2420. } else if (needs_alias) {
  2421. expected("alias for string or numeric literal name");
  2422. return {};
  2423. }
  2424. } else {
  2425. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2426. auto expression_position = position();
  2427. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2428. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2429. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2430. alias = synthesized_binding_pattern.release_nonnull();
  2431. else
  2432. syntax_error("Invalid destructuring assignment target", expression_position);
  2433. } else if (is<MemberExpression>(*expression)) {
  2434. alias = static_ptr_cast<MemberExpression>(expression);
  2435. } else if (is<Identifier>(*expression)) {
  2436. alias = static_ptr_cast<Identifier>(expression);
  2437. } else {
  2438. syntax_error("Invalid destructuring assignment target", expression_position);
  2439. }
  2440. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  2441. auto pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2442. if (!pattern) {
  2443. expected("binding pattern");
  2444. return {};
  2445. }
  2446. alias = pattern.release_nonnull();
  2447. } else if (match_identifier_name()) {
  2448. // BindingElement must always have an Empty name field
  2449. auto identifier_name = consume_identifier().value();
  2450. alias = create_ast_node<Identifier>(
  2451. { m_state.current_token.filename(), rule_start.position(), position() },
  2452. identifier_name);
  2453. } else {
  2454. expected("identifier or binding pattern");
  2455. return {};
  2456. }
  2457. }
  2458. if (match(TokenType::Equals)) {
  2459. if (is_rest) {
  2460. syntax_error("Unexpected initializer after rest element");
  2461. return {};
  2462. }
  2463. consume();
  2464. initializer = parse_expression(2);
  2465. if (!initializer) {
  2466. expected("initialization expression");
  2467. return {};
  2468. }
  2469. }
  2470. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  2471. if (match(TokenType::Comma)) {
  2472. if (is_rest) {
  2473. syntax_error("Rest element may not be followed by a comma");
  2474. return {};
  2475. }
  2476. consume();
  2477. } else if (is_object && !match(TokenType::CurlyClose)) {
  2478. consume(TokenType::Comma);
  2479. }
  2480. }
  2481. while (!is_object && match(TokenType::Comma))
  2482. consume();
  2483. consume(closing_token);
  2484. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  2485. auto pattern = adopt_ref(*new BindingPattern);
  2486. pattern->entries = move(entries);
  2487. pattern->kind = kind;
  2488. Vector<StringView> bound_names;
  2489. pattern->for_each_bound_name([&](auto& name) {
  2490. if (allow_duplicates == AllowDuplicates::No) {
  2491. if (bound_names.contains_slow(name))
  2492. syntax_error("Duplicate parameter names in bindings");
  2493. bound_names.append(name);
  2494. }
  2495. check_identifier_name_for_assignment_validity(name);
  2496. });
  2497. return pattern;
  2498. }
  2499. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  2500. {
  2501. auto rule_start = push_start();
  2502. DeclarationKind declaration_kind;
  2503. switch (m_state.current_token.type()) {
  2504. case TokenType::Var:
  2505. declaration_kind = DeclarationKind::Var;
  2506. break;
  2507. case TokenType::Let:
  2508. declaration_kind = DeclarationKind::Let;
  2509. break;
  2510. case TokenType::Const:
  2511. declaration_kind = DeclarationKind::Const;
  2512. break;
  2513. default:
  2514. VERIFY_NOT_REACHED();
  2515. }
  2516. consume();
  2517. NonnullRefPtrVector<VariableDeclarator> declarations;
  2518. for (;;) {
  2519. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target {};
  2520. if (match_identifier()) {
  2521. auto identifier_start = push_start();
  2522. auto name = consume_identifier().value();
  2523. target = create_ast_node<Identifier>(
  2524. { m_state.current_token.filename(), rule_start.position(), position() },
  2525. name);
  2526. check_identifier_name_for_assignment_validity(name);
  2527. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && name == "let"sv)
  2528. syntax_error("Lexical binding may not be called 'let'");
  2529. } else if (auto pattern = parse_binding_pattern(declaration_kind != DeclarationKind::Var ? AllowDuplicates::No : AllowDuplicates::Yes, AllowMemberExpressions::No)) {
  2530. target = pattern.release_nonnull();
  2531. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const)) {
  2532. target.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name([this](auto& name) {
  2533. if (name == "let"sv)
  2534. syntax_error("Lexical binding may not be called 'let'");
  2535. });
  2536. }
  2537. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  2538. if (m_state.strict_mode)
  2539. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  2540. target = create_ast_node<Identifier>(
  2541. { m_state.current_token.filename(), rule_start.position(), position() },
  2542. consume().value());
  2543. } else if (!m_state.await_expression_is_valid && match(TokenType::Async)) {
  2544. if (m_program_type == Program::Type::Module)
  2545. syntax_error("Identifier must not be a reserved word in modules ('async')");
  2546. target = create_ast_node<Identifier>(
  2547. { m_state.current_token.filename(), rule_start.position(), position() },
  2548. consume().value());
  2549. }
  2550. if (target.has<Empty>()) {
  2551. expected("identifier or a binding pattern");
  2552. if (match(TokenType::Comma)) {
  2553. consume();
  2554. continue;
  2555. }
  2556. break;
  2557. }
  2558. RefPtr<Expression> init;
  2559. if (match(TokenType::Equals)) {
  2560. consume();
  2561. // In a for loop 'in' can be ambiguous so we do not allow it
  2562. // 14.7.4 The for Statement, https://tc39.es/ecma262/#prod-ForStatement and 14.7.5 The for-in, for-of, and for-await-of Statements, https://tc39.es/ecma262/#prod-ForInOfStatement
  2563. if (for_loop_variable_declaration)
  2564. init = parse_expression(2, Associativity::Right, { TokenType::In });
  2565. else
  2566. init = parse_expression(2);
  2567. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  2568. syntax_error("Missing initializer in 'const' variable declaration");
  2569. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  2570. syntax_error("Missing initializer in destructuring assignment");
  2571. }
  2572. declarations.append(create_ast_node<VariableDeclarator>(
  2573. { m_state.current_token.filename(), rule_start.position(), position() },
  2574. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  2575. move(init)));
  2576. if (match(TokenType::Comma)) {
  2577. consume();
  2578. continue;
  2579. }
  2580. break;
  2581. }
  2582. if (!for_loop_variable_declaration)
  2583. consume_or_insert_semicolon();
  2584. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  2585. return declaration;
  2586. }
  2587. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  2588. {
  2589. auto rule_start = push_start();
  2590. consume(TokenType::Throw);
  2591. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  2592. if (m_state.current_token.trivia_contains_line_terminator()) {
  2593. syntax_error("No line break is allowed between 'throw' and its expression");
  2594. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }));
  2595. }
  2596. auto expression = parse_expression(0);
  2597. consume_or_insert_semicolon();
  2598. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2599. }
  2600. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  2601. {
  2602. auto rule_start = push_start();
  2603. consume(TokenType::Break);
  2604. FlyString target_label;
  2605. if (match(TokenType::Semicolon)) {
  2606. consume();
  2607. } else {
  2608. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2609. target_label = consume().value();
  2610. auto label = m_state.labels_in_scope.find(target_label);
  2611. if (label == m_state.labels_in_scope.end())
  2612. syntax_error(String::formatted("Label '{}' not found", target_label));
  2613. }
  2614. consume_or_insert_semicolon();
  2615. }
  2616. if (target_label.is_null() && !m_state.in_break_context)
  2617. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  2618. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2619. }
  2620. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  2621. {
  2622. auto rule_start = push_start();
  2623. if (!m_state.in_continue_context)
  2624. syntax_error("'continue' not allow outside of a loop");
  2625. consume(TokenType::Continue);
  2626. FlyString target_label;
  2627. if (match(TokenType::Semicolon)) {
  2628. consume();
  2629. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2630. }
  2631. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2632. auto label_position = position();
  2633. target_label = consume().value();
  2634. auto label = m_state.labels_in_scope.find(target_label);
  2635. if (label == m_state.labels_in_scope.end())
  2636. syntax_error(String::formatted("Label '{}' not found or invalid", target_label));
  2637. else
  2638. label->value = label_position;
  2639. }
  2640. consume_or_insert_semicolon();
  2641. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2642. }
  2643. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  2644. {
  2645. auto rule_start = push_start();
  2646. consume(TokenType::QuestionMark);
  2647. auto consequent = parse_expression(2);
  2648. consume(TokenType::Colon);
  2649. auto alternate = parse_expression(2);
  2650. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  2651. }
  2652. NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expression> base)
  2653. {
  2654. auto rule_start = push_start();
  2655. Vector<OptionalChain::Reference> chain;
  2656. do {
  2657. if (match(TokenType::QuestionMarkPeriod)) {
  2658. consume(TokenType::QuestionMarkPeriod);
  2659. switch (m_state.current_token.type()) {
  2660. case TokenType::ParenOpen:
  2661. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::Optional });
  2662. break;
  2663. case TokenType::BracketOpen:
  2664. consume();
  2665. chain.append(OptionalChain::ComputedReference { parse_expression(0), OptionalChain::Mode::Optional });
  2666. consume(TokenType::BracketClose);
  2667. break;
  2668. case TokenType::PrivateIdentifier: {
  2669. if (!is_private_identifier_valid())
  2670. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  2671. auto start = position();
  2672. auto private_identifier = consume();
  2673. chain.append(OptionalChain::PrivateMemberReference {
  2674. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2675. OptionalChain::Mode::Optional });
  2676. break;
  2677. }
  2678. case TokenType::TemplateLiteralStart:
  2679. // 13.3.1.1 - Static Semantics: Early Errors
  2680. // OptionalChain :
  2681. // ?. TemplateLiteral
  2682. // OptionalChain TemplateLiteral
  2683. // This is a hard error.
  2684. syntax_error("Invalid tagged template literal after ?.", position());
  2685. break;
  2686. default:
  2687. if (match_identifier_name()) {
  2688. auto start = position();
  2689. auto identifier = consume();
  2690. chain.append(OptionalChain::MemberReference {
  2691. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()),
  2692. OptionalChain::Mode::Optional,
  2693. });
  2694. } else {
  2695. syntax_error("Invalid optional chain reference after ?.", position());
  2696. }
  2697. break;
  2698. }
  2699. } else if (match(TokenType::ParenOpen)) {
  2700. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::NotOptional });
  2701. } else if (match(TokenType::Period)) {
  2702. consume();
  2703. if (match(TokenType::PrivateIdentifier)) {
  2704. auto start = position();
  2705. auto private_identifier = consume();
  2706. chain.append(OptionalChain::PrivateMemberReference {
  2707. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2708. OptionalChain::Mode::NotOptional,
  2709. });
  2710. } else if (match_identifier_name()) {
  2711. auto start = position();
  2712. auto identifier = consume();
  2713. chain.append(OptionalChain::MemberReference {
  2714. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()),
  2715. OptionalChain::Mode::NotOptional,
  2716. });
  2717. } else {
  2718. expected("an identifier");
  2719. break;
  2720. }
  2721. } else if (match(TokenType::TemplateLiteralStart)) {
  2722. // 13.3.1.1 - Static Semantics: Early Errors
  2723. // OptionalChain :
  2724. // ?. TemplateLiteral
  2725. // OptionalChain TemplateLiteral
  2726. syntax_error("Invalid tagged template literal after optional chain", position());
  2727. break;
  2728. } else if (match(TokenType::BracketOpen)) {
  2729. consume();
  2730. chain.append(OptionalChain::ComputedReference { parse_expression(2), OptionalChain::Mode::NotOptional });
  2731. consume(TokenType::BracketClose);
  2732. } else {
  2733. break;
  2734. }
  2735. } while (!done());
  2736. return create_ast_node<OptionalChain>(
  2737. { m_state.current_token.filename(), rule_start.position(), position() },
  2738. move(base),
  2739. move(chain));
  2740. }
  2741. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  2742. {
  2743. auto rule_start = push_start();
  2744. consume(TokenType::Try);
  2745. auto block = parse_block_statement();
  2746. RefPtr<CatchClause> handler;
  2747. if (match(TokenType::Catch))
  2748. handler = parse_catch_clause();
  2749. RefPtr<BlockStatement> finalizer;
  2750. if (match(TokenType::Finally)) {
  2751. consume();
  2752. finalizer = parse_block_statement();
  2753. }
  2754. if (!handler && !finalizer)
  2755. syntax_error("try statement must have a 'catch' or 'finally' clause");
  2756. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  2757. }
  2758. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  2759. {
  2760. auto rule_start = push_start();
  2761. consume(TokenType::Do);
  2762. auto body = [&]() -> NonnullRefPtr<Statement> {
  2763. TemporaryChange break_change(m_state.in_break_context, true);
  2764. TemporaryChange continue_change(m_state.in_continue_context, true);
  2765. return parse_statement();
  2766. }();
  2767. consume(TokenType::While);
  2768. consume(TokenType::ParenOpen);
  2769. auto test = parse_expression(0);
  2770. consume(TokenType::ParenClose);
  2771. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  2772. if (match(TokenType::Semicolon))
  2773. consume();
  2774. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2775. }
  2776. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  2777. {
  2778. auto rule_start = push_start();
  2779. consume(TokenType::While);
  2780. consume(TokenType::ParenOpen);
  2781. auto test = parse_expression(0);
  2782. consume(TokenType::ParenClose);
  2783. TemporaryChange break_change(m_state.in_break_context, true);
  2784. TemporaryChange continue_change(m_state.in_continue_context, true);
  2785. auto body = parse_statement();
  2786. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2787. }
  2788. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  2789. {
  2790. auto rule_start = push_start();
  2791. consume(TokenType::Switch);
  2792. consume(TokenType::ParenOpen);
  2793. auto determinant = parse_expression(0);
  2794. consume(TokenType::ParenClose);
  2795. consume(TokenType::CurlyOpen);
  2796. NonnullRefPtrVector<SwitchCase> cases;
  2797. auto switch_statement = create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant));
  2798. ScopePusher switch_scope = ScopePusher::block_scope(*this, switch_statement);
  2799. auto has_default = false;
  2800. while (match(TokenType::Case) || match(TokenType::Default)) {
  2801. if (match(TokenType::Default)) {
  2802. if (has_default)
  2803. syntax_error("Multiple 'default' clauses in switch statement");
  2804. has_default = true;
  2805. }
  2806. switch_statement->add_case(parse_switch_case());
  2807. }
  2808. consume(TokenType::CurlyClose);
  2809. return switch_statement;
  2810. }
  2811. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  2812. {
  2813. auto rule_start = push_start();
  2814. consume(TokenType::With);
  2815. consume(TokenType::ParenOpen);
  2816. auto object = parse_expression(0);
  2817. consume(TokenType::ParenClose);
  2818. auto body = parse_statement();
  2819. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  2820. }
  2821. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  2822. {
  2823. auto rule_start = push_start();
  2824. RefPtr<Expression> test;
  2825. if (consume().type() == TokenType::Case) {
  2826. test = parse_expression(0);
  2827. }
  2828. consume(TokenType::Colon);
  2829. NonnullRefPtrVector<Statement> consequent;
  2830. TemporaryChange break_change(m_state.in_break_context, true);
  2831. auto switch_case = create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test));
  2832. parse_statement_list(switch_case);
  2833. return switch_case;
  2834. }
  2835. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  2836. {
  2837. auto rule_start = push_start();
  2838. consume(TokenType::Catch);
  2839. FlyString parameter;
  2840. RefPtr<BindingPattern> pattern_parameter;
  2841. auto should_expect_parameter = false;
  2842. if (match(TokenType::ParenOpen)) {
  2843. should_expect_parameter = true;
  2844. consume();
  2845. if (match_identifier_name()
  2846. && (!match(TokenType::Yield) || !m_state.in_generator_function_context)
  2847. && (!match(TokenType::Async) || !m_state.await_expression_is_valid)
  2848. && (!match(TokenType::Await) || !m_state.in_class_static_init_block))
  2849. parameter = consume().value();
  2850. else
  2851. pattern_parameter = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No);
  2852. consume(TokenType::ParenClose);
  2853. }
  2854. if (should_expect_parameter && parameter.is_empty() && !pattern_parameter)
  2855. expected("an identifier or a binding pattern");
  2856. HashTable<FlyString> bound_names;
  2857. if (pattern_parameter) {
  2858. pattern_parameter->for_each_bound_name(
  2859. [&](auto& name) {
  2860. check_identifier_name_for_assignment_validity(name);
  2861. bound_names.set(name);
  2862. });
  2863. }
  2864. if (!parameter.is_empty()) {
  2865. check_identifier_name_for_assignment_validity(parameter);
  2866. bound_names.set(parameter);
  2867. }
  2868. ScopePusher catch_scope = ScopePusher::catch_scope(*this, pattern_parameter, parameter);
  2869. auto body = parse_block_statement();
  2870. body->for_each_lexically_declared_name([&](auto const& name) {
  2871. if (bound_names.contains(name))
  2872. syntax_error(String::formatted("Identifier '{}' already declared as catch parameter", name));
  2873. });
  2874. if (pattern_parameter) {
  2875. return create_ast_node<CatchClause>(
  2876. { m_state.current_token.filename(), rule_start.position(), position() },
  2877. pattern_parameter.release_nonnull(),
  2878. move(body));
  2879. }
  2880. return create_ast_node<CatchClause>(
  2881. { m_state.current_token.filename(), rule_start.position(), position() },
  2882. move(parameter),
  2883. move(body));
  2884. }
  2885. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  2886. {
  2887. auto rule_start = push_start();
  2888. auto parse_function_declaration_as_block_statement = [&] {
  2889. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  2890. // Code matching this production is processed as if each matching occurrence of
  2891. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  2892. // of a BlockStatement occupying that position in the source code.
  2893. VERIFY(match(TokenType::Function));
  2894. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2895. ScopePusher block_scope = ScopePusher::block_scope(*this, *block);
  2896. auto declaration = parse_declaration();
  2897. VERIFY(m_state.current_scope_pusher);
  2898. block_scope.add_declaration(declaration);
  2899. VERIFY(is<FunctionDeclaration>(*declaration));
  2900. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  2901. if (function_declaration.kind() == FunctionKind::Generator)
  2902. syntax_error("Generator functions can only be declared in top-level or within a block");
  2903. if (function_declaration.kind() == FunctionKind::Async)
  2904. syntax_error("Async functions can only be declared in top-level or within a block");
  2905. block->append(move(declaration));
  2906. return block;
  2907. };
  2908. consume(TokenType::If);
  2909. consume(TokenType::ParenOpen);
  2910. auto predicate = parse_expression(0);
  2911. consume(TokenType::ParenClose);
  2912. RefPtr<Statement> consequent;
  2913. if (!m_state.strict_mode && match(TokenType::Function))
  2914. consequent = parse_function_declaration_as_block_statement();
  2915. else
  2916. consequent = parse_statement();
  2917. RefPtr<Statement> alternate;
  2918. if (match(TokenType::Else)) {
  2919. consume();
  2920. if (!m_state.strict_mode && match(TokenType::Function))
  2921. alternate = parse_function_declaration_as_block_statement();
  2922. else
  2923. alternate = parse_statement();
  2924. }
  2925. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  2926. }
  2927. NonnullRefPtr<Statement> Parser::parse_for_statement()
  2928. {
  2929. auto rule_start = push_start();
  2930. auto is_await_loop = IsForAwaitLoop::No;
  2931. auto match_of = [&](Token const& token) {
  2932. return token.type() == TokenType::Identifier && token.original_value() == "of"sv;
  2933. };
  2934. auto match_for_in_of = [&]() {
  2935. bool is_of = match_of(m_state.current_token);
  2936. if (is_await_loop == IsForAwaitLoop::Yes) {
  2937. if (!is_of)
  2938. syntax_error("for await loop is only valid with 'of'");
  2939. else if (!m_state.await_expression_is_valid)
  2940. syntax_error("for await loop is only valid in async function or generator");
  2941. return true;
  2942. }
  2943. return match(TokenType::In) || is_of;
  2944. };
  2945. consume(TokenType::For);
  2946. if (match(TokenType::Await)) {
  2947. consume();
  2948. if (!m_state.await_expression_is_valid)
  2949. syntax_error("for-await-of is only allowed in async function context");
  2950. is_await_loop = IsForAwaitLoop::Yes;
  2951. }
  2952. consume(TokenType::ParenOpen);
  2953. Optional<ScopePusher> scope_pusher;
  2954. RefPtr<ASTNode> init;
  2955. if (!match(TokenType::Semicolon)) {
  2956. if (match_variable_declaration()) {
  2957. auto declaration = parse_variable_declaration(true);
  2958. if (declaration->declaration_kind() == DeclarationKind::Var) {
  2959. m_state.current_scope_pusher->add_declaration(declaration);
  2960. } else {
  2961. // This does not follow the normal declaration structure so we need additional checks.
  2962. HashTable<FlyString> bound_names;
  2963. declaration->for_each_bound_name([&](auto const& name) {
  2964. if (bound_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  2965. syntax_error(String::formatted("Identifier '{}' already declared in for loop initializer", name), declaration->source_range().start);
  2966. });
  2967. }
  2968. init = move(declaration);
  2969. if (match_for_in_of())
  2970. return parse_for_in_of_statement(*init, is_await_loop);
  2971. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  2972. for (auto& variable : static_cast<VariableDeclaration&>(*init).declarations()) {
  2973. if (!variable.init())
  2974. syntax_error("Missing initializer in 'const' variable declaration");
  2975. }
  2976. }
  2977. } else if (match_expression()) {
  2978. auto lookahead_token = next_token();
  2979. bool starts_with_async_of = match(TokenType::Async) && match_of(lookahead_token);
  2980. init = parse_expression(0, Associativity::Right, { TokenType::In });
  2981. if (match_for_in_of()) {
  2982. if (is_await_loop != IsForAwaitLoop::Yes
  2983. && starts_with_async_of && match_of(m_state.current_token))
  2984. syntax_error("for-of loop may not start with async of");
  2985. return parse_for_in_of_statement(*init, is_await_loop);
  2986. }
  2987. } else {
  2988. syntax_error("Unexpected token in for loop");
  2989. }
  2990. }
  2991. consume(TokenType::Semicolon);
  2992. RefPtr<Expression> test;
  2993. if (!match(TokenType::Semicolon))
  2994. test = parse_expression(0);
  2995. consume(TokenType::Semicolon);
  2996. RefPtr<Expression> update;
  2997. if (!match(TokenType::ParenClose))
  2998. update = parse_expression(0);
  2999. consume(TokenType::ParenClose);
  3000. TemporaryChange break_change(m_state.in_break_context, true);
  3001. TemporaryChange continue_change(m_state.in_continue_context, true);
  3002. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, init);
  3003. auto body = parse_statement();
  3004. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  3005. }
  3006. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_for_await_loop)
  3007. {
  3008. Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> for_declaration = lhs;
  3009. auto rule_start = push_start();
  3010. auto has_annexB_for_in_init_extension = false;
  3011. if (is<VariableDeclaration>(*lhs)) {
  3012. auto& declaration = static_cast<VariableDeclaration&>(*lhs);
  3013. if (declaration.declarations().size() > 1) {
  3014. syntax_error("Multiple declarations not allowed in for..in/of");
  3015. } else if (declaration.declarations().size() < 1) {
  3016. syntax_error("Need exactly one variable declaration in for..in/of");
  3017. } else {
  3018. // AnnexB extension B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  3019. auto& variable = declaration.declarations().first();
  3020. if (variable.init()) {
  3021. if (m_state.strict_mode || declaration.declaration_kind() != DeclarationKind::Var || !variable.target().has<NonnullRefPtr<Identifier>>())
  3022. syntax_error("Variable initializer not allowed in for..in/of");
  3023. else
  3024. has_annexB_for_in_init_extension = true;
  3025. }
  3026. }
  3027. } else if (!lhs->is_identifier() && !is<MemberExpression>(*lhs)) {
  3028. bool valid = false;
  3029. if (is<ObjectExpression>(*lhs) || is<ArrayExpression>(*lhs)) {
  3030. auto synthesized_binding_pattern = synthesize_binding_pattern(static_cast<Expression const&>(*lhs));
  3031. if (synthesized_binding_pattern) {
  3032. for_declaration = synthesized_binding_pattern.release_nonnull();
  3033. valid = true;
  3034. }
  3035. }
  3036. if (!valid)
  3037. syntax_error(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()));
  3038. }
  3039. auto in_or_of = consume();
  3040. auto is_in = in_or_of.type() == TokenType::In;
  3041. if (!is_in) {
  3042. if (is<MemberExpression>(*lhs)) {
  3043. auto& member = static_cast<MemberExpression const&>(*lhs);
  3044. if (member.object().is_identifier() && static_cast<Identifier const&>(member.object()).string() == "let"sv)
  3045. syntax_error("For of statement may not start with let.");
  3046. }
  3047. if (has_annexB_for_in_init_extension)
  3048. syntax_error("Variable initializer not allowed in for..of", rule_start.position());
  3049. }
  3050. auto rhs = parse_expression(is_in ? 0 : 2);
  3051. consume(TokenType::ParenClose);
  3052. TemporaryChange break_change(m_state.in_break_context, true);
  3053. TemporaryChange continue_change(m_state.in_continue_context, true);
  3054. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, lhs);
  3055. auto body = parse_statement();
  3056. if (is_in)
  3057. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3058. if (is_for_await_loop == IsForAwaitLoop::Yes)
  3059. return create_ast_node<ForAwaitOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3060. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3061. }
  3062. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  3063. {
  3064. auto rule_start = push_start();
  3065. consume(TokenType::Debugger);
  3066. consume_or_insert_semicolon();
  3067. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  3068. }
  3069. bool Parser::match(TokenType type) const
  3070. {
  3071. return m_state.current_token.type() == type;
  3072. }
  3073. bool Parser::match_expression() const
  3074. {
  3075. auto type = m_state.current_token.type();
  3076. if (type == TokenType::Import) {
  3077. auto lookahead_token = next_token();
  3078. return lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen;
  3079. }
  3080. return type == TokenType::BoolLiteral
  3081. || type == TokenType::NumericLiteral
  3082. || type == TokenType::BigIntLiteral
  3083. || type == TokenType::StringLiteral
  3084. || type == TokenType::TemplateLiteralStart
  3085. || type == TokenType::NullLiteral
  3086. || match_identifier()
  3087. || type == TokenType::PrivateIdentifier
  3088. || type == TokenType::Await
  3089. || type == TokenType::New
  3090. || type == TokenType::Class
  3091. || type == TokenType::CurlyOpen
  3092. || type == TokenType::BracketOpen
  3093. || type == TokenType::ParenOpen
  3094. || type == TokenType::Function
  3095. || type == TokenType::Async
  3096. || type == TokenType::This
  3097. || type == TokenType::Super
  3098. || type == TokenType::RegexLiteral
  3099. || type == TokenType::Slash // Wrongly recognized regex by lexer
  3100. || type == TokenType::SlashEquals // Wrongly recognized regex by lexer (/=a/ is a valid regex)
  3101. || type == TokenType::Yield
  3102. || match_unary_prefixed_expression();
  3103. }
  3104. bool Parser::match_unary_prefixed_expression() const
  3105. {
  3106. auto type = m_state.current_token.type();
  3107. return type == TokenType::PlusPlus
  3108. || type == TokenType::MinusMinus
  3109. || type == TokenType::ExclamationMark
  3110. || type == TokenType::Tilde
  3111. || type == TokenType::Plus
  3112. || type == TokenType::Minus
  3113. || type == TokenType::Typeof
  3114. || type == TokenType::Void
  3115. || type == TokenType::Delete;
  3116. }
  3117. bool Parser::match_secondary_expression(const Vector<TokenType>& forbidden) const
  3118. {
  3119. auto type = m_state.current_token.type();
  3120. if (forbidden.contains_slow(type))
  3121. return false;
  3122. return type == TokenType::Plus
  3123. || type == TokenType::PlusEquals
  3124. || type == TokenType::Minus
  3125. || type == TokenType::MinusEquals
  3126. || type == TokenType::Asterisk
  3127. || type == TokenType::AsteriskEquals
  3128. || type == TokenType::Slash
  3129. || type == TokenType::SlashEquals
  3130. || type == TokenType::Percent
  3131. || type == TokenType::PercentEquals
  3132. || type == TokenType::DoubleAsterisk
  3133. || type == TokenType::DoubleAsteriskEquals
  3134. || type == TokenType::Equals
  3135. || type == TokenType::EqualsEqualsEquals
  3136. || type == TokenType::ExclamationMarkEqualsEquals
  3137. || type == TokenType::EqualsEquals
  3138. || type == TokenType::ExclamationMarkEquals
  3139. || type == TokenType::GreaterThan
  3140. || type == TokenType::GreaterThanEquals
  3141. || type == TokenType::LessThan
  3142. || type == TokenType::LessThanEquals
  3143. || type == TokenType::ParenOpen
  3144. || type == TokenType::Period
  3145. || type == TokenType::BracketOpen
  3146. || (type == TokenType::PlusPlus && !m_state.current_token.trivia_contains_line_terminator())
  3147. || (type == TokenType::MinusMinus && !m_state.current_token.trivia_contains_line_terminator())
  3148. || type == TokenType::In
  3149. || type == TokenType::Instanceof
  3150. || type == TokenType::QuestionMark
  3151. || type == TokenType::Ampersand
  3152. || type == TokenType::AmpersandEquals
  3153. || type == TokenType::Pipe
  3154. || type == TokenType::PipeEquals
  3155. || type == TokenType::Caret
  3156. || type == TokenType::CaretEquals
  3157. || type == TokenType::ShiftLeft
  3158. || type == TokenType::ShiftLeftEquals
  3159. || type == TokenType::ShiftRight
  3160. || type == TokenType::ShiftRightEquals
  3161. || type == TokenType::UnsignedShiftRight
  3162. || type == TokenType::UnsignedShiftRightEquals
  3163. || type == TokenType::DoubleAmpersand
  3164. || type == TokenType::DoubleAmpersandEquals
  3165. || type == TokenType::DoublePipe
  3166. || type == TokenType::DoublePipeEquals
  3167. || type == TokenType::DoubleQuestionMark
  3168. || type == TokenType::DoubleQuestionMarkEquals
  3169. || type == TokenType::QuestionMarkPeriod;
  3170. }
  3171. bool Parser::match_statement() const
  3172. {
  3173. auto type = m_state.current_token.type();
  3174. return match_expression()
  3175. || type == TokenType::Return
  3176. || type == TokenType::Yield
  3177. || type == TokenType::Do
  3178. || type == TokenType::If
  3179. || type == TokenType::Throw
  3180. || type == TokenType::Try
  3181. || type == TokenType::While
  3182. || type == TokenType::With
  3183. || type == TokenType::For
  3184. || type == TokenType::CurlyOpen
  3185. || type == TokenType::Switch
  3186. || type == TokenType::Break
  3187. || type == TokenType::Continue
  3188. || type == TokenType::Var
  3189. || type == TokenType::Debugger
  3190. || type == TokenType::Semicolon;
  3191. }
  3192. bool Parser::match_export_or_import() const
  3193. {
  3194. auto type = m_state.current_token.type();
  3195. return type == TokenType::Export
  3196. || type == TokenType::Import;
  3197. }
  3198. bool Parser::match_declaration() const
  3199. {
  3200. auto type = m_state.current_token.type();
  3201. if (type == TokenType::Let && !m_state.strict_mode) {
  3202. return try_match_let_declaration();
  3203. }
  3204. if (type == TokenType::Async) {
  3205. auto lookahead_token = next_token();
  3206. return lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator();
  3207. }
  3208. return type == TokenType::Function
  3209. || type == TokenType::Class
  3210. || type == TokenType::Const
  3211. || type == TokenType::Let;
  3212. }
  3213. Token Parser::next_token(size_t steps) const
  3214. {
  3215. Lexer lookahead_lexer = m_state.lexer;
  3216. Token lookahead_token;
  3217. while (steps > 0) {
  3218. lookahead_token = lookahead_lexer.next();
  3219. steps--;
  3220. }
  3221. return lookahead_token;
  3222. }
  3223. bool Parser::try_match_let_declaration() const
  3224. {
  3225. VERIFY(m_state.current_token.type() == TokenType::Let);
  3226. auto token_after = next_token();
  3227. if (token_after.is_identifier_name() && token_after.value() != "in"sv)
  3228. return true;
  3229. if (token_after.type() == TokenType::CurlyOpen || token_after.type() == TokenType::BracketOpen)
  3230. return true;
  3231. return false;
  3232. }
  3233. bool Parser::match_variable_declaration() const
  3234. {
  3235. auto type = m_state.current_token.type();
  3236. if (type == TokenType::Let && !m_state.strict_mode) {
  3237. return try_match_let_declaration();
  3238. }
  3239. return type == TokenType::Var
  3240. || type == TokenType::Let
  3241. || type == TokenType::Const;
  3242. }
  3243. bool Parser::match_identifier() const
  3244. {
  3245. if (m_state.current_token.type() == TokenType::EscapedKeyword) {
  3246. if (m_state.current_token.value() == "let"sv)
  3247. return !m_state.strict_mode;
  3248. if (m_state.current_token.value() == "yield"sv)
  3249. return !m_state.strict_mode && !m_state.in_generator_function_context;
  3250. if (m_state.current_token.value() == "await"sv)
  3251. return m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block;
  3252. return true;
  3253. }
  3254. return m_state.current_token.type() == TokenType::Identifier
  3255. || m_state.current_token.type() == TokenType::Async
  3256. || (m_state.current_token.type() == TokenType::Let && !m_state.strict_mode)
  3257. || (m_state.current_token.type() == TokenType::Await && m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block)
  3258. || (m_state.current_token.type() == TokenType::Yield && !m_state.in_generator_function_context && !m_state.strict_mode); // See note in Parser::parse_identifier().
  3259. }
  3260. bool Parser::match_identifier_name() const
  3261. {
  3262. return m_state.current_token.is_identifier_name();
  3263. }
  3264. bool Parser::match_property_key() const
  3265. {
  3266. auto type = m_state.current_token.type();
  3267. return match_identifier_name()
  3268. || type == TokenType::BracketOpen
  3269. || type == TokenType::StringLiteral
  3270. || type == TokenType::NumericLiteral
  3271. || type == TokenType::BigIntLiteral;
  3272. }
  3273. bool Parser::done() const
  3274. {
  3275. return match(TokenType::Eof);
  3276. }
  3277. Token Parser::consume()
  3278. {
  3279. auto old_token = m_state.current_token;
  3280. m_state.current_token = m_state.lexer.next();
  3281. // NOTE: This is the bare minimum needed to decide whether we might need an arguments object
  3282. // in a function expression or declaration. ("might" because the AST implements some further
  3283. // conditions from the spec that rule out the need for allocating one)
  3284. if (old_token.type() == TokenType::Identifier && old_token.value().is_one_of("arguments"sv, "eval"sv))
  3285. m_state.function_might_need_arguments_object = true;
  3286. return old_token;
  3287. }
  3288. void Parser::consume_or_insert_semicolon()
  3289. {
  3290. // Semicolon was found and will be consumed
  3291. if (match(TokenType::Semicolon)) {
  3292. consume();
  3293. return;
  3294. }
  3295. // Insert semicolon if...
  3296. // ...token is preceded by one or more newlines
  3297. if (m_state.current_token.trivia_contains_line_terminator())
  3298. return;
  3299. // ...token is a closing curly brace
  3300. if (match(TokenType::CurlyClose))
  3301. return;
  3302. // ...token is eof
  3303. if (match(TokenType::Eof))
  3304. return;
  3305. // No rule for semicolon insertion applies -> syntax error
  3306. expected("Semicolon");
  3307. }
  3308. Token Parser::consume_identifier()
  3309. {
  3310. if (match(TokenType::Identifier))
  3311. return consume(TokenType::Identifier);
  3312. if (match(TokenType::EscapedKeyword))
  3313. return consume(TokenType::EscapedKeyword);
  3314. // Note that 'let' is not a reserved keyword, but our lexer considers it such
  3315. // As it's pretty nice to have that (for syntax highlighting and such), we'll
  3316. // special-case it here instead.
  3317. if (match(TokenType::Let)) {
  3318. if (m_state.strict_mode)
  3319. syntax_error("'let' is not allowed as an identifier in strict mode");
  3320. return consume();
  3321. }
  3322. if (match(TokenType::Yield)) {
  3323. if (m_state.strict_mode || m_state.in_generator_function_context)
  3324. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  3325. return consume();
  3326. }
  3327. if (match(TokenType::Await)) {
  3328. if (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)
  3329. syntax_error("Identifier must not be a reserved word in modules ('await')");
  3330. return consume();
  3331. }
  3332. if (match(TokenType::Async))
  3333. return consume();
  3334. expected("Identifier");
  3335. return consume();
  3336. }
  3337. // https://tc39.es/ecma262/#prod-IdentifierReference
  3338. Token Parser::consume_identifier_reference()
  3339. {
  3340. if (match(TokenType::Identifier))
  3341. return consume(TokenType::Identifier);
  3342. if (match(TokenType::EscapedKeyword)) {
  3343. auto name = m_state.current_token.value();
  3344. if (m_state.strict_mode && (name == "let"sv || name == "yield"sv))
  3345. syntax_error(String::formatted("'{}' is not allowed as an identifier in strict mode", name));
  3346. if (m_program_type == Program::Type::Module && name == "await"sv)
  3347. syntax_error("'await' is not allowed as an identifier in module");
  3348. return consume();
  3349. }
  3350. // See note in Parser::parse_identifier().
  3351. if (match(TokenType::Let)) {
  3352. if (m_state.strict_mode)
  3353. syntax_error("'let' is not allowed as an identifier in strict mode");
  3354. return consume();
  3355. }
  3356. if (match(TokenType::Yield)) {
  3357. if (m_state.strict_mode)
  3358. syntax_error("Identifier reference may not be 'yield' in strict mode");
  3359. return consume();
  3360. }
  3361. if (match(TokenType::Await)) {
  3362. if (m_program_type == Program::Type::Module)
  3363. syntax_error("'await' is not allowed as an identifier in module");
  3364. return consume();
  3365. }
  3366. if (match(TokenType::Async))
  3367. return consume();
  3368. expected(Token::name(TokenType::Identifier));
  3369. return consume();
  3370. }
  3371. Token Parser::consume(TokenType expected_type)
  3372. {
  3373. if (!match(expected_type)) {
  3374. expected(Token::name(expected_type));
  3375. }
  3376. auto token = consume();
  3377. if (expected_type == TokenType::Identifier) {
  3378. if (m_state.strict_mode && is_strict_reserved_word(token.value()))
  3379. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()));
  3380. }
  3381. return token;
  3382. }
  3383. Token Parser::consume_and_validate_numeric_literal()
  3384. {
  3385. auto is_unprefixed_octal_number = [](StringView value) {
  3386. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  3387. };
  3388. auto literal_start = position();
  3389. auto token = consume(TokenType::NumericLiteral);
  3390. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  3391. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  3392. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  3393. syntax_error("Numeric literal must not be immediately followed by identifier");
  3394. return token;
  3395. }
  3396. void Parser::expected(const char* what)
  3397. {
  3398. auto message = m_state.current_token.message();
  3399. if (message.is_empty())
  3400. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  3401. syntax_error(message);
  3402. }
  3403. Position Parser::position() const
  3404. {
  3405. return {
  3406. m_state.current_token.line_number(),
  3407. m_state.current_token.line_column(),
  3408. m_state.current_token.offset(),
  3409. };
  3410. }
  3411. bool Parser::try_parse_arrow_function_expression_failed_at_position(const Position& position) const
  3412. {
  3413. auto it = m_token_memoizations.find(position);
  3414. if (it == m_token_memoizations.end())
  3415. return false;
  3416. return (*it).value.try_parse_arrow_function_expression_failed;
  3417. }
  3418. void Parser::set_try_parse_arrow_function_expression_failed_at_position(const Position& position, bool failed)
  3419. {
  3420. m_token_memoizations.set(position, { failed });
  3421. }
  3422. void Parser::syntax_error(const String& message, Optional<Position> position)
  3423. {
  3424. if (!position.has_value())
  3425. position = this->position();
  3426. m_state.errors.append({ message, position });
  3427. }
  3428. void Parser::save_state()
  3429. {
  3430. m_saved_state.append(m_state);
  3431. }
  3432. void Parser::load_state()
  3433. {
  3434. VERIFY(!m_saved_state.is_empty());
  3435. m_state = m_saved_state.take_last();
  3436. }
  3437. void Parser::discard_saved_state()
  3438. {
  3439. m_saved_state.take_last();
  3440. }
  3441. void Parser::check_identifier_name_for_assignment_validity(StringView name, bool force_strict)
  3442. {
  3443. // FIXME: this is now called from multiple places maybe the error message should be dynamic?
  3444. if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) {
  3445. syntax_error("Binding pattern target may not be a reserved word");
  3446. } else if (m_state.strict_mode || force_strict) {
  3447. if (name.is_one_of("arguments"sv, "eval"sv))
  3448. syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");
  3449. else if (is_strict_reserved_word(name))
  3450. syntax_error(String::formatted("Binding pattern target may not be called '{}' in strict mode", name));
  3451. }
  3452. }
  3453. bool Parser::match_assert_clause() const
  3454. {
  3455. return !m_state.current_token.trivia_contains_line_terminator() && m_state.current_token.original_value() == "assert"sv;
  3456. }
  3457. FlyString Parser::consume_string_value()
  3458. {
  3459. VERIFY(match(TokenType::StringLiteral));
  3460. auto string_token = consume();
  3461. FlyString value = parse_string_literal(string_token, false)->value();
  3462. // This also checks IsStringWellFormedUnicode which makes sure there is no unpaired surrogate
  3463. // Surrogates are at least 3 bytes
  3464. if (value.length() < 3)
  3465. return value;
  3466. Utf8View view { value.view().substring_view(value.length() - 3) };
  3467. VERIFY(view.length() <= 3);
  3468. auto codepoint = *view.begin();
  3469. if (Utf16View::is_high_surrogate(codepoint)) {
  3470. syntax_error("StringValue ending with unpaired high surrogate");
  3471. VERIFY(view.length() == 1);
  3472. }
  3473. return value;
  3474. }
  3475. // AssertClause, https://tc39.es/proposal-import-assertions/#prod-AssertClause
  3476. ModuleRequest Parser::parse_module_request()
  3477. {
  3478. // Does not include the 'from' since that is not always required.
  3479. if (!match(TokenType::StringLiteral)) {
  3480. expected("ModuleSpecifier (string)");
  3481. return ModuleRequest { "!!invalid!!" };
  3482. }
  3483. ModuleRequest request { consume_string_value() };
  3484. if (!match_assert_clause())
  3485. return request;
  3486. VERIFY(m_state.current_token.original_value() == "assert"sv);
  3487. consume(TokenType::Identifier);
  3488. consume(TokenType::CurlyOpen);
  3489. while (!done() && !match(TokenType::CurlyClose)) {
  3490. String key;
  3491. if (match(TokenType::StringLiteral)) {
  3492. key = parse_string_literal(m_state.current_token)->value().to_string();
  3493. consume();
  3494. } else if (match_identifier_name()) {
  3495. key = consume().value();
  3496. } else {
  3497. expected("IdentifierName or StringValue as AssertionKey");
  3498. consume();
  3499. }
  3500. consume(TokenType::Colon);
  3501. if (match(TokenType::StringLiteral)) {
  3502. for (auto& entries : request.assertions) {
  3503. if (entries.key == key)
  3504. syntax_error(String::formatted("Duplicate assertion clauses with name: {}", key));
  3505. }
  3506. request.add_assertion(move(key), parse_string_literal(m_state.current_token)->value().to_string());
  3507. }
  3508. consume(TokenType::StringLiteral);
  3509. if (match(TokenType::Comma))
  3510. consume(TokenType::Comma);
  3511. else
  3512. break;
  3513. }
  3514. consume(TokenType::CurlyClose);
  3515. return request;
  3516. }
  3517. static FlyString default_string_value = "default";
  3518. NonnullRefPtr<ImportStatement> Parser::parse_import_statement(Program& program)
  3519. {
  3520. // We use the extended syntax which adds:
  3521. // ImportDeclaration:
  3522. // import ImportClause FromClause [no LineTerminator here] AssertClause;
  3523. // import ModuleSpecifier [no LineTerminator here] AssertClause;
  3524. // From: https://tc39.es/proposal-import-assertions/#prod-ImportDeclaration
  3525. auto rule_start = push_start();
  3526. if (program.type() != Program::Type::Module)
  3527. syntax_error("Cannot use import statement outside a module");
  3528. consume(TokenType::Import);
  3529. if (match(TokenType::StringLiteral)) {
  3530. // import ModuleSpecifier ;
  3531. auto module_request = parse_module_request();
  3532. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request));
  3533. }
  3534. auto match_imported_binding = [&] {
  3535. return match_identifier() || match(TokenType::Yield) || match(TokenType::Await);
  3536. };
  3537. auto match_as = [&] {
  3538. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3539. };
  3540. bool continue_parsing = true;
  3541. struct ImportWithLocation {
  3542. ImportStatement::ImportEntry entry;
  3543. Position position;
  3544. };
  3545. Vector<ImportWithLocation> entries_with_location;
  3546. // import ImportClause FromClause ;
  3547. // ImportClause :
  3548. // ImportedDefaultBinding
  3549. // NameSpaceImport
  3550. // NamedImports
  3551. // ImportedDefaultBinding , NameSpaceImport
  3552. // ImportedDefaultBinding , NamedImports
  3553. if (match_imported_binding()) {
  3554. // ImportedDefaultBinding : ImportedBinding
  3555. auto id_position = position();
  3556. auto bound_name = consume().value();
  3557. entries_with_location.append({ { default_string_value, bound_name }, id_position });
  3558. if (match(TokenType::Comma)) {
  3559. consume(TokenType::Comma);
  3560. } else {
  3561. continue_parsing = false;
  3562. }
  3563. }
  3564. if (!continue_parsing) {
  3565. // skip the rest
  3566. } else if (match(TokenType::Asterisk)) {
  3567. // NameSpaceImport : * as ImportedBinding
  3568. consume(TokenType::Asterisk);
  3569. if (!match_as())
  3570. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3571. consume(TokenType::Identifier);
  3572. if (match_imported_binding()) {
  3573. auto namespace_position = position();
  3574. auto namespace_name = consume().value();
  3575. entries_with_location.append({ ImportStatement::ImportEntry({}, namespace_name, true), namespace_position });
  3576. } else {
  3577. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3578. }
  3579. } else if (match(TokenType::CurlyOpen)) {
  3580. // NamedImports :
  3581. // { ImportSpecifier ,_opt } (repeated any amount of times)
  3582. consume(TokenType::CurlyOpen);
  3583. while (!done() && !match(TokenType::CurlyClose)) {
  3584. if (match_identifier_name()) {
  3585. // ImportSpecifier : ImportedBinding
  3586. auto require_as = !match_imported_binding();
  3587. auto name_position = position();
  3588. auto name = consume().value();
  3589. if (match_as()) {
  3590. consume(TokenType::Identifier);
  3591. auto alias_position = position();
  3592. auto alias = consume_identifier().value();
  3593. check_identifier_name_for_assignment_validity(alias);
  3594. entries_with_location.append({ { name, alias }, alias_position });
  3595. } else if (require_as) {
  3596. syntax_error(String::formatted("Unexpected reserved word '{}'", name));
  3597. } else {
  3598. check_identifier_name_for_assignment_validity(name);
  3599. entries_with_location.append({ { name, name }, name_position });
  3600. }
  3601. } else if (match(TokenType::StringLiteral)) {
  3602. // ImportSpecifier : ModuleExportName as ImportedBinding
  3603. auto name = consume_string_value();
  3604. if (!match_as())
  3605. expected("as");
  3606. consume(TokenType::Identifier);
  3607. auto alias_position = position();
  3608. auto alias = consume_identifier().value();
  3609. check_identifier_name_for_assignment_validity(alias);
  3610. entries_with_location.append({ { move(name), alias }, alias_position });
  3611. } else {
  3612. expected("identifier");
  3613. break;
  3614. }
  3615. if (!match(TokenType::Comma))
  3616. break;
  3617. consume(TokenType::Comma);
  3618. }
  3619. consume(TokenType::CurlyClose);
  3620. } else {
  3621. expected("import clauses");
  3622. }
  3623. auto from_statement = consume(TokenType::Identifier).original_value();
  3624. if (from_statement != "from"sv)
  3625. syntax_error(String::formatted("Expected 'from' got {}", from_statement));
  3626. auto module_request = parse_module_request();
  3627. Vector<ImportStatement::ImportEntry> entries;
  3628. entries.ensure_capacity(entries_with_location.size());
  3629. for (auto& entry : entries_with_location) {
  3630. for (auto& import_statement : program.imports()) {
  3631. if (import_statement.has_bound_name(entry.entry.local_name))
  3632. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3633. }
  3634. for (auto& new_entry : entries) {
  3635. if (new_entry.local_name == entry.entry.local_name)
  3636. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3637. }
  3638. entries.append(move(entry.entry));
  3639. }
  3640. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request), move(entries));
  3641. }
  3642. NonnullRefPtr<ExportStatement> Parser::parse_export_statement(Program& program)
  3643. {
  3644. using ExportEntry = ExportStatement::ExportEntry;
  3645. // We use the extended syntax which adds:
  3646. // ExportDeclaration:
  3647. // export ExportFromClause FromClause [no LineTerminator here] AssertClause ;
  3648. // From: https://tc39.es/proposal-import-assertions/#prod-ExportDeclaration
  3649. auto rule_start = push_start();
  3650. if (program.type() != Program::Type::Module)
  3651. syntax_error("Cannot use export statement outside a module");
  3652. auto match_as = [&] {
  3653. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3654. };
  3655. auto match_from = [&] {
  3656. return match(TokenType::Identifier) && m_state.current_token.original_value() == "from"sv;
  3657. };
  3658. auto match_default = [&] {
  3659. return match(TokenType::Default) && m_state.current_token.original_value() == "default"sv;
  3660. };
  3661. consume(TokenType::Export);
  3662. struct EntryAndLocation {
  3663. ExportEntry entry;
  3664. Position position;
  3665. };
  3666. Vector<EntryAndLocation> entries_with_location;
  3667. RefPtr<ASTNode> expression = {};
  3668. bool is_default = false;
  3669. ModuleRequest from_specifier;
  3670. if (match_default()) {
  3671. is_default = true;
  3672. auto default_position = position();
  3673. consume(TokenType::Default);
  3674. FlyString local_name;
  3675. auto lookahead_token = next_token();
  3676. // Note: For some reason the spec here has declaration which can have no name
  3677. // and the rest of the parser is just not setup for that. With these
  3678. // hacks below we get through most things but we should probably figure
  3679. // out a better solution. I have attempted to explain why/what these "hacks" do below.
  3680. // The summary is treat named declarations just as declarations and hack around unnamed
  3681. // declarations with expression see also SourceTextModule::initialize_environment.
  3682. // As far as I'm aware the only problem (which is a tricky one) is:
  3683. // `export default function() {}()`
  3684. // Since we parse this as an expression you are immediately allowed to call it
  3685. // which is incorrect and this should give a SyntaxError.
  3686. auto match_function_declaration = [&] {
  3687. // Hack part 1.
  3688. // Match a function declaration with a name, since we have async and generator
  3689. // and asyncgenerator variants this is quite complicated.
  3690. auto current_type = m_state.current_token.type();
  3691. Lexer lookahead_lexer = m_state.lexer;
  3692. lookahead_lexer.next();
  3693. if (current_type == TokenType::Function) {
  3694. if (lookahead_token.type() == TokenType::Asterisk)
  3695. return lookahead_lexer.next().type() != TokenType::ParenOpen; // function * <name>
  3696. else
  3697. return lookahead_token.type() != TokenType::ParenOpen; // function <name>
  3698. }
  3699. if (current_type == TokenType::Async) {
  3700. if (lookahead_token.type() != TokenType::Function)
  3701. return false;
  3702. if (lookahead_token.trivia_contains_line_terminator())
  3703. return false;
  3704. auto lookahead_two_token = lookahead_lexer.next();
  3705. if (lookahead_two_token.type() == TokenType::Asterisk)
  3706. return lookahead_lexer.next().type() != TokenType::ParenOpen; // async function * <name>
  3707. else
  3708. return lookahead_two_token.type() != TokenType::ParenOpen; // async function <name>
  3709. }
  3710. return false;
  3711. };
  3712. if (match_function_declaration()) {
  3713. auto function_declaration = parse_function_node<FunctionDeclaration>();
  3714. m_state.current_scope_pusher->add_declaration(function_declaration);
  3715. local_name = function_declaration->name();
  3716. expression = move(function_declaration);
  3717. } else if (match(TokenType::Class) && lookahead_token.type() != TokenType::CurlyOpen && lookahead_token.type() != TokenType::Extends) {
  3718. // Hack part 2.
  3719. // Attempt to detect classes with names only as those are declarations,
  3720. // this actually seems to cover all cases already.
  3721. auto class_expression = parse_class_declaration();
  3722. m_state.current_scope_pusher->add_declaration(class_expression);
  3723. local_name = class_expression->name();
  3724. expression = move(class_expression);
  3725. } else if (match_expression()) {
  3726. // Hack part 3.
  3727. // Even though the unnamed declarations look like expression we should
  3728. // not treat them as such and thus not consume a semicolon after them.
  3729. bool special_case_declaration_without_name = match(TokenType::Class) || match(TokenType::Function) || (match(TokenType::Async) && lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator());
  3730. expression = parse_expression(2);
  3731. if (!special_case_declaration_without_name)
  3732. consume_or_insert_semicolon();
  3733. if (is<ClassExpression>(*expression)) {
  3734. auto const& class_expression = static_cast<ClassExpression&>(*expression);
  3735. if (class_expression.has_name())
  3736. local_name = class_expression.name();
  3737. }
  3738. } else {
  3739. expected("Declaration or assignment expression");
  3740. local_name = "!!invalid!!";
  3741. }
  3742. if (local_name.is_null()) {
  3743. local_name = ExportStatement::local_name_for_default;
  3744. }
  3745. entries_with_location.append({ ExportEntry::named_export(default_string_value, move(local_name)), default_position });
  3746. } else {
  3747. enum FromSpecifier {
  3748. NotAllowed,
  3749. Optional,
  3750. Required
  3751. } check_for_from { NotAllowed };
  3752. if (match(TokenType::Asterisk)) {
  3753. auto asterisk_position = position();
  3754. consume(TokenType::Asterisk);
  3755. if (match_as()) {
  3756. consume(TokenType::Identifier);
  3757. if (match_identifier_name()) {
  3758. auto namespace_position = position();
  3759. auto exported_name = consume().value();
  3760. entries_with_location.append({ ExportEntry::all_module_request(exported_name), namespace_position });
  3761. } else {
  3762. expected("identifier");
  3763. }
  3764. } else {
  3765. entries_with_location.append({ ExportEntry::all_but_default_entry(), asterisk_position });
  3766. }
  3767. check_for_from = Required;
  3768. } else if (match_declaration()) {
  3769. auto decl_position = position();
  3770. auto declaration = parse_declaration();
  3771. m_state.current_scope_pusher->add_declaration(declaration);
  3772. if (is<FunctionDeclaration>(*declaration)) {
  3773. auto& func = static_cast<FunctionDeclaration&>(*declaration);
  3774. entries_with_location.append({ ExportEntry::named_export(func.name(), func.name()), func.source_range().start });
  3775. } else if (is<ClassDeclaration>(*declaration)) {
  3776. auto& class_declaration = static_cast<ClassDeclaration&>(*declaration);
  3777. entries_with_location.append({ ExportEntry::named_export(class_declaration.name(), class_declaration.name()), class_declaration.source_range().start });
  3778. } else {
  3779. VERIFY(is<VariableDeclaration>(*declaration));
  3780. auto& variables = static_cast<VariableDeclaration&>(*declaration);
  3781. VERIFY(variables.is_lexical_declaration());
  3782. for (auto& decl : variables.declarations()) {
  3783. decl.target().visit(
  3784. [&](NonnullRefPtr<Identifier> const& identifier) {
  3785. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3786. },
  3787. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3788. binding->for_each_bound_name([&](auto& name) {
  3789. entries_with_location.append({ ExportEntry::named_export(name, name), decl_position });
  3790. });
  3791. });
  3792. }
  3793. }
  3794. expression = declaration;
  3795. } else if (match(TokenType::Var)) {
  3796. auto variable_position = position();
  3797. auto variable_declaration = parse_variable_declaration();
  3798. m_state.current_scope_pusher->add_declaration(variable_declaration);
  3799. for (auto& decl : variable_declaration->declarations()) {
  3800. decl.target().visit(
  3801. [&](NonnullRefPtr<Identifier> const& identifier) {
  3802. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3803. },
  3804. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3805. binding->for_each_bound_name([&](auto& name) {
  3806. entries_with_location.append({ ExportEntry::named_export(name, name), variable_position });
  3807. });
  3808. });
  3809. }
  3810. expression = variable_declaration;
  3811. } else if (match(TokenType::CurlyOpen)) {
  3812. consume(TokenType::CurlyOpen);
  3813. check_for_from = Optional;
  3814. auto parse_export_specifier = [&](bool lhs) -> FlyString {
  3815. if (match_identifier_name()) {
  3816. return consume().value();
  3817. }
  3818. if (match(TokenType::StringLiteral)) {
  3819. // It is a Syntax Error if ReferencedBindings of NamedExports contains any StringLiterals.
  3820. // Only for export { "a" as "b" }; // <-- no from
  3821. if (lhs)
  3822. check_for_from = Required;
  3823. return consume_string_value();
  3824. }
  3825. expected("ExportSpecifier (string or identifier)");
  3826. return {};
  3827. };
  3828. while (!done() && !match(TokenType::CurlyClose)) {
  3829. auto identifier_position = position();
  3830. auto identifier = parse_export_specifier(true);
  3831. if (match_as()) {
  3832. consume(TokenType::Identifier);
  3833. auto export_name = parse_export_specifier(false);
  3834. entries_with_location.append({ ExportEntry::named_export(move(export_name), move(identifier)), identifier_position });
  3835. } else {
  3836. entries_with_location.append({ ExportEntry::named_export(identifier, identifier), identifier_position });
  3837. }
  3838. if (!match(TokenType::Comma))
  3839. break;
  3840. consume(TokenType::Comma);
  3841. }
  3842. consume(TokenType::CurlyClose);
  3843. } else {
  3844. syntax_error("Unexpected token 'export'", rule_start.position());
  3845. }
  3846. if (check_for_from != NotAllowed && match_from()) {
  3847. consume(TokenType::Identifier);
  3848. from_specifier = parse_module_request();
  3849. } else if (check_for_from == Required) {
  3850. expected("from");
  3851. }
  3852. if (check_for_from != NotAllowed)
  3853. consume_or_insert_semicolon();
  3854. }
  3855. Vector<ExportStatement::ExportEntry> entries;
  3856. entries.ensure_capacity(entries_with_location.size());
  3857. for (auto& entry : entries_with_location) {
  3858. for (auto& export_statement : program.exports()) {
  3859. if (export_statement.has_export(entry.entry.export_name))
  3860. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3861. }
  3862. for (auto& new_entry : entries) {
  3863. if (new_entry.export_name == entry.entry.export_name)
  3864. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3865. }
  3866. entries.append(move(entry.entry));
  3867. }
  3868. return create_ast_node<ExportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(entries), is_default, move(from_specifier));
  3869. }
  3870. }