AST.cpp 121 KB

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