AST.cpp 77 KB

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