Parser.cpp 179 KB

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