AST.cpp 66 KB

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