AST.cpp 121 KB

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