Parser.cpp 181 KB

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