Parser.cpp 217 KB

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