Parser.cpp 166 KB

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