AST.cpp 87 KB

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