AST.cpp 121 KB

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