AST.cpp 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904
  1. /*
  2. * Copyright (c) 2020-2024, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, 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/QuickSort.h>
  12. #include <AK/ScopeGuard.h>
  13. #include <AK/StringBuilder.h>
  14. #include <AK/TemporaryChange.h>
  15. #include <LibCrypto/BigInt/SignedBigInteger.h>
  16. #include <LibJS/AST.h>
  17. #include <LibJS/Heap/ConservativeVector.h>
  18. #include <LibJS/Heap/MarkedVector.h>
  19. #include <LibJS/Runtime/AbstractOperations.h>
  20. #include <LibJS/Runtime/Accessor.h>
  21. #include <LibJS/Runtime/Array.h>
  22. #include <LibJS/Runtime/BigInt.h>
  23. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  24. #include <LibJS/Runtime/Error.h>
  25. #include <LibJS/Runtime/FunctionEnvironment.h>
  26. #include <LibJS/Runtime/GlobalEnvironment.h>
  27. #include <LibJS/Runtime/GlobalObject.h>
  28. #include <LibJS/Runtime/Iterator.h>
  29. #include <LibJS/Runtime/NativeFunction.h>
  30. #include <LibJS/Runtime/ObjectEnvironment.h>
  31. #include <LibJS/Runtime/PrimitiveString.h>
  32. #include <LibJS/Runtime/PromiseCapability.h>
  33. #include <LibJS/Runtime/PromiseConstructor.h>
  34. #include <LibJS/Runtime/Reference.h>
  35. #include <LibJS/Runtime/RegExpObject.h>
  36. #include <LibJS/Runtime/Shape.h>
  37. #include <LibJS/Runtime/ValueInlines.h>
  38. #include <typeinfo>
  39. namespace JS {
  40. ASTNode::ASTNode(SourceRange source_range)
  41. : m_start_offset(source_range.start.offset)
  42. , m_source_code(source_range.code)
  43. , m_end_offset(source_range.end.offset)
  44. {
  45. }
  46. SourceRange ASTNode::source_range() const
  47. {
  48. return m_source_code->range_from_offsets(m_start_offset, m_end_offset);
  49. }
  50. ByteString ASTNode::class_name() const
  51. {
  52. // NOTE: We strip the "JS::" prefix.
  53. auto const* typename_ptr = typeid(*this).name();
  54. return demangle({ typename_ptr, strlen(typename_ptr) }).substring(4);
  55. }
  56. static void print_indent(int indent)
  57. {
  58. out("{}", ByteString::repeated(' ', indent * 2));
  59. }
  60. static void update_function_name(Value value, DeprecatedFlyString const& name)
  61. {
  62. if (!value.is_function())
  63. return;
  64. auto& function = value.as_function();
  65. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  66. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  67. }
  68. void LabelledStatement::dump(int indent) const
  69. {
  70. ASTNode::dump(indent);
  71. print_indent(indent + 1);
  72. outln("(Label)");
  73. print_indent(indent + 2);
  74. outln("\"{}\"", m_label);
  75. print_indent(indent + 1);
  76. outln("(Labelled item)");
  77. m_labelled_item->dump(indent + 2);
  78. }
  79. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  80. Value FunctionExpression::instantiate_ordinary_function_expression(VM& vm, DeprecatedFlyString given_name) const
  81. {
  82. auto& realm = *vm.current_realm();
  83. if (given_name.is_empty())
  84. given_name = "";
  85. auto has_own_name = !name().is_empty();
  86. auto const used_name = has_own_name ? name() : given_name.view();
  87. auto environment = NonnullGCPtr { *vm.running_execution_context().lexical_environment };
  88. if (has_own_name) {
  89. VERIFY(environment);
  90. environment = new_declarative_environment(*environment);
  91. MUST(environment->create_immutable_binding(vm, name(), false));
  92. }
  93. auto private_environment = vm.running_execution_context().private_environment;
  94. auto closure = ECMAScriptFunctionObject::create(realm, used_name, source_text(), body(), parameters(), function_length(), local_variables_names(), environment, private_environment, kind(), is_strict_mode(), uses_this(), might_need_arguments_object(), contains_direct_call_to_eval(), is_arrow_function());
  95. // FIXME: 6. Perform SetFunctionName(closure, name).
  96. // FIXME: 7. Perform MakeConstructor(closure).
  97. if (has_own_name)
  98. MUST(environment->initialize_binding(vm, name(), closure, Environment::InitializeBindingHint::Normal));
  99. return closure;
  100. }
  101. Optional<ByteString> CallExpression::expression_string() const
  102. {
  103. if (is<Identifier>(*m_callee))
  104. return static_cast<Identifier const&>(*m_callee).string();
  105. if (is<MemberExpression>(*m_callee))
  106. return static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  107. return {};
  108. }
  109. static ThrowCompletionOr<ClassElementName> class_key_to_property_name(VM& vm, Expression const& key)
  110. {
  111. if (is<PrivateIdentifier>(key)) {
  112. auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
  113. auto private_environment = vm.running_execution_context().private_environment;
  114. VERIFY(private_environment);
  115. return ClassElementName { private_environment->resolve_private_identifier(private_identifier.string()) };
  116. }
  117. auto prop_key = TRY(vm.execute_ast_node(key));
  118. if (prop_key.is_object())
  119. prop_key = TRY(prop_key.to_primitive(vm, Value::PreferredType::String));
  120. auto property_key = TRY(PropertyKey::from_value(vm, prop_key));
  121. return ClassElementName { property_key };
  122. }
  123. // 15.4.5 Runtime Semantics: MethodDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-methoddefinitionevaluation
  124. ThrowCompletionOr<ClassElement::ClassValue> ClassMethod::class_element_evaluation(VM& vm, Object& target) const
  125. {
  126. auto property_key_or_private_name = TRY(class_key_to_property_name(vm, *m_key));
  127. auto method_value = TRY(vm.execute_ast_node(*m_function));
  128. auto function_handle = make_handle(&method_value.as_function());
  129. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  130. method_function.make_method(target);
  131. auto set_function_name = [&](ByteString prefix = "") {
  132. auto name = property_key_or_private_name.visit(
  133. [&](PropertyKey const& property_key) -> ByteString {
  134. if (property_key.is_symbol()) {
  135. auto description = property_key.as_symbol()->description();
  136. if (!description.has_value() || description->is_empty())
  137. return "";
  138. return ByteString::formatted("[{}]", *description);
  139. } else {
  140. return property_key.to_string();
  141. }
  142. },
  143. [&](PrivateName const& private_name) -> ByteString {
  144. return private_name.description;
  145. });
  146. update_function_name(method_value, ByteString::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", name));
  147. };
  148. if (property_key_or_private_name.has<PropertyKey>()) {
  149. auto& property_key = property_key_or_private_name.get<PropertyKey>();
  150. switch (kind()) {
  151. case ClassMethod::Kind::Method:
  152. set_function_name();
  153. TRY(target.define_property_or_throw(property_key, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  154. break;
  155. case ClassMethod::Kind::Getter:
  156. set_function_name("get");
  157. TRY(target.define_property_or_throw(property_key, { .get = &method_function, .enumerable = true, .configurable = true }));
  158. break;
  159. case ClassMethod::Kind::Setter:
  160. set_function_name("set");
  161. TRY(target.define_property_or_throw(property_key, { .set = &method_function, .enumerable = true, .configurable = true }));
  162. break;
  163. default:
  164. VERIFY_NOT_REACHED();
  165. }
  166. return ClassValue { normal_completion({}) };
  167. } else {
  168. auto& private_name = property_key_or_private_name.get<PrivateName>();
  169. switch (kind()) {
  170. case Kind::Method:
  171. set_function_name();
  172. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Method, method_value } };
  173. case Kind::Getter:
  174. set_function_name("get");
  175. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Value(Accessor::create(vm, &method_function, nullptr)) } };
  176. case Kind::Setter:
  177. set_function_name("set");
  178. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Value(Accessor::create(vm, nullptr, &method_function)) } };
  179. default:
  180. VERIFY_NOT_REACHED();
  181. }
  182. }
  183. }
  184. void ClassFieldInitializerStatement::dump(int) const
  185. {
  186. // This should not be dumped as it is never part of an actual AST.
  187. VERIFY_NOT_REACHED();
  188. }
  189. // 15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classfielddefinitionevaluation
  190. ThrowCompletionOr<ClassElement::ClassValue> ClassField::class_element_evaluation(VM& vm, Object& target) const
  191. {
  192. auto& realm = *vm.current_realm();
  193. auto property_key_or_private_name = TRY(class_key_to_property_name(vm, *m_key));
  194. Handle<ECMAScriptFunctionObject> initializer {};
  195. if (m_initializer) {
  196. auto copy_initializer = m_initializer;
  197. auto name = property_key_or_private_name.visit(
  198. [&](PropertyKey const& property_key) -> ByteString {
  199. return property_key.is_number() ? property_key.to_string() : property_key.to_string_or_symbol().to_display_string();
  200. },
  201. [&](PrivateName const& private_name) -> ByteString {
  202. return private_name.description;
  203. });
  204. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  205. auto function_code = create_ast_node<ClassFieldInitializerStatement>(m_initializer->source_range(), copy_initializer.release_nonnull(), name);
  206. initializer = make_handle(*ECMAScriptFunctionObject::create(realm, "field", ByteString::empty(), *function_code, {}, 0, {}, vm.lexical_environment(), vm.running_execution_context().private_environment, FunctionKind::Normal, true, UsesThis::Yes, false, m_contains_direct_call_to_eval, false, property_key_or_private_name));
  207. initializer->make_method(target);
  208. }
  209. return ClassValue {
  210. ClassFieldDefinition {
  211. move(property_key_or_private_name),
  212. move(initializer),
  213. }
  214. };
  215. }
  216. static Optional<DeprecatedFlyString> nullopt_or_private_identifier_description(Expression const& expression)
  217. {
  218. if (is<PrivateIdentifier>(expression))
  219. return static_cast<PrivateIdentifier const&>(expression).string();
  220. return {};
  221. }
  222. Optional<DeprecatedFlyString> ClassField::private_bound_identifier() const
  223. {
  224. return nullopt_or_private_identifier_description(*m_key);
  225. }
  226. Optional<DeprecatedFlyString> ClassMethod::private_bound_identifier() const
  227. {
  228. return nullopt_or_private_identifier_description(*m_key);
  229. }
  230. // 15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classstaticblockdefinitionevaluation
  231. ThrowCompletionOr<ClassElement::ClassValue> StaticInitializer::class_element_evaluation(VM& vm, Object& home_object) const
  232. {
  233. auto& realm = *vm.current_realm();
  234. // 1. Let lex be the running execution context's LexicalEnvironment.
  235. auto lexical_environment = vm.running_execution_context().lexical_environment;
  236. // 2. Let privateEnv be the running execution context's PrivateEnvironment.
  237. auto private_environment = vm.running_execution_context().private_environment;
  238. // 3. Let sourceText be the empty sequence of Unicode code points.
  239. // 4. Let formalParameters be an instance of the production FormalParameters : [empty] .
  240. // 5. Let bodyFunction be OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateEnv).
  241. // Note: The function bodyFunction is never directly accessible to ECMAScript code.
  242. auto body_function = ECMAScriptFunctionObject::create(realm, ByteString::empty(), ByteString::empty(), *m_function_body, {}, 0, m_function_body->local_variables_names(), lexical_environment, private_environment, FunctionKind::Normal, true, UsesThis::Yes, false, m_contains_direct_call_to_eval, false);
  243. // 6. Perform MakeMethod(bodyFunction, homeObject).
  244. body_function->make_method(home_object);
  245. // 7. Return the ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }.
  246. return ClassValue { normal_completion(body_function) };
  247. }
  248. ThrowCompletionOr<ECMAScriptFunctionObject*> ClassExpression::create_class_constructor(VM& vm, Environment* class_environment, Environment* environment, Value super_class, Optional<DeprecatedFlyString> const& binding_name, DeprecatedFlyString const& class_name) const
  249. {
  250. auto& realm = *vm.current_realm();
  251. // We might not set the lexical environment but we always want to restore it eventually.
  252. ArmedScopeGuard restore_environment = [&] {
  253. vm.running_execution_context().lexical_environment = environment;
  254. };
  255. auto outer_private_environment = vm.running_execution_context().private_environment;
  256. auto class_private_environment = new_private_environment(vm, outer_private_environment);
  257. auto proto_parent = GCPtr { realm.intrinsics().object_prototype() };
  258. auto constructor_parent = realm.intrinsics().function_prototype();
  259. for (auto const& element : m_elements) {
  260. auto opt_private_name = element->private_bound_identifier();
  261. if (opt_private_name.has_value())
  262. class_private_environment->add_private_name({}, opt_private_name.release_value());
  263. }
  264. if (!m_super_class.is_null()) {
  265. if (super_class.is_null()) {
  266. proto_parent = nullptr;
  267. } else if (!super_class.is_constructor()) {
  268. return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects());
  269. } else {
  270. auto super_class_prototype = TRY(super_class.get(vm, vm.names.prototype));
  271. if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
  272. return vm.throw_completion<TypeError>(ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects());
  273. if (super_class_prototype.is_null())
  274. proto_parent = nullptr;
  275. else
  276. proto_parent = super_class_prototype.as_object();
  277. constructor_parent = super_class.as_object();
  278. }
  279. }
  280. auto prototype = Object::create_prototype(realm, proto_parent);
  281. VERIFY(prototype);
  282. vm.running_execution_context().lexical_environment = class_environment;
  283. vm.running_execution_context().private_environment = class_private_environment;
  284. ScopeGuard restore_private_environment = [&] {
  285. vm.running_execution_context().private_environment = outer_private_environment;
  286. };
  287. // FIXME: Step 14.a is done in the parser. By using a synthetic super(...args) which does not call @@iterator of %Array.prototype%
  288. auto const& constructor = *m_constructor;
  289. auto class_constructor = ECMAScriptFunctionObject::create(
  290. realm,
  291. constructor.name(),
  292. constructor.source_text(),
  293. constructor.body(),
  294. constructor.parameters(),
  295. constructor.function_length(),
  296. constructor.local_variables_names(),
  297. vm.lexical_environment(),
  298. vm.running_execution_context().private_environment,
  299. constructor.kind(),
  300. constructor.is_strict_mode(),
  301. UsesThis::Yes,
  302. constructor.might_need_arguments_object(),
  303. constructor.contains_direct_call_to_eval(),
  304. constructor.is_arrow_function());
  305. class_constructor->set_name(class_name);
  306. class_constructor->set_home_object(prototype);
  307. class_constructor->set_is_class_constructor();
  308. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  309. TRY(class_constructor->internal_set_prototype_of(constructor_parent));
  310. if (!m_super_class.is_null())
  311. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  312. prototype->define_direct_property(vm.names.constructor, class_constructor, Attribute::Writable | Attribute::Configurable);
  313. using StaticElement = Variant<ClassFieldDefinition, Handle<ECMAScriptFunctionObject>>;
  314. ConservativeVector<PrivateElement> static_private_methods(vm.heap());
  315. ConservativeVector<PrivateElement> instance_private_methods(vm.heap());
  316. Vector<ClassFieldDefinition> instance_fields;
  317. Vector<StaticElement> static_elements;
  318. for (auto const& element : m_elements) {
  319. // Note: All ClassElementEvaluation start with evaluating the name (or we fake it).
  320. auto element_value = TRY(element->class_element_evaluation(vm, element->is_static() ? *class_constructor : *prototype));
  321. if (element_value.has<PrivateElement>()) {
  322. auto& container = element->is_static() ? static_private_methods : instance_private_methods;
  323. auto& private_element = element_value.get<PrivateElement>();
  324. auto added_to_existing = false;
  325. // FIXME: We can skip this loop in most cases.
  326. for (auto& existing : container) {
  327. if (existing.key == private_element.key) {
  328. VERIFY(existing.kind == PrivateElement::Kind::Accessor);
  329. VERIFY(private_element.kind == PrivateElement::Kind::Accessor);
  330. auto& accessor = private_element.value.as_accessor();
  331. if (!accessor.getter())
  332. existing.value.as_accessor().set_setter(accessor.setter());
  333. else
  334. existing.value.as_accessor().set_getter(accessor.getter());
  335. added_to_existing = true;
  336. }
  337. }
  338. if (!added_to_existing)
  339. container.append(move(element_value.get<PrivateElement>()));
  340. } else if (auto* class_field_definition_ptr = element_value.get_pointer<ClassFieldDefinition>()) {
  341. if (element->is_static())
  342. static_elements.append(move(*class_field_definition_ptr));
  343. else
  344. instance_fields.append(move(*class_field_definition_ptr));
  345. } else if (element->class_element_kind() == ClassElement::ElementKind::StaticInitializer) {
  346. // We use Completion to hold the ClassStaticBlockDefinition Record.
  347. VERIFY(element_value.has<Completion>() && element_value.get<Completion>().value().has_value());
  348. auto& element_object = element_value.get<Completion>().value()->as_object();
  349. VERIFY(is<ECMAScriptFunctionObject>(element_object));
  350. static_elements.append(make_handle(static_cast<ECMAScriptFunctionObject*>(&element_object)));
  351. }
  352. }
  353. vm.running_execution_context().lexical_environment = environment;
  354. restore_environment.disarm();
  355. if (binding_name.has_value())
  356. MUST(class_environment->initialize_binding(vm, binding_name.value(), class_constructor, Environment::InitializeBindingHint::Normal));
  357. for (auto& field : instance_fields)
  358. class_constructor->add_field(field);
  359. for (auto& private_method : instance_private_methods)
  360. class_constructor->add_private_method(private_method);
  361. for (auto& method : static_private_methods)
  362. TRY(class_constructor->private_method_or_accessor_add(move(method)));
  363. for (auto& element : static_elements) {
  364. TRY(element.visit(
  365. [&](ClassFieldDefinition& field) -> ThrowCompletionOr<void> {
  366. return TRY(class_constructor->define_field(field));
  367. },
  368. [&](Handle<ECMAScriptFunctionObject> static_block_function) -> ThrowCompletionOr<void> {
  369. VERIFY(!static_block_function.is_null());
  370. // We discard any value returned here.
  371. TRY(call(vm, *static_block_function.cell(), class_constructor));
  372. return {};
  373. }));
  374. }
  375. class_constructor->set_source_text(source_text());
  376. return { class_constructor };
  377. }
  378. ThrowCompletionOr<ECMAScriptFunctionObject*> ClassExpression::class_definition_evaluation(VM& vm, Optional<DeprecatedFlyString> const& binding_name, DeprecatedFlyString const& class_name) const
  379. {
  380. auto* environment = vm.lexical_environment();
  381. VERIFY(environment);
  382. auto class_environment = new_declarative_environment(*environment);
  383. Value super_class;
  384. if (binding_name.has_value())
  385. MUST(class_environment->create_immutable_binding(vm, binding_name.value(), true));
  386. if (!m_super_class.is_null()) {
  387. vm.running_execution_context().lexical_environment = class_environment;
  388. super_class = TRY(vm.execute_ast_node(*m_super_class));
  389. vm.running_execution_context().lexical_environment = environment;
  390. }
  391. return create_class_constructor(vm, class_environment, environment, super_class, binding_name, class_name);
  392. }
  393. void ASTNode::dump(int indent) const
  394. {
  395. print_indent(indent);
  396. outln("{}", class_name());
  397. }
  398. void ScopeNode::dump(int indent) const
  399. {
  400. ASTNode::dump(indent);
  401. if (!m_children.is_empty()) {
  402. print_indent(indent + 1);
  403. outln("(Children)");
  404. for (auto& child : children())
  405. child->dump(indent + 2);
  406. }
  407. }
  408. void BinaryExpression::dump(int indent) const
  409. {
  410. char const* op_string = nullptr;
  411. switch (m_op) {
  412. case BinaryOp::Addition:
  413. op_string = "+";
  414. break;
  415. case BinaryOp::Subtraction:
  416. op_string = "-";
  417. break;
  418. case BinaryOp::Multiplication:
  419. op_string = "*";
  420. break;
  421. case BinaryOp::Division:
  422. op_string = "/";
  423. break;
  424. case BinaryOp::Modulo:
  425. op_string = "%";
  426. break;
  427. case BinaryOp::Exponentiation:
  428. op_string = "**";
  429. break;
  430. case BinaryOp::StrictlyEquals:
  431. op_string = "===";
  432. break;
  433. case BinaryOp::StrictlyInequals:
  434. op_string = "!==";
  435. break;
  436. case BinaryOp::LooselyEquals:
  437. op_string = "==";
  438. break;
  439. case BinaryOp::LooselyInequals:
  440. op_string = "!=";
  441. break;
  442. case BinaryOp::GreaterThan:
  443. op_string = ">";
  444. break;
  445. case BinaryOp::GreaterThanEquals:
  446. op_string = ">=";
  447. break;
  448. case BinaryOp::LessThan:
  449. op_string = "<";
  450. break;
  451. case BinaryOp::LessThanEquals:
  452. op_string = "<=";
  453. break;
  454. case BinaryOp::BitwiseAnd:
  455. op_string = "&";
  456. break;
  457. case BinaryOp::BitwiseOr:
  458. op_string = "|";
  459. break;
  460. case BinaryOp::BitwiseXor:
  461. op_string = "^";
  462. break;
  463. case BinaryOp::LeftShift:
  464. op_string = "<<";
  465. break;
  466. case BinaryOp::RightShift:
  467. op_string = ">>";
  468. break;
  469. case BinaryOp::UnsignedRightShift:
  470. op_string = ">>>";
  471. break;
  472. case BinaryOp::In:
  473. op_string = "in";
  474. break;
  475. case BinaryOp::InstanceOf:
  476. op_string = "instanceof";
  477. break;
  478. }
  479. print_indent(indent);
  480. outln("{}", class_name());
  481. m_lhs->dump(indent + 1);
  482. print_indent(indent + 1);
  483. outln("{}", op_string);
  484. m_rhs->dump(indent + 1);
  485. }
  486. void LogicalExpression::dump(int indent) const
  487. {
  488. char const* op_string = nullptr;
  489. switch (m_op) {
  490. case LogicalOp::And:
  491. op_string = "&&";
  492. break;
  493. case LogicalOp::Or:
  494. op_string = "||";
  495. break;
  496. case LogicalOp::NullishCoalescing:
  497. op_string = "??";
  498. break;
  499. }
  500. print_indent(indent);
  501. outln("{}", class_name());
  502. m_lhs->dump(indent + 1);
  503. print_indent(indent + 1);
  504. outln("{}", op_string);
  505. m_rhs->dump(indent + 1);
  506. }
  507. void UnaryExpression::dump(int indent) const
  508. {
  509. char const* op_string = nullptr;
  510. switch (m_op) {
  511. case UnaryOp::BitwiseNot:
  512. op_string = "~";
  513. break;
  514. case UnaryOp::Not:
  515. op_string = "!";
  516. break;
  517. case UnaryOp::Plus:
  518. op_string = "+";
  519. break;
  520. case UnaryOp::Minus:
  521. op_string = "-";
  522. break;
  523. case UnaryOp::Typeof:
  524. op_string = "typeof ";
  525. break;
  526. case UnaryOp::Void:
  527. op_string = "void ";
  528. break;
  529. case UnaryOp::Delete:
  530. op_string = "delete ";
  531. break;
  532. }
  533. print_indent(indent);
  534. outln("{}", class_name());
  535. print_indent(indent + 1);
  536. outln("{}", op_string);
  537. m_lhs->dump(indent + 1);
  538. }
  539. void CallExpression::dump(int indent) const
  540. {
  541. print_indent(indent);
  542. if (is<NewExpression>(*this))
  543. outln("CallExpression [new]");
  544. else
  545. outln("CallExpression");
  546. m_callee->dump(indent + 1);
  547. for (auto& argument : arguments())
  548. argument.value->dump(indent + 1);
  549. }
  550. void SuperCall::dump(int indent) const
  551. {
  552. print_indent(indent);
  553. outln("SuperCall");
  554. for (auto& argument : m_arguments)
  555. argument.value->dump(indent + 1);
  556. }
  557. void ClassDeclaration::dump(int indent) const
  558. {
  559. ASTNode::dump(indent);
  560. m_class_expression->dump(indent + 1);
  561. }
  562. ThrowCompletionOr<void> ClassDeclaration::for_each_bound_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  563. {
  564. if (!m_class_expression->m_name)
  565. return {};
  566. return callback(*m_class_expression->m_name);
  567. }
  568. void ClassExpression::dump(int indent) const
  569. {
  570. print_indent(indent);
  571. outln("ClassExpression: \"{}\"", name());
  572. print_indent(indent);
  573. outln("(Constructor)");
  574. m_constructor->dump(indent + 1);
  575. if (!m_super_class.is_null()) {
  576. print_indent(indent);
  577. outln("(Super Class)");
  578. m_super_class->dump(indent + 1);
  579. }
  580. print_indent(indent);
  581. outln("(Elements)");
  582. for (auto& method : m_elements)
  583. method->dump(indent + 1);
  584. }
  585. void ClassMethod::dump(int indent) const
  586. {
  587. ASTNode::dump(indent);
  588. print_indent(indent);
  589. outln("(Key)");
  590. m_key->dump(indent + 1);
  591. char const* kind_string = nullptr;
  592. switch (m_kind) {
  593. case Kind::Method:
  594. kind_string = "Method";
  595. break;
  596. case Kind::Getter:
  597. kind_string = "Getter";
  598. break;
  599. case Kind::Setter:
  600. kind_string = "Setter";
  601. break;
  602. }
  603. print_indent(indent);
  604. outln("Kind: {}", kind_string);
  605. print_indent(indent);
  606. outln("Static: {}", is_static());
  607. print_indent(indent);
  608. outln("(Function)");
  609. m_function->dump(indent + 1);
  610. }
  611. void ClassField::dump(int indent) const
  612. {
  613. ASTNode::dump(indent);
  614. print_indent(indent);
  615. outln("(Key)");
  616. m_key->dump(indent + 1);
  617. print_indent(indent);
  618. outln("Static: {}", is_static());
  619. if (m_initializer) {
  620. print_indent(indent);
  621. outln("(Initializer)");
  622. m_initializer->dump(indent + 1);
  623. }
  624. }
  625. void StaticInitializer::dump(int indent) const
  626. {
  627. ASTNode::dump(indent);
  628. m_function_body->dump(indent + 1);
  629. }
  630. void StringLiteral::dump(int indent) const
  631. {
  632. print_indent(indent);
  633. outln("StringLiteral \"{}\"", m_value);
  634. }
  635. void SuperExpression::dump(int indent) const
  636. {
  637. print_indent(indent);
  638. outln("super");
  639. }
  640. void NumericLiteral::dump(int indent) const
  641. {
  642. print_indent(indent);
  643. outln("NumericLiteral {}", m_value);
  644. }
  645. void BigIntLiteral::dump(int indent) const
  646. {
  647. print_indent(indent);
  648. outln("BigIntLiteral {}", m_value);
  649. }
  650. void BooleanLiteral::dump(int indent) const
  651. {
  652. print_indent(indent);
  653. outln("BooleanLiteral {}", m_value);
  654. }
  655. void NullLiteral::dump(int indent) const
  656. {
  657. print_indent(indent);
  658. outln("null");
  659. }
  660. bool BindingPattern::contains_expression() const
  661. {
  662. for (auto& entry : entries) {
  663. if (entry.name.has<NonnullRefPtr<Expression const>>())
  664. return true;
  665. if (entry.initializer)
  666. return true;
  667. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern const>>(); binding_ptr && (*binding_ptr)->contains_expression())
  668. return true;
  669. }
  670. return false;
  671. }
  672. ThrowCompletionOr<void> BindingPattern::for_each_bound_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  673. {
  674. for (auto const& entry : entries) {
  675. auto const& alias = entry.alias;
  676. if (alias.has<NonnullRefPtr<Identifier const>>()) {
  677. TRY(callback(alias.get<NonnullRefPtr<Identifier const>>()));
  678. } else if (alias.has<NonnullRefPtr<BindingPattern const>>()) {
  679. TRY(alias.get<NonnullRefPtr<BindingPattern const>>()->for_each_bound_identifier(forward<decltype(callback)>(callback)));
  680. } else {
  681. auto const& name = entry.name;
  682. if (name.has<NonnullRefPtr<Identifier const>>())
  683. TRY(callback(name.get<NonnullRefPtr<Identifier const>>()));
  684. }
  685. }
  686. return {};
  687. }
  688. void BindingPattern::dump(int indent) const
  689. {
  690. print_indent(indent);
  691. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  692. for (auto& entry : entries) {
  693. print_indent(indent + 1);
  694. outln("(Property)");
  695. if (kind == Kind::Object) {
  696. print_indent(indent + 2);
  697. outln("(Identifier)");
  698. if (entry.name.has<NonnullRefPtr<Identifier const>>()) {
  699. entry.name.get<NonnullRefPtr<Identifier const>>()->dump(indent + 3);
  700. } else if (entry.name.has<NonnullRefPtr<Expression const>>()) {
  701. entry.name.get<NonnullRefPtr<Expression const>>()->dump(indent + 3);
  702. } else {
  703. VERIFY(entry.name.has<Empty>());
  704. print_indent(indent + 3);
  705. outln("<empty>");
  706. }
  707. } else if (entry.is_elision()) {
  708. print_indent(indent + 2);
  709. outln("(Elision)");
  710. continue;
  711. }
  712. print_indent(indent + 2);
  713. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  714. if (entry.alias.has<NonnullRefPtr<Identifier const>>()) {
  715. entry.alias.get<NonnullRefPtr<Identifier const>>()->dump(indent + 3);
  716. } else if (entry.alias.has<NonnullRefPtr<BindingPattern const>>()) {
  717. entry.alias.get<NonnullRefPtr<BindingPattern const>>()->dump(indent + 3);
  718. } else if (entry.alias.has<NonnullRefPtr<MemberExpression const>>()) {
  719. entry.alias.get<NonnullRefPtr<MemberExpression const>>()->dump(indent + 3);
  720. } else {
  721. print_indent(indent + 3);
  722. outln("<empty>");
  723. }
  724. if (entry.initializer) {
  725. print_indent(indent + 2);
  726. outln("(Initializer)");
  727. entry.initializer->dump(indent + 3);
  728. }
  729. }
  730. }
  731. void FunctionNode::dump(int indent, ByteString const& class_name) const
  732. {
  733. print_indent(indent);
  734. auto is_async = m_kind == FunctionKind::Async || m_kind == FunctionKind::AsyncGenerator;
  735. auto is_generator = m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator;
  736. outln("{}{}{} '{}'", class_name, is_async ? " async" : "", is_generator ? "*" : "", name());
  737. if (m_contains_direct_call_to_eval) {
  738. print_indent(indent + 1);
  739. outln("\033[31;1m(direct eval)\033[0m");
  740. }
  741. if (!m_parameters.is_empty()) {
  742. print_indent(indent + 1);
  743. outln("(Parameters)");
  744. for (auto& parameter : m_parameters) {
  745. parameter.binding.visit(
  746. [&](Identifier const& identifier) {
  747. if (parameter.is_rest) {
  748. print_indent(indent + 2);
  749. out("...");
  750. identifier.dump(0);
  751. } else {
  752. identifier.dump(indent + 2);
  753. }
  754. },
  755. [&](BindingPattern const& pattern) {
  756. pattern.dump(indent + 2);
  757. });
  758. if (parameter.default_value)
  759. parameter.default_value->dump(indent + 3);
  760. }
  761. }
  762. print_indent(indent + 1);
  763. outln("(Body)");
  764. body().dump(indent + 2);
  765. }
  766. void FunctionDeclaration::dump(int indent) const
  767. {
  768. FunctionNode::dump(indent, class_name());
  769. }
  770. ThrowCompletionOr<void> FunctionDeclaration::for_each_bound_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  771. {
  772. if (!m_name)
  773. return {};
  774. return callback(*m_name);
  775. }
  776. void FunctionExpression::dump(int indent) const
  777. {
  778. FunctionNode::dump(indent, class_name());
  779. }
  780. void YieldExpression::dump(int indent) const
  781. {
  782. ASTNode::dump(indent);
  783. if (argument())
  784. argument()->dump(indent + 1);
  785. }
  786. void AwaitExpression::dump(int indent) const
  787. {
  788. ASTNode::dump(indent);
  789. m_argument->dump(indent + 1);
  790. }
  791. void ReturnStatement::dump(int indent) const
  792. {
  793. ASTNode::dump(indent);
  794. if (argument())
  795. argument()->dump(indent + 1);
  796. }
  797. void IfStatement::dump(int indent) const
  798. {
  799. ASTNode::dump(indent);
  800. print_indent(indent);
  801. outln("If");
  802. predicate().dump(indent + 1);
  803. consequent().dump(indent + 1);
  804. if (alternate()) {
  805. print_indent(indent);
  806. outln("Else");
  807. alternate()->dump(indent + 1);
  808. }
  809. }
  810. void WhileStatement::dump(int indent) const
  811. {
  812. ASTNode::dump(indent);
  813. print_indent(indent);
  814. outln("While");
  815. test().dump(indent + 1);
  816. body().dump(indent + 1);
  817. }
  818. void WithStatement::dump(int indent) const
  819. {
  820. ASTNode::dump(indent);
  821. print_indent(indent + 1);
  822. outln("Object");
  823. object().dump(indent + 2);
  824. print_indent(indent + 1);
  825. outln("Body");
  826. body().dump(indent + 2);
  827. }
  828. void DoWhileStatement::dump(int indent) const
  829. {
  830. ASTNode::dump(indent);
  831. print_indent(indent);
  832. outln("DoWhile");
  833. test().dump(indent + 1);
  834. body().dump(indent + 1);
  835. }
  836. void ForStatement::dump(int indent) const
  837. {
  838. ASTNode::dump(indent);
  839. print_indent(indent);
  840. outln("For");
  841. if (init())
  842. init()->dump(indent + 1);
  843. if (test())
  844. test()->dump(indent + 1);
  845. if (update())
  846. update()->dump(indent + 1);
  847. body().dump(indent + 1);
  848. }
  849. void ForInStatement::dump(int indent) const
  850. {
  851. ASTNode::dump(indent);
  852. print_indent(indent);
  853. outln("ForIn");
  854. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  855. rhs().dump(indent + 1);
  856. body().dump(indent + 1);
  857. }
  858. void ForOfStatement::dump(int indent) const
  859. {
  860. ASTNode::dump(indent);
  861. print_indent(indent);
  862. outln("ForOf");
  863. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  864. rhs().dump(indent + 1);
  865. body().dump(indent + 1);
  866. }
  867. void ForAwaitOfStatement::dump(int indent) const
  868. {
  869. ASTNode::dump(indent);
  870. print_indent(indent);
  871. outln("ForAwaitOf");
  872. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  873. m_rhs->dump(indent + 1);
  874. m_body->dump(indent + 1);
  875. }
  876. void Identifier::dump(int indent) const
  877. {
  878. print_indent(indent);
  879. if (is_local()) {
  880. outln("Identifier \"{}\" is_local=(true) index=({})", m_string, m_local_variable_index);
  881. } else if (is_global()) {
  882. outln("Identifier \"{}\" is_global=(true)", m_string);
  883. } else {
  884. outln("Identifier \"{}\"", m_string);
  885. }
  886. }
  887. void PrivateIdentifier::dump(int indent) const
  888. {
  889. print_indent(indent);
  890. outln("PrivateIdentifier \"{}\"", m_string);
  891. }
  892. void SpreadExpression::dump(int indent) const
  893. {
  894. ASTNode::dump(indent);
  895. m_target->dump(indent + 1);
  896. }
  897. void ThisExpression::dump(int indent) const
  898. {
  899. ASTNode::dump(indent);
  900. }
  901. void AssignmentExpression::dump(int indent) const
  902. {
  903. char const* op_string = nullptr;
  904. switch (m_op) {
  905. case AssignmentOp::Assignment:
  906. op_string = "=";
  907. break;
  908. case AssignmentOp::AdditionAssignment:
  909. op_string = "+=";
  910. break;
  911. case AssignmentOp::SubtractionAssignment:
  912. op_string = "-=";
  913. break;
  914. case AssignmentOp::MultiplicationAssignment:
  915. op_string = "*=";
  916. break;
  917. case AssignmentOp::DivisionAssignment:
  918. op_string = "/=";
  919. break;
  920. case AssignmentOp::ModuloAssignment:
  921. op_string = "%=";
  922. break;
  923. case AssignmentOp::ExponentiationAssignment:
  924. op_string = "**=";
  925. break;
  926. case AssignmentOp::BitwiseAndAssignment:
  927. op_string = "&=";
  928. break;
  929. case AssignmentOp::BitwiseOrAssignment:
  930. op_string = "|=";
  931. break;
  932. case AssignmentOp::BitwiseXorAssignment:
  933. op_string = "^=";
  934. break;
  935. case AssignmentOp::LeftShiftAssignment:
  936. op_string = "<<=";
  937. break;
  938. case AssignmentOp::RightShiftAssignment:
  939. op_string = ">>=";
  940. break;
  941. case AssignmentOp::UnsignedRightShiftAssignment:
  942. op_string = ">>>=";
  943. break;
  944. case AssignmentOp::AndAssignment:
  945. op_string = "&&=";
  946. break;
  947. case AssignmentOp::OrAssignment:
  948. op_string = "||=";
  949. break;
  950. case AssignmentOp::NullishAssignment:
  951. op_string = "\?\?=";
  952. break;
  953. }
  954. ASTNode::dump(indent);
  955. print_indent(indent + 1);
  956. outln("{}", op_string);
  957. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  958. m_rhs->dump(indent + 1);
  959. }
  960. void UpdateExpression::dump(int indent) const
  961. {
  962. char const* op_string = nullptr;
  963. switch (m_op) {
  964. case UpdateOp::Increment:
  965. op_string = "++";
  966. break;
  967. case UpdateOp::Decrement:
  968. op_string = "--";
  969. break;
  970. }
  971. ASTNode::dump(indent);
  972. if (m_prefixed) {
  973. print_indent(indent + 1);
  974. outln("{}", op_string);
  975. }
  976. m_argument->dump(indent + 1);
  977. if (!m_prefixed) {
  978. print_indent(indent + 1);
  979. outln("{}", op_string);
  980. }
  981. }
  982. ThrowCompletionOr<void> VariableDeclaration::for_each_bound_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  983. {
  984. for (auto const& entry : declarations()) {
  985. TRY(entry->target().visit(
  986. [&](NonnullRefPtr<Identifier const> const& id) {
  987. return callback(id);
  988. },
  989. [&](NonnullRefPtr<BindingPattern const> const& binding) {
  990. return binding->for_each_bound_identifier([&](auto const& id) {
  991. return callback(id);
  992. });
  993. }));
  994. }
  995. return {};
  996. }
  997. void VariableDeclaration::dump(int indent) const
  998. {
  999. char const* declaration_kind_string = nullptr;
  1000. switch (m_declaration_kind) {
  1001. case DeclarationKind::Let:
  1002. declaration_kind_string = "Let";
  1003. break;
  1004. case DeclarationKind::Var:
  1005. declaration_kind_string = "Var";
  1006. break;
  1007. case DeclarationKind::Const:
  1008. declaration_kind_string = "Const";
  1009. break;
  1010. }
  1011. ASTNode::dump(indent);
  1012. print_indent(indent + 1);
  1013. outln("{}", declaration_kind_string);
  1014. for (auto& declarator : m_declarations)
  1015. declarator->dump(indent + 1);
  1016. }
  1017. ThrowCompletionOr<void> UsingDeclaration::for_each_bound_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  1018. {
  1019. for (auto const& entry : m_declarations) {
  1020. VERIFY(entry->target().has<NonnullRefPtr<Identifier const>>());
  1021. TRY(callback(entry->target().get<NonnullRefPtr<Identifier const>>()));
  1022. }
  1023. return {};
  1024. }
  1025. void UsingDeclaration::dump(int indent) const
  1026. {
  1027. ASTNode::dump(indent);
  1028. print_indent(indent + 1);
  1029. for (auto& declarator : m_declarations)
  1030. declarator->dump(indent + 1);
  1031. }
  1032. void VariableDeclarator::dump(int indent) const
  1033. {
  1034. ASTNode::dump(indent);
  1035. m_target.visit([indent](auto const& value) { value->dump(indent + 1); });
  1036. if (m_init)
  1037. m_init->dump(indent + 1);
  1038. }
  1039. void ObjectProperty::dump(int indent) const
  1040. {
  1041. ASTNode::dump(indent);
  1042. if (m_property_type == Type::Spread) {
  1043. print_indent(indent + 1);
  1044. outln("...Spreading");
  1045. m_key->dump(indent + 1);
  1046. } else {
  1047. m_key->dump(indent + 1);
  1048. m_value->dump(indent + 1);
  1049. }
  1050. }
  1051. void ObjectExpression::dump(int indent) const
  1052. {
  1053. ASTNode::dump(indent);
  1054. for (auto& property : m_properties) {
  1055. property->dump(indent + 1);
  1056. }
  1057. }
  1058. void ExpressionStatement::dump(int indent) const
  1059. {
  1060. ASTNode::dump(indent);
  1061. m_expression->dump(indent + 1);
  1062. }
  1063. void MemberExpression::dump(int indent) const
  1064. {
  1065. print_indent(indent);
  1066. outln("{}(computed={})", class_name(), is_computed());
  1067. m_object->dump(indent + 1);
  1068. m_property->dump(indent + 1);
  1069. }
  1070. ByteString MemberExpression::to_string_approximation() const
  1071. {
  1072. ByteString object_string = "<object>";
  1073. if (is<Identifier>(*m_object))
  1074. object_string = static_cast<Identifier const&>(*m_object).string();
  1075. if (is_computed())
  1076. return ByteString::formatted("{}[<computed>]", object_string);
  1077. if (is<PrivateIdentifier>(*m_property))
  1078. return ByteString::formatted("{}.{}", object_string, verify_cast<PrivateIdentifier>(*m_property).string());
  1079. return ByteString::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  1080. }
  1081. bool MemberExpression::ends_in_private_name() const
  1082. {
  1083. if (is_computed())
  1084. return false;
  1085. if (is<PrivateIdentifier>(*m_property))
  1086. return true;
  1087. if (is<MemberExpression>(*m_property))
  1088. return static_cast<MemberExpression const&>(*m_property).ends_in_private_name();
  1089. return false;
  1090. }
  1091. void OptionalChain::dump(int indent) const
  1092. {
  1093. print_indent(indent);
  1094. outln("{}", class_name());
  1095. m_base->dump(indent + 1);
  1096. for (auto& reference : m_references) {
  1097. reference.visit(
  1098. [&](Call const& call) {
  1099. print_indent(indent + 1);
  1100. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  1101. for (auto& argument : call.arguments)
  1102. argument.value->dump(indent + 2);
  1103. },
  1104. [&](ComputedReference const& ref) {
  1105. print_indent(indent + 1);
  1106. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1107. ref.expression->dump(indent + 2);
  1108. },
  1109. [&](MemberReference const& ref) {
  1110. print_indent(indent + 1);
  1111. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1112. ref.identifier->dump(indent + 2);
  1113. },
  1114. [&](PrivateMemberReference const& ref) {
  1115. print_indent(indent + 1);
  1116. outln("PrivateMemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  1117. ref.private_identifier->dump(indent + 2);
  1118. });
  1119. }
  1120. }
  1121. void MetaProperty::dump(int indent) const
  1122. {
  1123. ByteString name;
  1124. if (m_type == MetaProperty::Type::NewTarget)
  1125. name = "new.target";
  1126. else if (m_type == MetaProperty::Type::ImportMeta)
  1127. name = "import.meta";
  1128. else
  1129. VERIFY_NOT_REACHED();
  1130. print_indent(indent);
  1131. outln("{} {}", class_name(), name);
  1132. }
  1133. void ImportCall::dump(int indent) const
  1134. {
  1135. ASTNode::dump(indent);
  1136. print_indent(indent);
  1137. outln("(Specifier)");
  1138. m_specifier->dump(indent + 1);
  1139. if (m_options) {
  1140. outln("(Options)");
  1141. m_options->dump(indent + 1);
  1142. }
  1143. }
  1144. void RegExpLiteral::dump(int indent) const
  1145. {
  1146. print_indent(indent);
  1147. outln("{} (/{}/{})", class_name(), pattern(), flags());
  1148. }
  1149. void ArrayExpression::dump(int indent) const
  1150. {
  1151. ASTNode::dump(indent);
  1152. for (auto& element : m_elements) {
  1153. if (element) {
  1154. element->dump(indent + 1);
  1155. } else {
  1156. print_indent(indent + 1);
  1157. outln("<empty>");
  1158. }
  1159. }
  1160. }
  1161. void TemplateLiteral::dump(int indent) const
  1162. {
  1163. ASTNode::dump(indent);
  1164. for (auto& expression : m_expressions)
  1165. expression->dump(indent + 1);
  1166. }
  1167. void TaggedTemplateLiteral::dump(int indent) const
  1168. {
  1169. ASTNode::dump(indent);
  1170. print_indent(indent + 1);
  1171. outln("(Tag)");
  1172. m_tag->dump(indent + 2);
  1173. print_indent(indent + 1);
  1174. outln("(Template Literal)");
  1175. m_template_literal->dump(indent + 2);
  1176. }
  1177. void TryStatement::dump(int indent) const
  1178. {
  1179. ASTNode::dump(indent);
  1180. print_indent(indent);
  1181. outln("(Block)");
  1182. block().dump(indent + 1);
  1183. if (handler()) {
  1184. print_indent(indent);
  1185. outln("(Handler)");
  1186. handler()->dump(indent + 1);
  1187. }
  1188. if (finalizer()) {
  1189. print_indent(indent);
  1190. outln("(Finalizer)");
  1191. finalizer()->dump(indent + 1);
  1192. }
  1193. }
  1194. void CatchClause::dump(int indent) const
  1195. {
  1196. print_indent(indent);
  1197. m_parameter.visit(
  1198. [&](DeprecatedFlyString const& parameter) {
  1199. if (parameter.is_empty())
  1200. outln("CatchClause");
  1201. else
  1202. outln("CatchClause ({})", parameter);
  1203. },
  1204. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  1205. outln("CatchClause");
  1206. print_indent(indent);
  1207. outln("(Parameter)");
  1208. pattern->dump(indent + 2);
  1209. });
  1210. body().dump(indent + 1);
  1211. }
  1212. void ThrowStatement::dump(int indent) const
  1213. {
  1214. ASTNode::dump(indent);
  1215. argument().dump(indent + 1);
  1216. }
  1217. void SwitchStatement::dump(int indent) const
  1218. {
  1219. ASTNode::dump(indent);
  1220. m_discriminant->dump(indent + 1);
  1221. for (auto& switch_case : m_cases) {
  1222. switch_case->dump(indent + 1);
  1223. }
  1224. }
  1225. void SwitchCase::dump(int indent) const
  1226. {
  1227. print_indent(indent + 1);
  1228. if (m_test) {
  1229. outln("(Test)");
  1230. m_test->dump(indent + 2);
  1231. } else {
  1232. outln("(Default)");
  1233. }
  1234. print_indent(indent + 1);
  1235. outln("(Consequent)");
  1236. ScopeNode::dump(indent + 2);
  1237. }
  1238. void ConditionalExpression::dump(int indent) const
  1239. {
  1240. ASTNode::dump(indent);
  1241. print_indent(indent + 1);
  1242. outln("(Test)");
  1243. m_test->dump(indent + 2);
  1244. print_indent(indent + 1);
  1245. outln("(Consequent)");
  1246. m_consequent->dump(indent + 2);
  1247. print_indent(indent + 1);
  1248. outln("(Alternate)");
  1249. m_alternate->dump(indent + 2);
  1250. }
  1251. void SequenceExpression::dump(int indent) const
  1252. {
  1253. ASTNode::dump(indent);
  1254. for (auto& expression : m_expressions)
  1255. expression->dump(indent + 1);
  1256. }
  1257. bool ScopeNode::has_non_local_lexical_declarations() const
  1258. {
  1259. bool result = false;
  1260. MUST(for_each_lexically_declared_identifier([&](Identifier const& identifier) {
  1261. if (!identifier.is_local())
  1262. result = true;
  1263. }));
  1264. return result;
  1265. }
  1266. ThrowCompletionOr<void> ScopeNode::for_each_lexically_scoped_declaration(ThrowCompletionOrVoidCallback<Declaration const&>&& callback) const
  1267. {
  1268. for (auto& declaration : m_lexical_declarations)
  1269. TRY(callback(declaration));
  1270. return {};
  1271. }
  1272. ThrowCompletionOr<void> ScopeNode::for_each_lexically_declared_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  1273. {
  1274. for (auto const& declaration : m_lexical_declarations) {
  1275. TRY(declaration->for_each_bound_identifier([&](auto const& identifier) {
  1276. return callback(identifier);
  1277. }));
  1278. }
  1279. return {};
  1280. }
  1281. ThrowCompletionOr<void> ScopeNode::for_each_var_declared_identifier(ThrowCompletionOrVoidCallback<Identifier const&>&& callback) const
  1282. {
  1283. for (auto& declaration : m_var_declarations) {
  1284. TRY(declaration->for_each_bound_identifier([&](auto const& id) {
  1285. return callback(id);
  1286. }));
  1287. }
  1288. return {};
  1289. }
  1290. ThrowCompletionOr<void> ScopeNode::for_each_var_function_declaration_in_reverse_order(ThrowCompletionOrVoidCallback<FunctionDeclaration const&>&& callback) const
  1291. {
  1292. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  1293. auto& declaration = m_var_declarations[i];
  1294. if (is<FunctionDeclaration>(declaration))
  1295. TRY(callback(static_cast<FunctionDeclaration const&>(*declaration)));
  1296. }
  1297. return {};
  1298. }
  1299. ThrowCompletionOr<void> ScopeNode::for_each_var_scoped_variable_declaration(ThrowCompletionOrVoidCallback<VariableDeclaration const&>&& callback) const
  1300. {
  1301. for (auto& declaration : m_var_declarations) {
  1302. if (!is<FunctionDeclaration>(declaration)) {
  1303. VERIFY(is<VariableDeclaration>(declaration));
  1304. TRY(callback(static_cast<VariableDeclaration const&>(*declaration)));
  1305. }
  1306. }
  1307. return {};
  1308. }
  1309. ThrowCompletionOr<void> ScopeNode::for_each_function_hoistable_with_annexB_extension(ThrowCompletionOrVoidCallback<FunctionDeclaration&>&& callback) const
  1310. {
  1311. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  1312. // We need const_cast here since it might have to set a property on function declaration.
  1313. TRY(callback(const_cast<FunctionDeclaration&>(*function)));
  1314. }
  1315. return {};
  1316. }
  1317. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration const> declaration)
  1318. {
  1319. m_lexical_declarations.append(move(declaration));
  1320. }
  1321. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration const> declaration)
  1322. {
  1323. m_var_declarations.append(move(declaration));
  1324. }
  1325. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration const> declaration)
  1326. {
  1327. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  1328. }
  1329. DeprecatedFlyString ExportStatement::local_name_for_default = "*default*";
  1330. static void dump_assert_clauses(ModuleRequest const& request)
  1331. {
  1332. if (!request.attributes.is_empty()) {
  1333. out("[ ");
  1334. for (auto& assertion : request.attributes)
  1335. out("{}: {}, ", assertion.key, assertion.value);
  1336. out(" ]");
  1337. }
  1338. }
  1339. void ExportStatement::dump(int indent) const
  1340. {
  1341. ASTNode::dump(indent);
  1342. print_indent(indent + 1);
  1343. outln("(ExportEntries)");
  1344. auto string_or_null = [](Optional<DeprecatedFlyString> const& string) -> ByteString {
  1345. if (!string.has_value()) {
  1346. return "null";
  1347. }
  1348. return ByteString::formatted("\"{}\"", string);
  1349. };
  1350. for (auto& entry : m_entries) {
  1351. print_indent(indent + 2);
  1352. out("ExportName: {}, ImportName: {}, LocalName: {}, ModuleRequest: ",
  1353. string_or_null(entry.export_name),
  1354. entry.is_module_request() ? string_or_null(entry.local_or_import_name) : "null",
  1355. entry.is_module_request() ? "null" : string_or_null(entry.local_or_import_name));
  1356. if (entry.is_module_request()) {
  1357. out("{}", entry.m_module_request->module_specifier);
  1358. dump_assert_clauses(*entry.m_module_request);
  1359. outln();
  1360. } else {
  1361. outln("null");
  1362. }
  1363. }
  1364. if (m_statement) {
  1365. print_indent(indent + 1);
  1366. outln("(Statement)");
  1367. m_statement->dump(indent + 2);
  1368. }
  1369. }
  1370. void ImportStatement::dump(int indent) const
  1371. {
  1372. ASTNode::dump(indent);
  1373. print_indent(indent + 1);
  1374. if (m_entries.is_empty()) {
  1375. // direct from "module" import
  1376. outln("Entire module '{}'", m_module_request.module_specifier);
  1377. dump_assert_clauses(m_module_request);
  1378. } else {
  1379. outln("(ExportEntries) from {}", m_module_request.module_specifier);
  1380. dump_assert_clauses(m_module_request);
  1381. for (auto& entry : m_entries) {
  1382. print_indent(indent + 2);
  1383. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  1384. }
  1385. }
  1386. }
  1387. bool ExportStatement::has_export(DeprecatedFlyString const& export_name) const
  1388. {
  1389. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  1390. // Make sure that empty exported names does not overlap with anything
  1391. if (entry.kind != ExportEntry::Kind::NamedExport)
  1392. return false;
  1393. return entry.export_name == export_name;
  1394. });
  1395. }
  1396. bool ImportStatement::has_bound_name(DeprecatedFlyString const& name) const
  1397. {
  1398. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  1399. return entry.local_name == name;
  1400. });
  1401. }
  1402. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  1403. void ScopeNode::block_declaration_instantiation(VM& vm, Environment* environment) const
  1404. {
  1405. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  1406. auto& realm = *vm.current_realm();
  1407. VERIFY(environment);
  1408. // 1. Let declarations be the LexicallyScopedDeclarations of code.
  1409. // 2. Let privateEnv be the running execution context's PrivateEnvironment.
  1410. auto private_environment = vm.running_execution_context().private_environment;
  1411. // Note: All the calls here are ! and thus we do not need to TRY this callback.
  1412. // We use MUST to ensure it does not throw and to avoid discarding the returned ThrowCompletionOr<void>.
  1413. // 3. For each element d of declarations, do
  1414. MUST(for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  1415. auto is_constant_declaration = declaration.is_constant_declaration();
  1416. // NOTE: Due to the use of MUST with `create_immutable_binding` and `create_mutable_binding` below,
  1417. // an exception should not result from `for_each_bound_name`.
  1418. // a. For each element dn of the BoundNames of d, do
  1419. MUST(declaration.for_each_bound_identifier([&](auto const& identifier) {
  1420. if (identifier.is_local()) {
  1421. // NOTE: No need to create bindings for local variables as their values are not stored in an environment.
  1422. return;
  1423. }
  1424. auto const& name = identifier.string();
  1425. // i. If IsConstantDeclaration of d is true, then
  1426. if (is_constant_declaration) {
  1427. // 1. Perform ! env.CreateImmutableBinding(dn, true).
  1428. MUST(environment->create_immutable_binding(vm, name, true));
  1429. }
  1430. // ii. Else,
  1431. else {
  1432. // 1. Perform ! env.CreateMutableBinding(dn, false). NOTE: This step is replaced in section B.3.2.6.
  1433. if (!MUST(environment->has_binding(name)))
  1434. MUST(environment->create_mutable_binding(vm, name, false));
  1435. }
  1436. }));
  1437. // b. If d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration, then
  1438. if (is<FunctionDeclaration>(declaration)) {
  1439. // i. Let fn be the sole element of the BoundNames of d.
  1440. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  1441. // ii. Let fo be InstantiateFunctionObject of d with arguments env and privateEnv.
  1442. auto function = ECMAScriptFunctionObject::create(realm, function_declaration.name(), function_declaration.source_text(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), function_declaration.local_variables_names(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.uses_this(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  1443. // iii. Perform ! env.InitializeBinding(fn, fo). NOTE: This step is replaced in section B.3.2.6.
  1444. if (function_declaration.name_identifier()->is_local()) {
  1445. vm.running_execution_context().local(function_declaration.name_identifier()->local_variable_index()) = function;
  1446. } else {
  1447. VERIFY(is<DeclarativeEnvironment>(*environment));
  1448. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, vm, function_declaration.name(), function);
  1449. }
  1450. }
  1451. }));
  1452. }
  1453. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  1454. ThrowCompletionOr<void> Program::global_declaration_instantiation(VM& vm, GlobalEnvironment& global_environment) const
  1455. {
  1456. auto& realm = *vm.current_realm();
  1457. // 1. Let lexNames be the LexicallyDeclaredNames of script.
  1458. // 2. Let varNames be the VarDeclaredNames of script.
  1459. // 3. For each element name of lexNames, do
  1460. TRY(for_each_lexically_declared_identifier([&](Identifier const& identifier) -> ThrowCompletionOr<void> {
  1461. auto const& name = identifier.string();
  1462. // a. If env.HasVarDeclaration(name) is true, throw a SyntaxError exception.
  1463. if (global_environment.has_var_declaration(name))
  1464. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, name);
  1465. // b. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  1466. if (global_environment.has_lexical_declaration(name))
  1467. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, name);
  1468. // c. Let hasRestrictedGlobal be ? env.HasRestrictedGlobalProperty(name).
  1469. auto has_restricted_global = TRY(global_environment.has_restricted_global_property(name));
  1470. // d. If hasRestrictedGlobal is true, throw a SyntaxError exception.
  1471. if (has_restricted_global)
  1472. return vm.throw_completion<SyntaxError>(ErrorType::RestrictedGlobalProperty, name);
  1473. return {};
  1474. }));
  1475. // 4. For each element name of varNames, do
  1476. TRY(for_each_var_declared_identifier([&](auto const& identifier) -> ThrowCompletionOr<void> {
  1477. // a. If env.HasLexicalDeclaration(name) is true, throw a SyntaxError exception.
  1478. if (global_environment.has_lexical_declaration(identifier.string()))
  1479. return vm.throw_completion<SyntaxError>(ErrorType::TopLevelVariableAlreadyDeclared, identifier.string());
  1480. return {};
  1481. }));
  1482. // 5. Let varDeclarations be the VarScopedDeclarations of script.
  1483. // 6. Let functionsToInitialize be a new empty List.
  1484. Vector<FunctionDeclaration const&> functions_to_initialize;
  1485. // 7. Let declaredFunctionNames be a new empty List.
  1486. HashTable<DeprecatedFlyString> declared_function_names;
  1487. // 8. For each element d of varDeclarations, in reverse List order, do
  1488. TRY(for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) -> ThrowCompletionOr<void> {
  1489. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  1490. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  1491. // Note: This is checked in for_each_var_function_declaration_in_reverse_order.
  1492. // ii. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  1493. // iii. Let fn be the sole element of the BoundNames of d.
  1494. // iv. If fn is not an element of declaredFunctionNames, then
  1495. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  1496. return {};
  1497. // 1. Let fnDefinable be ? env.CanDeclareGlobalFunction(fn).
  1498. auto function_definable = TRY(global_environment.can_declare_global_function(function.name()));
  1499. // 2. If fnDefinable is false, throw a TypeError exception.
  1500. if (!function_definable)
  1501. return vm.throw_completion<TypeError>(ErrorType::CannotDeclareGlobalFunction, function.name());
  1502. // 3. Append fn to declaredFunctionNames.
  1503. // Note: Already done in step iv. above.
  1504. // 4. Insert d as the first element of functionsToInitialize.
  1505. // NOTE: Since prepending is much slower, we just append
  1506. // and iterate in reverse order in step 16 below.
  1507. functions_to_initialize.append(function);
  1508. return {};
  1509. }));
  1510. // 9. Let declaredVarNames be a new empty List.
  1511. HashTable<DeprecatedFlyString> declared_var_names;
  1512. // 10. For each element d of varDeclarations, do
  1513. TRY(for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  1514. // a. If d is a VariableDeclaration, a ForBinding, or a BindingIdentifier, then
  1515. // Note: This is done in for_each_var_scoped_variable_declaration.
  1516. // i. For each String vn of the BoundNames of d, do
  1517. return declaration.for_each_bound_identifier([&](auto const& identifier) -> ThrowCompletionOr<void> {
  1518. auto const& name = identifier.string();
  1519. // 1. If vn is not an element of declaredFunctionNames, then
  1520. if (declared_function_names.contains(name))
  1521. return {};
  1522. // a. Let vnDefinable be ? env.CanDeclareGlobalVar(vn).
  1523. auto var_definable = TRY(global_environment.can_declare_global_var(name));
  1524. // b. If vnDefinable is false, throw a TypeError exception.
  1525. if (!var_definable)
  1526. return vm.throw_completion<TypeError>(ErrorType::CannotDeclareGlobalVariable, name);
  1527. // c. If vn is not an element of declaredVarNames, then
  1528. // i. Append vn to declaredVarNames.
  1529. declared_var_names.set(name);
  1530. return {};
  1531. });
  1532. }));
  1533. // 11. NOTE: No abnormal terminations occur after this algorithm step if the global object is an ordinary object. However, if the global object is a Proxy exotic object it may exhibit behaviours that cause abnormal terminations in some of the following steps.
  1534. // 12. NOTE: Annex B.3.2.2 adds additional steps at this point.
  1535. // 12. Let strict be IsStrict of script.
  1536. // 13. If strict is false, then
  1537. if (!m_is_strict_mode) {
  1538. // a. Let declaredFunctionOrVarNames be the list-concatenation of declaredFunctionNames and declaredVarNames.
  1539. // b. For each FunctionDeclaration f that is directly contained in the StatementList of a Block, CaseClause, or DefaultClause Contained within script, do
  1540. TRY(for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) -> ThrowCompletionOr<void> {
  1541. // i. Let F be StringValue of the BindingIdentifier of f.
  1542. auto function_name = function_declaration.name();
  1543. // ii. If replacing the FunctionDeclaration f with a VariableStatement that has F as a BindingIdentifier would not produce any Early Errors for script, then
  1544. // Note: This step is already performed during parsing and for_each_function_hoistable_with_annexB_extension so this always passes here.
  1545. // 1. If env.HasLexicalDeclaration(F) is false, then
  1546. if (global_environment.has_lexical_declaration(function_name))
  1547. return {};
  1548. // a. Let fnDefinable be ? env.CanDeclareGlobalVar(F).
  1549. auto function_definable = TRY(global_environment.can_declare_global_function(function_name));
  1550. // b. If fnDefinable is true, then
  1551. if (!function_definable)
  1552. return {};
  1553. // i. NOTE: A var binding for F is only instantiated here if it is neither a VarDeclaredName nor the name of another FunctionDeclaration.
  1554. // ii. If declaredFunctionOrVarNames does not contain F, then
  1555. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  1556. // i. Perform ? env.CreateGlobalVarBinding(F, false).
  1557. TRY(global_environment.create_global_var_binding(function_name, false));
  1558. // ii. Append F to declaredFunctionOrVarNames.
  1559. declared_function_names.set(function_name);
  1560. }
  1561. // iii. When the FunctionDeclaration f is evaluated, perform the following steps in place of the FunctionDeclaration Evaluation algorithm provided in 15.2.6:
  1562. // i. Let genv be the running execution context's VariableEnvironment.
  1563. // ii. Let benv be the running execution context's LexicalEnvironment.
  1564. // iii. Let fobj be ! benv.GetBindingValue(F, false).
  1565. // iv. Perform ? genv.SetMutableBinding(F, fobj, false).
  1566. // v. Return unused.
  1567. function_declaration.set_should_do_additional_annexB_steps();
  1568. return {};
  1569. }));
  1570. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  1571. declared_function_names.clear();
  1572. }
  1573. // 13. Let lexDeclarations be the LexicallyScopedDeclarations of script.
  1574. // 14. Let privateEnv be null.
  1575. PrivateEnvironment* private_environment = nullptr;
  1576. // 15. For each element d of lexDeclarations, do
  1577. TRY(for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  1578. // a. NOTE: Lexically declared names are only instantiated here but not initialized.
  1579. // b. For each element dn of the BoundNames of d, do
  1580. return declaration.for_each_bound_identifier([&](auto const& identifier) -> ThrowCompletionOr<void> {
  1581. auto const& name = identifier.string();
  1582. // i. If IsConstantDeclaration of d is true, then
  1583. if (declaration.is_constant_declaration()) {
  1584. // 1. Perform ? env.CreateImmutableBinding(dn, true).
  1585. TRY(global_environment.create_immutable_binding(vm, name, true));
  1586. }
  1587. // ii. Else,
  1588. else {
  1589. // 1. Perform ? env.CreateMutableBinding(dn, false).
  1590. TRY(global_environment.create_mutable_binding(vm, name, false));
  1591. }
  1592. return {};
  1593. });
  1594. }));
  1595. // 16. For each Parse Node f of functionsToInitialize, do
  1596. // NOTE: We iterate in reverse order since we appended the functions
  1597. // instead of prepending. We append because prepending is much slower
  1598. // and we only use the created vector here.
  1599. for (auto& declaration : functions_to_initialize.in_reverse()) {
  1600. // a. Let fn be the sole element of the BoundNames of f.
  1601. // b. Let fo be InstantiateFunctionObject of f with arguments env and privateEnv.
  1602. auto function = ECMAScriptFunctionObject::create(realm, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), declaration.local_variables_names(), &global_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.uses_this(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  1603. // c. Perform ? env.CreateGlobalFunctionBinding(fn, fo, false).
  1604. TRY(global_environment.create_global_function_binding(declaration.name(), function, false));
  1605. }
  1606. // 17. For each String vn of declaredVarNames, do
  1607. for (auto& var_name : declared_var_names) {
  1608. // a. Perform ? env.CreateGlobalVarBinding(vn, false).
  1609. TRY(global_environment.create_global_var_binding(var_name, false));
  1610. }
  1611. // 18. Return unused.
  1612. return {};
  1613. }
  1614. ModuleRequest::ModuleRequest(DeprecatedFlyString module_specifier_, Vector<ImportAttribute> attributes)
  1615. : module_specifier(move(module_specifier_))
  1616. , attributes(move(attributes))
  1617. {
  1618. // Perform step 10.e. from EvaluateImportCall, https://tc39.es/proposal-import-attributes/#sec-evaluate-import-call
  1619. // or step 2. from WithClauseToAttributes, https://tc39.es/proposal-import-attributes/#sec-with-clause-to-attributes
  1620. // e. / 2. Sort assertions by the code point order of the [[Key]] of each element.
  1621. // NOTE: This sorting is observable only in that hosts are prohibited from distinguishing among assertions by the order they occur in.
  1622. quick_sort(this->attributes, [](ImportAttribute const& lhs, ImportAttribute const& rhs) {
  1623. return lhs.key < rhs.key;
  1624. });
  1625. }
  1626. ByteString SourceRange::filename() const
  1627. {
  1628. return code->filename().to_byte_string();
  1629. }
  1630. NonnullRefPtr<CallExpression> CallExpression::create(SourceRange source_range, NonnullRefPtr<Expression const> callee, ReadonlySpan<Argument> arguments, InvocationStyleEnum invocation_style, InsideParenthesesEnum inside_parens)
  1631. {
  1632. return ASTNodeWithTailArray::create<CallExpression>(arguments.size(), move(source_range), move(callee), arguments, invocation_style, inside_parens);
  1633. }
  1634. NonnullRefPtr<NewExpression> NewExpression::create(SourceRange source_range, NonnullRefPtr<Expression const> callee, ReadonlySpan<Argument> arguments, InvocationStyleEnum invocation_style, InsideParenthesesEnum inside_parens)
  1635. {
  1636. return ASTNodeWithTailArray::create<NewExpression>(arguments.size(), move(source_range), move(callee), arguments, invocation_style, inside_parens);
  1637. }
  1638. }