AST.cpp 80 KB

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