Parser.cpp 204 KB

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