ECMAScriptFunctionObject.cpp 51 KB

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