AST.cpp 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356
  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 = TRY_OR_DISCARD(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 = TRY(key.to_property_key(global_object));
  1068. auto& target = method.is_static() ? *class_constructor : class_prototype.as_object();
  1069. method_function.set_home_object(&target);
  1070. switch (method.kind()) {
  1071. case ClassMethod::Kind::Method:
  1072. TRY(target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1073. break;
  1074. case ClassMethod::Kind::Getter:
  1075. update_function_name(method_value, String::formatted("get {}", TRY(get_function_name(global_object, key))));
  1076. TRY(target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true }));
  1077. break;
  1078. case ClassMethod::Kind::Setter:
  1079. update_function_name(method_value, String::formatted("set {}", TRY(get_function_name(global_object, key))));
  1080. TRY(target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true }));
  1081. break;
  1082. default:
  1083. VERIFY_NOT_REACHED();
  1084. }
  1085. }
  1086. for (auto& field : m_fields) {
  1087. auto key = field.key().execute(interpreter, global_object);
  1088. if (auto* exception = interpreter.exception())
  1089. return throw_completion(exception->value());
  1090. auto property_key = TRY(key.to_property_key(global_object));
  1091. ECMAScriptFunctionObject* initializer = nullptr;
  1092. if (field.initializer()) {
  1093. auto copy_initializer = field.initializer();
  1094. auto body = create_ast_node<ExpressionStatement>(field.initializer()->source_range(), copy_initializer.release_nonnull());
  1095. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  1096. initializer = ECMAScriptFunctionObject::create(interpreter.global_object(), property_key.to_display_string(), *body, {}, 0, interpreter.lexical_environment(), FunctionKind::Regular, false, false);
  1097. initializer->set_home_object(field.is_static() ? class_constructor : &class_prototype.as_object());
  1098. }
  1099. if (field.is_static()) {
  1100. Value field_value = js_undefined();
  1101. if (initializer)
  1102. field_value = TRY(interpreter.vm().call(*initializer, class_constructor_value));
  1103. TRY(class_constructor->create_data_property_or_throw(property_key, field_value));
  1104. } else {
  1105. class_constructor->add_field(property_key, initializer);
  1106. }
  1107. }
  1108. vm.running_execution_context().lexical_environment = environment;
  1109. restore_environment.disarm();
  1110. if (!binding_name.is_null())
  1111. MUST(class_scope->initialize_binding(global_object, binding_name, class_constructor));
  1112. return Value(class_constructor);
  1113. }
  1114. static void print_indent(int indent)
  1115. {
  1116. out("{}", String::repeated(' ', indent * 2));
  1117. }
  1118. void ASTNode::dump(int indent) const
  1119. {
  1120. print_indent(indent);
  1121. outln("{}", class_name());
  1122. }
  1123. void ScopeNode::dump(int indent) const
  1124. {
  1125. ASTNode::dump(indent);
  1126. if (!m_lexical_declarations.is_empty()) {
  1127. print_indent(indent + 1);
  1128. outln("(Lexical declarations)");
  1129. for (auto& declaration : m_lexical_declarations)
  1130. declaration.dump(indent + 2);
  1131. }
  1132. if (!m_var_declarations.is_empty()) {
  1133. print_indent(indent + 1);
  1134. outln("(Variable declarations)");
  1135. for (auto& declaration : m_var_declarations)
  1136. declaration.dump(indent + 2);
  1137. }
  1138. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1139. print_indent(indent + 1);
  1140. outln("(Hoisted functions via annexB extension)");
  1141. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1142. declaration.dump(indent + 2);
  1143. }
  1144. if (!m_children.is_empty()) {
  1145. print_indent(indent + 1);
  1146. outln("(Children)");
  1147. for (auto& child : children())
  1148. child.dump(indent + 2);
  1149. }
  1150. }
  1151. void BinaryExpression::dump(int indent) const
  1152. {
  1153. const char* op_string = nullptr;
  1154. switch (m_op) {
  1155. case BinaryOp::Addition:
  1156. op_string = "+";
  1157. break;
  1158. case BinaryOp::Subtraction:
  1159. op_string = "-";
  1160. break;
  1161. case BinaryOp::Multiplication:
  1162. op_string = "*";
  1163. break;
  1164. case BinaryOp::Division:
  1165. op_string = "/";
  1166. break;
  1167. case BinaryOp::Modulo:
  1168. op_string = "%";
  1169. break;
  1170. case BinaryOp::Exponentiation:
  1171. op_string = "**";
  1172. break;
  1173. case BinaryOp::StrictlyEquals:
  1174. op_string = "===";
  1175. break;
  1176. case BinaryOp::StrictlyInequals:
  1177. op_string = "!==";
  1178. break;
  1179. case BinaryOp::LooselyEquals:
  1180. op_string = "==";
  1181. break;
  1182. case BinaryOp::LooselyInequals:
  1183. op_string = "!=";
  1184. break;
  1185. case BinaryOp::GreaterThan:
  1186. op_string = ">";
  1187. break;
  1188. case BinaryOp::GreaterThanEquals:
  1189. op_string = ">=";
  1190. break;
  1191. case BinaryOp::LessThan:
  1192. op_string = "<";
  1193. break;
  1194. case BinaryOp::LessThanEquals:
  1195. op_string = "<=";
  1196. break;
  1197. case BinaryOp::BitwiseAnd:
  1198. op_string = "&";
  1199. break;
  1200. case BinaryOp::BitwiseOr:
  1201. op_string = "|";
  1202. break;
  1203. case BinaryOp::BitwiseXor:
  1204. op_string = "^";
  1205. break;
  1206. case BinaryOp::LeftShift:
  1207. op_string = "<<";
  1208. break;
  1209. case BinaryOp::RightShift:
  1210. op_string = ">>";
  1211. break;
  1212. case BinaryOp::UnsignedRightShift:
  1213. op_string = ">>>";
  1214. break;
  1215. case BinaryOp::In:
  1216. op_string = "in";
  1217. break;
  1218. case BinaryOp::InstanceOf:
  1219. op_string = "instanceof";
  1220. break;
  1221. }
  1222. print_indent(indent);
  1223. outln("{}", class_name());
  1224. m_lhs->dump(indent + 1);
  1225. print_indent(indent + 1);
  1226. outln("{}", op_string);
  1227. m_rhs->dump(indent + 1);
  1228. }
  1229. void LogicalExpression::dump(int indent) const
  1230. {
  1231. const char* op_string = nullptr;
  1232. switch (m_op) {
  1233. case LogicalOp::And:
  1234. op_string = "&&";
  1235. break;
  1236. case LogicalOp::Or:
  1237. op_string = "||";
  1238. break;
  1239. case LogicalOp::NullishCoalescing:
  1240. op_string = "??";
  1241. break;
  1242. }
  1243. print_indent(indent);
  1244. outln("{}", class_name());
  1245. m_lhs->dump(indent + 1);
  1246. print_indent(indent + 1);
  1247. outln("{}", op_string);
  1248. m_rhs->dump(indent + 1);
  1249. }
  1250. void UnaryExpression::dump(int indent) const
  1251. {
  1252. const char* op_string = nullptr;
  1253. switch (m_op) {
  1254. case UnaryOp::BitwiseNot:
  1255. op_string = "~";
  1256. break;
  1257. case UnaryOp::Not:
  1258. op_string = "!";
  1259. break;
  1260. case UnaryOp::Plus:
  1261. op_string = "+";
  1262. break;
  1263. case UnaryOp::Minus:
  1264. op_string = "-";
  1265. break;
  1266. case UnaryOp::Typeof:
  1267. op_string = "typeof ";
  1268. break;
  1269. case UnaryOp::Void:
  1270. op_string = "void ";
  1271. break;
  1272. case UnaryOp::Delete:
  1273. op_string = "delete ";
  1274. break;
  1275. }
  1276. print_indent(indent);
  1277. outln("{}", class_name());
  1278. print_indent(indent + 1);
  1279. outln("{}", op_string);
  1280. m_lhs->dump(indent + 1);
  1281. }
  1282. void CallExpression::dump(int indent) const
  1283. {
  1284. print_indent(indent);
  1285. if (is<NewExpression>(*this))
  1286. outln("CallExpression [new]");
  1287. else
  1288. outln("CallExpression");
  1289. m_callee->dump(indent + 1);
  1290. for (auto& argument : m_arguments)
  1291. argument.value->dump(indent + 1);
  1292. }
  1293. void SuperCall::dump(int indent) const
  1294. {
  1295. print_indent(indent);
  1296. outln("SuperCall");
  1297. for (auto& argument : m_arguments)
  1298. argument.value->dump(indent + 1);
  1299. }
  1300. void ClassDeclaration::dump(int indent) const
  1301. {
  1302. ASTNode::dump(indent);
  1303. m_class_expression->dump(indent + 1);
  1304. }
  1305. void ClassDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1306. {
  1307. if (!m_class_expression->name().is_empty())
  1308. callback(m_class_expression->name());
  1309. }
  1310. void ClassExpression::dump(int indent) const
  1311. {
  1312. print_indent(indent);
  1313. outln("ClassExpression: \"{}\"", m_name);
  1314. print_indent(indent);
  1315. outln("(Constructor)");
  1316. m_constructor->dump(indent + 1);
  1317. if (!m_super_class.is_null()) {
  1318. print_indent(indent);
  1319. outln("(Super Class)");
  1320. m_super_class->dump(indent + 1);
  1321. }
  1322. print_indent(indent);
  1323. outln("(Methods)");
  1324. for (auto& method : m_methods)
  1325. method.dump(indent + 1);
  1326. print_indent(indent);
  1327. outln("(Fields)");
  1328. for (auto& field : m_fields)
  1329. field.dump(indent + 1);
  1330. }
  1331. void ClassMethod::dump(int indent) const
  1332. {
  1333. ASTNode::dump(indent);
  1334. print_indent(indent);
  1335. outln("(Key)");
  1336. m_key->dump(indent + 1);
  1337. const char* kind_string = nullptr;
  1338. switch (m_kind) {
  1339. case Kind::Method:
  1340. kind_string = "Method";
  1341. break;
  1342. case Kind::Getter:
  1343. kind_string = "Getter";
  1344. break;
  1345. case Kind::Setter:
  1346. kind_string = "Setter";
  1347. break;
  1348. }
  1349. print_indent(indent);
  1350. outln("Kind: {}", kind_string);
  1351. print_indent(indent);
  1352. outln("Static: {}", m_is_static);
  1353. print_indent(indent);
  1354. outln("(Function)");
  1355. m_function->dump(indent + 1);
  1356. }
  1357. void ClassField::dump(int indent) const
  1358. {
  1359. ASTNode::dump(indent);
  1360. print_indent(indent);
  1361. outln("(Key)");
  1362. m_key->dump(indent + 1);
  1363. print_indent(indent);
  1364. outln("Static: {}", m_is_static);
  1365. if (m_initializer) {
  1366. print_indent(indent);
  1367. outln("(Initializer)");
  1368. m_initializer->dump(indent + 1);
  1369. }
  1370. }
  1371. void StringLiteral::dump(int indent) const
  1372. {
  1373. print_indent(indent);
  1374. outln("StringLiteral \"{}\"", m_value);
  1375. }
  1376. void SuperExpression::dump(int indent) const
  1377. {
  1378. print_indent(indent);
  1379. outln("super");
  1380. }
  1381. void NumericLiteral::dump(int indent) const
  1382. {
  1383. print_indent(indent);
  1384. outln("NumericLiteral {}", m_value);
  1385. }
  1386. void BigIntLiteral::dump(int indent) const
  1387. {
  1388. print_indent(indent);
  1389. outln("BigIntLiteral {}", m_value);
  1390. }
  1391. void BooleanLiteral::dump(int indent) const
  1392. {
  1393. print_indent(indent);
  1394. outln("BooleanLiteral {}", m_value);
  1395. }
  1396. void NullLiteral::dump(int indent) const
  1397. {
  1398. print_indent(indent);
  1399. outln("null");
  1400. }
  1401. bool BindingPattern::contains_expression() const
  1402. {
  1403. for (auto& entry : entries) {
  1404. if (entry.initializer)
  1405. return true;
  1406. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1407. return true;
  1408. }
  1409. return false;
  1410. }
  1411. void BindingPattern::dump(int indent) const
  1412. {
  1413. print_indent(indent);
  1414. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1415. for (auto& entry : entries) {
  1416. print_indent(indent + 1);
  1417. outln("(Property)");
  1418. if (kind == Kind::Object) {
  1419. print_indent(indent + 2);
  1420. outln("(Identifier)");
  1421. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1422. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1423. } else {
  1424. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1425. }
  1426. } else if (entry.is_elision()) {
  1427. print_indent(indent + 2);
  1428. outln("(Elision)");
  1429. continue;
  1430. }
  1431. print_indent(indent + 2);
  1432. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1433. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1434. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1435. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1436. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1437. } else if (entry.alias.has<NonnullRefPtr<MemberExpression>>()) {
  1438. entry.alias.get<NonnullRefPtr<MemberExpression>>()->dump(indent + 3);
  1439. } else {
  1440. print_indent(indent + 3);
  1441. outln("<empty>");
  1442. }
  1443. if (entry.initializer) {
  1444. print_indent(indent + 2);
  1445. outln("(Initializer)");
  1446. entry.initializer->dump(indent + 3);
  1447. }
  1448. }
  1449. }
  1450. void FunctionNode::dump(int indent, String const& class_name) const
  1451. {
  1452. print_indent(indent);
  1453. outln("{}{} '{}'", class_name, m_kind == FunctionKind::Generator ? "*" : "", name());
  1454. if (m_contains_direct_call_to_eval) {
  1455. print_indent(indent + 1);
  1456. outln("\033[31;1m(direct eval)\033[0m");
  1457. }
  1458. if (!m_parameters.is_empty()) {
  1459. print_indent(indent + 1);
  1460. outln("(Parameters)");
  1461. for (auto& parameter : m_parameters) {
  1462. print_indent(indent + 2);
  1463. if (parameter.is_rest)
  1464. out("...");
  1465. parameter.binding.visit(
  1466. [&](FlyString const& name) {
  1467. outln("{}", name);
  1468. },
  1469. [&](BindingPattern const& pattern) {
  1470. pattern.dump(indent + 2);
  1471. });
  1472. if (parameter.default_value)
  1473. parameter.default_value->dump(indent + 3);
  1474. }
  1475. }
  1476. print_indent(indent + 1);
  1477. outln("(Body)");
  1478. body().dump(indent + 2);
  1479. }
  1480. void FunctionDeclaration::dump(int indent) const
  1481. {
  1482. FunctionNode::dump(indent, class_name());
  1483. }
  1484. void FunctionDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1485. {
  1486. if (!name().is_empty())
  1487. callback(name());
  1488. }
  1489. void FunctionExpression::dump(int indent) const
  1490. {
  1491. FunctionNode::dump(indent, class_name());
  1492. }
  1493. void YieldExpression::dump(int indent) const
  1494. {
  1495. ASTNode::dump(indent);
  1496. if (argument())
  1497. argument()->dump(indent + 1);
  1498. }
  1499. void ReturnStatement::dump(int indent) const
  1500. {
  1501. ASTNode::dump(indent);
  1502. if (argument())
  1503. argument()->dump(indent + 1);
  1504. }
  1505. void IfStatement::dump(int indent) const
  1506. {
  1507. ASTNode::dump(indent);
  1508. print_indent(indent);
  1509. outln("If");
  1510. predicate().dump(indent + 1);
  1511. consequent().dump(indent + 1);
  1512. if (alternate()) {
  1513. print_indent(indent);
  1514. outln("Else");
  1515. alternate()->dump(indent + 1);
  1516. }
  1517. }
  1518. void WhileStatement::dump(int indent) const
  1519. {
  1520. ASTNode::dump(indent);
  1521. print_indent(indent);
  1522. outln("While");
  1523. test().dump(indent + 1);
  1524. body().dump(indent + 1);
  1525. }
  1526. void WithStatement::dump(int indent) const
  1527. {
  1528. ASTNode::dump(indent);
  1529. print_indent(indent + 1);
  1530. outln("Object");
  1531. object().dump(indent + 2);
  1532. print_indent(indent + 1);
  1533. outln("Body");
  1534. body().dump(indent + 2);
  1535. }
  1536. void DoWhileStatement::dump(int indent) const
  1537. {
  1538. ASTNode::dump(indent);
  1539. print_indent(indent);
  1540. outln("DoWhile");
  1541. test().dump(indent + 1);
  1542. body().dump(indent + 1);
  1543. }
  1544. void ForStatement::dump(int indent) const
  1545. {
  1546. ASTNode::dump(indent);
  1547. print_indent(indent);
  1548. outln("For");
  1549. if (init())
  1550. init()->dump(indent + 1);
  1551. if (test())
  1552. test()->dump(indent + 1);
  1553. if (update())
  1554. update()->dump(indent + 1);
  1555. body().dump(indent + 1);
  1556. }
  1557. void ForInStatement::dump(int indent) const
  1558. {
  1559. ASTNode::dump(indent);
  1560. print_indent(indent);
  1561. outln("ForIn");
  1562. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1563. rhs().dump(indent + 1);
  1564. body().dump(indent + 1);
  1565. }
  1566. void ForOfStatement::dump(int indent) const
  1567. {
  1568. ASTNode::dump(indent);
  1569. print_indent(indent);
  1570. outln("ForOf");
  1571. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1572. rhs().dump(indent + 1);
  1573. body().dump(indent + 1);
  1574. }
  1575. Value Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1576. {
  1577. InterpreterNodeScope node_scope { interpreter, *this };
  1578. auto reference = to_reference(interpreter, global_object);
  1579. if (interpreter.exception())
  1580. return {};
  1581. return reference.get_value(global_object);
  1582. }
  1583. void Identifier::dump(int indent) const
  1584. {
  1585. print_indent(indent);
  1586. outln("Identifier \"{}\"", m_string);
  1587. }
  1588. void SpreadExpression::dump(int indent) const
  1589. {
  1590. ASTNode::dump(indent);
  1591. m_target->dump(indent + 1);
  1592. }
  1593. Value SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1594. {
  1595. InterpreterNodeScope node_scope { interpreter, *this };
  1596. return m_target->execute(interpreter, global_object);
  1597. }
  1598. Value ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1599. {
  1600. InterpreterNodeScope node_scope { interpreter, *this };
  1601. return interpreter.vm().resolve_this_binding(global_object);
  1602. }
  1603. void ThisExpression::dump(int indent) const
  1604. {
  1605. ASTNode::dump(indent);
  1606. }
  1607. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  1608. Value AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1609. {
  1610. InterpreterNodeScope node_scope { interpreter, *this };
  1611. if (m_op == AssignmentOp::Assignment) {
  1612. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  1613. return m_lhs.visit(
  1614. [&](NonnullRefPtr<Expression>& lhs) -> JS::Value {
  1615. auto reference = lhs->to_reference(interpreter, global_object);
  1616. if (interpreter.exception())
  1617. return {};
  1618. Value rhs_result;
  1619. if (lhs->is_identifier()) {
  1620. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  1621. rhs_result = TRY_OR_DISCARD(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  1622. } else {
  1623. rhs_result = m_rhs->execute(interpreter, global_object);
  1624. }
  1625. if (interpreter.exception())
  1626. return {};
  1627. reference.put_value(global_object, rhs_result);
  1628. if (interpreter.exception())
  1629. return {};
  1630. return rhs_result;
  1631. },
  1632. [&](NonnullRefPtr<BindingPattern>& pattern) -> JS::Value {
  1633. Value rhs_result = m_rhs->execute(interpreter, global_object);
  1634. if (interpreter.exception())
  1635. return {};
  1636. TRY_OR_DISCARD(interpreter.vm().destructuring_assignment_evaluation(pattern, rhs_result, global_object));
  1637. return rhs_result;
  1638. });
  1639. }
  1640. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  1641. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression>>();
  1642. auto reference = lhs_expression.to_reference(interpreter, global_object);
  1643. if (interpreter.exception())
  1644. return {};
  1645. auto lhs_result = reference.get_value(global_object);
  1646. if (interpreter.exception())
  1647. return {};
  1648. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  1649. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  1650. switch (m_op) {
  1651. case AssignmentOp::AndAssignment:
  1652. if (!lhs_result.to_boolean())
  1653. return lhs_result;
  1654. break;
  1655. case AssignmentOp::OrAssignment:
  1656. if (lhs_result.to_boolean())
  1657. return lhs_result;
  1658. break;
  1659. case AssignmentOp::NullishAssignment:
  1660. if (!lhs_result.is_nullish())
  1661. return lhs_result;
  1662. break;
  1663. default:
  1664. VERIFY_NOT_REACHED();
  1665. }
  1666. Value rhs_result;
  1667. if (lhs_expression.is_identifier()) {
  1668. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  1669. rhs_result = TRY_OR_DISCARD(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  1670. } else {
  1671. rhs_result = m_rhs->execute(interpreter, global_object);
  1672. if (interpreter.exception())
  1673. return {};
  1674. }
  1675. reference.put_value(global_object, rhs_result);
  1676. if (interpreter.exception())
  1677. return {};
  1678. return rhs_result;
  1679. }
  1680. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  1681. auto rhs_result = m_rhs->execute(interpreter, global_object);
  1682. if (interpreter.exception())
  1683. return {};
  1684. switch (m_op) {
  1685. case AssignmentOp::AdditionAssignment:
  1686. rhs_result = add(global_object, lhs_result, rhs_result);
  1687. break;
  1688. case AssignmentOp::SubtractionAssignment:
  1689. rhs_result = sub(global_object, lhs_result, rhs_result);
  1690. break;
  1691. case AssignmentOp::MultiplicationAssignment:
  1692. rhs_result = mul(global_object, lhs_result, rhs_result);
  1693. break;
  1694. case AssignmentOp::DivisionAssignment:
  1695. rhs_result = div(global_object, lhs_result, rhs_result);
  1696. break;
  1697. case AssignmentOp::ModuloAssignment:
  1698. rhs_result = mod(global_object, lhs_result, rhs_result);
  1699. break;
  1700. case AssignmentOp::ExponentiationAssignment:
  1701. rhs_result = exp(global_object, lhs_result, rhs_result);
  1702. break;
  1703. case AssignmentOp::BitwiseAndAssignment:
  1704. rhs_result = bitwise_and(global_object, lhs_result, rhs_result);
  1705. break;
  1706. case AssignmentOp::BitwiseOrAssignment:
  1707. rhs_result = bitwise_or(global_object, lhs_result, rhs_result);
  1708. break;
  1709. case AssignmentOp::BitwiseXorAssignment:
  1710. rhs_result = bitwise_xor(global_object, lhs_result, rhs_result);
  1711. break;
  1712. case AssignmentOp::LeftShiftAssignment:
  1713. rhs_result = left_shift(global_object, lhs_result, rhs_result);
  1714. break;
  1715. case AssignmentOp::RightShiftAssignment:
  1716. rhs_result = right_shift(global_object, lhs_result, rhs_result);
  1717. break;
  1718. case AssignmentOp::UnsignedRightShiftAssignment:
  1719. rhs_result = unsigned_right_shift(global_object, lhs_result, rhs_result);
  1720. break;
  1721. case AssignmentOp::Assignment:
  1722. case AssignmentOp::AndAssignment:
  1723. case AssignmentOp::OrAssignment:
  1724. case AssignmentOp::NullishAssignment:
  1725. VERIFY_NOT_REACHED();
  1726. }
  1727. if (interpreter.exception())
  1728. return {};
  1729. reference.put_value(global_object, rhs_result);
  1730. if (interpreter.exception())
  1731. return {};
  1732. return rhs_result;
  1733. }
  1734. Value UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1735. {
  1736. InterpreterNodeScope node_scope { interpreter, *this };
  1737. auto reference = m_argument->to_reference(interpreter, global_object);
  1738. if (interpreter.exception())
  1739. return {};
  1740. auto old_value = reference.get_value(global_object);
  1741. if (interpreter.exception())
  1742. return {};
  1743. old_value = TRY_OR_DISCARD(old_value.to_numeric(global_object));
  1744. Value new_value;
  1745. switch (m_op) {
  1746. case UpdateOp::Increment:
  1747. if (old_value.is_number())
  1748. new_value = Value(old_value.as_double() + 1);
  1749. else
  1750. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  1751. break;
  1752. case UpdateOp::Decrement:
  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().minus(Crypto::SignedBigInteger { 1 }));
  1757. break;
  1758. default:
  1759. VERIFY_NOT_REACHED();
  1760. }
  1761. reference.put_value(global_object, new_value);
  1762. if (interpreter.exception())
  1763. return {};
  1764. return m_prefixed ? new_value : old_value;
  1765. }
  1766. void AssignmentExpression::dump(int indent) const
  1767. {
  1768. const char* op_string = nullptr;
  1769. switch (m_op) {
  1770. case AssignmentOp::Assignment:
  1771. op_string = "=";
  1772. break;
  1773. case AssignmentOp::AdditionAssignment:
  1774. op_string = "+=";
  1775. break;
  1776. case AssignmentOp::SubtractionAssignment:
  1777. op_string = "-=";
  1778. break;
  1779. case AssignmentOp::MultiplicationAssignment:
  1780. op_string = "*=";
  1781. break;
  1782. case AssignmentOp::DivisionAssignment:
  1783. op_string = "/=";
  1784. break;
  1785. case AssignmentOp::ModuloAssignment:
  1786. op_string = "%=";
  1787. break;
  1788. case AssignmentOp::ExponentiationAssignment:
  1789. op_string = "**=";
  1790. break;
  1791. case AssignmentOp::BitwiseAndAssignment:
  1792. op_string = "&=";
  1793. break;
  1794. case AssignmentOp::BitwiseOrAssignment:
  1795. op_string = "|=";
  1796. break;
  1797. case AssignmentOp::BitwiseXorAssignment:
  1798. op_string = "^=";
  1799. break;
  1800. case AssignmentOp::LeftShiftAssignment:
  1801. op_string = "<<=";
  1802. break;
  1803. case AssignmentOp::RightShiftAssignment:
  1804. op_string = ">>=";
  1805. break;
  1806. case AssignmentOp::UnsignedRightShiftAssignment:
  1807. op_string = ">>>=";
  1808. break;
  1809. case AssignmentOp::AndAssignment:
  1810. op_string = "&&=";
  1811. break;
  1812. case AssignmentOp::OrAssignment:
  1813. op_string = "||=";
  1814. break;
  1815. case AssignmentOp::NullishAssignment:
  1816. op_string = "\?\?=";
  1817. break;
  1818. }
  1819. ASTNode::dump(indent);
  1820. print_indent(indent + 1);
  1821. outln("{}", op_string);
  1822. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  1823. m_rhs->dump(indent + 1);
  1824. }
  1825. void UpdateExpression::dump(int indent) const
  1826. {
  1827. const char* op_string = nullptr;
  1828. switch (m_op) {
  1829. case UpdateOp::Increment:
  1830. op_string = "++";
  1831. break;
  1832. case UpdateOp::Decrement:
  1833. op_string = "--";
  1834. break;
  1835. }
  1836. ASTNode::dump(indent);
  1837. if (m_prefixed) {
  1838. print_indent(indent + 1);
  1839. outln("{}", op_string);
  1840. }
  1841. m_argument->dump(indent + 1);
  1842. if (!m_prefixed) {
  1843. print_indent(indent + 1);
  1844. outln("{}", op_string);
  1845. }
  1846. }
  1847. Value VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1848. {
  1849. InterpreterNodeScope node_scope { interpreter, *this };
  1850. for (auto& declarator : m_declarations) {
  1851. if (auto* init = declarator.init()) {
  1852. declarator.target().visit(
  1853. [&](NonnullRefPtr<Identifier> const& id) {
  1854. auto reference = id->to_reference(interpreter, global_object);
  1855. if (interpreter.exception())
  1856. return;
  1857. auto initializer_result_or_error = interpreter.vm().named_evaluation_if_anonymous_function(global_object, *init, id->string());
  1858. if (initializer_result_or_error.is_error())
  1859. return;
  1860. auto initializer_result = initializer_result_or_error.release_value();
  1861. VERIFY(!initializer_result.is_empty());
  1862. if (m_declaration_kind == DeclarationKind::Var)
  1863. reference.put_value(global_object, initializer_result);
  1864. else
  1865. reference.initialize_referenced_binding(global_object, initializer_result);
  1866. },
  1867. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  1868. auto initializer_result = init->execute(interpreter, global_object);
  1869. if (interpreter.exception())
  1870. return;
  1871. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  1872. // FIXME: I want to use TRY_OR_DISCARD here but can't return...
  1873. auto result = interpreter.vm().binding_initialization(pattern, initializer_result, environment, global_object);
  1874. (void)result;
  1875. });
  1876. if (interpreter.exception())
  1877. return {};
  1878. } else if (m_declaration_kind != DeclarationKind::Var) {
  1879. VERIFY(declarator.target().has<NonnullRefPtr<Identifier>>());
  1880. auto& identifier = declarator.target().get<NonnullRefPtr<Identifier>>();
  1881. auto reference = identifier->to_reference(interpreter, global_object);
  1882. reference.initialize_referenced_binding(global_object, js_undefined());
  1883. if (interpreter.exception())
  1884. return {};
  1885. }
  1886. }
  1887. return {};
  1888. }
  1889. Value VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  1890. {
  1891. InterpreterNodeScope node_scope { interpreter, *this };
  1892. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  1893. VERIFY_NOT_REACHED();
  1894. }
  1895. void VariableDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1896. {
  1897. for (auto& entry : declarations()) {
  1898. entry.target().template visit(
  1899. [&](const NonnullRefPtr<Identifier>& id) {
  1900. callback(id->string());
  1901. },
  1902. [&](const NonnullRefPtr<BindingPattern>& binding) {
  1903. binding->for_each_bound_name([&](const auto& name) {
  1904. callback(name);
  1905. });
  1906. });
  1907. }
  1908. }
  1909. void VariableDeclaration::dump(int indent) const
  1910. {
  1911. const char* declaration_kind_string = nullptr;
  1912. switch (m_declaration_kind) {
  1913. case DeclarationKind::Let:
  1914. declaration_kind_string = "Let";
  1915. break;
  1916. case DeclarationKind::Var:
  1917. declaration_kind_string = "Var";
  1918. break;
  1919. case DeclarationKind::Const:
  1920. declaration_kind_string = "Const";
  1921. break;
  1922. }
  1923. ASTNode::dump(indent);
  1924. print_indent(indent + 1);
  1925. outln("{}", declaration_kind_string);
  1926. for (auto& declarator : m_declarations)
  1927. declarator.dump(indent + 1);
  1928. }
  1929. void VariableDeclarator::dump(int indent) const
  1930. {
  1931. ASTNode::dump(indent);
  1932. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  1933. if (m_init)
  1934. m_init->dump(indent + 1);
  1935. }
  1936. void ObjectProperty::dump(int indent) const
  1937. {
  1938. ASTNode::dump(indent);
  1939. if (m_property_type == Type::Spread) {
  1940. print_indent(indent + 1);
  1941. outln("...Spreading");
  1942. m_key->dump(indent + 1);
  1943. } else {
  1944. m_key->dump(indent + 1);
  1945. m_value->dump(indent + 1);
  1946. }
  1947. }
  1948. void ObjectExpression::dump(int indent) const
  1949. {
  1950. ASTNode::dump(indent);
  1951. for (auto& property : m_properties) {
  1952. property.dump(indent + 1);
  1953. }
  1954. }
  1955. void ExpressionStatement::dump(int indent) const
  1956. {
  1957. ASTNode::dump(indent);
  1958. m_expression->dump(indent + 1);
  1959. }
  1960. Value ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  1961. {
  1962. InterpreterNodeScope node_scope { interpreter, *this };
  1963. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  1964. VERIFY_NOT_REACHED();
  1965. }
  1966. Value ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1967. {
  1968. InterpreterNodeScope node_scope { interpreter, *this };
  1969. auto* object = Object::create(global_object, global_object.object_prototype());
  1970. for (auto& property : m_properties) {
  1971. auto key = property.key().execute(interpreter, global_object);
  1972. if (interpreter.exception())
  1973. return {};
  1974. if (property.type() == ObjectProperty::Type::Spread) {
  1975. if (key.is_object() && is<Array>(key.as_object())) {
  1976. auto& array_to_spread = static_cast<Array&>(key.as_object());
  1977. for (auto& entry : array_to_spread.indexed_properties()) {
  1978. auto value = TRY_OR_DISCARD(array_to_spread.get(entry.index()));
  1979. object->indexed_properties().put(entry.index(), value);
  1980. if (interpreter.exception())
  1981. return {};
  1982. }
  1983. } else if (key.is_object()) {
  1984. auto& obj_to_spread = key.as_object();
  1985. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  1986. if (it.value.attributes.is_enumerable()) {
  1987. object->define_direct_property(it.key, TRY_OR_DISCARD(obj_to_spread.get(it.key)), JS::default_attributes);
  1988. if (interpreter.exception())
  1989. return {};
  1990. }
  1991. }
  1992. } else if (key.is_string()) {
  1993. auto& str_to_spread = key.as_string().string();
  1994. for (size_t i = 0; i < str_to_spread.length(); i++) {
  1995. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  1996. if (interpreter.exception())
  1997. return {};
  1998. }
  1999. }
  2000. continue;
  2001. }
  2002. auto value = property.value().execute(interpreter, global_object);
  2003. if (interpreter.exception())
  2004. return {};
  2005. if (value.is_function() && property.is_method())
  2006. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  2007. auto name = TRY_OR_DISCARD(get_function_name(global_object, key));
  2008. if (property.type() == ObjectProperty::Type::Getter) {
  2009. name = String::formatted("get {}", name);
  2010. } else if (property.type() == ObjectProperty::Type::Setter) {
  2011. name = String::formatted("set {}", name);
  2012. }
  2013. update_function_name(value, name);
  2014. switch (property.type()) {
  2015. case ObjectProperty::Type::Getter:
  2016. VERIFY(value.is_function());
  2017. object->define_direct_accessor(PropertyName::from_value(global_object, key), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  2018. break;
  2019. case ObjectProperty::Type::Setter:
  2020. VERIFY(value.is_function());
  2021. object->define_direct_accessor(PropertyName::from_value(global_object, key), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2022. break;
  2023. case ObjectProperty::Type::KeyValue:
  2024. object->define_direct_property(PropertyName::from_value(global_object, key), value, JS::default_attributes);
  2025. break;
  2026. case ObjectProperty::Type::Spread:
  2027. default:
  2028. VERIFY_NOT_REACHED();
  2029. }
  2030. if (interpreter.exception())
  2031. return {};
  2032. }
  2033. return object;
  2034. }
  2035. void MemberExpression::dump(int indent) const
  2036. {
  2037. print_indent(indent);
  2038. outln("{}(computed={})", class_name(), is_computed());
  2039. m_object->dump(indent + 1);
  2040. m_property->dump(indent + 1);
  2041. }
  2042. PropertyName MemberExpression::computed_property_name(Interpreter& interpreter, GlobalObject& global_object) const
  2043. {
  2044. if (!is_computed())
  2045. return verify_cast<Identifier>(*m_property).string();
  2046. auto value = m_property->execute(interpreter, global_object);
  2047. if (interpreter.exception())
  2048. return {};
  2049. VERIFY(!value.is_empty());
  2050. return PropertyName::from_value(global_object, value);
  2051. }
  2052. String MemberExpression::to_string_approximation() const
  2053. {
  2054. String object_string = "<object>";
  2055. if (is<Identifier>(*m_object))
  2056. object_string = static_cast<Identifier const&>(*m_object).string();
  2057. if (is_computed())
  2058. return String::formatted("{}[<computed>]", object_string);
  2059. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2060. }
  2061. Value MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2062. {
  2063. InterpreterNodeScope node_scope { interpreter, *this };
  2064. auto reference = to_reference(interpreter, global_object);
  2065. if (interpreter.exception())
  2066. return {};
  2067. return reference.get_value(global_object);
  2068. }
  2069. void OptionalChain::dump(int indent) const
  2070. {
  2071. print_indent(indent);
  2072. outln("{}", class_name());
  2073. m_base->dump(indent + 1);
  2074. for (auto& reference : m_references) {
  2075. reference.visit(
  2076. [&](Call const& call) {
  2077. print_indent(indent + 1);
  2078. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2079. for (auto& argument : call.arguments)
  2080. argument.value->dump(indent + 2);
  2081. },
  2082. [&](ComputedReference const& ref) {
  2083. print_indent(indent + 1);
  2084. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2085. ref.expression->dump(indent + 2);
  2086. },
  2087. [&](MemberReference const& ref) {
  2088. print_indent(indent + 1);
  2089. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2090. ref.identifier->dump(indent + 2);
  2091. });
  2092. }
  2093. }
  2094. Optional<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  2095. {
  2096. // Note: This is wrapped in an optional to allow base_reference = ...
  2097. Optional<JS::Reference> base_reference = m_base->to_reference(interpreter, global_object);
  2098. auto base = base_reference->is_unresolvable() ? m_base->execute(interpreter, global_object) : base_reference->get_value(global_object);
  2099. if (interpreter.exception())
  2100. return {};
  2101. for (auto& reference : m_references) {
  2102. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2103. if (is_optional && base.is_nullish())
  2104. return ReferenceAndValue { {}, js_undefined() };
  2105. auto expression = reference.visit(
  2106. [&](Call const& call) -> NonnullRefPtr<Expression> {
  2107. return create_ast_node<CallExpression>(source_range(),
  2108. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2109. call.arguments);
  2110. },
  2111. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  2112. return create_ast_node<MemberExpression>(source_range(),
  2113. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2114. ref.expression,
  2115. true);
  2116. },
  2117. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  2118. return create_ast_node<MemberExpression>(source_range(),
  2119. create_ast_node<SyntheticReferenceExpression>(source_range(), *base_reference, base),
  2120. ref.identifier,
  2121. false);
  2122. });
  2123. if (is<CallExpression>(*expression)) {
  2124. base_reference = JS::Reference {};
  2125. base = expression->execute(interpreter, global_object);
  2126. } else {
  2127. base_reference = expression->to_reference(interpreter, global_object);
  2128. base = base_reference->get_value(global_object);
  2129. }
  2130. if (interpreter.exception())
  2131. return {};
  2132. }
  2133. return ReferenceAndValue { base_reference.release_value(), base };
  2134. }
  2135. Value OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2136. {
  2137. InterpreterNodeScope node_scope { interpreter, *this };
  2138. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  2139. return result.release_value().value;
  2140. return {};
  2141. }
  2142. JS::Reference OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  2143. {
  2144. if (auto result = to_reference_and_value(interpreter, global_object); result.has_value())
  2145. return result.release_value().reference;
  2146. return {};
  2147. }
  2148. void MetaProperty::dump(int indent) const
  2149. {
  2150. String name;
  2151. if (m_type == MetaProperty::Type::NewTarget)
  2152. name = "new.target";
  2153. else if (m_type == MetaProperty::Type::ImportMeta)
  2154. name = "import.meta";
  2155. else
  2156. VERIFY_NOT_REACHED();
  2157. print_indent(indent);
  2158. outln("{} {}", class_name(), name);
  2159. }
  2160. Value MetaProperty::execute(Interpreter& interpreter, GlobalObject&) const
  2161. {
  2162. InterpreterNodeScope node_scope { interpreter, *this };
  2163. if (m_type == MetaProperty::Type::NewTarget)
  2164. return interpreter.vm().get_new_target().value_or(js_undefined());
  2165. if (m_type == MetaProperty::Type::ImportMeta)
  2166. TODO();
  2167. VERIFY_NOT_REACHED();
  2168. }
  2169. Value StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2170. {
  2171. InterpreterNodeScope node_scope { interpreter, *this };
  2172. return js_string(interpreter.heap(), m_value);
  2173. }
  2174. Value NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2175. {
  2176. InterpreterNodeScope node_scope { interpreter, *this };
  2177. return Value(m_value);
  2178. }
  2179. Value BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2180. {
  2181. InterpreterNodeScope node_scope { interpreter, *this };
  2182. Crypto::SignedBigInteger integer;
  2183. if (m_value[0] == '0' && m_value.length() >= 3) {
  2184. if (m_value[1] == 'x' || m_value[1] == 'X') {
  2185. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3)));
  2186. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  2187. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3)));
  2188. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  2189. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3)));
  2190. }
  2191. }
  2192. return js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1)));
  2193. }
  2194. Value BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2195. {
  2196. InterpreterNodeScope node_scope { interpreter, *this };
  2197. return Value(m_value);
  2198. }
  2199. Value NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2200. {
  2201. InterpreterNodeScope node_scope { interpreter, *this };
  2202. return js_null();
  2203. }
  2204. void RegExpLiteral::dump(int indent) const
  2205. {
  2206. print_indent(indent);
  2207. outln("{} (/{}/{})", class_name(), pattern(), flags());
  2208. }
  2209. Value RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2210. {
  2211. InterpreterNodeScope node_scope { interpreter, *this };
  2212. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  2213. return RegExpObject::create(global_object, move(regex), pattern(), flags());
  2214. }
  2215. void ArrayExpression::dump(int indent) const
  2216. {
  2217. ASTNode::dump(indent);
  2218. for (auto& element : m_elements) {
  2219. if (element) {
  2220. element->dump(indent + 1);
  2221. } else {
  2222. print_indent(indent + 1);
  2223. outln("<empty>");
  2224. }
  2225. }
  2226. }
  2227. Value ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2228. {
  2229. InterpreterNodeScope node_scope { interpreter, *this };
  2230. auto* array = Array::create(global_object, 0);
  2231. array->indexed_properties();
  2232. size_t index = 0;
  2233. for (auto& element : m_elements) {
  2234. auto value = Value();
  2235. if (element) {
  2236. value = element->execute(interpreter, global_object);
  2237. if (interpreter.exception())
  2238. return {};
  2239. if (is<SpreadExpression>(*element)) {
  2240. get_iterator_values(global_object, value, [&](Value iterator_value) {
  2241. array->indexed_properties().put(index++, iterator_value, default_attributes);
  2242. return IterationDecision::Continue;
  2243. });
  2244. if (interpreter.exception())
  2245. return {};
  2246. continue;
  2247. }
  2248. }
  2249. array->indexed_properties().put(index++, value, default_attributes);
  2250. }
  2251. return array;
  2252. }
  2253. void TemplateLiteral::dump(int indent) const
  2254. {
  2255. ASTNode::dump(indent);
  2256. for (auto& expression : m_expressions)
  2257. expression.dump(indent + 1);
  2258. }
  2259. Value TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2260. {
  2261. InterpreterNodeScope node_scope { interpreter, *this };
  2262. StringBuilder string_builder;
  2263. for (auto& expression : m_expressions) {
  2264. auto expr = expression.execute(interpreter, global_object);
  2265. if (interpreter.exception())
  2266. return {};
  2267. auto string = TRY_OR_DISCARD(expr.to_string(global_object));
  2268. string_builder.append(string);
  2269. }
  2270. return js_string(interpreter.heap(), string_builder.build());
  2271. }
  2272. void TaggedTemplateLiteral::dump(int indent) const
  2273. {
  2274. ASTNode::dump(indent);
  2275. print_indent(indent + 1);
  2276. outln("(Tag)");
  2277. m_tag->dump(indent + 2);
  2278. print_indent(indent + 1);
  2279. outln("(Template Literal)");
  2280. m_template_literal->dump(indent + 2);
  2281. }
  2282. Value TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2283. {
  2284. InterpreterNodeScope node_scope { interpreter, *this };
  2285. auto& vm = interpreter.vm();
  2286. auto tag = m_tag->execute(interpreter, global_object);
  2287. if (vm.exception())
  2288. return {};
  2289. if (!tag.is_function()) {
  2290. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, tag.to_string_without_side_effects());
  2291. return {};
  2292. }
  2293. auto& tag_function = tag.as_function();
  2294. auto& expressions = m_template_literal->expressions();
  2295. auto* strings = Array::create(global_object, 0);
  2296. MarkedValueList arguments(vm.heap());
  2297. arguments.append(strings);
  2298. for (size_t i = 0; i < expressions.size(); ++i) {
  2299. auto value = expressions[i].execute(interpreter, global_object);
  2300. if (vm.exception())
  2301. return {};
  2302. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  2303. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  2304. if (i % 2 == 0) {
  2305. strings->indexed_properties().append(value);
  2306. } else {
  2307. arguments.append(value);
  2308. }
  2309. }
  2310. auto* raw_strings = Array::create(global_object, 0);
  2311. for (auto& raw_string : m_template_literal->raw_strings()) {
  2312. auto value = raw_string.execute(interpreter, global_object);
  2313. if (vm.exception())
  2314. return {};
  2315. raw_strings->indexed_properties().append(value);
  2316. }
  2317. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  2318. return TRY_OR_DISCARD(vm.call(tag_function, js_undefined(), move(arguments)));
  2319. }
  2320. void TryStatement::dump(int indent) const
  2321. {
  2322. ASTNode::dump(indent);
  2323. print_indent(indent);
  2324. outln("(Block)");
  2325. block().dump(indent + 1);
  2326. if (handler()) {
  2327. print_indent(indent);
  2328. outln("(Handler)");
  2329. handler()->dump(indent + 1);
  2330. }
  2331. if (finalizer()) {
  2332. print_indent(indent);
  2333. outln("(Finalizer)");
  2334. finalizer()->dump(indent + 1);
  2335. }
  2336. }
  2337. void CatchClause::dump(int indent) const
  2338. {
  2339. print_indent(indent);
  2340. m_parameter.visit(
  2341. [&](FlyString const& parameter) {
  2342. if (parameter.is_null())
  2343. outln("CatchClause");
  2344. else
  2345. outln("CatchClause ({})", parameter);
  2346. },
  2347. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2348. outln("CatchClause");
  2349. print_indent(indent);
  2350. outln("(Parameter)");
  2351. pattern->dump(indent + 2);
  2352. });
  2353. body().dump(indent + 1);
  2354. }
  2355. void ThrowStatement::dump(int indent) const
  2356. {
  2357. ASTNode::dump(indent);
  2358. argument().dump(indent + 1);
  2359. }
  2360. void TryStatement::add_label(FlyString string)
  2361. {
  2362. m_block->add_label(move(string));
  2363. }
  2364. Value TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2365. {
  2366. InterpreterNodeScope node_scope { interpreter, *this };
  2367. // FIXME: Use Completions here to be closer to the spec.
  2368. auto result = m_block->execute(interpreter, global_object);
  2369. if (interpreter.vm().unwind_until() == ScopeType::Try)
  2370. interpreter.vm().stop_unwind();
  2371. if (auto* exception = interpreter.exception()) {
  2372. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  2373. if (m_handler) {
  2374. interpreter.vm().clear_exception();
  2375. auto* catch_scope = new_declarative_environment(*interpreter.lexical_environment());
  2376. m_handler->parameter().visit(
  2377. [&](FlyString const& parameter) {
  2378. MUST(catch_scope->create_mutable_binding(global_object, parameter, false));
  2379. },
  2380. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2381. pattern->for_each_bound_name([&](auto& name) {
  2382. MUST(catch_scope->create_mutable_binding(global_object, name, false));
  2383. });
  2384. });
  2385. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, catch_scope);
  2386. m_handler->parameter().visit(
  2387. [&](FlyString const& parameter) {
  2388. (void)catch_scope->initialize_binding(global_object, parameter, exception->value());
  2389. },
  2390. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2391. (void)interpreter.vm().binding_initialization(pattern, exception->value(), catch_scope, global_object);
  2392. });
  2393. if (!interpreter.exception())
  2394. result = m_handler->body().execute(interpreter, global_object);
  2395. }
  2396. }
  2397. if (m_finalizer) {
  2398. // Keep, if any, and then clear the current exception so we can
  2399. // execute() the finalizer without an exception in our way.
  2400. auto* previous_exception = interpreter.exception();
  2401. interpreter.vm().clear_exception();
  2402. // Remember what scope type we were unwinding to, and temporarily
  2403. // clear it as well (e.g. return from handler).
  2404. auto unwind_until = interpreter.vm().unwind_until();
  2405. interpreter.vm().stop_unwind();
  2406. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2407. if (interpreter.vm().should_unwind()) {
  2408. // This was NOT a 'normal' completion (e.g. return from finalizer).
  2409. result = finalizer_result;
  2410. } else {
  2411. // Continue unwinding to whatever we found ourselves unwinding
  2412. // to when the finalizer was entered (e.g. return from handler,
  2413. // which is unaffected by normal completion from finalizer).
  2414. interpreter.vm().unwind(unwind_until);
  2415. // If we previously had an exception and the finalizer didn't
  2416. // throw a new one, restore the old one.
  2417. if (previous_exception && !interpreter.exception())
  2418. interpreter.vm().set_exception(*previous_exception);
  2419. }
  2420. }
  2421. return result.value_or(js_undefined());
  2422. }
  2423. Value CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2424. {
  2425. InterpreterNodeScope node_scope { interpreter, *this };
  2426. // NOTE: CatchClause execution is handled by TryStatement.
  2427. VERIFY_NOT_REACHED();
  2428. return {};
  2429. }
  2430. Value ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2431. {
  2432. InterpreterNodeScope node_scope { interpreter, *this };
  2433. auto value = m_argument->execute(interpreter, global_object);
  2434. if (interpreter.vm().exception())
  2435. return {};
  2436. interpreter.vm().throw_exception(global_object, value);
  2437. return {};
  2438. }
  2439. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  2440. Value SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2441. {
  2442. // FIXME: This needs a massive refactoring, ideally once we start using continue, break, and return completions.
  2443. // Instead of having an optional test expression, SwitchCase should be split into CaseClause and DefaultClause.
  2444. // https://tc39.es/ecma262/#sec-switch-statement
  2445. InterpreterNodeScope node_scope { interpreter, *this };
  2446. auto discriminant_result = m_discriminant->execute(interpreter, global_object);
  2447. if (interpreter.exception())
  2448. return {};
  2449. // Optimization: Avoid creating a lexical environment if there are no lexical declarations.
  2450. Optional<TemporaryChange<Environment*>> lexical_environment_changer;
  2451. if (has_lexical_declarations()) {
  2452. auto* old_environment = interpreter.lexical_environment();
  2453. auto* block_environment = new_declarative_environment(*old_environment);
  2454. block_declaration_instantiation(global_object, block_environment);
  2455. lexical_environment_changer.emplace(interpreter.vm().running_execution_context().lexical_environment, block_environment);
  2456. }
  2457. Optional<size_t> first_passing_case;
  2458. for (size_t i = 0; i < m_cases.size(); ++i) {
  2459. auto& switch_case = m_cases[i];
  2460. if (switch_case.test()) {
  2461. auto test_result = switch_case.test()->execute(interpreter, global_object);
  2462. if (interpreter.exception())
  2463. return {};
  2464. if (is_strictly_equal(discriminant_result, test_result)) {
  2465. first_passing_case = i;
  2466. break;
  2467. }
  2468. }
  2469. }
  2470. // FIXME: we could optimize and store the location of the default case in a member variable.
  2471. if (!first_passing_case.has_value()) {
  2472. for (size_t i = 0; i < m_cases.size(); ++i) {
  2473. auto& switch_case = m_cases[i];
  2474. if (!switch_case.test()) {
  2475. first_passing_case = i;
  2476. break;
  2477. }
  2478. }
  2479. }
  2480. auto last_value = js_undefined();
  2481. if (!first_passing_case.has_value()) {
  2482. return last_value;
  2483. }
  2484. VERIFY(first_passing_case.value() < m_cases.size());
  2485. for (size_t i = first_passing_case.value(); i < m_cases.size(); ++i) {
  2486. auto& switch_case = m_cases[i];
  2487. for (auto& statement : switch_case.children()) {
  2488. auto value = statement.execute(interpreter, global_object);
  2489. if (!value.is_empty())
  2490. last_value = value;
  2491. if (interpreter.exception())
  2492. return {};
  2493. if (interpreter.vm().should_unwind()) {
  2494. if (interpreter.vm().should_unwind_until(ScopeType::Continuable, m_labels)) {
  2495. // No stop_unwind(), the outer loop will handle that - we just need to break out of the switch/case.
  2496. return last_value;
  2497. } else if (interpreter.vm().should_unwind_until(ScopeType::Breakable, m_labels)) {
  2498. interpreter.vm().stop_unwind();
  2499. return last_value;
  2500. } else {
  2501. return last_value;
  2502. }
  2503. }
  2504. }
  2505. }
  2506. return last_value;
  2507. }
  2508. Value SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  2509. {
  2510. InterpreterNodeScope node_scope { interpreter, *this };
  2511. // NOTE: SwitchCase execution is handled by SwitchStatement.
  2512. VERIFY_NOT_REACHED();
  2513. return {};
  2514. }
  2515. Value BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2516. {
  2517. InterpreterNodeScope node_scope { interpreter, *this };
  2518. interpreter.vm().unwind(ScopeType::Breakable, m_target_label);
  2519. return {};
  2520. }
  2521. Value ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2522. {
  2523. InterpreterNodeScope node_scope { interpreter, *this };
  2524. interpreter.vm().unwind(ScopeType::Continuable, m_target_label);
  2525. return {};
  2526. }
  2527. void SwitchStatement::dump(int indent) const
  2528. {
  2529. ASTNode::dump(indent);
  2530. m_discriminant->dump(indent + 1);
  2531. for (auto& switch_case : m_cases) {
  2532. switch_case.dump(indent + 1);
  2533. }
  2534. }
  2535. void SwitchCase::dump(int indent) const
  2536. {
  2537. print_indent(indent + 1);
  2538. if (m_test) {
  2539. outln("(Test)");
  2540. m_test->dump(indent + 2);
  2541. } else {
  2542. outln("(Default)");
  2543. }
  2544. print_indent(indent + 1);
  2545. outln("(Consequent)");
  2546. ScopeNode::dump(indent + 2);
  2547. }
  2548. Value ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2549. {
  2550. InterpreterNodeScope node_scope { interpreter, *this };
  2551. auto test_result = m_test->execute(interpreter, global_object);
  2552. if (interpreter.exception())
  2553. return {};
  2554. Value result;
  2555. if (test_result.to_boolean()) {
  2556. result = m_consequent->execute(interpreter, global_object);
  2557. } else {
  2558. result = m_alternate->execute(interpreter, global_object);
  2559. }
  2560. if (interpreter.exception())
  2561. return {};
  2562. return result;
  2563. }
  2564. void ConditionalExpression::dump(int indent) const
  2565. {
  2566. ASTNode::dump(indent);
  2567. print_indent(indent + 1);
  2568. outln("(Test)");
  2569. m_test->dump(indent + 2);
  2570. print_indent(indent + 1);
  2571. outln("(Consequent)");
  2572. m_consequent->dump(indent + 2);
  2573. print_indent(indent + 1);
  2574. outln("(Alternate)");
  2575. m_alternate->dump(indent + 2);
  2576. }
  2577. void SequenceExpression::dump(int indent) const
  2578. {
  2579. ASTNode::dump(indent);
  2580. for (auto& expression : m_expressions)
  2581. expression.dump(indent + 1);
  2582. }
  2583. Value SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2584. {
  2585. InterpreterNodeScope node_scope { interpreter, *this };
  2586. Value last_value;
  2587. for (auto& expression : m_expressions) {
  2588. last_value = expression.execute(interpreter, global_object);
  2589. if (interpreter.exception())
  2590. return {};
  2591. }
  2592. return last_value;
  2593. }
  2594. Value DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2595. {
  2596. InterpreterNodeScope node_scope { interpreter, *this };
  2597. // Sorry, no JavaScript debugger available (yet)!
  2598. return {};
  2599. }
  2600. void ScopeNode::for_each_lexically_scoped_declaration(IteratorOrVoidFunction<Declaration const&>&& callback) const
  2601. {
  2602. for (auto& declaration : m_lexical_declarations) {
  2603. if (callback(declaration) == IterationDecision::Break)
  2604. break;
  2605. }
  2606. }
  2607. void ScopeNode::for_each_lexically_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  2608. {
  2609. auto running = true;
  2610. for (auto& declaration : m_lexical_declarations) {
  2611. declaration.for_each_bound_name([&](auto const& name) {
  2612. if (callback(name) == IterationDecision::Break) {
  2613. running = false;
  2614. return IterationDecision::Break;
  2615. }
  2616. return IterationDecision::Continue;
  2617. });
  2618. if (!running)
  2619. break;
  2620. }
  2621. }
  2622. void ScopeNode::for_each_var_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  2623. {
  2624. auto running = true;
  2625. for (auto& declaration : m_var_declarations) {
  2626. declaration.for_each_bound_name([&](auto const& name) {
  2627. if (callback(name) == IterationDecision::Break) {
  2628. running = false;
  2629. return IterationDecision::Break;
  2630. }
  2631. return IterationDecision::Continue;
  2632. });
  2633. if (!running)
  2634. break;
  2635. }
  2636. }
  2637. void ScopeNode::for_each_var_function_declaration_in_reverse_order(IteratorOrVoidFunction<FunctionDeclaration const&>&& callback) const
  2638. {
  2639. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  2640. auto& declaration = m_var_declarations[i];
  2641. if (is<FunctionDeclaration>(declaration)) {
  2642. if (callback(static_cast<FunctionDeclaration const&>(declaration)) == IterationDecision::Break)
  2643. break;
  2644. }
  2645. }
  2646. }
  2647. void ScopeNode::for_each_var_scoped_variable_declaration(IteratorOrVoidFunction<VariableDeclaration const&>&& callback) const
  2648. {
  2649. for (auto& declaration : m_var_declarations) {
  2650. if (!is<FunctionDeclaration>(declaration)) {
  2651. VERIFY(is<VariableDeclaration>(declaration));
  2652. if (callback(static_cast<VariableDeclaration const&>(declaration)) == IterationDecision::Break)
  2653. break;
  2654. }
  2655. }
  2656. }
  2657. void ScopeNode::for_each_function_hoistable_with_annexB_extension(IteratorOrVoidFunction<FunctionDeclaration&>&& callback) const
  2658. {
  2659. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  2660. // We need const_cast here since it might have to set a property on function declaration.
  2661. if (callback(const_cast<FunctionDeclaration&>(function)) == IterationDecision::Break)
  2662. break;
  2663. }
  2664. }
  2665. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration> declaration)
  2666. {
  2667. m_lexical_declarations.append(move(declaration));
  2668. }
  2669. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration> declaration)
  2670. {
  2671. m_var_declarations.append(move(declaration));
  2672. }
  2673. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declaration)
  2674. {
  2675. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  2676. }
  2677. Value ImportStatement::execute(Interpreter& interpreter, GlobalObject&) const
  2678. {
  2679. InterpreterNodeScope node_scope { interpreter, *this };
  2680. dbgln("Modules are not fully supported yet!");
  2681. TODO();
  2682. return {};
  2683. }
  2684. Value ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2685. {
  2686. InterpreterNodeScope node_scope { interpreter, *this };
  2687. if (m_statement)
  2688. return m_statement->execute(interpreter, global_object);
  2689. return {};
  2690. }
  2691. void ExportStatement::dump(int indent) const
  2692. {
  2693. ASTNode::dump(indent);
  2694. print_indent(indent + 1);
  2695. outln("(ExportEntries)");
  2696. auto string_or_null = [](String const& string) -> String {
  2697. if (string.is_empty()) {
  2698. return "null";
  2699. }
  2700. return String::formatted("\"{}\"", string);
  2701. };
  2702. for (auto& entry : m_entries) {
  2703. print_indent(indent + 2);
  2704. 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));
  2705. }
  2706. }
  2707. void ImportStatement::dump(int indent) const
  2708. {
  2709. ASTNode::dump(indent);
  2710. print_indent(indent + 1);
  2711. if (m_entries.is_empty()) {
  2712. // direct from "module" import
  2713. outln("Entire module '{}'", m_module_request);
  2714. } else {
  2715. outln("(ExportEntries) from {}", m_module_request);
  2716. for (auto& entry : m_entries) {
  2717. print_indent(indent + 2);
  2718. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  2719. }
  2720. }
  2721. }
  2722. bool ExportStatement::has_export(StringView export_name) const
  2723. {
  2724. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2725. return entry.export_name == export_name;
  2726. });
  2727. }
  2728. bool ImportStatement::has_bound_name(StringView name) const
  2729. {
  2730. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  2731. return entry.local_name == name;
  2732. });
  2733. }
  2734. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  2735. void ScopeNode::block_declaration_instantiation(GlobalObject& global_object, Environment* environment) const
  2736. {
  2737. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  2738. VERIFY(environment);
  2739. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  2740. auto is_constant_declaration = declaration.is_constant_declaration();
  2741. declaration.for_each_bound_name([&](auto const& name) {
  2742. if (is_constant_declaration) {
  2743. MUST(environment->create_immutable_binding(global_object, name, true));
  2744. } else {
  2745. if (!MUST(environment->has_binding(name)))
  2746. MUST(environment->create_mutable_binding(global_object, name, false));
  2747. }
  2748. });
  2749. if (is<FunctionDeclaration>(declaration)) {
  2750. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  2751. 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());
  2752. VERIFY(is<DeclarativeEnvironment>(*environment));
  2753. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, global_object, function_declaration.name(), function);
  2754. }
  2755. });
  2756. }
  2757. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  2758. ThrowCompletionOr<void> Program::global_declaration_instantiation(Interpreter& interpreter, GlobalObject& global_object, GlobalEnvironment& global_environment) const
  2759. {
  2760. for_each_lexically_declared_name([&](FlyString const& name) {
  2761. if (global_environment.has_var_declaration(name) || global_environment.has_lexical_declaration(name)) {
  2762. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  2763. return IterationDecision::Break;
  2764. }
  2765. auto restricted_global = global_environment.has_restricted_global_property(name);
  2766. if (interpreter.exception())
  2767. return IterationDecision::Break;
  2768. if (restricted_global)
  2769. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::RestrictedGlobalProperty, name);
  2770. return IterationDecision::Continue;
  2771. });
  2772. if (auto* exception = interpreter.exception())
  2773. return throw_completion(exception->value());
  2774. for_each_var_declared_name([&](auto const& name) {
  2775. if (global_environment.has_lexical_declaration(name)) {
  2776. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  2777. return IterationDecision::Break;
  2778. }
  2779. return IterationDecision::Continue;
  2780. });
  2781. if (auto* exception = interpreter.exception())
  2782. return throw_completion(exception->value());
  2783. HashTable<FlyString> declared_function_names;
  2784. Vector<FunctionDeclaration const&> functions_to_initialize;
  2785. for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  2786. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  2787. return IterationDecision::Continue;
  2788. auto function_definable = global_environment.can_declare_global_function(function.name());
  2789. if (interpreter.exception())
  2790. return IterationDecision::Break;
  2791. if (!function_definable) {
  2792. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  2793. return IterationDecision::Break;
  2794. }
  2795. functions_to_initialize.append(function);
  2796. return IterationDecision::Continue;
  2797. });
  2798. if (auto* exception = interpreter.exception())
  2799. return throw_completion(exception->value());
  2800. HashTable<FlyString> declared_var_names;
  2801. for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  2802. declaration.for_each_bound_name([&](auto const& name) {
  2803. if (declared_function_names.contains(name))
  2804. return IterationDecision::Continue;
  2805. auto var_definable = global_environment.can_declare_global_var(name);
  2806. if (interpreter.exception())
  2807. return IterationDecision::Break;
  2808. if (!var_definable) {
  2809. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  2810. return IterationDecision::Break;
  2811. }
  2812. declared_var_names.set(name);
  2813. return IterationDecision::Continue;
  2814. });
  2815. if (interpreter.exception())
  2816. return IterationDecision::Break;
  2817. return IterationDecision::Continue;
  2818. });
  2819. if (auto* exception = interpreter.exception())
  2820. return throw_completion(exception->value());
  2821. if (!m_is_strict_mode) {
  2822. for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  2823. auto& function_name = function_declaration.name();
  2824. if (global_environment.has_lexical_declaration(function_name))
  2825. return IterationDecision::Continue;
  2826. auto function_definable = global_environment.can_declare_global_function(function_name);
  2827. if (interpreter.exception())
  2828. return IterationDecision::Break;
  2829. if (!function_definable) {
  2830. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function_name);
  2831. return IterationDecision::Break;
  2832. }
  2833. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  2834. global_environment.create_global_var_binding(function_name, false);
  2835. if (interpreter.exception())
  2836. return IterationDecision::Break;
  2837. declared_function_names.set(function_name);
  2838. }
  2839. function_declaration.set_should_do_additional_annexB_steps();
  2840. return IterationDecision::Continue;
  2841. });
  2842. if (auto* exception = interpreter.exception())
  2843. return throw_completion(exception->value());
  2844. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  2845. declared_function_names.clear();
  2846. }
  2847. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  2848. declaration.for_each_bound_name([&](auto const& name) {
  2849. if (declaration.is_constant_declaration())
  2850. (void)global_environment.create_immutable_binding(global_object, name, true);
  2851. else
  2852. (void)global_environment.create_mutable_binding(global_object, name, false);
  2853. if (interpreter.exception())
  2854. return IterationDecision::Break;
  2855. return IterationDecision::Continue;
  2856. });
  2857. if (interpreter.exception())
  2858. return IterationDecision::Break;
  2859. return IterationDecision::Continue;
  2860. });
  2861. for (auto& declaration : functions_to_initialize) {
  2862. 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());
  2863. global_environment.create_global_function_binding(declaration.name(), function, false);
  2864. if (auto* exception = interpreter.exception())
  2865. return throw_completion(exception->value());
  2866. }
  2867. for (auto& var_name : declared_var_names) {
  2868. global_environment.create_global_var_binding(var_name, false);
  2869. if (auto* exception = interpreter.exception())
  2870. return throw_completion(exception->value());
  2871. }
  2872. return {};
  2873. }
  2874. }