Parser.cpp 199 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585
  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", "interface", "let", "package", "private", "protected", "public", "static", "yield" };
  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"))
  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";
  1021. is_async = false;
  1022. } else {
  1023. VERIFY(is_static);
  1024. name = "static";
  1025. is_static = false;
  1026. }
  1027. break;
  1028. case ClassMethod::Kind::Getter:
  1029. name = "get";
  1030. method_kind = ClassMethod::Kind::Method;
  1031. break;
  1032. case ClassMethod::Kind::Setter:
  1033. name = "set";
  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. auto super_call = create_ast_node<SuperCall>(
  1121. { m_state.current_token.filename(), rule_start.position(), position() },
  1122. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  1123. // NOTE: While the JS approximation above doesn't do `return super(...args)`, the
  1124. // abstract closure is expected to capture and return the result, so we do need a
  1125. // return statement here to create the correct completion.
  1126. constructor_body->append(create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  1127. constructor = create_ast_node<FunctionExpression>(
  1128. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1129. move(constructor_body), Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Normal,
  1130. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1131. } else {
  1132. constructor = create_ast_node<FunctionExpression>(
  1133. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1134. move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Normal,
  1135. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1136. }
  1137. }
  1138. // We could be in a subclass defined within the main class so must move all non declared private names to outer.
  1139. for (auto& private_name : referenced_private_names) {
  1140. if (found_private_names.contains(private_name))
  1141. continue;
  1142. if (outer_referenced_private_names)
  1143. outer_referenced_private_names->set(private_name);
  1144. else // FIXME: Make these error appear in the appropriate places.
  1145. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", private_name));
  1146. }
  1147. auto function_start_offset = rule_start.position().offset;
  1148. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  1149. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  1150. 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));
  1151. }
  1152. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  1153. {
  1154. auto rule_start = push_start();
  1155. if (match_unary_prefixed_expression())
  1156. return { parse_unary_prefixed_expression() };
  1157. auto try_arrow_function_parse_or_fail = [this](Position const& position, bool expect_paren, bool is_async = false) -> RefPtr<FunctionExpression> {
  1158. if (try_parse_arrow_function_expression_failed_at_position(position))
  1159. return nullptr;
  1160. auto arrow_function = try_parse_arrow_function_expression(expect_paren, is_async);
  1161. if (arrow_function)
  1162. return arrow_function;
  1163. set_try_parse_arrow_function_expression_failed_at_position(position, true);
  1164. return nullptr;
  1165. };
  1166. switch (m_state.current_token.type()) {
  1167. case TokenType::ParenOpen: {
  1168. auto paren_position = position();
  1169. consume(TokenType::ParenOpen);
  1170. if ((match(TokenType::ParenClose) || match_identifier() || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))) {
  1171. if (auto arrow_function_result = try_arrow_function_parse_or_fail(paren_position, true))
  1172. return { arrow_function_result.release_nonnull(), false };
  1173. }
  1174. auto expression = parse_expression(0);
  1175. consume(TokenType::ParenClose);
  1176. if (is<FunctionExpression>(*expression)) {
  1177. auto& function = static_cast<FunctionExpression&>(*expression);
  1178. if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv)
  1179. syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start);
  1180. if (function.kind() == FunctionKind::Async && function.name() == "await"sv)
  1181. syntax_error("function is not allowed to be called 'await' in this context", function.source_range().start);
  1182. }
  1183. return { move(expression) };
  1184. }
  1185. case TokenType::This:
  1186. consume();
  1187. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1188. case TokenType::Class:
  1189. return { parse_class_expression(false) };
  1190. case TokenType::Super:
  1191. consume();
  1192. if (!m_state.allow_super_property_lookup)
  1193. syntax_error("'super' keyword unexpected here");
  1194. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1195. case TokenType::EscapedKeyword:
  1196. if (match_invalid_escaped_keyword())
  1197. syntax_error("Keyword must not contain escaped characters");
  1198. [[fallthrough]];
  1199. case TokenType::Identifier: {
  1200. read_as_identifier:;
  1201. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false))
  1202. return { arrow_function_result.release_nonnull(), false };
  1203. auto string = m_state.current_token.value();
  1204. // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`)
  1205. if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string)))
  1206. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string));
  1207. return { parse_identifier() };
  1208. }
  1209. case TokenType::NumericLiteral:
  1210. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  1211. case TokenType::BigIntLiteral:
  1212. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1213. case TokenType::BoolLiteral:
  1214. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  1215. case TokenType::StringLiteral:
  1216. return { parse_string_literal(consume()) };
  1217. case TokenType::NullLiteral:
  1218. consume();
  1219. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1220. case TokenType::CurlyOpen:
  1221. return { parse_object_expression() };
  1222. case TokenType::Async: {
  1223. auto lookahead_token = next_token();
  1224. // No valid async function (arrow or not) can have a line terminator after the async since asi would kick in.
  1225. if (lookahead_token.trivia_contains_line_terminator())
  1226. goto read_as_identifier;
  1227. if (lookahead_token.type() == TokenType::Function)
  1228. return { parse_function_node<FunctionExpression>() };
  1229. if (lookahead_token.type() == TokenType::ParenOpen) {
  1230. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), true, true))
  1231. return { arrow_function_result.release_nonnull(), false };
  1232. } else if (lookahead_token.is_identifier_name()) {
  1233. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false, true))
  1234. return { arrow_function_result.release_nonnull(), false };
  1235. }
  1236. goto read_as_identifier;
  1237. }
  1238. case TokenType::Function:
  1239. return { parse_function_node<FunctionExpression>() };
  1240. case TokenType::BracketOpen:
  1241. return { parse_array_expression() };
  1242. case TokenType::RegexLiteral:
  1243. return { parse_regexp_literal() };
  1244. case TokenType::TemplateLiteralStart:
  1245. return { parse_template_literal(false) };
  1246. case TokenType::New: {
  1247. auto new_start = position();
  1248. auto new_target_result = try_parse_new_target_expression();
  1249. if (!new_target_result.is_null()) {
  1250. if (!m_state.in_function_context && !m_state.in_eval_function_context && !m_state.in_class_static_init_block)
  1251. syntax_error("'new.target' not allowed outside of a function", new_start);
  1252. return { new_target_result.release_nonnull() };
  1253. }
  1254. return { parse_new_expression() };
  1255. }
  1256. case TokenType::Import: {
  1257. auto lookahead_token = next_token();
  1258. if (lookahead_token.type() == TokenType::ParenOpen)
  1259. return { parse_import_call() };
  1260. if (lookahead_token.type() == TokenType::Period) {
  1261. if (auto import_meta = try_parse_import_meta_expression()) {
  1262. if (m_program_type != Program::Type::Module)
  1263. syntax_error("import.meta is only allowed in modules");
  1264. return { import_meta.release_nonnull() };
  1265. }
  1266. } else {
  1267. consume();
  1268. expected("import.meta or import call");
  1269. }
  1270. break;
  1271. }
  1272. case TokenType::Yield:
  1273. if (!m_state.in_generator_function_context)
  1274. goto read_as_identifier;
  1275. return { parse_yield_expression(), false };
  1276. case TokenType::Await:
  1277. if (!m_state.await_expression_is_valid)
  1278. goto read_as_identifier;
  1279. return { parse_await_expression() };
  1280. case TokenType::PrivateIdentifier:
  1281. if (next_token().type() != TokenType::In)
  1282. syntax_error("Cannot have a private identifier in expression if not followed by 'in'");
  1283. if (!is_private_identifier_valid())
  1284. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1285. return { create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1286. default:
  1287. if (match_identifier_name())
  1288. goto read_as_identifier;
  1289. break;
  1290. }
  1291. expected("primary expression");
  1292. consume();
  1293. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1294. }
  1295. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  1296. {
  1297. auto rule_start = push_start();
  1298. auto pattern = consume().value();
  1299. // Remove leading and trailing slash.
  1300. pattern = pattern.substring_view(1, pattern.length() - 2);
  1301. auto flags = String::empty();
  1302. auto parsed_flags = RegExpObject::default_flags;
  1303. if (match(TokenType::RegexFlags)) {
  1304. auto flags_start = position();
  1305. flags = consume().value();
  1306. auto parsed_flags_or_error = regex_flags_from_string(flags);
  1307. if (parsed_flags_or_error.is_error())
  1308. syntax_error(parsed_flags_or_error.release_error(), flags_start);
  1309. else
  1310. parsed_flags = parsed_flags_or_error.release_value();
  1311. }
  1312. auto parsed_pattern = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode));
  1313. auto parsed_regex = Regex<ECMA262>::parse_pattern(parsed_pattern, parsed_flags);
  1314. if (parsed_regex.error != regex::Error::NoError)
  1315. syntax_error(String::formatted("RegExp compile error: {}", Regex<ECMA262>(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position());
  1316. SourceRange range { m_state.current_token.filename(), rule_start.position(), position() };
  1317. return create_ast_node<RegExpLiteral>(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_string(), move(flags));
  1318. }
  1319. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  1320. {
  1321. auto rule_start = push_start();
  1322. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  1323. auto associativity = operator_associativity(m_state.current_token.type());
  1324. switch (m_state.current_token.type()) {
  1325. case TokenType::PlusPlus: {
  1326. consume();
  1327. auto rhs_start = position();
  1328. auto rhs = parse_expression(precedence, associativity);
  1329. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1330. // other engines throw ReferenceError for ++foo()
  1331. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1332. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1333. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1334. auto& identifier = static_cast<Identifier&>(*rhs);
  1335. auto& name = identifier.string();
  1336. check_identifier_name_for_assignment_validity(name);
  1337. }
  1338. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  1339. }
  1340. case TokenType::MinusMinus: {
  1341. consume();
  1342. auto rhs_start = position();
  1343. auto rhs = parse_expression(precedence, associativity);
  1344. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1345. // other engines throw ReferenceError for --foo()
  1346. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1347. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1348. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1349. auto& identifier = static_cast<Identifier&>(*rhs);
  1350. auto& name = identifier.string();
  1351. check_identifier_name_for_assignment_validity(name);
  1352. }
  1353. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  1354. }
  1355. case TokenType::ExclamationMark:
  1356. consume();
  1357. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  1358. case TokenType::Tilde:
  1359. consume();
  1360. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  1361. case TokenType::Plus:
  1362. consume();
  1363. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  1364. case TokenType::Minus:
  1365. consume();
  1366. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  1367. case TokenType::Typeof:
  1368. consume();
  1369. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  1370. case TokenType::Void:
  1371. consume();
  1372. // FIXME: This check is really hiding the fact that we don't deal with different expressions correctly.
  1373. if (match(TokenType::Yield) && m_state.in_generator_function_context)
  1374. syntax_error("'yield' is not an identifier in generator function context");
  1375. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  1376. case TokenType::Delete: {
  1377. consume();
  1378. auto rhs_start = position();
  1379. auto rhs = parse_expression(precedence, associativity);
  1380. if (is<Identifier>(*rhs) && m_state.strict_mode) {
  1381. syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start);
  1382. }
  1383. if (is<MemberExpression>(*rhs)) {
  1384. auto& member_expression = static_cast<MemberExpression const&>(*rhs);
  1385. if (member_expression.ends_in_private_name())
  1386. syntax_error("Private fields cannot be deleted");
  1387. }
  1388. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, move(rhs));
  1389. }
  1390. default:
  1391. expected("primary expression");
  1392. consume();
  1393. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1394. }
  1395. }
  1396. NonnullRefPtr<Expression> Parser::parse_property_key()
  1397. {
  1398. auto rule_start = push_start();
  1399. if (match(TokenType::StringLiteral)) {
  1400. return parse_string_literal(consume());
  1401. } else if (match(TokenType::NumericLiteral)) {
  1402. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  1403. } else if (match(TokenType::BigIntLiteral)) {
  1404. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1405. } else if (match(TokenType::BracketOpen)) {
  1406. consume(TokenType::BracketOpen);
  1407. auto result = parse_expression(2);
  1408. consume(TokenType::BracketClose);
  1409. return result;
  1410. } else {
  1411. if (!match_identifier_name())
  1412. expected("IdentifierName");
  1413. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1414. }
  1415. }
  1416. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  1417. {
  1418. auto rule_start = push_start();
  1419. consume(TokenType::CurlyOpen);
  1420. NonnullRefPtrVector<ObjectProperty> properties;
  1421. ObjectProperty::Type property_type;
  1422. Optional<SourceRange> invalid_object_literal_property_range;
  1423. auto skip_to_next_property = [&] {
  1424. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  1425. consume();
  1426. };
  1427. // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate
  1428. // entries for "__proto__" and at least two of those entries were obtained from productions of
  1429. // the form PropertyDefinition : PropertyKey : AssignmentExpression .
  1430. bool has_direct_proto_property = false;
  1431. while (!done() && !match(TokenType::CurlyClose)) {
  1432. property_type = ObjectProperty::Type::KeyValue;
  1433. RefPtr<Expression> property_key;
  1434. RefPtr<Expression> property_value;
  1435. FunctionKind function_kind { FunctionKind::Normal };
  1436. if (match(TokenType::TripleDot)) {
  1437. consume();
  1438. property_key = parse_expression(4);
  1439. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, nullptr, ObjectProperty::Type::Spread, false));
  1440. if (!match(TokenType::Comma))
  1441. break;
  1442. consume(TokenType::Comma);
  1443. continue;
  1444. }
  1445. auto type = m_state.current_token.type();
  1446. auto function_start = position();
  1447. if (match(TokenType::Async)) {
  1448. auto lookahead_token = next_token();
  1449. if (lookahead_token.type() != TokenType::ParenOpen && lookahead_token.type() != TokenType::Colon
  1450. && lookahead_token.type() != TokenType::Comma && lookahead_token.type() != TokenType::CurlyClose
  1451. && lookahead_token.type() != TokenType::Async
  1452. && !lookahead_token.trivia_contains_line_terminator()) {
  1453. consume(TokenType::Async);
  1454. function_kind = FunctionKind::Async;
  1455. }
  1456. }
  1457. if (match(TokenType::Asterisk)) {
  1458. consume();
  1459. property_type = ObjectProperty::Type::KeyValue;
  1460. property_key = parse_property_key();
  1461. VERIFY(function_kind == FunctionKind::Normal || function_kind == FunctionKind::Async);
  1462. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  1463. } else if (match_identifier()) {
  1464. auto identifier = consume();
  1465. if (identifier.original_value() == "get"sv && match_property_key()) {
  1466. property_type = ObjectProperty::Type::Getter;
  1467. property_key = parse_property_key();
  1468. } else if (identifier.original_value() == "set"sv && match_property_key()) {
  1469. property_type = ObjectProperty::Type::Setter;
  1470. property_key = parse_property_key();
  1471. } else {
  1472. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1473. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.flystring_value());
  1474. }
  1475. } else {
  1476. property_key = parse_property_key();
  1477. }
  1478. // 4. Else if propKey is the String value "__proto__" and if IsComputedPropertyKey of PropertyName is false, then
  1479. // a. Let isProtoSetter be true.
  1480. bool is_proto = (type == TokenType::StringLiteral || type == TokenType::Identifier) && is<StringLiteral>(*property_key) && static_cast<StringLiteral const&>(*property_key).value() == "__proto__";
  1481. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  1482. if (!match(TokenType::ParenOpen)) {
  1483. expected("'(' for object getter or setter property");
  1484. skip_to_next_property();
  1485. continue;
  1486. }
  1487. }
  1488. if (match(TokenType::Equals)) {
  1489. // Not a valid object literal, but a valid assignment target
  1490. consume();
  1491. // Parse the expression and throw it away
  1492. auto expression = parse_expression(2);
  1493. if (!invalid_object_literal_property_range.has_value())
  1494. invalid_object_literal_property_range = expression->source_range();
  1495. } else if (match(TokenType::ParenOpen)) {
  1496. VERIFY(property_key);
  1497. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1498. if (property_type == ObjectProperty::Type::Getter)
  1499. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1500. if (property_type == ObjectProperty::Type::Setter)
  1501. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1502. if (function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator)
  1503. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1504. if (function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator)
  1505. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1506. auto function = parse_function_node<FunctionExpression>(parse_options, function_start);
  1507. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, function, property_type, true));
  1508. } else if (match(TokenType::Colon)) {
  1509. if (!property_key) {
  1510. expected("a property name");
  1511. skip_to_next_property();
  1512. continue;
  1513. }
  1514. consume();
  1515. if (is_proto) {
  1516. if (has_direct_proto_property)
  1517. syntax_error("Property name '__proto__' must not appear more than once in object literal");
  1518. has_direct_proto_property = true;
  1519. }
  1520. if (is_proto && property_type == ObjectProperty::Type::KeyValue)
  1521. property_type = ObjectProperty::Type::ProtoSetter;
  1522. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, parse_expression(2), property_type, false));
  1523. } else if (property_key && property_value) {
  1524. if (m_state.strict_mode && is<StringLiteral>(*property_key)) {
  1525. auto& string_literal = static_cast<StringLiteral const&>(*property_key);
  1526. if (is_strict_reserved_word(string_literal.value()))
  1527. syntax_error(String::formatted("'{}' is a reserved keyword", string_literal.value()));
  1528. }
  1529. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, *property_value, property_type, false));
  1530. } else {
  1531. expected("a property");
  1532. skip_to_next_property();
  1533. continue;
  1534. }
  1535. if (!match(TokenType::Comma))
  1536. break;
  1537. consume(TokenType::Comma);
  1538. }
  1539. consume(TokenType::CurlyClose);
  1540. return create_ast_node<ObjectExpression>(
  1541. { m_state.current_token.filename(), rule_start.position(), position() },
  1542. move(properties),
  1543. move(invalid_object_literal_property_range));
  1544. }
  1545. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  1546. {
  1547. auto rule_start = push_start();
  1548. consume(TokenType::BracketOpen);
  1549. Vector<RefPtr<Expression>> elements;
  1550. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  1551. RefPtr<Expression> expression;
  1552. if (match(TokenType::TripleDot)) {
  1553. consume(TokenType::TripleDot);
  1554. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  1555. } else if (match_expression()) {
  1556. expression = parse_expression(2);
  1557. }
  1558. elements.append(expression);
  1559. if (!match(TokenType::Comma))
  1560. break;
  1561. consume(TokenType::Comma);
  1562. }
  1563. consume(TokenType::BracketClose);
  1564. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  1565. }
  1566. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(Token const& token, bool in_template_literal)
  1567. {
  1568. auto rule_start = push_start();
  1569. auto status = Token::StringValueStatus::Ok;
  1570. auto string = token.string_value(status);
  1571. if (status != Token::StringValueStatus::Ok) {
  1572. String message;
  1573. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  1574. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  1575. if (in_template_literal)
  1576. message = "Octal escape sequence not allowed in template literal";
  1577. else if (m_state.strict_mode)
  1578. message = "Octal escape sequence in string literal not allowed in strict mode";
  1579. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  1580. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  1581. message = String::formatted("Malformed {} escape sequence", type);
  1582. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  1583. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  1584. } else {
  1585. VERIFY_NOT_REACHED();
  1586. }
  1587. if (!message.is_empty())
  1588. syntax_error(message, Position { token.line_number(), token.line_column() });
  1589. }
  1590. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  1591. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  1592. }
  1593. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  1594. {
  1595. auto rule_start = push_start();
  1596. consume(TokenType::TemplateLiteralStart);
  1597. NonnullRefPtrVector<Expression> expressions;
  1598. NonnullRefPtrVector<Expression> raw_strings;
  1599. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  1600. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  1601. expressions.append(string_literal);
  1602. if (is_tagged)
  1603. raw_strings.append(string_literal);
  1604. };
  1605. if (!match(TokenType::TemplateLiteralString))
  1606. append_empty_string();
  1607. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  1608. if (match(TokenType::TemplateLiteralString)) {
  1609. auto token = consume();
  1610. expressions.append(parse_string_literal(token, true));
  1611. if (is_tagged)
  1612. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.raw_template_value()));
  1613. } else if (match(TokenType::TemplateLiteralExprStart)) {
  1614. consume(TokenType::TemplateLiteralExprStart);
  1615. if (match(TokenType::TemplateLiteralExprEnd)) {
  1616. syntax_error("Empty template literal expression block");
  1617. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1618. }
  1619. expressions.append(parse_expression(0));
  1620. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1621. syntax_error("Unterminated template literal");
  1622. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1623. }
  1624. consume(TokenType::TemplateLiteralExprEnd);
  1625. if (!match(TokenType::TemplateLiteralString))
  1626. append_empty_string();
  1627. } else {
  1628. expected("Template literal string or expression");
  1629. break;
  1630. }
  1631. }
  1632. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1633. syntax_error("Unterminated template literal");
  1634. } else {
  1635. consume(TokenType::TemplateLiteralEnd);
  1636. }
  1637. if (is_tagged)
  1638. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  1639. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1640. }
  1641. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1642. {
  1643. auto rule_start = push_start();
  1644. auto [expression, should_continue_parsing] = parse_primary_expression();
  1645. auto check_for_invalid_object_property = [&](auto& expression) {
  1646. if (is<ObjectExpression>(*expression)) {
  1647. if (auto range = static_cast<ObjectExpression&>(*expression).invalid_property_range(); range.has_value())
  1648. syntax_error("Invalid property in object literal", range->start);
  1649. }
  1650. };
  1651. if (is<Identifier>(*expression) && m_state.current_scope_pusher) {
  1652. auto identifier_instance = static_ptr_cast<Identifier>(expression);
  1653. auto function_scope = m_state.current_scope_pusher->last_function_scope();
  1654. auto function_parent_scope = function_scope ? function_scope->parent_scope() : nullptr;
  1655. bool has_not_been_declared_as_variable = true;
  1656. for (auto scope = m_state.current_scope_pusher; scope != function_parent_scope; scope = scope->parent_scope()) {
  1657. if (scope->has_declaration(identifier_instance->string())) {
  1658. has_not_been_declared_as_variable = false;
  1659. break;
  1660. }
  1661. }
  1662. if (has_not_been_declared_as_variable) {
  1663. if (identifier_instance->string() == "arguments"sv)
  1664. m_state.current_scope_pusher->set_contains_access_to_arguments_object();
  1665. }
  1666. }
  1667. while (match(TokenType::TemplateLiteralStart)) {
  1668. auto template_literal = parse_template_literal(true);
  1669. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1670. }
  1671. if (should_continue_parsing) {
  1672. while (match_secondary_expression(forbidden)) {
  1673. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  1674. if (new_precedence < min_precedence)
  1675. break;
  1676. if (new_precedence == min_precedence && associativity == Associativity::Left)
  1677. break;
  1678. check_for_invalid_object_property(expression);
  1679. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  1680. auto result = parse_secondary_expression(move(expression), new_precedence, new_associativity, forbidden);
  1681. expression = result.expression;
  1682. forbidden = forbidden.merge(result.forbidden);
  1683. while (match(TokenType::TemplateLiteralStart) && !is<UpdateExpression>(*expression)) {
  1684. auto template_literal = parse_template_literal(true);
  1685. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1686. }
  1687. }
  1688. }
  1689. if (is<SuperExpression>(*expression))
  1690. syntax_error("'super' keyword unexpected here");
  1691. check_for_invalid_object_property(expression);
  1692. if (is<CallExpression>(*expression) && m_state.current_scope_pusher) {
  1693. auto& callee = static_ptr_cast<CallExpression>(expression)->callee();
  1694. if (is<Identifier>(callee)) {
  1695. auto& identifier_instance = static_cast<Identifier const&>(callee);
  1696. if (identifier_instance.string() == "eval"sv) {
  1697. bool has_not_been_declared_as_variable = true;
  1698. for (auto scope = m_state.current_scope_pusher; scope; scope = scope->parent_scope()) {
  1699. if (scope->has_declaration(identifier_instance.string())) {
  1700. has_not_been_declared_as_variable = false;
  1701. break;
  1702. }
  1703. }
  1704. if (has_not_been_declared_as_variable)
  1705. m_state.current_scope_pusher->set_contains_direct_call_to_eval();
  1706. }
  1707. }
  1708. }
  1709. if (match(TokenType::Comma) && min_precedence <= 1) {
  1710. NonnullRefPtrVector<Expression> expressions;
  1711. expressions.append(expression);
  1712. while (match(TokenType::Comma)) {
  1713. consume();
  1714. expressions.append(parse_expression(2));
  1715. }
  1716. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  1717. }
  1718. return expression;
  1719. }
  1720. Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1721. {
  1722. auto rule_start = push_start();
  1723. switch (m_state.current_token.type()) {
  1724. case TokenType::Plus:
  1725. consume();
  1726. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1727. case TokenType::PlusEquals:
  1728. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1729. case TokenType::Minus:
  1730. consume();
  1731. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1732. case TokenType::MinusEquals:
  1733. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1734. case TokenType::Asterisk:
  1735. consume();
  1736. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1737. case TokenType::AsteriskEquals:
  1738. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity, forbidden);
  1739. case TokenType::Slash:
  1740. consume();
  1741. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1742. case TokenType::SlashEquals:
  1743. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1744. case TokenType::Percent:
  1745. consume();
  1746. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1747. case TokenType::PercentEquals:
  1748. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity, forbidden);
  1749. case TokenType::DoubleAsterisk:
  1750. consume();
  1751. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1752. case TokenType::DoubleAsteriskEquals:
  1753. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity, forbidden);
  1754. case TokenType::GreaterThan:
  1755. consume();
  1756. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1757. case TokenType::GreaterThanEquals:
  1758. consume();
  1759. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1760. case TokenType::LessThan:
  1761. consume();
  1762. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1763. case TokenType::LessThanEquals:
  1764. consume();
  1765. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1766. case TokenType::EqualsEqualsEquals:
  1767. consume();
  1768. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1769. case TokenType::ExclamationMarkEqualsEquals:
  1770. consume();
  1771. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyInequals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1772. case TokenType::EqualsEquals:
  1773. consume();
  1774. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1775. case TokenType::ExclamationMarkEquals:
  1776. consume();
  1777. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyInequals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1778. case TokenType::In:
  1779. consume();
  1780. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1781. case TokenType::Instanceof:
  1782. consume();
  1783. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1784. case TokenType::Ampersand:
  1785. consume();
  1786. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1787. case TokenType::AmpersandEquals:
  1788. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity, forbidden);
  1789. case TokenType::Pipe:
  1790. consume();
  1791. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1792. case TokenType::PipeEquals:
  1793. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity, forbidden);
  1794. case TokenType::Caret:
  1795. consume();
  1796. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1797. case TokenType::CaretEquals:
  1798. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity, forbidden);
  1799. case TokenType::ShiftLeft:
  1800. consume();
  1801. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1802. case TokenType::ShiftLeftEquals:
  1803. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1804. case TokenType::ShiftRight:
  1805. consume();
  1806. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1807. case TokenType::ShiftRightEquals:
  1808. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1809. case TokenType::UnsignedShiftRight:
  1810. consume();
  1811. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1812. case TokenType::UnsignedShiftRightEquals:
  1813. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1814. case TokenType::ParenOpen:
  1815. return parse_call_expression(move(lhs));
  1816. case TokenType::Equals:
  1817. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity, forbidden);
  1818. case TokenType::Period:
  1819. consume();
  1820. if (match(TokenType::PrivateIdentifier)) {
  1821. if (!is_private_identifier_valid())
  1822. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1823. else if (is<SuperExpression>(*lhs))
  1824. syntax_error(String::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value()));
  1825. 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()));
  1826. } else if (!match_identifier_name()) {
  1827. expected("IdentifierName");
  1828. }
  1829. 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()));
  1830. case TokenType::BracketOpen: {
  1831. consume(TokenType::BracketOpen);
  1832. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1833. consume(TokenType::BracketClose);
  1834. return expression;
  1835. }
  1836. case TokenType::PlusPlus:
  1837. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1838. // other engines throw ReferenceError for foo()++
  1839. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1840. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1841. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1842. auto& identifier = static_cast<Identifier&>(*lhs);
  1843. auto& name = identifier.string();
  1844. check_identifier_name_for_assignment_validity(name);
  1845. }
  1846. consume();
  1847. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1848. case TokenType::MinusMinus:
  1849. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1850. // other engines throw ReferenceError for foo()--
  1851. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1852. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1853. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1854. auto& identifier = static_cast<Identifier&>(*lhs);
  1855. auto& name = identifier.string();
  1856. check_identifier_name_for_assignment_validity(name);
  1857. }
  1858. consume();
  1859. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1860. case TokenType::DoubleAmpersand: {
  1861. consume();
  1862. 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 })));
  1863. return { expression, { TokenType::DoubleQuestionMark } };
  1864. }
  1865. case TokenType::DoubleAmpersandEquals:
  1866. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity, forbidden);
  1867. case TokenType::DoublePipe: {
  1868. consume();
  1869. 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 })));
  1870. return { expression, { TokenType::DoubleQuestionMark } };
  1871. }
  1872. case TokenType::DoublePipeEquals:
  1873. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity, forbidden);
  1874. case TokenType::DoubleQuestionMark: {
  1875. consume();
  1876. 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 })));
  1877. return { expression, { TokenType::DoubleAmpersand, TokenType::DoublePipe } };
  1878. }
  1879. case TokenType::DoubleQuestionMarkEquals:
  1880. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity, forbidden);
  1881. case TokenType::QuestionMark:
  1882. return parse_conditional_expression(move(lhs), forbidden);
  1883. case TokenType::QuestionMarkPeriod:
  1884. // FIXME: This should allow `(new Foo)?.bar', but as our parser strips parenthesis,
  1885. // we can't really tell if `lhs' was parenthesized at this point.
  1886. if (is<NewExpression>(lhs.ptr())) {
  1887. syntax_error("'new' cannot be used with optional chaining", position());
  1888. consume();
  1889. return lhs;
  1890. }
  1891. return parse_optional_chain(move(lhs));
  1892. default:
  1893. expected("secondary expression");
  1894. consume();
  1895. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1896. }
  1897. }
  1898. bool Parser::is_private_identifier_valid() const
  1899. {
  1900. VERIFY(match(TokenType::PrivateIdentifier));
  1901. if (!m_state.referenced_private_names)
  1902. return false;
  1903. // We might not have hit the declaration yet so class will check this in the end
  1904. m_state.referenced_private_names->set(m_state.current_token.value());
  1905. return true;
  1906. }
  1907. RefPtr<BindingPattern> Parser::synthesize_binding_pattern(Expression const& expression)
  1908. {
  1909. VERIFY(is<ArrayExpression>(expression) || is<ObjectExpression>(expression));
  1910. // Clear any syntax error that has occurred in the range that 'expression' spans.
  1911. m_state.errors.remove_all_matching([range = expression.source_range()](auto const& error) {
  1912. return error.position.has_value() && range.contains(*error.position);
  1913. });
  1914. // Make a parser and parse the source for this expression as a binding pattern.
  1915. // NOTE: There's currently a fundamental problem that we pass the *next* (a.k.a. `current_token`)
  1916. // token's position to most nodes' SourceRange when using `rule_start.position(), position()`.
  1917. // This means that `source` will contain the subsequent token's trivia, if any (which is fine).
  1918. auto source_start_offset = expression.source_range().start.offset;
  1919. auto source_end_offset = expression.source_range().end.offset;
  1920. auto source = m_state.lexer.source().substring_view(source_start_offset, source_end_offset - source_start_offset);
  1921. Lexer lexer { source, m_state.lexer.filename(), expression.source_range().start.line, expression.source_range().start.column };
  1922. Parser parser { lexer };
  1923. parser.m_state.strict_mode = m_state.strict_mode;
  1924. parser.m_state.allow_super_property_lookup = m_state.allow_super_property_lookup;
  1925. parser.m_state.allow_super_constructor_call = m_state.allow_super_constructor_call;
  1926. parser.m_state.in_function_context = m_state.in_function_context;
  1927. parser.m_state.in_formal_parameter_context = m_state.in_formal_parameter_context;
  1928. parser.m_state.in_generator_function_context = m_state.in_generator_function_context;
  1929. parser.m_state.await_expression_is_valid = m_state.await_expression_is_valid;
  1930. parser.m_state.in_arrow_function_context = m_state.in_arrow_function_context;
  1931. parser.m_state.in_break_context = m_state.in_break_context;
  1932. parser.m_state.in_continue_context = m_state.in_continue_context;
  1933. parser.m_state.string_legacy_octal_escape_sequence_in_scope = m_state.string_legacy_octal_escape_sequence_in_scope;
  1934. parser.m_state.in_class_field_initializer = m_state.in_class_field_initializer;
  1935. parser.m_state.in_class_static_init_block = m_state.in_class_static_init_block;
  1936. parser.m_state.referenced_private_names = m_state.referenced_private_names;
  1937. auto result = parser.parse_binding_pattern(AllowDuplicates::Yes, AllowMemberExpressions::Yes);
  1938. if (parser.has_errors())
  1939. m_state.errors.extend(parser.errors());
  1940. return result;
  1941. }
  1942. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1943. {
  1944. auto rule_start = push_start();
  1945. VERIFY(match(TokenType::Equals)
  1946. || match(TokenType::PlusEquals)
  1947. || match(TokenType::MinusEquals)
  1948. || match(TokenType::AsteriskEquals)
  1949. || match(TokenType::SlashEquals)
  1950. || match(TokenType::PercentEquals)
  1951. || match(TokenType::DoubleAsteriskEquals)
  1952. || match(TokenType::AmpersandEquals)
  1953. || match(TokenType::PipeEquals)
  1954. || match(TokenType::CaretEquals)
  1955. || match(TokenType::ShiftLeftEquals)
  1956. || match(TokenType::ShiftRightEquals)
  1957. || match(TokenType::UnsignedShiftRightEquals)
  1958. || match(TokenType::DoubleAmpersandEquals)
  1959. || match(TokenType::DoublePipeEquals)
  1960. || match(TokenType::DoubleQuestionMarkEquals));
  1961. consume();
  1962. if (assignment_op == AssignmentOp::Assignment) {
  1963. if (is<ArrayExpression>(*lhs) || is<ObjectExpression>(*lhs)) {
  1964. auto binding_pattern = synthesize_binding_pattern(*lhs);
  1965. if (binding_pattern) {
  1966. auto rhs = parse_expression(min_precedence, associativity);
  1967. return create_ast_node<AssignmentExpression>(
  1968. { m_state.current_token.filename(), rule_start.position(), position() },
  1969. assignment_op,
  1970. binding_pattern.release_nonnull(),
  1971. move(rhs));
  1972. }
  1973. }
  1974. }
  1975. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1976. syntax_error("Invalid left-hand side in assignment");
  1977. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1978. auto const& name = static_cast<Identifier const&>(*lhs).string();
  1979. check_identifier_name_for_assignment_validity(name);
  1980. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1981. syntax_error("Cannot assign to function call");
  1982. }
  1983. auto rhs = parse_expression(min_precedence, associativity, forbidden);
  1984. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1985. }
  1986. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1987. {
  1988. auto identifier_start = position();
  1989. auto token = consume_identifier();
  1990. if (m_state.in_class_field_initializer && token.value() == "arguments"sv)
  1991. syntax_error("'arguments' is not allowed in class field initializer");
  1992. return create_ast_node<Identifier>(
  1993. { m_state.current_token.filename(), identifier_start, position() },
  1994. token.flystring_value());
  1995. }
  1996. Vector<CallExpression::Argument> Parser::parse_arguments()
  1997. {
  1998. Vector<CallExpression::Argument> arguments;
  1999. consume(TokenType::ParenOpen);
  2000. while (match_expression() || match(TokenType::TripleDot)) {
  2001. if (match(TokenType::TripleDot)) {
  2002. consume();
  2003. arguments.append({ parse_expression(2), true });
  2004. } else {
  2005. arguments.append({ parse_expression(2), false });
  2006. }
  2007. if (!match(TokenType::Comma))
  2008. break;
  2009. consume();
  2010. }
  2011. consume(TokenType::ParenClose);
  2012. return arguments;
  2013. }
  2014. NonnullRefPtr<Expression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  2015. {
  2016. auto rule_start = push_start();
  2017. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  2018. syntax_error("'super' keyword unexpected here");
  2019. auto arguments = parse_arguments();
  2020. if (is<SuperExpression>(*lhs))
  2021. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  2022. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  2023. }
  2024. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  2025. {
  2026. auto rule_start = push_start();
  2027. consume(TokenType::New);
  2028. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod });
  2029. if (is<ImportCall>(*callee))
  2030. syntax_error("Cannot call new on dynamic import", callee->source_range().start);
  2031. Vector<CallExpression::Argument> arguments;
  2032. if (match(TokenType::ParenOpen)) {
  2033. consume(TokenType::ParenOpen);
  2034. while (match_expression() || match(TokenType::TripleDot)) {
  2035. if (match(TokenType::TripleDot)) {
  2036. consume();
  2037. arguments.append({ parse_expression(2), true });
  2038. } else {
  2039. arguments.append({ parse_expression(2), false });
  2040. }
  2041. if (!match(TokenType::Comma))
  2042. break;
  2043. consume();
  2044. }
  2045. consume(TokenType::ParenClose);
  2046. }
  2047. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  2048. }
  2049. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  2050. {
  2051. auto rule_start = push_start();
  2052. if (m_state.in_formal_parameter_context)
  2053. syntax_error("'Yield' expression is not allowed in formal parameters of generator function");
  2054. consume(TokenType::Yield);
  2055. RefPtr<Expression> argument;
  2056. bool yield_from = false;
  2057. if (!m_state.current_token.trivia_contains_line_terminator()) {
  2058. if (match(TokenType::Asterisk)) {
  2059. consume();
  2060. yield_from = true;
  2061. }
  2062. if (yield_from || match_expression() || match(TokenType::Class))
  2063. argument = parse_expression(2);
  2064. }
  2065. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  2066. }
  2067. NonnullRefPtr<AwaitExpression> Parser::parse_await_expression()
  2068. {
  2069. auto rule_start = push_start();
  2070. if (m_state.in_formal_parameter_context)
  2071. syntax_error("'Await' expression is not allowed in formal parameters of an async function");
  2072. consume(TokenType::Await);
  2073. auto precedence = g_operator_precedence.get(TokenType::Await);
  2074. auto associativity = operator_associativity(TokenType::Await);
  2075. auto argument = parse_expression(precedence, associativity);
  2076. m_state.current_scope_pusher->set_contains_await_expression();
  2077. return create_ast_node<AwaitExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument));
  2078. }
  2079. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  2080. {
  2081. auto rule_start = push_start();
  2082. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  2083. syntax_error("'return' not allowed outside of a function");
  2084. consume(TokenType::Return);
  2085. // Automatic semicolon insertion: terminate statement when return is followed by newline
  2086. if (m_state.current_token.trivia_contains_line_terminator())
  2087. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2088. if (match_expression()) {
  2089. auto expression = parse_expression(0);
  2090. consume_or_insert_semicolon();
  2091. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2092. }
  2093. consume_or_insert_semicolon();
  2094. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2095. }
  2096. void Parser::parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions)
  2097. {
  2098. while (!done()) {
  2099. if (match_declaration()) {
  2100. auto declaration = parse_declaration();
  2101. VERIFY(m_state.current_scope_pusher);
  2102. m_state.current_scope_pusher->add_declaration(declaration);
  2103. output_node.append(move(declaration));
  2104. } else if (match_statement()) {
  2105. output_node.append(parse_statement(allow_labelled_functions));
  2106. } else {
  2107. break;
  2108. }
  2109. }
  2110. }
  2111. // FunctionBody, https://tc39.es/ecma262/#prod-FunctionBody
  2112. NonnullRefPtr<FunctionBody> Parser::parse_function_body(Vector<FunctionDeclaration::Parameter> const& parameters, FunctionKind function_kind, bool& contains_direct_call_to_eval)
  2113. {
  2114. auto rule_start = push_start();
  2115. auto function_body = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  2116. ScopePusher function_scope = ScopePusher::function_scope(*this, function_body, parameters); // FIXME <-
  2117. auto has_use_strict = parse_directive(function_body);
  2118. bool previous_strict_mode = m_state.strict_mode;
  2119. if (has_use_strict) {
  2120. m_state.strict_mode = true;
  2121. function_body->set_strict_mode();
  2122. if (!is_simple_parameter_list(parameters))
  2123. syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");
  2124. } else if (previous_strict_mode) {
  2125. function_body->set_strict_mode();
  2126. }
  2127. parse_statement_list(function_body);
  2128. // If we're parsing the function body standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2129. // Otherwise, we need a closing curly bracket (which is consumed elsewhere). If we get neither, it's an error.
  2130. if (!match(TokenType::Eof) && !match(TokenType::CurlyClose))
  2131. expected(Token::name(TokenType::CurlyClose));
  2132. // If the function contains 'use strict' we need to check the parameters (again).
  2133. if (function_body->in_strict_mode() || function_kind != FunctionKind::Normal) {
  2134. Vector<StringView> parameter_names;
  2135. for (auto& parameter : parameters) {
  2136. parameter.binding.visit(
  2137. [&](FlyString const& parameter_name) {
  2138. check_identifier_name_for_assignment_validity(parameter_name, function_body->in_strict_mode());
  2139. if (function_kind == FunctionKind::Generator && parameter_name == "yield"sv)
  2140. syntax_error("Parameter name 'yield' not allowed in this context");
  2141. if (function_kind == FunctionKind::Async && parameter_name == "await"sv)
  2142. syntax_error("Parameter name 'await' not allowed in this context");
  2143. for (auto& previous_name : parameter_names) {
  2144. if (previous_name == parameter_name) {
  2145. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name));
  2146. }
  2147. }
  2148. parameter_names.append(parameter_name);
  2149. },
  2150. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2151. binding->for_each_bound_name([&](auto& bound_name) {
  2152. if (function_kind == FunctionKind::Generator && bound_name == "yield"sv)
  2153. syntax_error("Parameter name 'yield' not allowed in this context");
  2154. if (function_kind == FunctionKind::Async && bound_name == "await"sv)
  2155. syntax_error("Parameter name 'await' not allowed in this context");
  2156. for (auto& previous_name : parameter_names) {
  2157. if (previous_name == bound_name) {
  2158. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", bound_name));
  2159. break;
  2160. }
  2161. }
  2162. parameter_names.append(bound_name);
  2163. });
  2164. });
  2165. }
  2166. }
  2167. m_state.strict_mode = previous_strict_mode;
  2168. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  2169. return function_body;
  2170. }
  2171. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  2172. {
  2173. auto rule_start = push_start();
  2174. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2175. ScopePusher block_scope = ScopePusher::block_scope(*this, block);
  2176. consume(TokenType::CurlyOpen);
  2177. parse_statement_list(block);
  2178. consume(TokenType::CurlyClose);
  2179. return block;
  2180. }
  2181. template<typename FunctionNodeType>
  2182. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options, Optional<Position> const& function_start)
  2183. {
  2184. auto rule_start = function_start.has_value()
  2185. ? RulePosition { *this, *function_start }
  2186. : push_start();
  2187. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  2188. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  2189. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  2190. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  2191. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  2192. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, false);
  2193. TemporaryChange might_need_arguments_object_rollback(m_state.function_might_need_arguments_object, false);
  2194. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  2195. FunctionKind function_kind;
  2196. if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0 && (parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2197. function_kind = FunctionKind::AsyncGenerator;
  2198. else if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0)
  2199. function_kind = FunctionKind::Generator;
  2200. else if ((parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2201. function_kind = FunctionKind::Async;
  2202. else
  2203. function_kind = FunctionKind::Normal;
  2204. FlyString name;
  2205. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  2206. if (function_kind == FunctionKind::Normal && match(TokenType::Async) && !next_token().trivia_contains_line_terminator()) {
  2207. function_kind = FunctionKind::Async;
  2208. consume(TokenType::Async);
  2209. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  2210. }
  2211. consume(TokenType::Function);
  2212. if (match(TokenType::Asterisk)) {
  2213. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  2214. consume(TokenType::Asterisk);
  2215. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  2216. }
  2217. if (FunctionNodeType::must_have_name() || match_identifier())
  2218. name = consume_identifier().flystring_value();
  2219. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  2220. name = consume().flystring_value();
  2221. check_identifier_name_for_assignment_validity(name);
  2222. if (function_kind == FunctionKind::AsyncGenerator && (name == "await"sv || name == "yield"sv))
  2223. syntax_error(String::formatted("async generator function is not allowed to be called '{}'", name));
  2224. if (m_state.in_class_static_init_block && name == "await"sv)
  2225. syntax_error("'await' is a reserved word");
  2226. }
  2227. TemporaryChange class_static_initializer_rollback(m_state.in_class_static_init_block, false);
  2228. TemporaryChange generator_change(m_state.in_generator_function_context, function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator);
  2229. TemporaryChange async_change(m_state.await_expression_is_valid, function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator);
  2230. consume(TokenType::ParenOpen);
  2231. i32 function_length = -1;
  2232. auto parameters = parse_formal_parameters(function_length, parse_options);
  2233. consume(TokenType::ParenClose);
  2234. if (function_length == -1)
  2235. function_length = parameters.size();
  2236. TemporaryChange function_context_rollback(m_state.in_function_context, true);
  2237. auto old_labels_in_scope = move(m_state.labels_in_scope);
  2238. ScopeGuard guard([&]() {
  2239. m_state.labels_in_scope = move(old_labels_in_scope);
  2240. });
  2241. consume(TokenType::CurlyOpen);
  2242. bool contains_direct_call_to_eval = false;
  2243. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  2244. consume(TokenType::CurlyClose);
  2245. auto has_strict_directive = body->in_strict_mode();
  2246. if (has_strict_directive)
  2247. check_identifier_name_for_assignment_validity(name, true);
  2248. auto function_start_offset = rule_start.position().offset;
  2249. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  2250. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  2251. return create_ast_node<FunctionNodeType>(
  2252. { m_state.current_token.filename(), rule_start.position(), position() },
  2253. name, move(source_text), move(body), move(parameters), function_length,
  2254. function_kind, has_strict_directive, m_state.function_might_need_arguments_object,
  2255. contains_direct_call_to_eval);
  2256. }
  2257. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  2258. {
  2259. auto rule_start = push_start();
  2260. bool has_default_parameter = false;
  2261. bool has_rest_parameter = false;
  2262. TemporaryChange formal_parameter_context_change { m_state.in_formal_parameter_context, true };
  2263. Vector<FunctionNode::Parameter> parameters;
  2264. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  2265. if (auto pattern = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No))
  2266. return pattern.release_nonnull();
  2267. auto token = consume_identifier();
  2268. auto parameter_name = token.flystring_value();
  2269. check_identifier_name_for_assignment_validity(parameter_name);
  2270. for (auto& parameter : parameters) {
  2271. bool has_same_name = parameter.binding.visit(
  2272. [&](FlyString const& name) {
  2273. return name == parameter_name;
  2274. },
  2275. [&](NonnullRefPtr<BindingPattern> const& bindings) {
  2276. bool found_duplicate = false;
  2277. bindings->for_each_bound_name([&](auto& bound_name) {
  2278. if (bound_name == parameter_name)
  2279. found_duplicate = true;
  2280. });
  2281. return found_duplicate;
  2282. });
  2283. if (!has_same_name)
  2284. continue;
  2285. String message;
  2286. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  2287. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  2288. else if (m_state.strict_mode)
  2289. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  2290. else if (has_default_parameter || match(TokenType::Equals))
  2291. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  2292. else if (has_rest_parameter)
  2293. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  2294. if (!message.is_empty())
  2295. syntax_error(message, Position { token.line_number(), token.line_column() });
  2296. break;
  2297. }
  2298. return FlyString { token.value() };
  2299. };
  2300. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) {
  2301. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  2302. syntax_error("Getter function must have no arguments");
  2303. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  2304. syntax_error("Setter function must have one argument");
  2305. auto is_rest = false;
  2306. if (match(TokenType::TripleDot)) {
  2307. consume();
  2308. has_rest_parameter = true;
  2309. function_length = parameters.size();
  2310. is_rest = true;
  2311. }
  2312. auto parameter = consume_identifier_or_binding_pattern();
  2313. RefPtr<Expression> default_value;
  2314. if (match(TokenType::Equals)) {
  2315. consume();
  2316. if (is_rest)
  2317. syntax_error("Rest parameter may not have a default initializer");
  2318. TemporaryChange change(m_state.in_function_context, true);
  2319. has_default_parameter = true;
  2320. function_length = parameters.size();
  2321. default_value = parse_expression(2);
  2322. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  2323. if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  2324. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  2325. }
  2326. parameters.append({ move(parameter), default_value, is_rest });
  2327. if (!match(TokenType::Comma) || is_rest)
  2328. break;
  2329. consume(TokenType::Comma);
  2330. }
  2331. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  2332. syntax_error("Setter function must have one argument");
  2333. // If we're parsing the parameters standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2334. // Otherwise, we need a closing parenthesis (which is consumed elsewhere). If we get neither, it's an error.
  2335. if (!match(TokenType::Eof) && !match(TokenType::ParenClose))
  2336. expected(Token::name(TokenType::ParenClose));
  2337. return parameters;
  2338. }
  2339. 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" };
  2340. RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates allow_duplicates, Parser::AllowMemberExpressions allow_member_expressions)
  2341. {
  2342. auto rule_start = push_start();
  2343. TokenType closing_token;
  2344. bool is_object = true;
  2345. if (match(TokenType::BracketOpen)) {
  2346. consume();
  2347. closing_token = TokenType::BracketClose;
  2348. is_object = false;
  2349. } else if (match(TokenType::CurlyOpen)) {
  2350. consume();
  2351. closing_token = TokenType::CurlyClose;
  2352. } else {
  2353. return {};
  2354. }
  2355. Vector<BindingPattern::BindingEntry> entries;
  2356. while (!match(closing_token)) {
  2357. if (!is_object && match(TokenType::Comma)) {
  2358. consume();
  2359. entries.append(BindingPattern::BindingEntry {});
  2360. continue;
  2361. }
  2362. auto is_rest = false;
  2363. if (match(TokenType::TripleDot)) {
  2364. consume();
  2365. is_rest = true;
  2366. }
  2367. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  2368. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  2369. RefPtr<Expression> initializer = {};
  2370. if (is_object) {
  2371. bool needs_alias = false;
  2372. if (allow_member_expressions == AllowMemberExpressions::Yes && is_rest) {
  2373. auto expression_position = position();
  2374. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2375. if (is<MemberExpression>(*expression))
  2376. alias = static_ptr_cast<MemberExpression>(expression);
  2377. else if (is<Identifier>(*expression))
  2378. name = static_ptr_cast<Identifier>(expression);
  2379. else
  2380. syntax_error("Invalid destructuring assignment target", expression_position);
  2381. } else if (match_identifier_name() || match(TokenType::StringLiteral) || match(TokenType::NumericLiteral)) {
  2382. if (match(TokenType::StringLiteral) || match(TokenType::NumericLiteral))
  2383. needs_alias = true;
  2384. if (match(TokenType::StringLiteral)) {
  2385. auto token = consume(TokenType::StringLiteral);
  2386. auto string_literal = parse_string_literal(token);
  2387. name = create_ast_node<Identifier>(
  2388. { m_state.current_token.filename(), rule_start.position(), position() },
  2389. string_literal->value());
  2390. } else {
  2391. name = create_ast_node<Identifier>(
  2392. { m_state.current_token.filename(), rule_start.position(), position() },
  2393. consume().flystring_value());
  2394. }
  2395. } else if (match(TokenType::BracketOpen)) {
  2396. consume();
  2397. auto expression = parse_expression(0);
  2398. name = move(expression);
  2399. consume(TokenType::BracketClose);
  2400. } else {
  2401. expected("identifier or computed property name");
  2402. return {};
  2403. }
  2404. if (!is_rest && match(TokenType::Colon)) {
  2405. consume();
  2406. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2407. auto expression_position = position();
  2408. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2409. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2410. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2411. alias = synthesized_binding_pattern.release_nonnull();
  2412. else
  2413. syntax_error("Invalid destructuring assignment target", expression_position);
  2414. } else if (is<MemberExpression>(*expression)) {
  2415. alias = static_ptr_cast<MemberExpression>(expression);
  2416. } else if (is<Identifier>(*expression)) {
  2417. alias = static_ptr_cast<Identifier>(expression);
  2418. } else {
  2419. syntax_error("Invalid destructuring assignment target", expression_position);
  2420. }
  2421. } else if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  2422. auto binding_pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2423. if (!binding_pattern)
  2424. return {};
  2425. alias = binding_pattern.release_nonnull();
  2426. } else if (match_identifier_name()) {
  2427. alias = create_ast_node<Identifier>(
  2428. { m_state.current_token.filename(), rule_start.position(), position() },
  2429. consume().flystring_value());
  2430. } else {
  2431. expected("identifier or binding pattern");
  2432. return {};
  2433. }
  2434. } else if (needs_alias) {
  2435. expected("alias for string or numeric literal name");
  2436. return {};
  2437. }
  2438. } else {
  2439. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2440. auto expression_position = position();
  2441. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2442. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2443. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2444. alias = synthesized_binding_pattern.release_nonnull();
  2445. else
  2446. syntax_error("Invalid destructuring assignment target", expression_position);
  2447. } else if (is<MemberExpression>(*expression)) {
  2448. alias = static_ptr_cast<MemberExpression>(expression);
  2449. } else if (is<Identifier>(*expression)) {
  2450. alias = static_ptr_cast<Identifier>(expression);
  2451. } else {
  2452. syntax_error("Invalid destructuring assignment target", expression_position);
  2453. }
  2454. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  2455. auto pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2456. if (!pattern) {
  2457. expected("binding pattern");
  2458. return {};
  2459. }
  2460. alias = pattern.release_nonnull();
  2461. } else if (match_identifier_name()) {
  2462. // BindingElement must always have an Empty name field
  2463. auto identifier_name = consume_identifier().flystring_value();
  2464. alias = create_ast_node<Identifier>(
  2465. { m_state.current_token.filename(), rule_start.position(), position() },
  2466. identifier_name);
  2467. } else {
  2468. expected("identifier or binding pattern");
  2469. return {};
  2470. }
  2471. }
  2472. if (match(TokenType::Equals)) {
  2473. if (is_rest) {
  2474. syntax_error("Unexpected initializer after rest element");
  2475. return {};
  2476. }
  2477. consume();
  2478. initializer = parse_expression(2);
  2479. if (!initializer) {
  2480. expected("initialization expression");
  2481. return {};
  2482. }
  2483. }
  2484. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  2485. if (match(TokenType::Comma)) {
  2486. if (is_rest) {
  2487. syntax_error("Rest element may not be followed by a comma");
  2488. return {};
  2489. }
  2490. consume();
  2491. } else if (is_object && !match(TokenType::CurlyClose)) {
  2492. consume(TokenType::Comma);
  2493. }
  2494. }
  2495. while (!is_object && match(TokenType::Comma))
  2496. consume();
  2497. consume(closing_token);
  2498. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  2499. auto pattern = adopt_ref(*new BindingPattern);
  2500. pattern->entries = move(entries);
  2501. pattern->kind = kind;
  2502. Vector<StringView> bound_names;
  2503. pattern->for_each_bound_name([&](auto& name) {
  2504. if (allow_duplicates == AllowDuplicates::No) {
  2505. if (bound_names.contains_slow(name))
  2506. syntax_error("Duplicate parameter names in bindings");
  2507. bound_names.append(name);
  2508. }
  2509. check_identifier_name_for_assignment_validity(name);
  2510. });
  2511. return pattern;
  2512. }
  2513. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  2514. {
  2515. auto rule_start = push_start();
  2516. DeclarationKind declaration_kind;
  2517. switch (m_state.current_token.type()) {
  2518. case TokenType::Var:
  2519. declaration_kind = DeclarationKind::Var;
  2520. break;
  2521. case TokenType::Let:
  2522. declaration_kind = DeclarationKind::Let;
  2523. break;
  2524. case TokenType::Const:
  2525. declaration_kind = DeclarationKind::Const;
  2526. break;
  2527. default:
  2528. VERIFY_NOT_REACHED();
  2529. }
  2530. consume();
  2531. NonnullRefPtrVector<VariableDeclarator> declarations;
  2532. for (;;) {
  2533. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target {};
  2534. if (match_identifier()) {
  2535. auto identifier_start = push_start();
  2536. auto name = consume_identifier().flystring_value();
  2537. target = create_ast_node<Identifier>(
  2538. { m_state.current_token.filename(), rule_start.position(), position() },
  2539. name);
  2540. check_identifier_name_for_assignment_validity(name);
  2541. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && name == "let"sv)
  2542. syntax_error("Lexical binding may not be called 'let'");
  2543. } else if (auto pattern = parse_binding_pattern(declaration_kind != DeclarationKind::Var ? AllowDuplicates::No : AllowDuplicates::Yes, AllowMemberExpressions::No)) {
  2544. target = pattern.release_nonnull();
  2545. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const)) {
  2546. target.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name([this](auto& name) {
  2547. if (name == "let"sv)
  2548. syntax_error("Lexical binding may not be called 'let'");
  2549. });
  2550. }
  2551. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  2552. if (m_state.strict_mode)
  2553. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  2554. target = create_ast_node<Identifier>(
  2555. { m_state.current_token.filename(), rule_start.position(), position() },
  2556. consume().flystring_value());
  2557. } else if (!m_state.await_expression_is_valid && match(TokenType::Async)) {
  2558. if (m_program_type == Program::Type::Module)
  2559. syntax_error("Identifier must not be a reserved word in modules ('async')");
  2560. target = create_ast_node<Identifier>(
  2561. { m_state.current_token.filename(), rule_start.position(), position() },
  2562. consume().flystring_value());
  2563. }
  2564. if (target.has<Empty>()) {
  2565. expected("identifier or a binding pattern");
  2566. if (match(TokenType::Comma)) {
  2567. consume();
  2568. continue;
  2569. }
  2570. break;
  2571. }
  2572. RefPtr<Expression> init;
  2573. if (match(TokenType::Equals)) {
  2574. consume();
  2575. // In a for loop 'in' can be ambiguous so we do not allow it
  2576. // 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
  2577. if (for_loop_variable_declaration)
  2578. init = parse_expression(2, Associativity::Right, { TokenType::In });
  2579. else
  2580. init = parse_expression(2);
  2581. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  2582. syntax_error("Missing initializer in 'const' variable declaration");
  2583. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  2584. syntax_error("Missing initializer in destructuring assignment");
  2585. }
  2586. declarations.append(create_ast_node<VariableDeclarator>(
  2587. { m_state.current_token.filename(), rule_start.position(), position() },
  2588. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  2589. move(init)));
  2590. if (match(TokenType::Comma)) {
  2591. consume();
  2592. continue;
  2593. }
  2594. break;
  2595. }
  2596. if (!for_loop_variable_declaration)
  2597. consume_or_insert_semicolon();
  2598. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  2599. return declaration;
  2600. }
  2601. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  2602. {
  2603. auto rule_start = push_start();
  2604. consume(TokenType::Throw);
  2605. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  2606. if (m_state.current_token.trivia_contains_line_terminator()) {
  2607. syntax_error("No line break is allowed between 'throw' and its expression");
  2608. 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() }));
  2609. }
  2610. auto expression = parse_expression(0);
  2611. consume_or_insert_semicolon();
  2612. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2613. }
  2614. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  2615. {
  2616. auto rule_start = push_start();
  2617. consume(TokenType::Break);
  2618. FlyString target_label;
  2619. if (match(TokenType::Semicolon)) {
  2620. consume();
  2621. } else {
  2622. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2623. target_label = consume().value();
  2624. auto label = m_state.labels_in_scope.find(target_label);
  2625. if (label == m_state.labels_in_scope.end())
  2626. syntax_error(String::formatted("Label '{}' not found", target_label));
  2627. }
  2628. consume_or_insert_semicolon();
  2629. }
  2630. if (target_label.is_null() && !m_state.in_break_context)
  2631. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  2632. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2633. }
  2634. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  2635. {
  2636. auto rule_start = push_start();
  2637. if (!m_state.in_continue_context)
  2638. syntax_error("'continue' not allow outside of a loop");
  2639. consume(TokenType::Continue);
  2640. FlyString target_label;
  2641. if (match(TokenType::Semicolon)) {
  2642. consume();
  2643. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2644. }
  2645. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2646. auto label_position = position();
  2647. target_label = consume().value();
  2648. auto label = m_state.labels_in_scope.find(target_label);
  2649. if (label == m_state.labels_in_scope.end())
  2650. syntax_error(String::formatted("Label '{}' not found or invalid", target_label));
  2651. else
  2652. label->value = label_position;
  2653. }
  2654. consume_or_insert_semicolon();
  2655. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2656. }
  2657. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test, ForbiddenTokens forbidden)
  2658. {
  2659. auto rule_start = push_start();
  2660. consume(TokenType::QuestionMark);
  2661. auto consequent = parse_expression(2);
  2662. consume(TokenType::Colon);
  2663. auto alternate = parse_expression(2, Associativity::Right, forbidden);
  2664. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  2665. }
  2666. NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expression> base)
  2667. {
  2668. auto rule_start = push_start();
  2669. Vector<OptionalChain::Reference> chain;
  2670. do {
  2671. if (match(TokenType::QuestionMarkPeriod)) {
  2672. consume(TokenType::QuestionMarkPeriod);
  2673. switch (m_state.current_token.type()) {
  2674. case TokenType::ParenOpen:
  2675. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::Optional });
  2676. break;
  2677. case TokenType::BracketOpen:
  2678. consume();
  2679. chain.append(OptionalChain::ComputedReference { parse_expression(0), OptionalChain::Mode::Optional });
  2680. consume(TokenType::BracketClose);
  2681. break;
  2682. case TokenType::PrivateIdentifier: {
  2683. if (!is_private_identifier_valid())
  2684. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  2685. auto start = position();
  2686. auto private_identifier = consume();
  2687. chain.append(OptionalChain::PrivateMemberReference {
  2688. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2689. OptionalChain::Mode::Optional });
  2690. break;
  2691. }
  2692. case TokenType::TemplateLiteralStart:
  2693. // 13.3.1.1 - Static Semantics: Early Errors
  2694. // OptionalChain :
  2695. // ?. TemplateLiteral
  2696. // OptionalChain TemplateLiteral
  2697. // This is a hard error.
  2698. syntax_error("Invalid tagged template literal after ?.", position());
  2699. break;
  2700. default:
  2701. if (match_identifier_name()) {
  2702. auto start = position();
  2703. auto identifier = consume();
  2704. chain.append(OptionalChain::MemberReference {
  2705. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()),
  2706. OptionalChain::Mode::Optional,
  2707. });
  2708. } else {
  2709. syntax_error("Invalid optional chain reference after ?.", position());
  2710. }
  2711. break;
  2712. }
  2713. } else if (match(TokenType::ParenOpen)) {
  2714. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::NotOptional });
  2715. } else if (match(TokenType::Period)) {
  2716. consume();
  2717. if (match(TokenType::PrivateIdentifier)) {
  2718. auto start = position();
  2719. auto private_identifier = consume();
  2720. chain.append(OptionalChain::PrivateMemberReference {
  2721. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2722. OptionalChain::Mode::NotOptional,
  2723. });
  2724. } else if (match_identifier_name()) {
  2725. auto start = position();
  2726. auto identifier = consume();
  2727. chain.append(OptionalChain::MemberReference {
  2728. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()),
  2729. OptionalChain::Mode::NotOptional,
  2730. });
  2731. } else {
  2732. expected("an identifier");
  2733. break;
  2734. }
  2735. } else if (match(TokenType::TemplateLiteralStart)) {
  2736. // 13.3.1.1 - Static Semantics: Early Errors
  2737. // OptionalChain :
  2738. // ?. TemplateLiteral
  2739. // OptionalChain TemplateLiteral
  2740. syntax_error("Invalid tagged template literal after optional chain", position());
  2741. break;
  2742. } else if (match(TokenType::BracketOpen)) {
  2743. consume();
  2744. chain.append(OptionalChain::ComputedReference { parse_expression(2), OptionalChain::Mode::NotOptional });
  2745. consume(TokenType::BracketClose);
  2746. } else {
  2747. break;
  2748. }
  2749. } while (!done());
  2750. return create_ast_node<OptionalChain>(
  2751. { m_state.current_token.filename(), rule_start.position(), position() },
  2752. move(base),
  2753. move(chain));
  2754. }
  2755. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  2756. {
  2757. auto rule_start = push_start();
  2758. consume(TokenType::Try);
  2759. auto block = parse_block_statement();
  2760. RefPtr<CatchClause> handler;
  2761. if (match(TokenType::Catch))
  2762. handler = parse_catch_clause();
  2763. RefPtr<BlockStatement> finalizer;
  2764. if (match(TokenType::Finally)) {
  2765. consume();
  2766. finalizer = parse_block_statement();
  2767. }
  2768. if (!handler && !finalizer)
  2769. syntax_error("try statement must have a 'catch' or 'finally' clause");
  2770. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  2771. }
  2772. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  2773. {
  2774. auto rule_start = push_start();
  2775. consume(TokenType::Do);
  2776. auto body = [&]() -> NonnullRefPtr<Statement> {
  2777. TemporaryChange break_change(m_state.in_break_context, true);
  2778. TemporaryChange continue_change(m_state.in_continue_context, true);
  2779. return parse_statement();
  2780. }();
  2781. consume(TokenType::While);
  2782. consume(TokenType::ParenOpen);
  2783. auto test = parse_expression(0);
  2784. consume(TokenType::ParenClose);
  2785. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  2786. if (match(TokenType::Semicolon))
  2787. consume();
  2788. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2789. }
  2790. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  2791. {
  2792. auto rule_start = push_start();
  2793. consume(TokenType::While);
  2794. consume(TokenType::ParenOpen);
  2795. auto test = parse_expression(0);
  2796. consume(TokenType::ParenClose);
  2797. TemporaryChange break_change(m_state.in_break_context, true);
  2798. TemporaryChange continue_change(m_state.in_continue_context, true);
  2799. auto body = parse_statement();
  2800. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2801. }
  2802. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  2803. {
  2804. auto rule_start = push_start();
  2805. consume(TokenType::Switch);
  2806. consume(TokenType::ParenOpen);
  2807. auto determinant = parse_expression(0);
  2808. consume(TokenType::ParenClose);
  2809. consume(TokenType::CurlyOpen);
  2810. NonnullRefPtrVector<SwitchCase> cases;
  2811. auto switch_statement = create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant));
  2812. ScopePusher switch_scope = ScopePusher::block_scope(*this, switch_statement);
  2813. auto has_default = false;
  2814. while (match(TokenType::Case) || match(TokenType::Default)) {
  2815. if (match(TokenType::Default)) {
  2816. if (has_default)
  2817. syntax_error("Multiple 'default' clauses in switch statement");
  2818. has_default = true;
  2819. }
  2820. switch_statement->add_case(parse_switch_case());
  2821. }
  2822. consume(TokenType::CurlyClose);
  2823. return switch_statement;
  2824. }
  2825. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  2826. {
  2827. auto rule_start = push_start();
  2828. consume(TokenType::With);
  2829. consume(TokenType::ParenOpen);
  2830. auto object = parse_expression(0);
  2831. consume(TokenType::ParenClose);
  2832. auto body = parse_statement();
  2833. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  2834. }
  2835. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  2836. {
  2837. auto rule_start = push_start();
  2838. RefPtr<Expression> test;
  2839. if (consume().type() == TokenType::Case) {
  2840. test = parse_expression(0);
  2841. }
  2842. consume(TokenType::Colon);
  2843. NonnullRefPtrVector<Statement> consequent;
  2844. TemporaryChange break_change(m_state.in_break_context, true);
  2845. auto switch_case = create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test));
  2846. parse_statement_list(switch_case);
  2847. return switch_case;
  2848. }
  2849. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  2850. {
  2851. auto rule_start = push_start();
  2852. consume(TokenType::Catch);
  2853. FlyString parameter;
  2854. RefPtr<BindingPattern> pattern_parameter;
  2855. auto should_expect_parameter = false;
  2856. if (match(TokenType::ParenOpen)) {
  2857. should_expect_parameter = true;
  2858. consume();
  2859. if (match_identifier_name()
  2860. && (!match(TokenType::Yield) || !m_state.in_generator_function_context)
  2861. && (!match(TokenType::Async) || !m_state.await_expression_is_valid)
  2862. && (!match(TokenType::Await) || !m_state.in_class_static_init_block))
  2863. parameter = consume().value();
  2864. else
  2865. pattern_parameter = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No);
  2866. consume(TokenType::ParenClose);
  2867. }
  2868. if (should_expect_parameter && parameter.is_empty() && !pattern_parameter)
  2869. expected("an identifier or a binding pattern");
  2870. HashTable<FlyString> bound_names;
  2871. if (pattern_parameter) {
  2872. pattern_parameter->for_each_bound_name(
  2873. [&](auto& name) {
  2874. check_identifier_name_for_assignment_validity(name);
  2875. bound_names.set(name);
  2876. });
  2877. }
  2878. if (!parameter.is_empty()) {
  2879. check_identifier_name_for_assignment_validity(parameter);
  2880. bound_names.set(parameter);
  2881. }
  2882. ScopePusher catch_scope = ScopePusher::catch_scope(*this, pattern_parameter, parameter);
  2883. auto body = parse_block_statement();
  2884. body->for_each_lexically_declared_name([&](auto const& name) {
  2885. if (bound_names.contains(name))
  2886. syntax_error(String::formatted("Identifier '{}' already declared as catch parameter", name));
  2887. });
  2888. if (pattern_parameter) {
  2889. return create_ast_node<CatchClause>(
  2890. { m_state.current_token.filename(), rule_start.position(), position() },
  2891. pattern_parameter.release_nonnull(),
  2892. move(body));
  2893. }
  2894. return create_ast_node<CatchClause>(
  2895. { m_state.current_token.filename(), rule_start.position(), position() },
  2896. move(parameter),
  2897. move(body));
  2898. }
  2899. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  2900. {
  2901. auto rule_start = push_start();
  2902. auto parse_function_declaration_as_block_statement = [&] {
  2903. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  2904. // This production only applies when parsing non-strict code. Source text matched
  2905. // by this production is processed as if each matching occurrence of
  2906. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  2907. // of a BlockStatement occupying that position in the source text.
  2908. // The semantics of such a synthetic BlockStatement includes the web legacy
  2909. // compatibility semantics specified in B.3.2.
  2910. VERIFY(match(TokenType::Function));
  2911. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2912. ScopePusher block_scope = ScopePusher::block_scope(*this, *block);
  2913. auto declaration = parse_declaration();
  2914. VERIFY(m_state.current_scope_pusher);
  2915. block_scope.add_declaration(declaration);
  2916. VERIFY(is<FunctionDeclaration>(*declaration));
  2917. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  2918. if (function_declaration.kind() == FunctionKind::Generator)
  2919. syntax_error("Generator functions can only be declared in top-level or within a block");
  2920. if (function_declaration.kind() == FunctionKind::Async)
  2921. syntax_error("Async functions can only be declared in top-level or within a block");
  2922. block->append(move(declaration));
  2923. return block;
  2924. };
  2925. consume(TokenType::If);
  2926. consume(TokenType::ParenOpen);
  2927. auto predicate = parse_expression(0);
  2928. consume(TokenType::ParenClose);
  2929. RefPtr<Statement> consequent;
  2930. if (!m_state.strict_mode && match(TokenType::Function))
  2931. consequent = parse_function_declaration_as_block_statement();
  2932. else
  2933. consequent = parse_statement();
  2934. RefPtr<Statement> alternate;
  2935. if (match(TokenType::Else)) {
  2936. consume();
  2937. if (!m_state.strict_mode && match(TokenType::Function))
  2938. alternate = parse_function_declaration_as_block_statement();
  2939. else
  2940. alternate = parse_statement();
  2941. }
  2942. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  2943. }
  2944. NonnullRefPtr<Statement> Parser::parse_for_statement()
  2945. {
  2946. auto rule_start = push_start();
  2947. auto is_await_loop = IsForAwaitLoop::No;
  2948. auto match_of = [&](Token const& token) {
  2949. return token.type() == TokenType::Identifier && token.original_value() == "of"sv;
  2950. };
  2951. auto match_for_in_of = [&]() {
  2952. bool is_of = match_of(m_state.current_token);
  2953. if (is_await_loop == IsForAwaitLoop::Yes) {
  2954. if (!is_of)
  2955. syntax_error("for await loop is only valid with 'of'");
  2956. else if (!m_state.await_expression_is_valid)
  2957. syntax_error("for await loop is only valid in async function or generator");
  2958. return true;
  2959. }
  2960. return match(TokenType::In) || is_of;
  2961. };
  2962. consume(TokenType::For);
  2963. if (match(TokenType::Await)) {
  2964. consume();
  2965. if (!m_state.await_expression_is_valid)
  2966. syntax_error("for-await-of is only allowed in async function context");
  2967. is_await_loop = IsForAwaitLoop::Yes;
  2968. }
  2969. consume(TokenType::ParenOpen);
  2970. Optional<ScopePusher> scope_pusher;
  2971. RefPtr<ASTNode> init;
  2972. if (!match(TokenType::Semicolon)) {
  2973. if (match_variable_declaration()) {
  2974. auto declaration = parse_variable_declaration(true);
  2975. if (declaration->declaration_kind() == DeclarationKind::Var) {
  2976. m_state.current_scope_pusher->add_declaration(declaration);
  2977. } else {
  2978. // This does not follow the normal declaration structure so we need additional checks.
  2979. HashTable<FlyString> bound_names;
  2980. declaration->for_each_bound_name([&](auto const& name) {
  2981. if (bound_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  2982. syntax_error(String::formatted("Identifier '{}' already declared in for loop initializer", name), declaration->source_range().start);
  2983. });
  2984. }
  2985. init = move(declaration);
  2986. if (match_for_in_of())
  2987. return parse_for_in_of_statement(*init, is_await_loop);
  2988. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  2989. for (auto& variable : static_cast<VariableDeclaration&>(*init).declarations()) {
  2990. if (!variable.init())
  2991. syntax_error("Missing initializer in 'const' variable declaration");
  2992. }
  2993. }
  2994. } else if (match_expression()) {
  2995. auto lookahead_token = next_token();
  2996. bool starts_with_async_of = match(TokenType::Async) && match_of(lookahead_token);
  2997. init = parse_expression(0, Associativity::Right, { TokenType::In });
  2998. if (match_for_in_of()) {
  2999. if (is_await_loop != IsForAwaitLoop::Yes
  3000. && starts_with_async_of && match_of(m_state.current_token))
  3001. syntax_error("for-of loop may not start with async of");
  3002. return parse_for_in_of_statement(*init, is_await_loop);
  3003. }
  3004. } else {
  3005. syntax_error("Unexpected token in for loop");
  3006. }
  3007. }
  3008. consume(TokenType::Semicolon);
  3009. RefPtr<Expression> test;
  3010. if (!match(TokenType::Semicolon))
  3011. test = parse_expression(0);
  3012. consume(TokenType::Semicolon);
  3013. RefPtr<Expression> update;
  3014. if (!match(TokenType::ParenClose))
  3015. update = parse_expression(0);
  3016. consume(TokenType::ParenClose);
  3017. TemporaryChange break_change(m_state.in_break_context, true);
  3018. TemporaryChange continue_change(m_state.in_continue_context, true);
  3019. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, init);
  3020. auto body = parse_statement();
  3021. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  3022. }
  3023. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_for_await_loop)
  3024. {
  3025. Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> for_declaration = lhs;
  3026. auto rule_start = push_start();
  3027. auto has_annexB_for_in_init_extension = false;
  3028. if (is<VariableDeclaration>(*lhs)) {
  3029. auto& declaration = static_cast<VariableDeclaration&>(*lhs);
  3030. if (declaration.declarations().size() > 1) {
  3031. syntax_error("Multiple declarations not allowed in for..in/of");
  3032. } else if (declaration.declarations().size() < 1) {
  3033. syntax_error("Need exactly one variable declaration in for..in/of");
  3034. } else {
  3035. // AnnexB extension B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  3036. auto& variable = declaration.declarations().first();
  3037. if (variable.init()) {
  3038. if (m_state.strict_mode || declaration.declaration_kind() != DeclarationKind::Var || !variable.target().has<NonnullRefPtr<Identifier>>())
  3039. syntax_error("Variable initializer not allowed in for..in/of");
  3040. else
  3041. has_annexB_for_in_init_extension = true;
  3042. }
  3043. }
  3044. } else if (!lhs->is_identifier() && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  3045. bool valid = false;
  3046. if (is<ObjectExpression>(*lhs) || is<ArrayExpression>(*lhs)) {
  3047. auto synthesized_binding_pattern = synthesize_binding_pattern(static_cast<Expression const&>(*lhs));
  3048. if (synthesized_binding_pattern) {
  3049. for_declaration = synthesized_binding_pattern.release_nonnull();
  3050. valid = true;
  3051. }
  3052. }
  3053. if (!valid)
  3054. syntax_error(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()));
  3055. }
  3056. auto in_or_of = consume();
  3057. auto is_in = in_or_of.type() == TokenType::In;
  3058. if (!is_in) {
  3059. if (is<MemberExpression>(*lhs)) {
  3060. auto& member = static_cast<MemberExpression const&>(*lhs);
  3061. if (member.object().is_identifier() && static_cast<Identifier const&>(member.object()).string() == "let"sv)
  3062. syntax_error("For of statement may not start with let.");
  3063. }
  3064. if (has_annexB_for_in_init_extension)
  3065. syntax_error("Variable initializer not allowed in for..of", rule_start.position());
  3066. }
  3067. auto rhs = parse_expression(is_in ? 0 : 2);
  3068. consume(TokenType::ParenClose);
  3069. TemporaryChange break_change(m_state.in_break_context, true);
  3070. TemporaryChange continue_change(m_state.in_continue_context, true);
  3071. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, lhs);
  3072. auto body = parse_statement();
  3073. if (is_in)
  3074. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3075. if (is_for_await_loop == IsForAwaitLoop::Yes)
  3076. return create_ast_node<ForAwaitOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3077. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3078. }
  3079. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  3080. {
  3081. auto rule_start = push_start();
  3082. consume(TokenType::Debugger);
  3083. consume_or_insert_semicolon();
  3084. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  3085. }
  3086. bool Parser::match(TokenType type) const
  3087. {
  3088. return m_state.current_token.type() == type;
  3089. }
  3090. bool Parser::match_expression() const
  3091. {
  3092. auto type = m_state.current_token.type();
  3093. if (type == TokenType::Import) {
  3094. auto lookahead_token = next_token();
  3095. return lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen;
  3096. }
  3097. return type == TokenType::BoolLiteral
  3098. || type == TokenType::NumericLiteral
  3099. || type == TokenType::BigIntLiteral
  3100. || type == TokenType::StringLiteral
  3101. || type == TokenType::TemplateLiteralStart
  3102. || type == TokenType::NullLiteral
  3103. || match_identifier()
  3104. || type == TokenType::PrivateIdentifier
  3105. || type == TokenType::Await
  3106. || type == TokenType::New
  3107. || type == TokenType::Class
  3108. || type == TokenType::CurlyOpen
  3109. || type == TokenType::BracketOpen
  3110. || type == TokenType::ParenOpen
  3111. || type == TokenType::Function
  3112. || type == TokenType::Async
  3113. || type == TokenType::This
  3114. || type == TokenType::Super
  3115. || type == TokenType::RegexLiteral
  3116. || type == TokenType::Slash // Wrongly recognized regex by lexer
  3117. || type == TokenType::SlashEquals // Wrongly recognized regex by lexer (/=a/ is a valid regex)
  3118. || type == TokenType::Yield
  3119. || match_unary_prefixed_expression();
  3120. }
  3121. bool Parser::match_unary_prefixed_expression() const
  3122. {
  3123. auto type = m_state.current_token.type();
  3124. return type == TokenType::PlusPlus
  3125. || type == TokenType::MinusMinus
  3126. || type == TokenType::ExclamationMark
  3127. || type == TokenType::Tilde
  3128. || type == TokenType::Plus
  3129. || type == TokenType::Minus
  3130. || type == TokenType::Typeof
  3131. || type == TokenType::Void
  3132. || type == TokenType::Delete;
  3133. }
  3134. bool Parser::match_secondary_expression(ForbiddenTokens forbidden) const
  3135. {
  3136. auto type = m_state.current_token.type();
  3137. if (!forbidden.allows(type))
  3138. return false;
  3139. return type == TokenType::Plus
  3140. || type == TokenType::PlusEquals
  3141. || type == TokenType::Minus
  3142. || type == TokenType::MinusEquals
  3143. || type == TokenType::Asterisk
  3144. || type == TokenType::AsteriskEquals
  3145. || type == TokenType::Slash
  3146. || type == TokenType::SlashEquals
  3147. || type == TokenType::Percent
  3148. || type == TokenType::PercentEquals
  3149. || type == TokenType::DoubleAsterisk
  3150. || type == TokenType::DoubleAsteriskEquals
  3151. || type == TokenType::Equals
  3152. || type == TokenType::EqualsEqualsEquals
  3153. || type == TokenType::ExclamationMarkEqualsEquals
  3154. || type == TokenType::EqualsEquals
  3155. || type == TokenType::ExclamationMarkEquals
  3156. || type == TokenType::GreaterThan
  3157. || type == TokenType::GreaterThanEquals
  3158. || type == TokenType::LessThan
  3159. || type == TokenType::LessThanEquals
  3160. || type == TokenType::ParenOpen
  3161. || type == TokenType::Period
  3162. || type == TokenType::BracketOpen
  3163. || (type == TokenType::PlusPlus && !m_state.current_token.trivia_contains_line_terminator())
  3164. || (type == TokenType::MinusMinus && !m_state.current_token.trivia_contains_line_terminator())
  3165. || type == TokenType::In
  3166. || type == TokenType::Instanceof
  3167. || type == TokenType::QuestionMark
  3168. || type == TokenType::Ampersand
  3169. || type == TokenType::AmpersandEquals
  3170. || type == TokenType::Pipe
  3171. || type == TokenType::PipeEquals
  3172. || type == TokenType::Caret
  3173. || type == TokenType::CaretEquals
  3174. || type == TokenType::ShiftLeft
  3175. || type == TokenType::ShiftLeftEquals
  3176. || type == TokenType::ShiftRight
  3177. || type == TokenType::ShiftRightEquals
  3178. || type == TokenType::UnsignedShiftRight
  3179. || type == TokenType::UnsignedShiftRightEquals
  3180. || type == TokenType::DoubleAmpersand
  3181. || type == TokenType::DoubleAmpersandEquals
  3182. || type == TokenType::DoublePipe
  3183. || type == TokenType::DoublePipeEquals
  3184. || type == TokenType::DoubleQuestionMark
  3185. || type == TokenType::DoubleQuestionMarkEquals
  3186. || type == TokenType::QuestionMarkPeriod;
  3187. }
  3188. bool Parser::match_statement() const
  3189. {
  3190. auto type = m_state.current_token.type();
  3191. return match_expression()
  3192. || type == TokenType::Return
  3193. || type == TokenType::Yield
  3194. || type == TokenType::Do
  3195. || type == TokenType::If
  3196. || type == TokenType::Throw
  3197. || type == TokenType::Try
  3198. || type == TokenType::While
  3199. || type == TokenType::With
  3200. || type == TokenType::For
  3201. || type == TokenType::CurlyOpen
  3202. || type == TokenType::Switch
  3203. || type == TokenType::Break
  3204. || type == TokenType::Continue
  3205. || type == TokenType::Var
  3206. || type == TokenType::Debugger
  3207. || type == TokenType::Semicolon;
  3208. }
  3209. bool Parser::match_export_or_import() const
  3210. {
  3211. auto type = m_state.current_token.type();
  3212. return type == TokenType::Export
  3213. || type == TokenType::Import;
  3214. }
  3215. bool Parser::match_declaration() const
  3216. {
  3217. auto type = m_state.current_token.type();
  3218. if (type == TokenType::Let && !m_state.strict_mode) {
  3219. return try_match_let_declaration();
  3220. }
  3221. if (type == TokenType::Async) {
  3222. auto lookahead_token = next_token();
  3223. return lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator();
  3224. }
  3225. return type == TokenType::Function
  3226. || type == TokenType::Class
  3227. || type == TokenType::Const
  3228. || type == TokenType::Let;
  3229. }
  3230. Token Parser::next_token(size_t steps) const
  3231. {
  3232. Lexer lookahead_lexer = m_state.lexer;
  3233. Token lookahead_token;
  3234. while (steps > 0) {
  3235. lookahead_token = lookahead_lexer.next();
  3236. steps--;
  3237. }
  3238. return lookahead_token;
  3239. }
  3240. bool Parser::try_match_let_declaration() const
  3241. {
  3242. VERIFY(m_state.current_token.type() == TokenType::Let);
  3243. auto token_after = next_token();
  3244. if (token_after.is_identifier_name() && token_after.value() != "in"sv)
  3245. return true;
  3246. if (token_after.type() == TokenType::CurlyOpen || token_after.type() == TokenType::BracketOpen)
  3247. return true;
  3248. return false;
  3249. }
  3250. bool Parser::match_variable_declaration() const
  3251. {
  3252. auto type = m_state.current_token.type();
  3253. if (type == TokenType::Let && !m_state.strict_mode) {
  3254. return try_match_let_declaration();
  3255. }
  3256. return type == TokenType::Var
  3257. || type == TokenType::Let
  3258. || type == TokenType::Const;
  3259. }
  3260. bool Parser::match_identifier() const
  3261. {
  3262. if (m_state.current_token.type() == TokenType::EscapedKeyword) {
  3263. if (m_state.current_token.value() == "let"sv)
  3264. return !m_state.strict_mode;
  3265. if (m_state.current_token.value() == "yield"sv)
  3266. return !m_state.strict_mode && !m_state.in_generator_function_context;
  3267. if (m_state.current_token.value() == "await"sv)
  3268. return m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block;
  3269. return true;
  3270. }
  3271. return m_state.current_token.type() == TokenType::Identifier
  3272. || m_state.current_token.type() == TokenType::Async
  3273. || (m_state.current_token.type() == TokenType::Let && !m_state.strict_mode)
  3274. || (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)
  3275. || (m_state.current_token.type() == TokenType::Yield && !m_state.in_generator_function_context && !m_state.strict_mode); // See note in Parser::parse_identifier().
  3276. }
  3277. bool Parser::match_identifier_name() const
  3278. {
  3279. return m_state.current_token.is_identifier_name();
  3280. }
  3281. bool Parser::match_property_key() const
  3282. {
  3283. auto type = m_state.current_token.type();
  3284. return match_identifier_name()
  3285. || type == TokenType::BracketOpen
  3286. || type == TokenType::StringLiteral
  3287. || type == TokenType::NumericLiteral
  3288. || type == TokenType::BigIntLiteral;
  3289. }
  3290. bool Parser::done() const
  3291. {
  3292. return match(TokenType::Eof);
  3293. }
  3294. Token Parser::consume()
  3295. {
  3296. auto old_token = m_state.current_token;
  3297. m_state.current_token = m_state.lexer.next();
  3298. // NOTE: This is the bare minimum needed to decide whether we might need an arguments object
  3299. // in a function expression or declaration. ("might" because the AST implements some further
  3300. // conditions from the spec that rule out the need for allocating one)
  3301. if (old_token.type() == TokenType::Identifier && old_token.value().is_one_of("arguments"sv, "eval"sv))
  3302. m_state.function_might_need_arguments_object = true;
  3303. return old_token;
  3304. }
  3305. void Parser::consume_or_insert_semicolon()
  3306. {
  3307. // Semicolon was found and will be consumed
  3308. if (match(TokenType::Semicolon)) {
  3309. consume();
  3310. return;
  3311. }
  3312. // Insert semicolon if...
  3313. // ...token is preceded by one or more newlines
  3314. if (m_state.current_token.trivia_contains_line_terminator())
  3315. return;
  3316. // ...token is a closing curly brace
  3317. if (match(TokenType::CurlyClose))
  3318. return;
  3319. // ...token is eof
  3320. if (match(TokenType::Eof))
  3321. return;
  3322. // No rule for semicolon insertion applies -> syntax error
  3323. expected("Semicolon");
  3324. }
  3325. Token Parser::consume_identifier()
  3326. {
  3327. if (match(TokenType::Identifier))
  3328. return consume(TokenType::Identifier);
  3329. if (match(TokenType::EscapedKeyword))
  3330. return consume(TokenType::EscapedKeyword);
  3331. // Note that 'let' is not a reserved keyword, but our lexer considers it such
  3332. // As it's pretty nice to have that (for syntax highlighting and such), we'll
  3333. // special-case it here instead.
  3334. if (match(TokenType::Let)) {
  3335. if (m_state.strict_mode)
  3336. syntax_error("'let' is not allowed as an identifier in strict mode");
  3337. return consume();
  3338. }
  3339. if (match(TokenType::Yield)) {
  3340. if (m_state.strict_mode || m_state.in_generator_function_context)
  3341. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  3342. return consume();
  3343. }
  3344. if (match(TokenType::Await)) {
  3345. if (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)
  3346. syntax_error("Identifier must not be a reserved word in modules ('await')");
  3347. return consume();
  3348. }
  3349. if (match(TokenType::Async))
  3350. return consume();
  3351. expected("Identifier");
  3352. return consume();
  3353. }
  3354. // https://tc39.es/ecma262/#prod-IdentifierReference
  3355. Token Parser::consume_identifier_reference()
  3356. {
  3357. if (match(TokenType::Identifier))
  3358. return consume(TokenType::Identifier);
  3359. if (match(TokenType::EscapedKeyword)) {
  3360. auto name = m_state.current_token.value();
  3361. if (m_state.strict_mode && (name == "let"sv || name == "yield"sv))
  3362. syntax_error(String::formatted("'{}' is not allowed as an identifier in strict mode", name));
  3363. if (m_program_type == Program::Type::Module && name == "await"sv)
  3364. syntax_error("'await' is not allowed as an identifier in module");
  3365. return consume();
  3366. }
  3367. // See note in Parser::parse_identifier().
  3368. if (match(TokenType::Let)) {
  3369. if (m_state.strict_mode)
  3370. syntax_error("'let' is not allowed as an identifier in strict mode");
  3371. return consume();
  3372. }
  3373. if (match(TokenType::Yield)) {
  3374. if (m_state.strict_mode)
  3375. syntax_error("Identifier reference may not be 'yield' in strict mode");
  3376. return consume();
  3377. }
  3378. if (match(TokenType::Await)) {
  3379. if (m_program_type == Program::Type::Module)
  3380. syntax_error("'await' is not allowed as an identifier in module");
  3381. return consume();
  3382. }
  3383. if (match(TokenType::Async))
  3384. return consume();
  3385. expected(Token::name(TokenType::Identifier));
  3386. return consume();
  3387. }
  3388. Token Parser::consume(TokenType expected_type)
  3389. {
  3390. if (!match(expected_type)) {
  3391. expected(Token::name(expected_type));
  3392. }
  3393. auto token = consume();
  3394. if (expected_type == TokenType::Identifier) {
  3395. if (m_state.strict_mode && is_strict_reserved_word(token.value()))
  3396. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()));
  3397. }
  3398. return token;
  3399. }
  3400. Token Parser::consume_and_validate_numeric_literal()
  3401. {
  3402. auto is_unprefixed_octal_number = [](StringView value) {
  3403. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  3404. };
  3405. auto literal_start = position();
  3406. auto token = consume(TokenType::NumericLiteral);
  3407. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  3408. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  3409. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  3410. syntax_error("Numeric literal must not be immediately followed by identifier");
  3411. return token;
  3412. }
  3413. void Parser::expected(char const* what)
  3414. {
  3415. auto message = m_state.current_token.message();
  3416. if (message.is_empty())
  3417. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  3418. syntax_error(message);
  3419. }
  3420. Position Parser::position() const
  3421. {
  3422. return {
  3423. m_state.current_token.line_number(),
  3424. m_state.current_token.line_column(),
  3425. m_state.current_token.offset(),
  3426. };
  3427. }
  3428. bool Parser::try_parse_arrow_function_expression_failed_at_position(Position const& position) const
  3429. {
  3430. auto it = m_token_memoizations.find(position);
  3431. if (it == m_token_memoizations.end())
  3432. return false;
  3433. return (*it).value.try_parse_arrow_function_expression_failed;
  3434. }
  3435. void Parser::set_try_parse_arrow_function_expression_failed_at_position(Position const& position, bool failed)
  3436. {
  3437. m_token_memoizations.set(position, { failed });
  3438. }
  3439. void Parser::syntax_error(String const& message, Optional<Position> position)
  3440. {
  3441. if (!position.has_value())
  3442. position = this->position();
  3443. m_state.errors.append({ message, position });
  3444. }
  3445. void Parser::save_state()
  3446. {
  3447. m_saved_state.append(m_state);
  3448. }
  3449. void Parser::load_state()
  3450. {
  3451. VERIFY(!m_saved_state.is_empty());
  3452. m_state = m_saved_state.take_last();
  3453. }
  3454. void Parser::discard_saved_state()
  3455. {
  3456. m_saved_state.take_last();
  3457. }
  3458. void Parser::check_identifier_name_for_assignment_validity(FlyString const& name, bool force_strict)
  3459. {
  3460. // FIXME: this is now called from multiple places maybe the error message should be dynamic?
  3461. if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) {
  3462. syntax_error("Binding pattern target may not be a reserved word");
  3463. } else if (m_state.strict_mode || force_strict) {
  3464. if (name.is_one_of("arguments"sv, "eval"sv))
  3465. syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");
  3466. else if (is_strict_reserved_word(name))
  3467. syntax_error(String::formatted("Binding pattern target may not be called '{}' in strict mode", name));
  3468. }
  3469. }
  3470. bool Parser::match_assert_clause() const
  3471. {
  3472. return !m_state.current_token.trivia_contains_line_terminator() && m_state.current_token.original_value() == "assert"sv;
  3473. }
  3474. FlyString Parser::consume_string_value()
  3475. {
  3476. VERIFY(match(TokenType::StringLiteral));
  3477. auto string_token = consume();
  3478. FlyString value = parse_string_literal(string_token, false)->value();
  3479. // This also checks IsStringWellFormedUnicode which makes sure there is no unpaired surrogate
  3480. // Surrogates are at least 3 bytes
  3481. if (value.length() < 3)
  3482. return value;
  3483. Utf8View view { value.view().substring_view(value.length() - 3) };
  3484. VERIFY(view.length() <= 3);
  3485. auto codepoint = *view.begin();
  3486. if (Utf16View::is_high_surrogate(codepoint)) {
  3487. syntax_error("StringValue ending with unpaired high surrogate");
  3488. VERIFY(view.length() == 1);
  3489. }
  3490. return value;
  3491. }
  3492. // AssertClause, https://tc39.es/proposal-import-assertions/#prod-AssertClause
  3493. ModuleRequest Parser::parse_module_request()
  3494. {
  3495. // Does not include the 'from' since that is not always required.
  3496. if (!match(TokenType::StringLiteral)) {
  3497. expected("ModuleSpecifier (string)");
  3498. return ModuleRequest { "!!invalid!!" };
  3499. }
  3500. ModuleRequest request { consume_string_value() };
  3501. if (!match_assert_clause())
  3502. return request;
  3503. VERIFY(m_state.current_token.original_value() == "assert"sv);
  3504. consume(TokenType::Identifier);
  3505. consume(TokenType::CurlyOpen);
  3506. while (!done() && !match(TokenType::CurlyClose)) {
  3507. String key;
  3508. if (match(TokenType::StringLiteral)) {
  3509. key = parse_string_literal(m_state.current_token)->value().to_string();
  3510. consume();
  3511. } else if (match_identifier_name()) {
  3512. key = consume().value();
  3513. } else {
  3514. expected("IdentifierName or StringValue as AssertionKey");
  3515. consume();
  3516. }
  3517. consume(TokenType::Colon);
  3518. if (match(TokenType::StringLiteral)) {
  3519. for (auto& entries : request.assertions) {
  3520. if (entries.key == key)
  3521. syntax_error(String::formatted("Duplicate assertion clauses with name: {}", key));
  3522. }
  3523. request.add_assertion(move(key), parse_string_literal(m_state.current_token)->value().to_string());
  3524. }
  3525. consume(TokenType::StringLiteral);
  3526. if (match(TokenType::Comma))
  3527. consume(TokenType::Comma);
  3528. else
  3529. break;
  3530. }
  3531. consume(TokenType::CurlyClose);
  3532. return request;
  3533. }
  3534. static FlyString default_string_value = "default";
  3535. NonnullRefPtr<ImportStatement> Parser::parse_import_statement(Program& program)
  3536. {
  3537. // We use the extended syntax which adds:
  3538. // ImportDeclaration:
  3539. // import ImportClause FromClause [no LineTerminator here] AssertClause;
  3540. // import ModuleSpecifier [no LineTerminator here] AssertClause;
  3541. // From: https://tc39.es/proposal-import-assertions/#prod-ImportDeclaration
  3542. auto rule_start = push_start();
  3543. if (program.type() != Program::Type::Module)
  3544. syntax_error("Cannot use import statement outside a module");
  3545. consume(TokenType::Import);
  3546. if (match(TokenType::StringLiteral)) {
  3547. // import ModuleSpecifier ;
  3548. auto module_request = parse_module_request();
  3549. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request));
  3550. }
  3551. auto match_imported_binding = [&] {
  3552. return match_identifier() || match(TokenType::Yield) || match(TokenType::Await);
  3553. };
  3554. auto match_as = [&] {
  3555. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3556. };
  3557. bool continue_parsing = true;
  3558. struct ImportWithLocation {
  3559. ImportStatement::ImportEntry entry;
  3560. Position position;
  3561. };
  3562. Vector<ImportWithLocation> entries_with_location;
  3563. // import ImportClause FromClause ;
  3564. // ImportClause :
  3565. // ImportedDefaultBinding
  3566. // NameSpaceImport
  3567. // NamedImports
  3568. // ImportedDefaultBinding , NameSpaceImport
  3569. // ImportedDefaultBinding , NamedImports
  3570. if (match_imported_binding()) {
  3571. // ImportedDefaultBinding : ImportedBinding
  3572. auto id_position = position();
  3573. auto bound_name = consume().value();
  3574. entries_with_location.append({ { default_string_value, bound_name }, id_position });
  3575. if (match(TokenType::Comma)) {
  3576. consume(TokenType::Comma);
  3577. } else {
  3578. continue_parsing = false;
  3579. }
  3580. }
  3581. if (!continue_parsing) {
  3582. // skip the rest
  3583. } else if (match(TokenType::Asterisk)) {
  3584. // NameSpaceImport : * as ImportedBinding
  3585. consume(TokenType::Asterisk);
  3586. if (!match_as())
  3587. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3588. consume(TokenType::Identifier);
  3589. if (match_imported_binding()) {
  3590. auto namespace_position = position();
  3591. auto namespace_name = consume().value();
  3592. entries_with_location.append({ ImportStatement::ImportEntry({}, namespace_name, true), namespace_position });
  3593. } else {
  3594. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3595. }
  3596. } else if (match(TokenType::CurlyOpen)) {
  3597. // NamedImports :
  3598. // { ImportSpecifier ,_opt } (repeated any amount of times)
  3599. consume(TokenType::CurlyOpen);
  3600. while (!done() && !match(TokenType::CurlyClose)) {
  3601. if (match_identifier_name()) {
  3602. // ImportSpecifier : ImportedBinding
  3603. auto require_as = !match_imported_binding();
  3604. auto name_position = position();
  3605. auto name = consume().flystring_value();
  3606. if (match_as()) {
  3607. consume(TokenType::Identifier);
  3608. auto alias_position = position();
  3609. auto alias = consume_identifier().flystring_value();
  3610. check_identifier_name_for_assignment_validity(alias);
  3611. entries_with_location.append({ { name, alias }, alias_position });
  3612. } else if (require_as) {
  3613. syntax_error(String::formatted("Unexpected reserved word '{}'", name));
  3614. } else {
  3615. check_identifier_name_for_assignment_validity(name);
  3616. entries_with_location.append({ { name, name }, name_position });
  3617. }
  3618. } else if (match(TokenType::StringLiteral)) {
  3619. // ImportSpecifier : ModuleExportName as ImportedBinding
  3620. auto name = consume_string_value();
  3621. if (!match_as())
  3622. expected("as");
  3623. consume(TokenType::Identifier);
  3624. auto alias_position = position();
  3625. auto alias = consume_identifier().flystring_value();
  3626. check_identifier_name_for_assignment_validity(alias);
  3627. entries_with_location.append({ { move(name), alias }, alias_position });
  3628. } else {
  3629. expected("identifier");
  3630. break;
  3631. }
  3632. if (!match(TokenType::Comma))
  3633. break;
  3634. consume(TokenType::Comma);
  3635. }
  3636. consume(TokenType::CurlyClose);
  3637. } else {
  3638. expected("import clauses");
  3639. }
  3640. auto from_statement = consume(TokenType::Identifier).original_value();
  3641. if (from_statement != "from"sv)
  3642. syntax_error(String::formatted("Expected 'from' got {}", from_statement));
  3643. auto module_request = parse_module_request();
  3644. Vector<ImportStatement::ImportEntry> entries;
  3645. entries.ensure_capacity(entries_with_location.size());
  3646. for (auto& entry : entries_with_location) {
  3647. for (auto& import_statement : program.imports()) {
  3648. if (import_statement.has_bound_name(entry.entry.local_name))
  3649. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3650. }
  3651. for (auto& new_entry : entries) {
  3652. if (new_entry.local_name == entry.entry.local_name)
  3653. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3654. }
  3655. entries.append(move(entry.entry));
  3656. }
  3657. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request), move(entries));
  3658. }
  3659. NonnullRefPtr<ExportStatement> Parser::parse_export_statement(Program& program)
  3660. {
  3661. using ExportEntry = ExportStatement::ExportEntry;
  3662. // We use the extended syntax which adds:
  3663. // ExportDeclaration:
  3664. // export ExportFromClause FromClause [no LineTerminator here] AssertClause ;
  3665. // From: https://tc39.es/proposal-import-assertions/#prod-ExportDeclaration
  3666. auto rule_start = push_start();
  3667. if (program.type() != Program::Type::Module)
  3668. syntax_error("Cannot use export statement outside a module");
  3669. auto match_as = [&] {
  3670. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3671. };
  3672. auto match_from = [&] {
  3673. return match(TokenType::Identifier) && m_state.current_token.original_value() == "from"sv;
  3674. };
  3675. auto match_default = [&] {
  3676. return match(TokenType::Default) && m_state.current_token.original_value() == "default"sv;
  3677. };
  3678. consume(TokenType::Export);
  3679. struct EntryAndLocation {
  3680. ExportEntry entry;
  3681. Position position;
  3682. };
  3683. Vector<EntryAndLocation> entries_with_location;
  3684. RefPtr<ASTNode> expression = {};
  3685. bool is_default = false;
  3686. ModuleRequest from_specifier;
  3687. if (match_default()) {
  3688. is_default = true;
  3689. auto default_position = position();
  3690. consume(TokenType::Default);
  3691. FlyString local_name;
  3692. auto lookahead_token = next_token();
  3693. // Note: For some reason the spec here has declaration which can have no name
  3694. // and the rest of the parser is just not setup for that. With these
  3695. // hacks below we get through most things but we should probably figure
  3696. // out a better solution. I have attempted to explain why/what these "hacks" do below.
  3697. // The summary is treat named declarations just as declarations and hack around unnamed
  3698. // declarations with expression see also SourceTextModule::initialize_environment.
  3699. // As far as I'm aware the only problem (which is a tricky one) is:
  3700. // `export default function() {}()`
  3701. // Since we parse this as an expression you are immediately allowed to call it
  3702. // which is incorrect and this should give a SyntaxError.
  3703. auto match_function_declaration = [&] {
  3704. // Hack part 1.
  3705. // Match a function declaration with a name, since we have async and generator
  3706. // and asyncgenerator variants this is quite complicated.
  3707. auto current_type = m_state.current_token.type();
  3708. Lexer lookahead_lexer = m_state.lexer;
  3709. lookahead_lexer.next();
  3710. if (current_type == TokenType::Function) {
  3711. if (lookahead_token.type() == TokenType::Asterisk)
  3712. return lookahead_lexer.next().type() != TokenType::ParenOpen; // function * <name>
  3713. else
  3714. return lookahead_token.type() != TokenType::ParenOpen; // function <name>
  3715. }
  3716. if (current_type == TokenType::Async) {
  3717. if (lookahead_token.type() != TokenType::Function)
  3718. return false;
  3719. if (lookahead_token.trivia_contains_line_terminator())
  3720. return false;
  3721. auto lookahead_two_token = lookahead_lexer.next();
  3722. if (lookahead_two_token.type() == TokenType::Asterisk)
  3723. return lookahead_lexer.next().type() != TokenType::ParenOpen; // async function * <name>
  3724. else
  3725. return lookahead_two_token.type() != TokenType::ParenOpen; // async function <name>
  3726. }
  3727. return false;
  3728. };
  3729. if (match_function_declaration()) {
  3730. auto function_declaration = parse_function_node<FunctionDeclaration>();
  3731. m_state.current_scope_pusher->add_declaration(function_declaration);
  3732. local_name = function_declaration->name();
  3733. expression = move(function_declaration);
  3734. } else if (match(TokenType::Class) && lookahead_token.type() != TokenType::CurlyOpen && lookahead_token.type() != TokenType::Extends) {
  3735. // Hack part 2.
  3736. // Attempt to detect classes with names only as those are declarations,
  3737. // this actually seems to cover all cases already.
  3738. auto class_expression = parse_class_declaration();
  3739. m_state.current_scope_pusher->add_declaration(class_expression);
  3740. local_name = class_expression->name();
  3741. expression = move(class_expression);
  3742. } else if (match_expression()) {
  3743. // Hack part 3.
  3744. // Even though the unnamed declarations look like expression we should
  3745. // not treat them as such and thus not consume a semicolon after them.
  3746. 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());
  3747. expression = parse_expression(2);
  3748. if (!special_case_declaration_without_name)
  3749. consume_or_insert_semicolon();
  3750. if (is<ClassExpression>(*expression)) {
  3751. auto const& class_expression = static_cast<ClassExpression&>(*expression);
  3752. if (class_expression.has_name())
  3753. local_name = class_expression.name();
  3754. }
  3755. } else {
  3756. expected("Declaration or assignment expression");
  3757. local_name = "!!invalid!!";
  3758. }
  3759. if (local_name.is_null()) {
  3760. local_name = ExportStatement::local_name_for_default;
  3761. }
  3762. entries_with_location.append({ ExportEntry::named_export(default_string_value, move(local_name)), default_position });
  3763. } else {
  3764. enum FromSpecifier {
  3765. NotAllowed,
  3766. Optional,
  3767. Required
  3768. } check_for_from { NotAllowed };
  3769. if (match(TokenType::Asterisk)) {
  3770. auto asterisk_position = position();
  3771. consume(TokenType::Asterisk);
  3772. if (match_as()) {
  3773. consume(TokenType::Identifier);
  3774. if (match_identifier_name()) {
  3775. auto namespace_position = position();
  3776. auto exported_name = consume().value();
  3777. entries_with_location.append({ ExportEntry::all_module_request(exported_name), namespace_position });
  3778. } else {
  3779. expected("identifier");
  3780. }
  3781. } else {
  3782. entries_with_location.append({ ExportEntry::all_but_default_entry(), asterisk_position });
  3783. }
  3784. check_for_from = Required;
  3785. } else if (match_declaration()) {
  3786. auto decl_position = position();
  3787. auto declaration = parse_declaration();
  3788. m_state.current_scope_pusher->add_declaration(declaration);
  3789. if (is<FunctionDeclaration>(*declaration)) {
  3790. auto& func = static_cast<FunctionDeclaration&>(*declaration);
  3791. entries_with_location.append({ ExportEntry::named_export(func.name(), func.name()), func.source_range().start });
  3792. } else if (is<ClassDeclaration>(*declaration)) {
  3793. auto& class_declaration = static_cast<ClassDeclaration&>(*declaration);
  3794. entries_with_location.append({ ExportEntry::named_export(class_declaration.name(), class_declaration.name()), class_declaration.source_range().start });
  3795. } else {
  3796. VERIFY(is<VariableDeclaration>(*declaration));
  3797. auto& variables = static_cast<VariableDeclaration&>(*declaration);
  3798. VERIFY(variables.is_lexical_declaration());
  3799. for (auto& decl : variables.declarations()) {
  3800. decl.target().visit(
  3801. [&](NonnullRefPtr<Identifier> const& identifier) {
  3802. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3803. },
  3804. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3805. binding->for_each_bound_name([&](auto& name) {
  3806. entries_with_location.append({ ExportEntry::named_export(name, name), decl_position });
  3807. });
  3808. });
  3809. }
  3810. }
  3811. expression = declaration;
  3812. } else if (match(TokenType::Var)) {
  3813. auto variable_position = position();
  3814. auto variable_declaration = parse_variable_declaration();
  3815. m_state.current_scope_pusher->add_declaration(variable_declaration);
  3816. for (auto& decl : variable_declaration->declarations()) {
  3817. decl.target().visit(
  3818. [&](NonnullRefPtr<Identifier> const& identifier) {
  3819. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3820. },
  3821. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3822. binding->for_each_bound_name([&](auto& name) {
  3823. entries_with_location.append({ ExportEntry::named_export(name, name), variable_position });
  3824. });
  3825. });
  3826. }
  3827. expression = variable_declaration;
  3828. } else if (match(TokenType::CurlyOpen)) {
  3829. consume(TokenType::CurlyOpen);
  3830. check_for_from = Optional;
  3831. auto parse_export_specifier = [&](bool lhs) -> FlyString {
  3832. if (match_identifier_name()) {
  3833. return consume().value();
  3834. }
  3835. if (match(TokenType::StringLiteral)) {
  3836. // It is a Syntax Error if ReferencedBindings of NamedExports contains any StringLiterals.
  3837. // Only for export { "a" as "b" }; // <-- no from
  3838. if (lhs)
  3839. check_for_from = Required;
  3840. return consume_string_value();
  3841. }
  3842. expected("ExportSpecifier (string or identifier)");
  3843. return {};
  3844. };
  3845. while (!done() && !match(TokenType::CurlyClose)) {
  3846. auto identifier_position = position();
  3847. auto identifier = parse_export_specifier(true);
  3848. if (match_as()) {
  3849. consume(TokenType::Identifier);
  3850. auto export_name = parse_export_specifier(false);
  3851. entries_with_location.append({ ExportEntry::named_export(move(export_name), move(identifier)), identifier_position });
  3852. } else {
  3853. entries_with_location.append({ ExportEntry::named_export(identifier, identifier), identifier_position });
  3854. }
  3855. if (!match(TokenType::Comma))
  3856. break;
  3857. consume(TokenType::Comma);
  3858. }
  3859. consume(TokenType::CurlyClose);
  3860. } else {
  3861. syntax_error("Unexpected token 'export'", rule_start.position());
  3862. }
  3863. if (check_for_from != NotAllowed && match_from()) {
  3864. consume(TokenType::Identifier);
  3865. from_specifier = parse_module_request();
  3866. } else if (check_for_from == Required) {
  3867. expected("from");
  3868. }
  3869. if (check_for_from != NotAllowed)
  3870. consume_or_insert_semicolon();
  3871. }
  3872. Vector<ExportStatement::ExportEntry> entries;
  3873. entries.ensure_capacity(entries_with_location.size());
  3874. for (auto& entry : entries_with_location) {
  3875. for (auto& export_statement : program.exports()) {
  3876. if (export_statement.has_export(entry.entry.export_name))
  3877. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3878. }
  3879. for (auto& new_entry : entries) {
  3880. if (new_entry.export_name == entry.entry.export_name)
  3881. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3882. }
  3883. entries.append(move(entry.entry));
  3884. }
  3885. return create_ast_node<ExportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(entries), is_default, move(from_specifier));
  3886. }
  3887. Parser::ForbiddenTokens::ForbiddenTokens(std::initializer_list<TokenType> const& forbidden)
  3888. {
  3889. forbid_tokens(forbidden);
  3890. }
  3891. void Parser::ForbiddenTokens::forbid_tokens(std::initializer_list<TokenType> const& forbidden)
  3892. {
  3893. for (auto token : forbidden) {
  3894. switch (token) {
  3895. case TokenType::In:
  3896. m_forbid_in_token = true;
  3897. break;
  3898. case TokenType::DoubleAmpersand:
  3899. case TokenType::DoublePipe:
  3900. m_forbid_logical_tokens = true;
  3901. break;
  3902. case TokenType::DoubleQuestionMark:
  3903. m_forbid_coalesce_token = true;
  3904. break;
  3905. case TokenType::QuestionMarkPeriod:
  3906. m_forbid_question_mark_period = true;
  3907. break;
  3908. case TokenType::ParenOpen:
  3909. m_forbid_paren_open = true;
  3910. break;
  3911. case TokenType::Equals:
  3912. m_forbid_equals = true;
  3913. break;
  3914. default:
  3915. VERIFY_NOT_REACHED();
  3916. }
  3917. }
  3918. }
  3919. bool Parser::ForbiddenTokens::allows(TokenType token) const
  3920. {
  3921. switch (token) {
  3922. case TokenType::In:
  3923. return !m_forbid_in_token;
  3924. case TokenType::DoubleAmpersand:
  3925. case TokenType::DoublePipe:
  3926. return !m_forbid_logical_tokens;
  3927. case TokenType::DoubleQuestionMark:
  3928. return !m_forbid_coalesce_token;
  3929. case TokenType::QuestionMarkPeriod:
  3930. return !m_forbid_question_mark_period;
  3931. case TokenType::ParenOpen:
  3932. return !m_forbid_paren_open;
  3933. case TokenType::Equals:
  3934. return !m_forbid_equals;
  3935. default:
  3936. return true;
  3937. }
  3938. }
  3939. Parser::ForbiddenTokens Parser::ForbiddenTokens::merge(ForbiddenTokens other) const
  3940. {
  3941. ForbiddenTokens result = *this;
  3942. result.m_forbid_in_token |= other.m_forbid_in_token;
  3943. result.m_forbid_logical_tokens |= other.m_forbid_logical_tokens;
  3944. result.m_forbid_coalesce_token |= other.m_forbid_coalesce_token;
  3945. result.m_forbid_paren_open |= other.m_forbid_paren_open;
  3946. result.m_forbid_question_mark_period |= other.m_forbid_question_mark_period;
  3947. result.m_forbid_equals |= other.m_forbid_equals;
  3948. return result;
  3949. }
  3950. Parser::ForbiddenTokens Parser::ForbiddenTokens::forbid(std::initializer_list<TokenType> const& forbidden) const
  3951. {
  3952. ForbiddenTokens result = *this;
  3953. result.forbid_tokens(forbidden);
  3954. return result;
  3955. }
  3956. }