AST.cpp 120 KB

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