AST.cpp 141 KB

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