AST.cpp 121 KB

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