AST.cpp 66 KB

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