Parser.cpp 197 KB

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