AST.cpp 120 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Demangle.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/HashTable.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <LibCrypto/BigInt/SignedBigInteger.h>
  15. #include <LibJS/AST.h>
  16. #include <LibJS/Interpreter.h>
  17. #include <LibJS/Runtime/AbstractOperations.h>
  18. #include <LibJS/Runtime/Accessor.h>
  19. #include <LibJS/Runtime/Array.h>
  20. #include <LibJS/Runtime/BigInt.h>
  21. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  22. #include <LibJS/Runtime/Error.h>
  23. #include <LibJS/Runtime/FunctionEnvironment.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/IteratorOperations.h>
  26. #include <LibJS/Runtime/MarkedValueList.h>
  27. #include <LibJS/Runtime/NativeFunction.h>
  28. #include <LibJS/Runtime/ObjectEnvironment.h>
  29. #include <LibJS/Runtime/PrimitiveString.h>
  30. #include <LibJS/Runtime/Reference.h>
  31. #include <LibJS/Runtime/RegExpObject.h>
  32. #include <LibJS/Runtime/Shape.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, ASTNode const& node)
  40. : m_interpreter(interpreter)
  41. , m_chain_node { nullptr, node }
  42. {
  43. m_interpreter.vm().running_execution_context().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, FlyString const& name)
  60. {
  61. if (!value.is_function())
  62. return;
  63. auto& function = value.as_function();
  64. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  65. static_cast<ECMAScriptFunctionObject&>(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::evaluate_statements(Interpreter& interpreter, GlobalObject& global_object) const
  76. {
  77. // FIXME: This should use completions but for now we just use the vm to communicate things.
  78. auto& vm = interpreter.vm();
  79. Value last_value;
  80. for (auto& node : children()) {
  81. auto value = node.execute(interpreter, global_object);
  82. if (!value.is_empty())
  83. last_value = value;
  84. if (vm.should_unwind()) {
  85. break;
  86. }
  87. }
  88. return last_value;
  89. }
  90. Value FunctionBody::execute(Interpreter& interpreter, GlobalObject& global_object) const
  91. {
  92. InterpreterNodeScope node_scope { interpreter, *this };
  93. // Note: Scoping should have already been setup by whoever is calling this FunctionBody.
  94. auto function_result = evaluate_statements(interpreter, global_object);
  95. if (interpreter.exception())
  96. return {};
  97. if (interpreter.vm().unwind_until() != ScopeType::Function)
  98. function_result = js_undefined();
  99. else
  100. interpreter.vm().stop_unwind();
  101. return function_result;
  102. }
  103. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  104. Value BlockStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  105. {
  106. InterpreterNodeScope node_scope { interpreter, *this };
  107. auto& vm = interpreter.vm();
  108. Environment* old_environment = vm.running_execution_context().lexical_environment;
  109. ScopeGuard restore_environment = [&] {
  110. vm.running_execution_context().lexical_environment = old_environment;
  111. };
  112. auto* block_environment = new_declarative_environment(*old_environment);
  113. block_declaration_instantiation(global_object, block_environment);
  114. vm.running_execution_context().lexical_environment = block_environment;
  115. auto block_value = evaluate_statements(interpreter, global_object);
  116. if (!labels().is_empty() && vm.should_unwind_until(ScopeType::Breakable, labels()))
  117. vm.stop_unwind();
  118. if (vm.exception())
  119. return {};
  120. return block_value;
  121. }
  122. Value Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  123. {
  124. InterpreterNodeScope node_scope { interpreter, *this };
  125. VERIFY(interpreter.lexical_environment() && interpreter.lexical_environment()->is_global_environment());
  126. auto& global_env = static_cast<GlobalEnvironment&>(*interpreter.lexical_environment());
  127. TRY_OR_DISCARD(global_declaration_instantiation(interpreter, global_object, global_env));
  128. return evaluate_statements(interpreter, global_object);
  129. }
  130. Value FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  131. {
  132. InterpreterNodeScope node_scope { interpreter, *this };
  133. if (m_is_hoisted) {
  134. // Perform special annexB steps see step 3 of: https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  135. auto function_object = interpreter.vm().running_execution_context().lexical_environment->get_binding_value(global_object, name(), false);
  136. interpreter.vm().running_execution_context().variable_environment->set_mutable_binding(global_object, name(), function_object, false);
  137. VERIFY(!interpreter.exception());
  138. }
  139. return {};
  140. }
  141. Value FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  142. {
  143. InterpreterNodeScope node_scope { interpreter, *this };
  144. return instantiate_ordinary_function_expression(interpreter, global_object, name());
  145. }
  146. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  147. Value FunctionExpression::instantiate_ordinary_function_expression(Interpreter& interpreter, GlobalObject& global_object, FlyString given_name) const
  148. {
  149. if (given_name.is_empty())
  150. given_name = "";
  151. auto has_own_name = !name().is_empty();
  152. auto const& used_name = has_own_name ? name() : given_name;
  153. auto* scope = interpreter.lexical_environment();
  154. if (has_own_name) {
  155. VERIFY(scope);
  156. scope = new_declarative_environment(*scope);
  157. scope->create_immutable_binding(global_object, name(), false);
  158. }
  159. auto closure = ECMAScriptFunctionObject::create(global_object, used_name, body(), parameters(), function_length(), scope, kind(), is_strict_mode(), is_arrow_function());
  160. // FIXME: 6. Perform SetFunctionName(closure, name).
  161. // FIXME: 7. Perform MakeConstructor(closure).
  162. if (has_own_name)
  163. scope->initialize_binding(global_object, name(), closure);
  164. return closure;
  165. }
  166. Value ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  167. {
  168. InterpreterNodeScope node_scope { interpreter, *this };
  169. return m_expression->execute(interpreter, global_object);
  170. }
  171. CallExpression::ThisAndCallee CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  172. {
  173. auto& vm = interpreter.vm();
  174. if (callee_reference.is_property_reference()) {
  175. auto this_value = callee_reference.get_this_value();
  176. auto callee = callee_reference.get_value(global_object);
  177. if (vm.exception())
  178. return {};
  179. return { this_value, callee };
  180. }
  181. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  182. return {
  183. js_undefined(),
  184. callee_reference.is_unresolvable()
  185. ? m_callee->execute(interpreter, global_object)
  186. : callee_reference.get_value(global_object)
  187. };
  188. }
  189. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  190. static void argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list)
  191. {
  192. auto& vm = global_object.vm();
  193. list.ensure_capacity(arguments.size());
  194. for (auto& argument : arguments) {
  195. auto value = argument.value->execute(interpreter, global_object);
  196. if (vm.exception())
  197. return;
  198. if (argument.is_spread) {
  199. get_iterator_values(global_object, value, [&](Value iterator_value) {
  200. if (vm.exception())
  201. return IterationDecision::Break;
  202. list.append(iterator_value);
  203. return IterationDecision::Continue;
  204. });
  205. if (vm.exception())
  206. return;
  207. } else {
  208. list.append(value);
  209. }
  210. }
  211. }
  212. Value NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  213. {
  214. InterpreterNodeScope node_scope { interpreter, *this };
  215. auto& vm = interpreter.vm();
  216. auto callee_value = m_callee->execute(interpreter, global_object);
  217. if (vm.exception())
  218. return {};
  219. if (!callee_value.is_function() || !callee_value.as_function().has_constructor()) {
  220. throw_type_error_for_callee(interpreter, global_object, callee_value, "constructor"sv);
  221. return {};
  222. }
  223. MarkedValueList arg_list(vm.heap());
  224. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  225. if (interpreter.exception())
  226. return {};
  227. auto& function = callee_value.as_function();
  228. return vm.construct(function, function, move(arg_list));
  229. }
  230. void CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const
  231. {
  232. auto& vm = interpreter.vm();
  233. if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) {
  234. String expression_string;
  235. if (is<Identifier>(*m_callee)) {
  236. expression_string = static_cast<Identifier const&>(*m_callee).string();
  237. } else {
  238. expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  239. }
  240. vm.throw_exception<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string);
  241. } else {
  242. vm.throw_exception<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
  243. }
  244. }
  245. Value CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  246. {
  247. InterpreterNodeScope node_scope { interpreter, *this };
  248. auto& vm = interpreter.vm();
  249. auto callee_reference = m_callee->to_reference(interpreter, global_object);
  250. if (vm.exception())
  251. return {};
  252. auto [this_value, callee] = compute_this_and_callee(interpreter, global_object, callee_reference);
  253. if (vm.exception())
  254. return {};
  255. VERIFY(!callee.is_empty());
  256. MarkedValueList arg_list(vm.heap());
  257. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  258. if (interpreter.exception())
  259. return {};
  260. if (!callee.is_function()) {
  261. throw_type_error_for_callee(interpreter, global_object, callee, "function"sv);
  262. return {};
  263. }
  264. auto& function = callee.as_function();
  265. if (&function == global_object.eval_function()
  266. && callee_reference.is_environment_reference()
  267. && callee_reference.name().is_string()
  268. && callee_reference.name().as_string() == vm.names.eval.as_string()) {
  269. auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
  270. return TRY_OR_DISCARD(perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct));
  271. }
  272. return TRY_OR_DISCARD(vm.call(function, this_value, move(arg_list)));
  273. }
  274. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  275. // SuperCall : super Arguments
  276. Value SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  277. {
  278. InterpreterNodeScope node_scope { interpreter, *this };
  279. auto& vm = interpreter.vm();
  280. // 1. Let newTarget be GetNewTarget().
  281. auto new_target = vm.get_new_target();
  282. if (vm.exception())
  283. return {};
  284. // 2. Assert: Type(newTarget) is Object.
  285. VERIFY(new_target.is_function());
  286. // 3. Let func be ! GetSuperConstructor().
  287. auto* func = get_super_constructor(interpreter.vm());
  288. VERIFY(!vm.exception());
  289. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  290. MarkedValueList arg_list(vm.heap());
  291. argument_list_evaluation(interpreter, global_object, m_arguments, arg_list);
  292. if (interpreter.exception())
  293. return {};
  294. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  295. if (!func || !func->value_of().is_constructor()) {
  296. vm.throw_exception<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  297. return {};
  298. }
  299. // 6. Let result be ? Construct(func, argList, newTarget).
  300. auto& function = new_target.as_function();
  301. auto result = vm.construct(static_cast<FunctionObject&>(*func), function, move(arg_list));
  302. if (vm.exception())
  303. return {};
  304. // 7. Let thisER be GetThisEnvironment().
  305. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  306. // 8. Perform ? thisER.BindThisValue(result).
  307. this_er.bind_this_value(global_object, result);
  308. if (vm.exception())
  309. return {};
  310. // 9. Let F be thisER.[[FunctionObject]].
  311. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  312. [[maybe_unused]] auto& f = this_er.function_object();
  313. // 11. Perform ? InitializeInstanceElements(result, F).
  314. VERIFY(result.is_object());
  315. vm.initialize_instance_elements(result.as_object(), f);
  316. // 12. Return result.
  317. return result;
  318. }
  319. Value YieldExpression::execute(Interpreter&, GlobalObject&) const
  320. {
  321. // This should be transformed to a return.
  322. VERIFY_NOT_REACHED();
  323. }
  324. Value ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  325. {
  326. InterpreterNodeScope node_scope { interpreter, *this };
  327. auto value = argument() ? argument()->execute(interpreter, global_object) : js_undefined();
  328. if (interpreter.exception())
  329. return {};
  330. interpreter.vm().unwind(ScopeType::Function);
  331. return value;
  332. }
  333. Value IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  334. {
  335. InterpreterNodeScope node_scope { interpreter, *this };
  336. auto predicate_result = m_predicate->execute(interpreter, global_object);
  337. if (interpreter.exception())
  338. return {};
  339. if (predicate_result.to_boolean())
  340. return m_consequent->execute(interpreter, global_object);
  341. if (m_alternate)
  342. return m_alternate->execute(interpreter, global_object);
  343. return js_undefined();
  344. }
  345. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  346. // WithStatement : with ( Expression ) Statement
  347. Value WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  348. {
  349. InterpreterNodeScope node_scope { interpreter, *this };
  350. // 1. Let value be the result of evaluating Expression.
  351. auto value = m_object->execute(interpreter, global_object);
  352. if (interpreter.exception())
  353. return {};
  354. // 2. Let obj be ? ToObject(? GetValue(value)).
  355. auto* object = value.to_object(global_object);
  356. if (interpreter.exception())
  357. return {};
  358. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  359. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  360. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  361. auto* new_environment = new_object_environment(*object, true, old_environment);
  362. if (interpreter.exception())
  363. return {};
  364. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  365. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  366. // 6. Let C be the result of evaluating Statement.
  367. auto result = m_body->execute(interpreter, global_object).value_or(js_undefined());
  368. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  369. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  370. if (interpreter.exception())
  371. return {};
  372. // 8. Return Completion(UpdateEmpty(C, undefined)).
  373. return result;
  374. }
  375. Value WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  376. {
  377. InterpreterNodeScope node_scope { interpreter, *this };
  378. auto last_value = js_undefined();
  379. for (;;) {
  380. auto test_result = m_test->execute(interpreter, global_object);
  381. if (interpreter.exception())
  382. return {};
  383. if (!test_result.to_boolean())
  384. break;
  385. last_value = m_body->execute(interpreter, global_object).value_or(last_value);
  386. if (interpreter.exception())
  387. return {};
  388. if (interpreter.vm().should_unwind()) {
  389. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  390. interpreter.vm().stop_unwind();
  391. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  392. interpreter.vm().stop_unwind();
  393. break;
  394. } else {
  395. return last_value;
  396. }
  397. }
  398. }
  399. return last_value;
  400. }
  401. Value DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  402. {
  403. InterpreterNodeScope node_scope { interpreter, *this };
  404. auto last_value = js_undefined();
  405. for (;;) {
  406. if (interpreter.exception())
  407. return {};
  408. last_value = m_body->execute(interpreter, global_object).value_or(last_value);
  409. if (interpreter.exception())
  410. return {};
  411. if (interpreter.vm().should_unwind()) {
  412. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  413. interpreter.vm().stop_unwind();
  414. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  415. interpreter.vm().stop_unwind();
  416. break;
  417. } else {
  418. return last_value;
  419. }
  420. }
  421. auto test_result = m_test->execute(interpreter, global_object);
  422. if (interpreter.exception())
  423. return {};
  424. if (!test_result.to_boolean())
  425. break;
  426. }
  427. return last_value;
  428. }
  429. Value ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  430. {
  431. InterpreterNodeScope node_scope { interpreter, *this };
  432. // Note we don't always set a new environment but to use RAII we must do this here.
  433. auto* old_environment = interpreter.lexical_environment();
  434. ScopeGuard restore_old_environment = [&] {
  435. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  436. };
  437. Vector<FlyString> let_declarations;
  438. if (m_init) {
  439. if (is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) {
  440. auto* loop_environment = new_declarative_environment(*old_environment);
  441. auto& declaration = static_cast<VariableDeclaration const&>(*m_init);
  442. declaration.for_each_bound_name([&](auto const& name) {
  443. if (declaration.declaration_kind() == DeclarationKind::Const) {
  444. loop_environment->create_immutable_binding(global_object, name, true);
  445. } else {
  446. loop_environment->create_mutable_binding(global_object, name, false);
  447. let_declarations.append(name);
  448. }
  449. return IterationDecision::Continue;
  450. });
  451. interpreter.vm().running_execution_context().lexical_environment = loop_environment;
  452. }
  453. m_init->execute(interpreter, global_object);
  454. if (interpreter.exception())
  455. return {};
  456. }
  457. auto last_value = js_undefined();
  458. // 14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings ), https://tc39.es/ecma262/#sec-createperiterationenvironment
  459. auto create_per_iteration_environment = [&]() -> ThrowCompletionOr<void> {
  460. if (let_declarations.is_empty())
  461. return {};
  462. auto* last_iteration_env = interpreter.lexical_environment();
  463. auto* outer = last_iteration_env->outer_environment();
  464. VERIFY(outer);
  465. auto* this_iteration_env = new_declarative_environment(*outer);
  466. for (auto& name : let_declarations) {
  467. this_iteration_env->create_mutable_binding(global_object, name, false);
  468. auto last_value = last_iteration_env->get_binding_value(global_object, name, true);
  469. if (auto* exception = interpreter.exception())
  470. return throw_completion(exception->value());
  471. VERIFY(!last_value.is_empty());
  472. this_iteration_env->initialize_binding(global_object, name, last_value);
  473. }
  474. interpreter.vm().running_execution_context().lexical_environment = this_iteration_env;
  475. return {};
  476. };
  477. TRY_OR_DISCARD(create_per_iteration_environment());
  478. auto test_empty_or_true = [&] {
  479. if (!m_test)
  480. return true;
  481. auto test_result = m_test->execute(interpreter, global_object);
  482. if (interpreter.exception())
  483. return false;
  484. return test_result.to_boolean();
  485. };
  486. while (true) {
  487. if (!test_empty_or_true())
  488. break;
  489. last_value = m_body->execute(interpreter, global_object).value_or(last_value);
  490. if (interpreter.exception())
  491. return {};
  492. if (interpreter.vm().should_unwind()) {
  493. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  494. interpreter.vm().stop_unwind();
  495. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  496. interpreter.vm().stop_unwind();
  497. break;
  498. } else {
  499. return last_value;
  500. }
  501. }
  502. TRY_OR_DISCARD(create_per_iteration_environment());
  503. if (m_update) {
  504. m_update->execute(interpreter, global_object);
  505. if (interpreter.exception())
  506. return {};
  507. }
  508. }
  509. if (interpreter.exception())
  510. return {};
  511. return last_value;
  512. }
  513. struct ForInOfHeadState {
  514. explicit ForInOfHeadState(Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs)
  515. {
  516. lhs.visit(
  517. [&](NonnullRefPtr<ASTNode>& ast_node) {
  518. expression_lhs = ast_node.ptr();
  519. },
  520. [&](NonnullRefPtr<BindingPattern>& pattern) {
  521. pattern_lhs = pattern.ptr();
  522. destructuring = true;
  523. lhs_kind = Assignment;
  524. });
  525. }
  526. ASTNode* expression_lhs = nullptr;
  527. BindingPattern* pattern_lhs = nullptr;
  528. enum LhsKind {
  529. Assignment,
  530. VarBinding,
  531. LexicalBinding
  532. };
  533. LhsKind lhs_kind = Assignment;
  534. bool destructuring = false;
  535. Value rhs_value;
  536. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  537. // Note: This is only steps 6.g through 6.j of the method because we currently implement for-in without an iterator so to prevent duplicated code we do this part here.
  538. ThrowCompletionOr<void> execute_head(Interpreter& interpreter, GlobalObject& global_object, Value next_value) const
  539. {
  540. VERIFY(!next_value.is_empty());
  541. Optional<Reference> lhs_reference;
  542. Environment* iteration_environment = nullptr;
  543. // g. If lhsKind is either assignment or varBinding, then
  544. if (lhs_kind == Assignment || lhs_kind == VarBinding) {
  545. if (!destructuring) {
  546. VERIFY(expression_lhs);
  547. if (is<VariableDeclaration>(*expression_lhs)) {
  548. auto& declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  549. VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  550. lhs_reference = declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter, global_object);
  551. } else {
  552. VERIFY(is<Identifier>(*expression_lhs) || is<MemberExpression>(*expression_lhs));
  553. auto& expression = static_cast<Expression const&>(*expression_lhs);
  554. lhs_reference = expression.to_reference(interpreter, global_object);
  555. }
  556. }
  557. }
  558. // h. Else,
  559. else {
  560. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  561. iteration_environment = new_declarative_environment(*interpreter.lexical_environment());
  562. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  563. for_declaration.for_each_bound_name([&](auto const& name) {
  564. if (for_declaration.declaration_kind() == DeclarationKind::Const)
  565. iteration_environment->create_immutable_binding(global_object, name, false);
  566. else
  567. iteration_environment->create_mutable_binding(global_object, name, true);
  568. });
  569. interpreter.vm().running_execution_context().lexical_environment = iteration_environment;
  570. if (!destructuring) {
  571. VERIFY(for_declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  572. lhs_reference = interpreter.vm().resolve_binding(for_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string());
  573. }
  574. }
  575. if (auto* exception = interpreter.exception())
  576. return throw_completion(exception->value());
  577. // i. If destructuring is false, then
  578. if (!destructuring) {
  579. VERIFY(lhs_reference.has_value());
  580. if (lhs_kind == LexicalBinding)
  581. lhs_reference->initialize_referenced_binding(global_object, next_value);
  582. else
  583. lhs_reference->put_value(global_object, next_value);
  584. if (auto* exception = interpreter.exception())
  585. return throw_completion(exception->value());
  586. return {};
  587. }
  588. // j. Else,
  589. if (lhs_kind == Assignment) {
  590. VERIFY(pattern_lhs);
  591. return interpreter.vm().destructuring_assignment_evaluation(*pattern_lhs, next_value, global_object);
  592. }
  593. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  594. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  595. auto& binding_pattern = for_declaration.declarations().first().target().get<NonnullRefPtr<BindingPattern>>();
  596. VERIFY(lhs_kind == VarBinding || iteration_environment);
  597. // At this point iteration_environment is undefined if lhs_kind == VarBinding which means this does both
  598. // branch j.ii and j.iii because ForBindingInitialization is just a forwarding call to BindingInitialization.
  599. return interpreter.vm().binding_initialization(binding_pattern, next_value, iteration_environment, global_object);
  600. }
  601. };
  602. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  603. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  604. // This method combines ForInOfLoopEvaluation and ForIn/OfHeadEvaluation for similar reason as ForIn/OfBodyEvaluation, to prevent code duplication.
  605. // For the same reason we also skip step 6 and 7 of ForIn/OfHeadEvaluation as this is done by the appropriate for loop type.
  606. static ThrowCompletionOr<ForInOfHeadState> for_in_of_head_execute(Interpreter& interpreter, GlobalObject& global_object, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs, Expression const& rhs)
  607. {
  608. ForInOfHeadState state(lhs);
  609. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(*(*ast_ptr))) {
  610. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  611. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  612. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  613. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  614. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  615. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  616. Environment* new_environment = nullptr;
  617. auto& variable_declaration = static_cast<VariableDeclaration const&>(*(*ast_ptr));
  618. VERIFY(variable_declaration.declarations().size() == 1);
  619. state.destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  620. if (variable_declaration.declaration_kind() == DeclarationKind::Var) {
  621. state.lhs_kind = ForInOfHeadState::VarBinding;
  622. auto& variable = variable_declaration.declarations().first();
  623. // B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  624. if (variable.init()) {
  625. VERIFY(variable.target().has<NonnullRefPtr<Identifier>>());
  626. auto& binding_id = variable.target().get<NonnullRefPtr<Identifier>>()->string();
  627. auto reference = interpreter.vm().resolve_binding(binding_id);
  628. if (auto* exception = interpreter.exception())
  629. return throw_completion(exception->value());
  630. auto result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *variable.init(), binding_id));
  631. reference.put_value(global_object, result);
  632. if (auto* exception = interpreter.exception())
  633. return throw_completion(exception->value());
  634. }
  635. } else {
  636. state.lhs_kind = ForInOfHeadState::LexicalBinding;
  637. new_environment = new_declarative_environment(*interpreter.lexical_environment());
  638. variable_declaration.for_each_bound_name([&](auto const& name) {
  639. new_environment->create_mutable_binding(global_object, name, false);
  640. });
  641. }
  642. if (new_environment) {
  643. // 2.d Set the running execution context's LexicalEnvironment to newEnv.
  644. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, new_environment);
  645. // 3. Let exprRef be the result of evaluating expr.
  646. // 5. Let exprValue be ? GetValue(exprRef).
  647. state.rhs_value = rhs.execute(interpreter, global_object);
  648. // Note that since a reference stores it's environment it doesn't matter we only reset
  649. // this after step 5. (Also we have no way of separating these steps at this point)
  650. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  651. } else {
  652. // 3. Let exprRef be the result of evaluating expr.
  653. // 5. Let exprValue be ? GetValue(exprRef).
  654. state.rhs_value = rhs.execute(interpreter, global_object);
  655. }
  656. if (auto* exception = interpreter.exception())
  657. return throw_completion(exception->value());
  658. return state;
  659. }
  660. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  661. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  662. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  663. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  664. // We can skip step 1, 2 and 4 here (on top of already skipping step 6 and 7).
  665. // 3. Let exprRef be the result of evaluating expr.
  666. // 5. Let exprValue be ? GetValue(exprRef).
  667. state.rhs_value = rhs.execute(interpreter, global_object);
  668. if (auto* exception = interpreter.exception())
  669. return throw_completion(exception->value());
  670. return state;
  671. }
  672. Value ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  673. {
  674. InterpreterNodeScope node_scope { interpreter, *this };
  675. auto for_in_head_state = TRY_OR_DISCARD(for_in_of_head_execute(interpreter, global_object, m_lhs, *m_rhs));
  676. auto rhs_result = for_in_head_state.rhs_value;
  677. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  678. if (rhs_result.is_nullish())
  679. return js_undefined();
  680. auto* object = rhs_result.to_object(global_object);
  681. VERIFY(object);
  682. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  683. Environment* old_environment = interpreter.lexical_environment();
  684. auto restore_scope = ScopeGuard([&] {
  685. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  686. });
  687. auto last_value = js_undefined();
  688. while (object) {
  689. auto property_names = object->enumerable_own_property_names(Object::PropertyKind::Key);
  690. for (auto& value : property_names) {
  691. TRY_OR_DISCARD(for_in_head_state.execute_head(interpreter, global_object, value));
  692. last_value = m_body->execute(interpreter, global_object).value_or(last_value);
  693. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  694. if (interpreter.exception())
  695. return {};
  696. if (interpreter.vm().should_unwind()) {
  697. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  698. interpreter.vm().stop_unwind();
  699. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  700. interpreter.vm().stop_unwind();
  701. break;
  702. } else {
  703. return last_value;
  704. }
  705. }
  706. }
  707. object = TRY_OR_DISCARD(object->internal_get_prototype_of());
  708. }
  709. return last_value;
  710. }
  711. Value ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  712. {
  713. InterpreterNodeScope node_scope { interpreter, *this };
  714. auto for_of_head_state = TRY_OR_DISCARD(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  715. auto rhs_result = for_of_head_state.rhs_value;
  716. auto last_value = js_undefined();
  717. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  718. // We use get_iterator_values which behaves like ForIn/OfBodyEvaluation with iteratorKind iterate.
  719. Environment* old_environment = interpreter.lexical_environment();
  720. auto restore_scope = ScopeGuard([&] {
  721. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  722. });
  723. get_iterator_values(global_object, rhs_result, [&](Value value) {
  724. auto result = for_of_head_state.execute_head(interpreter, global_object, value);
  725. if (result.is_error())
  726. return IterationDecision::Break;
  727. last_value = m_body->execute(interpreter, global_object).value_or(last_value);
  728. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  729. if (interpreter.exception())
  730. return IterationDecision::Break;
  731. if (interpreter.vm().should_unwind()) {
  732. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  733. interpreter.vm().stop_unwind();
  734. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  735. interpreter.vm().stop_unwind();
  736. return IterationDecision::Break;
  737. } else {
  738. return IterationDecision::Break;
  739. }
  740. }
  741. return IterationDecision::Continue;
  742. });
  743. if (interpreter.exception())
  744. return {};
  745. return last_value;
  746. }
  747. Value BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  748. {
  749. InterpreterNodeScope node_scope { interpreter, *this };
  750. auto lhs_result = m_lhs->execute(interpreter, global_object);
  751. if (interpreter.exception())
  752. return {};
  753. auto rhs_result = m_rhs->execute(interpreter, global_object);
  754. if (interpreter.exception())
  755. return {};
  756. switch (m_op) {
  757. case BinaryOp::Addition:
  758. return add(global_object, lhs_result, rhs_result);
  759. case BinaryOp::Subtraction:
  760. return sub(global_object, lhs_result, rhs_result);
  761. case BinaryOp::Multiplication:
  762. return mul(global_object, lhs_result, rhs_result);
  763. case BinaryOp::Division:
  764. return div(global_object, lhs_result, rhs_result);
  765. case BinaryOp::Modulo:
  766. return mod(global_object, lhs_result, rhs_result);
  767. case BinaryOp::Exponentiation:
  768. return exp(global_object, lhs_result, rhs_result);
  769. case BinaryOp::StrictlyEquals:
  770. return Value(is_strictly_equal(lhs_result, rhs_result));
  771. case BinaryOp::StrictlyInequals:
  772. return Value(!is_strictly_equal(lhs_result, rhs_result));
  773. case BinaryOp::LooselyEquals:
  774. return Value(is_loosely_equal(global_object, lhs_result, rhs_result));
  775. case BinaryOp::LooselyInequals:
  776. return Value(!is_loosely_equal(global_object, lhs_result, rhs_result));
  777. case BinaryOp::GreaterThan:
  778. return greater_than(global_object, lhs_result, rhs_result);
  779. case BinaryOp::GreaterThanEquals:
  780. return greater_than_equals(global_object, lhs_result, rhs_result);
  781. case BinaryOp::LessThan:
  782. return less_than(global_object, lhs_result, rhs_result);
  783. case BinaryOp::LessThanEquals:
  784. return less_than_equals(global_object, lhs_result, rhs_result);
  785. case BinaryOp::BitwiseAnd:
  786. return bitwise_and(global_object, lhs_result, rhs_result);
  787. case BinaryOp::BitwiseOr:
  788. return bitwise_or(global_object, lhs_result, rhs_result);
  789. case BinaryOp::BitwiseXor:
  790. return bitwise_xor(global_object, lhs_result, rhs_result);
  791. case BinaryOp::LeftShift:
  792. return left_shift(global_object, lhs_result, rhs_result);
  793. case BinaryOp::RightShift:
  794. return right_shift(global_object, lhs_result, rhs_result);
  795. case BinaryOp::UnsignedRightShift:
  796. return unsigned_right_shift(global_object, lhs_result, rhs_result);
  797. case BinaryOp::In:
  798. return in(global_object, lhs_result, rhs_result);
  799. case BinaryOp::InstanceOf:
  800. return instance_of(global_object, lhs_result, rhs_result);
  801. }
  802. VERIFY_NOT_REACHED();
  803. }
  804. Value LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  805. {
  806. InterpreterNodeScope node_scope { interpreter, *this };
  807. auto lhs_result = m_lhs->execute(interpreter, global_object);
  808. if (interpreter.exception())
  809. return {};
  810. switch (m_op) {
  811. case LogicalOp::And:
  812. if (lhs_result.to_boolean()) {
  813. auto rhs_result = m_rhs->execute(interpreter, global_object);
  814. if (interpreter.exception())
  815. return {};
  816. return rhs_result;
  817. }
  818. return lhs_result;
  819. case LogicalOp::Or: {
  820. if (lhs_result.to_boolean())
  821. return lhs_result;
  822. auto rhs_result = m_rhs->execute(interpreter, global_object);
  823. if (interpreter.exception())
  824. return {};
  825. return rhs_result;
  826. }
  827. case LogicalOp::NullishCoalescing:
  828. if (lhs_result.is_nullish()) {
  829. auto rhs_result = m_rhs->execute(interpreter, global_object);
  830. if (interpreter.exception())
  831. return {};
  832. return rhs_result;
  833. }
  834. return lhs_result;
  835. }
  836. VERIFY_NOT_REACHED();
  837. }
  838. Reference Expression::to_reference(Interpreter&, GlobalObject&) const
  839. {
  840. return {};
  841. }
  842. Reference Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const
  843. {
  844. return interpreter.vm().resolve_binding(string());
  845. }
  846. Reference MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  847. {
  848. // 13.3.7.1 Runtime Semantics: Evaluation
  849. // SuperProperty : super [ Expression ]
  850. // SuperProperty : super . IdentifierName
  851. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  852. if (is<SuperExpression>(object())) {
  853. // 1. Let env be GetThisEnvironment().
  854. auto& environment = get_this_environment(interpreter.vm());
  855. // 2. Let actualThis be ? env.GetThisBinding().
  856. auto actual_this = environment.get_this_binding(global_object);
  857. StringOrSymbol property_key;
  858. if (is_computed()) {
  859. // SuperProperty : super [ Expression ]
  860. // 3. Let propertyNameReference be the result of evaluating Expression.
  861. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  862. auto property_name_value = m_property->execute(interpreter, global_object);
  863. if (interpreter.exception())
  864. return {};
  865. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  866. property_key = property_name_value.to_property_key(global_object);
  867. } else {
  868. // SuperProperty : super . IdentifierName
  869. // 3. Let propertyKey be StringValue of IdentifierName.
  870. VERIFY(is<Identifier>(property()));
  871. property_key = static_cast<Identifier const&>(property()).string();
  872. }
  873. // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  874. bool strict = interpreter.vm().in_strict_mode();
  875. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  876. return TRY_OR_DISCARD(make_super_property_reference(global_object, actual_this, property_key, strict));
  877. }
  878. auto base_reference = m_object->to_reference(interpreter, global_object);
  879. if (interpreter.exception())
  880. return {};
  881. Value base_value;
  882. if (base_reference.is_valid_reference())
  883. base_value = base_reference.get_value(global_object);
  884. else
  885. base_value = m_object->execute(interpreter, global_object);
  886. if (interpreter.exception())
  887. return {};
  888. VERIFY(!base_value.is_empty());
  889. // From here on equivalent to
  890. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  891. PropertyName property_name;
  892. if (is_computed()) {
  893. // Weird order which I can't quite find from the specs.
  894. auto value = m_property->execute(interpreter, global_object);
  895. if (interpreter.exception())
  896. return Reference {};
  897. TRY_OR_DISCARD(require_object_coercible(global_object, base_value));
  898. VERIFY(!value.is_empty());
  899. property_name = PropertyName::from_value(global_object, value);
  900. if (interpreter.exception())
  901. return Reference {};
  902. } else {
  903. property_name = verify_cast<Identifier>(*m_property).string();
  904. TRY_OR_DISCARD(require_object_coercible(global_object, base_value));
  905. }
  906. if (!property_name.is_valid())
  907. return Reference {};
  908. auto strict = interpreter.vm().in_strict_mode();
  909. return Reference { base_value, move(property_name), {}, strict };
  910. }
  911. Value UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  912. {
  913. InterpreterNodeScope node_scope { interpreter, *this };
  914. auto& vm = interpreter.vm();
  915. if (m_op == UnaryOp::Delete) {
  916. auto reference = m_lhs->to_reference(interpreter, global_object);
  917. if (interpreter.exception())
  918. return {};
  919. return Value(reference.delete_(global_object));
  920. }
  921. Value lhs_result;
  922. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  923. auto reference = m_lhs->to_reference(interpreter, global_object);
  924. if (interpreter.exception())
  925. return {};
  926. if (reference.is_unresolvable()) {
  927. lhs_result = js_undefined();
  928. } else {
  929. lhs_result = reference.get_value(global_object);
  930. if (interpreter.exception())
  931. return {};
  932. }
  933. VERIFY(!lhs_result.is_empty());
  934. } else {
  935. lhs_result = m_lhs->execute(interpreter, global_object);
  936. if (interpreter.exception())
  937. return {};
  938. }
  939. switch (m_op) {
  940. case UnaryOp::BitwiseNot:
  941. return bitwise_not(global_object, lhs_result);
  942. case UnaryOp::Not:
  943. return Value(!lhs_result.to_boolean());
  944. case UnaryOp::Plus:
  945. return unary_plus(global_object, lhs_result);
  946. case UnaryOp::Minus:
  947. return unary_minus(global_object, lhs_result);
  948. case UnaryOp::Typeof:
  949. return js_string(vm, lhs_result.typeof());
  950. case UnaryOp::Void:
  951. return js_undefined();
  952. case UnaryOp::Delete:
  953. VERIFY_NOT_REACHED();
  954. }
  955. VERIFY_NOT_REACHED();
  956. }
  957. Value SuperExpression::execute(Interpreter&, GlobalObject&) const
  958. {
  959. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  960. VERIFY_NOT_REACHED();
  961. }
  962. Value ClassMethod::execute(Interpreter& interpreter, GlobalObject& global_object) const
  963. {
  964. InterpreterNodeScope node_scope { interpreter, *this };
  965. return m_function->execute(interpreter, global_object);
  966. }
  967. Value ClassField::execute(Interpreter& interpreter, GlobalObject&) const
  968. {
  969. InterpreterNodeScope node_scope { interpreter, *this };
  970. return {};
  971. }
  972. Value ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  973. {
  974. InterpreterNodeScope node_scope { interpreter, *this };
  975. // FIXME: Set value.[[SourceText]] to the source text matched by ClassExpression.
  976. return TRY_OR_DISCARD(class_definition_evaluation(interpreter, global_object, m_name, m_name.is_null() ? "" : m_name));
  977. }
  978. Value ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  979. {
  980. InterpreterNodeScope node_scope { interpreter, *this };
  981. auto name = m_class_expression->name();
  982. VERIFY(!name.is_empty());
  983. auto class_constructor = TRY_OR_DISCARD(m_class_expression->class_definition_evaluation(interpreter, global_object, name, name));
  984. if (interpreter.lexical_environment()) {
  985. interpreter.lexical_environment()->initialize_binding(global_object, name, class_constructor);
  986. } else {
  987. auto reference = interpreter.vm().resolve_binding(name);
  988. reference.put_value(global_object, class_constructor);
  989. if (interpreter.exception())
  990. return {};
  991. }
  992. return {};
  993. }
  994. // 15.7.14 Runtime Semantics: ClassDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
  995. ThrowCompletionOr<Value> ClassExpression::class_definition_evaluation(Interpreter& interpreter, GlobalObject& global_object, FlyString const& binding_name, FlyString const& class_name) const
  996. {
  997. auto& vm = interpreter.vm();
  998. auto* environment = vm.lexical_environment();
  999. VERIFY(environment);
  1000. auto* class_scope = new_declarative_environment(*environment);
  1001. if (!binding_name.is_null())
  1002. class_scope->create_immutable_binding(global_object, binding_name, true);
  1003. ArmedScopeGuard restore_environment = [&] {
  1004. vm.running_execution_context().lexical_environment = environment;
  1005. };
  1006. vm.running_execution_context().lexical_environment = class_scope;
  1007. Value class_constructor_value = m_constructor->execute(interpreter, global_object);
  1008. if (auto* exception = interpreter.exception())
  1009. return throw_completion(exception->value());
  1010. update_function_name(class_constructor_value, class_name);
  1011. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  1012. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  1013. class_constructor->set_is_class_constructor();
  1014. Value super_constructor = js_undefined();
  1015. if (!m_super_class.is_null()) {
  1016. super_constructor = m_super_class->execute(interpreter, global_object);
  1017. if (auto* exception = interpreter.exception())
  1018. return throw_completion(exception->value());
  1019. if (!super_constructor.is_function() && !super_constructor.is_null())
  1020. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_constructor.to_string_without_side_effects());
  1021. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  1022. Object* super_constructor_prototype = nullptr;
  1023. if (!super_constructor.is_null()) {
  1024. auto super_constructor_prototype_value = TRY(super_constructor.as_object().get(vm.names.prototype));
  1025. if (!super_constructor_prototype_value.is_object() && !super_constructor_prototype_value.is_null())
  1026. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_constructor_prototype_value.to_string_without_side_effects());
  1027. if (super_constructor_prototype_value.is_object())
  1028. super_constructor_prototype = &super_constructor_prototype_value.as_object();
  1029. }
  1030. auto* prototype = Object::create(global_object, super_constructor_prototype);
  1031. prototype->define_direct_property(vm.names.constructor, class_constructor, 0);
  1032. if (auto* exception = interpreter.exception())
  1033. return throw_completion(exception->value());
  1034. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  1035. if (auto* exception = interpreter.exception())
  1036. return throw_completion(exception->value());
  1037. TRY(class_constructor->internal_set_prototype_of(super_constructor.is_null() ? global_object.function_prototype() : &super_constructor.as_object()));
  1038. }
  1039. auto class_prototype = TRY(class_constructor->get(vm.names.prototype));
  1040. if (!class_prototype.is_object())
  1041. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::NotAnObject, "Class prototype");
  1042. for (auto const& method : m_methods) {
  1043. auto method_value = method.execute(interpreter, global_object);
  1044. if (auto* exception = interpreter.exception())
  1045. return throw_completion(exception->value());
  1046. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  1047. auto key = method.key().execute(interpreter, global_object);
  1048. if (auto* exception = interpreter.exception())
  1049. return throw_completion(exception->value());
  1050. auto property_key = key.to_property_key(global_object);
  1051. if (auto* exception = interpreter.exception())
  1052. return throw_completion(exception->value());
  1053. auto& target = method.is_static() ? *class_constructor : class_prototype.as_object();
  1054. method_function.set_home_object(&target);
  1055. switch (method.kind()) {
  1056. case ClassMethod::Kind::Method:
  1057. TRY(target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1058. break;
  1059. case ClassMethod::Kind::Getter:
  1060. update_function_name(method_value, String::formatted("get {}", get_function_name(global_object, key)));
  1061. TRY(target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true }));
  1062. break;
  1063. case ClassMethod::Kind::Setter:
  1064. update_function_name(method_value, String::formatted("set {}", get_function_name(global_object, key)));
  1065. TRY(target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true }));
  1066. break;
  1067. default:
  1068. VERIFY_NOT_REACHED();
  1069. }
  1070. }
  1071. for (auto& field : m_fields) {
  1072. auto key = field.key().execute(interpreter, global_object);
  1073. if (auto* exception = interpreter.exception())
  1074. return throw_completion(exception->value());
  1075. auto property_key = key.to_property_key(global_object);
  1076. if (auto* exception = interpreter.exception())
  1077. return throw_completion(exception->value());
  1078. ECMAScriptFunctionObject* initializer = nullptr;
  1079. if (field.initializer()) {
  1080. auto copy_initializer = field.initializer();
  1081. auto body = create_ast_node<ExpressionStatement>(field.initializer()->source_range(), copy_initializer.release_nonnull());
  1082. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  1083. initializer = ECMAScriptFunctionObject::create(interpreter.global_object(), property_key.to_display_string(), *body, {}, 0, interpreter.lexical_environment(), FunctionKind::Regular, false);
  1084. initializer->set_home_object(field.is_static() ? class_constructor : &class_prototype.as_object());
  1085. }
  1086. if (field.is_static()) {
  1087. Value field_value = js_undefined();
  1088. if (initializer)
  1089. field_value = TRY(interpreter.vm().call(*initializer, class_constructor_value));
  1090. TRY(class_constructor->create_data_property_or_throw(property_key, field_value));
  1091. } else {
  1092. class_constructor->add_field(property_key, initializer);
  1093. }
  1094. }
  1095. vm.running_execution_context().lexical_environment = environment;
  1096. restore_environment.disarm();
  1097. if (!binding_name.is_null())
  1098. class_scope->initialize_binding(global_object, binding_name, class_constructor);
  1099. return Value(class_constructor);
  1100. }
  1101. static void print_indent(int indent)
  1102. {
  1103. out("{}", String::repeated(' ', indent * 2));
  1104. }
  1105. void ASTNode::dump(int indent) const
  1106. {
  1107. print_indent(indent);
  1108. outln("{}", class_name());
  1109. }
  1110. void ScopeNode::dump(int indent) const
  1111. {
  1112. ASTNode::dump(indent);
  1113. if (!m_lexical_declarations.is_empty()) {
  1114. print_indent(indent + 1);
  1115. outln("(Lexical declarations)");
  1116. for (auto& declaration : m_lexical_declarations)
  1117. declaration.dump(indent + 2);
  1118. }
  1119. if (!m_var_declarations.is_empty()) {
  1120. print_indent(indent + 1);
  1121. outln("(Variable declarations)");
  1122. for (auto& declaration : m_var_declarations)
  1123. declaration.dump(indent + 2);
  1124. }
  1125. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1126. print_indent(indent + 1);
  1127. outln("(Hoisted functions via annexB extension)");
  1128. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1129. declaration.dump(indent + 2);
  1130. }
  1131. if (!m_children.is_empty()) {
  1132. print_indent(indent + 1);
  1133. outln("(Children)");
  1134. for (auto& child : children())
  1135. child.dump(indent + 2);
  1136. }
  1137. }
  1138. void BinaryExpression::dump(int indent) const
  1139. {
  1140. const char* op_string = nullptr;
  1141. switch (m_op) {
  1142. case BinaryOp::Addition:
  1143. op_string = "+";
  1144. break;
  1145. case BinaryOp::Subtraction:
  1146. op_string = "-";
  1147. break;
  1148. case BinaryOp::Multiplication:
  1149. op_string = "*";
  1150. break;
  1151. case BinaryOp::Division:
  1152. op_string = "/";
  1153. break;
  1154. case BinaryOp::Modulo:
  1155. op_string = "%";
  1156. break;
  1157. case BinaryOp::Exponentiation:
  1158. op_string = "**";
  1159. break;
  1160. case BinaryOp::StrictlyEquals:
  1161. op_string = "===";
  1162. break;
  1163. case BinaryOp::StrictlyInequals:
  1164. op_string = "!==";
  1165. break;
  1166. case BinaryOp::LooselyEquals:
  1167. op_string = "==";
  1168. break;
  1169. case BinaryOp::LooselyInequals:
  1170. op_string = "!=";
  1171. break;
  1172. case BinaryOp::GreaterThan:
  1173. op_string = ">";
  1174. break;
  1175. case BinaryOp::GreaterThanEquals:
  1176. op_string = ">=";
  1177. break;
  1178. case BinaryOp::LessThan:
  1179. op_string = "<";
  1180. break;
  1181. case BinaryOp::LessThanEquals:
  1182. op_string = "<=";
  1183. break;
  1184. case BinaryOp::BitwiseAnd:
  1185. op_string = "&";
  1186. break;
  1187. case BinaryOp::BitwiseOr:
  1188. op_string = "|";
  1189. break;
  1190. case BinaryOp::BitwiseXor:
  1191. op_string = "^";
  1192. break;
  1193. case BinaryOp::LeftShift:
  1194. op_string = "<<";
  1195. break;
  1196. case BinaryOp::RightShift:
  1197. op_string = ">>";
  1198. break;
  1199. case BinaryOp::UnsignedRightShift:
  1200. op_string = ">>>";
  1201. break;
  1202. case BinaryOp::In:
  1203. op_string = "in";
  1204. break;
  1205. case BinaryOp::InstanceOf:
  1206. op_string = "instanceof";
  1207. break;
  1208. }
  1209. print_indent(indent);
  1210. outln("{}", class_name());
  1211. m_lhs->dump(indent + 1);
  1212. print_indent(indent + 1);
  1213. outln("{}", op_string);
  1214. m_rhs->dump(indent + 1);
  1215. }
  1216. void LogicalExpression::dump(int indent) const
  1217. {
  1218. const char* op_string = nullptr;
  1219. switch (m_op) {
  1220. case LogicalOp::And:
  1221. op_string = "&&";
  1222. break;
  1223. case LogicalOp::Or:
  1224. op_string = "||";
  1225. break;
  1226. case LogicalOp::NullishCoalescing:
  1227. op_string = "??";
  1228. break;
  1229. }
  1230. print_indent(indent);
  1231. outln("{}", class_name());
  1232. m_lhs->dump(indent + 1);
  1233. print_indent(indent + 1);
  1234. outln("{}", op_string);
  1235. m_rhs->dump(indent + 1);
  1236. }
  1237. void UnaryExpression::dump(int indent) const
  1238. {
  1239. const char* op_string = nullptr;
  1240. switch (m_op) {
  1241. case UnaryOp::BitwiseNot:
  1242. op_string = "~";
  1243. break;
  1244. case UnaryOp::Not:
  1245. op_string = "!";
  1246. break;
  1247. case UnaryOp::Plus:
  1248. op_string = "+";
  1249. break;
  1250. case UnaryOp::Minus:
  1251. op_string = "-";
  1252. break;
  1253. case UnaryOp::Typeof:
  1254. op_string = "typeof ";
  1255. break;
  1256. case UnaryOp::Void:
  1257. op_string = "void ";
  1258. break;
  1259. case UnaryOp::Delete:
  1260. op_string = "delete ";
  1261. break;
  1262. }
  1263. print_indent(indent);
  1264. outln("{}", class_name());
  1265. print_indent(indent + 1);
  1266. outln("{}", op_string);
  1267. m_lhs->dump(indent + 1);
  1268. }
  1269. void CallExpression::dump(int indent) const
  1270. {
  1271. print_indent(indent);
  1272. if (is<NewExpression>(*this))
  1273. outln("CallExpression [new]");
  1274. else
  1275. outln("CallExpression");
  1276. m_callee->dump(indent + 1);
  1277. for (auto& argument : m_arguments)
  1278. argument.value->dump(indent + 1);
  1279. }
  1280. void SuperCall::dump(int indent) const
  1281. {
  1282. print_indent(indent);
  1283. outln("SuperCall");
  1284. for (auto& argument : m_arguments)
  1285. argument.value->dump(indent + 1);
  1286. }
  1287. void ClassDeclaration::dump(int indent) const
  1288. {
  1289. ASTNode::dump(indent);
  1290. m_class_expression->dump(indent + 1);
  1291. }
  1292. void ClassDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1293. {
  1294. if (!m_class_expression->name().is_empty())
  1295. callback(m_class_expression->name());
  1296. }
  1297. void ClassExpression::dump(int indent) const
  1298. {
  1299. print_indent(indent);
  1300. outln("ClassExpression: \"{}\"", m_name);
  1301. print_indent(indent);
  1302. outln("(Constructor)");
  1303. m_constructor->dump(indent + 1);
  1304. if (!m_super_class.is_null()) {
  1305. print_indent(indent);
  1306. outln("(Super Class)");
  1307. m_super_class->dump(indent + 1);
  1308. }
  1309. print_indent(indent);
  1310. outln("(Methods)");
  1311. for (auto& method : m_methods)
  1312. method.dump(indent + 1);
  1313. print_indent(indent);
  1314. outln("(Fields)");
  1315. for (auto& field : m_fields)
  1316. field.dump(indent + 1);
  1317. }
  1318. void ClassMethod::dump(int indent) const
  1319. {
  1320. ASTNode::dump(indent);
  1321. print_indent(indent);
  1322. outln("(Key)");
  1323. m_key->dump(indent + 1);
  1324. const char* kind_string = nullptr;
  1325. switch (m_kind) {
  1326. case Kind::Method:
  1327. kind_string = "Method";
  1328. break;
  1329. case Kind::Getter:
  1330. kind_string = "Getter";
  1331. break;
  1332. case Kind::Setter:
  1333. kind_string = "Setter";
  1334. break;
  1335. }
  1336. print_indent(indent);
  1337. outln("Kind: {}", kind_string);
  1338. print_indent(indent);
  1339. outln("Static: {}", m_is_static);
  1340. print_indent(indent);
  1341. outln("(Function)");
  1342. m_function->dump(indent + 1);
  1343. }
  1344. void ClassField::dump(int indent) const
  1345. {
  1346. ASTNode::dump(indent);
  1347. print_indent(indent);
  1348. outln("(Key)");
  1349. m_key->dump(indent + 1);
  1350. print_indent(indent);
  1351. outln("Static: {}", m_is_static);
  1352. if (m_initializer) {
  1353. print_indent(indent);
  1354. outln("(Initializer)");
  1355. m_initializer->dump(indent + 1);
  1356. }
  1357. }
  1358. void StringLiteral::dump(int indent) const
  1359. {
  1360. print_indent(indent);
  1361. outln("StringLiteral \"{}\"", m_value);
  1362. }
  1363. void SuperExpression::dump(int indent) const
  1364. {
  1365. print_indent(indent);
  1366. outln("super");
  1367. }
  1368. void NumericLiteral::dump(int indent) const
  1369. {
  1370. print_indent(indent);
  1371. outln("NumericLiteral {}", m_value);
  1372. }
  1373. void BigIntLiteral::dump(int indent) const
  1374. {
  1375. print_indent(indent);
  1376. outln("BigIntLiteral {}", m_value);
  1377. }
  1378. void BooleanLiteral::dump(int indent) const
  1379. {
  1380. print_indent(indent);
  1381. outln("BooleanLiteral {}", m_value);
  1382. }
  1383. void NullLiteral::dump(int indent) const
  1384. {
  1385. print_indent(indent);
  1386. outln("null");
  1387. }
  1388. bool BindingPattern::contains_expression() const
  1389. {
  1390. for (auto& entry : entries) {
  1391. if (entry.initializer)
  1392. return true;
  1393. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1394. return true;
  1395. }
  1396. return false;
  1397. }
  1398. void BindingPattern::dump(int indent) const
  1399. {
  1400. print_indent(indent);
  1401. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1402. for (auto& entry : entries) {
  1403. print_indent(indent + 1);
  1404. outln("(Property)");
  1405. if (kind == Kind::Object) {
  1406. print_indent(indent + 2);
  1407. outln("(Identifier)");
  1408. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1409. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1410. } else {
  1411. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1412. }
  1413. } else if (entry.is_elision()) {
  1414. print_indent(indent + 2);
  1415. outln("(Elision)");
  1416. continue;
  1417. }
  1418. print_indent(indent + 2);
  1419. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1420. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1421. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1422. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1423. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1424. } else if (entry.alias.has<NonnullRefPtr<MemberExpression>>()) {
  1425. entry.alias.get<NonnullRefPtr<MemberExpression>>()->dump(indent + 3);
  1426. } else {
  1427. print_indent(indent + 3);
  1428. outln("<empty>");
  1429. }
  1430. if (entry.initializer) {
  1431. print_indent(indent + 2);
  1432. outln("(Initializer)");
  1433. entry.initializer->dump(indent + 3);
  1434. }
  1435. }
  1436. }
  1437. void FunctionNode::dump(int indent, String const& class_name) const
  1438. {
  1439. print_indent(indent);
  1440. outln("{}{} '{}'", class_name, m_kind == FunctionKind::Generator ? "*" : "", name());
  1441. if (!m_parameters.is_empty()) {
  1442. print_indent(indent + 1);
  1443. outln("(Parameters)");
  1444. for (auto& parameter : m_parameters) {
  1445. print_indent(indent + 2);
  1446. if (parameter.is_rest)
  1447. out("...");
  1448. parameter.binding.visit(
  1449. [&](FlyString const& name) {
  1450. outln("{}", name);
  1451. },
  1452. [&](BindingPattern const& pattern) {
  1453. pattern.dump(indent + 2);
  1454. });
  1455. if (parameter.default_value)
  1456. parameter.default_value->dump(indent + 3);
  1457. }
  1458. }
  1459. print_indent(indent + 1);
  1460. outln("(Body)");
  1461. body().dump(indent + 2);
  1462. }
  1463. void FunctionDeclaration::dump(int indent) const
  1464. {
  1465. FunctionNode::dump(indent, class_name());
  1466. }
  1467. void FunctionDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1468. {
  1469. if (!name().is_empty())
  1470. callback(name());
  1471. }
  1472. void FunctionExpression::dump(int indent) const
  1473. {
  1474. FunctionNode::dump(indent, class_name());
  1475. }
  1476. void YieldExpression::dump(int indent) const
  1477. {
  1478. ASTNode::dump(indent);
  1479. if (argument())
  1480. argument()->dump(indent + 1);
  1481. }
  1482. void ReturnStatement::dump(int indent) const
  1483. {
  1484. ASTNode::dump(indent);
  1485. if (argument())
  1486. argument()->dump(indent + 1);
  1487. }
  1488. void IfStatement::dump(int indent) const
  1489. {
  1490. ASTNode::dump(indent);
  1491. print_indent(indent);
  1492. outln("If");
  1493. predicate().dump(indent + 1);
  1494. consequent().dump(indent + 1);
  1495. if (alternate()) {
  1496. print_indent(indent);
  1497. outln("Else");
  1498. alternate()->dump(indent + 1);
  1499. }
  1500. }
  1501. void WhileStatement::dump(int indent) const
  1502. {
  1503. ASTNode::dump(indent);
  1504. print_indent(indent);
  1505. outln("While");
  1506. test().dump(indent + 1);
  1507. body().dump(indent + 1);
  1508. }
  1509. void WithStatement::dump(int indent) const
  1510. {
  1511. ASTNode::dump(indent);
  1512. print_indent(indent + 1);
  1513. outln("Object");
  1514. object().dump(indent + 2);
  1515. print_indent(indent + 1);
  1516. outln("Body");
  1517. body().dump(indent + 2);
  1518. }
  1519. void DoWhileStatement::dump(int indent) const
  1520. {
  1521. ASTNode::dump(indent);
  1522. print_indent(indent);
  1523. outln("DoWhile");
  1524. test().dump(indent + 1);
  1525. body().dump(indent + 1);
  1526. }
  1527. void ForStatement::dump(int indent) const
  1528. {
  1529. ASTNode::dump(indent);
  1530. print_indent(indent);
  1531. outln("For");
  1532. if (init())
  1533. init()->dump(indent + 1);
  1534. if (test())
  1535. test()->dump(indent + 1);
  1536. if (update())
  1537. update()->dump(indent + 1);
  1538. body().dump(indent + 1);
  1539. }
  1540. void ForInStatement::dump(int indent) const
  1541. {
  1542. ASTNode::dump(indent);
  1543. print_indent(indent);
  1544. outln("ForIn");
  1545. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1546. rhs().dump(indent + 1);
  1547. body().dump(indent + 1);
  1548. }
  1549. void ForOfStatement::dump(int indent) const
  1550. {
  1551. ASTNode::dump(indent);
  1552. print_indent(indent);
  1553. outln("ForOf");
  1554. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1555. rhs().dump(indent + 1);
  1556. body().dump(indent + 1);
  1557. }
  1558. Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1559. {
  1560. InterpreterNodeScope node_scope { interpreter, *this };
  1561. auto reference = to_reference(interpreter, global_object);
  1562. if (interpreter.exception())
  1563. return {};
  1564. return reference.get_value(global_object);
  1565. }
  1566. void Identifier::dump(int indent) const
  1567. {
  1568. print_indent(indent);
  1569. outln("Identifier \"{}\"", m_string);
  1570. }
  1571. void SpreadExpression::dump(int indent) const
  1572. {
  1573. ASTNode::dump(indent);
  1574. m_target->dump(indent + 1);
  1575. }
  1576. Value SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1577. {
  1578. InterpreterNodeScope node_scope { interpreter, *this };
  1579. return m_target->execute(interpreter, global_object);
  1580. }
  1581. Value ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1582. {
  1583. InterpreterNodeScope node_scope { interpreter, *this };
  1584. return interpreter.vm().resolve_this_binding(global_object);
  1585. }
  1586. void ThisExpression::dump(int indent) const
  1587. {
  1588. ASTNode::dump(indent);
  1589. }
  1590. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  1591. Value AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1592. {
  1593. InterpreterNodeScope node_scope { interpreter, *this };
  1594. if (m_op == AssignmentOp::Assignment) {
  1595. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  1596. return m_lhs.visit(
  1597. [&](NonnullRefPtr<Expression>& lhs) -> JS::Value {
  1598. auto reference = lhs->to_reference(interpreter, global_object);
  1599. if (interpreter.exception())
  1600. return {};
  1601. Value rhs_result;
  1602. if (lhs->is_identifier()) {
  1603. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  1604. rhs_result = TRY_OR_DISCARD(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  1605. } else {
  1606. rhs_result = m_rhs->execute(interpreter, global_object);
  1607. }
  1608. if (interpreter.exception())
  1609. return {};
  1610. reference.put_value(global_object, rhs_result);
  1611. if (interpreter.exception())
  1612. return {};
  1613. return rhs_result;
  1614. },
  1615. [&](NonnullRefPtr<BindingPattern>& pattern) -> JS::Value {
  1616. Value rhs_result = m_rhs->execute(interpreter, global_object);
  1617. if (interpreter.exception())
  1618. return {};
  1619. TRY_OR_DISCARD(interpreter.vm().destructuring_assignment_evaluation(pattern, rhs_result, global_object));
  1620. return rhs_result;
  1621. });
  1622. }
  1623. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  1624. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression>>();
  1625. auto reference = lhs_expression.to_reference(interpreter, global_object);
  1626. if (interpreter.exception())
  1627. return {};
  1628. auto lhs_result = reference.get_value(global_object);
  1629. if (interpreter.exception())
  1630. return {};
  1631. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  1632. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  1633. switch (m_op) {
  1634. case AssignmentOp::AndAssignment:
  1635. if (!lhs_result.to_boolean())
  1636. return lhs_result;
  1637. break;
  1638. case AssignmentOp::OrAssignment:
  1639. if (lhs_result.to_boolean())
  1640. return lhs_result;
  1641. break;
  1642. case AssignmentOp::NullishAssignment:
  1643. if (!lhs_result.is_nullish())
  1644. return lhs_result;
  1645. break;
  1646. default:
  1647. VERIFY_NOT_REACHED();
  1648. }
  1649. Value rhs_result;
  1650. if (lhs_expression.is_identifier()) {
  1651. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  1652. rhs_result = TRY_OR_DISCARD(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  1653. } else {
  1654. rhs_result = m_rhs->execute(interpreter, global_object);
  1655. if (interpreter.exception())
  1656. return {};
  1657. }
  1658. reference.put_value(global_object, rhs_result);
  1659. if (interpreter.exception())
  1660. return {};
  1661. return rhs_result;
  1662. }
  1663. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1664. auto rhs_result = m_rhs->execute(interpreter, global_object);
  1665. if (interpreter.exception())
  1666. return {};
  1667. switch (m_op) {
  1668. case AssignmentOp::AdditionAssignment:
  1669. rhs_result = add(global_object, lhs_result, rhs_result);
  1670. break;
  1671. case AssignmentOp::SubtractionAssignment:
  1672. rhs_result = sub(global_object, lhs_result, rhs_result);
  1673. break;
  1674. case AssignmentOp::MultiplicationAssignment:
  1675. rhs_result = mul(global_object, lhs_result, rhs_result);
  1676. break;
  1677. case AssignmentOp::DivisionAssignment:
  1678. rhs_result = div(global_object, lhs_result, rhs_result);
  1679. break;
  1680. case AssignmentOp::ModuloAssignment:
  1681. rhs_result = mod(global_object, lhs_result, rhs_result);
  1682. break;
  1683. case AssignmentOp::ExponentiationAssignment:
  1684. rhs_result = exp(global_object, lhs_result, rhs_result);
  1685. break;
  1686. case AssignmentOp::BitwiseAndAssignment:
  1687. rhs_result = bitwise_and(global_object, lhs_result, rhs_result);
  1688. break;
  1689. case AssignmentOp::BitwiseOrAssignment:
  1690. rhs_result = bitwise_or(global_object, lhs_result, rhs_result);
  1691. break;
  1692. case AssignmentOp::BitwiseXorAssignment:
  1693. rhs_result = bitwise_xor(global_object, lhs_result, rhs_result);
  1694. break;
  1695. case AssignmentOp::LeftShiftAssignment:
  1696. rhs_result = left_shift(global_object, lhs_result, rhs_result);
  1697. break;
  1698. case AssignmentOp::RightShiftAssignment:
  1699. rhs_result = right_shift(global_object, lhs_result, rhs_result);
  1700. break;
  1701. case AssignmentOp::UnsignedRightShiftAssignment:
  1702. rhs_result = unsigned_right_shift(global_object, lhs_result, rhs_result);
  1703. break;
  1704. case AssignmentOp::Assignment:
  1705. case AssignmentOp::AndAssignment:
  1706. case AssignmentOp::OrAssignment:
  1707. case AssignmentOp::NullishAssignment:
  1708. VERIFY_NOT_REACHED();
  1709. }
  1710. if (interpreter.exception())
  1711. return {};
  1712. reference.put_value(global_object, rhs_result);
  1713. if (interpreter.exception())
  1714. return {};
  1715. return rhs_result;
  1716. }
  1717. Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1718. {
  1719. InterpreterNodeScope node_scope { interpreter, *this };
  1720. auto reference = m_argument->to_reference(interpreter, global_object);
  1721. if (interpreter.exception())
  1722. return {};
  1723. auto old_value = reference.get_value(global_object);
  1724. if (interpreter.exception())
  1725. return {};
  1726. old_value = old_value.to_numeric(global_object);
  1727. if (interpreter.exception())
  1728. return {};
  1729. Value new_value;
  1730. switch (m_op) {
  1731. case UpdateOp::Increment:
  1732. if (old_value.is_number())
  1733. new_value = Value(old_value.as_double() + 1);
  1734. else
  1735. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  1736. break;
  1737. case UpdateOp::Decrement:
  1738. if (old_value.is_number())
  1739. new_value = Value(old_value.as_double() - 1);
  1740. else
  1741. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  1742. break;
  1743. default:
  1744. VERIFY_NOT_REACHED();
  1745. }
  1746. reference.put_value(global_object, new_value);
  1747. if (interpreter.exception())
  1748. return {};
  1749. return m_prefixed ? new_value : old_value;
  1750. }
  1751. void AssignmentExpression::dump(int indent) const
  1752. {
  1753. const char* op_string = nullptr;
  1754. switch (m_op) {
  1755. case AssignmentOp::Assignment:
  1756. op_string = "=";
  1757. break;
  1758. case AssignmentOp::AdditionAssignment:
  1759. op_string = "+=";
  1760. break;
  1761. case AssignmentOp::SubtractionAssignment:
  1762. op_string = "-=";
  1763. break;
  1764. case AssignmentOp::MultiplicationAssignment:
  1765. op_string = "*=";
  1766. break;
  1767. case AssignmentOp::DivisionAssignment:
  1768. op_string = "/=";
  1769. break;
  1770. case AssignmentOp::ModuloAssignment:
  1771. op_string = "%=";
  1772. break;
  1773. case AssignmentOp::ExponentiationAssignment:
  1774. op_string = "**=";
  1775. break;
  1776. case AssignmentOp::BitwiseAndAssignment:
  1777. op_string = "&=";
  1778. break;
  1779. case AssignmentOp::BitwiseOrAssignment:
  1780. op_string = "|=";
  1781. break;
  1782. case AssignmentOp::BitwiseXorAssignment:
  1783. op_string = "^=";
  1784. break;
  1785. case AssignmentOp::LeftShiftAssignment:
  1786. op_string = "<<=";
  1787. break;
  1788. case AssignmentOp::RightShiftAssignment:
  1789. op_string = ">>=";
  1790. break;
  1791. case AssignmentOp::UnsignedRightShiftAssignment:
  1792. op_string = ">>>=";
  1793. break;
  1794. case AssignmentOp::AndAssignment:
  1795. op_string = "&&=";
  1796. break;
  1797. case AssignmentOp::OrAssignment:
  1798. op_string = "||=";
  1799. break;
  1800. case AssignmentOp::NullishAssignment:
  1801. op_string = "\?\?=";
  1802. break;
  1803. }
  1804. ASTNode::dump(indent);
  1805. print_indent(indent + 1);
  1806. outln("{}", op_string);
  1807. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1808. m_rhs->dump(indent + 1);
  1809. }
  1810. void UpdateExpression::dump(int indent) const
  1811. {
  1812. const char* op_string = nullptr;
  1813. switch (m_op) {
  1814. case UpdateOp::Increment:
  1815. op_string = "++";
  1816. break;
  1817. case UpdateOp::Decrement:
  1818. op_string = "--";
  1819. break;
  1820. }
  1821. ASTNode::dump(indent);
  1822. if (m_prefixed) {
  1823. print_indent(indent + 1);
  1824. outln("{}", op_string);
  1825. }
  1826. m_argument->dump(indent + 1);
  1827. if (!m_prefixed) {
  1828. print_indent(indent + 1);
  1829. outln("{}", op_string);
  1830. }
  1831. }
  1832. Value VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1833. {
  1834. InterpreterNodeScope node_scope { interpreter, *this };
  1835. for (auto& declarator : m_declarations) {
  1836. if (auto* init = declarator.init()) {
  1837. declarator.target().visit(
  1838. [&](NonnullRefPtr<Identifier> const& id) {
  1839. auto reference = id->to_reference(interpreter, global_object);
  1840. if (interpreter.exception())
  1841. return;
  1842. auto initializer_result_or_error = interpreter.vm().named_evaluation_if_anonymous_function(global_object, *init, id->string());
  1843. if (initializer_result_or_error.is_error())
  1844. return;
  1845. auto initializer_result = initializer_result_or_error.release_value();
  1846. VERIFY(!initializer_result.is_empty());
  1847. if (m_declaration_kind == DeclarationKind::Var)
  1848. reference.put_value(global_object, initializer_result);
  1849. else
  1850. reference.initialize_referenced_binding(global_object, initializer_result);
  1851. },
  1852. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  1853. auto initializer_result = init->execute(interpreter, global_object);
  1854. if (interpreter.exception())
  1855. return;
  1856. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  1857. // FIXME: I want to use TRY_OR_DISCARD here but can't return...
  1858. auto result = interpreter.vm().binding_initialization(pattern, initializer_result, environment, global_object);
  1859. (void)result;
  1860. });
  1861. if (interpreter.exception())
  1862. return {};
  1863. } else if (m_declaration_kind != DeclarationKind::Var) {
  1864. VERIFY(declarator.target().has<NonnullRefPtr<Identifier>>());
  1865. auto& identifier = declarator.target().get<NonnullRefPtr<Identifier>>();
  1866. auto reference = identifier->to_reference(interpreter, global_object);
  1867. reference.initialize_referenced_binding(global_object, js_undefined());
  1868. if (interpreter.exception())
  1869. return {};
  1870. }
  1871. }
  1872. return {};
  1873. }
  1874. Value VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  1875. {
  1876. InterpreterNodeScope node_scope { interpreter, *this };
  1877. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  1878. VERIFY_NOT_REACHED();
  1879. }
  1880. void VariableDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1881. {
  1882. for (auto& entry : declarations()) {
  1883. entry.target().template visit(
  1884. [&](const NonnullRefPtr<Identifier>& id) {
  1885. callback(id->string());
  1886. },
  1887. [&](const NonnullRefPtr<BindingPattern>& binding) {
  1888. binding->for_each_bound_name([&](const auto& name) {
  1889. callback(name);
  1890. });
  1891. });
  1892. }
  1893. }
  1894. void VariableDeclaration::dump(int indent) const
  1895. {
  1896. const char* declaration_kind_string = nullptr;
  1897. switch (m_declaration_kind) {
  1898. case DeclarationKind::Let:
  1899. declaration_kind_string = "Let";
  1900. break;
  1901. case DeclarationKind::Var:
  1902. declaration_kind_string = "Var";
  1903. break;
  1904. case DeclarationKind::Const:
  1905. declaration_kind_string = "Const";
  1906. break;
  1907. }
  1908. ASTNode::dump(indent);
  1909. print_indent(indent + 1);
  1910. outln("{}", declaration_kind_string);
  1911. for (auto& declarator : m_declarations)
  1912. declarator.dump(indent + 1);
  1913. }
  1914. void VariableDeclarator::dump(int indent) const
  1915. {
  1916. ASTNode::dump(indent);
  1917. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  1918. if (m_init)
  1919. m_init->dump(indent + 1);
  1920. }
  1921. void ObjectProperty::dump(int indent) const
  1922. {
  1923. ASTNode::dump(indent);
  1924. m_key->dump(indent + 1);
  1925. m_value->dump(indent + 1);
  1926. }
  1927. void ObjectExpression::dump(int indent) const
  1928. {
  1929. ASTNode::dump(indent);
  1930. for (auto& property : m_properties) {
  1931. property.dump(indent + 1);
  1932. }
  1933. }
  1934. void ExpressionStatement::dump(int indent) const
  1935. {
  1936. ASTNode::dump(indent);
  1937. m_expression->dump(indent + 1);
  1938. }
  1939. Value ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1940. {
  1941. InterpreterNodeScope node_scope { interpreter, *this };
  1942. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  1943. VERIFY_NOT_REACHED();
  1944. }
  1945. Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1946. {
  1947. InterpreterNodeScope node_scope { interpreter, *this };
  1948. auto* object = Object::create(global_object, global_object.object_prototype());
  1949. for (auto& property : m_properties) {
  1950. auto key = property.key().execute(interpreter, global_object);
  1951. if (interpreter.exception())
  1952. return {};
  1953. if (property.type() == ObjectProperty::Type::Spread) {
  1954. if (key.is_object() && is<Array>(key.as_object())) {
  1955. auto& array_to_spread = static_cast<Array&>(key.as_object());
  1956. for (auto& entry : array_to_spread.indexed_properties()) {
  1957. auto value = TRY_OR_DISCARD(array_to_spread.get(entry.index()));
  1958. object->indexed_properties().put(entry.index(), value);
  1959. if (interpreter.exception())
  1960. return {};
  1961. }
  1962. } else if (key.is_object()) {
  1963. auto& obj_to_spread = key.as_object();
  1964. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  1965. if (it.value.attributes.is_enumerable()) {
  1966. object->define_direct_property(it.key, TRY_OR_DISCARD(obj_to_spread.get(it.key)), JS::default_attributes);
  1967. if (interpreter.exception())
  1968. return {};
  1969. }
  1970. }
  1971. } else if (key.is_string()) {
  1972. auto& str_to_spread = key.as_string().string();
  1973. for (size_t i = 0; i < str_to_spread.length(); i++) {
  1974. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  1975. if (interpreter.exception())
  1976. return {};
  1977. }
  1978. }
  1979. continue;
  1980. }
  1981. auto value = property.value().execute(interpreter, global_object);
  1982. if (interpreter.exception())
  1983. return {};
  1984. if (value.is_function() && property.is_method())
  1985. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  1986. String name = get_function_name(global_object, key);
  1987. if (property.type() == ObjectProperty::Type::Getter) {
  1988. name = String::formatted("get {}", name);
  1989. } else if (property.type() == ObjectProperty::Type::Setter) {
  1990. name = String::formatted("set {}", name);
  1991. }
  1992. update_function_name(value, name);
  1993. switch (property.type()) {
  1994. case ObjectProperty::Type::Getter:
  1995. VERIFY(value.is_function());
  1996. object->define_direct_accessor(PropertyName::from_value(global_object, key), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  1997. break;
  1998. case ObjectProperty::Type::Setter:
  1999. VERIFY(value.is_function());
  2000. object->define_direct_accessor(PropertyName::from_value(global_object, key), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2001. break;
  2002. case ObjectProperty::Type::KeyValue:
  2003. object->define_direct_property(PropertyName::from_value(global_object, key), value, JS::default_attributes);
  2004. break;
  2005. case ObjectProperty::Type::Spread:
  2006. default:
  2007. VERIFY_NOT_REACHED();
  2008. }
  2009. if (interpreter.exception())
  2010. return {};
  2011. }
  2012. return object;
  2013. }
  2014. void MemberExpression::dump(int indent) const
  2015. {
  2016. print_indent(indent);
  2017. outln("{}(computed={})", class_name(), is_computed());
  2018. m_object->dump(indent + 1);
  2019. m_property->dump(indent + 1);
  2020. }
  2021. PropertyName MemberExpression::computed_property_name(Interpreter& interpreter, GlobalObject& global_object) const
  2022. {
  2023. if (!is_computed())
  2024. return verify_cast<Identifier>(*m_property).string();
  2025. auto value = m_property->execute(interpreter, global_object);
  2026. if (interpreter.exception())
  2027. return {};
  2028. VERIFY(!value.is_empty());
  2029. return PropertyName::from_value(global_object, value);
  2030. }
  2031. String MemberExpression::to_string_approximation() const
  2032. {
  2033. String object_string = "<object>";
  2034. if (is<Identifier>(*m_object))
  2035. object_string = static_cast<Identifier const&>(*m_object).string();
  2036. if (is_computed())
  2037. return String::formatted("{}[<computed>]", object_string);
  2038. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2039. }
  2040. Value MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2041. {
  2042. InterpreterNodeScope node_scope { interpreter, *this };
  2043. auto reference = to_reference(interpreter, global_object);
  2044. if (interpreter.exception())
  2045. return {};
  2046. return reference.get_value(global_object);
  2047. }
  2048. void OptionalChain::dump(int indent) const
  2049. {
  2050. print_indent(indent);
  2051. outln("{}", class_name());
  2052. m_base->dump(indent + 1);
  2053. for (auto& reference : m_references) {
  2054. reference.visit(
  2055. [&](Call const& call) {
  2056. print_indent(indent + 1);
  2057. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2058. for (auto& argument : call.arguments)
  2059. argument.value->dump(indent + 2);
  2060. },
  2061. [&](ComputedReference const& ref) {
  2062. print_indent(indent + 1);
  2063. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2064. ref.expression->dump(indent + 2);
  2065. },
  2066. [&](MemberReference const& ref) {
  2067. print_indent(indent + 1);
  2068. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2069. ref.identifier->dump(indent + 2);
  2070. });
  2071. }
  2072. }
  2073. Optional<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  2074. {
  2075. // Note: This is wrapped in an optional to allow base_reference = ...
  2076. Optional<JS::Reference> base_reference = m_base->to_reference(interpreter, global_object);
  2077. auto base = base_reference->is_unresolvable() ? m_base->execute(interpreter, global_object) : base_reference->get_value(global_object);
  2078. if (interpreter.exception())
  2079. return {};
  2080. for (auto& reference : m_references) {
  2081. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2082. if (is_optional && base.is_nullish())
  2083. return ReferenceAndValue { {}, js_undefined() };
  2084. auto expression = reference.visit(
  2085. [&](Call const& call) -> NonnullRefPtr<Expression> {
  2086. return create_ast_node<CallExpression>(source_range(),
  2087. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2088. call.arguments);
  2089. },
  2090. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  2091. return create_ast_node<MemberExpression>(source_range(),
  2092. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2093. ref.expression,
  2094. true);
  2095. },
  2096. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  2097. return create_ast_node<MemberExpression>(source_range(),
  2098. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2099. ref.identifier,
  2100. false);
  2101. });
  2102. if (is<CallExpression>(*expression)) {
  2103. base_reference = JS::Reference {};
  2104. base = expression->execute(interpreter, global_object);
  2105. } else {
  2106. base_reference = expression->to_reference(interpreter, global_object);
  2107. base = base_reference->get_value(global_object);
  2108. }
  2109. if (interpreter.exception())
  2110. return {};
  2111. }
  2112. return ReferenceAndValue { base_reference.release_value(), base };
  2113. }
  2114. Value OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2115. {
  2116. InterpreterNodeScope node_scope { interpreter, *this };
  2117. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  2118. return result.release_value().value;
  2119. return {};
  2120. }
  2121. JS::Reference OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  2122. {
  2123. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  2124. return result.release_value().reference;
  2125. return {};
  2126. }
  2127. void MetaProperty::dump(int indent) const
  2128. {
  2129. String name;
  2130. if (m_type == MetaProperty::Type::NewTarget)
  2131. name = "new.target";
  2132. else if (m_type == MetaProperty::Type::ImportMeta)
  2133. name = "import.meta";
  2134. else
  2135. VERIFY_NOT_REACHED();
  2136. print_indent(indent);
  2137. outln("{} {}", class_name(), name);
  2138. }
  2139. Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const
  2140. {
  2141. InterpreterNodeScope node_scope { interpreter, *this };
  2142. if (m_type == MetaProperty::Type::NewTarget)
  2143. return interpreter.vm().get_new_target().value_or(js_undefined());
  2144. if (m_type == MetaProperty::Type::ImportMeta)
  2145. TODO();
  2146. VERIFY_NOT_REACHED();
  2147. }
  2148. Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2149. {
  2150. InterpreterNodeScope node_scope { interpreter, *this };
  2151. return js_string(interpreter.heap(), m_value);
  2152. }
  2153. Value NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2154. {
  2155. InterpreterNodeScope node_scope { interpreter, *this };
  2156. return Value(m_value);
  2157. }
  2158. Value BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2159. {
  2160. InterpreterNodeScope node_scope { interpreter, *this };
  2161. Crypto::SignedBigInteger integer;
  2162. if (m_value[0] == '0' && m_value.length() >= 3) {
  2163. if (m_value[1] == 'x' || m_value[1] == 'X') {
  2164. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3)));
  2165. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  2166. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3)));
  2167. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  2168. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3)));
  2169. }
  2170. }
  2171. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  2172. }
  2173. Value BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2174. {
  2175. InterpreterNodeScope node_scope { interpreter, *this };
  2176. return Value(m_value);
  2177. }
  2178. Value NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2179. {
  2180. InterpreterNodeScope node_scope { interpreter, *this };
  2181. return js_null();
  2182. }
  2183. void RegExpLiteral::dump(int indent) const
  2184. {
  2185. print_indent(indent);
  2186. outln("{} (/{}/{})", class_name(), pattern(), flags());
  2187. }
  2188. Value RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2189. {
  2190. InterpreterNodeScope node_scope { interpreter, *this };
  2191. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  2192. return RegExpObject::create(global_object, move(regex), pattern(), flags());
  2193. }
  2194. void ArrayExpression::dump(int indent) const
  2195. {
  2196. ASTNode::dump(indent);
  2197. for (auto& element : m_elements) {
  2198. if (element) {
  2199. element->dump(indent + 1);
  2200. } else {
  2201. print_indent(indent + 1);
  2202. outln("<empty>");
  2203. }
  2204. }
  2205. }
  2206. Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2207. {
  2208. InterpreterNodeScope node_scope { interpreter, *this };
  2209. auto* array = Array::create(global_object, 0);
  2210. array->indexed_properties();
  2211. size_t index = 0;
  2212. for (auto& element : m_elements) {
  2213. auto value = Value();
  2214. if (element) {
  2215. value = element->execute(interpreter, global_object);
  2216. if (interpreter.exception())
  2217. return {};
  2218. if (is<SpreadExpression>(*element)) {
  2219. get_iterator_values(global_object, value, [&](Value iterator_value) {
  2220. array->indexed_properties().put(index++, iterator_value, default_attributes);
  2221. return IterationDecision::Continue;
  2222. });
  2223. if (interpreter.exception())
  2224. return {};
  2225. continue;
  2226. }
  2227. }
  2228. array->indexed_properties().put(index++, value, default_attributes);
  2229. }
  2230. return array;
  2231. }
  2232. void TemplateLiteral::dump(int indent) const
  2233. {
  2234. ASTNode::dump(indent);
  2235. for (auto& expression : m_expressions)
  2236. expression.dump(indent + 1);
  2237. }
  2238. Value TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2239. {
  2240. InterpreterNodeScope node_scope { interpreter, *this };
  2241. StringBuilder string_builder;
  2242. for (auto& expression : m_expressions) {
  2243. auto expr = expression.execute(interpreter, global_object);
  2244. if (interpreter.exception())
  2245. return {};
  2246. auto string = expr.to_string(global_object);
  2247. if (interpreter.exception())
  2248. return {};
  2249. string_builder.append(string);
  2250. }
  2251. return js_string(interpreter.heap(), string_builder.build());
  2252. }
  2253. void TaggedTemplateLiteral::dump(int indent) const
  2254. {
  2255. ASTNode::dump(indent);
  2256. print_indent(indent + 1);
  2257. outln("(Tag)");
  2258. m_tag->dump(indent + 2);
  2259. print_indent(indent + 1);
  2260. outln("(Template Literal)");
  2261. m_template_literal->dump(indent + 2);
  2262. }
  2263. Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2264. {
  2265. InterpreterNodeScope node_scope { interpreter, *this };
  2266. auto& vm = interpreter.vm();
  2267. auto tag = m_tag->execute(interpreter, global_object);
  2268. if (vm.exception())
  2269. return {};
  2270. if (!tag.is_function()) {
  2271. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, tag.to_string_without_side_effects());
  2272. return {};
  2273. }
  2274. auto& tag_function = tag.as_function();
  2275. auto& expressions = m_template_literal->expressions();
  2276. auto* strings = Array::create(global_object, 0);
  2277. MarkedValueList arguments(vm.heap());
  2278. arguments.append(strings);
  2279. for (size_t i = 0; i < expressions.size(); ++i) {
  2280. auto value = expressions[i].execute(interpreter, global_object);
  2281. if (vm.exception())
  2282. return {};
  2283. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  2284. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  2285. if (i % 2 == 0) {
  2286. strings->indexed_properties().append(value);
  2287. } else {
  2288. arguments.append(value);
  2289. }
  2290. }
  2291. auto* raw_strings = Array::create(global_object, 0);
  2292. for (auto& raw_string : m_template_literal->raw_strings()) {
  2293. auto value = raw_string.execute(interpreter, global_object);
  2294. if (vm.exception())
  2295. return {};
  2296. raw_strings->indexed_properties().append(value);
  2297. }
  2298. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  2299. return TRY_OR_DISCARD(vm.call(tag_function, js_undefined(), move(arguments)));
  2300. }
  2301. void TryStatement::dump(int indent) const
  2302. {
  2303. ASTNode::dump(indent);
  2304. print_indent(indent);
  2305. outln("(Block)");
  2306. block().dump(indent + 1);
  2307. if (handler()) {
  2308. print_indent(indent);
  2309. outln("(Handler)");
  2310. handler()->dump(indent + 1);
  2311. }
  2312. if (finalizer()) {
  2313. print_indent(indent);
  2314. outln("(Finalizer)");
  2315. finalizer()->dump(indent + 1);
  2316. }
  2317. }
  2318. void CatchClause::dump(int indent) const
  2319. {
  2320. print_indent(indent);
  2321. m_parameter.visit(
  2322. [&](FlyString const& parameter) {
  2323. if (parameter.is_null())
  2324. outln("CatchClause");
  2325. else
  2326. outln("CatchClause ({})", parameter);
  2327. },
  2328. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2329. outln("CatchClause");
  2330. print_indent(indent);
  2331. outln("(Parameter)");
  2332. pattern->dump(indent + 2);
  2333. });
  2334. body().dump(indent + 1);
  2335. }
  2336. void ThrowStatement::dump(int indent) const
  2337. {
  2338. ASTNode::dump(indent);
  2339. argument().dump(indent + 1);
  2340. }
  2341. void TryStatement::add_label(FlyString string)
  2342. {
  2343. m_block->add_label(move(string));
  2344. }
  2345. Value TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2346. {
  2347. InterpreterNodeScope node_scope { interpreter, *this };
  2348. // FIXME: Use Completions here to be closer to the spec.
  2349. auto result = m_block->execute(interpreter, global_object);
  2350. if (interpreter.vm().unwind_until() == ScopeType::Try)
  2351. interpreter.vm().stop_unwind();
  2352. if (auto* exception = interpreter.exception()) {
  2353. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  2354. if (m_handler) {
  2355. interpreter.vm().clear_exception();
  2356. auto* catch_scope = new_declarative_environment(*interpreter.lexical_environment());
  2357. m_handler->parameter().visit(
  2358. [&](FlyString const& parameter) {
  2359. catch_scope->create_mutable_binding(global_object, parameter, false);
  2360. },
  2361. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2362. pattern->for_each_bound_name([&](auto& name) {
  2363. catch_scope->create_mutable_binding(global_object, name, false);
  2364. });
  2365. });
  2366. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, catch_scope);
  2367. m_handler->parameter().visit(
  2368. [&](FlyString const& parameter) {
  2369. catch_scope->initialize_binding(global_object, parameter, exception->value());
  2370. },
  2371. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2372. (void)interpreter.vm().binding_initialization(pattern, exception->value(), catch_scope, global_object);
  2373. });
  2374. if (!interpreter.exception())
  2375. result = m_handler->body().execute(interpreter, global_object);
  2376. }
  2377. }
  2378. if (m_finalizer) {
  2379. // Keep, if any, and then clear the current exception so we can
  2380. // execute() the finalizer without an exception in our way.
  2381. auto* previous_exception = interpreter.exception();
  2382. interpreter.vm().clear_exception();
  2383. // Remember what scope type we were unwinding to, and temporarily
  2384. // clear it as well (e.g. return from handler).
  2385. auto unwind_until = interpreter.vm().unwind_until();
  2386. interpreter.vm().stop_unwind();
  2387. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2388. if (interpreter.vm().should_unwind()) {
  2389. // This was NOT a 'normal' completion (e.g. return from finalizer).
  2390. result = finalizer_result;
  2391. } else {
  2392. // Continue unwinding to whatever we found ourselves unwinding
  2393. // to when the finalizer was entered (e.g. return from handler,
  2394. // which is unaffected by normal completion from finalizer).
  2395. interpreter.vm().unwind(unwind_until);
  2396. // If we previously had an exception and the finalizer didn't
  2397. // throw a new one, restore the old one.
  2398. if (previous_exception && !interpreter.exception())
  2399. interpreter.vm().set_exception(*previous_exception);
  2400. }
  2401. }
  2402. return result.value_or(js_undefined());
  2403. }
  2404. Value CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2405. {
  2406. InterpreterNodeScope node_scope { interpreter, *this };
  2407. // NOTE: CatchClause execution is handled by TryStatement.
  2408. VERIFY_NOT_REACHED();
  2409. return {};
  2410. }
  2411. Value ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2412. {
  2413. InterpreterNodeScope node_scope { interpreter, *this };
  2414. auto value = m_argument->execute(interpreter, global_object);
  2415. if (interpreter.vm().exception())
  2416. return {};
  2417. interpreter.vm().throw_exception(global_object, value);
  2418. return {};
  2419. }
  2420. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  2421. Value SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2422. {
  2423. // FIXME: This needs a massive refactoring, ideally once we start using continue, break, and return completions.
  2424. // Instead of having an optional test expression, SwitchCase should be split into CaseClause and DefaultClause.
  2425. // https://tc39.es/ecma262/#sec-switch-statement
  2426. InterpreterNodeScope node_scope { interpreter, *this };
  2427. auto discriminant_result = m_discriminant->execute(interpreter, global_object);
  2428. if (interpreter.exception())
  2429. return {};
  2430. auto* old_environment = interpreter.lexical_environment();
  2431. ScopeGuard restore_environment = [&] {
  2432. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  2433. };
  2434. auto* block_environment = new_declarative_environment(*old_environment);
  2435. block_declaration_instantiation(global_object, block_environment);
  2436. interpreter.vm().running_execution_context().lexical_environment = block_environment;
  2437. Optional<size_t> first_passing_case;
  2438. for (size_t i = 0; i < m_cases.size(); ++i) {
  2439. auto& switch_case = m_cases[i];
  2440. if (switch_case.test()) {
  2441. auto test_result = switch_case.test()->execute(interpreter, global_object);
  2442. if (interpreter.exception())
  2443. return {};
  2444. if (is_strictly_equal(discriminant_result, test_result)) {
  2445. first_passing_case = i;
  2446. break;
  2447. }
  2448. }
  2449. }
  2450. // FIXME: we could optimize and store the location of the default case in a member variable.
  2451. if (!first_passing_case.has_value()) {
  2452. for (size_t i = 0; i < m_cases.size(); ++i) {
  2453. auto& switch_case = m_cases[i];
  2454. if (!switch_case.test()) {
  2455. first_passing_case = i;
  2456. break;
  2457. }
  2458. }
  2459. }
  2460. auto last_value = js_undefined();
  2461. if (!first_passing_case.has_value()) {
  2462. return last_value;
  2463. }
  2464. VERIFY(first_passing_case.value() < m_cases.size());
  2465. for (size_t i = first_passing_case.value(); i < m_cases.size(); ++i) {
  2466. auto& switch_case = m_cases[i];
  2467. for (auto& statement : switch_case.children()) {
  2468. auto value = statement.execute(interpreter, global_object);
  2469. if (!value.is_empty())
  2470. last_value = value;
  2471. if (interpreter.exception())
  2472. return {};
  2473. if (interpreter.vm().should_unwind()) {
  2474. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  2475. // No stop_unwind(), the outer loop will handle that - we just need to break out of the switch/case.
  2476. return last_value;
  2477. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  2478. interpreter.vm().stop_unwind();
  2479. return last_value;
  2480. } else {
  2481. return last_value;
  2482. }
  2483. }
  2484. }
  2485. }
  2486. return last_value;
  2487. }
  2488. Value SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  2489. {
  2490. InterpreterNodeScope node_scope { interpreter, *this };
  2491. // NOTE: SwitchCase execution is handled by SwitchStatement.
  2492. VERIFY_NOT_REACHED();
  2493. return {};
  2494. }
  2495. Value BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2496. {
  2497. InterpreterNodeScope node_scope { interpreter, *this };
  2498. interpreter.vm().unwind(ScopeType::Breakable, m_target_label);
  2499. return {};
  2500. }
  2501. Value ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2502. {
  2503. InterpreterNodeScope node_scope { interpreter, *this };
  2504. interpreter.vm().unwind(ScopeType::Continuable, m_target_label);
  2505. return {};
  2506. }
  2507. void SwitchStatement::dump(int indent) const
  2508. {
  2509. ASTNode::dump(indent);
  2510. m_discriminant->dump(indent + 1);
  2511. for (auto& switch_case : m_cases) {
  2512. switch_case.dump(indent + 1);
  2513. }
  2514. }
  2515. void SwitchCase::dump(int indent) const
  2516. {
  2517. print_indent(indent + 1);
  2518. if (m_test) {
  2519. outln("(Test)");
  2520. m_test->dump(indent + 2);
  2521. } else {
  2522. outln("(Default)");
  2523. }
  2524. print_indent(indent + 1);
  2525. outln("(Consequent)");
  2526. ScopeNode::dump(indent + 2);
  2527. }
  2528. Value ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2529. {
  2530. InterpreterNodeScope node_scope { interpreter, *this };
  2531. auto test_result = m_test->execute(interpreter, global_object);
  2532. if (interpreter.exception())
  2533. return {};
  2534. Value result;
  2535. if (test_result.to_boolean()) {
  2536. result = m_consequent->execute(interpreter, global_object);
  2537. } else {
  2538. result = m_alternate->execute(interpreter, global_object);
  2539. }
  2540. if (interpreter.exception())
  2541. return {};
  2542. return result;
  2543. }
  2544. void ConditionalExpression::dump(int indent) const
  2545. {
  2546. ASTNode::dump(indent);
  2547. print_indent(indent + 1);
  2548. outln("(Test)");
  2549. m_test->dump(indent + 2);
  2550. print_indent(indent + 1);
  2551. outln("(Consequent)");
  2552. m_consequent->dump(indent + 2);
  2553. print_indent(indent + 1);
  2554. outln("(Alternate)");
  2555. m_alternate->dump(indent + 2);
  2556. }
  2557. void SequenceExpression::dump(int indent) const
  2558. {
  2559. ASTNode::dump(indent);
  2560. for (auto& expression : m_expressions)
  2561. expression.dump(indent + 1);
  2562. }
  2563. Value SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2564. {
  2565. InterpreterNodeScope node_scope { interpreter, *this };
  2566. Value last_value;
  2567. for (auto& expression : m_expressions) {
  2568. last_value = expression.execute(interpreter, global_object);
  2569. if (interpreter.exception())
  2570. return {};
  2571. }
  2572. return last_value;
  2573. }
  2574. Value DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2575. {
  2576. InterpreterNodeScope node_scope { interpreter, *this };
  2577. // Sorry, no JavaScript debugger available (yet)!
  2578. return {};
  2579. }
  2580. void ScopeNode::for_each_lexically_scoped_declaration(IteratorOrVoidFunction<Declaration const&>&& callback) const
  2581. {
  2582. for (auto& declaration : m_lexical_declarations) {
  2583. if (callback(declaration) == IterationDecision::Break)
  2584. break;
  2585. }
  2586. }
  2587. void ScopeNode::for_each_lexically_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  2588. {
  2589. auto running = true;
  2590. for (auto& declaration : m_lexical_declarations) {
  2591. declaration.for_each_bound_name([&](auto const& name) {
  2592. if (callback(name) == IterationDecision::Break) {
  2593. running = false;
  2594. return IterationDecision::Break;
  2595. }
  2596. return IterationDecision::Continue;
  2597. });
  2598. if (!running)
  2599. break;
  2600. }
  2601. }
  2602. void ScopeNode::for_each_var_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  2603. {
  2604. auto running = true;
  2605. for (auto& declaration : m_var_declarations) {
  2606. declaration.for_each_bound_name([&](auto const& name) {
  2607. if (callback(name) == IterationDecision::Break) {
  2608. running = false;
  2609. return IterationDecision::Break;
  2610. }
  2611. return IterationDecision::Continue;
  2612. });
  2613. if (!running)
  2614. break;
  2615. }
  2616. }
  2617. void ScopeNode::for_each_var_function_declaration_in_reverse_order(IteratorOrVoidFunction<FunctionDeclaration const&>&& callback) const
  2618. {
  2619. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  2620. auto& declaration = m_var_declarations[i];
  2621. if (is<FunctionDeclaration>(declaration)) {
  2622. if (callback(static_cast<FunctionDeclaration const&>(declaration)) == IterationDecision::Break)
  2623. break;
  2624. }
  2625. }
  2626. }
  2627. void ScopeNode::for_each_var_scoped_variable_declaration(IteratorOrVoidFunction<VariableDeclaration const&>&& callback) const
  2628. {
  2629. for (auto& declaration : m_var_declarations) {
  2630. if (!is<FunctionDeclaration>(declaration)) {
  2631. VERIFY(is<VariableDeclaration>(declaration));
  2632. if (callback(static_cast<VariableDeclaration const&>(declaration)) == IterationDecision::Break)
  2633. break;
  2634. }
  2635. }
  2636. }
  2637. void ScopeNode::for_each_function_hoistable_with_annexB_extension(IteratorOrVoidFunction<FunctionDeclaration&>&& callback) const
  2638. {
  2639. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  2640. // We need const_cast here since it might have to set a property on function declaration.
  2641. if (callback(const_cast<FunctionDeclaration&>(function)) == IterationDecision::Break)
  2642. break;
  2643. }
  2644. }
  2645. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration> declaration)
  2646. {
  2647. m_lexical_declarations.append(move(declaration));
  2648. }
  2649. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration> declaration)
  2650. {
  2651. m_var_declarations.append(move(declaration));
  2652. }
  2653. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declaration)
  2654. {
  2655. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  2656. }
  2657. Value ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2658. {
  2659. InterpreterNodeScope node_scope { interpreter, *this };
  2660. dbgln("Modules are not fully supported yet!");
  2661. TODO();
  2662. return {};
  2663. }
  2664. Value ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2665. {
  2666. InterpreterNodeScope node_scope { interpreter, *this };
  2667. if (m_statement)
  2668. return m_statement->execute(interpreter, global_object);
  2669. return {};
  2670. }
  2671. void ExportStatement::dump(int indent) const
  2672. {
  2673. ASTNode::dump(indent);
  2674. print_indent(indent + 1);
  2675. outln("(ExportEntries)");
  2676. auto string_or_null = [](String const& string) -> String {
  2677. if (string.is_empty()) {
  2678. return "null";
  2679. }
  2680. return String::formatted("\"{}\"", string);
  2681. };
  2682. for (auto& entry : m_entries) {
  2683. print_indent(indent + 2);
  2684. outln("ModuleRequest: {}, ImportName: {}, LocalName: {}, ExportName: {}", string_or_null(entry.module_request), entry.kind == ExportEntry::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null", entry.kind != ExportEntry::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null", string_or_null(entry.export_name));
  2685. }
  2686. }
  2687. void ImportStatement::dump(int indent) const
  2688. {
  2689. ASTNode::dump(indent);
  2690. print_indent(indent + 1);
  2691. if (m_entries.is_empty()) {
  2692. // direct from "module" import
  2693. outln("Entire module '{}'", m_module_request);
  2694. } else {
  2695. outln("(ExportEntries) from {}", m_module_request);
  2696. for (auto& entry : m_entries) {
  2697. print_indent(indent + 2);
  2698. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  2699. }
  2700. }
  2701. }
  2702. bool ExportStatement::has_export(StringView export_name) const
  2703. {
  2704. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2705. return entry.export_name == export_name;
  2706. });
  2707. }
  2708. bool ImportStatement::has_bound_name(StringView name) const
  2709. {
  2710. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2711. return entry.local_name == name;
  2712. });
  2713. }
  2714. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  2715. void ScopeNode::block_declaration_instantiation(GlobalObject& global_object, Environment* environment) const
  2716. {
  2717. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  2718. VERIFY(environment);
  2719. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  2720. auto is_constant_declaration = declaration.is_constant_declaration();
  2721. declaration.for_each_bound_name([&](auto const& name) {
  2722. if (is_constant_declaration) {
  2723. environment->create_immutable_binding(global_object, name, true);
  2724. } else {
  2725. if (!environment->has_binding(name))
  2726. environment->create_mutable_binding(global_object, name, false);
  2727. }
  2728. });
  2729. if (is<FunctionDeclaration>(declaration)) {
  2730. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  2731. auto* function = ECMAScriptFunctionObject::create(global_object, function_declaration.name(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, function_declaration.kind(), function_declaration.is_strict_mode());
  2732. VERIFY(is<DeclarativeEnvironment>(*environment));
  2733. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, global_object, function_declaration.name(), function);
  2734. }
  2735. });
  2736. }
  2737. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  2738. ThrowCompletionOr<void> Program::global_declaration_instantiation(Interpreter& interpreter, GlobalObject& global_object, GlobalEnvironment& global_environment) const
  2739. {
  2740. for_each_lexically_declared_name([&](FlyString const& name) {
  2741. if (global_environment.has_var_declaration(name) || global_environment.has_lexical_declaration(name)) {
  2742. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Lexical variable top level already declared");
  2743. return IterationDecision::Break;
  2744. }
  2745. auto restricted_global = global_environment.has_restricted_global_property(name);
  2746. if (interpreter.exception())
  2747. return IterationDecision::Break;
  2748. if (restricted_global)
  2749. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Restricted global property");
  2750. return IterationDecision::Continue;
  2751. });
  2752. if (auto* exception = interpreter.exception())
  2753. return throw_completion(exception->value());
  2754. for_each_var_declared_name([&](auto const& name) {
  2755. if (global_environment.has_lexical_declaration(name)) {
  2756. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Var declared variable top level also lexically declared");
  2757. return IterationDecision::Break;
  2758. }
  2759. return IterationDecision::Continue;
  2760. });
  2761. if (auto* exception = interpreter.exception())
  2762. return throw_completion(exception->value());
  2763. HashTable<FlyString> declared_function_names;
  2764. Vector<FunctionDeclaration const&> functions_to_initialize;
  2765. for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  2766. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  2767. return IterationDecision::Continue;
  2768. auto function_definable = global_environment.can_declare_global_function(function.name());
  2769. if (interpreter.exception())
  2770. return IterationDecision::Break;
  2771. if (!function_definable) {
  2772. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Global function not definable");
  2773. return IterationDecision::Break;
  2774. }
  2775. functions_to_initialize.append(function);
  2776. return IterationDecision::Continue;
  2777. });
  2778. if (auto* exception = interpreter.exception())
  2779. return throw_completion(exception->value());
  2780. HashTable<FlyString> declared_var_names;
  2781. for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  2782. declaration.for_each_bound_name([&](auto const& name) {
  2783. if (declared_function_names.contains(name))
  2784. return IterationDecision::Continue;
  2785. auto var_definable = global_environment.can_declare_global_var(name);
  2786. if (interpreter.exception())
  2787. return IterationDecision::Break;
  2788. if (!var_definable) {
  2789. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Global variable not definable");
  2790. return IterationDecision::Break;
  2791. }
  2792. declared_var_names.set(name);
  2793. return IterationDecision::Continue;
  2794. });
  2795. if (interpreter.exception())
  2796. return IterationDecision::Break;
  2797. return IterationDecision::Continue;
  2798. });
  2799. if (auto* exception = interpreter.exception())
  2800. return throw_completion(exception->value());
  2801. if (!m_is_strict_mode) {
  2802. for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  2803. auto& function_name = function_declaration.name();
  2804. if (global_environment.has_lexical_declaration(function_name))
  2805. return IterationDecision::Continue;
  2806. auto function_definable = global_environment.can_declare_global_function(function_name);
  2807. if (interpreter.exception())
  2808. return IterationDecision::Break;
  2809. if (!function_definable) {
  2810. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::FixmeAddAnErrorStringWithMessage, "Global function not definable");
  2811. return IterationDecision::Break;
  2812. }
  2813. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  2814. global_environment.create_global_var_binding(function_name, false);
  2815. if (interpreter.exception())
  2816. return IterationDecision::Break;
  2817. declared_function_names.set(function_name);
  2818. }
  2819. function_declaration.set_should_do_additional_annexB_steps();
  2820. return IterationDecision::Continue;
  2821. });
  2822. if (auto* exception = interpreter.exception())
  2823. return throw_completion(exception->value());
  2824. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  2825. declared_function_names.clear();
  2826. }
  2827. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  2828. declaration.for_each_bound_name([&](auto const& name) {
  2829. if (declaration.is_constant_declaration())
  2830. global_environment.create_immutable_binding(global_object, name, true);
  2831. else
  2832. global_environment.create_mutable_binding(global_object, name, false);
  2833. if (interpreter.exception())
  2834. return IterationDecision::Break;
  2835. return IterationDecision::Continue;
  2836. });
  2837. if (interpreter.exception())
  2838. return IterationDecision::Break;
  2839. return IterationDecision::Continue;
  2840. });
  2841. for (auto& declaration : functions_to_initialize) {
  2842. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), &global_environment, declaration.kind(), declaration.is_strict_mode());
  2843. global_environment.create_global_function_binding(declaration.name(), function, false);
  2844. if (auto* exception = interpreter.exception())
  2845. return throw_completion(exception->value());
  2846. }
  2847. for (auto& var_name : declared_var_names) {
  2848. global_environment.create_global_var_binding(var_name, false);
  2849. if (auto* exception = interpreter.exception())
  2850. return throw_completion(exception->value());
  2851. }
  2852. return {};
  2853. }
  2854. }