AST.cpp 134 KB

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