Parser.cpp 194 KB

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