AST.cpp 131 KB

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