Parser.cpp 171 KB

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