AST.cpp 74 KB

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