AST.cpp 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Demangle.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/HashTable.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/TemporaryChange.h>
  13. #include <LibCrypto/BigInt/SignedBigInteger.h>
  14. #include <LibJS/AST.h>
  15. #include <LibJS/Interpreter.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/Accessor.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BigInt.h>
  20. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  21. #include <LibJS/Runtime/Error.h>
  22. #include <LibJS/Runtime/FunctionEnvironment.h>
  23. #include <LibJS/Runtime/GlobalObject.h>
  24. #include <LibJS/Runtime/IteratorOperations.h>
  25. #include <LibJS/Runtime/MarkedValueList.h>
  26. #include <LibJS/Runtime/NativeFunction.h>
  27. #include <LibJS/Runtime/ObjectEnvironment.h>
  28. #include <LibJS/Runtime/PrimitiveString.h>
  29. #include <LibJS/Runtime/Reference.h>
  30. #include <LibJS/Runtime/RegExpObject.h>
  31. #include <LibJS/Runtime/Shape.h>
  32. #include <typeinfo>
  33. namespace JS {
  34. class InterpreterNodeScope {
  35. AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
  36. AK_MAKE_NONMOVABLE(InterpreterNodeScope);
  37. public:
  38. InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
  39. : m_interpreter(interpreter)
  40. , m_chain_node { nullptr, node }
  41. {
  42. m_interpreter.vm().running_execution_context().current_node = &node;
  43. m_interpreter.push_ast_node(m_chain_node);
  44. }
  45. ~InterpreterNodeScope()
  46. {
  47. m_interpreter.pop_ast_node();
  48. }
  49. private:
  50. Interpreter& m_interpreter;
  51. ExecutingASTNodeChain m_chain_node;
  52. };
  53. String ASTNode::class_name() const
  54. {
  55. // NOTE: We strip the "JS::" prefix.
  56. return demangle(typeid(*this).name()).substring(4);
  57. }
  58. static void update_function_name(Value value, FlyString const& name)
  59. {
  60. if (!value.is_function())
  61. return;
  62. auto& function = value.as_function();
  63. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  64. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  65. }
  66. static String get_function_name(GlobalObject& global_object, Value value)
  67. {
  68. if (value.is_symbol())
  69. return String::formatted("[{}]", value.as_symbol().description());
  70. if (value.is_string())
  71. return value.as_string().string();
  72. return value.to_string(global_object);
  73. }
  74. Value ScopeNode::execute(Interpreter& interpreter, GlobalObject& global_object) const
  75. {
  76. InterpreterNodeScope node_scope { interpreter, *this };
  77. return interpreter.execute_statement(global_object, *this);
  78. }
  79. Value Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  80. {
  81. InterpreterNodeScope node_scope { interpreter, *this };
  82. return interpreter.execute_statement(global_object, *this, ScopeType::Block);
  83. }
  84. Value FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject&) const
  85. {
  86. InterpreterNodeScope node_scope { interpreter, *this };
  87. return {};
  88. }
  89. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  90. Value FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  91. {
  92. InterpreterNodeScope node_scope { interpreter, *this };
  93. auto* func_env = interpreter.lexical_environment();
  94. bool has_identifier = !name().is_empty() && !is_auto_renamed();
  95. if (has_identifier) {
  96. func_env = interpreter.heap().allocate<DeclarativeEnvironment>(global_object, func_env);
  97. func_env->create_immutable_binding(global_object, name(), false);
  98. }
  99. auto closure = ECMAScriptFunctionObject::create(global_object, name(), body(), parameters(), function_length(), func_env, kind(), is_strict_mode(), is_arrow_function());
  100. if (has_identifier)
  101. func_env->initialize_binding(global_object, name(), closure);
  102. return closure;
  103. }
  104. Value ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  105. {
  106. InterpreterNodeScope node_scope { interpreter, *this };
  107. return m_expression->execute(interpreter, global_object);
  108. }
  109. CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  110. {
  111. auto& vm = interpreter.vm();
  112. if (callee_reference.is_property_reference()) {
  113. auto this_value = callee_reference.get_this_value();
  114. auto callee = callee_reference.get_value(global_object);
  115. if (vm.exception())
  116. return {};
  117. return { this_value, callee };
  118. }
  119. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  120. return {
  121. js_undefined(),
  122. callee_reference.is_unresolvable()
  123. ? m_callee->execute(interpreter, global_object)
  124. : callee_reference.get_value(global_object)
  125. };
  126. }
  127. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  128. static void argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list)
  129. {
  130. auto& vm = global_object.vm();
  131. list.ensure_capacity(arguments.size());
  132. for (auto& argument : arguments) {
  133. auto value = argument.value->execute(interpreter, global_object);
  134. if (vm.exception())
  135. return;
  136. if (argument.is_spread) {
  137. get_iterator_values(global_object, value, [&](Value iterator_value) {
  138. if (vm.exception())
  139. return IterationDecision::Break;
  140. list.append(iterator_value);
  141. return IterationDecision::Continue;
  142. });
  143. if (vm.exception())
  144. return;
  145. } else {
  146. list.append(value);
  147. }
  148. }
  149. }
  150. Value NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  151. {
  152. InterpreterNodeScope node_scope { interpreter, *this };
  153. auto& vm = interpreter.vm();
  154. auto callee_value = m_callee->execute(interpreter, global_object);
  155. if (vm.exception())
  156. return {};
  157. if (!callee_value.is_function() || !callee_value.as_function().has_constructor()) {
  158. throw_type_error_for_callee(interpreter, global_object, callee_value, "constructor"sv);
  159. return {};
  160. }
  161. MarkedValueList arg_list(vm.heap());
  162. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  163. if (interpreter.exception())
  164. return {};
  165. auto& function = callee_value.as_function();
  166. return vm.construct(function, function, move(arg_list));
  167. }
  168. void CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const
  169. {
  170. auto& vm = interpreter.vm();
  171. if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) {
  172. String expression_string;
  173. if (is<Identifier>(*m_callee)) {
  174. expression_string = static_cast<Identifier const&>(*m_callee).string();
  175. } else {
  176. expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  177. }
  178. vm.throw_exception<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string);
  179. } else {
  180. vm.throw_exception<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
  181. }
  182. }
  183. Value CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  184. {
  185. InterpreterNodeScope node_scope { interpreter, *this };
  186. auto& vm = interpreter.vm();
  187. auto callee_reference = m_callee->to_reference(interpreter, global_object);
  188. if (vm.exception())
  189. return {};
  190. auto [this_value, callee] = compute_this_and_callee(interpreter, global_object, callee_reference);
  191. if (vm.exception())
  192. return {};
  193. VERIFY(!callee.is_empty());
  194. MarkedValueList arg_list(vm.heap());
  195. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  196. if (interpreter.exception())
  197. return {};
  198. if (!callee.is_function()) {
  199. throw_type_error_for_callee(interpreter, global_object, callee, "function"sv);
  200. return {};
  201. }
  202. auto& function = callee.as_function();
  203. if (&function == global_object.eval_function()
  204. && callee_reference.is_environment_reference()
  205. && callee_reference.name().is_string()
  206. && callee_reference.name().as_string() == vm.names.eval.as_string()) {
  207. auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
  208. return TRY_OR_DISCARD(perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  209. }
  210. return TRY_OR_DISCARD(vm.call(function, this_value, move(arg_list)));
  211. }
  212. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  213. // SuperCall : super Arguments
  214. Value SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  215. {
  216. InterpreterNodeScope node_scope { interpreter, *this };
  217. auto& vm = interpreter.vm();
  218. // 1. Let newTarget be GetNewTarget().
  219. auto new_target = vm.get_new_target();
  220. if (vm.exception())
  221. return {};
  222. // 2. Assert: Type(newTarget) is Object.
  223. VERIFY(new_target.is_function());
  224. // 3. Let func be ! GetSuperConstructor().
  225. auto* func = get_super_constructor(interpreter.vm());
  226. VERIFY(!vm.exception());
  227. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  228. MarkedValueList arg_list(vm.heap());
  229. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  230. if (interpreter.exception())
  231. return {};
  232. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  233. // FIXME: This check is non-conforming.
  234. if (!func || !func->is_function()) {
  235. vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  236. return {};
  237. }
  238. // 6. Let result be ? Construct(func, argList, newTarget).
  239. auto& function = new_target.as_function();
  240. auto result = vm.construct(static_cast<FunctionObject&>(*func), function, move(arg_list));
  241. if (vm.exception())
  242. return {};
  243. // 7. Let thisER be GetThisEnvironment().
  244. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  245. // 8. Perform ? thisER.BindThisValue(result).
  246. this_er.bind_this_value(global_object, result);
  247. if (vm.exception())
  248. return {};
  249. // 9. Let F be thisER.[[FunctionObject]].
  250. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  251. [[maybe_unused]] auto& f = this_er.function_object();
  252. // 11. Perform ? InitializeInstanceElements(result, F).
  253. VERIFY(result.is_object());
  254. vm.initialize_instance_elements(result.as_object(), f);
  255. // 12. Return result.
  256. return result;
  257. }
  258. Value YieldExpression::execute(Interpreter&, GlobalObject&) const
  259. {
  260. // This should be transformed to a return.
  261. VERIFY_NOT_REACHED();
  262. }
  263. Value ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  264. {
  265. InterpreterNodeScope node_scope { interpreter, *this };
  266. auto value = argument() ? argument()->execute(interpreter, global_object) : js_undefined();
  267. if (interpreter.exception())
  268. return {};
  269. interpreter.vm().unwind(ScopeType::Function);
  270. return value;
  271. }
  272. Value IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  273. {
  274. InterpreterNodeScope node_scope { interpreter, *this };
  275. auto predicate_result = m_predicate->execute(interpreter, global_object);
  276. if (interpreter.exception())
  277. return {};
  278. if (predicate_result.to_boolean())
  279. return interpreter.execute_statement(global_object, *m_consequent);
  280. if (m_alternate)
  281. return interpreter.execute_statement(global_object, *m_alternate);
  282. return js_undefined();
  283. }
  284. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  285. // WithStatement : with ( Expression ) Statement
  286. Value WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  287. {
  288. InterpreterNodeScope node_scope { interpreter, *this };
  289. // 1. Let value be the result of evaluating Expression.
  290. auto value = m_object->execute(interpreter, global_object);
  291. if (interpreter.exception())
  292. return {};
  293. // 2. Let obj be ? ToObject(? GetValue(value)).
  294. auto* object = value.to_object(global_object);
  295. if (interpreter.exception())
  296. return {};
  297. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  298. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  299. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  300. auto* new_environment = new_object_environment(*object, true, old_environment);
  301. if (interpreter.exception())
  302. return {};
  303. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  304. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  305. // 6. Let C be the result of evaluating Statement.
  306. auto result = interpreter.execute_statement(global_object, m_body).value_or(js_undefined());
  307. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  308. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  309. if (interpreter.exception())
  310. return {};
  311. // 8. Return Completion(UpdateEmpty(C, undefined)).
  312. return result;
  313. }
  314. Value WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  315. {
  316. InterpreterNodeScope node_scope { interpreter, *this };
  317. auto last_value = js_undefined();
  318. for (;;) {
  319. auto test_result = m_test->execute(interpreter, global_object);
  320. if (interpreter.exception())
  321. return {};
  322. if (!test_result.to_boolean())
  323. break;
  324. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  325. if (interpreter.exception())
  326. return {};
  327. if (interpreter.vm().should_unwind()) {
  328. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  329. interpreter.vm().stop_unwind();
  330. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  331. interpreter.vm().stop_unwind();
  332. break;
  333. } else {
  334. return last_value;
  335. }
  336. }
  337. }
  338. return last_value;
  339. }
  340. Value DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  341. {
  342. InterpreterNodeScope node_scope { interpreter, *this };
  343. auto last_value = js_undefined();
  344. for (;;) {
  345. if (interpreter.exception())
  346. return {};
  347. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  348. if (interpreter.exception())
  349. return {};
  350. if (interpreter.vm().should_unwind()) {
  351. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  352. interpreter.vm().stop_unwind();
  353. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  354. interpreter.vm().stop_unwind();
  355. break;
  356. } else {
  357. return last_value;
  358. }
  359. }
  360. auto test_result = m_test->execute(interpreter, global_object);
  361. if (interpreter.exception())
  362. return {};
  363. if (!test_result.to_boolean())
  364. break;
  365. }
  366. return last_value;
  367. }
  368. Value ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  369. {
  370. InterpreterNodeScope node_scope { interpreter, *this };
  371. RefPtr<BlockStatement> wrapper;
  372. if (m_init && is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) {
  373. wrapper = create_ast_node<BlockStatement>(source_range());
  374. NonnullRefPtrVector<VariableDeclaration> decls;
  375. decls.append(*static_cast<VariableDeclaration const*>(m_init.ptr()));
  376. wrapper->add_variables(decls);
  377. interpreter.enter_scope(*wrapper, ScopeType::Block, global_object);
  378. }
  379. auto wrapper_cleanup = ScopeGuard([&] {
  380. if (wrapper)
  381. interpreter.exit_scope(*wrapper);
  382. });
  383. auto last_value = js_undefined();
  384. if (m_init) {
  385. m_init->execute(interpreter, global_object);
  386. if (interpreter.exception())
  387. return {};
  388. }
  389. if (m_test) {
  390. while (true) {
  391. auto test_result = m_test->execute(interpreter, global_object);
  392. if (interpreter.exception())
  393. return {};
  394. if (!test_result.to_boolean())
  395. break;
  396. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  397. if (interpreter.exception())
  398. return {};
  399. if (interpreter.vm().should_unwind()) {
  400. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  401. interpreter.vm().stop_unwind();
  402. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  403. interpreter.vm().stop_unwind();
  404. break;
  405. } else {
  406. return last_value;
  407. }
  408. }
  409. if (m_update) {
  410. m_update->execute(interpreter, global_object);
  411. if (interpreter.exception())
  412. return {};
  413. }
  414. }
  415. } else {
  416. while (true) {
  417. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  418. if (interpreter.exception())
  419. return {};
  420. if (interpreter.vm().should_unwind()) {
  421. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  422. interpreter.vm().stop_unwind();
  423. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  424. interpreter.vm().stop_unwind();
  425. break;
  426. } else {
  427. return last_value;
  428. }
  429. }
  430. if (m_update) {
  431. m_update->execute(interpreter, global_object);
  432. if (interpreter.exception())
  433. return {};
  434. }
  435. }
  436. }
  437. return last_value;
  438. }
  439. static Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>> variable_from_for_declaration(Interpreter& interpreter, GlobalObject& global_object, ASTNode const& node, RefPtr<BlockStatement> wrapper)
  440. {
  441. if (is<VariableDeclaration>(node)) {
  442. auto& variable_declaration = static_cast<VariableDeclaration const&>(node);
  443. VERIFY(!variable_declaration.declarations().is_empty());
  444. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  445. wrapper = create_ast_node<BlockStatement>(node.source_range());
  446. interpreter.enter_scope(*wrapper, ScopeType::Block, global_object);
  447. }
  448. variable_declaration.execute(interpreter, global_object);
  449. return variable_declaration.declarations().first().target();
  450. }
  451. if (is<Identifier>(node)) {
  452. return NonnullRefPtr(static_cast<Identifier const&>(node));
  453. }
  454. VERIFY_NOT_REACHED();
  455. }
  456. Value ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  457. {
  458. InterpreterNodeScope node_scope { interpreter, *this };
  459. bool has_declaration = is<VariableDeclaration>(*m_lhs);
  460. if (!has_declaration && !is<Identifier>(*m_lhs)) {
  461. // FIXME: Implement "for (foo.bar in baz)", "for (foo[0] in bar)"
  462. VERIFY_NOT_REACHED();
  463. }
  464. RefPtr<BlockStatement> wrapper;
  465. auto target = variable_from_for_declaration(interpreter, global_object, m_lhs, wrapper);
  466. auto wrapper_cleanup = ScopeGuard([&] {
  467. if (wrapper)
  468. interpreter.exit_scope(*wrapper);
  469. });
  470. auto last_value = js_undefined();
  471. auto rhs_result = m_rhs->execute(interpreter, global_object);
  472. if (interpreter.exception())
  473. return {};
  474. if (rhs_result.is_nullish())
  475. return {};
  476. auto* object = rhs_result.to_object(global_object);
  477. while (object) {
  478. auto property_names = object->enumerable_own_property_names(Object::PropertyKind::Key);
  479. for (auto& value : property_names) {
  480. interpreter.vm().assign(target, value, global_object, has_declaration);
  481. if (interpreter.exception())
  482. return {};
  483. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  484. if (interpreter.exception())
  485. return {};
  486. if (interpreter.vm().should_unwind()) {
  487. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  488. interpreter.vm().stop_unwind();
  489. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  490. interpreter.vm().stop_unwind();
  491. break;
  492. } else {
  493. return last_value;
  494. }
  495. }
  496. }
  497. object = object->internal_get_prototype_of();
  498. if (interpreter.exception())
  499. return {};
  500. }
  501. return last_value;
  502. }
  503. Value ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  504. {
  505. InterpreterNodeScope node_scope { interpreter, *this };
  506. bool has_declaration = is<VariableDeclaration>(*m_lhs);
  507. if (!has_declaration && !is<Identifier>(*m_lhs)) {
  508. // FIXME: Implement "for (foo.bar of baz)", "for (foo[0] of bar)"
  509. VERIFY_NOT_REACHED();
  510. }
  511. RefPtr<BlockStatement> wrapper;
  512. auto target = variable_from_for_declaration(interpreter, global_object, m_lhs, wrapper);
  513. auto wrapper_cleanup = ScopeGuard([&] {
  514. if (wrapper)
  515. interpreter.exit_scope(*wrapper);
  516. });
  517. auto last_value = js_undefined();
  518. auto rhs_result = m_rhs->execute(interpreter, global_object);
  519. if (interpreter.exception())
  520. return {};
  521. get_iterator_values(global_object, rhs_result, [&](Value value) {
  522. interpreter.vm().assign(target, value, global_object, has_declaration);
  523. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  524. if (interpreter.exception())
  525. return IterationDecision::Break;
  526. if (interpreter.vm().should_unwind()) {
  527. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  528. interpreter.vm().stop_unwind();
  529. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  530. interpreter.vm().stop_unwind();
  531. return IterationDecision::Break;
  532. } else {
  533. return IterationDecision::Break;
  534. }
  535. }
  536. return IterationDecision::Continue;
  537. });
  538. if (interpreter.exception())
  539. return {};
  540. return last_value;
  541. }
  542. Value BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  543. {
  544. InterpreterNodeScope node_scope { interpreter, *this };
  545. auto lhs_result = m_lhs->execute(interpreter, global_object);
  546. if (interpreter.exception())
  547. return {};
  548. auto rhs_result = m_rhs->execute(interpreter, global_object);
  549. if (interpreter.exception())
  550. return {};
  551. switch (m_op) {
  552. case BinaryOp::Addition:
  553. return add(global_object, lhs_result, rhs_result);
  554. case BinaryOp::Subtraction:
  555. return sub(global_object, lhs_result, rhs_result);
  556. case BinaryOp::Multiplication:
  557. return mul(global_object, lhs_result, rhs_result);
  558. case BinaryOp::Division:
  559. return div(global_object, lhs_result, rhs_result);
  560. case BinaryOp::Modulo:
  561. return mod(global_object, lhs_result, rhs_result);
  562. case BinaryOp::Exponentiation:
  563. return exp(global_object, lhs_result, rhs_result);
  564. case BinaryOp::StrictlyEquals:
  565. return Value(is_strictly_equal(lhs_result, rhs_result));
  566. case BinaryOp::StrictlyInequals:
  567. return Value(!is_strictly_equal(lhs_result, rhs_result));
  568. case BinaryOp::LooselyEquals:
  569. return Value(is_loosely_equal(global_object, lhs_result, rhs_result));
  570. case BinaryOp::LooselyInequals:
  571. return Value(!is_loosely_equal(global_object, lhs_result, rhs_result));
  572. case BinaryOp::GreaterThan:
  573. return greater_than(global_object, lhs_result, rhs_result);
  574. case BinaryOp::GreaterThanEquals:
  575. return greater_than_equals(global_object, lhs_result, rhs_result);
  576. case BinaryOp::LessThan:
  577. return less_than(global_object, lhs_result, rhs_result);
  578. case BinaryOp::LessThanEquals:
  579. return less_than_equals(global_object, lhs_result, rhs_result);
  580. case BinaryOp::BitwiseAnd:
  581. return bitwise_and(global_object, lhs_result, rhs_result);
  582. case BinaryOp::BitwiseOr:
  583. return bitwise_or(global_object, lhs_result, rhs_result);
  584. case BinaryOp::BitwiseXor:
  585. return bitwise_xor(global_object, lhs_result, rhs_result);
  586. case BinaryOp::LeftShift:
  587. return left_shift(global_object, lhs_result, rhs_result);
  588. case BinaryOp::RightShift:
  589. return right_shift(global_object, lhs_result, rhs_result);
  590. case BinaryOp::UnsignedRightShift:
  591. return unsigned_right_shift(global_object, lhs_result, rhs_result);
  592. case BinaryOp::In:
  593. return in(global_object, lhs_result, rhs_result);
  594. case BinaryOp::InstanceOf:
  595. return instance_of(global_object, lhs_result, rhs_result);
  596. }
  597. VERIFY_NOT_REACHED();
  598. }
  599. Value LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  600. {
  601. InterpreterNodeScope node_scope { interpreter, *this };
  602. auto lhs_result = m_lhs->execute(interpreter, global_object);
  603. if (interpreter.exception())
  604. return {};
  605. switch (m_op) {
  606. case LogicalOp::And:
  607. if (lhs_result.to_boolean()) {
  608. auto rhs_result = m_rhs->execute(interpreter, global_object);
  609. if (interpreter.exception())
  610. return {};
  611. return rhs_result;
  612. }
  613. return lhs_result;
  614. case LogicalOp::Or: {
  615. if (lhs_result.to_boolean())
  616. return lhs_result;
  617. auto rhs_result = m_rhs->execute(interpreter, global_object);
  618. if (interpreter.exception())
  619. return {};
  620. return rhs_result;
  621. }
  622. case LogicalOp::NullishCoalescing:
  623. if (lhs_result.is_nullish()) {
  624. auto rhs_result = m_rhs->execute(interpreter, global_object);
  625. if (interpreter.exception())
  626. return {};
  627. return rhs_result;
  628. }
  629. return lhs_result;
  630. }
  631. VERIFY_NOT_REACHED();
  632. }
  633. Reference Expression::to_reference(Interpreter&, GlobalObject&) const
  634. {
  635. return {};
  636. }
  637. Reference Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const
  638. {
  639. return interpreter.vm().resolve_binding(string());
  640. }
  641. Reference MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  642. {
  643. // 13.3.7.1 Runtime Semantics: Evaluation
  644. // SuperProperty : super [ Expression ]
  645. // SuperProperty : super . IdentifierName
  646. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  647. if (is<SuperExpression>(object())) {
  648. // 1. Let env be GetThisEnvironment().
  649. auto& environment = get_this_environment(interpreter.vm());
  650. // 2. Let actualThis be ? env.GetThisBinding().
  651. auto actual_this = environment.get_this_binding(global_object);
  652. StringOrSymbol property_key;
  653. if (is_computed()) {
  654. // SuperProperty : super [ Expression ]
  655. // 3. Let propertyNameReference be the result of evaluating Expression.
  656. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  657. auto property_name_value = m_property->execute(interpreter, global_object);
  658. if (interpreter.exception())
  659. return {};
  660. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  661. property_key = property_name_value.to_property_key(global_object);
  662. } else {
  663. // SuperProperty : super . IdentifierName
  664. // 3. Let propertyKey be StringValue of IdentifierName.
  665. VERIFY(is<Identifier>(property()));
  666. property_key = static_cast<Identifier const&>(property()).string();
  667. }
  668. // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  669. bool strict = interpreter.vm().in_strict_mode();
  670. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  671. return TRY_OR_DISCARD(make_super_property_reference(global_object, actual_this, property_key, strict));
  672. }
  673. auto object_value = m_object->execute(interpreter, global_object);
  674. if (interpreter.exception())
  675. return {};
  676. // From here on equivalent to
  677. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  678. object_value = TRY_OR_DISCARD(require_object_coercible(global_object, object_value));
  679. auto property_name = computed_property_name(interpreter, global_object);
  680. if (!property_name.is_valid())
  681. return Reference {};
  682. auto strict = interpreter.vm().in_strict_mode();
  683. return Reference { object_value, move(property_name), {}, strict };
  684. }
  685. Value UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  686. {
  687. InterpreterNodeScope node_scope { interpreter, *this };
  688. auto& vm = interpreter.vm();
  689. if (m_op == UnaryOp::Delete) {
  690. auto reference = m_lhs->to_reference(interpreter, global_object);
  691. if (interpreter.exception())
  692. return {};
  693. return Value(reference.delete_(global_object));
  694. }
  695. Value lhs_result;
  696. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  697. auto reference = m_lhs->to_reference(interpreter, global_object);
  698. if (interpreter.exception()) {
  699. return {};
  700. }
  701. if (reference.is_unresolvable()) {
  702. lhs_result = js_undefined();
  703. } else {
  704. lhs_result = reference.get_value(global_object, false);
  705. }
  706. } else {
  707. lhs_result = m_lhs->execute(interpreter, global_object);
  708. if (interpreter.exception())
  709. return {};
  710. }
  711. switch (m_op) {
  712. case UnaryOp::BitwiseNot:
  713. return bitwise_not(global_object, lhs_result);
  714. case UnaryOp::Not:
  715. return Value(!lhs_result.to_boolean());
  716. case UnaryOp::Plus:
  717. return unary_plus(global_object, lhs_result);
  718. case UnaryOp::Minus:
  719. return unary_minus(global_object, lhs_result);
  720. case UnaryOp::Typeof:
  721. return js_string(vm, lhs_result.typeof());
  722. case UnaryOp::Void:
  723. return js_undefined();
  724. case UnaryOp::Delete:
  725. VERIFY_NOT_REACHED();
  726. }
  727. VERIFY_NOT_REACHED();
  728. }
  729. Value SuperExpression::execute(Interpreter&, GlobalObject&) const
  730. {
  731. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  732. VERIFY_NOT_REACHED();
  733. }
  734. Value ClassMethod::execute(Interpreter& interpreter, GlobalObject& global_object) const
  735. {
  736. InterpreterNodeScope node_scope { interpreter, *this };
  737. return m_function->execute(interpreter, global_object);
  738. }
  739. Value ClassField::execute(Interpreter& interpreter, GlobalObject&) const
  740. {
  741. InterpreterNodeScope node_scope { interpreter, *this };
  742. return {};
  743. }
  744. Value ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  745. {
  746. InterpreterNodeScope node_scope { interpreter, *this };
  747. auto& vm = interpreter.vm();
  748. Value class_constructor_value = m_constructor->execute(interpreter, global_object);
  749. if (interpreter.exception())
  750. return {};
  751. update_function_name(class_constructor_value, m_name);
  752. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  753. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  754. class_constructor->set_is_class_constructor();
  755. Value super_constructor = js_undefined();
  756. if (!m_super_class.is_null()) {
  757. super_constructor = m_super_class->execute(interpreter, global_object);
  758. if (interpreter.exception())
  759. return {};
  760. if (!super_constructor.is_function() && !super_constructor.is_null()) {
  761. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_constructor.to_string_without_side_effects());
  762. return {};
  763. }
  764. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  765. Object* super_constructor_prototype = nullptr;
  766. if (!super_constructor.is_null()) {
  767. auto super_constructor_prototype_value = super_constructor.as_object().get(vm.names.prototype);
  768. if (interpreter.exception())
  769. return {};
  770. if (!super_constructor_prototype_value.is_object() && !super_constructor_prototype_value.is_null()) {
  771. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_constructor_prototype_value.to_string_without_side_effects());
  772. return {};
  773. }
  774. if (super_constructor_prototype_value.is_object())
  775. super_constructor_prototype = &super_constructor_prototype_value.as_object();
  776. }
  777. auto* prototype = Object::create(global_object, super_constructor_prototype);
  778. prototype->define_direct_property(vm.names.constructor, class_constructor, 0);
  779. if (interpreter.exception())
  780. return {};
  781. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  782. if (interpreter.exception())
  783. return {};
  784. class_constructor->internal_set_prototype_of(super_constructor.is_null() ? global_object.function_prototype() : &super_constructor.as_object());
  785. }
  786. auto class_prototype = class_constructor->get(vm.names.prototype);
  787. if (interpreter.exception())
  788. return {};
  789. if (!class_prototype.is_object()) {
  790. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::NotAnObject, "Class prototype");
  791. return {};
  792. }
  793. for (auto const& method : m_methods) {
  794. auto method_value = method.execute(interpreter, global_object);
  795. if (interpreter.exception())
  796. return {};
  797. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  798. auto key = method.key().execute(interpreter, global_object);
  799. if (interpreter.exception())
  800. return {};
  801. auto property_key = key.to_property_key(global_object);
  802. if (interpreter.exception())
  803. return {};
  804. auto& target = method.is_static() ? *class_constructor : class_prototype.as_object();
  805. method_function.set_home_object(&target);
  806. switch (method.kind()) {
  807. case ClassMethod::Kind::Method:
  808. target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true });
  809. break;
  810. case ClassMethod::Kind::Getter:
  811. update_function_name(method_value, String::formatted("get {}", get_function_name(global_object, key)));
  812. target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true });
  813. break;
  814. case ClassMethod::Kind::Setter:
  815. update_function_name(method_value, String::formatted("set {}", get_function_name(global_object, key)));
  816. target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true });
  817. break;
  818. default:
  819. VERIFY_NOT_REACHED();
  820. }
  821. if (interpreter.exception())
  822. return {};
  823. }
  824. for (auto& field : m_fields) {
  825. auto key = field.key().execute(interpreter, global_object);
  826. if (interpreter.exception())
  827. return {};
  828. auto property_key = key.to_property_key(global_object);
  829. if (interpreter.exception())
  830. return {};
  831. ECMAScriptFunctionObject* initializer = nullptr;
  832. if (field.initializer()) {
  833. auto copy_initializer = field.initializer();
  834. auto body = create_ast_node<ExpressionStatement>(field.initializer()->source_range(), copy_initializer.release_nonnull());
  835. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  836. initializer = ECMAScriptFunctionObject::create(interpreter.global_object(), property_key.to_display_string(), *body, {}, 0, interpreter.lexical_environment(), FunctionKind::Regular, false);
  837. initializer->set_home_object(field.is_static() ? class_constructor : &class_prototype.as_object());
  838. }
  839. if (field.is_static()) {
  840. Value field_value = js_undefined();
  841. if (initializer)
  842. field_value = TRY_OR_DISCARD(interpreter.vm().call(*initializer, class_constructor_value));
  843. class_constructor->create_data_property_or_throw(property_key, field_value);
  844. if (interpreter.exception())
  845. return {};
  846. } else {
  847. class_constructor->add_field(property_key, initializer);
  848. }
  849. }
  850. return class_constructor;
  851. }
  852. Value ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  853. {
  854. InterpreterNodeScope node_scope { interpreter, *this };
  855. Value class_constructor = m_class_expression->execute(interpreter, global_object);
  856. if (interpreter.exception())
  857. return {};
  858. interpreter.lexical_environment()->put_into_environment(m_class_expression->name(), { class_constructor, DeclarationKind::Let });
  859. return {};
  860. }
  861. static void print_indent(int indent)
  862. {
  863. out("{}", String::repeated(' ', indent * 2));
  864. }
  865. void ASTNode::dump(int indent) const
  866. {
  867. print_indent(indent);
  868. outln("{}", class_name());
  869. }
  870. void ScopeNode::dump(int indent) const
  871. {
  872. ASTNode::dump(indent);
  873. if (!m_variables.is_empty()) {
  874. print_indent(indent + 1);
  875. outln("(Variables)");
  876. for (auto& variable : m_variables)
  877. variable.dump(indent + 2);
  878. }
  879. if (!m_children.is_empty()) {
  880. print_indent(indent + 1);
  881. outln("(Children)");
  882. for (auto& child : children())
  883. child.dump(indent + 2);
  884. }
  885. }
  886. void BinaryExpression::dump(int indent) const
  887. {
  888. const char* op_string = nullptr;
  889. switch (m_op) {
  890. case BinaryOp::Addition:
  891. op_string = "+";
  892. break;
  893. case BinaryOp::Subtraction:
  894. op_string = "-";
  895. break;
  896. case BinaryOp::Multiplication:
  897. op_string = "*";
  898. break;
  899. case BinaryOp::Division:
  900. op_string = "/";
  901. break;
  902. case BinaryOp::Modulo:
  903. op_string = "%";
  904. break;
  905. case BinaryOp::Exponentiation:
  906. op_string = "**";
  907. break;
  908. case BinaryOp::StrictlyEquals:
  909. op_string = "===";
  910. break;
  911. case BinaryOp::StrictlyInequals:
  912. op_string = "!==";
  913. break;
  914. case BinaryOp::LooselyEquals:
  915. op_string = "==";
  916. break;
  917. case BinaryOp::LooselyInequals:
  918. op_string = "!=";
  919. break;
  920. case BinaryOp::GreaterThan:
  921. op_string = ">";
  922. break;
  923. case BinaryOp::GreaterThanEquals:
  924. op_string = ">=";
  925. break;
  926. case BinaryOp::LessThan:
  927. op_string = "<";
  928. break;
  929. case BinaryOp::LessThanEquals:
  930. op_string = "<=";
  931. break;
  932. case BinaryOp::BitwiseAnd:
  933. op_string = "&";
  934. break;
  935. case BinaryOp::BitwiseOr:
  936. op_string = "|";
  937. break;
  938. case BinaryOp::BitwiseXor:
  939. op_string = "^";
  940. break;
  941. case BinaryOp::LeftShift:
  942. op_string = "<<";
  943. break;
  944. case BinaryOp::RightShift:
  945. op_string = ">>";
  946. break;
  947. case BinaryOp::UnsignedRightShift:
  948. op_string = ">>>";
  949. break;
  950. case BinaryOp::In:
  951. op_string = "in";
  952. break;
  953. case BinaryOp::InstanceOf:
  954. op_string = "instanceof";
  955. break;
  956. }
  957. print_indent(indent);
  958. outln("{}", class_name());
  959. m_lhs->dump(indent + 1);
  960. print_indent(indent + 1);
  961. outln("{}", op_string);
  962. m_rhs->dump(indent + 1);
  963. }
  964. void LogicalExpression::dump(int indent) const
  965. {
  966. const char* op_string = nullptr;
  967. switch (m_op) {
  968. case LogicalOp::And:
  969. op_string = "&&";
  970. break;
  971. case LogicalOp::Or:
  972. op_string = "||";
  973. break;
  974. case LogicalOp::NullishCoalescing:
  975. op_string = "??";
  976. break;
  977. }
  978. print_indent(indent);
  979. outln("{}", class_name());
  980. m_lhs->dump(indent + 1);
  981. print_indent(indent + 1);
  982. outln("{}", op_string);
  983. m_rhs->dump(indent + 1);
  984. }
  985. void UnaryExpression::dump(int indent) const
  986. {
  987. const char* op_string = nullptr;
  988. switch (m_op) {
  989. case UnaryOp::BitwiseNot:
  990. op_string = "~";
  991. break;
  992. case UnaryOp::Not:
  993. op_string = "!";
  994. break;
  995. case UnaryOp::Plus:
  996. op_string = "+";
  997. break;
  998. case UnaryOp::Minus:
  999. op_string = "-";
  1000. break;
  1001. case UnaryOp::Typeof:
  1002. op_string = "typeof ";
  1003. break;
  1004. case UnaryOp::Void:
  1005. op_string = "void ";
  1006. break;
  1007. case UnaryOp::Delete:
  1008. op_string = "delete ";
  1009. break;
  1010. }
  1011. print_indent(indent);
  1012. outln("{}", class_name());
  1013. print_indent(indent + 1);
  1014. outln("{}", op_string);
  1015. m_lhs->dump(indent + 1);
  1016. }
  1017. void CallExpression::dump(int indent) const
  1018. {
  1019. print_indent(indent);
  1020. if (is<NewExpression>(*this))
  1021. outln("CallExpression [new]");
  1022. else
  1023. outln("CallExpression");
  1024. m_callee->dump(indent + 1);
  1025. for (auto& argument : m_arguments)
  1026. argument.value->dump(indent + 1);
  1027. }
  1028. void SuperCall::dump(int indent) const
  1029. {
  1030. print_indent(indent);
  1031. outln("SuperCall");
  1032. for (auto& argument : m_arguments)
  1033. argument.value->dump(indent + 1);
  1034. }
  1035. void ClassDeclaration::dump(int indent) const
  1036. {
  1037. ASTNode::dump(indent);
  1038. m_class_expression->dump(indent + 1);
  1039. }
  1040. void ClassExpression::dump(int indent) const
  1041. {
  1042. print_indent(indent);
  1043. outln("ClassExpression: \"{}\"", m_name);
  1044. print_indent(indent);
  1045. outln("(Constructor)");
  1046. m_constructor->dump(indent + 1);
  1047. if (!m_super_class.is_null()) {
  1048. print_indent(indent);
  1049. outln("(Super Class)");
  1050. m_super_class->dump(indent + 1);
  1051. }
  1052. print_indent(indent);
  1053. outln("(Methods)");
  1054. for (auto& method : m_methods)
  1055. method.dump(indent + 1);
  1056. print_indent(indent);
  1057. outln("(Fields)");
  1058. for (auto& field : m_fields)
  1059. field.dump(indent + 1);
  1060. }
  1061. void ClassMethod::dump(int indent) const
  1062. {
  1063. ASTNode::dump(indent);
  1064. print_indent(indent);
  1065. outln("(Key)");
  1066. m_key->dump(indent + 1);
  1067. const char* kind_string = nullptr;
  1068. switch (m_kind) {
  1069. case Kind::Method:
  1070. kind_string = "Method";
  1071. break;
  1072. case Kind::Getter:
  1073. kind_string = "Getter";
  1074. break;
  1075. case Kind::Setter:
  1076. kind_string = "Setter";
  1077. break;
  1078. }
  1079. print_indent(indent);
  1080. outln("Kind: {}", kind_string);
  1081. print_indent(indent);
  1082. outln("Static: {}", m_is_static);
  1083. print_indent(indent);
  1084. outln("(Function)");
  1085. m_function->dump(indent + 1);
  1086. }
  1087. void ClassField::dump(int indent) const
  1088. {
  1089. ASTNode::dump(indent);
  1090. print_indent(indent);
  1091. outln("(Key)");
  1092. m_key->dump(indent + 1);
  1093. print_indent(indent);
  1094. outln("Static: {}", m_is_static);
  1095. if (m_initializer) {
  1096. print_indent(indent);
  1097. outln("(Initializer)");
  1098. m_initializer->dump(indent + 1);
  1099. }
  1100. }
  1101. void StringLiteral::dump(int indent) const
  1102. {
  1103. print_indent(indent);
  1104. outln("StringLiteral \"{}\"", m_value);
  1105. }
  1106. void SuperExpression::dump(int indent) const
  1107. {
  1108. print_indent(indent);
  1109. outln("super");
  1110. }
  1111. void NumericLiteral::dump(int indent) const
  1112. {
  1113. print_indent(indent);
  1114. outln("NumericLiteral {}", m_value);
  1115. }
  1116. void BigIntLiteral::dump(int indent) const
  1117. {
  1118. print_indent(indent);
  1119. outln("BigIntLiteral {}", m_value);
  1120. }
  1121. void BooleanLiteral::dump(int indent) const
  1122. {
  1123. print_indent(indent);
  1124. outln("BooleanLiteral {}", m_value);
  1125. }
  1126. void NullLiteral::dump(int indent) const
  1127. {
  1128. print_indent(indent);
  1129. outln("null");
  1130. }
  1131. void BindingPattern::dump(int indent) const
  1132. {
  1133. print_indent(indent);
  1134. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1135. for (auto& entry : entries) {
  1136. print_indent(indent + 1);
  1137. outln("(Property)");
  1138. if (kind == Kind::Object) {
  1139. print_indent(indent + 2);
  1140. outln("(Identifier)");
  1141. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1142. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1143. } else {
  1144. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1145. }
  1146. } else if (entry.is_elision()) {
  1147. print_indent(indent + 2);
  1148. outln("(Elision)");
  1149. continue;
  1150. }
  1151. print_indent(indent + 2);
  1152. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1153. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1154. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1155. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1156. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1157. } else {
  1158. print_indent(indent + 3);
  1159. outln("<empty>");
  1160. }
  1161. if (entry.initializer) {
  1162. print_indent(indent + 2);
  1163. outln("(Initializer)");
  1164. entry.initializer->dump(indent + 3);
  1165. }
  1166. }
  1167. }
  1168. void FunctionNode::dump(int indent, String const& class_name) const
  1169. {
  1170. print_indent(indent);
  1171. outln("{}{} '{}'", class_name, m_kind == FunctionKind::Generator ? "*" : "", name());
  1172. if (!m_parameters.is_empty()) {
  1173. print_indent(indent + 1);
  1174. outln("(Parameters)");
  1175. for (auto& parameter : m_parameters) {
  1176. print_indent(indent + 2);
  1177. if (parameter.is_rest)
  1178. out("...");
  1179. parameter.binding.visit(
  1180. [&](FlyString const& name) {
  1181. outln("{}", name);
  1182. },
  1183. [&](BindingPattern const& pattern) {
  1184. pattern.dump(indent + 2);
  1185. });
  1186. if (parameter.default_value)
  1187. parameter.default_value->dump(indent + 3);
  1188. }
  1189. }
  1190. print_indent(indent + 1);
  1191. outln("(Body)");
  1192. body().dump(indent + 2);
  1193. }
  1194. void FunctionDeclaration::dump(int indent) const
  1195. {
  1196. FunctionNode::dump(indent, class_name());
  1197. }
  1198. void FunctionExpression::dump(int indent) const
  1199. {
  1200. FunctionNode::dump(indent, class_name());
  1201. }
  1202. void YieldExpression::dump(int indent) const
  1203. {
  1204. ASTNode::dump(indent);
  1205. if (argument())
  1206. argument()->dump(indent + 1);
  1207. }
  1208. void ReturnStatement::dump(int indent) const
  1209. {
  1210. ASTNode::dump(indent);
  1211. if (argument())
  1212. argument()->dump(indent + 1);
  1213. }
  1214. void IfStatement::dump(int indent) const
  1215. {
  1216. ASTNode::dump(indent);
  1217. print_indent(indent);
  1218. outln("If");
  1219. predicate().dump(indent + 1);
  1220. consequent().dump(indent + 1);
  1221. if (alternate()) {
  1222. print_indent(indent);
  1223. outln("Else");
  1224. alternate()->dump(indent + 1);
  1225. }
  1226. }
  1227. void WhileStatement::dump(int indent) const
  1228. {
  1229. ASTNode::dump(indent);
  1230. print_indent(indent);
  1231. outln("While");
  1232. test().dump(indent + 1);
  1233. body().dump(indent + 1);
  1234. }
  1235. void WithStatement::dump(int indent) const
  1236. {
  1237. ASTNode::dump(indent);
  1238. print_indent(indent + 1);
  1239. outln("Object");
  1240. object().dump(indent + 2);
  1241. print_indent(indent + 1);
  1242. outln("Body");
  1243. body().dump(indent + 2);
  1244. }
  1245. void DoWhileStatement::dump(int indent) const
  1246. {
  1247. ASTNode::dump(indent);
  1248. print_indent(indent);
  1249. outln("DoWhile");
  1250. test().dump(indent + 1);
  1251. body().dump(indent + 1);
  1252. }
  1253. void ForStatement::dump(int indent) const
  1254. {
  1255. ASTNode::dump(indent);
  1256. print_indent(indent);
  1257. outln("For");
  1258. if (init())
  1259. init()->dump(indent + 1);
  1260. if (test())
  1261. test()->dump(indent + 1);
  1262. if (update())
  1263. update()->dump(indent + 1);
  1264. body().dump(indent + 1);
  1265. }
  1266. void ForInStatement::dump(int indent) const
  1267. {
  1268. ASTNode::dump(indent);
  1269. print_indent(indent);
  1270. outln("ForIn");
  1271. lhs().dump(indent + 1);
  1272. rhs().dump(indent + 1);
  1273. body().dump(indent + 1);
  1274. }
  1275. void ForOfStatement::dump(int indent) const
  1276. {
  1277. ASTNode::dump(indent);
  1278. print_indent(indent);
  1279. outln("ForOf");
  1280. lhs().dump(indent + 1);
  1281. rhs().dump(indent + 1);
  1282. body().dump(indent + 1);
  1283. }
  1284. Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1285. {
  1286. InterpreterNodeScope node_scope { interpreter, *this };
  1287. auto value = interpreter.vm().get_variable(string(), global_object);
  1288. if (interpreter.exception())
  1289. return {};
  1290. if (value.is_empty()) {
  1291. interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::UnknownIdentifier, string());
  1292. return {};
  1293. }
  1294. return value;
  1295. }
  1296. void Identifier::dump(int indent) const
  1297. {
  1298. print_indent(indent);
  1299. outln("Identifier \"{}\"", m_string);
  1300. }
  1301. void SpreadExpression::dump(int indent) const
  1302. {
  1303. ASTNode::dump(indent);
  1304. m_target->dump(indent + 1);
  1305. }
  1306. Value SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1307. {
  1308. InterpreterNodeScope node_scope { interpreter, *this };
  1309. return m_target->execute(interpreter, global_object);
  1310. }
  1311. Value ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1312. {
  1313. InterpreterNodeScope node_scope { interpreter, *this };
  1314. return interpreter.vm().resolve_this_binding(global_object);
  1315. }
  1316. void ThisExpression::dump(int indent) const
  1317. {
  1318. ASTNode::dump(indent);
  1319. }
  1320. Value AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1321. {
  1322. InterpreterNodeScope node_scope { interpreter, *this };
  1323. #define EXECUTE_LHS() \
  1324. do { \
  1325. if (auto* ptr = m_lhs.get_pointer<NonnullRefPtr<Expression>>()) { \
  1326. lhs_result = (*ptr)->execute(interpreter, global_object); \
  1327. if (interpreter.exception()) \
  1328. return {}; \
  1329. } \
  1330. } while (0)
  1331. #define EXECUTE_LHS_AND_RHS() \
  1332. do { \
  1333. EXECUTE_LHS(); \
  1334. rhs_result = m_rhs->execute(interpreter, global_object); \
  1335. if (interpreter.exception()) \
  1336. return {}; \
  1337. } while (0)
  1338. Value lhs_result;
  1339. Value rhs_result;
  1340. switch (m_op) {
  1341. case AssignmentOp::Assignment:
  1342. break;
  1343. case AssignmentOp::AdditionAssignment:
  1344. EXECUTE_LHS_AND_RHS();
  1345. rhs_result = add(global_object, lhs_result, rhs_result);
  1346. break;
  1347. case AssignmentOp::SubtractionAssignment:
  1348. EXECUTE_LHS_AND_RHS();
  1349. rhs_result = sub(global_object, lhs_result, rhs_result);
  1350. break;
  1351. case AssignmentOp::MultiplicationAssignment:
  1352. EXECUTE_LHS_AND_RHS();
  1353. rhs_result = mul(global_object, lhs_result, rhs_result);
  1354. break;
  1355. case AssignmentOp::DivisionAssignment:
  1356. EXECUTE_LHS_AND_RHS();
  1357. rhs_result = div(global_object, lhs_result, rhs_result);
  1358. break;
  1359. case AssignmentOp::ModuloAssignment:
  1360. EXECUTE_LHS_AND_RHS();
  1361. rhs_result = mod(global_object, lhs_result, rhs_result);
  1362. break;
  1363. case AssignmentOp::ExponentiationAssignment:
  1364. EXECUTE_LHS_AND_RHS();
  1365. rhs_result = exp(global_object, lhs_result, rhs_result);
  1366. break;
  1367. case AssignmentOp::BitwiseAndAssignment:
  1368. EXECUTE_LHS_AND_RHS();
  1369. rhs_result = bitwise_and(global_object, lhs_result, rhs_result);
  1370. break;
  1371. case AssignmentOp::BitwiseOrAssignment:
  1372. EXECUTE_LHS_AND_RHS();
  1373. rhs_result = bitwise_or(global_object, lhs_result, rhs_result);
  1374. break;
  1375. case AssignmentOp::BitwiseXorAssignment:
  1376. EXECUTE_LHS_AND_RHS();
  1377. rhs_result = bitwise_xor(global_object, lhs_result, rhs_result);
  1378. break;
  1379. case AssignmentOp::LeftShiftAssignment:
  1380. EXECUTE_LHS_AND_RHS();
  1381. rhs_result = left_shift(global_object, lhs_result, rhs_result);
  1382. break;
  1383. case AssignmentOp::RightShiftAssignment:
  1384. EXECUTE_LHS_AND_RHS();
  1385. rhs_result = right_shift(global_object, lhs_result, rhs_result);
  1386. break;
  1387. case AssignmentOp::UnsignedRightShiftAssignment:
  1388. EXECUTE_LHS_AND_RHS();
  1389. rhs_result = unsigned_right_shift(global_object, lhs_result, rhs_result);
  1390. break;
  1391. case AssignmentOp::AndAssignment:
  1392. EXECUTE_LHS();
  1393. if (!lhs_result.to_boolean())
  1394. return lhs_result;
  1395. rhs_result = m_rhs->execute(interpreter, global_object);
  1396. break;
  1397. case AssignmentOp::OrAssignment:
  1398. EXECUTE_LHS();
  1399. if (lhs_result.to_boolean())
  1400. return lhs_result;
  1401. rhs_result = m_rhs->execute(interpreter, global_object);
  1402. break;
  1403. case AssignmentOp::NullishAssignment:
  1404. EXECUTE_LHS();
  1405. if (!lhs_result.is_nullish())
  1406. return lhs_result;
  1407. rhs_result = m_rhs->execute(interpreter, global_object);
  1408. break;
  1409. }
  1410. if (interpreter.exception())
  1411. return {};
  1412. return m_lhs.visit(
  1413. [&](NonnullRefPtr<Expression>& lhs) -> JS::Value {
  1414. auto reference = lhs->to_reference(interpreter, global_object);
  1415. if (interpreter.exception())
  1416. return {};
  1417. if (m_op == AssignmentOp::Assignment) {
  1418. rhs_result = m_rhs->execute(interpreter, global_object);
  1419. if (interpreter.exception())
  1420. return {};
  1421. }
  1422. if (reference.is_unresolvable()) {
  1423. interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::InvalidLeftHandAssignment);
  1424. return {};
  1425. }
  1426. reference.put_value(global_object, rhs_result);
  1427. if (interpreter.exception())
  1428. return {};
  1429. return rhs_result;
  1430. },
  1431. [&](NonnullRefPtr<BindingPattern>& pattern) -> JS::Value {
  1432. VERIFY(m_op == AssignmentOp::Assignment);
  1433. rhs_result = m_rhs->execute(interpreter, global_object);
  1434. if (interpreter.exception())
  1435. return {};
  1436. interpreter.vm().assign(pattern, rhs_result, global_object);
  1437. if (interpreter.exception())
  1438. return {};
  1439. return rhs_result;
  1440. });
  1441. }
  1442. Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1443. {
  1444. InterpreterNodeScope node_scope { interpreter, *this };
  1445. auto reference = m_argument->to_reference(interpreter, global_object);
  1446. if (interpreter.exception())
  1447. return {};
  1448. auto old_value = reference.get_value(global_object);
  1449. if (interpreter.exception())
  1450. return {};
  1451. old_value = old_value.to_numeric(global_object);
  1452. if (interpreter.exception())
  1453. return {};
  1454. Value new_value;
  1455. switch (m_op) {
  1456. case UpdateOp::Increment:
  1457. if (old_value.is_number())
  1458. new_value = Value(old_value.as_double() + 1);
  1459. else
  1460. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  1461. break;
  1462. case UpdateOp::Decrement:
  1463. if (old_value.is_number())
  1464. new_value = Value(old_value.as_double() - 1);
  1465. else
  1466. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  1467. break;
  1468. default:
  1469. VERIFY_NOT_REACHED();
  1470. }
  1471. reference.put_value(global_object, new_value);
  1472. if (interpreter.exception())
  1473. return {};
  1474. return m_prefixed ? new_value : old_value;
  1475. }
  1476. void AssignmentExpression::dump(int indent) const
  1477. {
  1478. const char* op_string = nullptr;
  1479. switch (m_op) {
  1480. case AssignmentOp::Assignment:
  1481. op_string = "=";
  1482. break;
  1483. case AssignmentOp::AdditionAssignment:
  1484. op_string = "+=";
  1485. break;
  1486. case AssignmentOp::SubtractionAssignment:
  1487. op_string = "-=";
  1488. break;
  1489. case AssignmentOp::MultiplicationAssignment:
  1490. op_string = "*=";
  1491. break;
  1492. case AssignmentOp::DivisionAssignment:
  1493. op_string = "/=";
  1494. break;
  1495. case AssignmentOp::ModuloAssignment:
  1496. op_string = "%=";
  1497. break;
  1498. case AssignmentOp::ExponentiationAssignment:
  1499. op_string = "**=";
  1500. break;
  1501. case AssignmentOp::BitwiseAndAssignment:
  1502. op_string = "&=";
  1503. break;
  1504. case AssignmentOp::BitwiseOrAssignment:
  1505. op_string = "|=";
  1506. break;
  1507. case AssignmentOp::BitwiseXorAssignment:
  1508. op_string = "^=";
  1509. break;
  1510. case AssignmentOp::LeftShiftAssignment:
  1511. op_string = "<<=";
  1512. break;
  1513. case AssignmentOp::RightShiftAssignment:
  1514. op_string = ">>=";
  1515. break;
  1516. case AssignmentOp::UnsignedRightShiftAssignment:
  1517. op_string = ">>>=";
  1518. break;
  1519. case AssignmentOp::AndAssignment:
  1520. op_string = "&&=";
  1521. break;
  1522. case AssignmentOp::OrAssignment:
  1523. op_string = "||=";
  1524. break;
  1525. case AssignmentOp::NullishAssignment:
  1526. op_string = "\?\?=";
  1527. break;
  1528. }
  1529. ASTNode::dump(indent);
  1530. print_indent(indent + 1);
  1531. outln("{}", op_string);
  1532. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1533. m_rhs->dump(indent + 1);
  1534. }
  1535. void UpdateExpression::dump(int indent) const
  1536. {
  1537. const char* op_string = nullptr;
  1538. switch (m_op) {
  1539. case UpdateOp::Increment:
  1540. op_string = "++";
  1541. break;
  1542. case UpdateOp::Decrement:
  1543. op_string = "--";
  1544. break;
  1545. }
  1546. ASTNode::dump(indent);
  1547. if (m_prefixed) {
  1548. print_indent(indent + 1);
  1549. outln("{}", op_string);
  1550. }
  1551. m_argument->dump(indent + 1);
  1552. if (!m_prefixed) {
  1553. print_indent(indent + 1);
  1554. outln("{}", op_string);
  1555. }
  1556. }
  1557. Value VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1558. {
  1559. InterpreterNodeScope node_scope { interpreter, *this };
  1560. for (auto& declarator : m_declarations) {
  1561. if (auto* init = declarator.init()) {
  1562. auto initializer_result = init->execute(interpreter, global_object);
  1563. if (interpreter.exception())
  1564. return {};
  1565. declarator.target().visit(
  1566. [&](NonnullRefPtr<Identifier> const& id) {
  1567. auto variable_name = id->string();
  1568. if (is<ClassExpression>(*init))
  1569. update_function_name(initializer_result, variable_name);
  1570. interpreter.vm().set_variable(variable_name, initializer_result, global_object, true);
  1571. },
  1572. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  1573. interpreter.vm().assign(pattern, initializer_result, global_object, true);
  1574. });
  1575. }
  1576. }
  1577. return {};
  1578. }
  1579. Value VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  1580. {
  1581. InterpreterNodeScope node_scope { interpreter, *this };
  1582. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  1583. VERIFY_NOT_REACHED();
  1584. }
  1585. void VariableDeclaration::dump(int indent) const
  1586. {
  1587. const char* declaration_kind_string = nullptr;
  1588. switch (m_declaration_kind) {
  1589. case DeclarationKind::Let:
  1590. declaration_kind_string = "Let";
  1591. break;
  1592. case DeclarationKind::Var:
  1593. declaration_kind_string = "Var";
  1594. break;
  1595. case DeclarationKind::Const:
  1596. declaration_kind_string = "Const";
  1597. break;
  1598. }
  1599. ASTNode::dump(indent);
  1600. print_indent(indent + 1);
  1601. outln("{}", declaration_kind_string);
  1602. for (auto& declarator : m_declarations)
  1603. declarator.dump(indent + 1);
  1604. }
  1605. void VariableDeclarator::dump(int indent) const
  1606. {
  1607. ASTNode::dump(indent);
  1608. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  1609. if (m_init)
  1610. m_init->dump(indent + 1);
  1611. }
  1612. void ObjectProperty::dump(int indent) const
  1613. {
  1614. ASTNode::dump(indent);
  1615. m_key->dump(indent + 1);
  1616. m_value->dump(indent + 1);
  1617. }
  1618. void ObjectExpression::dump(int indent) const
  1619. {
  1620. ASTNode::dump(indent);
  1621. for (auto& property : m_properties) {
  1622. property.dump(indent + 1);
  1623. }
  1624. }
  1625. void ExpressionStatement::dump(int indent) const
  1626. {
  1627. ASTNode::dump(indent);
  1628. m_expression->dump(indent + 1);
  1629. }
  1630. Value ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1631. {
  1632. InterpreterNodeScope node_scope { interpreter, *this };
  1633. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  1634. VERIFY_NOT_REACHED();
  1635. }
  1636. Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1637. {
  1638. InterpreterNodeScope node_scope { interpreter, *this };
  1639. auto* object = Object::create(global_object, global_object.object_prototype());
  1640. for (auto& property : m_properties) {
  1641. auto key = property.key().execute(interpreter, global_object);
  1642. if (interpreter.exception())
  1643. return {};
  1644. if (property.type() == ObjectProperty::Type::Spread) {
  1645. if (key.is_object() && is<Array>(key.as_object())) {
  1646. auto& array_to_spread = static_cast<Array&>(key.as_object());
  1647. for (auto& entry : array_to_spread.indexed_properties()) {
  1648. auto value = array_to_spread.get(entry.index());
  1649. if (interpreter.exception())
  1650. return {};
  1651. object->indexed_properties().put(entry.index(), value);
  1652. if (interpreter.exception())
  1653. return {};
  1654. }
  1655. } else if (key.is_object()) {
  1656. auto& obj_to_spread = key.as_object();
  1657. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  1658. if (it.value.attributes.is_enumerable()) {
  1659. object->define_direct_property(it.key, obj_to_spread.get(it.key), JS::default_attributes);
  1660. if (interpreter.exception())
  1661. return {};
  1662. }
  1663. }
  1664. } else if (key.is_string()) {
  1665. auto& str_to_spread = key.as_string().string();
  1666. for (size_t i = 0; i < str_to_spread.length(); i++) {
  1667. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  1668. if (interpreter.exception())
  1669. return {};
  1670. }
  1671. }
  1672. continue;
  1673. }
  1674. auto value = property.value().execute(interpreter, global_object);
  1675. if (interpreter.exception())
  1676. return {};
  1677. if (value.is_function() && property.is_method())
  1678. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  1679. String name = get_function_name(global_object, key);
  1680. if (property.type() == ObjectProperty::Type::Getter) {
  1681. name = String::formatted("get {}", name);
  1682. } else if (property.type() == ObjectProperty::Type::Setter) {
  1683. name = String::formatted("set {}", name);
  1684. }
  1685. update_function_name(value, name);
  1686. switch (property.type()) {
  1687. case ObjectProperty::Type::Getter:
  1688. VERIFY(value.is_function());
  1689. object->define_direct_accessor(PropertyName::from_value(global_object, key), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  1690. break;
  1691. case ObjectProperty::Type::Setter:
  1692. VERIFY(value.is_function());
  1693. object->define_direct_accessor(PropertyName::from_value(global_object, key), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  1694. break;
  1695. case ObjectProperty::Type::KeyValue:
  1696. object->define_direct_property(PropertyName::from_value(global_object, key), value, JS::default_attributes);
  1697. break;
  1698. case ObjectProperty::Type::Spread:
  1699. default:
  1700. VERIFY_NOT_REACHED();
  1701. }
  1702. if (interpreter.exception())
  1703. return {};
  1704. }
  1705. return object;
  1706. }
  1707. void MemberExpression::dump(int indent) const
  1708. {
  1709. print_indent(indent);
  1710. outln("{}(computed={})", class_name(), is_computed());
  1711. m_object->dump(indent + 1);
  1712. m_property->dump(indent + 1);
  1713. }
  1714. PropertyName MemberExpression::computed_property_name(Interpreter& interpreter, GlobalObject& global_object) const
  1715. {
  1716. if (!is_computed())
  1717. return verify_cast<Identifier>(*m_property).string();
  1718. auto value = m_property->execute(interpreter, global_object);
  1719. if (interpreter.exception())
  1720. return {};
  1721. VERIFY(!value.is_empty());
  1722. return PropertyName::from_value(global_object, value);
  1723. }
  1724. String MemberExpression::to_string_approximation() const
  1725. {
  1726. String object_string = "<object>";
  1727. if (is<Identifier>(*m_object))
  1728. object_string = static_cast<Identifier const&>(*m_object).string();
  1729. if (is_computed())
  1730. return String::formatted("{}[<computed>]", object_string);
  1731. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  1732. }
  1733. Value MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1734. {
  1735. InterpreterNodeScope node_scope { interpreter, *this };
  1736. auto reference = to_reference(interpreter, global_object);
  1737. if (interpreter.exception())
  1738. return {};
  1739. return reference.get_value(global_object);
  1740. }
  1741. void OptionalChain::dump(int indent) const
  1742. {
  1743. print_indent(indent);
  1744. outln("{}", class_name());
  1745. m_base->dump(indent + 1);
  1746. for (auto& reference : m_references) {
  1747. reference.visit(
  1748. [&](Call const& call) {
  1749. print_indent(indent + 1);
  1750. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  1751. for (auto& argument : call.arguments)
  1752. argument.value->dump(indent + 2);
  1753. },
  1754. [&](ComputedReference const& ref) {
  1755. print_indent(indent + 1);
  1756. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1757. ref.expression->dump(indent + 2);
  1758. },
  1759. [&](MemberReference const& ref) {
  1760. print_indent(indent + 1);
  1761. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1762. ref.identifier->dump(indent + 2);
  1763. });
  1764. }
  1765. }
  1766. Optional<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  1767. {
  1768. // Note: This is wrapped in an optional to allow base_reference = ...
  1769. Optional<JS::Reference> base_reference = m_base->to_reference(interpreter, global_object);
  1770. auto base = base_reference->is_unresolvable() ? m_base->execute(interpreter, global_object) : base_reference->get_value(global_object);
  1771. if (interpreter.exception())
  1772. return {};
  1773. for (auto& reference : m_references) {
  1774. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  1775. if (is_optional && base.is_nullish())
  1776. return ReferenceAndValue { {}, js_undefined() };
  1777. auto expression = reference.visit(
  1778. [&](Call const& call) -> NonnullRefPtr<Expression> {
  1779. return create_ast_node<CallExpression>(source_range(),
  1780. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1781. call.arguments);
  1782. },
  1783. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  1784. return create_ast_node<MemberExpression>(source_range(),
  1785. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1786. ref.expression,
  1787. true);
  1788. },
  1789. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  1790. return create_ast_node<MemberExpression>(source_range(),
  1791. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1792. ref.identifier,
  1793. false);
  1794. });
  1795. if (is<CallExpression>(*expression)) {
  1796. base_reference = JS::Reference {};
  1797. base = expression->execute(interpreter, global_object);
  1798. } else {
  1799. base_reference = expression->to_reference(interpreter, global_object);
  1800. base = base_reference->get_value(global_object);
  1801. }
  1802. if (interpreter.exception())
  1803. return {};
  1804. }
  1805. return ReferenceAndValue { base_reference.release_value(), base };
  1806. }
  1807. Value OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1808. {
  1809. InterpreterNodeScope node_scope { interpreter, *this };
  1810. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  1811. return result.release_value().value;
  1812. return {};
  1813. }
  1814. JS::Reference OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  1815. {
  1816. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  1817. return result.release_value().reference;
  1818. return {};
  1819. }
  1820. void MetaProperty::dump(int indent) const
  1821. {
  1822. String name;
  1823. if (m_type == MetaProperty::Type::NewTarget)
  1824. name = "new.target";
  1825. else if (m_type == MetaProperty::Type::ImportMeta)
  1826. name = "import.meta";
  1827. else
  1828. VERIFY_NOT_REACHED();
  1829. print_indent(indent);
  1830. outln("{} {}", class_name(), name);
  1831. }
  1832. Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1833. {
  1834. InterpreterNodeScope node_scope { interpreter, *this };
  1835. if (m_type == MetaProperty::Type::NewTarget)
  1836. return interpreter.vm().get_new_target().value_or(js_undefined());
  1837. if (m_type == MetaProperty::Type::ImportMeta)
  1838. TODO();
  1839. VERIFY_NOT_REACHED();
  1840. }
  1841. Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1842. {
  1843. InterpreterNodeScope node_scope { interpreter, *this };
  1844. return js_string(interpreter.heap(), m_value);
  1845. }
  1846. Value NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1847. {
  1848. InterpreterNodeScope node_scope { interpreter, *this };
  1849. return Value(m_value);
  1850. }
  1851. Value BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1852. {
  1853. InterpreterNodeScope node_scope { interpreter, *this };
  1854. Crypto::SignedBigInteger integer;
  1855. if (m_value[0] == '0' && m_value.length() >= 3) {
  1856. if (m_value[1] == 'x' || m_value[1] == 'X') {
  1857. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3)));
  1858. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  1859. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3)));
  1860. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  1861. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3)));
  1862. }
  1863. }
  1864. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  1865. }
  1866. Value BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1867. {
  1868. InterpreterNodeScope node_scope { interpreter, *this };
  1869. return Value(m_value);
  1870. }
  1871. Value NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1872. {
  1873. InterpreterNodeScope node_scope { interpreter, *this };
  1874. return js_null();
  1875. }
  1876. void RegExpLiteral::dump(int indent) const
  1877. {
  1878. print_indent(indent);
  1879. outln("{} (/{}/{})", class_name(), pattern(), flags());
  1880. }
  1881. Value RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1882. {
  1883. InterpreterNodeScope node_scope { interpreter, *this };
  1884. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  1885. return RegExpObject::create(global_object, move(regex), pattern(), flags());
  1886. }
  1887. void ArrayExpression::dump(int indent) const
  1888. {
  1889. ASTNode::dump(indent);
  1890. for (auto& element : m_elements) {
  1891. if (element) {
  1892. element->dump(indent + 1);
  1893. } else {
  1894. print_indent(indent + 1);
  1895. outln("<empty>");
  1896. }
  1897. }
  1898. }
  1899. Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1900. {
  1901. InterpreterNodeScope node_scope { interpreter, *this };
  1902. auto* array = Array::create(global_object, 0);
  1903. array->indexed_properties();
  1904. size_t index = 0;
  1905. for (auto& element : m_elements) {
  1906. auto value = Value();
  1907. if (element) {
  1908. value = element->execute(interpreter, global_object);
  1909. if (interpreter.exception())
  1910. return {};
  1911. if (is<SpreadExpression>(*element)) {
  1912. get_iterator_values(global_object, value, [&](Value iterator_value) {
  1913. array->indexed_properties().put(index++, iterator_value, default_attributes);
  1914. return IterationDecision::Continue;
  1915. });
  1916. if (interpreter.exception())
  1917. return {};
  1918. continue;
  1919. }
  1920. }
  1921. array->indexed_properties().put(index++, value, default_attributes);
  1922. }
  1923. return array;
  1924. }
  1925. void TemplateLiteral::dump(int indent) const
  1926. {
  1927. ASTNode::dump(indent);
  1928. for (auto& expression : m_expressions)
  1929. expression.dump(indent + 1);
  1930. }
  1931. Value TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1932. {
  1933. InterpreterNodeScope node_scope { interpreter, *this };
  1934. StringBuilder string_builder;
  1935. for (auto& expression : m_expressions) {
  1936. auto expr = expression.execute(interpreter, global_object);
  1937. if (interpreter.exception())
  1938. return {};
  1939. auto string = expr.to_string(global_object);
  1940. if (interpreter.exception())
  1941. return {};
  1942. string_builder.append(string);
  1943. }
  1944. return js_string(interpreter.heap(), string_builder.build());
  1945. }
  1946. void TaggedTemplateLiteral::dump(int indent) const
  1947. {
  1948. ASTNode::dump(indent);
  1949. print_indent(indent + 1);
  1950. outln("(Tag)");
  1951. m_tag->dump(indent + 2);
  1952. print_indent(indent + 1);
  1953. outln("(Template Literal)");
  1954. m_template_literal->dump(indent + 2);
  1955. }
  1956. Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1957. {
  1958. InterpreterNodeScope node_scope { interpreter, *this };
  1959. auto& vm = interpreter.vm();
  1960. auto tag = m_tag->execute(interpreter, global_object);
  1961. if (vm.exception())
  1962. return {};
  1963. if (!tag.is_function()) {
  1964. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, tag.to_string_without_side_effects());
  1965. return {};
  1966. }
  1967. auto& tag_function = tag.as_function();
  1968. auto& expressions = m_template_literal->expressions();
  1969. auto* strings = Array::create(global_object, 0);
  1970. MarkedValueList arguments(vm.heap());
  1971. arguments.append(strings);
  1972. for (size_t i = 0; i < expressions.size(); ++i) {
  1973. auto value = expressions[i].execute(interpreter, global_object);
  1974. if (vm.exception())
  1975. return {};
  1976. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  1977. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  1978. if (i % 2 == 0) {
  1979. strings->indexed_properties().append(value);
  1980. } else {
  1981. arguments.append(value);
  1982. }
  1983. }
  1984. auto* raw_strings = Array::create(global_object, 0);
  1985. for (auto& raw_string : m_template_literal->raw_strings()) {
  1986. auto value = raw_string.execute(interpreter, global_object);
  1987. if (vm.exception())
  1988. return {};
  1989. raw_strings->indexed_properties().append(value);
  1990. }
  1991. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  1992. return TRY_OR_DISCARD(vm.call(tag_function, js_undefined(), move(arguments)));
  1993. }
  1994. void TryStatement::dump(int indent) const
  1995. {
  1996. ASTNode::dump(indent);
  1997. print_indent(indent);
  1998. outln("(Block)");
  1999. block().dump(indent + 1);
  2000. if (handler()) {
  2001. print_indent(indent);
  2002. outln("(Handler)");
  2003. handler()->dump(indent + 1);
  2004. }
  2005. if (finalizer()) {
  2006. print_indent(indent);
  2007. outln("(Finalizer)");
  2008. finalizer()->dump(indent + 1);
  2009. }
  2010. }
  2011. void CatchClause::dump(int indent) const
  2012. {
  2013. print_indent(indent);
  2014. m_parameter.visit(
  2015. [&](FlyString const& parameter) {
  2016. if (parameter.is_null())
  2017. outln("CatchClause");
  2018. else
  2019. outln("CatchClause ({})", parameter);
  2020. },
  2021. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2022. outln("CatchClause");
  2023. print_indent(indent);
  2024. outln("(Parameter)");
  2025. pattern->dump(indent + 2);
  2026. });
  2027. body().dump(indent + 1);
  2028. }
  2029. void ThrowStatement::dump(int indent) const
  2030. {
  2031. ASTNode::dump(indent);
  2032. argument().dump(indent + 1);
  2033. }
  2034. Value TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2035. {
  2036. InterpreterNodeScope node_scope { interpreter, *this };
  2037. auto result = interpreter.execute_statement(global_object, m_block, ScopeType::Try);
  2038. if (auto* exception = interpreter.exception()) {
  2039. if (m_handler) {
  2040. interpreter.vm().clear_exception();
  2041. HashMap<FlyString, Variable> parameters;
  2042. m_handler->parameter().visit(
  2043. [&](FlyString const& parameter) {
  2044. parameters.set(parameter, Variable { exception->value(), DeclarationKind::Var });
  2045. },
  2046. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2047. pattern->for_each_bound_name([&](auto& name) {
  2048. parameters.set(name, Variable { Value {}, DeclarationKind::Var });
  2049. });
  2050. });
  2051. auto* catch_scope = interpreter.heap().allocate<DeclarativeEnvironment>(global_object, move(parameters), interpreter.vm().running_execution_context().lexical_environment);
  2052. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, catch_scope);
  2053. if (auto* pattern = m_handler->parameter().get_pointer<NonnullRefPtr<BindingPattern>>())
  2054. interpreter.vm().assign(*pattern, exception->value(), global_object, true);
  2055. if (interpreter.exception())
  2056. result = js_undefined();
  2057. else
  2058. result = interpreter.execute_statement(global_object, m_handler->body());
  2059. }
  2060. }
  2061. if (m_finalizer) {
  2062. // Keep, if any, and then clear the current exception so we can
  2063. // execute() the finalizer without an exception in our way.
  2064. auto* previous_exception = interpreter.exception();
  2065. interpreter.vm().clear_exception();
  2066. // Remember what scope type we were unwinding to, and temporarily
  2067. // clear it as well (e.g. return from handler).
  2068. auto unwind_until = interpreter.vm().unwind_until();
  2069. interpreter.vm().stop_unwind();
  2070. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2071. if (interpreter.vm().should_unwind()) {
  2072. // This was NOT a 'normal' completion (e.g. return from finalizer).
  2073. result = finalizer_result;
  2074. } else {
  2075. // Continue unwinding to whatever we found ourselves unwinding
  2076. // to when the finalizer was entered (e.g. return from handler,
  2077. // which is unaffected by normal completion from finalizer).
  2078. interpreter.vm().unwind(unwind_until);
  2079. // If we previously had an exception and the finalizer didn't
  2080. // throw a new one, restore the old one.
  2081. if (previous_exception && !interpreter.exception())
  2082. interpreter.vm().set_exception(*previous_exception);
  2083. }
  2084. }
  2085. return result.value_or(js_undefined());
  2086. }
  2087. Value CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2088. {
  2089. InterpreterNodeScope node_scope { interpreter, *this };
  2090. // NOTE: CatchClause execution is handled by TryStatement.
  2091. VERIFY_NOT_REACHED();
  2092. return {};
  2093. }
  2094. Value ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2095. {
  2096. InterpreterNodeScope node_scope { interpreter, *this };
  2097. auto value = m_argument->execute(interpreter, global_object);
  2098. if (interpreter.vm().exception())
  2099. return {};
  2100. interpreter.vm().throw_exception(global_object, value);
  2101. return {};
  2102. }
  2103. Value SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2104. {
  2105. // FIXME: This needs a massive refactoring, ideally once we start using continue, break, and return completions.
  2106. // Instead of having an optional test expression, SwitchCase should be split into CaseClause and DefaultClause.
  2107. // https://tc39.es/ecma262/#sec-switch-statement
  2108. InterpreterNodeScope node_scope { interpreter, *this };
  2109. auto discriminant_result = m_discriminant->execute(interpreter, global_object);
  2110. if (interpreter.exception())
  2111. return {};
  2112. auto last_value = js_undefined();
  2113. auto execute_switch_case = [&](auto const& switch_case) -> Optional<Value> {
  2114. for (auto& statement : switch_case.consequent()) {
  2115. auto value = statement.execute(interpreter, global_object);
  2116. if (!value.is_empty())
  2117. last_value = value;
  2118. if (interpreter.exception())
  2119. return Value {};
  2120. if (interpreter.vm().should_unwind()) {
  2121. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  2122. // No stop_unwind(), the outer loop will handle that - we just need to break out of the switch/case.
  2123. return last_value;
  2124. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  2125. interpreter.vm().stop_unwind();
  2126. return last_value;
  2127. } else {
  2128. return last_value;
  2129. }
  2130. }
  2131. }
  2132. return {};
  2133. };
  2134. bool falling_through = false;
  2135. SwitchCase const* default_switch_case = nullptr;
  2136. for (auto& switch_case : m_cases) {
  2137. if (!switch_case.test()) {
  2138. default_switch_case = &switch_case;
  2139. falling_through = true;
  2140. continue;
  2141. }
  2142. if (!falling_through) {
  2143. auto test_result = switch_case.test()->execute(interpreter, global_object);
  2144. if (interpreter.exception())
  2145. return {};
  2146. if (!is_strictly_equal(discriminant_result, test_result))
  2147. continue;
  2148. }
  2149. falling_through = true;
  2150. if (auto result = execute_switch_case(switch_case); result.has_value())
  2151. return *result;
  2152. }
  2153. if (default_switch_case) {
  2154. if (auto result = execute_switch_case(*default_switch_case); result.has_value())
  2155. return *result;
  2156. }
  2157. return last_value;
  2158. }
  2159. Value SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  2160. {
  2161. InterpreterNodeScope node_scope { interpreter, *this };
  2162. // NOTE: SwitchCase execution is handled by SwitchStatement.
  2163. VERIFY_NOT_REACHED();
  2164. return {};
  2165. }
  2166. Value BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2167. {
  2168. InterpreterNodeScope node_scope { interpreter, *this };
  2169. interpreter.vm().unwind(ScopeType::Breakable, m_target_label);
  2170. return {};
  2171. }
  2172. Value ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2173. {
  2174. InterpreterNodeScope node_scope { interpreter, *this };
  2175. interpreter.vm().unwind(ScopeType::Continuable, m_target_label);
  2176. return {};
  2177. }
  2178. void SwitchStatement::dump(int indent) const
  2179. {
  2180. ASTNode::dump(indent);
  2181. m_discriminant->dump(indent + 1);
  2182. for (auto& switch_case : m_cases) {
  2183. switch_case.dump(indent + 1);
  2184. }
  2185. }
  2186. void SwitchCase::dump(int indent) const
  2187. {
  2188. ASTNode::dump(indent);
  2189. print_indent(indent + 1);
  2190. if (m_test) {
  2191. outln("(Test)");
  2192. m_test->dump(indent + 2);
  2193. } else {
  2194. outln("(Default)");
  2195. }
  2196. print_indent(indent + 1);
  2197. outln("(Consequent)");
  2198. for (auto& statement : m_consequent)
  2199. statement.dump(indent + 2);
  2200. }
  2201. Value ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2202. {
  2203. InterpreterNodeScope node_scope { interpreter, *this };
  2204. auto test_result = m_test->execute(interpreter, global_object);
  2205. if (interpreter.exception())
  2206. return {};
  2207. Value result;
  2208. if (test_result.to_boolean()) {
  2209. result = m_consequent->execute(interpreter, global_object);
  2210. } else {
  2211. result = m_alternate->execute(interpreter, global_object);
  2212. }
  2213. if (interpreter.exception())
  2214. return {};
  2215. return result;
  2216. }
  2217. void ConditionalExpression::dump(int indent) const
  2218. {
  2219. ASTNode::dump(indent);
  2220. print_indent(indent + 1);
  2221. outln("(Test)");
  2222. m_test->dump(indent + 2);
  2223. print_indent(indent + 1);
  2224. outln("(Consequent)");
  2225. m_consequent->dump(indent + 2);
  2226. print_indent(indent + 1);
  2227. outln("(Alternate)");
  2228. m_alternate->dump(indent + 2);
  2229. }
  2230. void SequenceExpression::dump(int indent) const
  2231. {
  2232. ASTNode::dump(indent);
  2233. for (auto& expression : m_expressions)
  2234. expression.dump(indent + 1);
  2235. }
  2236. Value SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2237. {
  2238. InterpreterNodeScope node_scope { interpreter, *this };
  2239. Value last_value;
  2240. for (auto& expression : m_expressions) {
  2241. last_value = expression.execute(interpreter, global_object);
  2242. if (interpreter.exception())
  2243. return {};
  2244. }
  2245. return last_value;
  2246. }
  2247. Value DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2248. {
  2249. InterpreterNodeScope node_scope { interpreter, *this };
  2250. // Sorry, no JavaScript debugger available (yet)!
  2251. return {};
  2252. }
  2253. void ScopeNode::add_variables(NonnullRefPtrVector<VariableDeclaration> variables)
  2254. {
  2255. m_variables.extend(move(variables));
  2256. }
  2257. void ScopeNode::add_functions(NonnullRefPtrVector<FunctionDeclaration> functions)
  2258. {
  2259. m_functions.extend(move(functions));
  2260. }
  2261. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> hoisted_function)
  2262. {
  2263. m_hoisted_functions.append(hoisted_function);
  2264. }
  2265. Value ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2266. {
  2267. InterpreterNodeScope node_scope { interpreter, *this };
  2268. dbgln("Modules are not fully supported yet!");
  2269. TODO();
  2270. return {};
  2271. }
  2272. Value ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2273. {
  2274. InterpreterNodeScope node_scope { interpreter, *this };
  2275. if (m_statement)
  2276. return m_statement->execute(interpreter, global_object);
  2277. return {};
  2278. }
  2279. void ExportStatement::dump(int indent) const
  2280. {
  2281. ASTNode::dump(indent);
  2282. print_indent(indent + 1);
  2283. outln("(ExportEntries)");
  2284. auto string_or_null = [](String const& string) -> String {
  2285. if (string.is_empty()) {
  2286. return "null";
  2287. }
  2288. return String::formatted("\"{}\"", string);
  2289. };
  2290. for (auto& entry : m_entries) {
  2291. print_indent(indent + 2);
  2292. 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));
  2293. }
  2294. }
  2295. void ImportStatement::dump(int indent) const
  2296. {
  2297. ASTNode::dump(indent);
  2298. print_indent(indent + 1);
  2299. if (m_entries.is_empty()) {
  2300. // direct from "module" import
  2301. outln("Entire module '{}'", m_module_request);
  2302. } else {
  2303. outln("(ExportEntries) from {}", m_module_request);
  2304. for (auto& entry : m_entries) {
  2305. print_indent(indent + 2);
  2306. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  2307. }
  2308. }
  2309. }
  2310. bool ExportStatement::has_export(StringView export_name) const
  2311. {
  2312. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2313. return entry.export_name == export_name;
  2314. });
  2315. }
  2316. bool ImportStatement::has_bound_name(StringView name) const
  2317. {
  2318. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2319. return entry.local_name == name;
  2320. });
  2321. }
  2322. }