Parser.cpp 198 KB

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