AST.cpp 67 KB

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