AST.cpp 141 KB

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