AST.cpp 67 KB

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