AST.cpp 66 KB

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