Parser.cpp 185 KB

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