AST.cpp 66 KB

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