AST.cpp 65 KB

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