AST.cpp 133 KB

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