AST.cpp 66 KB

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