AST.cpp 134 KB

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