AST.cpp 88 KB

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