AST.cpp 134 KB

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