Parser.cpp 175 KB

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