Parser.cpp 176 KB

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