ECMAScriptFunctionObject.cpp 48 KB

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