AST.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Demangle.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/HashTable.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/StringBuilder.h>
  12. #include <AK/TemporaryChange.h>
  13. #include <LibCrypto/BigInt/SignedBigInteger.h>
  14. #include <LibJS/AST.h>
  15. #include <LibJS/Interpreter.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/Accessor.h>
  18. #include <LibJS/Runtime/Array.h>
  19. #include <LibJS/Runtime/BigInt.h>
  20. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  21. #include <LibJS/Runtime/Error.h>
  22. #include <LibJS/Runtime/FunctionEnvironment.h>
  23. #include <LibJS/Runtime/GlobalObject.h>
  24. #include <LibJS/Runtime/IteratorOperations.h>
  25. #include <LibJS/Runtime/MarkedValueList.h>
  26. #include <LibJS/Runtime/NativeFunction.h>
  27. #include <LibJS/Runtime/ObjectEnvironment.h>
  28. #include <LibJS/Runtime/PrimitiveString.h>
  29. #include <LibJS/Runtime/Reference.h>
  30. #include <LibJS/Runtime/RegExpObject.h>
  31. #include <LibJS/Runtime/Shape.h>
  32. #include <typeinfo>
  33. namespace JS {
  34. class InterpreterNodeScope {
  35. AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
  36. AK_MAKE_NONMOVABLE(InterpreterNodeScope);
  37. public:
  38. InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
  39. : m_interpreter(interpreter)
  40. , m_chain_node { nullptr, node }
  41. {
  42. m_interpreter.vm().running_execution_context().current_node = &node;
  43. m_interpreter.push_ast_node(m_chain_node);
  44. }
  45. ~InterpreterNodeScope()
  46. {
  47. m_interpreter.pop_ast_node();
  48. }
  49. private:
  50. Interpreter& m_interpreter;
  51. ExecutingASTNodeChain m_chain_node;
  52. };
  53. String ASTNode::class_name() const
  54. {
  55. // NOTE: We strip the "JS::" prefix.
  56. return demangle(typeid(*this).name()).substring(4);
  57. }
  58. static void update_function_name(Value value, FlyString const& name)
  59. {
  60. if (!value.is_function())
  61. return;
  62. auto& function = value.as_function();
  63. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  64. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  65. }
  66. static String get_function_name(GlobalObject& global_object, Value value)
  67. {
  68. if (value.is_symbol())
  69. return String::formatted("[{}]", value.as_symbol().description());
  70. if (value.is_string())
  71. return value.as_string().string();
  72. return value.to_string(global_object);
  73. }
  74. Value ScopeNode::execute(Interpreter& interpreter, GlobalObject& global_object) const
  75. {
  76. InterpreterNodeScope node_scope { interpreter, *this };
  77. return interpreter.execute_statement(global_object, *this);
  78. }
  79. Value Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  80. {
  81. InterpreterNodeScope node_scope { interpreter, *this };
  82. return interpreter.execute_statement(global_object, *this, ScopeType::Block);
  83. }
  84. Value FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject&) const
  85. {
  86. InterpreterNodeScope node_scope { interpreter, *this };
  87. return {};
  88. }
  89. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  90. Value FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  91. {
  92. InterpreterNodeScope node_scope { interpreter, *this };
  93. auto* func_env = interpreter.lexical_environment();
  94. bool has_identifier = !name().is_empty() && !is_auto_renamed();
  95. if (has_identifier) {
  96. func_env = interpreter.heap().allocate<DeclarativeEnvironment>(global_object, func_env);
  97. func_env->create_immutable_binding(global_object, name(), false);
  98. }
  99. auto closure = ECMAScriptFunctionObject::create(global_object, name(), body(), parameters(), function_length(), func_env, kind(), is_strict_mode(), is_arrow_function());
  100. if (has_identifier)
  101. func_env->initialize_binding(global_object, name(), closure);
  102. return closure;
  103. }
  104. Value ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  105. {
  106. InterpreterNodeScope node_scope { interpreter, *this };
  107. return m_expression->execute(interpreter, global_object);
  108. }
  109. CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  110. {
  111. auto& vm = interpreter.vm();
  112. if (callee_reference.is_property_reference()) {
  113. auto this_value = callee_reference.get_this_value();
  114. auto callee = callee_reference.get_value(global_object);
  115. if (vm.exception())
  116. return {};
  117. return { this_value, callee };
  118. }
  119. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  120. return {
  121. js_undefined(),
  122. callee_reference.is_unresolvable()
  123. ? m_callee->execute(interpreter, global_object)
  124. : callee_reference.get_value(global_object)
  125. };
  126. }
  127. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  128. static void argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list)
  129. {
  130. auto& vm = global_object.vm();
  131. list.ensure_capacity(arguments.size());
  132. for (auto& argument : arguments) {
  133. auto value = argument.value->execute(interpreter, global_object);
  134. if (vm.exception())
  135. return;
  136. if (argument.is_spread) {
  137. get_iterator_values(global_object, value, [&](Value iterator_value) {
  138. if (vm.exception())
  139. return IterationDecision::Break;
  140. list.append(iterator_value);
  141. return IterationDecision::Continue;
  142. });
  143. if (vm.exception())
  144. return;
  145. } else {
  146. list.append(value);
  147. }
  148. }
  149. }
  150. Value NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  151. {
  152. InterpreterNodeScope node_scope { interpreter, *this };
  153. auto& vm = interpreter.vm();
  154. auto callee_value = m_callee->execute(interpreter, global_object);
  155. if (vm.exception())
  156. return {};
  157. if (!callee_value.is_function() || (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 TRY_OR_DISCARD(perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  209. }
  210. return TRY_OR_DISCARD(vm.call(function, this_value, move(arg_list)));
  211. }
  212. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  213. // SuperCall : super Arguments
  214. Value SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  215. {
  216. InterpreterNodeScope node_scope { interpreter, *this };
  217. auto& vm = interpreter.vm();
  218. // 1. Let newTarget be GetNewTarget().
  219. auto new_target = vm.get_new_target();
  220. if (vm.exception())
  221. return {};
  222. // 2. Assert: Type(newTarget) is Object.
  223. VERIFY(new_target.is_function());
  224. // 3. Let func be ! GetSuperConstructor().
  225. auto* func = get_super_constructor(interpreter.vm());
  226. VERIFY(!vm.exception());
  227. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  228. MarkedValueList arg_list(vm.heap());
  229. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  230. if (interpreter.exception())
  231. return {};
  232. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  233. // FIXME: This check is non-conforming.
  234. if (!func || !func->is_function()) {
  235. vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  236. return {};
  237. }
  238. // 6. Let result be ? Construct(func, argList, newTarget).
  239. auto& function = new_target.as_function();
  240. auto result = vm.construct(static_cast<FunctionObject&>(*func), function, move(arg_list));
  241. if (vm.exception())
  242. return {};
  243. // 7. Let thisER be GetThisEnvironment().
  244. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  245. // 8. Perform ? thisER.BindThisValue(result).
  246. this_er.bind_this_value(global_object, result);
  247. if (vm.exception())
  248. return {};
  249. // 9. Let F be thisER.[[FunctionObject]].
  250. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  251. [[maybe_unused]] auto& f = this_er.function_object();
  252. // 11. Perform ? InitializeInstanceElements(result, F).
  253. VERIFY(result.is_object());
  254. vm.initialize_instance_elements(result.as_object(), f);
  255. // 12. Return result.
  256. return result;
  257. }
  258. Value YieldExpression::execute(Interpreter&, GlobalObject&) const
  259. {
  260. // This should be transformed to a return.
  261. VERIFY_NOT_REACHED();
  262. }
  263. Value ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  264. {
  265. InterpreterNodeScope node_scope { interpreter, *this };
  266. auto value = argument() ? argument()->execute(interpreter, global_object) : js_undefined();
  267. if (interpreter.exception())
  268. return {};
  269. interpreter.vm().unwind(ScopeType::Function);
  270. return value;
  271. }
  272. Value IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  273. {
  274. InterpreterNodeScope node_scope { interpreter, *this };
  275. auto predicate_result = m_predicate->execute(interpreter, global_object);
  276. if (interpreter.exception())
  277. return {};
  278. if (predicate_result.to_boolean())
  279. return interpreter.execute_statement(global_object, *m_consequent);
  280. if (m_alternate)
  281. return interpreter.execute_statement(global_object, *m_alternate);
  282. return js_undefined();
  283. }
  284. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  285. // WithStatement : with ( Expression ) Statement
  286. Value WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  287. {
  288. InterpreterNodeScope node_scope { interpreter, *this };
  289. // 1. Let value be the result of evaluating Expression.
  290. auto value = m_object->execute(interpreter, global_object);
  291. if (interpreter.exception())
  292. return {};
  293. // 2. Let obj be ? ToObject(? GetValue(value)).
  294. auto* object = value.to_object(global_object);
  295. if (interpreter.exception())
  296. return {};
  297. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  298. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  299. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  300. auto* new_environment = new_object_environment(*object, true, old_environment);
  301. if (interpreter.exception())
  302. return {};
  303. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  304. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  305. // 6. Let C be the result of evaluating Statement.
  306. auto result = interpreter.execute_statement(global_object, m_body).value_or(js_undefined());
  307. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  308. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  309. if (interpreter.exception())
  310. return {};
  311. // 8. Return Completion(UpdateEmpty(C, undefined)).
  312. return result;
  313. }
  314. Value WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  315. {
  316. InterpreterNodeScope node_scope { interpreter, *this };
  317. auto last_value = js_undefined();
  318. for (;;) {
  319. auto test_result = m_test->execute(interpreter, global_object);
  320. if (interpreter.exception())
  321. return {};
  322. if (!test_result.to_boolean())
  323. break;
  324. last_value = interpreter.execute_statement(global_object, *m_body).value_or(last_value);
  325. if (interpreter.exception())
  326. return {};
  327. if (interpreter.vm().should_unwind()) {
  328. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_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::StrictlyEquals:
  565. return Value(is_strictly_equal(lhs_result, rhs_result));
  566. case BinaryOp::StrictlyInequals:
  567. return Value(!is_strictly_equal(lhs_result, rhs_result));
  568. case BinaryOp::LooselyEquals:
  569. return Value(is_loosely_equal(global_object, lhs_result, rhs_result));
  570. case BinaryOp::LooselyInequals:
  571. return Value(!is_loosely_equal(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 TRY_OR_DISCARD(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<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  753. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&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 = ECMAScriptFunctionObject::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 = TRY_OR_DISCARD(interpreter.vm().call(*initializer, class_constructor_value));
  843. class_constructor->create_data_property_or_throw(property_key, field_value);
  844. if (interpreter.exception())
  845. return {};
  846. } else {
  847. class_constructor->add_field(property_key, initializer);
  848. }
  849. }
  850. return class_constructor;
  851. }
  852. Value ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  853. {
  854. InterpreterNodeScope node_scope { interpreter, *this };
  855. Value class_constructor = m_class_expression->execute(interpreter, global_object);
  856. if (interpreter.exception())
  857. return {};
  858. interpreter.lexical_environment()->put_into_environment(m_class_expression->name(), { class_constructor, DeclarationKind::Let });
  859. return {};
  860. }
  861. static void print_indent(int indent)
  862. {
  863. out("{}", String::repeated(' ', indent * 2));
  864. }
  865. void ASTNode::dump(int indent) const
  866. {
  867. print_indent(indent);
  868. outln("{}", class_name());
  869. }
  870. void ScopeNode::dump(int indent) const
  871. {
  872. ASTNode::dump(indent);
  873. if (!m_variables.is_empty()) {
  874. print_indent(indent + 1);
  875. outln("(Variables)");
  876. for (auto& variable : m_variables)
  877. variable.dump(indent + 2);
  878. }
  879. if (!m_children.is_empty()) {
  880. print_indent(indent + 1);
  881. outln("(Children)");
  882. for (auto& child : children())
  883. child.dump(indent + 2);
  884. }
  885. }
  886. void BinaryExpression::dump(int indent) const
  887. {
  888. const char* op_string = nullptr;
  889. switch (m_op) {
  890. case BinaryOp::Addition:
  891. op_string = "+";
  892. break;
  893. case BinaryOp::Subtraction:
  894. op_string = "-";
  895. break;
  896. case BinaryOp::Multiplication:
  897. op_string = "*";
  898. break;
  899. case BinaryOp::Division:
  900. op_string = "/";
  901. break;
  902. case BinaryOp::Modulo:
  903. op_string = "%";
  904. break;
  905. case BinaryOp::Exponentiation:
  906. op_string = "**";
  907. break;
  908. case BinaryOp::StrictlyEquals:
  909. op_string = "===";
  910. break;
  911. case BinaryOp::StrictlyInequals:
  912. op_string = "!==";
  913. break;
  914. case BinaryOp::LooselyEquals:
  915. op_string = "==";
  916. break;
  917. case BinaryOp::LooselyInequals:
  918. op_string = "!=";
  919. break;
  920. case BinaryOp::GreaterThan:
  921. op_string = ">";
  922. break;
  923. case BinaryOp::GreaterThanEquals:
  924. op_string = ">=";
  925. break;
  926. case BinaryOp::LessThan:
  927. op_string = "<";
  928. break;
  929. case BinaryOp::LessThanEquals:
  930. op_string = "<=";
  931. break;
  932. case BinaryOp::BitwiseAnd:
  933. op_string = "&";
  934. break;
  935. case BinaryOp::BitwiseOr:
  936. op_string = "|";
  937. break;
  938. case BinaryOp::BitwiseXor:
  939. op_string = "^";
  940. break;
  941. case BinaryOp::LeftShift:
  942. op_string = "<<";
  943. break;
  944. case BinaryOp::RightShift:
  945. op_string = ">>";
  946. break;
  947. case BinaryOp::UnsignedRightShift:
  948. op_string = ">>>";
  949. break;
  950. case BinaryOp::In:
  951. op_string = "in";
  952. break;
  953. case BinaryOp::InstanceOf:
  954. op_string = "instanceof";
  955. break;
  956. }
  957. print_indent(indent);
  958. outln("{}", class_name());
  959. m_lhs->dump(indent + 1);
  960. print_indent(indent + 1);
  961. outln("{}", op_string);
  962. m_rhs->dump(indent + 1);
  963. }
  964. void LogicalExpression::dump(int indent) const
  965. {
  966. const char* op_string = nullptr;
  967. switch (m_op) {
  968. case LogicalOp::And:
  969. op_string = "&&";
  970. break;
  971. case LogicalOp::Or:
  972. op_string = "||";
  973. break;
  974. case LogicalOp::NullishCoalescing:
  975. op_string = "??";
  976. break;
  977. }
  978. print_indent(indent);
  979. outln("{}", class_name());
  980. m_lhs->dump(indent + 1);
  981. print_indent(indent + 1);
  982. outln("{}", op_string);
  983. m_rhs->dump(indent + 1);
  984. }
  985. void UnaryExpression::dump(int indent) const
  986. {
  987. const char* op_string = nullptr;
  988. switch (m_op) {
  989. case UnaryOp::BitwiseNot:
  990. op_string = "~";
  991. break;
  992. case UnaryOp::Not:
  993. op_string = "!";
  994. break;
  995. case UnaryOp::Plus:
  996. op_string = "+";
  997. break;
  998. case UnaryOp::Minus:
  999. op_string = "-";
  1000. break;
  1001. case UnaryOp::Typeof:
  1002. op_string = "typeof ";
  1003. break;
  1004. case UnaryOp::Void:
  1005. op_string = "void ";
  1006. break;
  1007. case UnaryOp::Delete:
  1008. op_string = "delete ";
  1009. break;
  1010. }
  1011. print_indent(indent);
  1012. outln("{}", class_name());
  1013. print_indent(indent + 1);
  1014. outln("{}", op_string);
  1015. m_lhs->dump(indent + 1);
  1016. }
  1017. void CallExpression::dump(int indent) const
  1018. {
  1019. print_indent(indent);
  1020. if (is<NewExpression>(*this))
  1021. outln("CallExpression [new]");
  1022. else
  1023. outln("CallExpression");
  1024. m_callee->dump(indent + 1);
  1025. for (auto& argument : m_arguments)
  1026. argument.value->dump(indent + 1);
  1027. }
  1028. void SuperCall::dump(int indent) const
  1029. {
  1030. print_indent(indent);
  1031. outln("SuperCall");
  1032. for (auto& argument : m_arguments)
  1033. argument.value->dump(indent + 1);
  1034. }
  1035. void ClassDeclaration::dump(int indent) const
  1036. {
  1037. ASTNode::dump(indent);
  1038. m_class_expression->dump(indent + 1);
  1039. }
  1040. void ClassExpression::dump(int indent) const
  1041. {
  1042. print_indent(indent);
  1043. outln("ClassExpression: \"{}\"", m_name);
  1044. print_indent(indent);
  1045. outln("(Constructor)");
  1046. m_constructor->dump(indent + 1);
  1047. if (!m_super_class.is_null()) {
  1048. print_indent(indent);
  1049. outln("(Super Class)");
  1050. m_super_class->dump(indent + 1);
  1051. }
  1052. print_indent(indent);
  1053. outln("(Methods)");
  1054. for (auto& method : m_methods)
  1055. method.dump(indent + 1);
  1056. print_indent(indent);
  1057. outln("(Fields)");
  1058. for (auto& field : m_fields)
  1059. field.dump(indent + 1);
  1060. }
  1061. void ClassMethod::dump(int indent) const
  1062. {
  1063. ASTNode::dump(indent);
  1064. print_indent(indent);
  1065. outln("(Key)");
  1066. m_key->dump(indent + 1);
  1067. const char* kind_string = nullptr;
  1068. switch (m_kind) {
  1069. case Kind::Method:
  1070. kind_string = "Method";
  1071. break;
  1072. case Kind::Getter:
  1073. kind_string = "Getter";
  1074. break;
  1075. case Kind::Setter:
  1076. kind_string = "Setter";
  1077. break;
  1078. }
  1079. print_indent(indent);
  1080. outln("Kind: {}", kind_string);
  1081. print_indent(indent);
  1082. outln("Static: {}", m_is_static);
  1083. print_indent(indent);
  1084. outln("(Function)");
  1085. m_function->dump(indent + 1);
  1086. }
  1087. void ClassField::dump(int indent) const
  1088. {
  1089. ASTNode::dump(indent);
  1090. print_indent(indent);
  1091. outln("(Key)");
  1092. m_key->dump(indent + 1);
  1093. print_indent(indent);
  1094. outln("Static: {}", m_is_static);
  1095. if (m_initializer) {
  1096. print_indent(indent);
  1097. outln("(Initializer)");
  1098. m_initializer->dump(indent + 1);
  1099. }
  1100. }
  1101. void StringLiteral::dump(int indent) const
  1102. {
  1103. print_indent(indent);
  1104. outln("StringLiteral \"{}\"", m_value);
  1105. }
  1106. void SuperExpression::dump(int indent) const
  1107. {
  1108. print_indent(indent);
  1109. outln("super");
  1110. }
  1111. void NumericLiteral::dump(int indent) const
  1112. {
  1113. print_indent(indent);
  1114. outln("NumericLiteral {}", m_value);
  1115. }
  1116. void BigIntLiteral::dump(int indent) const
  1117. {
  1118. print_indent(indent);
  1119. outln("BigIntLiteral {}", m_value);
  1120. }
  1121. void BooleanLiteral::dump(int indent) const
  1122. {
  1123. print_indent(indent);
  1124. outln("BooleanLiteral {}", m_value);
  1125. }
  1126. void NullLiteral::dump(int indent) const
  1127. {
  1128. print_indent(indent);
  1129. outln("null");
  1130. }
  1131. void BindingPattern::dump(int indent) const
  1132. {
  1133. print_indent(indent);
  1134. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1135. for (auto& entry : entries) {
  1136. print_indent(indent + 1);
  1137. outln("(Property)");
  1138. if (kind == Kind::Object) {
  1139. print_indent(indent + 2);
  1140. outln("(Identifier)");
  1141. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1142. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1143. } else {
  1144. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1145. }
  1146. } else if (entry.is_elision()) {
  1147. print_indent(indent + 2);
  1148. outln("(Elision)");
  1149. continue;
  1150. }
  1151. print_indent(indent + 2);
  1152. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1153. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1154. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1155. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1156. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1157. } else {
  1158. print_indent(indent + 3);
  1159. outln("<empty>");
  1160. }
  1161. if (entry.initializer) {
  1162. print_indent(indent + 2);
  1163. outln("(Initializer)");
  1164. entry.initializer->dump(indent + 3);
  1165. }
  1166. }
  1167. }
  1168. void FunctionNode::dump(int indent, String const& class_name) const
  1169. {
  1170. print_indent(indent);
  1171. outln("{}{} '{}'", class_name, m_kind == FunctionKind::Generator ? "*" : "", name());
  1172. if (!m_parameters.is_empty()) {
  1173. print_indent(indent + 1);
  1174. outln("(Parameters)");
  1175. for (auto& parameter : m_parameters) {
  1176. print_indent(indent + 2);
  1177. if (parameter.is_rest)
  1178. out("...");
  1179. parameter.binding.visit(
  1180. [&](FlyString const& name) {
  1181. outln("{}", name);
  1182. },
  1183. [&](BindingPattern const& pattern) {
  1184. pattern.dump(indent + 2);
  1185. });
  1186. if (parameter.default_value)
  1187. parameter.default_value->dump(indent + 3);
  1188. }
  1189. }
  1190. print_indent(indent + 1);
  1191. outln("(Body)");
  1192. body().dump(indent + 2);
  1193. }
  1194. void FunctionDeclaration::dump(int indent) const
  1195. {
  1196. FunctionNode::dump(indent, class_name());
  1197. }
  1198. void FunctionExpression::dump(int indent) const
  1199. {
  1200. FunctionNode::dump(indent, class_name());
  1201. }
  1202. void YieldExpression::dump(int indent) const
  1203. {
  1204. ASTNode::dump(indent);
  1205. if (argument())
  1206. argument()->dump(indent + 1);
  1207. }
  1208. void ReturnStatement::dump(int indent) const
  1209. {
  1210. ASTNode::dump(indent);
  1211. if (argument())
  1212. argument()->dump(indent + 1);
  1213. }
  1214. void IfStatement::dump(int indent) const
  1215. {
  1216. ASTNode::dump(indent);
  1217. print_indent(indent);
  1218. outln("If");
  1219. predicate().dump(indent + 1);
  1220. consequent().dump(indent + 1);
  1221. if (alternate()) {
  1222. print_indent(indent);
  1223. outln("Else");
  1224. alternate()->dump(indent + 1);
  1225. }
  1226. }
  1227. void WhileStatement::dump(int indent) const
  1228. {
  1229. ASTNode::dump(indent);
  1230. print_indent(indent);
  1231. outln("While");
  1232. test().dump(indent + 1);
  1233. body().dump(indent + 1);
  1234. }
  1235. void WithStatement::dump(int indent) const
  1236. {
  1237. ASTNode::dump(indent);
  1238. print_indent(indent + 1);
  1239. outln("Object");
  1240. object().dump(indent + 2);
  1241. print_indent(indent + 1);
  1242. outln("Body");
  1243. body().dump(indent + 2);
  1244. }
  1245. void DoWhileStatement::dump(int indent) const
  1246. {
  1247. ASTNode::dump(indent);
  1248. print_indent(indent);
  1249. outln("DoWhile");
  1250. test().dump(indent + 1);
  1251. body().dump(indent + 1);
  1252. }
  1253. void ForStatement::dump(int indent) const
  1254. {
  1255. ASTNode::dump(indent);
  1256. print_indent(indent);
  1257. outln("For");
  1258. if (init())
  1259. init()->dump(indent + 1);
  1260. if (test())
  1261. test()->dump(indent + 1);
  1262. if (update())
  1263. update()->dump(indent + 1);
  1264. body().dump(indent + 1);
  1265. }
  1266. void ForInStatement::dump(int indent) const
  1267. {
  1268. ASTNode::dump(indent);
  1269. print_indent(indent);
  1270. outln("ForIn");
  1271. lhs().dump(indent + 1);
  1272. rhs().dump(indent + 1);
  1273. body().dump(indent + 1);
  1274. }
  1275. void ForOfStatement::dump(int indent) const
  1276. {
  1277. ASTNode::dump(indent);
  1278. print_indent(indent);
  1279. outln("ForOf");
  1280. lhs().dump(indent + 1);
  1281. rhs().dump(indent + 1);
  1282. body().dump(indent + 1);
  1283. }
  1284. Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1285. {
  1286. InterpreterNodeScope node_scope { interpreter, *this };
  1287. auto value = interpreter.vm().get_variable(string(), global_object);
  1288. if (interpreter.exception())
  1289. return {};
  1290. if (value.is_empty()) {
  1291. interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::UnknownIdentifier, string());
  1292. return {};
  1293. }
  1294. return value;
  1295. }
  1296. void Identifier::dump(int indent) const
  1297. {
  1298. print_indent(indent);
  1299. outln("Identifier \"{}\"", m_string);
  1300. }
  1301. void SpreadExpression::dump(int indent) const
  1302. {
  1303. ASTNode::dump(indent);
  1304. m_target->dump(indent + 1);
  1305. }
  1306. Value SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1307. {
  1308. InterpreterNodeScope node_scope { interpreter, *this };
  1309. return m_target->execute(interpreter, global_object);
  1310. }
  1311. Value ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1312. {
  1313. InterpreterNodeScope node_scope { interpreter, *this };
  1314. return interpreter.vm().resolve_this_binding(global_object);
  1315. }
  1316. void ThisExpression::dump(int indent) const
  1317. {
  1318. ASTNode::dump(indent);
  1319. }
  1320. Value AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1321. {
  1322. InterpreterNodeScope node_scope { interpreter, *this };
  1323. #define EXECUTE_LHS() \
  1324. do { \
  1325. if (auto* ptr = m_lhs.get_pointer<NonnullRefPtr<Expression>>()) { \
  1326. lhs_result = (*ptr)->execute(interpreter, global_object); \
  1327. if (interpreter.exception()) \
  1328. return {}; \
  1329. } \
  1330. } while (0)
  1331. #define EXECUTE_LHS_AND_RHS() \
  1332. do { \
  1333. EXECUTE_LHS(); \
  1334. rhs_result = m_rhs->execute(interpreter, global_object); \
  1335. if (interpreter.exception()) \
  1336. return {}; \
  1337. } while (0)
  1338. Value lhs_result;
  1339. Value rhs_result;
  1340. switch (m_op) {
  1341. case AssignmentOp::Assignment:
  1342. break;
  1343. case AssignmentOp::AdditionAssignment:
  1344. EXECUTE_LHS_AND_RHS();
  1345. rhs_result = add(global_object, lhs_result, rhs_result);
  1346. break;
  1347. case AssignmentOp::SubtractionAssignment:
  1348. EXECUTE_LHS_AND_RHS();
  1349. rhs_result = sub(global_object, lhs_result, rhs_result);
  1350. break;
  1351. case AssignmentOp::MultiplicationAssignment:
  1352. EXECUTE_LHS_AND_RHS();
  1353. rhs_result = mul(global_object, lhs_result, rhs_result);
  1354. break;
  1355. case AssignmentOp::DivisionAssignment:
  1356. EXECUTE_LHS_AND_RHS();
  1357. rhs_result = div(global_object, lhs_result, rhs_result);
  1358. break;
  1359. case AssignmentOp::ModuloAssignment:
  1360. EXECUTE_LHS_AND_RHS();
  1361. rhs_result = mod(global_object, lhs_result, rhs_result);
  1362. break;
  1363. case AssignmentOp::ExponentiationAssignment:
  1364. EXECUTE_LHS_AND_RHS();
  1365. rhs_result = exp(global_object, lhs_result, rhs_result);
  1366. break;
  1367. case AssignmentOp::BitwiseAndAssignment:
  1368. EXECUTE_LHS_AND_RHS();
  1369. rhs_result = bitwise_and(global_object, lhs_result, rhs_result);
  1370. break;
  1371. case AssignmentOp::BitwiseOrAssignment:
  1372. EXECUTE_LHS_AND_RHS();
  1373. rhs_result = bitwise_or(global_object, lhs_result, rhs_result);
  1374. break;
  1375. case AssignmentOp::BitwiseXorAssignment:
  1376. EXECUTE_LHS_AND_RHS();
  1377. rhs_result = bitwise_xor(global_object, lhs_result, rhs_result);
  1378. break;
  1379. case AssignmentOp::LeftShiftAssignment:
  1380. EXECUTE_LHS_AND_RHS();
  1381. rhs_result = left_shift(global_object, lhs_result, rhs_result);
  1382. break;
  1383. case AssignmentOp::RightShiftAssignment:
  1384. EXECUTE_LHS_AND_RHS();
  1385. rhs_result = right_shift(global_object, lhs_result, rhs_result);
  1386. break;
  1387. case AssignmentOp::UnsignedRightShiftAssignment:
  1388. EXECUTE_LHS_AND_RHS();
  1389. rhs_result = unsigned_right_shift(global_object, lhs_result, rhs_result);
  1390. break;
  1391. case AssignmentOp::AndAssignment:
  1392. EXECUTE_LHS();
  1393. if (!lhs_result.to_boolean())
  1394. return lhs_result;
  1395. rhs_result = m_rhs->execute(interpreter, global_object);
  1396. break;
  1397. case AssignmentOp::OrAssignment:
  1398. EXECUTE_LHS();
  1399. if (lhs_result.to_boolean())
  1400. return lhs_result;
  1401. rhs_result = m_rhs->execute(interpreter, global_object);
  1402. break;
  1403. case AssignmentOp::NullishAssignment:
  1404. EXECUTE_LHS();
  1405. if (!lhs_result.is_nullish())
  1406. return lhs_result;
  1407. rhs_result = m_rhs->execute(interpreter, global_object);
  1408. break;
  1409. }
  1410. if (interpreter.exception())
  1411. return {};
  1412. return m_lhs.visit(
  1413. [&](NonnullRefPtr<Expression>& lhs) -> JS::Value {
  1414. auto reference = lhs->to_reference(interpreter, global_object);
  1415. if (interpreter.exception())
  1416. return {};
  1417. if (m_op == AssignmentOp::Assignment) {
  1418. rhs_result = m_rhs->execute(interpreter, global_object);
  1419. if (interpreter.exception())
  1420. return {};
  1421. }
  1422. if (reference.is_unresolvable()) {
  1423. interpreter.vm().throw_exception<ReferenceError>(global_object, ErrorType::InvalidLeftHandAssignment);
  1424. return {};
  1425. }
  1426. reference.put_value(global_object, rhs_result);
  1427. if (interpreter.exception())
  1428. return {};
  1429. return rhs_result;
  1430. },
  1431. [&](NonnullRefPtr<BindingPattern>& pattern) -> JS::Value {
  1432. VERIFY(m_op == AssignmentOp::Assignment);
  1433. rhs_result = m_rhs->execute(interpreter, global_object);
  1434. if (interpreter.exception())
  1435. return {};
  1436. interpreter.vm().assign(pattern, rhs_result, global_object);
  1437. if (interpreter.exception())
  1438. return {};
  1439. return rhs_result;
  1440. });
  1441. }
  1442. Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1443. {
  1444. InterpreterNodeScope node_scope { interpreter, *this };
  1445. auto reference = m_argument->to_reference(interpreter, global_object);
  1446. if (interpreter.exception())
  1447. return {};
  1448. auto old_value = reference.get_value(global_object);
  1449. if (interpreter.exception())
  1450. return {};
  1451. old_value = old_value.to_numeric(global_object);
  1452. if (interpreter.exception())
  1453. return {};
  1454. Value new_value;
  1455. switch (m_op) {
  1456. case UpdateOp::Increment:
  1457. if (old_value.is_number())
  1458. new_value = Value(old_value.as_double() + 1);
  1459. else
  1460. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  1461. break;
  1462. case UpdateOp::Decrement:
  1463. if (old_value.is_number())
  1464. new_value = Value(old_value.as_double() - 1);
  1465. else
  1466. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  1467. break;
  1468. default:
  1469. VERIFY_NOT_REACHED();
  1470. }
  1471. reference.put_value(global_object, new_value);
  1472. if (interpreter.exception())
  1473. return {};
  1474. return m_prefixed ? new_value : old_value;
  1475. }
  1476. void AssignmentExpression::dump(int indent) const
  1477. {
  1478. const char* op_string = nullptr;
  1479. switch (m_op) {
  1480. case AssignmentOp::Assignment:
  1481. op_string = "=";
  1482. break;
  1483. case AssignmentOp::AdditionAssignment:
  1484. op_string = "+=";
  1485. break;
  1486. case AssignmentOp::SubtractionAssignment:
  1487. op_string = "-=";
  1488. break;
  1489. case AssignmentOp::MultiplicationAssignment:
  1490. op_string = "*=";
  1491. break;
  1492. case AssignmentOp::DivisionAssignment:
  1493. op_string = "/=";
  1494. break;
  1495. case AssignmentOp::ModuloAssignment:
  1496. op_string = "%=";
  1497. break;
  1498. case AssignmentOp::ExponentiationAssignment:
  1499. op_string = "**=";
  1500. break;
  1501. case AssignmentOp::BitwiseAndAssignment:
  1502. op_string = "&=";
  1503. break;
  1504. case AssignmentOp::BitwiseOrAssignment:
  1505. op_string = "|=";
  1506. break;
  1507. case AssignmentOp::BitwiseXorAssignment:
  1508. op_string = "^=";
  1509. break;
  1510. case AssignmentOp::LeftShiftAssignment:
  1511. op_string = "<<=";
  1512. break;
  1513. case AssignmentOp::RightShiftAssignment:
  1514. op_string = ">>=";
  1515. break;
  1516. case AssignmentOp::UnsignedRightShiftAssignment:
  1517. op_string = ">>>=";
  1518. break;
  1519. case AssignmentOp::AndAssignment:
  1520. op_string = "&&=";
  1521. break;
  1522. case AssignmentOp::OrAssignment:
  1523. op_string = "||=";
  1524. break;
  1525. case AssignmentOp::NullishAssignment:
  1526. op_string = "\?\?=";
  1527. break;
  1528. }
  1529. ASTNode::dump(indent);
  1530. print_indent(indent + 1);
  1531. outln("{}", op_string);
  1532. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1533. m_rhs->dump(indent + 1);
  1534. }
  1535. void UpdateExpression::dump(int indent) const
  1536. {
  1537. const char* op_string = nullptr;
  1538. switch (m_op) {
  1539. case UpdateOp::Increment:
  1540. op_string = "++";
  1541. break;
  1542. case UpdateOp::Decrement:
  1543. op_string = "--";
  1544. break;
  1545. }
  1546. ASTNode::dump(indent);
  1547. if (m_prefixed) {
  1548. print_indent(indent + 1);
  1549. outln("{}", op_string);
  1550. }
  1551. m_argument->dump(indent + 1);
  1552. if (!m_prefixed) {
  1553. print_indent(indent + 1);
  1554. outln("{}", op_string);
  1555. }
  1556. }
  1557. Value VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1558. {
  1559. InterpreterNodeScope node_scope { interpreter, *this };
  1560. for (auto& declarator : m_declarations) {
  1561. if (auto* init = declarator.init()) {
  1562. auto initializer_result = init->execute(interpreter, global_object);
  1563. if (interpreter.exception())
  1564. return {};
  1565. declarator.target().visit(
  1566. [&](NonnullRefPtr<Identifier> const& id) {
  1567. auto variable_name = id->string();
  1568. if (is<ClassExpression>(*init))
  1569. update_function_name(initializer_result, variable_name);
  1570. interpreter.vm().set_variable(variable_name, initializer_result, global_object, true);
  1571. },
  1572. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  1573. interpreter.vm().assign(pattern, initializer_result, global_object, true);
  1574. });
  1575. }
  1576. }
  1577. return {};
  1578. }
  1579. Value VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  1580. {
  1581. InterpreterNodeScope node_scope { interpreter, *this };
  1582. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  1583. VERIFY_NOT_REACHED();
  1584. }
  1585. void VariableDeclaration::dump(int indent) const
  1586. {
  1587. const char* declaration_kind_string = nullptr;
  1588. switch (m_declaration_kind) {
  1589. case DeclarationKind::Let:
  1590. declaration_kind_string = "Let";
  1591. break;
  1592. case DeclarationKind::Var:
  1593. declaration_kind_string = "Var";
  1594. break;
  1595. case DeclarationKind::Const:
  1596. declaration_kind_string = "Const";
  1597. break;
  1598. }
  1599. ASTNode::dump(indent);
  1600. print_indent(indent + 1);
  1601. outln("{}", declaration_kind_string);
  1602. for (auto& declarator : m_declarations)
  1603. declarator.dump(indent + 1);
  1604. }
  1605. void VariableDeclarator::dump(int indent) const
  1606. {
  1607. ASTNode::dump(indent);
  1608. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  1609. if (m_init)
  1610. m_init->dump(indent + 1);
  1611. }
  1612. void ObjectProperty::dump(int indent) const
  1613. {
  1614. ASTNode::dump(indent);
  1615. m_key->dump(indent + 1);
  1616. m_value->dump(indent + 1);
  1617. }
  1618. void ObjectExpression::dump(int indent) const
  1619. {
  1620. ASTNode::dump(indent);
  1621. for (auto& property : m_properties) {
  1622. property.dump(indent + 1);
  1623. }
  1624. }
  1625. void ExpressionStatement::dump(int indent) const
  1626. {
  1627. ASTNode::dump(indent);
  1628. m_expression->dump(indent + 1);
  1629. }
  1630. Value ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1631. {
  1632. InterpreterNodeScope node_scope { interpreter, *this };
  1633. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  1634. VERIFY_NOT_REACHED();
  1635. }
  1636. Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1637. {
  1638. InterpreterNodeScope node_scope { interpreter, *this };
  1639. auto* object = Object::create(global_object, global_object.object_prototype());
  1640. for (auto& property : m_properties) {
  1641. auto key = property.key().execute(interpreter, global_object);
  1642. if (interpreter.exception())
  1643. return {};
  1644. if (property.type() == ObjectProperty::Type::Spread) {
  1645. if (key.is_object() && is<Array>(key.as_object())) {
  1646. auto& array_to_spread = static_cast<Array&>(key.as_object());
  1647. for (auto& entry : array_to_spread.indexed_properties()) {
  1648. auto value = array_to_spread.get(entry.index());
  1649. if (interpreter.exception())
  1650. return {};
  1651. object->indexed_properties().put(entry.index(), value);
  1652. if (interpreter.exception())
  1653. return {};
  1654. }
  1655. } else if (key.is_object()) {
  1656. auto& obj_to_spread = key.as_object();
  1657. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  1658. if (it.value.attributes.is_enumerable()) {
  1659. object->define_direct_property(it.key, obj_to_spread.get(it.key), JS::default_attributes);
  1660. if (interpreter.exception())
  1661. return {};
  1662. }
  1663. }
  1664. } else if (key.is_string()) {
  1665. auto& str_to_spread = key.as_string().string();
  1666. for (size_t i = 0; i < str_to_spread.length(); i++) {
  1667. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  1668. if (interpreter.exception())
  1669. return {};
  1670. }
  1671. }
  1672. continue;
  1673. }
  1674. auto value = property.value().execute(interpreter, global_object);
  1675. if (interpreter.exception())
  1676. return {};
  1677. if (value.is_function() && property.is_method())
  1678. value.as_function().set_home_object(object);
  1679. String name = get_function_name(global_object, key);
  1680. if (property.type() == ObjectProperty::Type::Getter) {
  1681. name = String::formatted("get {}", name);
  1682. } else if (property.type() == ObjectProperty::Type::Setter) {
  1683. name = String::formatted("set {}", name);
  1684. }
  1685. update_function_name(value, name);
  1686. switch (property.type()) {
  1687. case ObjectProperty::Type::Getter:
  1688. VERIFY(value.is_function());
  1689. object->define_direct_accessor(PropertyName::from_value(global_object, key), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  1690. break;
  1691. case ObjectProperty::Type::Setter:
  1692. VERIFY(value.is_function());
  1693. object->define_direct_accessor(PropertyName::from_value(global_object, key), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  1694. break;
  1695. case ObjectProperty::Type::KeyValue:
  1696. object->define_direct_property(PropertyName::from_value(global_object, key), value, JS::default_attributes);
  1697. break;
  1698. case ObjectProperty::Type::Spread:
  1699. default:
  1700. VERIFY_NOT_REACHED();
  1701. }
  1702. if (interpreter.exception())
  1703. return {};
  1704. }
  1705. return object;
  1706. }
  1707. void MemberExpression::dump(int indent) const
  1708. {
  1709. print_indent(indent);
  1710. outln("{}(computed={})", class_name(), is_computed());
  1711. m_object->dump(indent + 1);
  1712. m_property->dump(indent + 1);
  1713. }
  1714. PropertyName MemberExpression::computed_property_name(Interpreter& interpreter, GlobalObject& global_object) const
  1715. {
  1716. if (!is_computed())
  1717. return verify_cast<Identifier>(*m_property).string();
  1718. auto value = m_property->execute(interpreter, global_object);
  1719. if (interpreter.exception())
  1720. return {};
  1721. VERIFY(!value.is_empty());
  1722. return PropertyName::from_value(global_object, value);
  1723. }
  1724. String MemberExpression::to_string_approximation() const
  1725. {
  1726. String object_string = "<object>";
  1727. if (is<Identifier>(*m_object))
  1728. object_string = static_cast<Identifier const&>(*m_object).string();
  1729. if (is_computed())
  1730. return String::formatted("{}[<computed>]", object_string);
  1731. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  1732. }
  1733. Value MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1734. {
  1735. InterpreterNodeScope node_scope { interpreter, *this };
  1736. auto reference = to_reference(interpreter, global_object);
  1737. if (interpreter.exception())
  1738. return {};
  1739. return reference.get_value(global_object);
  1740. }
  1741. void OptionalChain::dump(int indent) const
  1742. {
  1743. print_indent(indent);
  1744. outln("{}", class_name());
  1745. m_base->dump(indent + 1);
  1746. for (auto& reference : m_references) {
  1747. reference.visit(
  1748. [&](Call const& call) {
  1749. print_indent(indent + 1);
  1750. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  1751. for (auto& argument : call.arguments)
  1752. argument.value->dump(indent + 2);
  1753. },
  1754. [&](ComputedReference const& ref) {
  1755. print_indent(indent + 1);
  1756. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1757. ref.expression->dump(indent + 2);
  1758. },
  1759. [&](MemberReference const& ref) {
  1760. print_indent(indent + 1);
  1761. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1762. ref.identifier->dump(indent + 2);
  1763. });
  1764. }
  1765. }
  1766. Optional<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  1767. {
  1768. // Note: This is wrapped in an optional to allow base_reference = ...
  1769. Optional<JS::Reference> base_reference = m_base->to_reference(interpreter, global_object);
  1770. auto base = base_reference->is_unresolvable() ? m_base->execute(interpreter, global_object) : base_reference->get_value(global_object);
  1771. if (interpreter.exception())
  1772. return {};
  1773. for (auto& reference : m_references) {
  1774. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  1775. if (is_optional && base.is_nullish())
  1776. return ReferenceAndValue { {}, js_undefined() };
  1777. auto expression = reference.visit(
  1778. [&](Call const& call) -> NonnullRefPtr<Expression> {
  1779. return create_ast_node<CallExpression>(source_range(),
  1780. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1781. call.arguments);
  1782. },
  1783. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  1784. return create_ast_node<MemberExpression>(source_range(),
  1785. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1786. ref.expression,
  1787. true);
  1788. },
  1789. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  1790. return create_ast_node<MemberExpression>(source_range(),
  1791. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  1792. ref.identifier,
  1793. false);
  1794. });
  1795. if (is<CallExpression>(*expression)) {
  1796. base_reference = JS::Reference {};
  1797. base = expression->execute(interpreter, global_object);
  1798. } else {
  1799. base_reference = expression->to_reference(interpreter, global_object);
  1800. base = base_reference->get_value(global_object);
  1801. }
  1802. if (interpreter.exception())
  1803. return {};
  1804. }
  1805. return ReferenceAndValue { base_reference.release_value(), base };
  1806. }
  1807. Value OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1808. {
  1809. InterpreterNodeScope node_scope { interpreter, *this };
  1810. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  1811. return result.release_value().value;
  1812. return {};
  1813. }
  1814. JS::Reference OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  1815. {
  1816. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  1817. return result.release_value().reference;
  1818. return {};
  1819. }
  1820. void MetaProperty::dump(int indent) const
  1821. {
  1822. String name;
  1823. if (m_type == MetaProperty::Type::NewTarget)
  1824. name = "new.target";
  1825. else if (m_type == MetaProperty::Type::ImportMeta)
  1826. name = "import.meta";
  1827. else
  1828. VERIFY_NOT_REACHED();
  1829. print_indent(indent);
  1830. outln("{} {}", class_name(), name);
  1831. }
  1832. Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1833. {
  1834. InterpreterNodeScope node_scope { interpreter, *this };
  1835. if (m_type == MetaProperty::Type::NewTarget)
  1836. return interpreter.vm().get_new_target().value_or(js_undefined());
  1837. if (m_type == MetaProperty::Type::ImportMeta)
  1838. TODO();
  1839. VERIFY_NOT_REACHED();
  1840. }
  1841. Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1842. {
  1843. InterpreterNodeScope node_scope { interpreter, *this };
  1844. return js_string(interpreter.heap(), m_value);
  1845. }
  1846. Value NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1847. {
  1848. InterpreterNodeScope node_scope { interpreter, *this };
  1849. return Value(m_value);
  1850. }
  1851. Value BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1852. {
  1853. InterpreterNodeScope node_scope { interpreter, *this };
  1854. Crypto::SignedBigInteger integer;
  1855. if (m_value[0] == '0' && m_value.length() >= 3) {
  1856. if (m_value[1] == 'x' || m_value[1] == 'X') {
  1857. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3)));
  1858. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  1859. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3)));
  1860. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  1861. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3)));
  1862. }
  1863. }
  1864. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  1865. }
  1866. Value BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1867. {
  1868. InterpreterNodeScope node_scope { interpreter, *this };
  1869. return Value(m_value);
  1870. }
  1871. Value NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  1872. {
  1873. InterpreterNodeScope node_scope { interpreter, *this };
  1874. return js_null();
  1875. }
  1876. void RegExpLiteral::dump(int indent) const
  1877. {
  1878. print_indent(indent);
  1879. outln("{} (/{}/{})", class_name(), pattern(), flags());
  1880. }
  1881. Value RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1882. {
  1883. InterpreterNodeScope node_scope { interpreter, *this };
  1884. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  1885. return RegExpObject::create(global_object, move(regex), pattern(), flags());
  1886. }
  1887. void ArrayExpression::dump(int indent) const
  1888. {
  1889. ASTNode::dump(indent);
  1890. for (auto& element : m_elements) {
  1891. if (element) {
  1892. element->dump(indent + 1);
  1893. } else {
  1894. print_indent(indent + 1);
  1895. outln("<empty>");
  1896. }
  1897. }
  1898. }
  1899. Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1900. {
  1901. InterpreterNodeScope node_scope { interpreter, *this };
  1902. auto* array = Array::create(global_object, 0);
  1903. array->indexed_properties();
  1904. size_t index = 0;
  1905. for (auto& element : m_elements) {
  1906. auto value = Value();
  1907. if (element) {
  1908. value = element->execute(interpreter, global_object);
  1909. if (interpreter.exception())
  1910. return {};
  1911. if (is<SpreadExpression>(*element)) {
  1912. get_iterator_values(global_object, value, [&](Value iterator_value) {
  1913. array->indexed_properties().put(index++, iterator_value, default_attributes);
  1914. return IterationDecision::Continue;
  1915. });
  1916. if (interpreter.exception())
  1917. return {};
  1918. continue;
  1919. }
  1920. }
  1921. array->indexed_properties().put(index++, value, default_attributes);
  1922. }
  1923. return array;
  1924. }
  1925. void TemplateLiteral::dump(int indent) const
  1926. {
  1927. ASTNode::dump(indent);
  1928. for (auto& expression : m_expressions)
  1929. expression.dump(indent + 1);
  1930. }
  1931. Value TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1932. {
  1933. InterpreterNodeScope node_scope { interpreter, *this };
  1934. StringBuilder string_builder;
  1935. for (auto& expression : m_expressions) {
  1936. auto expr = expression.execute(interpreter, global_object);
  1937. if (interpreter.exception())
  1938. return {};
  1939. auto string = expr.to_string(global_object);
  1940. if (interpreter.exception())
  1941. return {};
  1942. string_builder.append(string);
  1943. }
  1944. return js_string(interpreter.heap(), string_builder.build());
  1945. }
  1946. void TaggedTemplateLiteral::dump(int indent) const
  1947. {
  1948. ASTNode::dump(indent);
  1949. print_indent(indent + 1);
  1950. outln("(Tag)");
  1951. m_tag->dump(indent + 2);
  1952. print_indent(indent + 1);
  1953. outln("(Template Literal)");
  1954. m_template_literal->dump(indent + 2);
  1955. }
  1956. Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1957. {
  1958. InterpreterNodeScope node_scope { interpreter, *this };
  1959. auto& vm = interpreter.vm();
  1960. auto tag = m_tag->execute(interpreter, global_object);
  1961. if (vm.exception())
  1962. return {};
  1963. if (!tag.is_function()) {
  1964. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, tag.to_string_without_side_effects());
  1965. return {};
  1966. }
  1967. auto& tag_function = tag.as_function();
  1968. auto& expressions = m_template_literal->expressions();
  1969. auto* strings = Array::create(global_object, 0);
  1970. MarkedValueList arguments(vm.heap());
  1971. arguments.append(strings);
  1972. for (size_t i = 0; i < expressions.size(); ++i) {
  1973. auto value = expressions[i].execute(interpreter, global_object);
  1974. if (vm.exception())
  1975. return {};
  1976. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  1977. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  1978. if (i % 2 == 0) {
  1979. strings->indexed_properties().append(value);
  1980. } else {
  1981. arguments.append(value);
  1982. }
  1983. }
  1984. auto* raw_strings = Array::create(global_object, 0);
  1985. for (auto& raw_string : m_template_literal->raw_strings()) {
  1986. auto value = raw_string.execute(interpreter, global_object);
  1987. if (vm.exception())
  1988. return {};
  1989. raw_strings->indexed_properties().append(value);
  1990. }
  1991. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  1992. return TRY_OR_DISCARD(vm.call(tag_function, js_undefined(), move(arguments)));
  1993. }
  1994. void TryStatement::dump(int indent) const
  1995. {
  1996. ASTNode::dump(indent);
  1997. print_indent(indent);
  1998. outln("(Block)");
  1999. block().dump(indent + 1);
  2000. if (handler()) {
  2001. print_indent(indent);
  2002. outln("(Handler)");
  2003. handler()->dump(indent + 1);
  2004. }
  2005. if (finalizer()) {
  2006. print_indent(indent);
  2007. outln("(Finalizer)");
  2008. finalizer()->dump(indent + 1);
  2009. }
  2010. }
  2011. void CatchClause::dump(int indent) const
  2012. {
  2013. print_indent(indent);
  2014. m_parameter.visit(
  2015. [&](FlyString const& parameter) {
  2016. if (parameter.is_null())
  2017. outln("CatchClause");
  2018. else
  2019. outln("CatchClause ({})", parameter);
  2020. },
  2021. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2022. outln("CatchClause");
  2023. print_indent(indent);
  2024. outln("(Parameter)");
  2025. pattern->dump(indent + 2);
  2026. });
  2027. body().dump(indent + 1);
  2028. }
  2029. void ThrowStatement::dump(int indent) const
  2030. {
  2031. ASTNode::dump(indent);
  2032. argument().dump(indent + 1);
  2033. }
  2034. Value TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2035. {
  2036. InterpreterNodeScope node_scope { interpreter, *this };
  2037. auto result = interpreter.execute_statement(global_object, m_block, ScopeType::Try);
  2038. if (auto* exception = interpreter.exception()) {
  2039. if (m_handler) {
  2040. interpreter.vm().clear_exception();
  2041. HashMap<FlyString, Variable> parameters;
  2042. m_handler->parameter().visit(
  2043. [&](FlyString const& parameter) {
  2044. parameters.set(parameter, Variable { exception->value(), DeclarationKind::Var });
  2045. },
  2046. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2047. pattern->for_each_bound_name([&](auto& name) {
  2048. parameters.set(name, Variable { Value {}, DeclarationKind::Var });
  2049. });
  2050. });
  2051. auto* catch_scope = interpreter.heap().allocate<DeclarativeEnvironment>(global_object, move(parameters), interpreter.vm().running_execution_context().lexical_environment);
  2052. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, catch_scope);
  2053. if (auto* pattern = m_handler->parameter().get_pointer<NonnullRefPtr<BindingPattern>>())
  2054. interpreter.vm().assign(*pattern, exception->value(), global_object, true);
  2055. if (interpreter.exception())
  2056. result = js_undefined();
  2057. else
  2058. result = interpreter.execute_statement(global_object, m_handler->body());
  2059. }
  2060. }
  2061. if (m_finalizer) {
  2062. // Keep, if any, and then clear the current exception so we can
  2063. // execute() the finalizer without an exception in our way.
  2064. auto* previous_exception = interpreter.exception();
  2065. interpreter.vm().clear_exception();
  2066. // Remember what scope type we were unwinding to, and temporarily
  2067. // clear it as well (e.g. return from handler).
  2068. auto unwind_until = interpreter.vm().unwind_until();
  2069. interpreter.vm().stop_unwind();
  2070. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2071. if (interpreter.vm().should_unwind()) {
  2072. // This was NOT a 'normal' completion (e.g. return from finalizer).
  2073. result = finalizer_result;
  2074. } else {
  2075. // Continue unwinding to whatever we found ourselves unwinding
  2076. // to when the finalizer was entered (e.g. return from handler,
  2077. // which is unaffected by normal completion from finalizer).
  2078. interpreter.vm().unwind(unwind_until);
  2079. // If we previously had an exception and the finalizer didn't
  2080. // throw a new one, restore the old one.
  2081. if (previous_exception && !interpreter.exception())
  2082. interpreter.vm().set_exception(*previous_exception);
  2083. }
  2084. }
  2085. return result.value_or(js_undefined());
  2086. }
  2087. Value CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2088. {
  2089. InterpreterNodeScope node_scope { interpreter, *this };
  2090. // NOTE: CatchClause execution is handled by TryStatement.
  2091. VERIFY_NOT_REACHED();
  2092. return {};
  2093. }
  2094. Value ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2095. {
  2096. InterpreterNodeScope node_scope { interpreter, *this };
  2097. auto value = m_argument->execute(interpreter, global_object);
  2098. if (interpreter.vm().exception())
  2099. return {};
  2100. interpreter.vm().throw_exception(global_object, value);
  2101. return {};
  2102. }
  2103. Value SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2104. {
  2105. InterpreterNodeScope node_scope { interpreter, *this };
  2106. auto discriminant_result = m_discriminant->execute(interpreter, global_object);
  2107. if (interpreter.exception())
  2108. return {};
  2109. bool falling_through = false;
  2110. auto last_value = js_undefined();
  2111. for (auto& switch_case : m_cases) {
  2112. if (!falling_through && switch_case.test()) {
  2113. auto test_result = switch_case.test()->execute(interpreter, global_object);
  2114. if (interpreter.exception())
  2115. return {};
  2116. if (!is_strictly_equal(discriminant_result, test_result))
  2117. continue;
  2118. }
  2119. falling_through = true;
  2120. for (auto& statement : switch_case.consequent()) {
  2121. auto value = statement.execute(interpreter, global_object);
  2122. if (!value.is_empty())
  2123. last_value = value;
  2124. if (interpreter.exception())
  2125. return {};
  2126. if (interpreter.vm().should_unwind()) {
  2127. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_label)) {
  2128. // No stop_unwind(), the outer loop will handle that - we just need to break out of the switch/case.
  2129. return last_value;
  2130. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_label)) {
  2131. interpreter.vm().stop_unwind();
  2132. return last_value;
  2133. } else {
  2134. return last_value;
  2135. }
  2136. }
  2137. }
  2138. }
  2139. return last_value;
  2140. }
  2141. Value SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  2142. {
  2143. InterpreterNodeScope node_scope { interpreter, *this };
  2144. // NOTE: SwitchCase execution is handled by SwitchStatement.
  2145. VERIFY_NOT_REACHED();
  2146. return {};
  2147. }
  2148. Value BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2149. {
  2150. InterpreterNodeScope node_scope { interpreter, *this };
  2151. interpreter.vm().unwind(ScopeType::Breakable, m_target_label);
  2152. return {};
  2153. }
  2154. Value ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2155. {
  2156. InterpreterNodeScope node_scope { interpreter, *this };
  2157. interpreter.vm().unwind(ScopeType::Continuable, m_target_label);
  2158. return {};
  2159. }
  2160. void SwitchStatement::dump(int indent) const
  2161. {
  2162. ASTNode::dump(indent);
  2163. m_discriminant->dump(indent + 1);
  2164. for (auto& switch_case : m_cases) {
  2165. switch_case.dump(indent + 1);
  2166. }
  2167. }
  2168. void SwitchCase::dump(int indent) const
  2169. {
  2170. ASTNode::dump(indent);
  2171. print_indent(indent + 1);
  2172. if (m_test) {
  2173. outln("(Test)");
  2174. m_test->dump(indent + 2);
  2175. } else {
  2176. outln("(Default)");
  2177. }
  2178. print_indent(indent + 1);
  2179. outln("(Consequent)");
  2180. for (auto& statement : m_consequent)
  2181. statement.dump(indent + 2);
  2182. }
  2183. Value ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2184. {
  2185. InterpreterNodeScope node_scope { interpreter, *this };
  2186. auto test_result = m_test->execute(interpreter, global_object);
  2187. if (interpreter.exception())
  2188. return {};
  2189. Value result;
  2190. if (test_result.to_boolean()) {
  2191. result = m_consequent->execute(interpreter, global_object);
  2192. } else {
  2193. result = m_alternate->execute(interpreter, global_object);
  2194. }
  2195. if (interpreter.exception())
  2196. return {};
  2197. return result;
  2198. }
  2199. void ConditionalExpression::dump(int indent) const
  2200. {
  2201. ASTNode::dump(indent);
  2202. print_indent(indent + 1);
  2203. outln("(Test)");
  2204. m_test->dump(indent + 2);
  2205. print_indent(indent + 1);
  2206. outln("(Consequent)");
  2207. m_consequent->dump(indent + 2);
  2208. print_indent(indent + 1);
  2209. outln("(Alternate)");
  2210. m_alternate->dump(indent + 2);
  2211. }
  2212. void SequenceExpression::dump(int indent) const
  2213. {
  2214. ASTNode::dump(indent);
  2215. for (auto& expression : m_expressions)
  2216. expression.dump(indent + 1);
  2217. }
  2218. Value SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2219. {
  2220. InterpreterNodeScope node_scope { interpreter, *this };
  2221. Value last_value;
  2222. for (auto& expression : m_expressions) {
  2223. last_value = expression.execute(interpreter, global_object);
  2224. if (interpreter.exception())
  2225. return {};
  2226. }
  2227. return last_value;
  2228. }
  2229. Value DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2230. {
  2231. InterpreterNodeScope node_scope { interpreter, *this };
  2232. // Sorry, no JavaScript debugger available (yet)!
  2233. return {};
  2234. }
  2235. void ScopeNode::add_variables(NonnullRefPtrVector<VariableDeclaration> variables)
  2236. {
  2237. m_variables.extend(move(variables));
  2238. }
  2239. void ScopeNode::add_functions(NonnullRefPtrVector<FunctionDeclaration> functions)
  2240. {
  2241. m_functions.extend(move(functions));
  2242. }
  2243. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> hoisted_function)
  2244. {
  2245. m_hoisted_functions.append(hoisted_function);
  2246. }
  2247. Value ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2248. {
  2249. InterpreterNodeScope node_scope { interpreter, *this };
  2250. dbgln("Modules are not fully supported yet!");
  2251. TODO();
  2252. return {};
  2253. }
  2254. Value ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2255. {
  2256. InterpreterNodeScope node_scope { interpreter, *this };
  2257. if (m_statement)
  2258. return m_statement->execute(interpreter, global_object);
  2259. return {};
  2260. }
  2261. void ExportStatement::dump(int indent) const
  2262. {
  2263. ASTNode::dump(indent);
  2264. print_indent(indent + 1);
  2265. outln("(ExportEntries)");
  2266. auto string_or_null = [](String const& string) -> String {
  2267. if (string.is_empty()) {
  2268. return "null";
  2269. }
  2270. return String::formatted("\"{}\"", string);
  2271. };
  2272. for (auto& entry : m_entries) {
  2273. print_indent(indent + 2);
  2274. 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));
  2275. }
  2276. }
  2277. void ImportStatement::dump(int indent) const
  2278. {
  2279. ASTNode::dump(indent);
  2280. print_indent(indent + 1);
  2281. if (m_entries.is_empty()) {
  2282. // direct from "module" import
  2283. outln("Entire module '{}'", m_module_request);
  2284. } else {
  2285. outln("(ExportEntries) from {}", m_module_request);
  2286. for (auto& entry : m_entries) {
  2287. print_indent(indent + 2);
  2288. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  2289. }
  2290. }
  2291. }
  2292. bool ExportStatement::has_export(StringView export_name) const
  2293. {
  2294. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2295. return entry.export_name == export_name;
  2296. });
  2297. }
  2298. bool ImportStatement::has_bound_name(StringView name) const
  2299. {
  2300. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2301. return entry.local_name == name;
  2302. });
  2303. }
  2304. }