Parser.cpp 158 KB

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