AST.cpp 159 KB

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