AST.cpp 174 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Demangle.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/HashTable.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <LibCrypto/BigInt/SignedBigInteger.h>
  15. #include <LibJS/AST.h>
  16. #include <LibJS/Interpreter.h>
  17. #include <LibJS/Runtime/AbstractOperations.h>
  18. #include <LibJS/Runtime/Accessor.h>
  19. #include <LibJS/Runtime/Array.h>
  20. #include <LibJS/Runtime/BigInt.h>
  21. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  22. #include <LibJS/Runtime/Error.h>
  23. #include <LibJS/Runtime/FunctionEnvironment.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/IteratorOperations.h>
  26. #include <LibJS/Runtime/MarkedValueList.h>
  27. #include <LibJS/Runtime/NativeFunction.h>
  28. #include <LibJS/Runtime/ObjectEnvironment.h>
  29. #include <LibJS/Runtime/PrimitiveString.h>
  30. #include <LibJS/Runtime/PromiseConstructor.h>
  31. #include <LibJS/Runtime/PromiseReaction.h>
  32. #include <LibJS/Runtime/Reference.h>
  33. #include <LibJS/Runtime/RegExpObject.h>
  34. #include <LibJS/Runtime/Shape.h>
  35. #include <typeinfo>
  36. namespace JS {
  37. class InterpreterNodeScope {
  38. AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
  39. AK_MAKE_NONMOVABLE(InterpreterNodeScope);
  40. public:
  41. InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
  42. : m_interpreter(interpreter)
  43. , m_chain_node { nullptr, node }
  44. {
  45. m_interpreter.vm().running_execution_context().current_node = &node;
  46. m_interpreter.push_ast_node(m_chain_node);
  47. }
  48. ~InterpreterNodeScope()
  49. {
  50. m_interpreter.pop_ast_node();
  51. }
  52. private:
  53. Interpreter& m_interpreter;
  54. ExecutingASTNodeChain m_chain_node;
  55. };
  56. String ASTNode::class_name() const
  57. {
  58. // NOTE: We strip the "JS::" prefix.
  59. return demangle(typeid(*this).name()).substring(4);
  60. }
  61. static void print_indent(int indent)
  62. {
  63. out("{}", String::repeated(' ', indent * 2));
  64. }
  65. static void update_function_name(Value value, FlyString const& name)
  66. {
  67. if (!value.is_function())
  68. return;
  69. auto& function = value.as_function();
  70. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  71. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  72. }
  73. static ThrowCompletionOr<String> get_function_name(GlobalObject& global_object, Value value)
  74. {
  75. if (value.is_symbol())
  76. return String::formatted("[{}]", value.as_symbol().description());
  77. if (value.is_string())
  78. return value.as_string().string();
  79. return value.to_string(global_object);
  80. }
  81. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  82. // StatementList : StatementList StatementListItem
  83. Completion ScopeNode::evaluate_statements(Interpreter& interpreter, GlobalObject& global_object) const
  84. {
  85. auto completion = normal_completion({});
  86. for (auto const& node : children()) {
  87. completion = node.execute(interpreter, global_object).update_empty(completion.value());
  88. if (completion.is_abrupt())
  89. break;
  90. }
  91. return completion;
  92. }
  93. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  94. // BreakableStatement : IterationStatement
  95. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, IterationStatement const& statement, Vector<FlyString> const& label_set)
  96. {
  97. // 1. Let stmtResult be LoopEvaluation of IterationStatement with argument labelSet.
  98. auto result = statement.loop_evaluation(interpreter, global_object, label_set);
  99. // 2. If stmtResult.[[Type]] is break, then
  100. if (result.type() == Completion::Type::Break) {
  101. // a. If stmtResult.[[Target]] is empty, then
  102. if (!result.target().has_value()) {
  103. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  104. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  105. result = normal_completion(result.value().value_or(js_undefined()));
  106. }
  107. }
  108. // 3. Return Completion(stmtResult).
  109. return result;
  110. }
  111. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  112. // BreakableStatement : SwitchStatement
  113. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, SwitchStatement const& statement, Vector<FlyString> const&)
  114. {
  115. // 1. Let stmtResult be the result of evaluating SwitchStatement.
  116. auto result = statement.execute_impl(interpreter, global_object);
  117. // 2. If stmtResult.[[Type]] is break, then
  118. if (result.type() == Completion::Type::Break) {
  119. // a. If stmtResult.[[Target]] is empty, then
  120. if (!result.target().has_value()) {
  121. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  122. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  123. result = normal_completion(result.value().value_or(js_undefined()));
  124. }
  125. }
  126. // 3. Return Completion(stmtResult).
  127. return result;
  128. }
  129. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  130. // LabelledStatement : LabelIdentifier : LabelledItem
  131. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, LabelledStatement const& statement, Vector<FlyString> const& label_set)
  132. {
  133. auto const& labelled_item = *statement.labelled_item();
  134. // 1. Let label be the StringValue of LabelIdentifier.
  135. auto const& label = statement.label();
  136. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  137. // Optimization: Avoid vector copy if possible.
  138. Optional<Vector<FlyString>> new_label_set;
  139. if (is<IterationStatement>(labelled_item) || is<SwitchStatement>(labelled_item) || is<LabelledStatement>(labelled_item)) {
  140. new_label_set = label_set;
  141. new_label_set->append(label);
  142. }
  143. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  144. Completion result;
  145. if (is<IterationStatement>(labelled_item))
  146. result = labelled_evaluation(interpreter, global_object, static_cast<IterationStatement const&>(labelled_item), *new_label_set);
  147. else if (is<SwitchStatement>(labelled_item))
  148. result = labelled_evaluation(interpreter, global_object, static_cast<SwitchStatement const&>(labelled_item), *new_label_set);
  149. else if (is<LabelledStatement>(labelled_item))
  150. result = labelled_evaluation(interpreter, global_object, static_cast<LabelledStatement const&>(labelled_item), *new_label_set);
  151. else
  152. result = labelled_item.execute(interpreter, global_object);
  153. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  154. if (result.type() == Completion::Type::Break && result.target() == label) {
  155. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  156. result = normal_completion(result.value());
  157. }
  158. // 5. Return Completion(stmtResult).
  159. return result;
  160. }
  161. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  162. Completion LabelledStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  163. {
  164. InterpreterNodeScope node_scope { interpreter, *this };
  165. // 1. Let newLabelSet be a new empty List.
  166. // 2. Return LabelledEvaluation of this LabelledStatement with argument newLabelSet.
  167. return labelled_evaluation(interpreter, global_object, *this, {});
  168. }
  169. void LabelledStatement::dump(int indent) const
  170. {
  171. ASTNode::dump(indent);
  172. print_indent(indent + 1);
  173. outln("(Label)");
  174. print_indent(indent + 2);
  175. outln("\"{}\"", m_label);
  176. print_indent(indent + 1);
  177. outln("(Labelled item)");
  178. m_labelled_item->dump(indent + 2);
  179. }
  180. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  181. Completion FunctionBody::execute(Interpreter& interpreter, GlobalObject& global_object) const
  182. {
  183. InterpreterNodeScope node_scope { interpreter, *this };
  184. // Note: Scoping should have already been set up by whoever is calling this FunctionBody.
  185. // 1. Return ? EvaluateFunctionBody of FunctionBody with arguments functionObject and argumentsList.
  186. return evaluate_statements(interpreter, global_object);
  187. }
  188. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  189. Completion BlockStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  190. {
  191. InterpreterNodeScope node_scope { interpreter, *this };
  192. auto& vm = interpreter.vm();
  193. Environment* old_environment { nullptr };
  194. ArmedScopeGuard restore_environment = [&] {
  195. vm.running_execution_context().lexical_environment = old_environment;
  196. };
  197. // Optimization: We only need a new lexical environment if there are any lexical declarations. :^)
  198. if (has_lexical_declarations()) {
  199. old_environment = vm.running_execution_context().lexical_environment;
  200. auto* block_environment = new_declarative_environment(*old_environment);
  201. block_declaration_instantiation(global_object, block_environment);
  202. vm.running_execution_context().lexical_environment = block_environment;
  203. } else {
  204. restore_environment.disarm();
  205. }
  206. return evaluate_statements(interpreter, global_object);
  207. }
  208. Completion Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  209. {
  210. // FIXME: This tries to be "ScriptEvaluation" and "evaluating scriptBody" at once. It shouldn't.
  211. // Clean this up and update perform_eval() / perform_shadow_realm_eval()
  212. InterpreterNodeScope node_scope { interpreter, *this };
  213. VERIFY(interpreter.lexical_environment() && interpreter.lexical_environment()->is_global_environment());
  214. auto& global_env = static_cast<GlobalEnvironment&>(*interpreter.lexical_environment());
  215. TRY(global_declaration_instantiation(interpreter, global_object, global_env));
  216. return evaluate_statements(interpreter, global_object);
  217. }
  218. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  219. Completion FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  220. {
  221. InterpreterNodeScope node_scope { interpreter, *this };
  222. if (m_is_hoisted) {
  223. // Perform special annexB steps see step 3 of: https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  224. auto* variable_environment = interpreter.vm().running_execution_context().variable_environment;
  225. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  226. auto function_object = MUST(lexical_environment->get_binding_value(global_object, name(), false));
  227. MUST(variable_environment->set_mutable_binding(global_object, name(), function_object, false));
  228. }
  229. // 1. Return NormalCompletion(empty).
  230. return normal_completion({});
  231. }
  232. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  233. Completion FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  234. {
  235. InterpreterNodeScope node_scope { interpreter, *this };
  236. // 1. Return InstantiateOrdinaryFunctionExpression of FunctionExpression.
  237. return instantiate_ordinary_function_expression(interpreter, global_object, name());
  238. }
  239. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  240. Value FunctionExpression::instantiate_ordinary_function_expression(Interpreter& interpreter, GlobalObject& global_object, FlyString given_name) const
  241. {
  242. if (given_name.is_empty())
  243. given_name = "";
  244. auto has_own_name = !name().is_empty();
  245. auto const& used_name = has_own_name ? name() : given_name;
  246. auto* scope = interpreter.lexical_environment();
  247. if (has_own_name) {
  248. VERIFY(scope);
  249. scope = new_declarative_environment(*scope);
  250. MUST(scope->create_immutable_binding(global_object, name(), false));
  251. }
  252. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  253. auto closure = ECMAScriptFunctionObject::create(global_object, used_name, body(), parameters(), function_length(), scope, private_scope, kind(), is_strict_mode(), might_need_arguments_object(), contains_direct_call_to_eval(), is_arrow_function());
  254. // FIXME: 6. Perform SetFunctionName(closure, name).
  255. // FIXME: 7. Perform MakeConstructor(closure).
  256. if (has_own_name)
  257. MUST(scope->initialize_binding(global_object, name(), closure));
  258. return closure;
  259. }
  260. // 14.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-empty-statement-runtime-semantics-evaluation
  261. Completion EmptyStatement::execute(Interpreter&, GlobalObject&) const
  262. {
  263. // 1. Return NormalCompletion(empty).
  264. return normal_completion({});
  265. }
  266. // 14.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-expression-statement-runtime-semantics-evaluation
  267. Completion ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  268. {
  269. InterpreterNodeScope node_scope { interpreter, *this };
  270. // 1. Let exprRef be the result of evaluating Expression.
  271. // 2. Return ? GetValue(exprRef).
  272. return m_expression->execute(interpreter, global_object);
  273. }
  274. // TODO: This shouldn't exist. Refactor into EvaluateCall.
  275. ThrowCompletionOr<CallExpression::ThisAndCallee> CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  276. {
  277. if (callee_reference.is_property_reference()) {
  278. auto this_value = callee_reference.get_this_value();
  279. auto callee = TRY(callee_reference.get_value(global_object));
  280. return ThisAndCallee { this_value, callee };
  281. }
  282. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  283. return ThisAndCallee {
  284. js_undefined(),
  285. callee_reference.is_unresolvable()
  286. ? TRY(m_callee->execute(interpreter, global_object)).release_value()
  287. : TRY(callee_reference.get_value(global_object))
  288. };
  289. }
  290. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  291. static ThrowCompletionOr<void> argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list)
  292. {
  293. list.ensure_capacity(arguments.size());
  294. for (auto& argument : arguments) {
  295. auto value = TRY(argument.value->execute(interpreter, global_object)).release_value();
  296. if (argument.is_spread) {
  297. auto result = TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  298. list.append(iterator_value);
  299. return {};
  300. }));
  301. } else {
  302. list.append(value);
  303. }
  304. }
  305. return {};
  306. }
  307. // 13.3.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-new-operator-runtime-semantics-evaluation
  308. // 13.3.5.1.1 EvaluateNew ( constructExpr, arguments ), https://tc39.es/ecma262/#sec-evaluatenew
  309. Completion NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  310. {
  311. InterpreterNodeScope node_scope { interpreter, *this };
  312. auto& vm = interpreter.vm();
  313. // 1. Let ref be the result of evaluating constructExpr.
  314. // 2. Let constructor be ? GetValue(ref).
  315. auto constructor = TRY(m_callee->execute(interpreter, global_object)).release_value();
  316. // 3. If arguments is empty, let argList be a new empty List.
  317. // 4. Else,
  318. // a. Let argList be ? ArgumentListEvaluation of arguments.
  319. MarkedValueList arg_list(vm.heap());
  320. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  321. // 5. If IsConstructor(constructor) is false, throw a TypeError exception.
  322. if (!constructor.is_constructor())
  323. return throw_type_error_for_callee(interpreter, global_object, constructor, "constructor"sv);
  324. // 6. Return ? Construct(constructor, argList).
  325. return Value { TRY(construct(global_object, constructor.as_function(), move(arg_list))) };
  326. }
  327. Completion CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const
  328. {
  329. auto& vm = interpreter.vm();
  330. if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) {
  331. String expression_string;
  332. if (is<Identifier>(*m_callee)) {
  333. expression_string = static_cast<Identifier const&>(*m_callee).string();
  334. } else {
  335. expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  336. }
  337. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string);
  338. } else {
  339. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
  340. }
  341. }
  342. // 13.3.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation
  343. Completion CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  344. {
  345. InterpreterNodeScope node_scope { interpreter, *this };
  346. auto& vm = interpreter.vm();
  347. auto callee_reference = TRY(m_callee->to_reference(interpreter, global_object));
  348. auto [this_value, callee] = TRY(compute_this_and_callee(interpreter, global_object, callee_reference));
  349. VERIFY(!callee.is_empty());
  350. MarkedValueList arg_list(vm.heap());
  351. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  352. if (!callee.is_function())
  353. return throw_type_error_for_callee(interpreter, global_object, callee, "function"sv);
  354. auto& function = callee.as_function();
  355. if (&function == global_object.eval_function()
  356. && callee_reference.is_environment_reference()
  357. && callee_reference.name().is_string()
  358. && callee_reference.name().as_string() == vm.names.eval.as_string()) {
  359. auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
  360. return perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct);
  361. }
  362. return vm.call(function, this_value, move(arg_list));
  363. }
  364. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  365. // SuperCall : super Arguments
  366. Completion SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  367. {
  368. InterpreterNodeScope node_scope { interpreter, *this };
  369. auto& vm = interpreter.vm();
  370. // 1. Let newTarget be GetNewTarget().
  371. auto new_target = vm.get_new_target();
  372. // 2. Assert: Type(newTarget) is Object.
  373. VERIFY(new_target.is_function());
  374. // 3. Let func be ! GetSuperConstructor().
  375. auto* func = get_super_constructor(interpreter.vm());
  376. VERIFY(!vm.exception());
  377. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  378. MarkedValueList arg_list(vm.heap());
  379. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  380. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  381. if (!func || !Value(func).is_constructor())
  382. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  383. // 6. Let result be ? Construct(func, argList, newTarget).
  384. auto* result = TRY(construct(global_object, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
  385. // 7. Let thisER be GetThisEnvironment().
  386. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  387. // 8. Perform ? thisER.BindThisValue(result).
  388. TRY(this_er.bind_this_value(global_object, result));
  389. // 9. Let F be thisER.[[FunctionObject]].
  390. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  391. [[maybe_unused]] auto& f = this_er.function_object();
  392. // 11. Perform ? InitializeInstanceElements(result, F).
  393. TRY(vm.initialize_instance_elements(*result, f));
  394. // 12. Return result.
  395. return Value { result };
  396. }
  397. // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
  398. Completion YieldExpression::execute(Interpreter&, GlobalObject&) const
  399. {
  400. // This should be transformed to a return.
  401. VERIFY_NOT_REACHED();
  402. }
  403. // 15.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-async-function-definitions-runtime-semantics-evaluation
  404. Completion AwaitExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  405. {
  406. InterpreterNodeScope node_scope { interpreter, *this };
  407. // 1. Let exprRef be the result of evaluating UnaryExpression.
  408. // 2. Let value be ? GetValue(exprRef).
  409. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  410. // 3. Return ? Await(value).
  411. return await(global_object, value);
  412. }
  413. // 14.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-return-statement-runtime-semantics-evaluation
  414. Completion ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  415. {
  416. InterpreterNodeScope node_scope { interpreter, *this };
  417. // ReturnStatement : return ;
  418. if (!m_argument) {
  419. // 1. Return Completion { [[Type]]: return, [[Value]]: undefined, [[Target]]: empty }.
  420. return { Completion::Type::Return, js_undefined(), {} };
  421. }
  422. // ReturnStatement : return Expression ;
  423. // 1. Let exprRef be the result of evaluating Expression.
  424. // 2. Let exprValue be ? GetValue(exprRef).
  425. auto value = TRY(m_argument->execute(interpreter, global_object));
  426. // NOTE: Generators are not supported in the AST interpreter
  427. // 3. If ! GetGeneratorKind() is async, set exprValue to ? Await(exprValue).
  428. // 4. Return Completion { [[Type]]: return, [[Value]]: exprValue, [[Target]]: empty }.
  429. return { Completion::Type::Return, value, {} };
  430. }
  431. // 14.6.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-if-statement-runtime-semantics-evaluation
  432. Completion IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  433. {
  434. InterpreterNodeScope node_scope { interpreter, *this };
  435. // IfStatement : if ( Expression ) Statement else Statement
  436. // 1. Let exprRef be the result of evaluating Expression.
  437. // 2. Let exprValue be ! ToBoolean(? GetValue(exprRef)).
  438. auto predicate_result = TRY(m_predicate->execute(interpreter, global_object)).release_value();
  439. // 3. If exprValue is true, then
  440. if (predicate_result.to_boolean()) {
  441. // a. Let stmtCompletion be the result of evaluating the first Statement.
  442. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  443. return m_consequent->execute(interpreter, global_object).update_empty(js_undefined());
  444. }
  445. // 4. Else,
  446. if (m_alternate) {
  447. // a. Let stmtCompletion be the result of evaluating the second Statement.
  448. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  449. return m_alternate->execute(interpreter, global_object).update_empty(js_undefined());
  450. }
  451. // IfStatement : if ( Expression ) Statement
  452. // 3. If exprValue is false, then
  453. // a. Return NormalCompletion(undefined).
  454. return normal_completion(js_undefined());
  455. }
  456. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  457. // WithStatement : with ( Expression ) Statement
  458. Completion WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  459. {
  460. InterpreterNodeScope node_scope { interpreter, *this };
  461. // 1. Let value be the result of evaluating Expression.
  462. auto value = TRY(m_object->execute(interpreter, global_object)).release_value();
  463. // 2. Let obj be ? ToObject(? GetValue(value)).
  464. auto* object = TRY(value.to_object(global_object));
  465. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  466. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  467. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  468. auto* new_environment = new_object_environment(*object, true, old_environment);
  469. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  470. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  471. // 6. Let C be the result of evaluating Statement.
  472. auto result = m_body->execute(interpreter, global_object);
  473. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  474. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  475. // 8. Return Completion(UpdateEmpty(C, undefined)).
  476. return result.update_empty(js_undefined());
  477. }
  478. // 14.7.1.1 LoopContinues ( completion, labelSet ), https://tc39.es/ecma262/#sec-loopcontinues
  479. static bool loop_continues(Completion const& completion, Vector<FlyString> const& label_set)
  480. {
  481. // 1. If completion.[[Type]] is normal, return true.
  482. if (completion.type() == Completion::Type::Normal)
  483. return true;
  484. // 2. If completion.[[Type]] is not continue, return false.
  485. if (completion.type() != Completion::Type::Continue)
  486. return false;
  487. // 3. If completion.[[Target]] is empty, return true.
  488. if (!completion.target().has_value())
  489. return true;
  490. // 4. If completion.[[Target]] is an element of labelSet, return true.
  491. if (label_set.contains_slow(*completion.target()))
  492. return true;
  493. // 5. Return false.
  494. return false;
  495. }
  496. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  497. // BreakableStatement : IterationStatement
  498. Completion WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  499. {
  500. // 1. Let newLabelSet be a new empty List.
  501. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  502. return labelled_evaluation(interpreter, global_object, *this, {});
  503. }
  504. // 14.7.3.2 Runtime Semantics: WhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-whileloopevaluation
  505. Completion WhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  506. {
  507. InterpreterNodeScope node_scope { interpreter, *this };
  508. // 1. Let V be undefined.
  509. auto last_value = js_undefined();
  510. // 2. Repeat,
  511. for (;;) {
  512. // a. Let exprRef be the result of evaluating Expression.
  513. // b. Let exprValue be ? GetValue(exprRef).
  514. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  515. // c. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  516. if (!test_result.to_boolean())
  517. return normal_completion(last_value);
  518. // d. Let stmtResult be the result of evaluating Statement.
  519. auto body_result = m_body->execute(interpreter, global_object);
  520. // e. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  521. if (!loop_continues(body_result, label_set))
  522. return body_result.update_empty(last_value);
  523. // f. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  524. if (body_result.value().has_value())
  525. last_value = *body_result.value();
  526. }
  527. VERIFY_NOT_REACHED();
  528. }
  529. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  530. // BreakableStatement : IterationStatement
  531. Completion DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  532. {
  533. // 1. Let newLabelSet be a new empty List.
  534. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  535. return labelled_evaluation(interpreter, global_object, *this, {});
  536. }
  537. // 14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-dowhileloopevaluation
  538. Completion DoWhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  539. {
  540. InterpreterNodeScope node_scope { interpreter, *this };
  541. // 1. Let V be undefined.
  542. auto last_value = js_undefined();
  543. // 2. Repeat,
  544. for (;;) {
  545. // a. Let stmtResult be the result of evaluating Statement.
  546. auto body_result = m_body->execute(interpreter, global_object);
  547. // b. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  548. if (!loop_continues(body_result, label_set))
  549. return body_result.update_empty(last_value);
  550. // c. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  551. if (body_result.value().has_value())
  552. last_value = *body_result.value();
  553. // d. Let exprRef be the result of evaluating Expression.
  554. // e. Let exprValue be ? GetValue(exprRef).
  555. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  556. // f. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  557. if (!test_result.to_boolean())
  558. return normal_completion(last_value);
  559. }
  560. VERIFY_NOT_REACHED();
  561. }
  562. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  563. // BreakableStatement : IterationStatement
  564. Completion ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  565. {
  566. // 1. Let newLabelSet be a new empty List.
  567. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  568. return labelled_evaluation(interpreter, global_object, *this, {});
  569. }
  570. // 14.7.4.2 Runtime Semantics: ForLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forloopevaluation
  571. Completion ForStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  572. {
  573. InterpreterNodeScope node_scope { interpreter, *this };
  574. // Note we don't always set a new environment but to use RAII we must do this here.
  575. auto* old_environment = interpreter.lexical_environment();
  576. ScopeGuard restore_old_environment = [&] {
  577. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  578. };
  579. Vector<FlyString> let_declarations;
  580. if (m_init) {
  581. if (is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) {
  582. auto* loop_environment = new_declarative_environment(*old_environment);
  583. auto& declaration = static_cast<VariableDeclaration const&>(*m_init);
  584. declaration.for_each_bound_name([&](auto const& name) {
  585. if (declaration.declaration_kind() == DeclarationKind::Const) {
  586. MUST(loop_environment->create_immutable_binding(global_object, name, true));
  587. } else {
  588. MUST(loop_environment->create_mutable_binding(global_object, name, false));
  589. let_declarations.append(name);
  590. }
  591. });
  592. interpreter.vm().running_execution_context().lexical_environment = loop_environment;
  593. }
  594. (void)TRY(m_init->execute(interpreter, global_object));
  595. }
  596. // 14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings ), https://tc39.es/ecma262/#sec-createperiterationenvironment
  597. auto create_per_iteration_environment = [&]() -> ThrowCompletionOr<void> {
  598. // 1. If perIterationBindings has any elements, then
  599. if (let_declarations.is_empty())
  600. return {};
  601. // a. Let lastIterationEnv be the running execution context's LexicalEnvironment.
  602. auto* last_iteration_env = interpreter.lexical_environment();
  603. // b. Let outer be lastIterationEnv.[[OuterEnv]].
  604. auto* outer = last_iteration_env->outer_environment();
  605. // c. Assert: outer is not null.
  606. VERIFY(outer);
  607. // d. Let thisIterationEnv be NewDeclarativeEnvironment(outer).
  608. auto* this_iteration_env = new_declarative_environment(*outer);
  609. // e. For each element bn of perIterationBindings, do
  610. for (auto& name : let_declarations) {
  611. // i. Perform ! thisIterationEnv.CreateMutableBinding(bn, false).
  612. MUST(this_iteration_env->create_mutable_binding(global_object, name, false));
  613. // ii. Let lastValue be ? lastIterationEnv.GetBindingValue(bn, true).
  614. auto last_value = TRY(last_iteration_env->get_binding_value(global_object, name, true));
  615. VERIFY(!last_value.is_empty());
  616. // iii. Perform thisIterationEnv.InitializeBinding(bn, lastValue).
  617. MUST(this_iteration_env->initialize_binding(global_object, name, last_value));
  618. }
  619. // f. Set the running execution context's LexicalEnvironment to thisIterationEnv.
  620. interpreter.vm().running_execution_context().lexical_environment = this_iteration_env;
  621. // 2. Return undefined.
  622. return {};
  623. };
  624. // 14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet ), https://tc39.es/ecma262/#sec-forbodyevaluation
  625. // 1. Let V be undefined.
  626. auto last_value = js_undefined();
  627. // 2. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  628. TRY(create_per_iteration_environment());
  629. // 3. Repeat,
  630. while (true) {
  631. // a. If test is not [empty], then
  632. if (m_test) {
  633. // i. Let testRef be the result of evaluating test.
  634. // ii. Let testValue be ? GetValue(testRef).
  635. auto test_value = TRY(m_test->execute(interpreter, global_object)).release_value();
  636. // iii. If ! ToBoolean(testValue) is false, return NormalCompletion(V).
  637. if (!test_value.to_boolean())
  638. return normal_completion(last_value);
  639. }
  640. // b. Let result be the result of evaluating stmt.
  641. auto result = m_body->execute(interpreter, global_object);
  642. // c. If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
  643. if (!loop_continues(result, label_set))
  644. return result.update_empty(last_value);
  645. // d. If result.[[Value]] is not empty, set V to result.[[Value]].
  646. if (result.value().has_value())
  647. last_value = *result.value();
  648. // e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  649. TRY(create_per_iteration_environment());
  650. // f. If increment is not [empty], then
  651. if (m_update) {
  652. // i. Let incRef be the result of evaluating increment.
  653. // ii. Perform ? GetValue(incRef).
  654. (void)TRY(m_update->execute(interpreter, global_object));
  655. }
  656. }
  657. VERIFY_NOT_REACHED();
  658. }
  659. struct ForInOfHeadState {
  660. explicit ForInOfHeadState(Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs)
  661. {
  662. lhs.visit(
  663. [&](NonnullRefPtr<ASTNode>& ast_node) {
  664. expression_lhs = ast_node.ptr();
  665. },
  666. [&](NonnullRefPtr<BindingPattern>& pattern) {
  667. pattern_lhs = pattern.ptr();
  668. destructuring = true;
  669. lhs_kind = Assignment;
  670. });
  671. }
  672. ASTNode* expression_lhs = nullptr;
  673. BindingPattern* pattern_lhs = nullptr;
  674. enum LhsKind {
  675. Assignment,
  676. VarBinding,
  677. LexicalBinding
  678. };
  679. LhsKind lhs_kind = Assignment;
  680. bool destructuring = false;
  681. Value rhs_value;
  682. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  683. // Note: This is only steps 6.g through 6.j of the method because we currently implement for-in without an iterator so to prevent duplicated code we do this part here.
  684. ThrowCompletionOr<void> execute_head(Interpreter& interpreter, GlobalObject& global_object, Value next_value) const
  685. {
  686. VERIFY(!next_value.is_empty());
  687. Optional<Reference> lhs_reference;
  688. Environment* iteration_environment = nullptr;
  689. // g. If lhsKind is either assignment or varBinding, then
  690. if (lhs_kind == Assignment || lhs_kind == VarBinding) {
  691. if (!destructuring) {
  692. VERIFY(expression_lhs);
  693. if (is<VariableDeclaration>(*expression_lhs)) {
  694. auto& declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  695. VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  696. lhs_reference = TRY(declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter, global_object));
  697. } else {
  698. VERIFY(is<Identifier>(*expression_lhs) || is<MemberExpression>(*expression_lhs));
  699. auto& expression = static_cast<Expression const&>(*expression_lhs);
  700. lhs_reference = TRY(expression.to_reference(interpreter, global_object));
  701. }
  702. }
  703. }
  704. // h. Else,
  705. else {
  706. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  707. iteration_environment = new_declarative_environment(*interpreter.lexical_environment());
  708. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  709. for_declaration.for_each_bound_name([&](auto const& name) {
  710. if (for_declaration.declaration_kind() == DeclarationKind::Const)
  711. MUST(iteration_environment->create_immutable_binding(global_object, name, false));
  712. else
  713. MUST(iteration_environment->create_mutable_binding(global_object, name, true));
  714. });
  715. interpreter.vm().running_execution_context().lexical_environment = iteration_environment;
  716. if (!destructuring) {
  717. VERIFY(for_declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  718. lhs_reference = MUST(interpreter.vm().resolve_binding(for_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string()));
  719. }
  720. }
  721. // i. If destructuring is false, then
  722. if (!destructuring) {
  723. VERIFY(lhs_reference.has_value());
  724. if (lhs_kind == LexicalBinding)
  725. return lhs_reference->initialize_referenced_binding(global_object, next_value);
  726. else
  727. return lhs_reference->put_value(global_object, next_value);
  728. }
  729. // j. Else,
  730. if (lhs_kind == Assignment) {
  731. VERIFY(pattern_lhs);
  732. return interpreter.vm().destructuring_assignment_evaluation(*pattern_lhs, next_value, global_object);
  733. }
  734. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  735. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  736. auto& binding_pattern = for_declaration.declarations().first().target().get<NonnullRefPtr<BindingPattern>>();
  737. VERIFY(lhs_kind == VarBinding || iteration_environment);
  738. // At this point iteration_environment is undefined if lhs_kind == VarBinding which means this does both
  739. // branch j.ii and j.iii because ForBindingInitialization is just a forwarding call to BindingInitialization.
  740. return interpreter.vm().binding_initialization(binding_pattern, next_value, iteration_environment, global_object);
  741. }
  742. };
  743. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  744. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  745. // This method combines ForInOfLoopEvaluation and ForIn/OfHeadEvaluation for similar reason as ForIn/OfBodyEvaluation, to prevent code duplication.
  746. // For the same reason we also skip step 6 and 7 of ForIn/OfHeadEvaluation as this is done by the appropriate for loop type.
  747. static ThrowCompletionOr<ForInOfHeadState> for_in_of_head_execute(Interpreter& interpreter, GlobalObject& global_object, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs, Expression const& rhs)
  748. {
  749. ForInOfHeadState state(lhs);
  750. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(*(*ast_ptr))) {
  751. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  752. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  753. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  754. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  755. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  756. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  757. Environment* new_environment = nullptr;
  758. auto& variable_declaration = static_cast<VariableDeclaration const&>(*(*ast_ptr));
  759. VERIFY(variable_declaration.declarations().size() == 1);
  760. state.destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  761. if (variable_declaration.declaration_kind() == DeclarationKind::Var) {
  762. state.lhs_kind = ForInOfHeadState::VarBinding;
  763. auto& variable = variable_declaration.declarations().first();
  764. // B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  765. if (variable.init()) {
  766. VERIFY(variable.target().has<NonnullRefPtr<Identifier>>());
  767. auto& binding_id = variable.target().get<NonnullRefPtr<Identifier>>()->string();
  768. auto reference = TRY(interpreter.vm().resolve_binding(binding_id));
  769. auto result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *variable.init(), binding_id));
  770. TRY(reference.put_value(global_object, result));
  771. }
  772. } else {
  773. state.lhs_kind = ForInOfHeadState::LexicalBinding;
  774. new_environment = new_declarative_environment(*interpreter.lexical_environment());
  775. variable_declaration.for_each_bound_name([&](auto const& name) {
  776. MUST(new_environment->create_mutable_binding(global_object, name, false));
  777. });
  778. }
  779. if (new_environment) {
  780. // 2.d Set the running execution context's LexicalEnvironment to newEnv.
  781. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, new_environment);
  782. // 3. Let exprRef be the result of evaluating expr.
  783. // 5. Let exprValue be ? GetValue(exprRef).
  784. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  785. // Note that since a reference stores its environment it doesn't matter we only reset
  786. // this after step 5. (Also we have no way of separating these steps at this point)
  787. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  788. } else {
  789. // 3. Let exprRef be the result of evaluating expr.
  790. // 5. Let exprValue be ? GetValue(exprRef).
  791. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  792. }
  793. return state;
  794. }
  795. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  796. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  797. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  798. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  799. // We can skip step 1, 2 and 4 here (on top of already skipping step 6 and 7).
  800. // 3. Let exprRef be the result of evaluating expr.
  801. // 5. Let exprValue be ? GetValue(exprRef).
  802. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  803. return state;
  804. }
  805. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  806. // BreakableStatement : IterationStatement
  807. Completion ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  808. {
  809. // 1. Let newLabelSet be a new empty List.
  810. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  811. return labelled_evaluation(interpreter, global_object, *this, {});
  812. }
  813. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  814. Completion ForInStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  815. {
  816. InterpreterNodeScope node_scope { interpreter, *this };
  817. auto for_in_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, *m_rhs));
  818. auto rhs_result = for_in_head_state.rhs_value;
  819. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  820. // a. If exprValue is undefined or null, then
  821. if (rhs_result.is_nullish()) {
  822. // i. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  823. return { Completion::Type::Break, {}, {} };
  824. }
  825. // b. Let obj be ! ToObject(exprValue).
  826. auto* object = MUST(rhs_result.to_object(global_object));
  827. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  828. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  829. Environment* old_environment = interpreter.lexical_environment();
  830. auto restore_scope = ScopeGuard([&] {
  831. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  832. });
  833. // 3. Let V be undefined.
  834. auto last_value = js_undefined();
  835. while (object) {
  836. auto property_names = TRY(object->enumerable_own_property_names(Object::PropertyKind::Key));
  837. for (auto& value : property_names) {
  838. TRY(for_in_head_state.execute_head(interpreter, global_object, value));
  839. // l. Let result be the result of evaluating stmt.
  840. auto result = m_body->execute(interpreter, global_object);
  841. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  842. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  843. // n. If LoopContinues(result, labelSet) is false, then
  844. if (!loop_continues(result, label_set)) {
  845. // 1. Return Completion(UpdateEmpty(result, V)).
  846. return result.update_empty(last_value);
  847. }
  848. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  849. if (result.value().has_value())
  850. last_value = *result.value();
  851. }
  852. object = TRY(object->internal_get_prototype_of());
  853. }
  854. return last_value;
  855. }
  856. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  857. // BreakableStatement : IterationStatement
  858. Completion ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  859. {
  860. // 1. Let newLabelSet be a new empty List.
  861. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  862. return labelled_evaluation(interpreter, global_object, *this, {});
  863. }
  864. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  865. Completion ForOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  866. {
  867. InterpreterNodeScope node_scope { interpreter, *this };
  868. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  869. auto rhs_result = for_of_head_state.rhs_value;
  870. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  871. // We use get_iterator_values which behaves like ForIn/OfBodyEvaluation with iteratorKind iterate.
  872. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  873. Environment* old_environment = interpreter.lexical_environment();
  874. auto restore_scope = ScopeGuard([&] {
  875. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  876. });
  877. // 3. Let V be undefined.
  878. auto last_value = js_undefined();
  879. Optional<Completion> status;
  880. (void)TRY(get_iterator_values(global_object, rhs_result, [&](Value value) -> Optional<Completion> {
  881. TRY(for_of_head_state.execute_head(interpreter, global_object, value));
  882. // l. Let result be the result of evaluating stmt.
  883. auto result = m_body->execute(interpreter, global_object);
  884. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  885. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  886. // n. If LoopContinues(result, labelSet) is false, then
  887. if (!loop_continues(result, label_set)) {
  888. // 2. Set status to UpdateEmpty(result, V).
  889. status = result.update_empty(last_value);
  890. // 4. Return ? IteratorClose(iteratorRecord, status).
  891. // NOTE: This is done by returning a completion from the callback.
  892. return status;
  893. }
  894. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  895. if (result.value().has_value())
  896. last_value = *result.value();
  897. return {};
  898. }));
  899. // Return `status` set during step n.2. in the callback, or...
  900. // e. If done is true, return NormalCompletion(V).
  901. return status.value_or(normal_completion(last_value));
  902. }
  903. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  904. // BreakableStatement : IterationStatement
  905. Completion ForAwaitOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  906. {
  907. // 1. Let newLabelSet be a new empty List.
  908. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  909. return labelled_evaluation(interpreter, global_object, *this, {});
  910. }
  911. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  912. Completion ForAwaitOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  913. {
  914. InterpreterNodeScope node_scope { interpreter, *this };
  915. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  916. // Note: Performs only steps 1 through 5.
  917. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  918. auto rhs_result = for_of_head_state.rhs_value;
  919. // NOTE: Perform step 7 from ForIn/OfHeadEvaluation. And since this is always async we only have to do step 7.d.
  920. // d. Return ? GetIterator(exprValue, iteratorHint).
  921. auto iterator = TRY(get_iterator(global_object, rhs_result, IteratorHint::Async));
  922. auto& vm = interpreter.vm();
  923. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  924. // NOTE: Here iteratorKind is always async.
  925. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  926. Environment* old_environment = interpreter.lexical_environment();
  927. auto restore_scope = ScopeGuard([&] {
  928. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  929. });
  930. // 3. Let V be undefined.
  931. auto last_value = js_undefined();
  932. // NOTE: Step 4 and 5 are just extracting properties from the head which is done already in for_in_of_head_execute.
  933. // And these are only used in step 6.g through 6.k which is done with for_of_head_state.execute_head.
  934. // 6. Repeat,
  935. while (true) {
  936. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  937. auto next_result = TRY(call(global_object, iterator.next_method, iterator.iterator));
  938. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  939. next_result = TRY(await(global_object, next_result));
  940. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  941. if (!next_result.is_object())
  942. return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextBadReturn);
  943. // d. Let done be ? IteratorComplete(nextResult).
  944. auto done = TRY(iterator_complete(global_object, next_result.as_object()));
  945. // e. If done is true, return NormalCompletion(V).
  946. if (done)
  947. return last_value;
  948. // f. Let nextValue be ? IteratorValue(nextResult).
  949. auto next_value = TRY(iterator_value(global_object, next_result.as_object()));
  950. // NOTE: This performs steps g. through to k.
  951. TRY(for_of_head_state.execute_head(interpreter, global_object, next_value));
  952. // l. Let result be the result of evaluating stmt.
  953. auto result = m_body->execute(interpreter, global_object);
  954. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  955. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  956. // n. If LoopContinues(result, labelSet) is false, then
  957. if (!loop_continues(result, label_set)) {
  958. // 2. Set status to UpdateEmpty(result, V).
  959. auto status = result.update_empty(last_value);
  960. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  961. return async_iterator_close(global_object, iterator, move(status));
  962. }
  963. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  964. if (result.value().has_value())
  965. last_value = *result.value();
  966. }
  967. VERIFY_NOT_REACHED();
  968. }
  969. // 13.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exp-operator-runtime-semantics-evaluation
  970. // 13.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-multiplicative-operators-runtime-semantics-evaluation
  971. // 13.8.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-addition-operator-plus-runtime-semantics-evaluation
  972. // 13.8.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-subtraction-operator-minus-runtime-semantics-evaluation
  973. // 13.9.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-left-shift-operator-runtime-semantics-evaluation
  974. // 13.9.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-signed-right-shift-operator-runtime-semantics-evaluation
  975. // 13.9.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unsigned-right-shift-operator-runtime-semantics-evaluation
  976. // 13.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  977. // 13.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-equality-operators-runtime-semantics-evaluation
  978. Completion BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  979. {
  980. InterpreterNodeScope node_scope { interpreter, *this };
  981. // Special case in which we cannot execute the lhs. RelationalExpression : PrivateIdentifier in ShiftExpression
  982. // RelationalExpression : PrivateIdentifier in ShiftExpression, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  983. if (m_op == BinaryOp::In && is<PrivateIdentifier>(*m_lhs)) {
  984. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_lhs).string();
  985. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  986. if (!rhs_result.is_object())
  987. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::InOperatorWithObject);
  988. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  989. VERIFY(private_environment);
  990. auto private_name = private_environment->resolve_private_identifier(private_identifier);
  991. return Value(rhs_result.as_object().private_element_find(private_name) != nullptr);
  992. }
  993. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  994. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  995. switch (m_op) {
  996. case BinaryOp::Addition:
  997. return TRY(add(global_object, lhs_result, rhs_result));
  998. case BinaryOp::Subtraction:
  999. return TRY(sub(global_object, lhs_result, rhs_result));
  1000. case BinaryOp::Multiplication:
  1001. return TRY(mul(global_object, lhs_result, rhs_result));
  1002. case BinaryOp::Division:
  1003. return TRY(div(global_object, lhs_result, rhs_result));
  1004. case BinaryOp::Modulo:
  1005. return TRY(mod(global_object, lhs_result, rhs_result));
  1006. case BinaryOp::Exponentiation:
  1007. return TRY(exp(global_object, lhs_result, rhs_result));
  1008. case BinaryOp::StrictlyEquals:
  1009. return Value(is_strictly_equal(lhs_result, rhs_result));
  1010. case BinaryOp::StrictlyInequals:
  1011. return Value(!is_strictly_equal(lhs_result, rhs_result));
  1012. case BinaryOp::LooselyEquals:
  1013. return Value(TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1014. case BinaryOp::LooselyInequals:
  1015. return Value(!TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1016. case BinaryOp::GreaterThan:
  1017. return TRY(greater_than(global_object, lhs_result, rhs_result));
  1018. case BinaryOp::GreaterThanEquals:
  1019. return TRY(greater_than_equals(global_object, lhs_result, rhs_result));
  1020. case BinaryOp::LessThan:
  1021. return TRY(less_than(global_object, lhs_result, rhs_result));
  1022. case BinaryOp::LessThanEquals:
  1023. return TRY(less_than_equals(global_object, lhs_result, rhs_result));
  1024. case BinaryOp::BitwiseAnd:
  1025. return TRY(bitwise_and(global_object, lhs_result, rhs_result));
  1026. case BinaryOp::BitwiseOr:
  1027. return TRY(bitwise_or(global_object, lhs_result, rhs_result));
  1028. case BinaryOp::BitwiseXor:
  1029. return TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  1030. case BinaryOp::LeftShift:
  1031. return TRY(left_shift(global_object, lhs_result, rhs_result));
  1032. case BinaryOp::RightShift:
  1033. return TRY(right_shift(global_object, lhs_result, rhs_result));
  1034. case BinaryOp::UnsignedRightShift:
  1035. return TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  1036. case BinaryOp::In:
  1037. return TRY(in(global_object, lhs_result, rhs_result));
  1038. case BinaryOp::InstanceOf:
  1039. return TRY(instance_of(global_object, lhs_result, rhs_result));
  1040. }
  1041. VERIFY_NOT_REACHED();
  1042. }
  1043. // 13.13.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-binary-logical-operators-runtime-semantics-evaluation
  1044. Completion LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1045. {
  1046. InterpreterNodeScope node_scope { interpreter, *this };
  1047. // 1. Let lref be the result of evaluating <Expression>.
  1048. // 2. Let lval be ? GetValue(lref).
  1049. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1050. switch (m_op) {
  1051. // LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1052. case LogicalOp::And:
  1053. // 3. Let lbool be ! ToBoolean(lval).
  1054. // 4. If lbool is false, return lval.
  1055. if (!lhs_result.to_boolean())
  1056. return lhs_result;
  1057. // 5. Let rref be the result of evaluating BitwiseORExpression.
  1058. // 6. Return ? GetValue(rref).
  1059. return m_rhs->execute(interpreter, global_object);
  1060. // LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1061. case LogicalOp::Or:
  1062. // 3. Let lbool be ! ToBoolean(lval).
  1063. // 4. If lbool is true, return lval.
  1064. if (lhs_result.to_boolean())
  1065. return lhs_result;
  1066. // 5. Let rref be the result of evaluating LogicalANDExpression.
  1067. // 6. Return ? GetValue(rref).
  1068. return m_rhs->execute(interpreter, global_object);
  1069. // CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1070. case LogicalOp::NullishCoalescing:
  1071. // 3. If lval is undefined or null, then
  1072. if (lhs_result.is_nullish()) {
  1073. // a. Let rref be the result of evaluating BitwiseORExpression.
  1074. // b. Return ? GetValue(rref).
  1075. return m_rhs->execute(interpreter, global_object);
  1076. }
  1077. // 4. Otherwise, return lval.
  1078. return lhs_result;
  1079. }
  1080. VERIFY_NOT_REACHED();
  1081. }
  1082. ThrowCompletionOr<Reference> Expression::to_reference(Interpreter&, GlobalObject&) const
  1083. {
  1084. return Reference {};
  1085. }
  1086. ThrowCompletionOr<Reference> Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const
  1087. {
  1088. if (m_cached_environment_coordinate.has_value()) {
  1089. auto* environment = interpreter.vm().running_execution_context().lexical_environment;
  1090. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  1091. environment = environment->outer_environment();
  1092. VERIFY(environment);
  1093. VERIFY(environment->is_declarative_environment());
  1094. if (!environment->is_permanently_screwed_by_eval()) {
  1095. return Reference { *environment, string(), interpreter.vm().in_strict_mode(), m_cached_environment_coordinate };
  1096. }
  1097. m_cached_environment_coordinate = {};
  1098. }
  1099. auto reference = TRY(interpreter.vm().resolve_binding(string()));
  1100. if (reference.environment_coordinate().has_value())
  1101. m_cached_environment_coordinate = reference.environment_coordinate();
  1102. return reference;
  1103. }
  1104. ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  1105. {
  1106. // 13.3.7.1 Runtime Semantics: Evaluation
  1107. // SuperProperty : super [ Expression ]
  1108. // SuperProperty : super . IdentifierName
  1109. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1110. if (is<SuperExpression>(object())) {
  1111. // 1. Let env be GetThisEnvironment().
  1112. auto& environment = get_this_environment(interpreter.vm());
  1113. // 2. Let actualThis be ? env.GetThisBinding().
  1114. auto actual_this = TRY(environment.get_this_binding(global_object));
  1115. PropertyKey property_key;
  1116. if (is_computed()) {
  1117. // SuperProperty : super [ Expression ]
  1118. // 3. Let propertyNameReference be the result of evaluating Expression.
  1119. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1120. auto property_name_value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1121. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1122. property_key = TRY(property_name_value.to_property_key(global_object));
  1123. } else {
  1124. // SuperProperty : super . IdentifierName
  1125. // 3. Let propertyKey be StringValue of IdentifierName.
  1126. VERIFY(is<Identifier>(property()));
  1127. property_key = static_cast<Identifier const&>(property()).string();
  1128. }
  1129. // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  1130. bool strict = interpreter.vm().in_strict_mode();
  1131. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1132. return TRY(make_super_property_reference(global_object, actual_this, property_key, strict));
  1133. }
  1134. auto base_reference = TRY(m_object->to_reference(interpreter, global_object));
  1135. Value base_value;
  1136. if (base_reference.is_valid_reference())
  1137. base_value = TRY(base_reference.get_value(global_object));
  1138. else
  1139. base_value = TRY(m_object->execute(interpreter, global_object)).release_value();
  1140. VERIFY(!base_value.is_empty());
  1141. // From here on equivalent to
  1142. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  1143. PropertyKey property_name;
  1144. if (is_computed()) {
  1145. // Weird order which I can't quite find from the specs.
  1146. auto value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1147. VERIFY(!value.is_empty());
  1148. TRY(require_object_coercible(global_object, base_value));
  1149. property_name = TRY(PropertyKey::from_value(global_object, value));
  1150. } else if (is<PrivateIdentifier>(*m_property)) {
  1151. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property);
  1152. return make_private_reference(interpreter.vm(), base_value, private_identifier.string());
  1153. } else {
  1154. property_name = verify_cast<Identifier>(*m_property).string();
  1155. TRY(require_object_coercible(global_object, base_value));
  1156. }
  1157. if (!property_name.is_valid())
  1158. return Reference {};
  1159. auto strict = interpreter.vm().in_strict_mode();
  1160. return Reference { base_value, move(property_name), {}, strict };
  1161. }
  1162. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  1163. // 13.5.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-void-operator-runtime-semantics-evaluation
  1164. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  1165. // 13.5.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-plus-operator-runtime-semantics-evaluation
  1166. // 13.5.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-minus-operator-runtime-semantics-evaluation
  1167. // 13.5.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-bitwise-not-operator-runtime-semantics-evaluation
  1168. // 13.5.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-logical-not-operator-runtime-semantics-evaluation
  1169. Completion UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1170. {
  1171. InterpreterNodeScope node_scope { interpreter, *this };
  1172. auto& vm = interpreter.vm();
  1173. if (m_op == UnaryOp::Delete) {
  1174. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1175. return Value(TRY(reference.delete_(global_object)));
  1176. }
  1177. Value lhs_result;
  1178. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  1179. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1180. if (reference.is_unresolvable())
  1181. lhs_result = js_undefined();
  1182. else
  1183. lhs_result = TRY(reference.get_value(global_object));
  1184. VERIFY(!lhs_result.is_empty());
  1185. } else {
  1186. // 1. Let expr be the result of evaluating UnaryExpression.
  1187. lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1188. }
  1189. switch (m_op) {
  1190. case UnaryOp::BitwiseNot:
  1191. return TRY(bitwise_not(global_object, lhs_result));
  1192. case UnaryOp::Not:
  1193. return Value(!lhs_result.to_boolean());
  1194. case UnaryOp::Plus:
  1195. return TRY(unary_plus(global_object, lhs_result));
  1196. case UnaryOp::Minus:
  1197. return TRY(unary_minus(global_object, lhs_result));
  1198. case UnaryOp::Typeof:
  1199. return Value { js_string(vm, lhs_result.typeof()) };
  1200. case UnaryOp::Void:
  1201. return js_undefined();
  1202. case UnaryOp::Delete:
  1203. VERIFY_NOT_REACHED();
  1204. }
  1205. VERIFY_NOT_REACHED();
  1206. }
  1207. Completion SuperExpression::execute(Interpreter&, GlobalObject&) const
  1208. {
  1209. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  1210. VERIFY_NOT_REACHED();
  1211. }
  1212. Completion ClassElement::execute(Interpreter&, GlobalObject&) const
  1213. {
  1214. // Note: The semantics of class element are handled in class_element_evaluation
  1215. VERIFY_NOT_REACHED();
  1216. }
  1217. static ThrowCompletionOr<ClassElement::ClassElementName> class_key_to_property_name(Interpreter& interpreter, GlobalObject& global_object, Expression const& key)
  1218. {
  1219. if (is<PrivateIdentifier>(key)) {
  1220. auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
  1221. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  1222. VERIFY(private_environment);
  1223. return ClassElement::ClassElementName { private_environment->resolve_private_identifier(private_identifier.string()) };
  1224. }
  1225. auto prop_key = TRY(key.execute(interpreter, global_object)).release_value();
  1226. if (prop_key.is_object())
  1227. prop_key = TRY(prop_key.to_primitive(global_object, Value::PreferredType::String));
  1228. auto property_key = TRY(PropertyKey::from_value(global_object, prop_key));
  1229. return ClassElement::ClassElementName { property_key };
  1230. }
  1231. // 15.4.5 Runtime Semantics: MethodDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-methoddefinitionevaluation
  1232. ThrowCompletionOr<ClassElement::ClassValue> ClassMethod::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1233. {
  1234. auto property_key = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1235. auto method_value = TRY(m_function->execute(interpreter, global_object)).release_value();
  1236. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  1237. method_function.make_method(target);
  1238. auto set_function_name = [&](String prefix = "") {
  1239. auto property_name = property_key.visit(
  1240. [&](PropertyKey const& property_name) -> String {
  1241. if (property_name.is_symbol()) {
  1242. auto description = property_name.as_symbol()->description();
  1243. if (description.is_empty())
  1244. return "";
  1245. return String::formatted("[{}]", description);
  1246. } else {
  1247. return property_name.to_string();
  1248. }
  1249. },
  1250. [&](PrivateName const& private_name) -> String {
  1251. return private_name.description;
  1252. });
  1253. update_function_name(method_value, String::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", property_name));
  1254. };
  1255. if (property_key.has<PropertyKey>()) {
  1256. auto& property_name = property_key.get<PropertyKey>();
  1257. switch (kind()) {
  1258. case ClassMethod::Kind::Method:
  1259. set_function_name();
  1260. TRY(target.define_property_or_throw(property_name, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1261. break;
  1262. case ClassMethod::Kind::Getter:
  1263. set_function_name("get");
  1264. TRY(target.define_property_or_throw(property_name, { .get = &method_function, .enumerable = true, .configurable = true }));
  1265. break;
  1266. case ClassMethod::Kind::Setter:
  1267. set_function_name("set");
  1268. TRY(target.define_property_or_throw(property_name, { .set = &method_function, .enumerable = true, .configurable = true }));
  1269. break;
  1270. default:
  1271. VERIFY_NOT_REACHED();
  1272. }
  1273. return ClassValue { normal_completion({}) };
  1274. } else {
  1275. auto& private_name = property_key.get<PrivateName>();
  1276. switch (kind()) {
  1277. case Kind::Method:
  1278. set_function_name();
  1279. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Method, method_value } };
  1280. case Kind::Getter:
  1281. set_function_name("get");
  1282. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), &method_function, nullptr) } };
  1283. case Kind::Setter:
  1284. set_function_name("set");
  1285. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), nullptr, &method_function) } };
  1286. default:
  1287. VERIFY_NOT_REACHED();
  1288. }
  1289. }
  1290. }
  1291. // We use this class to mimic Initializer : = AssignmentExpression of
  1292. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  1293. class ClassFieldInitializerStatement : public Statement {
  1294. public:
  1295. ClassFieldInitializerStatement(SourceRange source_range, NonnullRefPtr<Expression> expression, FlyString field_name)
  1296. : Statement(source_range)
  1297. , m_expression(move(expression))
  1298. , m_class_field_identifier_name(move(field_name))
  1299. {
  1300. }
  1301. Completion execute(Interpreter& interpreter, GlobalObject& global_object) const override
  1302. {
  1303. // 1. Assert: argumentsList is empty.
  1304. VERIFY(interpreter.vm().argument_count() == 0);
  1305. // 2. Assert: functionObject.[[ClassFieldInitializerName]] is not empty.
  1306. VERIFY(!m_class_field_identifier_name.is_empty());
  1307. // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  1308. // a. Let value be NamedEvaluation of Initializer with argument functionObject.[[ClassFieldInitializerName]].
  1309. // 4. Else,
  1310. // a. Let rhs be the result of evaluating AssignmentExpression.
  1311. // b. Let value be ? GetValue(rhs).
  1312. auto value = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_expression, m_class_field_identifier_name));
  1313. // 5. Return Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1314. return { Completion::Type::Return, value, {} };
  1315. }
  1316. void dump(int) const override
  1317. {
  1318. // This should not be dumped as it is never part of an actual AST.
  1319. VERIFY_NOT_REACHED();
  1320. }
  1321. private:
  1322. NonnullRefPtr<Expression> m_expression;
  1323. FlyString m_class_field_identifier_name; // [[ClassFieldIdentifierName]]
  1324. };
  1325. // 15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classfielddefinitionevaluation
  1326. ThrowCompletionOr<ClassElement::ClassValue> ClassField::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1327. {
  1328. auto property_key = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1329. ECMAScriptFunctionObject* initializer = nullptr;
  1330. if (m_initializer) {
  1331. auto copy_initializer = m_initializer;
  1332. auto name = property_key.visit(
  1333. [&](PropertyKey const& property_name) -> String {
  1334. return property_name.is_number() ? property_name.to_string() : property_name.to_string_or_symbol().to_display_string();
  1335. },
  1336. [&](PrivateName const& private_name) -> String {
  1337. return private_name.description;
  1338. });
  1339. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  1340. auto function_code = create_ast_node<ClassFieldInitializerStatement>(m_initializer->source_range(), copy_initializer.release_nonnull(), name);
  1341. initializer = ECMAScriptFunctionObject::create(interpreter.global_object(), String::empty(), *function_code, {}, 0, interpreter.lexical_environment(), interpreter.vm().running_execution_context().private_environment, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false);
  1342. initializer->make_method(target);
  1343. }
  1344. return ClassValue {
  1345. ClassFieldDefinition {
  1346. property_key,
  1347. initializer,
  1348. }
  1349. };
  1350. }
  1351. static Optional<FlyString> nullopt_or_private_identifier_description(Expression const& expression)
  1352. {
  1353. if (is<PrivateIdentifier>(expression))
  1354. return static_cast<PrivateIdentifier const&>(expression).string();
  1355. return {};
  1356. }
  1357. Optional<FlyString> ClassField::private_bound_identifier() const
  1358. {
  1359. return nullopt_or_private_identifier_description(*m_key);
  1360. }
  1361. Optional<FlyString> ClassMethod::private_bound_identifier() const
  1362. {
  1363. return nullopt_or_private_identifier_description(*m_key);
  1364. }
  1365. // 15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classstaticblockdefinitionevaluation
  1366. ThrowCompletionOr<ClassElement::ClassValue> StaticInitializer::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& home_object) const
  1367. {
  1368. // 1. Let lex be the running execution context's LexicalEnvironment.
  1369. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  1370. // 2. Let privateScope be the running execution context's PrivateEnvironment.
  1371. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  1372. // 3. Let sourceText be the empty sequence of Unicode code points.
  1373. // 4. Let formalParameters be an instance of the production FormalParameters : [empty] .
  1374. // 5. Let bodyFunction be OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateScope).
  1375. // Note: The function bodyFunction is never directly accessible to ECMAScript code.
  1376. auto* body_function = ECMAScriptFunctionObject::create(global_object, "", *m_function_body, {}, 0, lexical_environment, private_scope, FunctionKind::Normal, true, false, m_contains_direct_call_to_eval, false);
  1377. // 6. Perform MakeMethod(bodyFunction, homeObject).
  1378. body_function->make_method(home_object);
  1379. // 7. Return the ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }.
  1380. return ClassValue { normal_completion(body_function) };
  1381. }
  1382. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1383. // ClassExpression : class BindingIdentifier ClassTail
  1384. Completion ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1385. {
  1386. InterpreterNodeScope node_scope { interpreter, *this };
  1387. // 1. Let className be StringValue of BindingIdentifier.
  1388. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1389. auto value = TRY(class_definition_evaluation(interpreter, global_object, m_name, m_name.is_null() ? "" : m_name));
  1390. // FIXME:
  1391. // 3. Set value.[[SourceText]] to the source text matched by ClassExpression.
  1392. // 4. Return value.
  1393. return value;
  1394. }
  1395. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1396. // ClassDeclaration : class BindingIdentifier ClassTail
  1397. Completion ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1398. {
  1399. InterpreterNodeScope node_scope { interpreter, *this };
  1400. // 1. Perform ? BindingClassDeclarationEvaluation of this ClassDeclaration.
  1401. (void)TRY(binding_class_declaration_evaluation(interpreter, global_object));
  1402. // 2. Return NormalCompletion(empty).
  1403. return normal_completion({});
  1404. }
  1405. // 15.7.14 Runtime Semantics: ClassDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
  1406. ThrowCompletionOr<Value> ClassExpression::class_definition_evaluation(Interpreter& interpreter, GlobalObject& global_object, FlyString const& binding_name, FlyString const& class_name) const
  1407. {
  1408. auto& vm = interpreter.vm();
  1409. auto* environment = vm.lexical_environment();
  1410. VERIFY(environment);
  1411. auto* class_scope = new_declarative_environment(*environment);
  1412. // We might not set the lexical environment but we always want to restore it eventually.
  1413. ArmedScopeGuard restore_environment = [&] {
  1414. vm.running_execution_context().lexical_environment = environment;
  1415. };
  1416. if (!binding_name.is_null())
  1417. MUST(class_scope->create_immutable_binding(global_object, binding_name, true));
  1418. auto* outer_private_environment = vm.running_execution_context().private_environment;
  1419. auto* class_private_environment = new_private_environment(vm, outer_private_environment);
  1420. for (auto const& element : m_elements) {
  1421. auto opt_private_name = element.private_bound_identifier();
  1422. if (opt_private_name.has_value())
  1423. class_private_environment->add_private_name({}, opt_private_name.release_value());
  1424. }
  1425. auto* proto_parent = vm.current_realm()->global_object().object_prototype();
  1426. auto* constructor_parent = vm.current_realm()->global_object().function_prototype();
  1427. if (!m_super_class.is_null()) {
  1428. vm.running_execution_context().lexical_environment = class_scope;
  1429. // Note: Since our execute does evaluation and GetValue in once we must check for a valid reference first
  1430. Value super_class;
  1431. auto reference = TRY(m_super_class->to_reference(interpreter, global_object));
  1432. if (reference.is_valid_reference()) {
  1433. super_class = TRY(reference.get_value(global_object));
  1434. } else {
  1435. super_class = TRY(m_super_class->execute(interpreter, global_object)).release_value();
  1436. }
  1437. vm.running_execution_context().lexical_environment = environment;
  1438. if (super_class.is_null()) {
  1439. proto_parent = nullptr;
  1440. } else if (!super_class.is_constructor()) {
  1441. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects());
  1442. } else {
  1443. auto super_class_prototype = TRY(super_class.get(global_object, vm.names.prototype));
  1444. if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
  1445. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects());
  1446. if (super_class_prototype.is_null())
  1447. proto_parent = nullptr;
  1448. else
  1449. proto_parent = &super_class_prototype.as_object();
  1450. constructor_parent = &super_class.as_object();
  1451. }
  1452. }
  1453. auto* prototype = Object::create(global_object, proto_parent);
  1454. VERIFY(prototype);
  1455. vm.running_execution_context().lexical_environment = class_scope;
  1456. vm.running_execution_context().private_environment = class_private_environment;
  1457. ScopeGuard restore_private_environment = [&] {
  1458. vm.running_execution_context().private_environment = outer_private_environment;
  1459. };
  1460. // FIXME: Step 14.a is done in the parser. But maybe it shouldn't?
  1461. auto class_constructor_value = TRY(m_constructor->execute(interpreter, global_object)).release_value();
  1462. update_function_name(class_constructor_value, class_name);
  1463. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  1464. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  1465. class_constructor->set_home_object(prototype);
  1466. class_constructor->set_is_class_constructor();
  1467. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  1468. TRY(class_constructor->internal_set_prototype_of(constructor_parent));
  1469. if (!m_super_class.is_null())
  1470. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  1471. prototype->define_direct_property(vm.names.constructor, class_constructor, Attribute::Writable | Attribute::Configurable);
  1472. using StaticElement = Variant<ClassElement::ClassFieldDefinition, ECMAScriptFunctionObject*>;
  1473. Vector<PrivateElement> static_private_methods;
  1474. Vector<PrivateElement> instance_private_methods;
  1475. Vector<ClassElement::ClassFieldDefinition> instance_fields;
  1476. Vector<StaticElement> static_elements;
  1477. for (auto const& element : m_elements) {
  1478. // Note: All ClassElementEvaluation start with evaluating the name (or we fake it).
  1479. auto element_value = TRY(element.class_element_evaluation(interpreter, global_object, element.is_static() ? *class_constructor : *prototype));
  1480. if (element_value.has<PrivateElement>()) {
  1481. auto& container = element.is_static() ? static_private_methods : instance_private_methods;
  1482. auto& private_element = element_value.get<PrivateElement>();
  1483. auto added_to_existing = false;
  1484. // FIXME: We can skip this loop in most cases.
  1485. for (auto& existing : container) {
  1486. if (existing.key == private_element.key) {
  1487. VERIFY(existing.kind == PrivateElement::Kind::Accessor);
  1488. VERIFY(private_element.kind == PrivateElement::Kind::Accessor);
  1489. auto& accessor = private_element.value.as_accessor();
  1490. if (!accessor.getter())
  1491. existing.value.as_accessor().set_setter(accessor.setter());
  1492. else
  1493. existing.value.as_accessor().set_getter(accessor.getter());
  1494. added_to_existing = true;
  1495. }
  1496. }
  1497. if (!added_to_existing)
  1498. container.append(move(element_value.get<PrivateElement>()));
  1499. } else if (auto* class_field_definition_ptr = element_value.get_pointer<ClassElement::ClassFieldDefinition>()) {
  1500. if (element.is_static())
  1501. static_elements.append(move(*class_field_definition_ptr));
  1502. else
  1503. instance_fields.append(move(*class_field_definition_ptr));
  1504. } else if (element.class_element_kind() == ClassElement::ElementKind::StaticInitializer) {
  1505. // We use Completion to hold the ClassStaticBlockDefinition Record.
  1506. VERIFY(element_value.has<Completion>() && element_value.get<Completion>().value().has_value());
  1507. auto& element_object = element_value.get<Completion>().value()->as_object();
  1508. VERIFY(is<ECMAScriptFunctionObject>(element_object));
  1509. static_elements.append(static_cast<ECMAScriptFunctionObject*>(&element_object));
  1510. }
  1511. }
  1512. vm.running_execution_context().lexical_environment = environment;
  1513. restore_environment.disarm();
  1514. if (!binding_name.is_null())
  1515. MUST(class_scope->initialize_binding(global_object, binding_name, class_constructor));
  1516. for (auto& field : instance_fields)
  1517. class_constructor->add_field(field.name, field.initializer);
  1518. for (auto& private_method : instance_private_methods)
  1519. class_constructor->add_private_method(private_method);
  1520. for (auto& method : static_private_methods)
  1521. class_constructor->private_method_or_accessor_add(move(method));
  1522. for (auto& element : static_elements) {
  1523. TRY(element.visit(
  1524. [&](ClassElement::ClassFieldDefinition const& field) -> ThrowCompletionOr<void> {
  1525. return TRY(class_constructor->define_field(field.name, field.initializer));
  1526. },
  1527. [&](ECMAScriptFunctionObject* static_block_function) -> ThrowCompletionOr<void> {
  1528. // We discard any value returned here.
  1529. TRY(call(global_object, static_block_function, class_constructor_value));
  1530. return {};
  1531. }));
  1532. }
  1533. return Value(class_constructor);
  1534. }
  1535. // 15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-bindingclassdeclarationevaluation
  1536. ThrowCompletionOr<Value> ClassDeclaration::binding_class_declaration_evaluation(Interpreter& interpreter, GlobalObject& global_object) const
  1537. {
  1538. // 1. Let className be StringValue of BindingIdentifier.
  1539. auto class_name = m_class_expression->name();
  1540. VERIFY(!class_name.is_empty());
  1541. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1542. auto value = TRY(m_class_expression->class_definition_evaluation(interpreter, global_object, class_name, class_name));
  1543. // FIXME:
  1544. // 3. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1545. // 4. Let env be the running execution context's LexicalEnvironment.
  1546. auto* env = interpreter.lexical_environment();
  1547. // 5. Perform ? InitializeBoundName(className, value, env).
  1548. TRY(initialize_bound_name(global_object, class_name, value, env));
  1549. // 6. Return value.
  1550. return value;
  1551. }
  1552. void ASTNode::dump(int indent) const
  1553. {
  1554. print_indent(indent);
  1555. outln("{}", class_name());
  1556. }
  1557. void ScopeNode::dump(int indent) const
  1558. {
  1559. ASTNode::dump(indent);
  1560. if (!m_lexical_declarations.is_empty()) {
  1561. print_indent(indent + 1);
  1562. outln("(Lexical declarations)");
  1563. for (auto& declaration : m_lexical_declarations)
  1564. declaration.dump(indent + 2);
  1565. }
  1566. if (!m_var_declarations.is_empty()) {
  1567. print_indent(indent + 1);
  1568. outln("(Variable declarations)");
  1569. for (auto& declaration : m_var_declarations)
  1570. declaration.dump(indent + 2);
  1571. }
  1572. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1573. print_indent(indent + 1);
  1574. outln("(Hoisted functions via annexB extension)");
  1575. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1576. declaration.dump(indent + 2);
  1577. }
  1578. if (!m_children.is_empty()) {
  1579. print_indent(indent + 1);
  1580. outln("(Children)");
  1581. for (auto& child : children())
  1582. child.dump(indent + 2);
  1583. }
  1584. }
  1585. void BinaryExpression::dump(int indent) const
  1586. {
  1587. const char* op_string = nullptr;
  1588. switch (m_op) {
  1589. case BinaryOp::Addition:
  1590. op_string = "+";
  1591. break;
  1592. case BinaryOp::Subtraction:
  1593. op_string = "-";
  1594. break;
  1595. case BinaryOp::Multiplication:
  1596. op_string = "*";
  1597. break;
  1598. case BinaryOp::Division:
  1599. op_string = "/";
  1600. break;
  1601. case BinaryOp::Modulo:
  1602. op_string = "%";
  1603. break;
  1604. case BinaryOp::Exponentiation:
  1605. op_string = "**";
  1606. break;
  1607. case BinaryOp::StrictlyEquals:
  1608. op_string = "===";
  1609. break;
  1610. case BinaryOp::StrictlyInequals:
  1611. op_string = "!==";
  1612. break;
  1613. case BinaryOp::LooselyEquals:
  1614. op_string = "==";
  1615. break;
  1616. case BinaryOp::LooselyInequals:
  1617. op_string = "!=";
  1618. break;
  1619. case BinaryOp::GreaterThan:
  1620. op_string = ">";
  1621. break;
  1622. case BinaryOp::GreaterThanEquals:
  1623. op_string = ">=";
  1624. break;
  1625. case BinaryOp::LessThan:
  1626. op_string = "<";
  1627. break;
  1628. case BinaryOp::LessThanEquals:
  1629. op_string = "<=";
  1630. break;
  1631. case BinaryOp::BitwiseAnd:
  1632. op_string = "&";
  1633. break;
  1634. case BinaryOp::BitwiseOr:
  1635. op_string = "|";
  1636. break;
  1637. case BinaryOp::BitwiseXor:
  1638. op_string = "^";
  1639. break;
  1640. case BinaryOp::LeftShift:
  1641. op_string = "<<";
  1642. break;
  1643. case BinaryOp::RightShift:
  1644. op_string = ">>";
  1645. break;
  1646. case BinaryOp::UnsignedRightShift:
  1647. op_string = ">>>";
  1648. break;
  1649. case BinaryOp::In:
  1650. op_string = "in";
  1651. break;
  1652. case BinaryOp::InstanceOf:
  1653. op_string = "instanceof";
  1654. break;
  1655. }
  1656. print_indent(indent);
  1657. outln("{}", class_name());
  1658. m_lhs->dump(indent + 1);
  1659. print_indent(indent + 1);
  1660. outln("{}", op_string);
  1661. m_rhs->dump(indent + 1);
  1662. }
  1663. void LogicalExpression::dump(int indent) const
  1664. {
  1665. const char* op_string = nullptr;
  1666. switch (m_op) {
  1667. case LogicalOp::And:
  1668. op_string = "&&";
  1669. break;
  1670. case LogicalOp::Or:
  1671. op_string = "||";
  1672. break;
  1673. case LogicalOp::NullishCoalescing:
  1674. op_string = "??";
  1675. break;
  1676. }
  1677. print_indent(indent);
  1678. outln("{}", class_name());
  1679. m_lhs->dump(indent + 1);
  1680. print_indent(indent + 1);
  1681. outln("{}", op_string);
  1682. m_rhs->dump(indent + 1);
  1683. }
  1684. void UnaryExpression::dump(int indent) const
  1685. {
  1686. const char* op_string = nullptr;
  1687. switch (m_op) {
  1688. case UnaryOp::BitwiseNot:
  1689. op_string = "~";
  1690. break;
  1691. case UnaryOp::Not:
  1692. op_string = "!";
  1693. break;
  1694. case UnaryOp::Plus:
  1695. op_string = "+";
  1696. break;
  1697. case UnaryOp::Minus:
  1698. op_string = "-";
  1699. break;
  1700. case UnaryOp::Typeof:
  1701. op_string = "typeof ";
  1702. break;
  1703. case UnaryOp::Void:
  1704. op_string = "void ";
  1705. break;
  1706. case UnaryOp::Delete:
  1707. op_string = "delete ";
  1708. break;
  1709. }
  1710. print_indent(indent);
  1711. outln("{}", class_name());
  1712. print_indent(indent + 1);
  1713. outln("{}", op_string);
  1714. m_lhs->dump(indent + 1);
  1715. }
  1716. void CallExpression::dump(int indent) const
  1717. {
  1718. print_indent(indent);
  1719. if (is<NewExpression>(*this))
  1720. outln("CallExpression [new]");
  1721. else
  1722. outln("CallExpression");
  1723. m_callee->dump(indent + 1);
  1724. for (auto& argument : m_arguments)
  1725. argument.value->dump(indent + 1);
  1726. }
  1727. void SuperCall::dump(int indent) const
  1728. {
  1729. print_indent(indent);
  1730. outln("SuperCall");
  1731. for (auto& argument : m_arguments)
  1732. argument.value->dump(indent + 1);
  1733. }
  1734. void ClassDeclaration::dump(int indent) const
  1735. {
  1736. ASTNode::dump(indent);
  1737. m_class_expression->dump(indent + 1);
  1738. }
  1739. void ClassDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1740. {
  1741. if (!m_class_expression->name().is_empty())
  1742. callback(m_class_expression->name());
  1743. }
  1744. void ClassExpression::dump(int indent) const
  1745. {
  1746. print_indent(indent);
  1747. outln("ClassExpression: \"{}\"", m_name);
  1748. print_indent(indent);
  1749. outln("(Constructor)");
  1750. m_constructor->dump(indent + 1);
  1751. if (!m_super_class.is_null()) {
  1752. print_indent(indent);
  1753. outln("(Super Class)");
  1754. m_super_class->dump(indent + 1);
  1755. }
  1756. print_indent(indent);
  1757. outln("(Elements)");
  1758. for (auto& method : m_elements)
  1759. method.dump(indent + 1);
  1760. }
  1761. void ClassMethod::dump(int indent) const
  1762. {
  1763. ASTNode::dump(indent);
  1764. print_indent(indent);
  1765. outln("(Key)");
  1766. m_key->dump(indent + 1);
  1767. const char* kind_string = nullptr;
  1768. switch (m_kind) {
  1769. case Kind::Method:
  1770. kind_string = "Method";
  1771. break;
  1772. case Kind::Getter:
  1773. kind_string = "Getter";
  1774. break;
  1775. case Kind::Setter:
  1776. kind_string = "Setter";
  1777. break;
  1778. }
  1779. print_indent(indent);
  1780. outln("Kind: {}", kind_string);
  1781. print_indent(indent);
  1782. outln("Static: {}", is_static());
  1783. print_indent(indent);
  1784. outln("(Function)");
  1785. m_function->dump(indent + 1);
  1786. }
  1787. void ClassField::dump(int indent) const
  1788. {
  1789. ASTNode::dump(indent);
  1790. print_indent(indent);
  1791. outln("(Key)");
  1792. m_key->dump(indent + 1);
  1793. print_indent(indent);
  1794. outln("Static: {}", is_static());
  1795. if (m_initializer) {
  1796. print_indent(indent);
  1797. outln("(Initializer)");
  1798. m_initializer->dump(indent + 1);
  1799. }
  1800. }
  1801. void StaticInitializer::dump(int indent) const
  1802. {
  1803. ASTNode::dump(indent);
  1804. m_function_body->dump(indent + 1);
  1805. }
  1806. void StringLiteral::dump(int indent) const
  1807. {
  1808. print_indent(indent);
  1809. outln("StringLiteral \"{}\"", m_value);
  1810. }
  1811. void SuperExpression::dump(int indent) const
  1812. {
  1813. print_indent(indent);
  1814. outln("super");
  1815. }
  1816. void NumericLiteral::dump(int indent) const
  1817. {
  1818. print_indent(indent);
  1819. outln("NumericLiteral {}", m_value);
  1820. }
  1821. void BigIntLiteral::dump(int indent) const
  1822. {
  1823. print_indent(indent);
  1824. outln("BigIntLiteral {}", m_value);
  1825. }
  1826. void BooleanLiteral::dump(int indent) const
  1827. {
  1828. print_indent(indent);
  1829. outln("BooleanLiteral {}", m_value);
  1830. }
  1831. void NullLiteral::dump(int indent) const
  1832. {
  1833. print_indent(indent);
  1834. outln("null");
  1835. }
  1836. bool BindingPattern::contains_expression() const
  1837. {
  1838. for (auto& entry : entries) {
  1839. if (entry.initializer)
  1840. return true;
  1841. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1842. return true;
  1843. }
  1844. return false;
  1845. }
  1846. void BindingPattern::dump(int indent) const
  1847. {
  1848. print_indent(indent);
  1849. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1850. for (auto& entry : entries) {
  1851. print_indent(indent + 1);
  1852. outln("(Property)");
  1853. if (kind == Kind::Object) {
  1854. print_indent(indent + 2);
  1855. outln("(Identifier)");
  1856. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1857. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1858. } else {
  1859. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1860. }
  1861. } else if (entry.is_elision()) {
  1862. print_indent(indent + 2);
  1863. outln("(Elision)");
  1864. continue;
  1865. }
  1866. print_indent(indent + 2);
  1867. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1868. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1869. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1870. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1871. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1872. } else if (entry.alias.has<NonnullRefPtr<MemberExpression>>()) {
  1873. entry.alias.get<NonnullRefPtr<MemberExpression>>()->dump(indent + 3);
  1874. } else {
  1875. print_indent(indent + 3);
  1876. outln("<empty>");
  1877. }
  1878. if (entry.initializer) {
  1879. print_indent(indent + 2);
  1880. outln("(Initializer)");
  1881. entry.initializer->dump(indent + 3);
  1882. }
  1883. }
  1884. }
  1885. void FunctionNode::dump(int indent, String const& class_name) const
  1886. {
  1887. print_indent(indent);
  1888. auto is_async = m_kind == FunctionKind::Async || m_kind == FunctionKind::AsyncGenerator;
  1889. auto is_generator = m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator;
  1890. outln("{}{}{} '{}'", class_name, is_async ? " async" : "", is_generator ? "*" : "", name());
  1891. if (m_contains_direct_call_to_eval) {
  1892. print_indent(indent + 1);
  1893. outln("\033[31;1m(direct eval)\033[0m");
  1894. }
  1895. if (!m_parameters.is_empty()) {
  1896. print_indent(indent + 1);
  1897. outln("(Parameters)");
  1898. for (auto& parameter : m_parameters) {
  1899. print_indent(indent + 2);
  1900. if (parameter.is_rest)
  1901. out("...");
  1902. parameter.binding.visit(
  1903. [&](FlyString const& name) {
  1904. outln("{}", name);
  1905. },
  1906. [&](BindingPattern const& pattern) {
  1907. pattern.dump(indent + 2);
  1908. });
  1909. if (parameter.default_value)
  1910. parameter.default_value->dump(indent + 3);
  1911. }
  1912. }
  1913. print_indent(indent + 1);
  1914. outln("(Body)");
  1915. body().dump(indent + 2);
  1916. }
  1917. void FunctionDeclaration::dump(int indent) const
  1918. {
  1919. FunctionNode::dump(indent, class_name());
  1920. }
  1921. void FunctionDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1922. {
  1923. if (!name().is_empty())
  1924. callback(name());
  1925. }
  1926. void FunctionExpression::dump(int indent) const
  1927. {
  1928. FunctionNode::dump(indent, class_name());
  1929. }
  1930. void YieldExpression::dump(int indent) const
  1931. {
  1932. ASTNode::dump(indent);
  1933. if (argument())
  1934. argument()->dump(indent + 1);
  1935. }
  1936. void AwaitExpression::dump(int indent) const
  1937. {
  1938. ASTNode::dump(indent);
  1939. m_argument->dump(indent + 1);
  1940. }
  1941. void ReturnStatement::dump(int indent) const
  1942. {
  1943. ASTNode::dump(indent);
  1944. if (argument())
  1945. argument()->dump(indent + 1);
  1946. }
  1947. void IfStatement::dump(int indent) const
  1948. {
  1949. ASTNode::dump(indent);
  1950. print_indent(indent);
  1951. outln("If");
  1952. predicate().dump(indent + 1);
  1953. consequent().dump(indent + 1);
  1954. if (alternate()) {
  1955. print_indent(indent);
  1956. outln("Else");
  1957. alternate()->dump(indent + 1);
  1958. }
  1959. }
  1960. void WhileStatement::dump(int indent) const
  1961. {
  1962. ASTNode::dump(indent);
  1963. print_indent(indent);
  1964. outln("While");
  1965. test().dump(indent + 1);
  1966. body().dump(indent + 1);
  1967. }
  1968. void WithStatement::dump(int indent) const
  1969. {
  1970. ASTNode::dump(indent);
  1971. print_indent(indent + 1);
  1972. outln("Object");
  1973. object().dump(indent + 2);
  1974. print_indent(indent + 1);
  1975. outln("Body");
  1976. body().dump(indent + 2);
  1977. }
  1978. void DoWhileStatement::dump(int indent) const
  1979. {
  1980. ASTNode::dump(indent);
  1981. print_indent(indent);
  1982. outln("DoWhile");
  1983. test().dump(indent + 1);
  1984. body().dump(indent + 1);
  1985. }
  1986. void ForStatement::dump(int indent) const
  1987. {
  1988. ASTNode::dump(indent);
  1989. print_indent(indent);
  1990. outln("For");
  1991. if (init())
  1992. init()->dump(indent + 1);
  1993. if (test())
  1994. test()->dump(indent + 1);
  1995. if (update())
  1996. update()->dump(indent + 1);
  1997. body().dump(indent + 1);
  1998. }
  1999. void ForInStatement::dump(int indent) const
  2000. {
  2001. ASTNode::dump(indent);
  2002. print_indent(indent);
  2003. outln("ForIn");
  2004. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2005. rhs().dump(indent + 1);
  2006. body().dump(indent + 1);
  2007. }
  2008. void ForOfStatement::dump(int indent) const
  2009. {
  2010. ASTNode::dump(indent);
  2011. print_indent(indent);
  2012. outln("ForOf");
  2013. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2014. rhs().dump(indent + 1);
  2015. body().dump(indent + 1);
  2016. }
  2017. void ForAwaitOfStatement::dump(int indent) const
  2018. {
  2019. ASTNode::dump(indent);
  2020. print_indent(indent);
  2021. outln("ForAwaitOf");
  2022. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2023. m_rhs->dump(indent + 1);
  2024. m_body->dump(indent + 1);
  2025. }
  2026. // 13.1.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-identifiers-runtime-semantics-evaluation
  2027. Completion Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2028. {
  2029. InterpreterNodeScope node_scope { interpreter, *this };
  2030. // 1. Return ? ResolveBinding(StringValue of Identifier).
  2031. auto reference = TRY(interpreter.vm().resolve_binding(m_string));
  2032. // NOTE: The spec wants us to return the reference directly; this is not possible with ASTNode::execute() (short of letting it return a variant).
  2033. // So, instead of calling GetValue at the call site, we do it here.
  2034. return TRY(reference.get_value(global_object));
  2035. }
  2036. void Identifier::dump(int indent) const
  2037. {
  2038. print_indent(indent);
  2039. outln("Identifier \"{}\"", m_string);
  2040. }
  2041. Completion PrivateIdentifier::execute(Interpreter&, GlobalObject&) const
  2042. {
  2043. // Note: This should be handled by either the member expression this is part of
  2044. // or the binary expression in the case of `#foo in bar`.
  2045. VERIFY_NOT_REACHED();
  2046. }
  2047. void PrivateIdentifier::dump(int indent) const
  2048. {
  2049. print_indent(indent);
  2050. outln("PrivateIdentifier \"{}\"", m_string);
  2051. }
  2052. void SpreadExpression::dump(int indent) const
  2053. {
  2054. ASTNode::dump(indent);
  2055. m_target->dump(indent + 1);
  2056. }
  2057. Completion SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2058. {
  2059. InterpreterNodeScope node_scope { interpreter, *this };
  2060. return m_target->execute(interpreter, global_object);
  2061. }
  2062. // 13.2.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-this-keyword-runtime-semantics-evaluation
  2063. Completion ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2064. {
  2065. InterpreterNodeScope node_scope { interpreter, *this };
  2066. // 1. Return ? ResolveThisBinding().
  2067. return interpreter.vm().resolve_this_binding(global_object);
  2068. }
  2069. void ThisExpression::dump(int indent) const
  2070. {
  2071. ASTNode::dump(indent);
  2072. }
  2073. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  2074. Completion AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2075. {
  2076. InterpreterNodeScope node_scope { interpreter, *this };
  2077. if (m_op == AssignmentOp::Assignment) {
  2078. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  2079. return m_lhs.visit(
  2080. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  2081. [&](NonnullRefPtr<Expression> const& lhs) -> ThrowCompletionOr<Value> {
  2082. // a. Let lref be the result of evaluating LeftHandSideExpression.
  2083. // b. ReturnIfAbrupt(lref).
  2084. auto reference = TRY(lhs->to_reference(interpreter, global_object));
  2085. Value rhs_result;
  2086. // c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  2087. if (lhs->is_identifier()) {
  2088. // i. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2089. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  2090. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2091. }
  2092. // d. Else,
  2093. else {
  2094. // i. Let rref be the result of evaluating AssignmentExpression.
  2095. // ii. Let rval be ? GetValue(rref).
  2096. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2097. }
  2098. // e. Perform ? PutValue(lref, rval).
  2099. TRY(reference.put_value(global_object, rhs_result));
  2100. // f. Return rval.
  2101. return rhs_result;
  2102. },
  2103. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  2104. [&](NonnullRefPtr<BindingPattern> const& pattern) -> ThrowCompletionOr<Value> {
  2105. // 3. Let rref be the result of evaluating AssignmentExpression.
  2106. // 4. Let rval be ? GetValue(rref).
  2107. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2108. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern using rval as the argument.
  2109. TRY(interpreter.vm().destructuring_assignment_evaluation(pattern, rhs_result, global_object));
  2110. // 6. Return rval.
  2111. return rhs_result;
  2112. });
  2113. }
  2114. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  2115. // 1. Let lref be the result of evaluating LeftHandSideExpression.
  2116. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression>>();
  2117. auto reference = TRY(lhs_expression.to_reference(interpreter, global_object));
  2118. // 2. Let lval be ? GetValue(lref).
  2119. auto lhs_result = TRY(reference.get_value(global_object));
  2120. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  2121. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  2122. switch (m_op) {
  2123. // AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  2124. case AssignmentOp::AndAssignment:
  2125. // 3. Let lbool be ! ToBoolean(lval).
  2126. // 4. If lbool is false, return lval.
  2127. if (!lhs_result.to_boolean())
  2128. return lhs_result;
  2129. break;
  2130. // AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  2131. case AssignmentOp::OrAssignment:
  2132. // 3. Let lbool be ! ToBoolean(lval).
  2133. // 4. If lbool is true, return lval.
  2134. if (lhs_result.to_boolean())
  2135. return lhs_result;
  2136. break;
  2137. // AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  2138. case AssignmentOp::NullishAssignment:
  2139. // 3. If lval is neither undefined nor null, return lval.
  2140. if (!lhs_result.is_nullish())
  2141. return lhs_result;
  2142. break;
  2143. default:
  2144. VERIFY_NOT_REACHED();
  2145. }
  2146. Value rhs_result;
  2147. // 5. If IsAnonymousFunctionDefinition(AssignmentExpression) is true and IsIdentifierRef of LeftHandSideExpression is true, then
  2148. if (lhs_expression.is_identifier()) {
  2149. // a. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2150. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  2151. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2152. }
  2153. // 6. Else,
  2154. else {
  2155. // a. Let rref be the result of evaluating AssignmentExpression.
  2156. // b. Let rval be ? GetValue(rref).
  2157. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2158. }
  2159. // 7. Perform ? PutValue(lref, rval).
  2160. TRY(reference.put_value(global_object, rhs_result));
  2161. // 8. Return rval.
  2162. return rhs_result;
  2163. }
  2164. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  2165. // 3. Let rref be the result of evaluating AssignmentExpression.
  2166. // 4. Let rval be ? GetValue(rref).
  2167. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2168. // 5. Let assignmentOpText be the source text matched by AssignmentOperator.
  2169. // 6. Let opText be the sequence of Unicode code points associated with assignmentOpText in the following table:
  2170. // 7. Let r be ApplyStringOrNumericBinaryOperator(lval, opText, rval).
  2171. switch (m_op) {
  2172. case AssignmentOp::AdditionAssignment:
  2173. rhs_result = TRY(add(global_object, lhs_result, rhs_result));
  2174. break;
  2175. case AssignmentOp::SubtractionAssignment:
  2176. rhs_result = TRY(sub(global_object, lhs_result, rhs_result));
  2177. break;
  2178. case AssignmentOp::MultiplicationAssignment:
  2179. rhs_result = TRY(mul(global_object, lhs_result, rhs_result));
  2180. break;
  2181. case AssignmentOp::DivisionAssignment:
  2182. rhs_result = TRY(div(global_object, lhs_result, rhs_result));
  2183. break;
  2184. case AssignmentOp::ModuloAssignment:
  2185. rhs_result = TRY(mod(global_object, lhs_result, rhs_result));
  2186. break;
  2187. case AssignmentOp::ExponentiationAssignment:
  2188. rhs_result = TRY(exp(global_object, lhs_result, rhs_result));
  2189. break;
  2190. case AssignmentOp::BitwiseAndAssignment:
  2191. rhs_result = TRY(bitwise_and(global_object, lhs_result, rhs_result));
  2192. break;
  2193. case AssignmentOp::BitwiseOrAssignment:
  2194. rhs_result = TRY(bitwise_or(global_object, lhs_result, rhs_result));
  2195. break;
  2196. case AssignmentOp::BitwiseXorAssignment:
  2197. rhs_result = TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  2198. break;
  2199. case AssignmentOp::LeftShiftAssignment:
  2200. rhs_result = TRY(left_shift(global_object, lhs_result, rhs_result));
  2201. break;
  2202. case AssignmentOp::RightShiftAssignment:
  2203. rhs_result = TRY(right_shift(global_object, lhs_result, rhs_result));
  2204. break;
  2205. case AssignmentOp::UnsignedRightShiftAssignment:
  2206. rhs_result = TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  2207. break;
  2208. case AssignmentOp::Assignment:
  2209. case AssignmentOp::AndAssignment:
  2210. case AssignmentOp::OrAssignment:
  2211. case AssignmentOp::NullishAssignment:
  2212. VERIFY_NOT_REACHED();
  2213. }
  2214. // 8. Perform ? PutValue(lref, r).
  2215. TRY(reference.put_value(global_object, rhs_result));
  2216. // 9. Return r.
  2217. return rhs_result;
  2218. }
  2219. // 13.4.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-increment-operator-runtime-semantics-evaluation
  2220. // 13.4.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-decrement-operator-runtime-semantics-evaluation
  2221. // 13.4.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-increment-operator-runtime-semantics-evaluation
  2222. // 13.4.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-decrement-operator-runtime-semantics-evaluation
  2223. Completion UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2224. {
  2225. InterpreterNodeScope node_scope { interpreter, *this };
  2226. // 1. Let expr be the result of evaluating <Expression>.
  2227. auto reference = TRY(m_argument->to_reference(interpreter, global_object));
  2228. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  2229. auto old_value = TRY(reference.get_value(global_object));
  2230. old_value = TRY(old_value.to_numeric(global_object));
  2231. Value new_value;
  2232. switch (m_op) {
  2233. case UpdateOp::Increment:
  2234. // 3. If Type(oldValue) is Number, then
  2235. if (old_value.is_number()) {
  2236. // a. Let newValue be ! Number::add(oldValue, 1𝔽).
  2237. new_value = Value(old_value.as_double() + 1);
  2238. }
  2239. // 4. Else,
  2240. else {
  2241. // a. Assert: Type(oldValue) is BigInt.
  2242. // b. Let newValue be ! BigInt::add(oldValue, 1ℤ).
  2243. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  2244. }
  2245. break;
  2246. case UpdateOp::Decrement:
  2247. // 3. If Type(oldValue) is Number, then
  2248. if (old_value.is_number()) {
  2249. // a. Let newValue be ! Number::subtract(oldValue, 1𝔽).
  2250. new_value = Value(old_value.as_double() - 1);
  2251. }
  2252. // 4. Else,
  2253. else {
  2254. // a. Assert: Type(oldValue) is BigInt.
  2255. // b. Let newValue be ! BigInt::subtract(oldValue, 1ℤ).
  2256. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  2257. }
  2258. break;
  2259. default:
  2260. VERIFY_NOT_REACHED();
  2261. }
  2262. // 5. Perform ? PutValue(expr, newValue).
  2263. TRY(reference.put_value(global_object, new_value));
  2264. // 6. Return newValue.
  2265. // 6. Return oldValue.
  2266. return m_prefixed ? new_value : old_value;
  2267. }
  2268. void AssignmentExpression::dump(int indent) const
  2269. {
  2270. const char* op_string = nullptr;
  2271. switch (m_op) {
  2272. case AssignmentOp::Assignment:
  2273. op_string = "=";
  2274. break;
  2275. case AssignmentOp::AdditionAssignment:
  2276. op_string = "+=";
  2277. break;
  2278. case AssignmentOp::SubtractionAssignment:
  2279. op_string = "-=";
  2280. break;
  2281. case AssignmentOp::MultiplicationAssignment:
  2282. op_string = "*=";
  2283. break;
  2284. case AssignmentOp::DivisionAssignment:
  2285. op_string = "/=";
  2286. break;
  2287. case AssignmentOp::ModuloAssignment:
  2288. op_string = "%=";
  2289. break;
  2290. case AssignmentOp::ExponentiationAssignment:
  2291. op_string = "**=";
  2292. break;
  2293. case AssignmentOp::BitwiseAndAssignment:
  2294. op_string = "&=";
  2295. break;
  2296. case AssignmentOp::BitwiseOrAssignment:
  2297. op_string = "|=";
  2298. break;
  2299. case AssignmentOp::BitwiseXorAssignment:
  2300. op_string = "^=";
  2301. break;
  2302. case AssignmentOp::LeftShiftAssignment:
  2303. op_string = "<<=";
  2304. break;
  2305. case AssignmentOp::RightShiftAssignment:
  2306. op_string = ">>=";
  2307. break;
  2308. case AssignmentOp::UnsignedRightShiftAssignment:
  2309. op_string = ">>>=";
  2310. break;
  2311. case AssignmentOp::AndAssignment:
  2312. op_string = "&&=";
  2313. break;
  2314. case AssignmentOp::OrAssignment:
  2315. op_string = "||=";
  2316. break;
  2317. case AssignmentOp::NullishAssignment:
  2318. op_string = "\?\?=";
  2319. break;
  2320. }
  2321. ASTNode::dump(indent);
  2322. print_indent(indent + 1);
  2323. outln("{}", op_string);
  2324. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2325. m_rhs->dump(indent + 1);
  2326. }
  2327. void UpdateExpression::dump(int indent) const
  2328. {
  2329. const char* op_string = nullptr;
  2330. switch (m_op) {
  2331. case UpdateOp::Increment:
  2332. op_string = "++";
  2333. break;
  2334. case UpdateOp::Decrement:
  2335. op_string = "--";
  2336. break;
  2337. }
  2338. ASTNode::dump(indent);
  2339. if (m_prefixed) {
  2340. print_indent(indent + 1);
  2341. outln("{}", op_string);
  2342. }
  2343. m_argument->dump(indent + 1);
  2344. if (!m_prefixed) {
  2345. print_indent(indent + 1);
  2346. outln("{}", op_string);
  2347. }
  2348. }
  2349. // 14.3.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation
  2350. // 14.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-variable-statement-runtime-semantics-evaluation
  2351. Completion VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2352. {
  2353. InterpreterNodeScope node_scope { interpreter, *this };
  2354. for (auto& declarator : m_declarations) {
  2355. if (auto* init = declarator.init()) {
  2356. TRY(declarator.target().visit(
  2357. [&](NonnullRefPtr<Identifier> const& id) -> ThrowCompletionOr<void> {
  2358. auto reference = TRY(id->to_reference(interpreter, global_object));
  2359. auto initializer_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *init, id->string()));
  2360. VERIFY(!initializer_result.is_empty());
  2361. if (m_declaration_kind == DeclarationKind::Var)
  2362. return reference.put_value(global_object, initializer_result);
  2363. else
  2364. return reference.initialize_referenced_binding(global_object, initializer_result);
  2365. },
  2366. [&](NonnullRefPtr<BindingPattern> const& pattern) -> ThrowCompletionOr<void> {
  2367. auto initializer_result = TRY(init->execute(interpreter, global_object)).release_value();
  2368. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  2369. return interpreter.vm().binding_initialization(pattern, initializer_result, environment, global_object);
  2370. }));
  2371. } else if (m_declaration_kind != DeclarationKind::Var) {
  2372. VERIFY(declarator.target().has<NonnullRefPtr<Identifier>>());
  2373. auto& identifier = declarator.target().get<NonnullRefPtr<Identifier>>();
  2374. auto reference = TRY(identifier->to_reference(interpreter, global_object));
  2375. TRY(reference.initialize_referenced_binding(global_object, js_undefined()));
  2376. }
  2377. }
  2378. return normal_completion({});
  2379. }
  2380. Completion VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  2381. {
  2382. InterpreterNodeScope node_scope { interpreter, *this };
  2383. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  2384. VERIFY_NOT_REACHED();
  2385. }
  2386. void VariableDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  2387. {
  2388. for (auto& entry : declarations()) {
  2389. entry.target().template visit(
  2390. [&](const NonnullRefPtr<Identifier>& id) {
  2391. callback(id->string());
  2392. },
  2393. [&](const NonnullRefPtr<BindingPattern>& binding) {
  2394. binding->for_each_bound_name([&](const auto& name) {
  2395. callback(name);
  2396. });
  2397. });
  2398. }
  2399. }
  2400. void VariableDeclaration::dump(int indent) const
  2401. {
  2402. const char* declaration_kind_string = nullptr;
  2403. switch (m_declaration_kind) {
  2404. case DeclarationKind::Let:
  2405. declaration_kind_string = "Let";
  2406. break;
  2407. case DeclarationKind::Var:
  2408. declaration_kind_string = "Var";
  2409. break;
  2410. case DeclarationKind::Const:
  2411. declaration_kind_string = "Const";
  2412. break;
  2413. }
  2414. ASTNode::dump(indent);
  2415. print_indent(indent + 1);
  2416. outln("{}", declaration_kind_string);
  2417. for (auto& declarator : m_declarations)
  2418. declarator.dump(indent + 1);
  2419. }
  2420. void VariableDeclarator::dump(int indent) const
  2421. {
  2422. ASTNode::dump(indent);
  2423. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  2424. if (m_init)
  2425. m_init->dump(indent + 1);
  2426. }
  2427. void ObjectProperty::dump(int indent) const
  2428. {
  2429. ASTNode::dump(indent);
  2430. if (m_property_type == Type::Spread) {
  2431. print_indent(indent + 1);
  2432. outln("...Spreading");
  2433. m_key->dump(indent + 1);
  2434. } else {
  2435. m_key->dump(indent + 1);
  2436. m_value->dump(indent + 1);
  2437. }
  2438. }
  2439. void ObjectExpression::dump(int indent) const
  2440. {
  2441. ASTNode::dump(indent);
  2442. for (auto& property : m_properties) {
  2443. property.dump(indent + 1);
  2444. }
  2445. }
  2446. void ExpressionStatement::dump(int indent) const
  2447. {
  2448. ASTNode::dump(indent);
  2449. m_expression->dump(indent + 1);
  2450. }
  2451. Completion ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  2452. {
  2453. InterpreterNodeScope node_scope { interpreter, *this };
  2454. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  2455. VERIFY_NOT_REACHED();
  2456. }
  2457. // 13.2.5.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-evaluation
  2458. Completion ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2459. {
  2460. InterpreterNodeScope node_scope { interpreter, *this };
  2461. // 1. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
  2462. auto* object = Object::create(global_object, global_object.object_prototype());
  2463. // 2. Perform ? PropertyDefinitionEvaluation of PropertyDefinitionList with argument obj.
  2464. for (auto& property : m_properties) {
  2465. auto key = TRY(property.key().execute(interpreter, global_object)).release_value();
  2466. if (property.type() == ObjectProperty::Type::Spread) {
  2467. if (key.is_object() && is<Array>(key.as_object())) {
  2468. auto& array_to_spread = static_cast<Array&>(key.as_object());
  2469. for (auto& entry : array_to_spread.indexed_properties()) {
  2470. auto value = TRY(array_to_spread.get(entry.index()));
  2471. object->indexed_properties().put(entry.index(), value);
  2472. }
  2473. } else if (key.is_object()) {
  2474. auto& obj_to_spread = key.as_object();
  2475. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  2476. if (it.value.attributes.is_enumerable()) {
  2477. auto value = TRY(obj_to_spread.get(it.key));
  2478. object->define_direct_property(it.key, value, JS::default_attributes);
  2479. }
  2480. }
  2481. } else if (key.is_string()) {
  2482. auto& str_to_spread = key.as_string().string();
  2483. for (size_t i = 0; i < str_to_spread.length(); i++)
  2484. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  2485. }
  2486. continue;
  2487. }
  2488. auto value = TRY(property.value().execute(interpreter, global_object)).release_value();
  2489. if (value.is_function() && property.is_method())
  2490. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  2491. auto name = TRY(get_function_name(global_object, key));
  2492. if (property.type() == ObjectProperty::Type::Getter) {
  2493. name = String::formatted("get {}", name);
  2494. } else if (property.type() == ObjectProperty::Type::Setter) {
  2495. name = String::formatted("set {}", name);
  2496. }
  2497. update_function_name(value, name);
  2498. switch (property.type()) {
  2499. case ObjectProperty::Type::Getter:
  2500. VERIFY(value.is_function());
  2501. object->define_direct_accessor(TRY(PropertyKey::from_value(global_object, key)), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  2502. break;
  2503. case ObjectProperty::Type::Setter:
  2504. VERIFY(value.is_function());
  2505. object->define_direct_accessor(TRY(PropertyKey::from_value(global_object, key)), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2506. break;
  2507. case ObjectProperty::Type::KeyValue:
  2508. object->define_direct_property(TRY(PropertyKey::from_value(global_object, key)), value, JS::default_attributes);
  2509. break;
  2510. case ObjectProperty::Type::Spread:
  2511. default:
  2512. VERIFY_NOT_REACHED();
  2513. }
  2514. }
  2515. // 3. Return obj.
  2516. return Value { object };
  2517. }
  2518. void MemberExpression::dump(int indent) const
  2519. {
  2520. print_indent(indent);
  2521. outln("{}(computed={})", class_name(), is_computed());
  2522. m_object->dump(indent + 1);
  2523. m_property->dump(indent + 1);
  2524. }
  2525. String MemberExpression::to_string_approximation() const
  2526. {
  2527. String object_string = "<object>";
  2528. if (is<Identifier>(*m_object))
  2529. object_string = static_cast<Identifier const&>(*m_object).string();
  2530. if (is_computed())
  2531. return String::formatted("{}[<computed>]", object_string);
  2532. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2533. }
  2534. // 13.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-property-accessors-runtime-semantics-evaluation
  2535. Completion MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2536. {
  2537. InterpreterNodeScope node_scope { interpreter, *this };
  2538. auto reference = TRY(to_reference(interpreter, global_object));
  2539. return TRY(reference.get_value(global_object));
  2540. }
  2541. bool MemberExpression::ends_in_private_name() const
  2542. {
  2543. if (is_computed())
  2544. return false;
  2545. if (is<PrivateIdentifier>(*m_property))
  2546. return true;
  2547. if (is<MemberExpression>(*m_property))
  2548. return static_cast<MemberExpression const&>(*m_property).ends_in_private_name();
  2549. return false;
  2550. }
  2551. void OptionalChain::dump(int indent) const
  2552. {
  2553. print_indent(indent);
  2554. outln("{}", class_name());
  2555. m_base->dump(indent + 1);
  2556. for (auto& reference : m_references) {
  2557. reference.visit(
  2558. [&](Call const& call) {
  2559. print_indent(indent + 1);
  2560. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2561. for (auto& argument : call.arguments)
  2562. argument.value->dump(indent + 2);
  2563. },
  2564. [&](ComputedReference const& ref) {
  2565. print_indent(indent + 1);
  2566. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2567. ref.expression->dump(indent + 2);
  2568. },
  2569. [&](MemberReference const& ref) {
  2570. print_indent(indent + 1);
  2571. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2572. ref.identifier->dump(indent + 2);
  2573. },
  2574. [&](PrivateMemberReference const& ref) {
  2575. print_indent(indent + 1);
  2576. outln("PrivateMemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2577. ref.private_identifier->dump(indent + 2);
  2578. });
  2579. }
  2580. }
  2581. ThrowCompletionOr<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  2582. {
  2583. auto base_reference = TRY(m_base->to_reference(interpreter, global_object));
  2584. auto base = base_reference.is_unresolvable()
  2585. ? TRY(m_base->execute(interpreter, global_object)).release_value()
  2586. : TRY(base_reference.get_value(global_object));
  2587. for (auto& reference : m_references) {
  2588. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2589. if (is_optional && base.is_nullish())
  2590. return ReferenceAndValue { {}, js_undefined() };
  2591. auto expression = reference.visit(
  2592. [&](Call const& call) -> NonnullRefPtr<Expression> {
  2593. return create_ast_node<CallExpression>(source_range(),
  2594. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2595. call.arguments);
  2596. },
  2597. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  2598. return create_ast_node<MemberExpression>(source_range(),
  2599. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2600. ref.expression,
  2601. true);
  2602. },
  2603. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  2604. return create_ast_node<MemberExpression>(source_range(),
  2605. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2606. ref.identifier,
  2607. false);
  2608. },
  2609. [&](PrivateMemberReference const& ref) -> NonnullRefPtr<Expression> {
  2610. return create_ast_node<MemberExpression>(source_range(),
  2611. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2612. ref.private_identifier,
  2613. false);
  2614. });
  2615. if (is<CallExpression>(*expression)) {
  2616. base_reference = JS::Reference {};
  2617. base = TRY(expression->execute(interpreter, global_object)).release_value();
  2618. } else {
  2619. base_reference = TRY(expression->to_reference(interpreter, global_object));
  2620. base = TRY(base_reference.get_value(global_object));
  2621. }
  2622. }
  2623. return ReferenceAndValue { move(base_reference), base };
  2624. }
  2625. // 13.3.9.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-optional-chaining-evaluation
  2626. Completion OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2627. {
  2628. InterpreterNodeScope node_scope { interpreter, *this };
  2629. return TRY(to_reference_and_value(interpreter, global_object)).value;
  2630. }
  2631. ThrowCompletionOr<JS::Reference> OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  2632. {
  2633. return TRY(to_reference_and_value(interpreter, global_object)).reference;
  2634. }
  2635. void MetaProperty::dump(int indent) const
  2636. {
  2637. String name;
  2638. if (m_type == MetaProperty::Type::NewTarget)
  2639. name = "new.target";
  2640. else if (m_type == MetaProperty::Type::ImportMeta)
  2641. name = "import.meta";
  2642. else
  2643. VERIFY_NOT_REACHED();
  2644. print_indent(indent);
  2645. outln("{} {}", class_name(), name);
  2646. }
  2647. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2648. Completion MetaProperty::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2649. {
  2650. InterpreterNodeScope node_scope { interpreter, *this };
  2651. // NewTarget : new . target
  2652. if (m_type == MetaProperty::Type::NewTarget) {
  2653. // 1. Return GetNewTarget().
  2654. return interpreter.vm().get_new_target();
  2655. }
  2656. // ImportMeta : import . meta
  2657. if (m_type == MetaProperty::Type::ImportMeta) {
  2658. // TODO: Implement me :^)
  2659. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import.meta' in modules");
  2660. }
  2661. VERIFY_NOT_REACHED();
  2662. }
  2663. void ImportCall::dump(int indent) const
  2664. {
  2665. ASTNode::dump(indent);
  2666. print_indent(indent);
  2667. outln("(Specifier)");
  2668. m_specifier->dump(indent + 1);
  2669. if (m_options) {
  2670. outln("(Options)");
  2671. m_options->dump(indent + 1);
  2672. }
  2673. }
  2674. // 13.3.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation
  2675. Completion ImportCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2676. {
  2677. InterpreterNodeScope node_scope { interpreter, *this };
  2678. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import(...)' in modules");
  2679. }
  2680. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2681. Completion StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2682. {
  2683. InterpreterNodeScope node_scope { interpreter, *this };
  2684. // 1. Return the SV of StringLiteral as defined in 12.8.4.2.
  2685. return Value { js_string(interpreter.heap(), m_value) };
  2686. }
  2687. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2688. Completion NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2689. {
  2690. InterpreterNodeScope node_scope { interpreter, *this };
  2691. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2692. return Value(m_value);
  2693. }
  2694. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2695. Completion BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2696. {
  2697. InterpreterNodeScope node_scope { interpreter, *this };
  2698. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2699. Crypto::SignedBigInteger integer;
  2700. if (m_value[0] == '0' && m_value.length() >= 3) {
  2701. if (m_value[1] == 'x' || m_value[1] == 'X') {
  2702. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3))) };
  2703. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  2704. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3))) };
  2705. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  2706. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3))) };
  2707. }
  2708. }
  2709. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))) };
  2710. }
  2711. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2712. Completion BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2713. {
  2714. InterpreterNodeScope node_scope { interpreter, *this };
  2715. // 1. If BooleanLiteral is the token false, return false.
  2716. // 2. If BooleanLiteral is the token true, return true.
  2717. return Value(m_value);
  2718. }
  2719. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2720. Completion NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2721. {
  2722. InterpreterNodeScope node_scope { interpreter, *this };
  2723. // 1. Return null.
  2724. return js_null();
  2725. }
  2726. void RegExpLiteral::dump(int indent) const
  2727. {
  2728. print_indent(indent);
  2729. outln("{} (/{}/{})", class_name(), pattern(), flags());
  2730. }
  2731. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  2732. Completion RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2733. {
  2734. InterpreterNodeScope node_scope { interpreter, *this };
  2735. // 1. Let pattern be ! CodePointsToString(BodyText of RegularExpressionLiteral).
  2736. auto pattern = this->pattern();
  2737. // 2. Let flags be ! CodePointsToString(FlagText of RegularExpressionLiteral).
  2738. auto flags = this->flags();
  2739. // 3. Return RegExpCreate(pattern, flags).
  2740. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  2741. return Value { RegExpObject::create(global_object, move(regex), move(pattern), move(flags)) };
  2742. }
  2743. void ArrayExpression::dump(int indent) const
  2744. {
  2745. ASTNode::dump(indent);
  2746. for (auto& element : m_elements) {
  2747. if (element) {
  2748. element->dump(indent + 1);
  2749. } else {
  2750. print_indent(indent + 1);
  2751. outln("<empty>");
  2752. }
  2753. }
  2754. }
  2755. // 13.2.4.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-array-initializer-runtime-semantics-evaluation
  2756. Completion ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2757. {
  2758. InterpreterNodeScope node_scope { interpreter, *this };
  2759. // 1. Let array be ! ArrayCreate(0).
  2760. auto* array = MUST(Array::create(global_object, 0));
  2761. // 2. Let len be the result of performing ArrayAccumulation of ElementList with arguments array and 0.
  2762. // 3. ReturnIfAbrupt(len).
  2763. array->indexed_properties();
  2764. size_t index = 0;
  2765. for (auto& element : m_elements) {
  2766. auto value = Value();
  2767. if (element) {
  2768. value = TRY(element->execute(interpreter, global_object)).release_value();
  2769. if (is<SpreadExpression>(*element)) {
  2770. (void)TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  2771. array->indexed_properties().put(index++, iterator_value, default_attributes);
  2772. return {};
  2773. }));
  2774. continue;
  2775. }
  2776. }
  2777. array->indexed_properties().put(index++, value, default_attributes);
  2778. }
  2779. // 4. Return array.
  2780. return Value { array };
  2781. }
  2782. void TemplateLiteral::dump(int indent) const
  2783. {
  2784. ASTNode::dump(indent);
  2785. for (auto& expression : m_expressions)
  2786. expression.dump(indent + 1);
  2787. }
  2788. // 13.2.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-template-literals-runtime-semantics-evaluation
  2789. Completion TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2790. {
  2791. InterpreterNodeScope node_scope { interpreter, *this };
  2792. StringBuilder string_builder;
  2793. for (auto& expression : m_expressions) {
  2794. // 1. Let head be the TV of TemplateHead as defined in 12.8.6.
  2795. // 2. Let subRef be the result of evaluating Expression.
  2796. // 3. Let sub be ? GetValue(subRef).
  2797. auto sub = TRY(expression.execute(interpreter, global_object)).release_value();
  2798. // 4. Let middle be ? ToString(sub).
  2799. auto string = TRY(sub.to_string(global_object));
  2800. string_builder.append(string);
  2801. // 5. Let tail be the result of evaluating TemplateSpans.
  2802. // 6. ReturnIfAbrupt(tail).
  2803. }
  2804. // 7. Return the string-concatenation of head, middle, and tail.
  2805. return Value { js_string(interpreter.heap(), string_builder.build()) };
  2806. }
  2807. void TaggedTemplateLiteral::dump(int indent) const
  2808. {
  2809. ASTNode::dump(indent);
  2810. print_indent(indent + 1);
  2811. outln("(Tag)");
  2812. m_tag->dump(indent + 2);
  2813. print_indent(indent + 1);
  2814. outln("(Template Literal)");
  2815. m_template_literal->dump(indent + 2);
  2816. }
  2817. // 13.3.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-tagged-templates-runtime-semantics-evaluation
  2818. Completion TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2819. {
  2820. InterpreterNodeScope node_scope { interpreter, *this };
  2821. auto& vm = interpreter.vm();
  2822. auto tag = TRY(m_tag->execute(interpreter, global_object)).release_value();
  2823. auto& expressions = m_template_literal->expressions();
  2824. auto* strings = MUST(Array::create(global_object, 0));
  2825. MarkedValueList arguments(vm.heap());
  2826. arguments.append(strings);
  2827. for (size_t i = 0; i < expressions.size(); ++i) {
  2828. auto value = TRY(expressions[i].execute(interpreter, global_object)).release_value();
  2829. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  2830. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  2831. if (i % 2 == 0) {
  2832. strings->indexed_properties().append(value);
  2833. } else {
  2834. arguments.append(value);
  2835. }
  2836. }
  2837. auto* raw_strings = MUST(Array::create(global_object, 0));
  2838. for (auto& raw_string : m_template_literal->raw_strings()) {
  2839. auto value = TRY(raw_string.execute(interpreter, global_object)).release_value();
  2840. raw_strings->indexed_properties().append(value);
  2841. }
  2842. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  2843. return call(global_object, tag, js_undefined(), move(arguments));
  2844. }
  2845. void TryStatement::dump(int indent) const
  2846. {
  2847. ASTNode::dump(indent);
  2848. print_indent(indent);
  2849. outln("(Block)");
  2850. block().dump(indent + 1);
  2851. if (handler()) {
  2852. print_indent(indent);
  2853. outln("(Handler)");
  2854. handler()->dump(indent + 1);
  2855. }
  2856. if (finalizer()) {
  2857. print_indent(indent);
  2858. outln("(Finalizer)");
  2859. finalizer()->dump(indent + 1);
  2860. }
  2861. }
  2862. void CatchClause::dump(int indent) const
  2863. {
  2864. print_indent(indent);
  2865. m_parameter.visit(
  2866. [&](FlyString const& parameter) {
  2867. if (parameter.is_null())
  2868. outln("CatchClause");
  2869. else
  2870. outln("CatchClause ({})", parameter);
  2871. },
  2872. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2873. outln("CatchClause");
  2874. print_indent(indent);
  2875. outln("(Parameter)");
  2876. pattern->dump(indent + 2);
  2877. });
  2878. body().dump(indent + 1);
  2879. }
  2880. void ThrowStatement::dump(int indent) const
  2881. {
  2882. ASTNode::dump(indent);
  2883. argument().dump(indent + 1);
  2884. }
  2885. // 14.15.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-try-statement-runtime-semantics-evaluation
  2886. Completion TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2887. {
  2888. InterpreterNodeScope node_scope { interpreter, *this };
  2889. auto& vm = interpreter.vm();
  2890. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  2891. auto catch_clause_evaluation = [&](Value thrown_value) {
  2892. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  2893. auto* old_environment = vm.running_execution_context().lexical_environment;
  2894. // 2. Let catchEnv be NewDeclarativeEnvironment(oldEnv).
  2895. auto* catch_environment = new_declarative_environment(*old_environment);
  2896. m_handler->parameter().visit(
  2897. [&](FlyString const& parameter) {
  2898. // 3. For each element argName of the BoundNames of CatchParameter, do
  2899. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  2900. MUST(catch_environment->create_mutable_binding(global_object, parameter, false));
  2901. },
  2902. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2903. // 3. For each element argName of the BoundNames of CatchParameter, do
  2904. pattern->for_each_bound_name([&](auto& name) {
  2905. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  2906. MUST(catch_environment->create_mutable_binding(global_object, name, false));
  2907. });
  2908. });
  2909. // 4. Set the running execution context's LexicalEnvironment to catchEnv.
  2910. vm.running_execution_context().lexical_environment = catch_environment;
  2911. // 5. Let status be BindingInitialization of CatchParameter with arguments thrownValue and catchEnv.
  2912. auto status = m_handler->parameter().visit(
  2913. [&](FlyString const& parameter) {
  2914. return catch_environment->initialize_binding(global_object, parameter, thrown_value);
  2915. },
  2916. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2917. return vm.binding_initialization(pattern, thrown_value, catch_environment, global_object);
  2918. });
  2919. // 6. If status is an abrupt completion, then
  2920. if (status.is_error()) {
  2921. // a. Set the running execution context's LexicalEnvironment to oldEnv.
  2922. vm.running_execution_context().lexical_environment = old_environment;
  2923. // b. Return Completion(status).
  2924. return status.release_error();
  2925. }
  2926. // 7. Let B be the result of evaluating Block.
  2927. auto handler_result = m_handler->body().execute(interpreter, global_object);
  2928. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  2929. vm.running_execution_context().lexical_environment = old_environment;
  2930. // 9. Return Completion(B).
  2931. return handler_result;
  2932. };
  2933. Completion result;
  2934. // 1. Let B be the result of evaluating Block.
  2935. auto block_result = m_block->execute(interpreter, global_object);
  2936. // TryStatement : try Block Catch
  2937. // TryStatement : try Block Catch Finally
  2938. if (m_handler) {
  2939. vm.clear_exception();
  2940. // 2. If B.[[Type]] is throw, let C be CatchClauseEvaluation of Catch with argument B.[[Value]].
  2941. if (block_result.type() == Completion::Type::Throw)
  2942. result = catch_clause_evaluation(*block_result.value());
  2943. // 3. Else, let C be B.
  2944. else
  2945. result = move(block_result);
  2946. } else {
  2947. // TryStatement : try Block Finally
  2948. // This variant doesn't have C & uses B in the finalizer step.
  2949. result = move(block_result);
  2950. }
  2951. // TryStatement : try Block Finally
  2952. // TryStatement : try Block Catch Finally
  2953. if (m_finalizer) {
  2954. // NOTE: Temporary until VM::exception() is removed
  2955. // Keep, if any, and then clear the current exception so we can
  2956. // execute() the finalizer without an exception in our way.
  2957. auto* previous_exception = vm.exception();
  2958. vm.clear_exception();
  2959. // 4. Let F be the result of evaluating Finally.
  2960. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2961. // 5. If F.[[Type]] is normal, set F to C.
  2962. if (finalizer_result.type() == Completion::Type::Normal)
  2963. finalizer_result = move(result);
  2964. // NOTE: Temporary until VM::exception() is removed
  2965. // If we previously had an exception and we're carrying over
  2966. // the catch block completion, restore it.
  2967. if (finalizer_result.type() == Completion::Type::Normal && previous_exception)
  2968. vm.set_exception(*previous_exception);
  2969. // 6. Return Completion(UpdateEmpty(F, undefined)).
  2970. return finalizer_result.update_empty(js_undefined());
  2971. }
  2972. // 4. Return Completion(UpdateEmpty(C, undefined)).
  2973. return result.update_empty(js_undefined());
  2974. }
  2975. Completion CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2976. {
  2977. InterpreterNodeScope node_scope { interpreter, *this };
  2978. // NOTE: CatchClause execution is handled by TryStatement.
  2979. VERIFY_NOT_REACHED();
  2980. return {};
  2981. }
  2982. // 14.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-throw-statement-runtime-semantics-evaluation
  2983. Completion ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2984. {
  2985. InterpreterNodeScope node_scope { interpreter, *this };
  2986. // 1. Let exprRef be the result of evaluating Expression.
  2987. // 2. Let exprValue be ? GetValue(exprRef).
  2988. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  2989. // 3. Return ThrowCompletion(exprValue).
  2990. // TODO: Remove this once we get rid of VM::exception()
  2991. interpreter.vm().throw_exception(global_object, value);
  2992. return throw_completion(value);
  2993. }
  2994. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  2995. // BreakableStatement : SwitchStatement
  2996. Completion SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2997. {
  2998. // 1. Let newLabelSet be a new empty List.
  2999. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  3000. return labelled_evaluation(interpreter, global_object, *this, {});
  3001. }
  3002. // NOTE: Since we don't have the 'BreakableStatement' from the spec as a separate ASTNode that wraps IterationStatement / SwitchStatement,
  3003. // execute() needs to take care of LabelledEvaluation, which in turn calls execute_impl().
  3004. // 14.12.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-switch-statement-runtime-semantics-evaluation
  3005. Completion SwitchStatement::execute_impl(Interpreter& interpreter, GlobalObject& global_object) const
  3006. {
  3007. InterpreterNodeScope node_scope { interpreter, *this };
  3008. auto& vm = interpreter.vm();
  3009. // 14.12.3 CaseClauseIsSelected ( C, input ), https://tc39.es/ecma262/#sec-runtime-semantics-caseclauseisselected
  3010. auto case_clause_is_selected = [&](auto const& case_clause, auto input) -> ThrowCompletionOr<bool> {
  3011. // 1. Assert: C is an instance of the production CaseClause : case Expression : StatementList[opt] .
  3012. VERIFY(case_clause.test());
  3013. // 2. Let exprRef be the result of evaluating the Expression of C.
  3014. // 3. Let clauseSelector be ? GetValue(exprRef).
  3015. auto clause_selector = TRY(case_clause.test()->execute(interpreter, global_object)).release_value();
  3016. // 4. Return IsStrictlyEqual(input, clauseSelector).
  3017. return is_strictly_equal(input, clause_selector);
  3018. };
  3019. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  3020. auto case_block_evaluation = [&](auto input) {
  3021. // CaseBlock : { }
  3022. if (m_cases.is_empty()) {
  3023. // 1. Return NormalCompletion(undefined).
  3024. return normal_completion(js_undefined());
  3025. }
  3026. NonnullRefPtrVector<SwitchCase> case_clauses_1;
  3027. NonnullRefPtrVector<SwitchCase> case_clauses_2;
  3028. RefPtr<SwitchCase> default_clause;
  3029. for (auto const& switch_case : m_cases) {
  3030. if (!switch_case.test())
  3031. default_clause = switch_case;
  3032. else if (!default_clause)
  3033. case_clauses_1.append(switch_case);
  3034. else
  3035. case_clauses_2.append(switch_case);
  3036. }
  3037. // CaseBlock : { CaseClauses }
  3038. if (!default_clause) {
  3039. VERIFY(!case_clauses_1.is_empty());
  3040. VERIFY(case_clauses_2.is_empty());
  3041. // 1. Let V be undefined.
  3042. auto last_value = js_undefined();
  3043. // 2. Let A be the List of CaseClause items in CaseClauses, in source text order.
  3044. // NOTE: A is case_clauses_1.
  3045. // 3. Let found be false.
  3046. auto found = false;
  3047. // 4. For each CaseClause C of A, do
  3048. for (auto const& case_clause : case_clauses_1) {
  3049. // a. If found is false, then
  3050. if (!found) {
  3051. // i. Set found to ? CaseClauseIsSelected(C, input).
  3052. found = TRY(case_clause_is_selected(case_clause, input));
  3053. }
  3054. // b. If found is true, then
  3055. if (found) {
  3056. // i. Let R be the result of evaluating C.
  3057. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3058. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3059. if (result.value().has_value())
  3060. last_value = *result.value();
  3061. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3062. if (result.is_abrupt())
  3063. return result.update_empty(last_value);
  3064. }
  3065. }
  3066. // 5. Return NormalCompletion(V).
  3067. return normal_completion(last_value);
  3068. }
  3069. // CaseBlock : { CaseClauses[opt] DefaultClause CaseClauses[opt] }
  3070. else {
  3071. // 1. Let V be undefined.
  3072. auto last_value = js_undefined();
  3073. // 2. If the first CaseClauses is present, then
  3074. // a. Let A be the List of CaseClause items in the first CaseClauses, in source text order.
  3075. // 3. Else,
  3076. // a. Let A be « ».
  3077. // NOTE: A is case_clauses_1.
  3078. // 4. Let found be false.
  3079. auto found = false;
  3080. // 5. For each CaseClause C of A, do
  3081. for (auto const& case_clause : case_clauses_1) {
  3082. // a. If found is false, then
  3083. if (!found) {
  3084. // i. Set found to ? CaseClauseIsSelected(C, input).
  3085. found = TRY(case_clause_is_selected(case_clause, input));
  3086. }
  3087. // b. If found is true, then
  3088. if (found) {
  3089. // i. Let R be the result of evaluating C.
  3090. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3091. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3092. if (result.value().has_value())
  3093. last_value = *result.value();
  3094. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3095. if (result.is_abrupt())
  3096. return result.update_empty(last_value);
  3097. }
  3098. }
  3099. // 6. Let foundInB be false.
  3100. auto found_in_b = false;
  3101. // 7. If the second CaseClauses is present, then
  3102. // a. Let B be the List of CaseClause items in the second CaseClauses, in source text order.
  3103. // 8. Else,
  3104. // a. Let B be « ».
  3105. // NOTE: B is case_clauses_2.
  3106. // 9. If found is false, then
  3107. if (!found) {
  3108. // a. For each CaseClause C of B, do
  3109. for (auto const& case_clause : case_clauses_2) {
  3110. // i. If foundInB is false, then
  3111. if (!found_in_b) {
  3112. // 1. Set foundInB to ? CaseClauseIsSelected(C, input).
  3113. found_in_b = TRY(case_clause_is_selected(case_clause, input));
  3114. }
  3115. // ii. If foundInB is true, then
  3116. if (found_in_b) {
  3117. // 1. Let R be the result of evaluating CaseClause C.
  3118. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3119. // 2. If R.[[Value]] is not empty, set V to R.[[Value]].
  3120. if (result.value().has_value())
  3121. last_value = *result.value();
  3122. // 3. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3123. if (result.is_abrupt())
  3124. return result.update_empty(last_value);
  3125. }
  3126. }
  3127. }
  3128. // 10. If foundInB is true, return NormalCompletion(V).
  3129. if (found_in_b)
  3130. return normal_completion(last_value);
  3131. // 11. Let R be the result of evaluating DefaultClause.
  3132. auto result = default_clause->evaluate_statements(interpreter, global_object);
  3133. // 12. If R.[[Value]] is not empty, set V to R.[[Value]].
  3134. if (result.value().has_value())
  3135. last_value = *result.value();
  3136. // 13. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3137. if (result.is_abrupt())
  3138. return result.update_empty(last_value);
  3139. // 14. NOTE: The following is another complete iteration of the second CaseClauses.
  3140. // 15. For each CaseClause C of B, do
  3141. for (auto const& case_clause : case_clauses_2) {
  3142. // a. Let R be the result of evaluating CaseClause C.
  3143. result = case_clause.evaluate_statements(interpreter, global_object);
  3144. // b. If R.[[Value]] is not empty, set V to R.[[Value]].
  3145. if (result.value().has_value())
  3146. last_value = *result.value();
  3147. // c. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3148. if (result.is_abrupt())
  3149. return result.update_empty(last_value);
  3150. }
  3151. // 16. Return NormalCompletion(V).
  3152. return normal_completion(last_value);
  3153. }
  3154. VERIFY_NOT_REACHED();
  3155. };
  3156. // SwitchStatement : switch ( Expression ) CaseBlock
  3157. // 1. Let exprRef be the result of evaluating Expression.
  3158. // 2. Let switchValue be ? GetValue(exprRef).
  3159. auto switch_value = TRY(m_discriminant->execute(interpreter, global_object)).release_value();
  3160. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  3161. auto* old_environment = interpreter.lexical_environment();
  3162. // Optimization: Avoid creating a lexical environment if there are no lexical declarations.
  3163. if (has_lexical_declarations()) {
  3164. // 4. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
  3165. auto* block_environment = new_declarative_environment(*old_environment);
  3166. // 5. Perform BlockDeclarationInstantiation(CaseBlock, blockEnv).
  3167. block_declaration_instantiation(global_object, block_environment);
  3168. // 6. Set the running execution context's LexicalEnvironment to blockEnv.
  3169. vm.running_execution_context().lexical_environment = block_environment;
  3170. }
  3171. // 7. Let R be CaseBlockEvaluation of CaseBlock with argument switchValue.
  3172. auto result = case_block_evaluation(switch_value);
  3173. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  3174. vm.running_execution_context().lexical_environment = old_environment;
  3175. // 9. Return R.
  3176. return result;
  3177. }
  3178. Completion SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  3179. {
  3180. InterpreterNodeScope node_scope { interpreter, *this };
  3181. // NOTE: SwitchCase execution is handled by SwitchStatement.
  3182. VERIFY_NOT_REACHED();
  3183. return {};
  3184. }
  3185. // 14.9.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-break-statement-runtime-semantics-evaluation
  3186. Completion BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3187. {
  3188. InterpreterNodeScope node_scope { interpreter, *this };
  3189. // BreakStatement : break ;
  3190. if (m_target_label.is_null()) {
  3191. // 1. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  3192. return { Completion::Type::Break, {}, {} };
  3193. }
  3194. // BreakStatement : break LabelIdentifier ;
  3195. // 1. Let label be the StringValue of LabelIdentifier.
  3196. // 2. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: label }.
  3197. return { Completion::Type::Break, {}, m_target_label };
  3198. }
  3199. // 14.8.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-continue-statement-runtime-semantics-evaluation
  3200. Completion ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3201. {
  3202. InterpreterNodeScope node_scope { interpreter, *this };
  3203. // ContinueStatement : continue ;
  3204. if (m_target_label.is_null()) {
  3205. // 1. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }.
  3206. return { Completion::Type::Continue, {}, {} };
  3207. }
  3208. // ContinueStatement : continue LabelIdentifier ;
  3209. // 1. Let label be the StringValue of LabelIdentifier.
  3210. // 2. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }.
  3211. return { Completion::Type::Continue, {}, m_target_label };
  3212. }
  3213. void SwitchStatement::dump(int indent) const
  3214. {
  3215. ASTNode::dump(indent);
  3216. m_discriminant->dump(indent + 1);
  3217. for (auto& switch_case : m_cases) {
  3218. switch_case.dump(indent + 1);
  3219. }
  3220. }
  3221. void SwitchCase::dump(int indent) const
  3222. {
  3223. print_indent(indent + 1);
  3224. if (m_test) {
  3225. outln("(Test)");
  3226. m_test->dump(indent + 2);
  3227. } else {
  3228. outln("(Default)");
  3229. }
  3230. print_indent(indent + 1);
  3231. outln("(Consequent)");
  3232. ScopeNode::dump(indent + 2);
  3233. }
  3234. // 13.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-conditional-operator-runtime-semantics-evaluation
  3235. Completion ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3236. {
  3237. InterpreterNodeScope node_scope { interpreter, *this };
  3238. // 1. Let lref be the result of evaluating ShortCircuitExpression.
  3239. // 2. Let lval be ! ToBoolean(? GetValue(lref)).
  3240. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  3241. // 3. If lval is true, then
  3242. if (test_result.to_boolean()) {
  3243. // a. Let trueRef be the result of evaluating the first AssignmentExpression.
  3244. // b. Return ? GetValue(trueRef).
  3245. return m_consequent->execute(interpreter, global_object);
  3246. }
  3247. // 4. Else,
  3248. else {
  3249. // a. Let falseRef be the result of evaluating the second AssignmentExpression.
  3250. // b. Return ? GetValue(falseRef).
  3251. return m_alternate->execute(interpreter, global_object);
  3252. }
  3253. }
  3254. void ConditionalExpression::dump(int indent) const
  3255. {
  3256. ASTNode::dump(indent);
  3257. print_indent(indent + 1);
  3258. outln("(Test)");
  3259. m_test->dump(indent + 2);
  3260. print_indent(indent + 1);
  3261. outln("(Consequent)");
  3262. m_consequent->dump(indent + 2);
  3263. print_indent(indent + 1);
  3264. outln("(Alternate)");
  3265. m_alternate->dump(indent + 2);
  3266. }
  3267. void SequenceExpression::dump(int indent) const
  3268. {
  3269. ASTNode::dump(indent);
  3270. for (auto& expression : m_expressions)
  3271. expression.dump(indent + 1);
  3272. }
  3273. // 13.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-comma-operator-runtime-semantics-evaluation
  3274. Completion SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3275. {
  3276. InterpreterNodeScope node_scope { interpreter, *this };
  3277. // NOTE: Not sure why the last node is an AssignmentExpression in the spec :yakfused:
  3278. // 1. Let lref be the result of evaluating Expression.
  3279. // 2. Perform ? GetValue(lref).
  3280. // 3. Let rref be the result of evaluating AssignmentExpression.
  3281. // 4. Return ? GetValue(rref).
  3282. Value last_value;
  3283. for (auto const& expression : m_expressions)
  3284. last_value = TRY(expression.execute(interpreter, global_object)).release_value();
  3285. return { move(last_value) };
  3286. }
  3287. // 14.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-debugger-statement-runtime-semantics-evaluation
  3288. Completion DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3289. {
  3290. InterpreterNodeScope node_scope { interpreter, *this };
  3291. Completion result;
  3292. // 1. If an implementation-defined debugging facility is available and enabled, then
  3293. if (false) {
  3294. // a. Perform an implementation-defined debugging action.
  3295. // b. Let result be an implementation-defined Completion value.
  3296. }
  3297. // 2. Else,
  3298. else {
  3299. // a. Let result be NormalCompletion(empty).
  3300. result = normal_completion({});
  3301. }
  3302. // 3. Return result.
  3303. return result;
  3304. }
  3305. void ScopeNode::for_each_lexically_scoped_declaration(IteratorOrVoidFunction<Declaration const&>&& callback) const
  3306. {
  3307. for (auto& declaration : m_lexical_declarations) {
  3308. if (callback(declaration) == IterationDecision::Break)
  3309. break;
  3310. }
  3311. }
  3312. void ScopeNode::for_each_lexically_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  3313. {
  3314. auto running = true;
  3315. for (auto& declaration : m_lexical_declarations) {
  3316. declaration.for_each_bound_name([&](auto const& name) {
  3317. if (callback(name) == IterationDecision::Break) {
  3318. running = false;
  3319. return IterationDecision::Break;
  3320. }
  3321. return IterationDecision::Continue;
  3322. });
  3323. if (!running)
  3324. break;
  3325. }
  3326. }
  3327. void ScopeNode::for_each_var_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  3328. {
  3329. auto running = true;
  3330. for (auto& declaration : m_var_declarations) {
  3331. declaration.for_each_bound_name([&](auto const& name) {
  3332. if (callback(name) == IterationDecision::Break) {
  3333. running = false;
  3334. return IterationDecision::Break;
  3335. }
  3336. return IterationDecision::Continue;
  3337. });
  3338. if (!running)
  3339. break;
  3340. }
  3341. }
  3342. void ScopeNode::for_each_var_function_declaration_in_reverse_order(IteratorOrVoidFunction<FunctionDeclaration const&>&& callback) const
  3343. {
  3344. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  3345. auto& declaration = m_var_declarations[i];
  3346. if (is<FunctionDeclaration>(declaration)) {
  3347. if (callback(static_cast<FunctionDeclaration const&>(declaration)) == IterationDecision::Break)
  3348. break;
  3349. }
  3350. }
  3351. }
  3352. void ScopeNode::for_each_var_scoped_variable_declaration(IteratorOrVoidFunction<VariableDeclaration const&>&& callback) const
  3353. {
  3354. for (auto& declaration : m_var_declarations) {
  3355. if (!is<FunctionDeclaration>(declaration)) {
  3356. VERIFY(is<VariableDeclaration>(declaration));
  3357. if (callback(static_cast<VariableDeclaration const&>(declaration)) == IterationDecision::Break)
  3358. break;
  3359. }
  3360. }
  3361. }
  3362. void ScopeNode::for_each_function_hoistable_with_annexB_extension(IteratorOrVoidFunction<FunctionDeclaration&>&& callback) const
  3363. {
  3364. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  3365. // We need const_cast here since it might have to set a property on function declaration.
  3366. if (callback(const_cast<FunctionDeclaration&>(function)) == IterationDecision::Break)
  3367. break;
  3368. }
  3369. }
  3370. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration> declaration)
  3371. {
  3372. m_lexical_declarations.append(move(declaration));
  3373. }
  3374. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration> declaration)
  3375. {
  3376. m_var_declarations.append(move(declaration));
  3377. }
  3378. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declaration)
  3379. {
  3380. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  3381. }
  3382. // 16.2.1.11 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-module-semantics-runtime-semantics-evaluation
  3383. Completion ImportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3384. {
  3385. InterpreterNodeScope node_scope { interpreter, *this };
  3386. dbgln("Modules are not fully supported yet!");
  3387. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import' in modules");
  3388. }
  3389. // 16.2.3.7 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation
  3390. Completion ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3391. {
  3392. InterpreterNodeScope node_scope { interpreter, *this };
  3393. if (m_statement) {
  3394. // 1. Return the result of evaluating <Thing>.
  3395. return m_statement->execute(interpreter, global_object);
  3396. }
  3397. // 1. Return NormalCompletion(empty).
  3398. return normal_completion({});
  3399. }
  3400. static void dump_assert_clauses(ModuleRequest const& request)
  3401. {
  3402. if (!request.assertions.is_empty()) {
  3403. out("[ ");
  3404. for (auto& assertion : request.assertions)
  3405. out("{}: {}, ", assertion.key, assertion.value);
  3406. out(" ]");
  3407. }
  3408. }
  3409. void ExportStatement::dump(int indent) const
  3410. {
  3411. ASTNode::dump(indent);
  3412. print_indent(indent + 1);
  3413. outln("(ExportEntries)");
  3414. auto string_or_null = [](String const& string) -> String {
  3415. if (string.is_empty()) {
  3416. return "null";
  3417. }
  3418. return String::formatted("\"{}\"", string);
  3419. };
  3420. for (auto& entry : m_entries) {
  3421. print_indent(indent + 2);
  3422. out("ModuleRequest: {}", entry.module_request.module_specifier);
  3423. dump_assert_clauses(entry.module_request);
  3424. outln(", ImportName: {}, LocalName: {}, ExportName: {}",
  3425. entry.kind == ExportEntry::Kind::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null",
  3426. entry.kind != ExportEntry::Kind::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null",
  3427. string_or_null(entry.export_name));
  3428. }
  3429. }
  3430. void ImportStatement::dump(int indent) const
  3431. {
  3432. ASTNode::dump(indent);
  3433. print_indent(indent + 1);
  3434. if (m_entries.is_empty()) {
  3435. // direct from "module" import
  3436. outln("Entire module '{}'", m_module_request.module_specifier);
  3437. dump_assert_clauses(m_module_request);
  3438. } else {
  3439. outln("(ExportEntries) from {}", m_module_request.module_specifier);
  3440. dump_assert_clauses(m_module_request);
  3441. for (auto& entry : m_entries) {
  3442. print_indent(indent + 2);
  3443. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  3444. }
  3445. }
  3446. }
  3447. bool ExportStatement::has_export(StringView export_name) const
  3448. {
  3449. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3450. return entry.export_name == export_name;
  3451. });
  3452. }
  3453. bool ImportStatement::has_bound_name(StringView name) const
  3454. {
  3455. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3456. return entry.local_name == name;
  3457. });
  3458. }
  3459. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  3460. void ScopeNode::block_declaration_instantiation(GlobalObject& global_object, Environment* environment) const
  3461. {
  3462. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  3463. VERIFY(environment);
  3464. auto* private_environment = global_object.vm().running_execution_context().private_environment;
  3465. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3466. auto is_constant_declaration = declaration.is_constant_declaration();
  3467. declaration.for_each_bound_name([&](auto const& name) {
  3468. if (is_constant_declaration) {
  3469. MUST(environment->create_immutable_binding(global_object, name, true));
  3470. } else {
  3471. if (!MUST(environment->has_binding(name)))
  3472. MUST(environment->create_mutable_binding(global_object, name, false));
  3473. }
  3474. });
  3475. if (is<FunctionDeclaration>(declaration)) {
  3476. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  3477. auto* function = ECMAScriptFunctionObject::create(global_object, function_declaration.name(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  3478. VERIFY(is<DeclarativeEnvironment>(*environment));
  3479. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, global_object, function_declaration.name(), function);
  3480. }
  3481. });
  3482. }
  3483. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  3484. ThrowCompletionOr<void> Program::global_declaration_instantiation(Interpreter& interpreter, GlobalObject& global_object, GlobalEnvironment& global_environment) const
  3485. {
  3486. for_each_lexically_declared_name([&](FlyString const& name) {
  3487. if (global_environment.has_var_declaration(name) || global_environment.has_lexical_declaration(name)) {
  3488. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3489. return IterationDecision::Break;
  3490. }
  3491. auto restricted_global_or_error = global_environment.has_restricted_global_property(name);
  3492. if (restricted_global_or_error.is_error())
  3493. return IterationDecision::Break;
  3494. auto restricted_global = restricted_global_or_error.release_value();
  3495. if (restricted_global)
  3496. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::RestrictedGlobalProperty, name);
  3497. return IterationDecision::Continue;
  3498. });
  3499. if (auto* exception = interpreter.exception())
  3500. return throw_completion(exception->value());
  3501. for_each_var_declared_name([&](auto const& name) {
  3502. if (global_environment.has_lexical_declaration(name)) {
  3503. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3504. return IterationDecision::Break;
  3505. }
  3506. return IterationDecision::Continue;
  3507. });
  3508. if (auto* exception = interpreter.exception())
  3509. return throw_completion(exception->value());
  3510. HashTable<FlyString> declared_function_names;
  3511. Vector<FunctionDeclaration const&> functions_to_initialize;
  3512. for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  3513. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  3514. return IterationDecision::Continue;
  3515. auto function_definable_or_error = global_environment.can_declare_global_function(function.name());
  3516. if (function_definable_or_error.is_error())
  3517. return IterationDecision::Break;
  3518. auto function_definable = function_definable_or_error.release_value();
  3519. if (!function_definable) {
  3520. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  3521. return IterationDecision::Break;
  3522. }
  3523. functions_to_initialize.append(function);
  3524. return IterationDecision::Continue;
  3525. });
  3526. if (auto* exception = interpreter.exception())
  3527. return throw_completion(exception->value());
  3528. HashTable<FlyString> declared_var_names;
  3529. for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  3530. declaration.for_each_bound_name([&](auto const& name) {
  3531. if (declared_function_names.contains(name))
  3532. return IterationDecision::Continue;
  3533. auto var_definable_or_error = global_environment.can_declare_global_var(name);
  3534. if (var_definable_or_error.is_error())
  3535. return IterationDecision::Break;
  3536. auto var_definable = var_definable_or_error.release_value();
  3537. if (!var_definable) {
  3538. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  3539. return IterationDecision::Break;
  3540. }
  3541. declared_var_names.set(name);
  3542. return IterationDecision::Continue;
  3543. });
  3544. if (interpreter.exception())
  3545. return IterationDecision::Break;
  3546. return IterationDecision::Continue;
  3547. });
  3548. if (auto* exception = interpreter.exception())
  3549. return throw_completion(exception->value());
  3550. if (!m_is_strict_mode) {
  3551. for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  3552. auto& function_name = function_declaration.name();
  3553. if (global_environment.has_lexical_declaration(function_name))
  3554. return IterationDecision::Continue;
  3555. auto function_definable_or_error = global_environment.can_declare_global_function(function_name);
  3556. if (function_definable_or_error.is_error())
  3557. return IterationDecision::Break;
  3558. auto function_definable = function_definable_or_error.release_value();
  3559. if (!function_definable) {
  3560. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function_name);
  3561. return IterationDecision::Break;
  3562. }
  3563. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  3564. auto result = global_environment.create_global_var_binding(function_name, false);
  3565. if (result.is_error())
  3566. return IterationDecision::Break;
  3567. declared_function_names.set(function_name);
  3568. }
  3569. function_declaration.set_should_do_additional_annexB_steps();
  3570. return IterationDecision::Continue;
  3571. });
  3572. if (auto* exception = interpreter.exception())
  3573. return throw_completion(exception->value());
  3574. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  3575. declared_function_names.clear();
  3576. }
  3577. PrivateEnvironment* private_environment = nullptr;
  3578. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3579. declaration.for_each_bound_name([&](auto const& name) {
  3580. if (declaration.is_constant_declaration())
  3581. (void)global_environment.create_immutable_binding(global_object, name, true);
  3582. else
  3583. (void)global_environment.create_mutable_binding(global_object, name, false);
  3584. if (interpreter.exception())
  3585. return IterationDecision::Break;
  3586. return IterationDecision::Continue;
  3587. });
  3588. if (interpreter.exception())
  3589. return IterationDecision::Break;
  3590. return IterationDecision::Continue;
  3591. });
  3592. for (auto& declaration : functions_to_initialize) {
  3593. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), &global_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  3594. TRY(global_environment.create_global_function_binding(declaration.name(), function, false));
  3595. }
  3596. for (auto& var_name : declared_var_names)
  3597. TRY(global_environment.create_global_var_binding(var_name, false));
  3598. return {};
  3599. }
  3600. }