Parser.cpp 188 KB

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