ECMAScriptFunctionObject.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/Function.h>
  10. #include <LibJS/AST.h>
  11. #include <LibJS/Bytecode/BasicBlock.h>
  12. #include <LibJS/Bytecode/Generator.h>
  13. #include <LibJS/Bytecode/Interpreter.h>
  14. #include <LibJS/Bytecode/PassManager.h>
  15. #include <LibJS/Interpreter.h>
  16. #include <LibJS/Runtime/AbstractOperations.h>
  17. #include <LibJS/Runtime/Array.h>
  18. #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h>
  19. #include <LibJS/Runtime/AsyncGenerator.h>
  20. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  21. #include <LibJS/Runtime/Error.h>
  22. #include <LibJS/Runtime/ExecutionContext.h>
  23. #include <LibJS/Runtime/FunctionEnvironment.h>
  24. #include <LibJS/Runtime/GeneratorObject.h>
  25. #include <LibJS/Runtime/GlobalObject.h>
  26. #include <LibJS/Runtime/NativeFunction.h>
  27. #include <LibJS/Runtime/PromiseCapability.h>
  28. #include <LibJS/Runtime/PromiseConstructor.h>
  29. #include <LibJS/Runtime/Value.h>
  30. namespace JS {
  31. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> parameters, i32 m_function_length, Vector<DeprecatedFlyString> local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name)
  32. {
  33. Object* prototype = nullptr;
  34. switch (kind) {
  35. case FunctionKind::Normal:
  36. prototype = realm.intrinsics().function_prototype();
  37. break;
  38. case FunctionKind::Generator:
  39. prototype = realm.intrinsics().generator_function_prototype();
  40. break;
  41. case FunctionKind::Async:
  42. prototype = realm.intrinsics().async_function_prototype();
  43. break;
  44. case FunctionKind::AsyncGenerator:
  45. prototype = realm.intrinsics().async_generator_function_prototype();
  46. break;
  47. }
  48. return realm.heap().allocate<ECMAScriptFunctionObject>(realm, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, *prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function, move(class_field_initializer_name)).release_allocated_value_but_fixme_should_propagate_errors();
  49. }
  50. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, Object& prototype, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> parameters, i32 m_function_length, Vector<DeprecatedFlyString> local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, FunctionKind kind, bool is_strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name)
  51. {
  52. return realm.heap().allocate<ECMAScriptFunctionObject>(realm, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function, move(class_field_initializer_name)).release_allocated_value_but_fixme_should_propagate_errors();
  53. }
  54. ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> formal_parameters, i32 function_length, Vector<DeprecatedFlyString> local_variables_names, Environment* parent_environment, PrivateEnvironment* private_environment, Object& prototype, FunctionKind kind, bool strict, bool might_need_arguments_object, bool contains_direct_call_to_eval, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name)
  55. : FunctionObject(prototype)
  56. , m_name(move(name))
  57. , m_function_length(function_length)
  58. , m_local_variables_names(move(local_variables_names))
  59. , m_environment(parent_environment)
  60. , m_private_environment(private_environment)
  61. , m_formal_parameters(move(formal_parameters))
  62. , m_ecmascript_code(ecmascript_code)
  63. , m_realm(&prototype.shape().realm())
  64. , m_source_text(move(source_text))
  65. , m_class_field_initializer_name(move(class_field_initializer_name))
  66. , m_strict(strict)
  67. , m_might_need_arguments_object(might_need_arguments_object)
  68. , m_contains_direct_call_to_eval(contains_direct_call_to_eval)
  69. , m_is_arrow_function(is_arrow_function)
  70. , m_kind(kind)
  71. {
  72. // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate
  73. // 9. If thisMode is lexical-this, set F.[[ThisMode]] to lexical.
  74. if (m_is_arrow_function)
  75. m_this_mode = ThisMode::Lexical;
  76. // 10. Else if Strict is true, set F.[[ThisMode]] to strict.
  77. else if (m_strict)
  78. m_this_mode = ThisMode::Strict;
  79. else
  80. // 11. Else, set F.[[ThisMode]] to global.
  81. m_this_mode = ThisMode::Global;
  82. // 15. Set F.[[ScriptOrModule]] to GetActiveScriptOrModule().
  83. m_script_or_module = vm().get_active_script_or_module();
  84. // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist
  85. m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) {
  86. if (parameter.is_rest)
  87. return false;
  88. if (parameter.default_value)
  89. return false;
  90. if (!parameter.binding.template has<NonnullRefPtr<Identifier const>>())
  91. return false;
  92. return true;
  93. });
  94. }
  95. ThrowCompletionOr<void> ECMAScriptFunctionObject::initialize(Realm& realm)
  96. {
  97. auto& vm = this->vm();
  98. MUST_OR_THROW_OOM(Base::initialize(realm));
  99. // Note: The ordering of these properties must be: length, name, prototype which is the order
  100. // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances .
  101. // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
  102. // which must give the properties in chronological order which in this case is the order they
  103. // are defined in the spec.
  104. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true }));
  105. MUST(define_property_or_throw(vm.names.name, { .value = PrimitiveString::create(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true }));
  106. if (!m_is_arrow_function) {
  107. Object* prototype = nullptr;
  108. switch (m_kind) {
  109. case FunctionKind::Normal:
  110. prototype = MUST_OR_THROW_OOM(vm.heap().allocate<Object>(realm, realm.intrinsics().new_ordinary_function_prototype_object_shape()));
  111. MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true }));
  112. break;
  113. case FunctionKind::Generator:
  114. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  115. prototype = Object::create(realm, realm.intrinsics().generator_function_prototype_prototype());
  116. break;
  117. case FunctionKind::Async:
  118. break;
  119. case FunctionKind::AsyncGenerator:
  120. prototype = Object::create(realm, realm.intrinsics().async_generator_function_prototype_prototype());
  121. break;
  122. }
  123. // 27.7.4 AsyncFunction Instances, https://tc39.es/ecma262/#sec-async-function-instances
  124. // AsyncFunction instances do not have a prototype property as they are not constructible.
  125. if (m_kind != FunctionKind::Async)
  126. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  127. }
  128. return {};
  129. }
  130. // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  131. ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, MarkedVector<Value> arguments_list)
  132. {
  133. auto& vm = this->vm();
  134. // 1. Let callerContext be the running execution context.
  135. // NOTE: No-op, kept by the VM in its execution context stack.
  136. ExecutionContext callee_context(heap());
  137. callee_context.local_variables.resize(m_local_variables_names.size());
  138. // Non-standard
  139. callee_context.arguments.extend(move(arguments_list));
  140. if (auto* interpreter = vm.interpreter_if_exists())
  141. callee_context.current_node = interpreter->current_node();
  142. // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
  143. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  144. TRY(prepare_for_ordinary_call(callee_context, nullptr));
  145. // 3. Assert: calleeContext is now the running execution context.
  146. VERIFY(&vm.running_execution_context() == &callee_context);
  147. // 4. If F.[[IsClassConstructor]] is true, then
  148. if (m_is_class_constructor) {
  149. // a. Let error be a newly created TypeError object.
  150. // b. NOTE: error is created in calleeContext with F's associated Realm Record.
  151. auto throw_completion = vm.throw_completion<TypeError>(ErrorType::ClassConstructorWithoutNew, m_name);
  152. // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  153. vm.pop_execution_context();
  154. // d. Return ThrowCompletion(error).
  155. return throw_completion;
  156. }
  157. // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  158. ordinary_call_bind_this(callee_context, this_argument);
  159. // 6. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  160. auto result = ordinary_call_evaluate_body();
  161. // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  162. vm.pop_execution_context();
  163. // 8. If result.[[Type]] is return, return result.[[Value]].
  164. if (result.type() == Completion::Type::Return)
  165. return *result.value();
  166. // 9. ReturnIfAbrupt(result).
  167. if (result.is_abrupt()) {
  168. VERIFY(result.is_error());
  169. return result;
  170. }
  171. // 10. Return undefined.
  172. return js_undefined();
  173. }
  174. // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget
  175. ThrowCompletionOr<NonnullGCPtr<Object>> ECMAScriptFunctionObject::internal_construct(MarkedVector<Value> arguments_list, FunctionObject& new_target)
  176. {
  177. auto& vm = this->vm();
  178. // 1. Let callerContext be the running execution context.
  179. // NOTE: No-op, kept by the VM in its execution context stack.
  180. // 2. Let kind be F.[[ConstructorKind]].
  181. auto kind = m_constructor_kind;
  182. GCPtr<Object> this_argument;
  183. // 3. If kind is base, then
  184. if (kind == ConstructorKind::Base) {
  185. // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
  186. this_argument = TRY(ordinary_create_from_constructor<Object>(vm, new_target, &Intrinsics::object_prototype, ConstructWithPrototypeTag::Tag));
  187. }
  188. ExecutionContext callee_context(heap());
  189. callee_context.local_variables.resize(m_local_variables_names.size());
  190. // Non-standard
  191. callee_context.arguments.extend(move(arguments_list));
  192. if (auto* interpreter = vm.interpreter_if_exists())
  193. callee_context.current_node = interpreter->current_node();
  194. // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
  195. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  196. TRY(prepare_for_ordinary_call(callee_context, &new_target));
  197. // 5. Assert: calleeContext is now the running execution context.
  198. VERIFY(&vm.running_execution_context() == &callee_context);
  199. // 6. If kind is base, then
  200. if (kind == ConstructorKind::Base) {
  201. // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  202. ordinary_call_bind_this(callee_context, this_argument);
  203. // b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)).
  204. auto initialize_result = this_argument->initialize_instance_elements(*this);
  205. // c. If initializeResult is an abrupt completion, then
  206. if (initialize_result.is_throw_completion()) {
  207. // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  208. vm.pop_execution_context();
  209. // ii. Return ? initializeResult.
  210. return initialize_result.throw_completion();
  211. }
  212. }
  213. // 7. Let constructorEnv be the LexicalEnvironment of calleeContext.
  214. auto constructor_env = callee_context.lexical_environment;
  215. // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  216. auto result = ordinary_call_evaluate_body();
  217. // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  218. vm.pop_execution_context();
  219. // 10. If result.[[Type]] is return, then
  220. if (result.type() == Completion::Type::Return) {
  221. // FIXME: This is leftover from untangling the call/construct mess - doesn't belong here in any way, but removing it breaks derived classes.
  222. // Likely fixed by making ClassDefinitionEvaluation fully spec compliant.
  223. if (kind == ConstructorKind::Derived && result.value()->is_object()) {
  224. auto prototype = TRY(new_target.get(vm.names.prototype));
  225. if (prototype.is_object())
  226. TRY(result.value()->as_object().internal_set_prototype_of(&prototype.as_object()));
  227. }
  228. // EOF (End of FIXME)
  229. // a. If Type(result.[[Value]]) is Object, return result.[[Value]].
  230. if (result.value()->is_object())
  231. return result.value()->as_object();
  232. // b. If kind is base, return thisArgument.
  233. if (kind == ConstructorKind::Base)
  234. return *this_argument;
  235. // c. If result.[[Value]] is not undefined, throw a TypeError exception.
  236. if (!result.value()->is_undefined())
  237. return vm.throw_completion<TypeError>(ErrorType::DerivedConstructorReturningInvalidValue);
  238. }
  239. // 11. Else, ReturnIfAbrupt(result).
  240. else if (result.is_abrupt()) {
  241. VERIFY(result.is_error());
  242. return result;
  243. }
  244. // 12. Let thisBinding be ? constructorEnv.GetThisBinding().
  245. auto this_binding = TRY(constructor_env->get_this_binding(vm));
  246. // 13. Assert: Type(thisBinding) is Object.
  247. VERIFY(this_binding.is_object());
  248. // 14. Return thisBinding.
  249. return this_binding.as_object();
  250. }
  251. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  252. {
  253. Base::visit_edges(visitor);
  254. visitor.visit(m_environment);
  255. visitor.visit(m_private_environment);
  256. visitor.visit(m_realm);
  257. visitor.visit(m_home_object);
  258. for (auto& field : m_fields) {
  259. if (auto* property_key_ptr = field.name.get_pointer<PropertyKey>(); property_key_ptr && property_key_ptr->is_symbol())
  260. visitor.visit(property_key_ptr->as_symbol());
  261. }
  262. m_script_or_module.visit(
  263. [](Empty) {},
  264. [&](auto& script_or_module) {
  265. visitor.visit(script_or_module.ptr());
  266. });
  267. }
  268. // 10.2.7 MakeMethod ( F, homeObject ), https://tc39.es/ecma262/#sec-makemethod
  269. void ECMAScriptFunctionObject::make_method(Object& home_object)
  270. {
  271. // 1. Set F.[[HomeObject]] to homeObject.
  272. m_home_object = &home_object;
  273. // 2. Return unused.
  274. }
  275. // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  276. ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter)
  277. {
  278. auto& vm = this->vm();
  279. auto& realm = *vm.current_realm();
  280. auto& callee_context = vm.running_execution_context();
  281. // Needed to extract declarations and functions
  282. ScopeNode const* scope_body = nullptr;
  283. if (is<ScopeNode>(*m_ecmascript_code))
  284. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  285. bool has_parameter_expressions = false;
  286. // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases)
  287. bool has_duplicates = false;
  288. HashTable<DeprecatedFlyString> parameter_names;
  289. for (auto& parameter : m_formal_parameters) {
  290. if (parameter.default_value)
  291. has_parameter_expressions = true;
  292. parameter.binding.visit(
  293. [&](Identifier const& identifier) {
  294. if (parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  295. has_duplicates = true;
  296. },
  297. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  298. if (pattern->contains_expression())
  299. has_parameter_expressions = true;
  300. // NOTE: Nothing in the callback throws an exception.
  301. MUST(pattern->for_each_bound_identifier([&](auto& identifier) {
  302. if (parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  303. has_duplicates = true;
  304. }));
  305. });
  306. }
  307. auto arguments_object_needed = m_might_need_arguments_object;
  308. if (this_mode() == ThisMode::Lexical)
  309. arguments_object_needed = false;
  310. if (parameter_names.contains(vm.names.arguments.as_string()))
  311. arguments_object_needed = false;
  312. HashTable<DeprecatedFlyString> function_names;
  313. Vector<FunctionDeclaration const&> functions_to_initialize;
  314. if (scope_body) {
  315. // NOTE: Nothing in the callback throws an exception.
  316. MUST(scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  317. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  318. functions_to_initialize.append(function);
  319. }));
  320. auto const& arguments_name = vm.names.arguments.as_string();
  321. if (!has_parameter_expressions && function_names.contains(arguments_name))
  322. arguments_object_needed = false;
  323. if (!has_parameter_expressions && arguments_object_needed) {
  324. // NOTE: Nothing in the callback throws an exception.
  325. MUST(scope_body->for_each_lexically_declared_name([&](auto const& name) {
  326. if (name == arguments_name)
  327. arguments_object_needed = false;
  328. }));
  329. }
  330. } else {
  331. arguments_object_needed = false;
  332. }
  333. GCPtr<Environment> environment;
  334. if (is_strict_mode() || !has_parameter_expressions) {
  335. environment = callee_context.lexical_environment;
  336. } else {
  337. environment = new_declarative_environment(*callee_context.lexical_environment);
  338. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  339. callee_context.lexical_environment = environment;
  340. }
  341. for (auto const& parameter_name : parameter_names) {
  342. if (MUST(environment->has_binding(parameter_name)))
  343. continue;
  344. MUST(environment->create_mutable_binding(vm, parameter_name, false));
  345. if (has_duplicates)
  346. MUST(environment->initialize_binding(vm, parameter_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  347. }
  348. if (arguments_object_needed) {
  349. Object* arguments_object;
  350. if (is_strict_mode() || !has_simple_parameter_list())
  351. arguments_object = create_unmapped_arguments_object(vm, vm.running_execution_context().arguments);
  352. else
  353. arguments_object = create_mapped_arguments_object(vm, *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  354. if (is_strict_mode())
  355. MUST(environment->create_immutable_binding(vm, vm.names.arguments.as_string(), false));
  356. else
  357. MUST(environment->create_mutable_binding(vm, vm.names.arguments.as_string(), false));
  358. MUST(environment->initialize_binding(vm, vm.names.arguments.as_string(), arguments_object, Environment::InitializeBindingHint::Normal));
  359. parameter_names.set(vm.names.arguments.as_string());
  360. }
  361. // We now treat parameterBindings as parameterNames.
  362. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  363. auto& execution_context_arguments = vm.running_execution_context().arguments;
  364. size_t default_parameter_index = 0;
  365. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  366. auto& parameter = m_formal_parameters[i];
  367. if (parameter.default_value)
  368. ++default_parameter_index;
  369. TRY(parameter.binding.visit(
  370. [&](auto const& param) -> ThrowCompletionOr<void> {
  371. Value argument_value;
  372. if (parameter.is_rest) {
  373. auto array = MUST(Array::create(realm, 0));
  374. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  375. array->indexed_properties().append(execution_context_arguments[rest_index]);
  376. argument_value = array;
  377. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  378. argument_value = execution_context_arguments[i];
  379. } else if (parameter.default_value) {
  380. auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists();
  381. if (static_cast<FunctionKind>(m_kind) == FunctionKind::Generator || static_cast<FunctionKind>(m_kind) == FunctionKind::AsyncGenerator)
  382. bytecode_interpreter = &vm.bytecode_interpreter();
  383. if (bytecode_interpreter) {
  384. auto value_and_frame = bytecode_interpreter->run_and_return_frame(realm, *m_default_parameter_bytecode_executables[default_parameter_index - 1], nullptr);
  385. if (value_and_frame.value.is_error())
  386. return value_and_frame.value.release_error();
  387. // Resulting value is in the accumulator.
  388. argument_value = value_and_frame.frame->registers.at(0);
  389. } else if (interpreter) {
  390. argument_value = TRY(parameter.default_value->execute(*interpreter)).release_value();
  391. }
  392. } else {
  393. argument_value = js_undefined();
  394. }
  395. Environment* used_environment = has_duplicates ? nullptr : environment;
  396. if constexpr (IsSame<NonnullRefPtr<Identifier const> const&, decltype(param)>) {
  397. if ((vm.bytecode_interpreter_if_exists() || kind() == FunctionKind::Generator || kind() == FunctionKind::AsyncGenerator) && param->is_local()) {
  398. // NOTE: Local variables are supported only in bytecode interpreter
  399. callee_context.local_variables[param->local_variable_index()] = argument_value;
  400. return {};
  401. } else {
  402. Reference reference = TRY(vm.resolve_binding(param->string(), used_environment));
  403. // Here the difference from hasDuplicates is important
  404. if (has_duplicates)
  405. return reference.put_value(vm, argument_value);
  406. else
  407. return reference.initialize_referenced_binding(vm, argument_value);
  408. }
  409. }
  410. if constexpr (IsSame<NonnullRefPtr<BindingPattern const> const&, decltype(param)>) {
  411. // Here the difference from hasDuplicates is important
  412. return vm.binding_initialization(param, argument_value, used_environment);
  413. }
  414. }));
  415. }
  416. GCPtr<Environment> var_environment;
  417. HashTable<DeprecatedFlyString> instantiated_var_names;
  418. if (scope_body)
  419. instantiated_var_names.ensure_capacity(scope_body->var_declaration_count());
  420. if (!has_parameter_expressions) {
  421. if (scope_body) {
  422. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  423. // an exception should not result from `for_each_var_declared_name`.
  424. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  425. if (!parameter_names.contains(id.string()) && instantiated_var_names.set(id.string()) == AK::HashSetResult::InsertedNewEntry) {
  426. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  427. callee_context.local_variables[id.local_variable_index()] = js_undefined();
  428. } else {
  429. MUST(environment->create_mutable_binding(vm, id.string(), false));
  430. MUST(environment->initialize_binding(vm, id.string(), js_undefined(), Environment::InitializeBindingHint::Normal));
  431. }
  432. }
  433. }));
  434. }
  435. var_environment = environment;
  436. } else {
  437. var_environment = new_declarative_environment(*environment);
  438. callee_context.variable_environment = var_environment;
  439. if (scope_body) {
  440. // NOTE: Due to the use of MUST with `create_mutable_binding`, `get_binding_value` and `initialize_binding` below,
  441. // an exception should not result from `for_each_var_declared_name`.
  442. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  443. if (instantiated_var_names.set(id.string()) != AK::HashSetResult::InsertedNewEntry)
  444. return;
  445. MUST(var_environment->create_mutable_binding(vm, id.string(), false));
  446. Value initial_value;
  447. if (!parameter_names.contains(id.string()) || function_names.contains(id.string()))
  448. initial_value = js_undefined();
  449. else
  450. initial_value = MUST(environment->get_binding_value(vm, id.string(), false));
  451. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  452. // NOTE: Local variables are supported only in bytecode interpreter
  453. callee_context.local_variables[id.local_variable_index()] = initial_value;
  454. } else {
  455. MUST(var_environment->initialize_binding(vm, id.string(), initial_value, Environment::InitializeBindingHint::Normal));
  456. }
  457. }));
  458. }
  459. }
  460. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  461. if (!m_strict && scope_body) {
  462. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  463. // an exception should not result from `for_each_function_hoistable_with_annexB_extension`.
  464. MUST(scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  465. auto function_name = function_declaration.name();
  466. if (parameter_names.contains(function_name))
  467. return;
  468. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  469. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  470. MUST(var_environment->create_mutable_binding(vm, function_name, false));
  471. MUST(var_environment->initialize_binding(vm, function_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  472. instantiated_var_names.set(function_name);
  473. }
  474. function_declaration.set_should_do_additional_annexB_steps();
  475. }));
  476. }
  477. GCPtr<Environment> lex_environment;
  478. // 30. If strict is false, then
  479. if (!is_strict_mode()) {
  480. // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true:
  481. // 1. there is no direct call to eval() within this function
  482. // 2. there are no lexical declarations that would go into the environment
  483. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  484. if (can_elide_declarative_environment) {
  485. lex_environment = var_environment;
  486. } else {
  487. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  488. // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval
  489. // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level
  490. // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places
  491. // all declarations into a new Environment Record.
  492. lex_environment = new_declarative_environment(*var_environment);
  493. }
  494. } else {
  495. // 31. Else, let lexEnv be varEnv.
  496. lex_environment = var_environment;
  497. }
  498. // 32. Set the LexicalEnvironment of calleeContext to lexEnv.
  499. callee_context.lexical_environment = lex_environment;
  500. if (!scope_body)
  501. return {};
  502. // NOTE: Due to the use of MUST in the callback, an exception should not result from `for_each_lexically_scoped_declaration`.
  503. MUST(scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  504. // NOTE: Due to the use of MUST with `create_immutable_binding` and `create_mutable_binding` below,
  505. // an exception should not result from `for_each_bound_name`.
  506. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  507. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  508. // NOTE: Local variables are supported only in bytecode interpreter
  509. return;
  510. }
  511. if (declaration.is_constant_declaration())
  512. MUST(lex_environment->create_immutable_binding(vm, id.string(), true));
  513. else
  514. MUST(lex_environment->create_mutable_binding(vm, id.string(), false));
  515. }));
  516. }));
  517. auto private_environment = callee_context.private_environment;
  518. for (auto& declaration : functions_to_initialize) {
  519. auto function = ECMAScriptFunctionObject::create(realm, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), declaration.local_variables_names(), lex_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  520. if ((vm.bytecode_interpreter_if_exists() || kind() == FunctionKind::Generator || kind() == FunctionKind::AsyncGenerator) && declaration.name_identifier()->is_local()) {
  521. callee_context.local_variables[declaration.name_identifier()->local_variable_index()] = function;
  522. } else {
  523. MUST(var_environment->set_mutable_binding(vm, declaration.name(), function, false));
  524. }
  525. }
  526. if (is<DeclarativeEnvironment>(*lex_environment))
  527. static_cast<DeclarativeEnvironment*>(lex_environment.ptr())->shrink_to_fit();
  528. if (is<DeclarativeEnvironment>(*var_environment))
  529. static_cast<DeclarativeEnvironment*>(var_environment.ptr())->shrink_to_fit();
  530. return {};
  531. }
  532. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  533. ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  534. {
  535. auto& vm = this->vm();
  536. // Non-standard
  537. callee_context.is_strict_mode = m_strict;
  538. // 1. Let callerContext be the running execution context.
  539. // 2. Let calleeContext be a new ECMAScript code execution context.
  540. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  541. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  542. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  543. // 3. Set the Function of calleeContext to F.
  544. callee_context.function = this;
  545. callee_context.function_name = m_name;
  546. // 4. Let calleeRealm be F.[[Realm]].
  547. auto callee_realm = m_realm;
  548. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  549. // every function has a realm - especially in LibWeb that's sometimes not the case
  550. // when a function is created while no JS is running, as we currently need to rely on
  551. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  552. // If there's no 'current realm' either, we can't continue and crash.
  553. if (!callee_realm)
  554. callee_realm = vm.current_realm();
  555. VERIFY(callee_realm);
  556. // 5. Set the Realm of calleeContext to calleeRealm.
  557. callee_context.realm = callee_realm;
  558. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  559. callee_context.script_or_module = m_script_or_module;
  560. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  561. auto local_environment = new_function_environment(*this, new_target);
  562. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  563. callee_context.lexical_environment = local_environment;
  564. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  565. callee_context.variable_environment = local_environment;
  566. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  567. callee_context.private_environment = m_private_environment;
  568. // 11. If callerContext is not already suspended, suspend callerContext.
  569. // FIXME: We don't have this concept yet.
  570. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  571. TRY(vm.push_execution_context(callee_context, {}));
  572. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  573. // 14. Return calleeContext.
  574. // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack.
  575. return {};
  576. }
  577. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  578. void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument)
  579. {
  580. auto& vm = this->vm();
  581. // 1. Let thisMode be F.[[ThisMode]].
  582. auto this_mode = m_this_mode;
  583. // If thisMode is lexical, return unused.
  584. if (this_mode == ThisMode::Lexical)
  585. return;
  586. // 3. Let calleeRealm be F.[[Realm]].
  587. auto callee_realm = m_realm;
  588. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  589. // every function has a realm - especially in LibWeb that's sometimes not the case
  590. // when a function is created while no JS is running, as we currently need to rely on
  591. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  592. // If there's no 'current realm' either, we can't continue and crash.
  593. if (!callee_realm)
  594. callee_realm = vm.current_realm();
  595. VERIFY(callee_realm);
  596. // 4. Let localEnv be the LexicalEnvironment of calleeContext.
  597. auto local_env = callee_context.lexical_environment;
  598. Value this_value;
  599. // 5. If thisMode is strict, let thisValue be thisArgument.
  600. if (this_mode == ThisMode::Strict) {
  601. this_value = this_argument;
  602. }
  603. // 6. Else,
  604. else {
  605. // a. If thisArgument is undefined or null, then
  606. if (this_argument.is_nullish()) {
  607. // i. Let globalEnv be calleeRealm.[[GlobalEnv]].
  608. // ii. Assert: globalEnv is a global Environment Record.
  609. auto& global_env = callee_realm->global_environment();
  610. // iii. Let thisValue be globalEnv.[[GlobalThisValue]].
  611. this_value = &global_env.global_this_value();
  612. }
  613. // b. Else,
  614. else {
  615. // i. Let thisValue be ! ToObject(thisArgument).
  616. this_value = MUST(this_argument.to_object(vm));
  617. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
  618. VERIFY(vm.current_realm() == callee_realm);
  619. }
  620. }
  621. // 7. Assert: localEnv is a function Environment Record.
  622. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
  623. // 9. Perform ! localEnv.BindThisValue(thisValue).
  624. MUST(verify_cast<FunctionEnvironment>(*local_env).bind_this_value(vm, this_value));
  625. // 10. Return unused.
  626. }
  627. // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  628. template<typename T>
  629. void async_function_start(VM& vm, PromiseCapability const& promise_capability, T const& async_function_body)
  630. {
  631. // 1. Let runningContext be the running execution context.
  632. auto& running_context = vm.running_execution_context();
  633. // 2. Let asyncContext be a copy of runningContext.
  634. auto async_context = running_context.copy();
  635. // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context.
  636. // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext).
  637. async_block_start(vm, async_function_body, promise_capability, async_context);
  638. // 5. Return unused.
  639. }
  640. // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart
  641. template<typename T>
  642. void async_block_start(VM& vm, T const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context)
  643. {
  644. auto& realm = *vm.current_realm();
  645. // 1. Assert: promiseCapability is a PromiseCapability Record.
  646. // 2. Let runningContext be the running execution context.
  647. auto& running_context = vm.running_execution_context();
  648. // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
  649. auto execution_steps = NativeFunction::create(realm, "", [&realm, &async_body, &promise_capability, &async_context](auto& vm) -> ThrowCompletionOr<Value> {
  650. // a. Let result be the result of evaluating asyncBody.
  651. Completion result;
  652. if (auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists()) {
  653. // FIXME: Cache this executable somewhere.
  654. auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"sv);
  655. if (maybe_executable.is_error())
  656. result = maybe_executable.release_error();
  657. else
  658. result = bytecode_interpreter->run_and_return_frame(realm, *maybe_executable.value(), nullptr).value;
  659. } else {
  660. result = async_body->execute(vm.interpreter());
  661. }
  662. // b. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
  663. // c. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
  664. vm.pop_execution_context();
  665. // d. Let env be asyncContext's LexicalEnvironment.
  666. auto env = async_context.lexical_environment;
  667. VERIFY(is<DeclarativeEnvironment>(*env));
  668. // e. Set result to DisposeResources(env, result).
  669. result = dispose_resources(vm, static_cast<DeclarativeEnvironment*>(env.ptr()), result);
  670. // f. If result.[[Type]] is normal, then
  671. if (result.type() == Completion::Type::Normal) {
  672. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
  673. MUST(call(vm, *promise_capability.resolve(), js_undefined(), js_undefined()));
  674. }
  675. // g. Else if result.[[Type]] is return, then
  676. else if (result.type() == Completion::Type::Return) {
  677. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
  678. MUST(call(vm, *promise_capability.resolve(), js_undefined(), *result.value()));
  679. }
  680. // h. Else,
  681. else {
  682. // i. Assert: result.[[Type]] is throw.
  683. VERIFY(result.type() == Completion::Type::Throw);
  684. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
  685. MUST(call(vm, *promise_capability.reject(), js_undefined(), *result.value()));
  686. }
  687. // i. Return unused.
  688. // NOTE: We don't support returning an empty/optional/unused value here.
  689. return js_undefined();
  690. });
  691. // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  692. auto push_result = vm.push_execution_context(async_context, {});
  693. if (push_result.is_error())
  694. return;
  695. // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  696. auto result = call(vm, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value);
  697. // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  698. VERIFY(&vm.running_execution_context() == &running_context);
  699. // 7. Assert: result is a normal completion with a value of unused. The possible sources of this value are Await or, if the async function doesn't await anything, step 3.g above.
  700. VERIFY(result.has_value() && result.value().is_undefined());
  701. // 8. Return unused.
  702. }
  703. template void async_block_start(VM&, NonnullGCPtr<Statement const> const& async_body, PromiseCapability const&, ExecutionContext&);
  704. template void async_function_start(VM&, PromiseCapability const&, NonnullGCPtr<Statement const> const& async_function_body);
  705. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  706. // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  707. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  708. {
  709. auto& vm = this->vm();
  710. auto& realm = *vm.current_realm();
  711. auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists();
  712. // The bytecode interpreter can execute generator functions while the AST interpreter cannot.
  713. // This simply makes it create a new bytecode interpreter when one doesn't exist when executing a generator function.
  714. // Doing so makes it automatically switch to the bytecode interpreter to execute any future code until it exits the generator. See below.
  715. // This allows us to keep all of the existing functionality that works in AST while adding generator support on top of it.
  716. // However, this does cause an awkward situation with features not supported in bytecode, where features that work outside of generators with AST
  717. // suddenly stop working inside of generators.
  718. // This is a stop gap until bytecode mode becomes the default.
  719. if ((m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator) && !bytecode_interpreter) {
  720. bytecode_interpreter = &vm.bytecode_interpreter();
  721. }
  722. if (bytecode_interpreter) {
  723. // NOTE: There's a subtle ordering issue here:
  724. // - We have to compile the default parameter values before instantiating the function.
  725. // - We have to instantiate the function before compiling the function body.
  726. // This is why FunctionDeclarationInstantiation is invoked in the middle.
  727. // The issue is that FunctionDeclarationInstantiation may mark certain functions as hoisted
  728. // per Annex B. This affects code generation for FunctionDeclaration nodes.
  729. if (!m_bytecode_executable) {
  730. size_t default_parameter_index = 0;
  731. for (auto& parameter : m_formal_parameters) {
  732. if (!parameter.default_value)
  733. continue;
  734. auto executable = TRY(Bytecode::compile(vm, *parameter.default_value, FunctionKind::Normal, DeprecatedString::formatted("default parameter #{} for {}", default_parameter_index, m_name)));
  735. m_default_parameter_bytecode_executables.append(move(executable));
  736. }
  737. }
  738. auto declaration_result = function_declaration_instantiation(nullptr);
  739. if (m_kind == FunctionKind::Normal || m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator) {
  740. if (declaration_result.is_error())
  741. return declaration_result.release_error();
  742. }
  743. if (!m_bytecode_executable)
  744. m_bytecode_executable = TRY(Bytecode::compile(vm, *m_ecmascript_code, m_kind, m_name));
  745. if (m_kind == FunctionKind::Async) {
  746. if (declaration_result.is_throw_completion()) {
  747. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  748. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  749. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  750. }
  751. }
  752. auto result_and_frame = bytecode_interpreter->run_and_return_frame(realm, *m_bytecode_executable, nullptr);
  753. VERIFY(result_and_frame.frame != nullptr);
  754. if (result_and_frame.value.is_error())
  755. return result_and_frame.value.release_error();
  756. auto result = result_and_frame.value.release_value();
  757. // NOTE: Running the bytecode should eventually return a completion.
  758. // Until it does, we assume "return" and include the undefined fallback from the call site.
  759. if (m_kind == FunctionKind::Normal)
  760. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  761. if (m_kind == FunctionKind::AsyncGenerator) {
  762. auto async_generator_object = TRY(AsyncGenerator::create(realm, result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame)));
  763. return { Completion::Type::Return, async_generator_object, {} };
  764. }
  765. auto generator_object = TRY(GeneratorObject::create(realm, result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame)));
  766. // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise
  767. // See AwaitExpression::generate_bytecode() for the transformation.
  768. if (m_kind == FunctionKind::Async)
  769. return { Completion::Type::Return, TRY(AsyncFunctionDriverWrapper::create(realm, generator_object)), {} };
  770. VERIFY(m_kind == FunctionKind::Generator);
  771. return { Completion::Type::Return, generator_object, {} };
  772. } else {
  773. if (m_kind == FunctionKind::Generator)
  774. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Generator function execution in AST interpreter");
  775. if (m_kind == FunctionKind::AsyncGenerator)
  776. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Async generator function execution in AST interpreter");
  777. OwnPtr<Interpreter> local_interpreter;
  778. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  779. if (!ast_interpreter) {
  780. local_interpreter = Interpreter::create_with_existing_realm(realm);
  781. ast_interpreter = local_interpreter.ptr();
  782. }
  783. VM::InterpreterExecutionScope scope(*ast_interpreter);
  784. // FunctionBody : FunctionStatementList
  785. if (m_kind == FunctionKind::Normal) {
  786. // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
  787. TRY(function_declaration_instantiation(ast_interpreter));
  788. // 2. Let result be result of evaluating FunctionStatementList.
  789. auto result = m_ecmascript_code->execute(*ast_interpreter);
  790. // 3. Let env be the running execution context's LexicalEnvironment.
  791. auto env = vm.running_execution_context().lexical_environment;
  792. VERIFY(is<DeclarativeEnvironment>(*env));
  793. // 4. Return ? DisposeResources(env, result).
  794. return dispose_resources(vm, static_cast<DeclarativeEnvironment*>(env.ptr()), result);
  795. }
  796. // AsyncFunctionBody : FunctionBody
  797. else if (m_kind == FunctionKind::Async) {
  798. // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  799. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  800. // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)).
  801. auto declaration_result = function_declaration_instantiation(ast_interpreter);
  802. // 3. If declResult is an abrupt completion, then
  803. if (declaration_result.is_throw_completion()) {
  804. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « declResult.[[Value]] »).
  805. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  806. }
  807. // 4. Else,
  808. else {
  809. // a. Perform AsyncFunctionStart(promiseCapability, FunctionBody).
  810. async_function_start(vm, promise_capability, m_ecmascript_code);
  811. }
  812. // 5. Return Completion Record { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
  813. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  814. }
  815. }
  816. VERIFY_NOT_REACHED();
  817. }
  818. void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name)
  819. {
  820. VERIFY(!name.is_null());
  821. auto& vm = this->vm();
  822. m_name = name;
  823. MUST(define_property_or_throw(vm.names.name, { .value = PrimitiveString::create(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  824. }
  825. }