AST.cpp 134 KB

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