AST.cpp 78 KB

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