Parser.cpp 201 KB

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