AST.cpp 78 KB

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