AST.cpp 66 KB

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