AST.cpp 141 KB

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