AST.cpp 121 KB

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