AST.cpp 80 KB

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