AST.cpp 66 KB

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