Parser.cpp 182 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229
  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::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. ScopePusher static_init_scope = ScopePusher::static_init_block_scope(*this, *static_init_block);
  1024. parse_statement_list(static_init_block);
  1025. consume(TokenType::CurlyClose);
  1026. 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()));
  1027. continue;
  1028. } else {
  1029. expected("property key");
  1030. }
  1031. // Constructor may be a StringLiteral or an Identifier.
  1032. if (!is_static && name == "constructor"sv) {
  1033. if (method_kind != ClassMethod::Kind::Method)
  1034. syntax_error("Class constructor may not be an accessor");
  1035. if (!constructor.is_null())
  1036. syntax_error("Classes may not have more than one constructor");
  1037. if (is_generator)
  1038. syntax_error("Class constructor may not be a generator");
  1039. if (is_async)
  1040. syntax_error("Class constructor may not be async");
  1041. is_constructor = true;
  1042. }
  1043. }
  1044. if (match(TokenType::ParenOpen)) {
  1045. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1046. if (!super_class.is_null() && !is_static && is_constructor)
  1047. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  1048. if (method_kind == ClassMethod::Kind::Getter)
  1049. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1050. if (method_kind == ClassMethod::Kind::Setter)
  1051. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1052. if (is_generator)
  1053. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1054. if (is_async)
  1055. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1056. auto function = parse_function_node<FunctionExpression>(parse_options);
  1057. if (is_constructor) {
  1058. constructor = move(function);
  1059. } else if (!property_key.is_null()) {
  1060. 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));
  1061. } else {
  1062. syntax_error("No key for class method");
  1063. }
  1064. } else if (is_generator || is_async) {
  1065. expected("ParenOpen");
  1066. consume();
  1067. } else if (property_key.is_null()) {
  1068. expected("property key");
  1069. consume();
  1070. } else {
  1071. if (name == "constructor"sv)
  1072. syntax_error("Class cannot have field named 'constructor'");
  1073. RefPtr<Expression> initializer;
  1074. bool contains_direct_call_to_eval = false;
  1075. if (match(TokenType::Equals)) {
  1076. consume();
  1077. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, true);
  1078. TemporaryChange field_initializer_rollback(m_state.in_class_field_initializer, true);
  1079. auto class_field_scope = ScopePusher::class_field_scope(*this);
  1080. initializer = parse_expression(2);
  1081. contains_direct_call_to_eval = class_field_scope.contains_direct_call_to_eval();
  1082. }
  1083. 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));
  1084. consume_or_insert_semicolon();
  1085. }
  1086. }
  1087. consume(TokenType::CurlyClose);
  1088. if (constructor.is_null()) {
  1089. auto constructor_body = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1090. if (!super_class.is_null()) {
  1091. // Set constructor to the result of parsing the source text
  1092. // constructor(... args){ super (...args);}
  1093. auto super_call = create_ast_node<SuperCall>(
  1094. { m_state.current_token.filename(), rule_start.position(), position() },
  1095. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  1096. constructor_body->append(create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  1097. constructor = create_ast_node<FunctionExpression>(
  1098. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  1099. Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Regular,
  1100. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1101. } else {
  1102. constructor = create_ast_node<FunctionExpression>(
  1103. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, move(constructor_body),
  1104. Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Regular,
  1105. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1106. }
  1107. }
  1108. // We could be in a subclass defined within the main class so must move all non declared private names to outer.
  1109. for (auto& private_name : referenced_private_names) {
  1110. if (found_private_names.contains(private_name))
  1111. continue;
  1112. if (outer_referenced_private_names)
  1113. outer_referenced_private_names->set(private_name);
  1114. else // FIXME: Make these error appear in the appropriate places.
  1115. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", private_name));
  1116. }
  1117. return create_ast_node<ClassExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(class_name), move(constructor), move(super_class), move(elements));
  1118. }
  1119. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  1120. {
  1121. auto rule_start = push_start();
  1122. if (match_unary_prefixed_expression())
  1123. return { parse_unary_prefixed_expression() };
  1124. auto try_arrow_function_parse_or_fail = [this](Position const& position, bool expect_paren, bool is_async = false) -> RefPtr<FunctionExpression> {
  1125. if (try_parse_arrow_function_expression_failed_at_position(position))
  1126. return nullptr;
  1127. auto arrow_function = try_parse_arrow_function_expression(expect_paren, is_async);
  1128. if (arrow_function)
  1129. return arrow_function;
  1130. set_try_parse_arrow_function_expression_failed_at_position(position, true);
  1131. return nullptr;
  1132. };
  1133. switch (m_state.current_token.type()) {
  1134. case TokenType::ParenOpen: {
  1135. auto paren_position = position();
  1136. consume(TokenType::ParenOpen);
  1137. if ((match(TokenType::ParenClose) || match_identifier() || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))) {
  1138. if (auto arrow_function_result = try_arrow_function_parse_or_fail(paren_position, true))
  1139. return { arrow_function_result.release_nonnull(), false };
  1140. }
  1141. auto expression = parse_expression(0);
  1142. consume(TokenType::ParenClose);
  1143. if (is<FunctionExpression>(*expression)) {
  1144. auto& function = static_cast<FunctionExpression&>(*expression);
  1145. if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv)
  1146. syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start);
  1147. if (function.kind() == FunctionKind::Async && function.name() == "await"sv)
  1148. syntax_error("function is not allowed to be called 'await' in this context", function.source_range().start);
  1149. }
  1150. return { move(expression) };
  1151. }
  1152. case TokenType::This:
  1153. consume();
  1154. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1155. case TokenType::Class:
  1156. return { parse_class_expression(false) };
  1157. case TokenType::Super:
  1158. consume();
  1159. if (!m_state.allow_super_property_lookup)
  1160. syntax_error("'super' keyword unexpected here");
  1161. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1162. case TokenType::EscapedKeyword:
  1163. if (match_invalid_escaped_keyword())
  1164. syntax_error("Keyword must not contain escaped characters");
  1165. [[fallthrough]];
  1166. case TokenType::Identifier: {
  1167. read_as_identifier:;
  1168. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false))
  1169. return { arrow_function_result.release_nonnull(), false };
  1170. auto string = m_state.current_token.value();
  1171. // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`)
  1172. if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string)))
  1173. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string));
  1174. return { parse_identifier() };
  1175. }
  1176. case TokenType::NumericLiteral:
  1177. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  1178. case TokenType::BigIntLiteral:
  1179. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1180. case TokenType::BoolLiteral:
  1181. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  1182. case TokenType::StringLiteral:
  1183. return { parse_string_literal(consume()) };
  1184. case TokenType::NullLiteral:
  1185. consume();
  1186. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1187. case TokenType::CurlyOpen:
  1188. return { parse_object_expression() };
  1189. case TokenType::Async: {
  1190. auto lookahead_token = next_token();
  1191. // No valid async function (arrow or not) can have a line terminator after the async since asi would kick in.
  1192. if (lookahead_token.trivia_contains_line_terminator())
  1193. goto read_as_identifier;
  1194. if (lookahead_token.type() == TokenType::Function)
  1195. return { parse_function_node<FunctionExpression>() };
  1196. if (lookahead_token.type() == TokenType::ParenOpen) {
  1197. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), true, true))
  1198. return { arrow_function_result.release_nonnull(), false };
  1199. } else if (lookahead_token.is_identifier_name()) {
  1200. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false, true))
  1201. return { arrow_function_result.release_nonnull(), false };
  1202. }
  1203. goto read_as_identifier;
  1204. }
  1205. case TokenType::Function:
  1206. return { parse_function_node<FunctionExpression>() };
  1207. case TokenType::BracketOpen:
  1208. return { parse_array_expression() };
  1209. case TokenType::RegexLiteral:
  1210. return { parse_regexp_literal() };
  1211. case TokenType::TemplateLiteralStart:
  1212. return { parse_template_literal(false) };
  1213. case TokenType::New: {
  1214. auto new_start = position();
  1215. auto new_target_result = try_parse_new_target_expression();
  1216. if (!new_target_result.is_null()) {
  1217. if (!m_state.in_function_context)
  1218. syntax_error("'new.target' not allowed outside of a function", new_start);
  1219. return { new_target_result.release_nonnull() };
  1220. }
  1221. return { parse_new_expression() };
  1222. }
  1223. case TokenType::Import: {
  1224. auto lookahead_token = next_token();
  1225. VERIFY(lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen);
  1226. if (lookahead_token.type() == TokenType::ParenOpen)
  1227. return { parse_import_call() };
  1228. if (auto import_meta = try_parse_import_meta_expression()) {
  1229. if (m_program_type != Program::Type::Module)
  1230. syntax_error("import.meta is only allowed in modules");
  1231. return { import_meta.release_nonnull() };
  1232. }
  1233. break;
  1234. }
  1235. case TokenType::Yield:
  1236. if (!m_state.in_generator_function_context)
  1237. goto read_as_identifier;
  1238. return { parse_yield_expression(), false };
  1239. case TokenType::Await:
  1240. if (!m_state.await_expression_is_valid)
  1241. goto read_as_identifier;
  1242. return { parse_await_expression() };
  1243. case TokenType::PrivateIdentifier:
  1244. if (next_token().type() != TokenType::In)
  1245. syntax_error("Cannot have a private identifier in expression if not followed by 'in'");
  1246. if (!is_private_identifier_valid())
  1247. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1248. return { create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1249. default:
  1250. if (match_identifier_name())
  1251. goto read_as_identifier;
  1252. break;
  1253. }
  1254. expected("primary expression");
  1255. consume();
  1256. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1257. }
  1258. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  1259. {
  1260. auto rule_start = push_start();
  1261. auto pattern = consume().value();
  1262. // Remove leading and trailing slash.
  1263. pattern = pattern.substring_view(1, pattern.length() - 2);
  1264. auto flags = String::empty();
  1265. auto parsed_flags = RegExpObject::default_flags;
  1266. if (match(TokenType::RegexFlags)) {
  1267. auto flags_start = position();
  1268. flags = consume().value();
  1269. auto parsed_flags_or_error = regex_flags_from_string(flags);
  1270. if (parsed_flags_or_error.is_error())
  1271. syntax_error(parsed_flags_or_error.release_error(), flags_start);
  1272. else
  1273. parsed_flags = parsed_flags_or_error.release_value();
  1274. }
  1275. auto parsed_pattern = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode));
  1276. auto parsed_regex = Regex<ECMA262>::parse_pattern(parsed_pattern, parsed_flags);
  1277. if (parsed_regex.error != regex::Error::NoError)
  1278. syntax_error(String::formatted("RegExp compile error: {}", Regex<ECMA262>(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position());
  1279. SourceRange range { m_state.current_token.filename(), rule_start.position(), position() };
  1280. return create_ast_node<RegExpLiteral>(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_string(), move(flags));
  1281. }
  1282. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  1283. {
  1284. auto rule_start = push_start();
  1285. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  1286. auto associativity = operator_associativity(m_state.current_token.type());
  1287. switch (m_state.current_token.type()) {
  1288. case TokenType::PlusPlus: {
  1289. consume();
  1290. auto rhs_start = position();
  1291. auto rhs = parse_expression(precedence, associativity);
  1292. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1293. // other engines throw ReferenceError for ++foo()
  1294. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1295. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1296. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1297. auto& identifier = static_cast<Identifier&>(*rhs);
  1298. auto& name = identifier.string();
  1299. check_identifier_name_for_assignment_validity(name);
  1300. }
  1301. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  1302. }
  1303. case TokenType::MinusMinus: {
  1304. consume();
  1305. auto rhs_start = position();
  1306. auto rhs = parse_expression(precedence, associativity);
  1307. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1308. // other engines throw ReferenceError for --foo()
  1309. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1310. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1311. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1312. auto& identifier = static_cast<Identifier&>(*rhs);
  1313. auto& name = identifier.string();
  1314. check_identifier_name_for_assignment_validity(name);
  1315. }
  1316. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  1317. }
  1318. case TokenType::ExclamationMark:
  1319. consume();
  1320. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  1321. case TokenType::Tilde:
  1322. consume();
  1323. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  1324. case TokenType::Plus:
  1325. consume();
  1326. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  1327. case TokenType::Minus:
  1328. consume();
  1329. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  1330. case TokenType::Typeof:
  1331. consume();
  1332. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  1333. case TokenType::Void:
  1334. consume();
  1335. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  1336. case TokenType::Delete: {
  1337. consume();
  1338. auto rhs_start = position();
  1339. auto rhs = parse_expression(precedence, associativity);
  1340. if (is<Identifier>(*rhs) && m_state.strict_mode) {
  1341. syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start);
  1342. }
  1343. if (is<MemberExpression>(*rhs)) {
  1344. auto& member_expression = static_cast<MemberExpression const&>(*rhs);
  1345. if (member_expression.ends_in_private_name())
  1346. syntax_error("Private fields cannot be deleted");
  1347. }
  1348. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, move(rhs));
  1349. }
  1350. default:
  1351. expected("primary expression");
  1352. consume();
  1353. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1354. }
  1355. }
  1356. NonnullRefPtr<Expression> Parser::parse_property_key()
  1357. {
  1358. auto rule_start = push_start();
  1359. if (match(TokenType::StringLiteral)) {
  1360. return parse_string_literal(consume());
  1361. } else if (match(TokenType::NumericLiteral)) {
  1362. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  1363. } else if (match(TokenType::BigIntLiteral)) {
  1364. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1365. } else if (match(TokenType::BracketOpen)) {
  1366. consume(TokenType::BracketOpen);
  1367. auto result = parse_expression(2);
  1368. consume(TokenType::BracketClose);
  1369. return result;
  1370. } else {
  1371. if (!match_identifier_name())
  1372. expected("IdentifierName");
  1373. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1374. }
  1375. }
  1376. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  1377. {
  1378. auto rule_start = push_start();
  1379. consume(TokenType::CurlyOpen);
  1380. NonnullRefPtrVector<ObjectProperty> properties;
  1381. ObjectProperty::Type property_type;
  1382. Optional<SourceRange> invalid_object_literal_property_range;
  1383. auto skip_to_next_property = [&] {
  1384. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  1385. consume();
  1386. };
  1387. // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate
  1388. // entries for "__proto__" and at least two of those entries were obtained from productions of
  1389. // the form PropertyDefinition : PropertyKey : AssignmentExpression .
  1390. bool has_direct_proto_property = false;
  1391. while (!done() && !match(TokenType::CurlyClose)) {
  1392. property_type = ObjectProperty::Type::KeyValue;
  1393. RefPtr<Expression> property_name;
  1394. RefPtr<Expression> property_value;
  1395. FunctionKind function_kind { FunctionKind::Regular };
  1396. if (match(TokenType::TripleDot)) {
  1397. consume();
  1398. property_name = parse_expression(4);
  1399. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, nullptr, ObjectProperty::Type::Spread, false));
  1400. if (!match(TokenType::Comma))
  1401. break;
  1402. consume(TokenType::Comma);
  1403. continue;
  1404. }
  1405. auto type = m_state.current_token.type();
  1406. if (match(TokenType::Async)) {
  1407. auto lookahead_token = next_token();
  1408. if (lookahead_token.type() != TokenType::ParenOpen && lookahead_token.type() != TokenType::Colon
  1409. && lookahead_token.type() != TokenType::Comma && lookahead_token.type() != TokenType::CurlyClose
  1410. && lookahead_token.type() != TokenType::Async
  1411. && !lookahead_token.trivia_contains_line_terminator()) {
  1412. consume(TokenType::Async);
  1413. function_kind = FunctionKind::Async;
  1414. }
  1415. }
  1416. if (match(TokenType::Asterisk)) {
  1417. consume();
  1418. property_type = ObjectProperty::Type::KeyValue;
  1419. property_name = parse_property_key();
  1420. VERIFY(function_kind == FunctionKind::Regular || function_kind == FunctionKind::Async);
  1421. function_kind = function_kind == FunctionKind::Regular ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  1422. } else if (match_identifier()) {
  1423. auto identifier = consume();
  1424. if (identifier.original_value() == "get"sv && match_property_key()) {
  1425. property_type = ObjectProperty::Type::Getter;
  1426. property_name = parse_property_key();
  1427. } else if (identifier.original_value() == "set"sv && match_property_key()) {
  1428. property_type = ObjectProperty::Type::Setter;
  1429. property_name = parse_property_key();
  1430. } else {
  1431. property_name = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1432. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1433. }
  1434. } else {
  1435. property_name = parse_property_key();
  1436. }
  1437. bool is_proto = (type == TokenType::StringLiteral || type == TokenType::Identifier) && is<StringLiteral>(*property_name) && static_cast<StringLiteral const&>(*property_name).value() == "__proto__";
  1438. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  1439. if (!match(TokenType::ParenOpen)) {
  1440. expected("'(' for object getter or setter property");
  1441. skip_to_next_property();
  1442. continue;
  1443. }
  1444. }
  1445. if (match(TokenType::Equals)) {
  1446. // Not a valid object literal, but a valid assignment target
  1447. consume();
  1448. // Parse the expression and throw it away
  1449. auto expression = parse_expression(2);
  1450. if (!invalid_object_literal_property_range.has_value())
  1451. invalid_object_literal_property_range = expression->source_range();
  1452. } else if (match(TokenType::ParenOpen)) {
  1453. VERIFY(property_name);
  1454. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1455. if (property_type == ObjectProperty::Type::Getter)
  1456. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1457. if (property_type == ObjectProperty::Type::Setter)
  1458. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1459. if (function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator)
  1460. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1461. if (function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator)
  1462. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1463. auto function = parse_function_node<FunctionExpression>(parse_options);
  1464. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, function, property_type, true));
  1465. } else if (match(TokenType::Colon)) {
  1466. if (!property_name) {
  1467. expected("a property name");
  1468. skip_to_next_property();
  1469. continue;
  1470. }
  1471. consume();
  1472. if (is_proto) {
  1473. if (has_direct_proto_property)
  1474. syntax_error("Property name '__proto__' must not appear more than once in object literal");
  1475. has_direct_proto_property = true;
  1476. }
  1477. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, parse_expression(2), property_type, false));
  1478. } else if (property_name && property_value) {
  1479. if (m_state.strict_mode && is<StringLiteral>(*property_name)) {
  1480. auto& string_literal = static_cast<StringLiteral const&>(*property_name);
  1481. if (is_strict_reserved_word(string_literal.value()))
  1482. syntax_error(String::formatted("'{}' is a reserved keyword", string_literal.value()));
  1483. }
  1484. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_name, *property_value, property_type, false));
  1485. } else {
  1486. expected("a property");
  1487. skip_to_next_property();
  1488. continue;
  1489. }
  1490. if (!match(TokenType::Comma))
  1491. break;
  1492. consume(TokenType::Comma);
  1493. }
  1494. consume(TokenType::CurlyClose);
  1495. return create_ast_node<ObjectExpression>(
  1496. { m_state.current_token.filename(), rule_start.position(), position() },
  1497. move(properties),
  1498. move(invalid_object_literal_property_range));
  1499. }
  1500. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  1501. {
  1502. auto rule_start = push_start();
  1503. consume(TokenType::BracketOpen);
  1504. Vector<RefPtr<Expression>> elements;
  1505. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  1506. RefPtr<Expression> expression;
  1507. if (match(TokenType::TripleDot)) {
  1508. consume(TokenType::TripleDot);
  1509. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  1510. } else if (match_expression()) {
  1511. expression = parse_expression(2);
  1512. }
  1513. elements.append(expression);
  1514. if (!match(TokenType::Comma))
  1515. break;
  1516. consume(TokenType::Comma);
  1517. }
  1518. consume(TokenType::BracketClose);
  1519. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  1520. }
  1521. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(const Token& token, bool in_template_literal)
  1522. {
  1523. auto rule_start = push_start();
  1524. auto status = Token::StringValueStatus::Ok;
  1525. auto string = token.string_value(status);
  1526. if (status != Token::StringValueStatus::Ok) {
  1527. String message;
  1528. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  1529. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  1530. if (in_template_literal)
  1531. message = "Octal escape sequence not allowed in template literal";
  1532. else if (m_state.strict_mode)
  1533. message = "Octal escape sequence in string literal not allowed in strict mode";
  1534. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  1535. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  1536. message = String::formatted("Malformed {} escape sequence", type);
  1537. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  1538. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  1539. } else {
  1540. VERIFY_NOT_REACHED();
  1541. }
  1542. if (!message.is_empty())
  1543. syntax_error(message, Position { token.line_number(), token.line_column() });
  1544. }
  1545. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  1546. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  1547. }
  1548. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  1549. {
  1550. auto rule_start = push_start();
  1551. consume(TokenType::TemplateLiteralStart);
  1552. NonnullRefPtrVector<Expression> expressions;
  1553. NonnullRefPtrVector<Expression> raw_strings;
  1554. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  1555. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  1556. expressions.append(string_literal);
  1557. if (is_tagged)
  1558. raw_strings.append(string_literal);
  1559. };
  1560. if (!match(TokenType::TemplateLiteralString))
  1561. append_empty_string();
  1562. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  1563. if (match(TokenType::TemplateLiteralString)) {
  1564. auto token = consume();
  1565. expressions.append(parse_string_literal(token, true));
  1566. if (is_tagged)
  1567. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.raw_template_value()));
  1568. } else if (match(TokenType::TemplateLiteralExprStart)) {
  1569. consume(TokenType::TemplateLiteralExprStart);
  1570. if (match(TokenType::TemplateLiteralExprEnd)) {
  1571. syntax_error("Empty template literal expression block");
  1572. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1573. }
  1574. expressions.append(parse_expression(0));
  1575. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1576. syntax_error("Unterminated template literal");
  1577. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1578. }
  1579. consume(TokenType::TemplateLiteralExprEnd);
  1580. if (!match(TokenType::TemplateLiteralString))
  1581. append_empty_string();
  1582. } else {
  1583. expected("Template literal string or expression");
  1584. break;
  1585. }
  1586. }
  1587. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1588. syntax_error("Unterminated template literal");
  1589. } else {
  1590. consume(TokenType::TemplateLiteralEnd);
  1591. }
  1592. if (is_tagged)
  1593. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  1594. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1595. }
  1596. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, const Vector<TokenType>& forbidden)
  1597. {
  1598. auto rule_start = push_start();
  1599. auto [expression, should_continue_parsing] = parse_primary_expression();
  1600. auto check_for_invalid_object_property = [&](auto& expression) {
  1601. if (is<ObjectExpression>(*expression)) {
  1602. if (auto range = static_cast<ObjectExpression&>(*expression).invalid_property_range(); range.has_value())
  1603. syntax_error("Invalid property in object literal", range->start);
  1604. }
  1605. };
  1606. if (is<Identifier>(*expression) && m_state.current_scope_pusher) {
  1607. auto identifier_instance = static_ptr_cast<Identifier>(expression);
  1608. auto function_scope = m_state.current_scope_pusher->last_function_scope();
  1609. auto function_parent_scope = function_scope ? function_scope->parent_scope() : nullptr;
  1610. bool has_not_been_declared_as_variable = true;
  1611. for (auto scope = m_state.current_scope_pusher; scope != function_parent_scope; scope = scope->parent_scope()) {
  1612. if (scope->has_declaration(identifier_instance->string())) {
  1613. has_not_been_declared_as_variable = false;
  1614. break;
  1615. }
  1616. }
  1617. if (has_not_been_declared_as_variable) {
  1618. if (identifier_instance->string() == "arguments"sv)
  1619. m_state.current_scope_pusher->set_contains_access_to_arguments_object();
  1620. }
  1621. }
  1622. while (match(TokenType::TemplateLiteralStart)) {
  1623. auto template_literal = parse_template_literal(true);
  1624. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1625. }
  1626. if (should_continue_parsing) {
  1627. while (match_secondary_expression(forbidden)) {
  1628. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  1629. if (new_precedence < min_precedence)
  1630. break;
  1631. if (new_precedence == min_precedence && associativity == Associativity::Left)
  1632. break;
  1633. check_for_invalid_object_property(expression);
  1634. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  1635. expression = parse_secondary_expression(move(expression), new_precedence, new_associativity);
  1636. while (match(TokenType::TemplateLiteralStart) && !is<UpdateExpression>(*expression)) {
  1637. auto template_literal = parse_template_literal(true);
  1638. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1639. }
  1640. }
  1641. }
  1642. if (is<SuperExpression>(*expression))
  1643. syntax_error("'super' keyword unexpected here");
  1644. check_for_invalid_object_property(expression);
  1645. if (is<CallExpression>(*expression) && m_state.current_scope_pusher) {
  1646. auto& callee = static_ptr_cast<CallExpression>(expression)->callee();
  1647. if (is<Identifier>(callee)) {
  1648. auto& identifier_instance = static_cast<Identifier const&>(callee);
  1649. if (identifier_instance.string() == "eval"sv) {
  1650. bool has_not_been_declared_as_variable = true;
  1651. for (auto scope = m_state.current_scope_pusher; scope; scope = scope->parent_scope()) {
  1652. if (scope->has_declaration(identifier_instance.string())) {
  1653. has_not_been_declared_as_variable = false;
  1654. break;
  1655. }
  1656. }
  1657. if (has_not_been_declared_as_variable)
  1658. m_state.current_scope_pusher->set_contains_direct_call_to_eval();
  1659. }
  1660. }
  1661. }
  1662. if (match(TokenType::Comma) && min_precedence <= 1) {
  1663. NonnullRefPtrVector<Expression> expressions;
  1664. expressions.append(expression);
  1665. while (match(TokenType::Comma)) {
  1666. consume();
  1667. expressions.append(parse_expression(2));
  1668. }
  1669. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  1670. }
  1671. return expression;
  1672. }
  1673. NonnullRefPtr<Expression> Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1674. {
  1675. auto rule_start = push_start();
  1676. switch (m_state.current_token.type()) {
  1677. case TokenType::Plus:
  1678. consume();
  1679. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity));
  1680. case TokenType::PlusEquals:
  1681. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity);
  1682. case TokenType::Minus:
  1683. consume();
  1684. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity));
  1685. case TokenType::MinusEquals:
  1686. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity);
  1687. case TokenType::Asterisk:
  1688. consume();
  1689. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity));
  1690. case TokenType::AsteriskEquals:
  1691. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity);
  1692. case TokenType::Slash:
  1693. consume();
  1694. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity));
  1695. case TokenType::SlashEquals:
  1696. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity);
  1697. case TokenType::Percent:
  1698. consume();
  1699. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity));
  1700. case TokenType::PercentEquals:
  1701. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity);
  1702. case TokenType::DoubleAsterisk:
  1703. consume();
  1704. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity));
  1705. case TokenType::DoubleAsteriskEquals:
  1706. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity);
  1707. case TokenType::GreaterThan:
  1708. consume();
  1709. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity));
  1710. case TokenType::GreaterThanEquals:
  1711. consume();
  1712. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1713. case TokenType::LessThan:
  1714. consume();
  1715. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity));
  1716. case TokenType::LessThanEquals:
  1717. consume();
  1718. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity));
  1719. case TokenType::EqualsEqualsEquals:
  1720. consume();
  1721. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyEquals, move(lhs), parse_expression(min_precedence, associativity));
  1722. case TokenType::ExclamationMarkEqualsEquals:
  1723. consume();
  1724. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyInequals, move(lhs), parse_expression(min_precedence, associativity));
  1725. case TokenType::EqualsEquals:
  1726. consume();
  1727. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyEquals, move(lhs), parse_expression(min_precedence, associativity));
  1728. case TokenType::ExclamationMarkEquals:
  1729. consume();
  1730. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyInequals, move(lhs), parse_expression(min_precedence, associativity));
  1731. case TokenType::In:
  1732. consume();
  1733. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1734. case TokenType::Instanceof:
  1735. consume();
  1736. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity));
  1737. case TokenType::Ampersand:
  1738. consume();
  1739. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity));
  1740. case TokenType::AmpersandEquals:
  1741. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity);
  1742. case TokenType::Pipe:
  1743. consume();
  1744. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity));
  1745. case TokenType::PipeEquals:
  1746. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity);
  1747. case TokenType::Caret:
  1748. consume();
  1749. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity));
  1750. case TokenType::CaretEquals:
  1751. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity);
  1752. case TokenType::ShiftLeft:
  1753. consume();
  1754. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity));
  1755. case TokenType::ShiftLeftEquals:
  1756. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity);
  1757. case TokenType::ShiftRight:
  1758. consume();
  1759. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity));
  1760. case TokenType::ShiftRightEquals:
  1761. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity);
  1762. case TokenType::UnsignedShiftRight:
  1763. consume();
  1764. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity));
  1765. case TokenType::UnsignedShiftRightEquals:
  1766. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity);
  1767. case TokenType::ParenOpen:
  1768. return parse_call_expression(move(lhs));
  1769. case TokenType::Equals:
  1770. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity);
  1771. case TokenType::Period:
  1772. consume();
  1773. if (match(TokenType::PrivateIdentifier)) {
  1774. if (!is_private_identifier_valid())
  1775. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1776. else if (is<SuperExpression>(*lhs))
  1777. syntax_error(String::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value()));
  1778. 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()));
  1779. } else if (!match_identifier_name()) {
  1780. expected("IdentifierName");
  1781. }
  1782. 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()));
  1783. case TokenType::BracketOpen: {
  1784. consume(TokenType::BracketOpen);
  1785. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1786. consume(TokenType::BracketClose);
  1787. return expression;
  1788. }
  1789. case TokenType::PlusPlus:
  1790. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1791. // other engines throw ReferenceError for foo()++
  1792. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1793. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1794. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1795. auto& identifier = static_cast<Identifier&>(*lhs);
  1796. auto& name = identifier.string();
  1797. check_identifier_name_for_assignment_validity(name);
  1798. }
  1799. consume();
  1800. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1801. case TokenType::MinusMinus:
  1802. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1803. // other engines throw ReferenceError for foo()--
  1804. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1805. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1806. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1807. auto& identifier = static_cast<Identifier&>(*lhs);
  1808. auto& name = identifier.string();
  1809. check_identifier_name_for_assignment_validity(name);
  1810. }
  1811. consume();
  1812. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1813. case TokenType::DoubleAmpersand:
  1814. consume();
  1815. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity));
  1816. case TokenType::DoubleAmpersandEquals:
  1817. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity);
  1818. case TokenType::DoublePipe:
  1819. consume();
  1820. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity));
  1821. case TokenType::DoublePipeEquals:
  1822. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity);
  1823. case TokenType::DoubleQuestionMark:
  1824. consume();
  1825. return create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity));
  1826. case TokenType::DoubleQuestionMarkEquals:
  1827. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity);
  1828. case TokenType::QuestionMark:
  1829. return parse_conditional_expression(move(lhs));
  1830. case TokenType::QuestionMarkPeriod:
  1831. // FIXME: This should allow `(new Foo)?.bar', but as our parser strips parenthesis,
  1832. // we can't really tell if `lhs' was parenthesized at this point.
  1833. if (is<NewExpression>(lhs.ptr())) {
  1834. syntax_error("'new' cannot be used with optional chaining", position());
  1835. consume();
  1836. return lhs;
  1837. }
  1838. return parse_optional_chain(move(lhs));
  1839. default:
  1840. expected("secondary expression");
  1841. consume();
  1842. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1843. }
  1844. }
  1845. bool Parser::is_private_identifier_valid() const
  1846. {
  1847. VERIFY(match(TokenType::PrivateIdentifier));
  1848. if (!m_state.referenced_private_names)
  1849. return false;
  1850. // We might not have hit the declaration yet so class will check this in the end
  1851. m_state.referenced_private_names->set(m_state.current_token.value());
  1852. return true;
  1853. }
  1854. RefPtr<BindingPattern> Parser::synthesize_binding_pattern(Expression const& expression)
  1855. {
  1856. VERIFY(is<ArrayExpression>(expression) || is<ObjectExpression>(expression));
  1857. // Clear any syntax error that has occurred in the range that 'expression' spans.
  1858. m_state.errors.remove_all_matching([range = expression.source_range()](auto const& error) {
  1859. return error.position.has_value() && range.contains(*error.position);
  1860. });
  1861. // Make a parser and parse the source for this expression as a binding pattern.
  1862. auto source = m_state.lexer.source().substring_view(expression.source_range().start.offset - 2, expression.source_range().end.offset - expression.source_range().start.offset);
  1863. Lexer lexer { source, m_state.lexer.filename(), expression.source_range().start.line, expression.source_range().start.column };
  1864. Parser parser { lexer };
  1865. parser.m_state.strict_mode = m_state.strict_mode;
  1866. parser.m_state.allow_super_property_lookup = m_state.allow_super_property_lookup;
  1867. parser.m_state.allow_super_constructor_call = m_state.allow_super_constructor_call;
  1868. parser.m_state.in_function_context = m_state.in_function_context;
  1869. parser.m_state.in_formal_parameter_context = m_state.in_formal_parameter_context;
  1870. parser.m_state.in_generator_function_context = m_state.in_generator_function_context;
  1871. parser.m_state.await_expression_is_valid = m_state.await_expression_is_valid;
  1872. parser.m_state.in_arrow_function_context = m_state.in_arrow_function_context;
  1873. parser.m_state.in_break_context = m_state.in_break_context;
  1874. parser.m_state.in_continue_context = m_state.in_continue_context;
  1875. parser.m_state.string_legacy_octal_escape_sequence_in_scope = m_state.string_legacy_octal_escape_sequence_in_scope;
  1876. parser.m_state.in_class_field_initializer = m_state.in_class_field_initializer;
  1877. parser.m_state.in_class_static_init_block = m_state.in_class_static_init_block;
  1878. parser.m_state.referenced_private_names = m_state.referenced_private_names;
  1879. auto result = parser.parse_binding_pattern(AllowDuplicates::Yes, AllowMemberExpressions::Yes);
  1880. if (parser.has_errors())
  1881. m_state.errors.extend(parser.errors());
  1882. return result;
  1883. }
  1884. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity)
  1885. {
  1886. auto rule_start = push_start();
  1887. VERIFY(match(TokenType::Equals)
  1888. || match(TokenType::PlusEquals)
  1889. || match(TokenType::MinusEquals)
  1890. || match(TokenType::AsteriskEquals)
  1891. || match(TokenType::SlashEquals)
  1892. || match(TokenType::PercentEquals)
  1893. || match(TokenType::DoubleAsteriskEquals)
  1894. || match(TokenType::AmpersandEquals)
  1895. || match(TokenType::PipeEquals)
  1896. || match(TokenType::CaretEquals)
  1897. || match(TokenType::ShiftLeftEquals)
  1898. || match(TokenType::ShiftRightEquals)
  1899. || match(TokenType::UnsignedShiftRightEquals)
  1900. || match(TokenType::DoubleAmpersandEquals)
  1901. || match(TokenType::DoublePipeEquals)
  1902. || match(TokenType::DoubleQuestionMarkEquals));
  1903. consume();
  1904. if (assignment_op == AssignmentOp::Assignment) {
  1905. if (is<ArrayExpression>(*lhs) || is<ObjectExpression>(*lhs)) {
  1906. auto binding_pattern = synthesize_binding_pattern(*lhs);
  1907. if (binding_pattern) {
  1908. auto rhs = parse_expression(min_precedence, associativity);
  1909. return create_ast_node<AssignmentExpression>(
  1910. { m_state.current_token.filename(), rule_start.position(), position() },
  1911. assignment_op,
  1912. binding_pattern.release_nonnull(),
  1913. move(rhs));
  1914. }
  1915. }
  1916. }
  1917. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1918. syntax_error("Invalid left-hand side in assignment");
  1919. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1920. auto name = static_cast<const Identifier&>(*lhs).string();
  1921. check_identifier_name_for_assignment_validity(name);
  1922. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1923. syntax_error("Cannot assign to function call");
  1924. }
  1925. auto rhs = parse_expression(min_precedence, associativity);
  1926. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1927. }
  1928. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1929. {
  1930. auto identifier_start = position();
  1931. auto token = consume_identifier();
  1932. if (m_state.in_class_field_initializer && token.value() == "arguments"sv)
  1933. syntax_error("'arguments' is not allowed in class field initializer");
  1934. return create_ast_node<Identifier>(
  1935. { m_state.current_token.filename(), identifier_start, position() },
  1936. token.value());
  1937. }
  1938. Vector<CallExpression::Argument> Parser::parse_arguments()
  1939. {
  1940. Vector<CallExpression::Argument> arguments;
  1941. consume(TokenType::ParenOpen);
  1942. while (match_expression() || match(TokenType::TripleDot)) {
  1943. if (match(TokenType::TripleDot)) {
  1944. consume();
  1945. arguments.append({ parse_expression(2), true });
  1946. } else {
  1947. arguments.append({ parse_expression(2), false });
  1948. }
  1949. if (!match(TokenType::Comma))
  1950. break;
  1951. consume();
  1952. }
  1953. consume(TokenType::ParenClose);
  1954. return arguments;
  1955. }
  1956. NonnullRefPtr<Expression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  1957. {
  1958. auto rule_start = push_start();
  1959. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  1960. syntax_error("'super' keyword unexpected here");
  1961. auto arguments = parse_arguments();
  1962. if (is<SuperExpression>(*lhs))
  1963. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  1964. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  1965. }
  1966. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  1967. {
  1968. auto rule_start = push_start();
  1969. consume(TokenType::New);
  1970. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod });
  1971. if (is<ImportCall>(*callee))
  1972. syntax_error("Cannot call new on dynamic import", callee->source_range().start);
  1973. Vector<CallExpression::Argument> arguments;
  1974. if (match(TokenType::ParenOpen)) {
  1975. consume(TokenType::ParenOpen);
  1976. while (match_expression() || match(TokenType::TripleDot)) {
  1977. if (match(TokenType::TripleDot)) {
  1978. consume();
  1979. arguments.append({ parse_expression(2), true });
  1980. } else {
  1981. arguments.append({ parse_expression(2), false });
  1982. }
  1983. if (!match(TokenType::Comma))
  1984. break;
  1985. consume();
  1986. }
  1987. consume(TokenType::ParenClose);
  1988. }
  1989. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  1990. }
  1991. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  1992. {
  1993. auto rule_start = push_start();
  1994. if (m_state.in_formal_parameter_context)
  1995. syntax_error("'Yield' expression is not allowed in formal parameters of generator function");
  1996. consume(TokenType::Yield);
  1997. RefPtr<Expression> argument;
  1998. bool yield_from = false;
  1999. if (!m_state.current_token.trivia_contains_line_terminator()) {
  2000. if (match(TokenType::Asterisk)) {
  2001. consume();
  2002. yield_from = true;
  2003. }
  2004. if (yield_from || match_expression() || match(TokenType::Class))
  2005. argument = parse_expression(2);
  2006. }
  2007. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  2008. }
  2009. NonnullRefPtr<AwaitExpression> Parser::parse_await_expression()
  2010. {
  2011. auto rule_start = push_start();
  2012. if (m_state.in_formal_parameter_context)
  2013. syntax_error("'Await' expression is not allowed in formal parameters of an async function");
  2014. consume(TokenType::Await);
  2015. auto precedence = g_operator_precedence.get(TokenType::Await);
  2016. auto associativity = operator_associativity(TokenType::Await);
  2017. auto argument = parse_expression(precedence, associativity);
  2018. return create_ast_node<AwaitExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument));
  2019. }
  2020. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  2021. {
  2022. auto rule_start = push_start();
  2023. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  2024. syntax_error("'return' not allowed outside of a function");
  2025. consume(TokenType::Return);
  2026. // Automatic semicolon insertion: terminate statement when return is followed by newline
  2027. if (m_state.current_token.trivia_contains_line_terminator())
  2028. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2029. if (match_expression()) {
  2030. auto expression = parse_expression(0);
  2031. consume_or_insert_semicolon();
  2032. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2033. }
  2034. consume_or_insert_semicolon();
  2035. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2036. }
  2037. void Parser::parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions)
  2038. {
  2039. while (!done()) {
  2040. if (match_declaration()) {
  2041. auto declaration = parse_declaration();
  2042. VERIFY(m_state.current_scope_pusher);
  2043. m_state.current_scope_pusher->add_declaration(declaration);
  2044. output_node.append(move(declaration));
  2045. } else if (match_statement()) {
  2046. output_node.append(parse_statement(allow_labelled_functions));
  2047. } else {
  2048. break;
  2049. }
  2050. }
  2051. }
  2052. // FunctionBody, https://tc39.es/ecma262/#prod-FunctionBody
  2053. NonnullRefPtr<FunctionBody> Parser::parse_function_body(Vector<FunctionDeclaration::Parameter> const& parameters, FunctionKind function_kind, bool& contains_direct_call_to_eval)
  2054. {
  2055. auto rule_start = push_start();
  2056. auto function_body = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  2057. ScopePusher function_scope = ScopePusher::function_scope(*this, function_body, parameters); // FIXME <-
  2058. consume(TokenType::CurlyOpen);
  2059. auto has_use_strict = parse_directive(function_body);
  2060. bool previous_strict_mode = m_state.strict_mode;
  2061. if (has_use_strict) {
  2062. m_state.strict_mode = true;
  2063. function_body->set_strict_mode();
  2064. if (!is_simple_parameter_list(parameters))
  2065. syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");
  2066. } else if (previous_strict_mode) {
  2067. function_body->set_strict_mode();
  2068. }
  2069. parse_statement_list(function_body);
  2070. // If the function contains 'use strict' we need to check the parameters (again).
  2071. if (function_body->in_strict_mode() || function_kind != FunctionKind::Regular) {
  2072. Vector<StringView> parameter_names;
  2073. for (auto& parameter : parameters) {
  2074. parameter.binding.visit(
  2075. [&](FlyString const& parameter_name) {
  2076. check_identifier_name_for_assignment_validity(parameter_name, function_body->in_strict_mode());
  2077. if (function_kind == FunctionKind::Generator && parameter_name == "yield"sv)
  2078. syntax_error("Parameter name 'yield' not allowed in this context");
  2079. if (function_kind == FunctionKind::Async && parameter_name == "await"sv)
  2080. syntax_error("Parameter name 'await' not allowed in this context");
  2081. for (auto& previous_name : parameter_names) {
  2082. if (previous_name == parameter_name) {
  2083. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name));
  2084. }
  2085. }
  2086. parameter_names.append(parameter_name);
  2087. },
  2088. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2089. binding->for_each_bound_name([&](auto& bound_name) {
  2090. if (function_kind == FunctionKind::Generator && bound_name == "yield"sv)
  2091. syntax_error("Parameter name 'yield' not allowed in this context");
  2092. if (function_kind == FunctionKind::Async && bound_name == "await"sv)
  2093. syntax_error("Parameter name 'await' not allowed in this context");
  2094. for (auto& previous_name : parameter_names) {
  2095. if (previous_name == bound_name) {
  2096. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", bound_name));
  2097. break;
  2098. }
  2099. }
  2100. parameter_names.append(bound_name);
  2101. });
  2102. });
  2103. }
  2104. }
  2105. consume(TokenType::CurlyClose);
  2106. m_state.strict_mode = previous_strict_mode;
  2107. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  2108. return function_body;
  2109. }
  2110. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  2111. {
  2112. auto rule_start = push_start();
  2113. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2114. ScopePusher block_scope = ScopePusher::block_scope(*this, block);
  2115. consume(TokenType::CurlyOpen);
  2116. parse_statement_list(block);
  2117. consume(TokenType::CurlyClose);
  2118. return block;
  2119. }
  2120. template<typename FunctionNodeType>
  2121. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options)
  2122. {
  2123. auto rule_start = push_start();
  2124. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  2125. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  2126. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  2127. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  2128. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  2129. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, false);
  2130. TemporaryChange might_need_arguments_object_rollback(m_state.function_might_need_arguments_object, false);
  2131. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  2132. FunctionKind function_kind;
  2133. if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0 && (parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2134. function_kind = FunctionKind::AsyncGenerator;
  2135. else if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0)
  2136. function_kind = FunctionKind::Generator;
  2137. else if ((parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2138. function_kind = FunctionKind::Async;
  2139. else
  2140. function_kind = FunctionKind::Regular;
  2141. String name;
  2142. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  2143. if (function_kind == FunctionKind::Regular && match(TokenType::Async) && !next_token().trivia_contains_line_terminator()) {
  2144. function_kind = FunctionKind::Async;
  2145. consume(TokenType::Async);
  2146. parse_options = parse_options | FunctionNodeParseOptions::IsAsyncFunction;
  2147. }
  2148. consume(TokenType::Function);
  2149. if (match(TokenType::Asterisk)) {
  2150. function_kind = function_kind == FunctionKind::Regular ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  2151. consume(TokenType::Asterisk);
  2152. parse_options = parse_options | FunctionNodeParseOptions::IsGeneratorFunction;
  2153. }
  2154. if (FunctionNodeType::must_have_name() || match_identifier())
  2155. name = consume_identifier().value();
  2156. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  2157. name = consume().value();
  2158. check_identifier_name_for_assignment_validity(name);
  2159. if (m_state.in_class_static_init_block && name == "await"sv)
  2160. syntax_error("'await' is a reserved word");
  2161. }
  2162. TemporaryChange class_static_initializer_rollback(m_state.in_class_static_init_block, false);
  2163. TemporaryChange generator_change(m_state.in_generator_function_context, function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator);
  2164. TemporaryChange async_change(m_state.await_expression_is_valid, function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator);
  2165. consume(TokenType::ParenOpen);
  2166. i32 function_length = -1;
  2167. auto parameters = parse_formal_parameters(function_length, parse_options);
  2168. consume(TokenType::ParenClose);
  2169. if (function_length == -1)
  2170. function_length = parameters.size();
  2171. TemporaryChange function_context_rollback(m_state.in_function_context, true);
  2172. auto old_labels_in_scope = move(m_state.labels_in_scope);
  2173. ScopeGuard guard([&]() {
  2174. m_state.labels_in_scope = move(old_labels_in_scope);
  2175. });
  2176. bool contains_direct_call_to_eval = false;
  2177. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  2178. auto has_strict_directive = body->in_strict_mode();
  2179. if (has_strict_directive)
  2180. check_identifier_name_for_assignment_validity(name, true);
  2181. return create_ast_node<FunctionNodeType>(
  2182. { m_state.current_token.filename(), rule_start.position(), position() },
  2183. name, move(body), move(parameters), function_length,
  2184. function_kind, has_strict_directive, m_state.function_might_need_arguments_object,
  2185. contains_direct_call_to_eval);
  2186. }
  2187. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  2188. {
  2189. auto rule_start = push_start();
  2190. bool has_default_parameter = false;
  2191. bool has_rest_parameter = false;
  2192. TemporaryChange formal_parameter_context_change { m_state.in_formal_parameter_context, true };
  2193. Vector<FunctionNode::Parameter> parameters;
  2194. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  2195. if (auto pattern = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No))
  2196. return pattern.release_nonnull();
  2197. auto token = consume_identifier();
  2198. auto parameter_name = token.value();
  2199. check_identifier_name_for_assignment_validity(parameter_name);
  2200. for (auto& parameter : parameters) {
  2201. bool has_same_name = parameter.binding.visit(
  2202. [&](FlyString const& name) {
  2203. return name == parameter_name;
  2204. },
  2205. [&](NonnullRefPtr<BindingPattern> const& bindings) {
  2206. bool found_duplicate = false;
  2207. bindings->for_each_bound_name([&](auto& bound_name) {
  2208. if (bound_name == parameter_name)
  2209. found_duplicate = true;
  2210. });
  2211. return found_duplicate;
  2212. });
  2213. if (!has_same_name)
  2214. continue;
  2215. String message;
  2216. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  2217. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  2218. else if (m_state.strict_mode)
  2219. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  2220. else if (has_default_parameter || match(TokenType::Equals))
  2221. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  2222. else if (has_rest_parameter)
  2223. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  2224. if (!message.is_empty())
  2225. syntax_error(message, Position { token.line_number(), token.line_column() });
  2226. break;
  2227. }
  2228. return FlyString { token.value() };
  2229. };
  2230. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) {
  2231. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  2232. syntax_error("Getter function must have no arguments");
  2233. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  2234. syntax_error("Setter function must have one argument");
  2235. auto is_rest = false;
  2236. if (match(TokenType::TripleDot)) {
  2237. consume();
  2238. has_rest_parameter = true;
  2239. function_length = parameters.size();
  2240. is_rest = true;
  2241. }
  2242. auto parameter = consume_identifier_or_binding_pattern();
  2243. RefPtr<Expression> default_value;
  2244. if (match(TokenType::Equals)) {
  2245. consume();
  2246. if (is_rest)
  2247. syntax_error("Rest parameter may not have a default initializer");
  2248. TemporaryChange change(m_state.in_function_context, true);
  2249. has_default_parameter = true;
  2250. function_length = parameters.size();
  2251. default_value = parse_expression(2);
  2252. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  2253. if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  2254. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  2255. }
  2256. parameters.append({ move(parameter), default_value, is_rest });
  2257. if (match(TokenType::ParenClose) || is_rest)
  2258. break;
  2259. consume(TokenType::Comma);
  2260. }
  2261. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  2262. syntax_error("Setter function must have one argument");
  2263. return parameters;
  2264. }
  2265. 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" };
  2266. RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates allow_duplicates, Parser::AllowMemberExpressions allow_member_expressions)
  2267. {
  2268. auto rule_start = push_start();
  2269. TokenType closing_token;
  2270. bool is_object = true;
  2271. if (match(TokenType::BracketOpen)) {
  2272. consume();
  2273. closing_token = TokenType::BracketClose;
  2274. is_object = false;
  2275. } else if (match(TokenType::CurlyOpen)) {
  2276. consume();
  2277. closing_token = TokenType::CurlyClose;
  2278. } else {
  2279. return {};
  2280. }
  2281. Vector<BindingPattern::BindingEntry> entries;
  2282. while (!match(closing_token)) {
  2283. if (!is_object && match(TokenType::Comma)) {
  2284. consume();
  2285. entries.append(BindingPattern::BindingEntry {});
  2286. continue;
  2287. }
  2288. auto is_rest = false;
  2289. if (match(TokenType::TripleDot)) {
  2290. consume();
  2291. is_rest = true;
  2292. }
  2293. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  2294. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  2295. RefPtr<Expression> initializer = {};
  2296. if (is_object) {
  2297. bool needs_alias = false;
  2298. if (allow_member_expressions == AllowMemberExpressions::Yes && is_rest) {
  2299. auto expression_position = position();
  2300. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2301. if (is<MemberExpression>(*expression))
  2302. alias = static_ptr_cast<MemberExpression>(expression);
  2303. else if (is<Identifier>(*expression))
  2304. name = static_ptr_cast<Identifier>(expression);
  2305. else
  2306. syntax_error("Invalid destructuring assignment target", expression_position);
  2307. } else if (match_identifier_name() || match(TokenType::StringLiteral) || match(TokenType::NumericLiteral)) {
  2308. if (match(TokenType::StringLiteral) || match(TokenType::NumericLiteral))
  2309. needs_alias = true;
  2310. if (match(TokenType::StringLiteral)) {
  2311. auto token = consume(TokenType::StringLiteral);
  2312. auto string_literal = parse_string_literal(token);
  2313. name = create_ast_node<Identifier>(
  2314. { m_state.current_token.filename(), rule_start.position(), position() },
  2315. string_literal->value());
  2316. } else {
  2317. name = create_ast_node<Identifier>(
  2318. { m_state.current_token.filename(), rule_start.position(), position() },
  2319. consume().value());
  2320. }
  2321. } else if (match(TokenType::BracketOpen)) {
  2322. consume();
  2323. auto expression = parse_expression(0);
  2324. name = move(expression);
  2325. consume(TokenType::BracketClose);
  2326. } else {
  2327. expected("identifier or computed property name");
  2328. return {};
  2329. }
  2330. if (!is_rest && match(TokenType::Colon)) {
  2331. consume();
  2332. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2333. auto expression_position = position();
  2334. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2335. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2336. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2337. alias = synthesized_binding_pattern.release_nonnull();
  2338. else
  2339. syntax_error("Invalid destructuring assignment target", expression_position);
  2340. } else if (is<MemberExpression>(*expression)) {
  2341. alias = static_ptr_cast<MemberExpression>(expression);
  2342. } else if (is<Identifier>(*expression)) {
  2343. alias = static_ptr_cast<Identifier>(expression);
  2344. } else {
  2345. syntax_error("Invalid destructuring assignment target", expression_position);
  2346. }
  2347. } else if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  2348. auto binding_pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2349. if (!binding_pattern)
  2350. return {};
  2351. alias = binding_pattern.release_nonnull();
  2352. } else if (match_identifier_name()) {
  2353. alias = create_ast_node<Identifier>(
  2354. { m_state.current_token.filename(), rule_start.position(), position() },
  2355. consume().value());
  2356. } else {
  2357. expected("identifier or binding pattern");
  2358. return {};
  2359. }
  2360. } else if (needs_alias) {
  2361. expected("alias for string or numeric literal name");
  2362. return {};
  2363. }
  2364. } else {
  2365. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2366. auto expression_position = position();
  2367. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2368. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2369. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2370. alias = synthesized_binding_pattern.release_nonnull();
  2371. else
  2372. syntax_error("Invalid destructuring assignment target", expression_position);
  2373. } else if (is<MemberExpression>(*expression)) {
  2374. alias = static_ptr_cast<MemberExpression>(expression);
  2375. } else if (is<Identifier>(*expression)) {
  2376. alias = static_ptr_cast<Identifier>(expression);
  2377. } else {
  2378. syntax_error("Invalid destructuring assignment target", expression_position);
  2379. }
  2380. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  2381. auto pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2382. if (!pattern) {
  2383. expected("binding pattern");
  2384. return {};
  2385. }
  2386. alias = pattern.release_nonnull();
  2387. } else if (match_identifier_name()) {
  2388. // BindingElement must always have an Empty name field
  2389. auto identifier_name = consume_identifier().value();
  2390. alias = create_ast_node<Identifier>(
  2391. { m_state.current_token.filename(), rule_start.position(), position() },
  2392. identifier_name);
  2393. } else {
  2394. expected("identifier or binding pattern");
  2395. return {};
  2396. }
  2397. }
  2398. if (match(TokenType::Equals)) {
  2399. if (is_rest) {
  2400. syntax_error("Unexpected initializer after rest element");
  2401. return {};
  2402. }
  2403. consume();
  2404. initializer = parse_expression(2);
  2405. if (!initializer) {
  2406. expected("initialization expression");
  2407. return {};
  2408. }
  2409. }
  2410. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  2411. if (match(TokenType::Comma)) {
  2412. if (is_rest) {
  2413. syntax_error("Rest element may not be followed by a comma");
  2414. return {};
  2415. }
  2416. consume();
  2417. } else if (is_object && !match(TokenType::CurlyClose)) {
  2418. consume(TokenType::Comma);
  2419. }
  2420. }
  2421. while (!is_object && match(TokenType::Comma))
  2422. consume();
  2423. consume(closing_token);
  2424. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  2425. auto pattern = adopt_ref(*new BindingPattern);
  2426. pattern->entries = move(entries);
  2427. pattern->kind = kind;
  2428. Vector<StringView> bound_names;
  2429. pattern->for_each_bound_name([&](auto& name) {
  2430. if (allow_duplicates == AllowDuplicates::No) {
  2431. if (bound_names.contains_slow(name))
  2432. syntax_error("Duplicate parameter names in bindings");
  2433. bound_names.append(name);
  2434. }
  2435. check_identifier_name_for_assignment_validity(name);
  2436. });
  2437. return pattern;
  2438. }
  2439. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  2440. {
  2441. auto rule_start = push_start();
  2442. DeclarationKind declaration_kind;
  2443. switch (m_state.current_token.type()) {
  2444. case TokenType::Var:
  2445. declaration_kind = DeclarationKind::Var;
  2446. break;
  2447. case TokenType::Let:
  2448. declaration_kind = DeclarationKind::Let;
  2449. break;
  2450. case TokenType::Const:
  2451. declaration_kind = DeclarationKind::Const;
  2452. break;
  2453. default:
  2454. VERIFY_NOT_REACHED();
  2455. }
  2456. consume();
  2457. NonnullRefPtrVector<VariableDeclarator> declarations;
  2458. for (;;) {
  2459. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target {};
  2460. if (match_identifier()) {
  2461. auto identifier_start = push_start();
  2462. auto name = consume_identifier().value();
  2463. target = create_ast_node<Identifier>(
  2464. { m_state.current_token.filename(), rule_start.position(), position() },
  2465. name);
  2466. check_identifier_name_for_assignment_validity(name);
  2467. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && name == "let"sv)
  2468. syntax_error("Lexical binding may not be called 'let'");
  2469. } else if (auto pattern = parse_binding_pattern(declaration_kind != DeclarationKind::Var ? AllowDuplicates::No : AllowDuplicates::Yes, AllowMemberExpressions::No)) {
  2470. target = pattern.release_nonnull();
  2471. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const)) {
  2472. target.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name([this](auto& name) {
  2473. if (name == "let"sv)
  2474. syntax_error("Lexical binding may not be called 'let'");
  2475. });
  2476. }
  2477. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  2478. if (m_state.strict_mode)
  2479. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  2480. target = create_ast_node<Identifier>(
  2481. { m_state.current_token.filename(), rule_start.position(), position() },
  2482. consume().value());
  2483. } else if (!m_state.await_expression_is_valid && match(TokenType::Async)) {
  2484. if (m_program_type == Program::Type::Module)
  2485. syntax_error("Identifier must not be a reserved word in modules ('async')");
  2486. target = create_ast_node<Identifier>(
  2487. { m_state.current_token.filename(), rule_start.position(), position() },
  2488. consume().value());
  2489. }
  2490. if (target.has<Empty>()) {
  2491. expected("identifier or a binding pattern");
  2492. if (match(TokenType::Comma)) {
  2493. consume();
  2494. continue;
  2495. }
  2496. break;
  2497. }
  2498. RefPtr<Expression> init;
  2499. if (match(TokenType::Equals)) {
  2500. consume();
  2501. // In a for loop 'in' can be ambiguous so we do not allow it
  2502. // 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
  2503. if (for_loop_variable_declaration)
  2504. init = parse_expression(2, Associativity::Right, { TokenType::In });
  2505. else
  2506. init = parse_expression(2);
  2507. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  2508. syntax_error("Missing initializer in 'const' variable declaration");
  2509. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  2510. syntax_error("Missing initializer in destructuring assignment");
  2511. }
  2512. declarations.append(create_ast_node<VariableDeclarator>(
  2513. { m_state.current_token.filename(), rule_start.position(), position() },
  2514. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  2515. move(init)));
  2516. if (match(TokenType::Comma)) {
  2517. consume();
  2518. continue;
  2519. }
  2520. break;
  2521. }
  2522. if (!for_loop_variable_declaration)
  2523. consume_or_insert_semicolon();
  2524. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  2525. return declaration;
  2526. }
  2527. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  2528. {
  2529. auto rule_start = push_start();
  2530. consume(TokenType::Throw);
  2531. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  2532. if (m_state.current_token.trivia_contains_line_terminator()) {
  2533. syntax_error("No line break is allowed between 'throw' and its expression");
  2534. 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() }));
  2535. }
  2536. auto expression = parse_expression(0);
  2537. consume_or_insert_semicolon();
  2538. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2539. }
  2540. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  2541. {
  2542. auto rule_start = push_start();
  2543. consume(TokenType::Break);
  2544. FlyString target_label;
  2545. if (match(TokenType::Semicolon)) {
  2546. consume();
  2547. } else {
  2548. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2549. target_label = consume().value();
  2550. auto label = m_state.labels_in_scope.find(target_label);
  2551. if (label == m_state.labels_in_scope.end())
  2552. syntax_error(String::formatted("Label '{}' not found", target_label));
  2553. }
  2554. consume_or_insert_semicolon();
  2555. }
  2556. if (target_label.is_null() && !m_state.in_break_context)
  2557. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  2558. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2559. }
  2560. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  2561. {
  2562. auto rule_start = push_start();
  2563. if (!m_state.in_continue_context)
  2564. syntax_error("'continue' not allow outside of a loop");
  2565. consume(TokenType::Continue);
  2566. FlyString target_label;
  2567. if (match(TokenType::Semicolon)) {
  2568. consume();
  2569. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2570. }
  2571. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2572. auto label_position = position();
  2573. target_label = consume().value();
  2574. auto label = m_state.labels_in_scope.find(target_label);
  2575. if (label == m_state.labels_in_scope.end())
  2576. syntax_error(String::formatted("Label '{}' not found or invalid", target_label));
  2577. else
  2578. label->value = label_position;
  2579. }
  2580. consume_or_insert_semicolon();
  2581. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2582. }
  2583. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test)
  2584. {
  2585. auto rule_start = push_start();
  2586. consume(TokenType::QuestionMark);
  2587. auto consequent = parse_expression(2);
  2588. consume(TokenType::Colon);
  2589. auto alternate = parse_expression(2);
  2590. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  2591. }
  2592. NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expression> base)
  2593. {
  2594. auto rule_start = push_start();
  2595. Vector<OptionalChain::Reference> chain;
  2596. do {
  2597. if (match(TokenType::QuestionMarkPeriod)) {
  2598. consume(TokenType::QuestionMarkPeriod);
  2599. switch (m_state.current_token.type()) {
  2600. case TokenType::ParenOpen:
  2601. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::Optional });
  2602. break;
  2603. case TokenType::BracketOpen:
  2604. consume();
  2605. chain.append(OptionalChain::ComputedReference { parse_expression(0), OptionalChain::Mode::Optional });
  2606. consume(TokenType::BracketClose);
  2607. break;
  2608. case TokenType::PrivateIdentifier: {
  2609. if (!is_private_identifier_valid())
  2610. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  2611. auto start = position();
  2612. auto private_identifier = consume();
  2613. chain.append(OptionalChain::PrivateMemberReference {
  2614. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2615. OptionalChain::Mode::Optional });
  2616. break;
  2617. }
  2618. case TokenType::TemplateLiteralStart:
  2619. // 13.3.1.1 - Static Semantics: Early Errors
  2620. // OptionalChain :
  2621. // ?. TemplateLiteral
  2622. // OptionalChain TemplateLiteral
  2623. // This is a hard error.
  2624. syntax_error("Invalid tagged template literal after ?.", position());
  2625. break;
  2626. default:
  2627. if (match_identifier_name()) {
  2628. auto start = position();
  2629. auto identifier = consume();
  2630. chain.append(OptionalChain::MemberReference {
  2631. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()),
  2632. OptionalChain::Mode::Optional,
  2633. });
  2634. } else {
  2635. syntax_error("Invalid optional chain reference after ?.", position());
  2636. }
  2637. break;
  2638. }
  2639. } else if (match(TokenType::ParenOpen)) {
  2640. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::NotOptional });
  2641. } else if (match(TokenType::Period)) {
  2642. consume();
  2643. if (match(TokenType::PrivateIdentifier)) {
  2644. auto start = position();
  2645. auto private_identifier = consume();
  2646. chain.append(OptionalChain::PrivateMemberReference {
  2647. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2648. OptionalChain::Mode::NotOptional,
  2649. });
  2650. } else if (match_identifier_name()) {
  2651. auto start = position();
  2652. auto identifier = consume();
  2653. chain.append(OptionalChain::MemberReference {
  2654. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.value()),
  2655. OptionalChain::Mode::NotOptional,
  2656. });
  2657. } else {
  2658. expected("an identifier");
  2659. break;
  2660. }
  2661. } else if (match(TokenType::TemplateLiteralStart)) {
  2662. // 13.3.1.1 - Static Semantics: Early Errors
  2663. // OptionalChain :
  2664. // ?. TemplateLiteral
  2665. // OptionalChain TemplateLiteral
  2666. syntax_error("Invalid tagged template literal after optional chain", position());
  2667. break;
  2668. } else if (match(TokenType::BracketOpen)) {
  2669. consume();
  2670. chain.append(OptionalChain::ComputedReference { parse_expression(2), OptionalChain::Mode::NotOptional });
  2671. consume(TokenType::BracketClose);
  2672. } else {
  2673. break;
  2674. }
  2675. } while (!done());
  2676. return create_ast_node<OptionalChain>(
  2677. { m_state.current_token.filename(), rule_start.position(), position() },
  2678. move(base),
  2679. move(chain));
  2680. }
  2681. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  2682. {
  2683. auto rule_start = push_start();
  2684. consume(TokenType::Try);
  2685. auto block = parse_block_statement();
  2686. RefPtr<CatchClause> handler;
  2687. if (match(TokenType::Catch))
  2688. handler = parse_catch_clause();
  2689. RefPtr<BlockStatement> finalizer;
  2690. if (match(TokenType::Finally)) {
  2691. consume();
  2692. finalizer = parse_block_statement();
  2693. }
  2694. if (!handler && !finalizer)
  2695. syntax_error("try statement must have a 'catch' or 'finally' clause");
  2696. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  2697. }
  2698. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  2699. {
  2700. auto rule_start = push_start();
  2701. consume(TokenType::Do);
  2702. auto body = [&]() -> NonnullRefPtr<Statement> {
  2703. TemporaryChange break_change(m_state.in_break_context, true);
  2704. TemporaryChange continue_change(m_state.in_continue_context, true);
  2705. return parse_statement();
  2706. }();
  2707. consume(TokenType::While);
  2708. consume(TokenType::ParenOpen);
  2709. auto test = parse_expression(0);
  2710. consume(TokenType::ParenClose);
  2711. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  2712. if (match(TokenType::Semicolon))
  2713. consume();
  2714. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2715. }
  2716. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  2717. {
  2718. auto rule_start = push_start();
  2719. consume(TokenType::While);
  2720. consume(TokenType::ParenOpen);
  2721. auto test = parse_expression(0);
  2722. consume(TokenType::ParenClose);
  2723. TemporaryChange break_change(m_state.in_break_context, true);
  2724. TemporaryChange continue_change(m_state.in_continue_context, true);
  2725. auto body = parse_statement();
  2726. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2727. }
  2728. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  2729. {
  2730. auto rule_start = push_start();
  2731. consume(TokenType::Switch);
  2732. consume(TokenType::ParenOpen);
  2733. auto determinant = parse_expression(0);
  2734. consume(TokenType::ParenClose);
  2735. consume(TokenType::CurlyOpen);
  2736. NonnullRefPtrVector<SwitchCase> cases;
  2737. auto switch_statement = create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant));
  2738. ScopePusher switch_scope = ScopePusher::block_scope(*this, switch_statement);
  2739. auto has_default = false;
  2740. while (match(TokenType::Case) || match(TokenType::Default)) {
  2741. if (match(TokenType::Default)) {
  2742. if (has_default)
  2743. syntax_error("Multiple 'default' clauses in switch statement");
  2744. has_default = true;
  2745. }
  2746. switch_statement->add_case(parse_switch_case());
  2747. }
  2748. consume(TokenType::CurlyClose);
  2749. return switch_statement;
  2750. }
  2751. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  2752. {
  2753. auto rule_start = push_start();
  2754. consume(TokenType::With);
  2755. consume(TokenType::ParenOpen);
  2756. auto object = parse_expression(0);
  2757. consume(TokenType::ParenClose);
  2758. auto body = parse_statement();
  2759. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  2760. }
  2761. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  2762. {
  2763. auto rule_start = push_start();
  2764. RefPtr<Expression> test;
  2765. if (consume().type() == TokenType::Case) {
  2766. test = parse_expression(0);
  2767. }
  2768. consume(TokenType::Colon);
  2769. NonnullRefPtrVector<Statement> consequent;
  2770. TemporaryChange break_change(m_state.in_break_context, true);
  2771. auto switch_case = create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test));
  2772. parse_statement_list(switch_case);
  2773. return switch_case;
  2774. }
  2775. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  2776. {
  2777. auto rule_start = push_start();
  2778. consume(TokenType::Catch);
  2779. FlyString parameter;
  2780. RefPtr<BindingPattern> pattern_parameter;
  2781. auto should_expect_parameter = false;
  2782. if (match(TokenType::ParenOpen)) {
  2783. should_expect_parameter = true;
  2784. consume();
  2785. if (match_identifier_name()
  2786. && (!match(TokenType::Yield) || !m_state.in_generator_function_context)
  2787. && (!match(TokenType::Async) || !m_state.await_expression_is_valid)
  2788. && (!match(TokenType::Await) || !m_state.in_class_static_init_block))
  2789. parameter = consume().value();
  2790. else
  2791. pattern_parameter = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No);
  2792. consume(TokenType::ParenClose);
  2793. }
  2794. if (should_expect_parameter && parameter.is_empty() && !pattern_parameter)
  2795. expected("an identifier or a binding pattern");
  2796. HashTable<FlyString> bound_names;
  2797. if (pattern_parameter) {
  2798. pattern_parameter->for_each_bound_name(
  2799. [&](auto& name) {
  2800. check_identifier_name_for_assignment_validity(name);
  2801. bound_names.set(name);
  2802. });
  2803. }
  2804. if (!parameter.is_empty()) {
  2805. check_identifier_name_for_assignment_validity(parameter);
  2806. bound_names.set(parameter);
  2807. }
  2808. ScopePusher catch_scope = ScopePusher::catch_scope(*this, pattern_parameter, parameter);
  2809. auto body = parse_block_statement();
  2810. body->for_each_lexically_declared_name([&](auto const& name) {
  2811. if (bound_names.contains(name))
  2812. syntax_error(String::formatted("Identifier '{}' already declared as catch parameter", name));
  2813. });
  2814. if (pattern_parameter) {
  2815. return create_ast_node<CatchClause>(
  2816. { m_state.current_token.filename(), rule_start.position(), position() },
  2817. pattern_parameter.release_nonnull(),
  2818. move(body));
  2819. }
  2820. return create_ast_node<CatchClause>(
  2821. { m_state.current_token.filename(), rule_start.position(), position() },
  2822. move(parameter),
  2823. move(body));
  2824. }
  2825. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  2826. {
  2827. auto rule_start = push_start();
  2828. auto parse_function_declaration_as_block_statement = [&] {
  2829. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  2830. // Code matching this production is processed as if each matching occurrence of
  2831. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  2832. // of a BlockStatement occupying that position in the source code.
  2833. VERIFY(match(TokenType::Function));
  2834. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2835. ScopePusher block_scope = ScopePusher::block_scope(*this, *block);
  2836. auto declaration = parse_declaration();
  2837. VERIFY(m_state.current_scope_pusher);
  2838. block_scope.add_declaration(declaration);
  2839. VERIFY(is<FunctionDeclaration>(*declaration));
  2840. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  2841. if (function_declaration.kind() == FunctionKind::Generator)
  2842. syntax_error("Generator functions can only be declared in top-level or within a block");
  2843. if (function_declaration.kind() == FunctionKind::Async)
  2844. syntax_error("Async functions can only be declared in top-level or within a block");
  2845. block->append(move(declaration));
  2846. return block;
  2847. };
  2848. consume(TokenType::If);
  2849. consume(TokenType::ParenOpen);
  2850. auto predicate = parse_expression(0);
  2851. consume(TokenType::ParenClose);
  2852. RefPtr<Statement> consequent;
  2853. if (!m_state.strict_mode && match(TokenType::Function))
  2854. consequent = parse_function_declaration_as_block_statement();
  2855. else
  2856. consequent = parse_statement();
  2857. RefPtr<Statement> alternate;
  2858. if (match(TokenType::Else)) {
  2859. consume();
  2860. if (!m_state.strict_mode && match(TokenType::Function))
  2861. alternate = parse_function_declaration_as_block_statement();
  2862. else
  2863. alternate = parse_statement();
  2864. }
  2865. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  2866. }
  2867. NonnullRefPtr<Statement> Parser::parse_for_statement()
  2868. {
  2869. auto rule_start = push_start();
  2870. auto is_await_loop = IsForAwaitLoop::No;
  2871. auto match_of = [&](Token const& token) {
  2872. return token.type() == TokenType::Identifier && token.original_value() == "of"sv;
  2873. };
  2874. auto match_for_in_of = [&]() {
  2875. bool is_of = match_of(m_state.current_token);
  2876. if (is_await_loop == IsForAwaitLoop::Yes) {
  2877. if (!is_of)
  2878. syntax_error("for await loop is only valid with 'of'");
  2879. else if (!m_state.await_expression_is_valid)
  2880. syntax_error("for await loop is only valid in async function or generator");
  2881. return true;
  2882. }
  2883. return match(TokenType::In) || is_of;
  2884. };
  2885. consume(TokenType::For);
  2886. if (match(TokenType::Await)) {
  2887. consume();
  2888. if (!m_state.await_expression_is_valid)
  2889. syntax_error("for-await-of is only allowed in async function context");
  2890. is_await_loop = IsForAwaitLoop::Yes;
  2891. }
  2892. consume(TokenType::ParenOpen);
  2893. Optional<ScopePusher> scope_pusher;
  2894. RefPtr<ASTNode> init;
  2895. if (!match(TokenType::Semicolon)) {
  2896. if (match_variable_declaration()) {
  2897. auto declaration = parse_variable_declaration(true);
  2898. if (declaration->declaration_kind() == DeclarationKind::Var) {
  2899. m_state.current_scope_pusher->add_declaration(declaration);
  2900. } else {
  2901. // This does not follow the normal declaration structure so we need additional checks.
  2902. HashTable<FlyString> bound_names;
  2903. declaration->for_each_bound_name([&](auto const& name) {
  2904. if (bound_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  2905. syntax_error(String::formatted("Identifier '{}' already declared in for loop initializer", name), declaration->source_range().start);
  2906. });
  2907. }
  2908. init = move(declaration);
  2909. if (match_for_in_of())
  2910. return parse_for_in_of_statement(*init, is_await_loop);
  2911. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  2912. for (auto& variable : static_cast<VariableDeclaration&>(*init).declarations()) {
  2913. if (!variable.init())
  2914. syntax_error("Missing initializer in 'const' variable declaration");
  2915. }
  2916. }
  2917. } else if (match_expression()) {
  2918. auto lookahead_token = next_token();
  2919. bool starts_with_async_of = match(TokenType::Async) && match_of(lookahead_token);
  2920. init = parse_expression(0, Associativity::Right, { TokenType::In });
  2921. if (match_for_in_of()) {
  2922. if (is_await_loop != IsForAwaitLoop::Yes
  2923. && starts_with_async_of && match_of(m_state.current_token))
  2924. syntax_error("for-of loop may not start with async of");
  2925. return parse_for_in_of_statement(*init, is_await_loop);
  2926. }
  2927. } else {
  2928. syntax_error("Unexpected token in for loop");
  2929. }
  2930. }
  2931. consume(TokenType::Semicolon);
  2932. RefPtr<Expression> test;
  2933. if (!match(TokenType::Semicolon))
  2934. test = parse_expression(0);
  2935. consume(TokenType::Semicolon);
  2936. RefPtr<Expression> update;
  2937. if (!match(TokenType::ParenClose))
  2938. update = parse_expression(0);
  2939. consume(TokenType::ParenClose);
  2940. TemporaryChange break_change(m_state.in_break_context, true);
  2941. TemporaryChange continue_change(m_state.in_continue_context, true);
  2942. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, init);
  2943. auto body = parse_statement();
  2944. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  2945. }
  2946. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_for_await_loop)
  2947. {
  2948. Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> for_declaration = lhs;
  2949. auto rule_start = push_start();
  2950. auto has_annexB_for_in_init_extension = false;
  2951. if (is<VariableDeclaration>(*lhs)) {
  2952. auto& declaration = static_cast<VariableDeclaration&>(*lhs);
  2953. if (declaration.declarations().size() > 1) {
  2954. syntax_error("Multiple declarations not allowed in for..in/of");
  2955. } else if (declaration.declarations().size() < 1) {
  2956. syntax_error("Need exactly one variable declaration in for..in/of");
  2957. } else {
  2958. // AnnexB extension B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  2959. auto& variable = declaration.declarations().first();
  2960. if (variable.init()) {
  2961. if (m_state.strict_mode || declaration.declaration_kind() != DeclarationKind::Var || !variable.target().has<NonnullRefPtr<Identifier>>())
  2962. syntax_error("Variable initializer not allowed in for..in/of");
  2963. else
  2964. has_annexB_for_in_init_extension = true;
  2965. }
  2966. }
  2967. } else if (!lhs->is_identifier() && !is<MemberExpression>(*lhs)) {
  2968. bool valid = false;
  2969. if (is<ObjectExpression>(*lhs) || is<ArrayExpression>(*lhs)) {
  2970. auto synthesized_binding_pattern = synthesize_binding_pattern(static_cast<Expression const&>(*lhs));
  2971. if (synthesized_binding_pattern) {
  2972. for_declaration = synthesized_binding_pattern.release_nonnull();
  2973. valid = true;
  2974. }
  2975. }
  2976. if (!valid)
  2977. syntax_error(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()));
  2978. }
  2979. auto in_or_of = consume();
  2980. auto is_in = in_or_of.type() == TokenType::In;
  2981. if (!is_in) {
  2982. if (is<MemberExpression>(*lhs)) {
  2983. auto& member = static_cast<MemberExpression const&>(*lhs);
  2984. if (member.object().is_identifier() && static_cast<Identifier const&>(member.object()).string() == "let"sv)
  2985. syntax_error("For of statement may not start with let.");
  2986. }
  2987. if (has_annexB_for_in_init_extension)
  2988. syntax_error("Variable initializer not allowed in for..of", rule_start.position());
  2989. }
  2990. auto rhs = parse_expression(is_in ? 0 : 2);
  2991. consume(TokenType::ParenClose);
  2992. TemporaryChange break_change(m_state.in_break_context, true);
  2993. TemporaryChange continue_change(m_state.in_continue_context, true);
  2994. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, lhs);
  2995. auto body = parse_statement();
  2996. if (is_in)
  2997. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  2998. if (is_for_await_loop == IsForAwaitLoop::Yes)
  2999. return create_ast_node<ForAwaitOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3000. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3001. }
  3002. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  3003. {
  3004. auto rule_start = push_start();
  3005. consume(TokenType::Debugger);
  3006. consume_or_insert_semicolon();
  3007. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  3008. }
  3009. bool Parser::match(TokenType type) const
  3010. {
  3011. return m_state.current_token.type() == type;
  3012. }
  3013. bool Parser::match_expression() const
  3014. {
  3015. auto type = m_state.current_token.type();
  3016. if (type == TokenType::Import) {
  3017. auto lookahead_token = next_token();
  3018. return lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen;
  3019. }
  3020. return type == TokenType::BoolLiteral
  3021. || type == TokenType::NumericLiteral
  3022. || type == TokenType::BigIntLiteral
  3023. || type == TokenType::StringLiteral
  3024. || type == TokenType::TemplateLiteralStart
  3025. || type == TokenType::NullLiteral
  3026. || match_identifier()
  3027. || type == TokenType::PrivateIdentifier
  3028. || type == TokenType::Await
  3029. || type == TokenType::New
  3030. || type == TokenType::Class
  3031. || type == TokenType::CurlyOpen
  3032. || type == TokenType::BracketOpen
  3033. || type == TokenType::ParenOpen
  3034. || type == TokenType::Function
  3035. || type == TokenType::Async
  3036. || type == TokenType::This
  3037. || type == TokenType::Super
  3038. || type == TokenType::RegexLiteral
  3039. || type == TokenType::Slash // Wrongly recognized regex by lexer
  3040. || type == TokenType::SlashEquals // Wrongly recognized regex by lexer (/=a/ is a valid regex)
  3041. || type == TokenType::Yield
  3042. || match_unary_prefixed_expression();
  3043. }
  3044. bool Parser::match_unary_prefixed_expression() const
  3045. {
  3046. auto type = m_state.current_token.type();
  3047. return type == TokenType::PlusPlus
  3048. || type == TokenType::MinusMinus
  3049. || type == TokenType::ExclamationMark
  3050. || type == TokenType::Tilde
  3051. || type == TokenType::Plus
  3052. || type == TokenType::Minus
  3053. || type == TokenType::Typeof
  3054. || type == TokenType::Void
  3055. || type == TokenType::Delete;
  3056. }
  3057. bool Parser::match_secondary_expression(const Vector<TokenType>& forbidden) const
  3058. {
  3059. auto type = m_state.current_token.type();
  3060. if (forbidden.contains_slow(type))
  3061. return false;
  3062. return type == TokenType::Plus
  3063. || type == TokenType::PlusEquals
  3064. || type == TokenType::Minus
  3065. || type == TokenType::MinusEquals
  3066. || type == TokenType::Asterisk
  3067. || type == TokenType::AsteriskEquals
  3068. || type == TokenType::Slash
  3069. || type == TokenType::SlashEquals
  3070. || type == TokenType::Percent
  3071. || type == TokenType::PercentEquals
  3072. || type == TokenType::DoubleAsterisk
  3073. || type == TokenType::DoubleAsteriskEquals
  3074. || type == TokenType::Equals
  3075. || type == TokenType::EqualsEqualsEquals
  3076. || type == TokenType::ExclamationMarkEqualsEquals
  3077. || type == TokenType::EqualsEquals
  3078. || type == TokenType::ExclamationMarkEquals
  3079. || type == TokenType::GreaterThan
  3080. || type == TokenType::GreaterThanEquals
  3081. || type == TokenType::LessThan
  3082. || type == TokenType::LessThanEquals
  3083. || type == TokenType::ParenOpen
  3084. || type == TokenType::Period
  3085. || type == TokenType::BracketOpen
  3086. || (type == TokenType::PlusPlus && !m_state.current_token.trivia_contains_line_terminator())
  3087. || (type == TokenType::MinusMinus && !m_state.current_token.trivia_contains_line_terminator())
  3088. || type == TokenType::In
  3089. || type == TokenType::Instanceof
  3090. || type == TokenType::QuestionMark
  3091. || type == TokenType::Ampersand
  3092. || type == TokenType::AmpersandEquals
  3093. || type == TokenType::Pipe
  3094. || type == TokenType::PipeEquals
  3095. || type == TokenType::Caret
  3096. || type == TokenType::CaretEquals
  3097. || type == TokenType::ShiftLeft
  3098. || type == TokenType::ShiftLeftEquals
  3099. || type == TokenType::ShiftRight
  3100. || type == TokenType::ShiftRightEquals
  3101. || type == TokenType::UnsignedShiftRight
  3102. || type == TokenType::UnsignedShiftRightEquals
  3103. || type == TokenType::DoubleAmpersand
  3104. || type == TokenType::DoubleAmpersandEquals
  3105. || type == TokenType::DoublePipe
  3106. || type == TokenType::DoublePipeEquals
  3107. || type == TokenType::DoubleQuestionMark
  3108. || type == TokenType::DoubleQuestionMarkEquals
  3109. || type == TokenType::QuestionMarkPeriod;
  3110. }
  3111. bool Parser::match_statement() const
  3112. {
  3113. auto type = m_state.current_token.type();
  3114. return match_expression()
  3115. || type == TokenType::Return
  3116. || type == TokenType::Yield
  3117. || type == TokenType::Do
  3118. || type == TokenType::If
  3119. || type == TokenType::Throw
  3120. || type == TokenType::Try
  3121. || type == TokenType::While
  3122. || type == TokenType::With
  3123. || type == TokenType::For
  3124. || type == TokenType::CurlyOpen
  3125. || type == TokenType::Switch
  3126. || type == TokenType::Break
  3127. || type == TokenType::Continue
  3128. || type == TokenType::Var
  3129. || type == TokenType::Debugger
  3130. || type == TokenType::Semicolon;
  3131. }
  3132. bool Parser::match_export_or_import() const
  3133. {
  3134. auto type = m_state.current_token.type();
  3135. return type == TokenType::Export
  3136. || type == TokenType::Import;
  3137. }
  3138. bool Parser::match_declaration() const
  3139. {
  3140. auto type = m_state.current_token.type();
  3141. if (type == TokenType::Let && !m_state.strict_mode) {
  3142. return try_match_let_declaration();
  3143. }
  3144. if (type == TokenType::Async) {
  3145. auto lookahead_token = next_token();
  3146. return lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator();
  3147. }
  3148. return type == TokenType::Function
  3149. || type == TokenType::Class
  3150. || type == TokenType::Const
  3151. || type == TokenType::Let;
  3152. }
  3153. Token Parser::next_token() const
  3154. {
  3155. Lexer lookahead_lexer = m_state.lexer;
  3156. auto token_after = lookahead_lexer.next();
  3157. return token_after;
  3158. }
  3159. bool Parser::try_match_let_declaration() const
  3160. {
  3161. VERIFY(m_state.current_token.type() == TokenType::Let);
  3162. auto token_after = next_token();
  3163. if (token_after.is_identifier_name() && token_after.value() != "in"sv)
  3164. return true;
  3165. if (token_after.type() == TokenType::CurlyOpen || token_after.type() == TokenType::BracketOpen)
  3166. return true;
  3167. return false;
  3168. }
  3169. bool Parser::match_variable_declaration() const
  3170. {
  3171. auto type = m_state.current_token.type();
  3172. if (type == TokenType::Let && !m_state.strict_mode) {
  3173. return try_match_let_declaration();
  3174. }
  3175. return type == TokenType::Var
  3176. || type == TokenType::Let
  3177. || type == TokenType::Const;
  3178. }
  3179. bool Parser::match_identifier() const
  3180. {
  3181. if (m_state.current_token.type() == TokenType::EscapedKeyword) {
  3182. if (m_state.current_token.value() == "let"sv)
  3183. return !m_state.strict_mode;
  3184. if (m_state.current_token.value() == "yield"sv)
  3185. return !m_state.strict_mode && !m_state.in_generator_function_context;
  3186. if (m_state.current_token.value() == "await"sv)
  3187. return m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block;
  3188. return true;
  3189. }
  3190. return m_state.current_token.type() == TokenType::Identifier
  3191. || m_state.current_token.type() == TokenType::Async
  3192. || (m_state.current_token.type() == TokenType::Let && !m_state.strict_mode)
  3193. || (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)
  3194. || (m_state.current_token.type() == TokenType::Yield && !m_state.in_generator_function_context && !m_state.strict_mode); // See note in Parser::parse_identifier().
  3195. }
  3196. bool Parser::match_identifier_name() const
  3197. {
  3198. return m_state.current_token.is_identifier_name();
  3199. }
  3200. bool Parser::match_property_key() const
  3201. {
  3202. auto type = m_state.current_token.type();
  3203. return match_identifier_name()
  3204. || type == TokenType::BracketOpen
  3205. || type == TokenType::StringLiteral
  3206. || type == TokenType::NumericLiteral
  3207. || type == TokenType::BigIntLiteral;
  3208. }
  3209. bool Parser::done() const
  3210. {
  3211. return match(TokenType::Eof);
  3212. }
  3213. Token Parser::consume()
  3214. {
  3215. auto old_token = m_state.current_token;
  3216. m_state.current_token = m_state.lexer.next();
  3217. // NOTE: This is the bare minimum needed to decide whether we might need an arguments object
  3218. // in a function expression or declaration. ("might" because the AST implements some further
  3219. // conditions from the spec that rule out the need for allocating one)
  3220. if (old_token.type() == TokenType::Identifier && old_token.value().is_one_of("arguments"sv, "eval"sv))
  3221. m_state.function_might_need_arguments_object = true;
  3222. return old_token;
  3223. }
  3224. void Parser::consume_or_insert_semicolon()
  3225. {
  3226. // Semicolon was found and will be consumed
  3227. if (match(TokenType::Semicolon)) {
  3228. consume();
  3229. return;
  3230. }
  3231. // Insert semicolon if...
  3232. // ...token is preceded by one or more newlines
  3233. if (m_state.current_token.trivia_contains_line_terminator())
  3234. return;
  3235. // ...token is a closing curly brace
  3236. if (match(TokenType::CurlyClose))
  3237. return;
  3238. // ...token is eof
  3239. if (match(TokenType::Eof))
  3240. return;
  3241. // No rule for semicolon insertion applies -> syntax error
  3242. expected("Semicolon");
  3243. }
  3244. Token Parser::consume_identifier()
  3245. {
  3246. if (match(TokenType::Identifier))
  3247. return consume(TokenType::Identifier);
  3248. if (match(TokenType::EscapedKeyword))
  3249. return consume(TokenType::EscapedKeyword);
  3250. // Note that 'let' is not a reserved keyword, but our lexer considers it such
  3251. // As it's pretty nice to have that (for syntax highlighting and such), we'll
  3252. // special-case it here instead.
  3253. if (match(TokenType::Let)) {
  3254. if (m_state.strict_mode)
  3255. syntax_error("'let' is not allowed as an identifier in strict mode");
  3256. return consume();
  3257. }
  3258. if (match(TokenType::Yield)) {
  3259. if (m_state.strict_mode || m_state.in_generator_function_context)
  3260. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  3261. return consume();
  3262. }
  3263. if (match(TokenType::Await)) {
  3264. if (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)
  3265. syntax_error("Identifier must not be a reserved word in modules ('await')");
  3266. return consume();
  3267. }
  3268. if (match(TokenType::Async))
  3269. return consume();
  3270. expected("Identifier");
  3271. return consume();
  3272. }
  3273. // https://tc39.es/ecma262/#prod-IdentifierReference
  3274. Token Parser::consume_identifier_reference()
  3275. {
  3276. if (match(TokenType::Identifier))
  3277. return consume(TokenType::Identifier);
  3278. if (match(TokenType::EscapedKeyword)) {
  3279. auto name = m_state.current_token.value();
  3280. if (m_state.strict_mode && (name == "let"sv || name == "yield"sv))
  3281. syntax_error(String::formatted("'{}' is not allowed as an identifier in strict mode", name));
  3282. if (m_program_type == Program::Type::Module && name == "await"sv)
  3283. syntax_error("'await' is not allowed as an identifier in module");
  3284. return consume();
  3285. }
  3286. // See note in Parser::parse_identifier().
  3287. if (match(TokenType::Let)) {
  3288. if (m_state.strict_mode)
  3289. syntax_error("'let' is not allowed as an identifier in strict mode");
  3290. return consume();
  3291. }
  3292. if (match(TokenType::Yield)) {
  3293. if (m_state.strict_mode)
  3294. syntax_error("Identifier reference may not be 'yield' in strict mode");
  3295. return consume();
  3296. }
  3297. if (match(TokenType::Await)) {
  3298. if (m_program_type == Program::Type::Module)
  3299. syntax_error("'await' is not allowed as an identifier in module");
  3300. return consume();
  3301. }
  3302. if (match(TokenType::Async))
  3303. return consume();
  3304. expected(Token::name(TokenType::Identifier));
  3305. return consume();
  3306. }
  3307. Token Parser::consume(TokenType expected_type)
  3308. {
  3309. if (!match(expected_type)) {
  3310. expected(Token::name(expected_type));
  3311. }
  3312. auto token = consume();
  3313. if (expected_type == TokenType::Identifier) {
  3314. if (m_state.strict_mode && is_strict_reserved_word(token.value()))
  3315. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()));
  3316. }
  3317. return token;
  3318. }
  3319. Token Parser::consume_and_validate_numeric_literal()
  3320. {
  3321. auto is_unprefixed_octal_number = [](StringView value) {
  3322. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  3323. };
  3324. auto literal_start = position();
  3325. auto token = consume(TokenType::NumericLiteral);
  3326. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  3327. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  3328. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  3329. syntax_error("Numeric literal must not be immediately followed by identifier");
  3330. return token;
  3331. }
  3332. void Parser::expected(const char* what)
  3333. {
  3334. auto message = m_state.current_token.message();
  3335. if (message.is_empty())
  3336. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  3337. syntax_error(message);
  3338. }
  3339. Position Parser::position() const
  3340. {
  3341. return {
  3342. m_state.current_token.line_number(),
  3343. m_state.current_token.line_column(),
  3344. m_state.current_token.offset(),
  3345. };
  3346. }
  3347. bool Parser::try_parse_arrow_function_expression_failed_at_position(const Position& position) const
  3348. {
  3349. auto it = m_token_memoizations.find(position);
  3350. if (it == m_token_memoizations.end())
  3351. return false;
  3352. return (*it).value.try_parse_arrow_function_expression_failed;
  3353. }
  3354. void Parser::set_try_parse_arrow_function_expression_failed_at_position(const Position& position, bool failed)
  3355. {
  3356. m_token_memoizations.set(position, { failed });
  3357. }
  3358. void Parser::syntax_error(const String& message, Optional<Position> position)
  3359. {
  3360. if (!position.has_value())
  3361. position = this->position();
  3362. m_state.errors.append({ message, position });
  3363. }
  3364. void Parser::save_state()
  3365. {
  3366. m_saved_state.append(m_state);
  3367. }
  3368. void Parser::load_state()
  3369. {
  3370. VERIFY(!m_saved_state.is_empty());
  3371. m_state = m_saved_state.take_last();
  3372. }
  3373. void Parser::discard_saved_state()
  3374. {
  3375. m_saved_state.take_last();
  3376. }
  3377. void Parser::check_identifier_name_for_assignment_validity(StringView name, bool force_strict)
  3378. {
  3379. // FIXME: this is now called from multiple places maybe the error message should be dynamic?
  3380. if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) {
  3381. syntax_error("Binding pattern target may not be a reserved word");
  3382. } else if (m_state.strict_mode || force_strict) {
  3383. if (name.is_one_of("arguments"sv, "eval"sv))
  3384. syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");
  3385. else if (is_strict_reserved_word(name))
  3386. syntax_error(String::formatted("Binding pattern target may not be called '{}' in strict mode", name));
  3387. }
  3388. }
  3389. NonnullRefPtr<ImportStatement> Parser::parse_import_statement(Program& program)
  3390. {
  3391. auto rule_start = push_start();
  3392. if (program.type() != Program::Type::Module)
  3393. syntax_error("Cannot use import statement outside a module");
  3394. consume(TokenType::Import);
  3395. if (match(TokenType::StringLiteral)) {
  3396. auto module_name = consume(TokenType::StringLiteral).value();
  3397. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, module_name);
  3398. }
  3399. auto match_imported_binding = [&] {
  3400. return match_identifier() || match(TokenType::Yield) || match(TokenType::Await);
  3401. };
  3402. auto match_as = [&] {
  3403. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3404. };
  3405. bool continue_parsing = true;
  3406. struct ImportWithLocation {
  3407. ImportStatement::ImportEntry entry;
  3408. Position position;
  3409. };
  3410. Vector<ImportWithLocation> entries_with_location;
  3411. if (match_imported_binding()) {
  3412. auto id_position = position();
  3413. auto bound_name = consume().value();
  3414. entries_with_location.append({ { "default", bound_name }, id_position });
  3415. if (match(TokenType::Comma)) {
  3416. consume(TokenType::Comma);
  3417. } else {
  3418. continue_parsing = false;
  3419. }
  3420. }
  3421. if (!continue_parsing) {
  3422. // skip the rest
  3423. } else if (match(TokenType::Asterisk)) {
  3424. consume(TokenType::Asterisk);
  3425. if (!match_as())
  3426. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3427. consume(TokenType::Identifier);
  3428. if (match_imported_binding()) {
  3429. auto namespace_position = position();
  3430. auto namespace_name = consume().value();
  3431. entries_with_location.append({ { "*", namespace_name }, namespace_position });
  3432. } else {
  3433. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3434. }
  3435. } else if (match(TokenType::CurlyOpen)) {
  3436. consume(TokenType::CurlyOpen);
  3437. while (!done() && !match(TokenType::CurlyClose)) {
  3438. if (match_identifier_name()) {
  3439. auto require_as = !match_imported_binding();
  3440. auto name_position = position();
  3441. auto name = consume().value();
  3442. if (match_as()) {
  3443. consume(TokenType::Identifier);
  3444. auto alias_position = position();
  3445. auto alias = consume_identifier().value();
  3446. check_identifier_name_for_assignment_validity(alias);
  3447. entries_with_location.append({ { name, alias }, alias_position });
  3448. } else if (require_as) {
  3449. syntax_error(String::formatted("Unexpected reserved word '{}'", name));
  3450. } else {
  3451. check_identifier_name_for_assignment_validity(name);
  3452. entries_with_location.append({ { name, name }, name_position });
  3453. }
  3454. } else {
  3455. expected("identifier");
  3456. break;
  3457. }
  3458. if (!match(TokenType::Comma))
  3459. break;
  3460. consume(TokenType::Comma);
  3461. }
  3462. consume(TokenType::CurlyClose);
  3463. } else {
  3464. expected("import clauses");
  3465. }
  3466. auto from_statement = consume(TokenType::Identifier).original_value();
  3467. if (from_statement != "from"sv)
  3468. syntax_error(String::formatted("Expected 'from' got {}", from_statement));
  3469. auto module_name = consume(TokenType::StringLiteral).value();
  3470. Vector<ImportStatement::ImportEntry> entries;
  3471. entries.ensure_capacity(entries_with_location.size());
  3472. for (auto& entry : entries_with_location) {
  3473. for (auto& import_statement : program.imports()) {
  3474. if (import_statement.has_bound_name(entry.entry.local_name))
  3475. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3476. }
  3477. for (auto& new_entry : entries) {
  3478. if (new_entry.local_name == entry.entry.local_name)
  3479. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3480. }
  3481. entries.append(move(entry.entry));
  3482. }
  3483. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, module_name, move(entries));
  3484. }
  3485. NonnullRefPtr<ExportStatement> Parser::parse_export_statement(Program& program)
  3486. {
  3487. auto rule_start = push_start();
  3488. if (program.type() != Program::Type::Module)
  3489. syntax_error("Cannot use export statement outside a module");
  3490. auto match_as = [&] {
  3491. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3492. };
  3493. auto match_from = [&] {
  3494. return match(TokenType::Identifier) && m_state.current_token.original_value() == "from"sv;
  3495. };
  3496. auto match_default = [&] {
  3497. return match(TokenType::Default) && m_state.current_token.original_value() == "default"sv;
  3498. };
  3499. consume(TokenType::Export);
  3500. struct EntryAndLocation {
  3501. ExportStatement::ExportEntry entry;
  3502. Position position;
  3503. void to_module_request(String from_module)
  3504. {
  3505. entry.kind = ExportStatement::ExportEntry::Kind::ModuleRequest;
  3506. entry.module_request = from_module;
  3507. }
  3508. };
  3509. Vector<EntryAndLocation> entries_with_location;
  3510. RefPtr<ASTNode> expression = {};
  3511. if (match_default()) {
  3512. auto default_position = position();
  3513. consume(TokenType::Default);
  3514. String local_name;
  3515. if (match(TokenType::Class)) {
  3516. auto class_expression = parse_class_expression(false);
  3517. local_name = class_expression->name();
  3518. expression = move(class_expression);
  3519. } else if (match(TokenType::Function) || (match(TokenType::Async) && next_token().type() == TokenType::Function)) {
  3520. auto func_expr = parse_function_node<FunctionExpression>();
  3521. local_name = func_expr->name();
  3522. expression = move(func_expr);
  3523. } else if (match_expression()) {
  3524. expression = parse_expression(2);
  3525. consume_or_insert_semicolon();
  3526. local_name = "*default*";
  3527. } else {
  3528. expected("Declaration or assignment expression");
  3529. }
  3530. entries_with_location.append({ { "default", local_name }, default_position });
  3531. } else {
  3532. enum FromSpecifier {
  3533. NotAllowed,
  3534. Optional,
  3535. Required
  3536. } check_for_from { NotAllowed };
  3537. if (match(TokenType::Asterisk)) {
  3538. auto asterisk_position = position();
  3539. consume(TokenType::Asterisk);
  3540. if (match_as()) {
  3541. consume(TokenType::Identifier);
  3542. if (match_identifier_name()) {
  3543. auto namespace_position = position();
  3544. auto exported_name = consume().value();
  3545. entries_with_location.append({ { exported_name, "*" }, namespace_position });
  3546. } else {
  3547. expected("identifier");
  3548. }
  3549. } else {
  3550. entries_with_location.append({ { {}, "*" }, asterisk_position });
  3551. }
  3552. check_for_from = Required;
  3553. } else if (match_declaration()) {
  3554. auto decl_position = position();
  3555. auto declaration = parse_declaration();
  3556. m_state.current_scope_pusher->add_declaration(declaration);
  3557. if (is<FunctionDeclaration>(*declaration)) {
  3558. auto& func = static_cast<FunctionDeclaration&>(*declaration);
  3559. entries_with_location.append({ { func.name(), func.name() }, func.source_range().start });
  3560. } else if (is<ClassDeclaration>(*declaration)) {
  3561. auto& class_declaration = static_cast<ClassDeclaration&>(*declaration);
  3562. entries_with_location.append({ { class_declaration.name(), class_declaration.name() }, class_declaration.source_range().start });
  3563. } else {
  3564. VERIFY(is<VariableDeclaration>(*declaration));
  3565. auto& variables = static_cast<VariableDeclaration&>(*declaration);
  3566. for (auto& decl : variables.declarations()) {
  3567. decl.target().visit(
  3568. [&](NonnullRefPtr<Identifier> const& identifier) {
  3569. entries_with_location.append({ { identifier->string(), identifier->string() }, identifier->source_range().start });
  3570. },
  3571. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3572. binding->for_each_bound_name([&](auto& name) {
  3573. entries_with_location.append({ { name, name }, decl_position });
  3574. });
  3575. });
  3576. }
  3577. }
  3578. expression = declaration;
  3579. } else if (match(TokenType::Var)) {
  3580. auto variable_position = position();
  3581. auto variable_declaration = parse_variable_declaration();
  3582. for (auto& decl : variable_declaration->declarations()) {
  3583. decl.target().visit(
  3584. [&](NonnullRefPtr<Identifier> const& identifier) {
  3585. entries_with_location.append({ { identifier->string(), identifier->string() }, identifier->source_range().start });
  3586. },
  3587. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3588. binding->for_each_bound_name([&](auto& name) {
  3589. entries_with_location.append({ { name, name }, variable_position });
  3590. });
  3591. });
  3592. }
  3593. expression = variable_declaration;
  3594. } else if (match(TokenType::CurlyOpen)) {
  3595. consume(TokenType::CurlyOpen);
  3596. while (!done() && !match(TokenType::CurlyClose)) {
  3597. if (match_identifier_name()) {
  3598. auto identifier_position = position();
  3599. auto identifier = consume().value();
  3600. if (match_as()) {
  3601. consume(TokenType::Identifier);
  3602. if (match_identifier_name()) {
  3603. auto export_name = consume().value();
  3604. entries_with_location.append({ { export_name, identifier }, identifier_position });
  3605. } else {
  3606. expected("identifier name");
  3607. }
  3608. } else {
  3609. entries_with_location.append({ { identifier, identifier }, identifier_position });
  3610. }
  3611. } else {
  3612. expected("identifier");
  3613. break;
  3614. }
  3615. if (!match(TokenType::Comma))
  3616. break;
  3617. consume(TokenType::Comma);
  3618. }
  3619. consume(TokenType::CurlyClose);
  3620. check_for_from = Optional;
  3621. } else {
  3622. syntax_error("Unexpected token 'export'", rule_start.position());
  3623. }
  3624. if (check_for_from != NotAllowed && match_from()) {
  3625. consume(TokenType::Identifier);
  3626. if (match(TokenType::StringLiteral)) {
  3627. auto from_specifier = consume().value();
  3628. for (auto& entry : entries_with_location)
  3629. entry.to_module_request(from_specifier);
  3630. } else {
  3631. expected("ModuleSpecifier");
  3632. }
  3633. } else if (check_for_from == Required) {
  3634. expected("from");
  3635. }
  3636. if (check_for_from != NotAllowed)
  3637. consume_or_insert_semicolon();
  3638. }
  3639. Vector<ExportStatement::ExportEntry> entries;
  3640. entries.ensure_capacity(entries_with_location.size());
  3641. for (auto& entry : entries_with_location) {
  3642. for (auto& export_statement : program.exports()) {
  3643. if (export_statement.has_export(entry.entry.export_name))
  3644. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3645. }
  3646. for (auto& new_entry : entries) {
  3647. if (new_entry.export_name == entry.entry.export_name)
  3648. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3649. }
  3650. entries.append(move(entry.entry));
  3651. }
  3652. return create_ast_node<ExportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(entries));
  3653. }
  3654. }