Parser.cpp 170 KB

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