Parser.cpp 203 KB

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