Parser.cpp 220 KB

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