AST.cpp 141 KB

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