AST.cpp 120 KB

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