AST.cpp 121 KB

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