ECMAScriptFunctionObject.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  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. // 1. Let calleeContext be the running execution context.
  282. auto& callee_context = vm.running_execution_context();
  283. // 2. Let code be func.[[ECMAScriptCode]].
  284. ScopeNode const* scope_body = nullptr;
  285. if (is<ScopeNode>(*m_ecmascript_code))
  286. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  287. // 3. Let strict be func.[[Strict]].
  288. bool const strict = is_strict_mode();
  289. bool has_parameter_expressions = false;
  290. // 4. Let formals be func.[[FormalParameters]].
  291. auto const& formals = m_formal_parameters;
  292. // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases)
  293. // 5. Let parameterNames be the BoundNames of formals.
  294. // 6. If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false.
  295. bool has_duplicates = false;
  296. HashTable<DeprecatedFlyString> parameter_names;
  297. // NOTE: This loop performs step 5, 6, and 8.
  298. for (auto const& parameter : formals) {
  299. if (parameter.default_value)
  300. has_parameter_expressions = true;
  301. parameter.binding.visit(
  302. [&](Identifier const& identifier) {
  303. if (parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  304. has_duplicates = true;
  305. },
  306. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  307. if (pattern->contains_expression())
  308. has_parameter_expressions = true;
  309. // NOTE: Nothing in the callback throws an exception.
  310. MUST(pattern->for_each_bound_identifier([&](auto& identifier) {
  311. if (parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  312. has_duplicates = true;
  313. }));
  314. });
  315. }
  316. // 7. Let simpleParameterList be IsSimpleParameterList of formals.
  317. bool const simple_parameter_list = has_simple_parameter_list();
  318. // 8. Let hasParameterExpressions be ContainsExpression of formals.
  319. // NOTE: Already set above.
  320. // 9. Let varNames be the VarDeclaredNames of code.
  321. // 10. Let varDeclarations be the VarScopedDeclarations of code.
  322. // 11. Let lexicalNames be the LexicallyDeclaredNames of code.
  323. // NOTE: Not needed as we use iteration helpers for this instead.
  324. // 12. Let functionNames be a new empty List.
  325. HashTable<DeprecatedFlyString> function_names;
  326. // 13. Let functionsToInitialize be a new empty List.
  327. Vector<FunctionDeclaration const&> functions_to_initialize;
  328. // 14. For each element d of varDeclarations, in reverse List order, do
  329. // a. If d is neither a VariableDeclaration nor a ForBinding nor a BindingIdentifier, then
  330. // i. Assert: d is either a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration.
  331. // ii. Let fn be the sole element of the BoundNames of d.
  332. // iii. If functionNames does not contain fn, then
  333. // 1. Insert fn as the first element of functionNames.
  334. // 2. NOTE: If there are multiple function declarations for the same name, the last declaration is used.
  335. // 3. Insert d as the first element of functionsToInitialize.
  336. // NOTE: This block is done in step 18 below.
  337. // 15. Let argumentsObjectNeeded be true.
  338. auto arguments_object_needed = m_might_need_arguments_object;
  339. // 16. If func.[[ThisMode]] is lexical, then
  340. if (this_mode() == ThisMode::Lexical) {
  341. // a. NOTE: Arrow functions never have an arguments object.
  342. // b. Set argumentsObjectNeeded to false.
  343. arguments_object_needed = false;
  344. }
  345. // 17. Else if parameterNames contains "arguments", then
  346. else if (parameter_names.contains(vm.names.arguments.as_string())) {
  347. // a. Set argumentsObjectNeeded to false.
  348. arguments_object_needed = false;
  349. }
  350. // 18. Else if hasParameterExpressions is false, then
  351. // a. If functionNames contains "arguments" or lexicalNames contains "arguments", then
  352. // i. Set argumentsObjectNeeded to false.
  353. // NOTE: The block below is a combination of step 14 and step 18.
  354. if (scope_body) {
  355. // NOTE: Nothing in the callback throws an exception.
  356. MUST(scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  357. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  358. functions_to_initialize.append(function);
  359. }));
  360. auto const& arguments_name = vm.names.arguments.as_string();
  361. if (!has_parameter_expressions && function_names.contains(arguments_name))
  362. arguments_object_needed = false;
  363. if (!has_parameter_expressions && arguments_object_needed) {
  364. // NOTE: Nothing in the callback throws an exception.
  365. MUST(scope_body->for_each_lexically_declared_name([&](auto const& name) {
  366. if (name == arguments_name)
  367. arguments_object_needed = false;
  368. }));
  369. }
  370. } else {
  371. arguments_object_needed = false;
  372. }
  373. GCPtr<Environment> environment;
  374. // 19. If strict is true or hasParameterExpressions is false, then
  375. if (strict || !has_parameter_expressions) {
  376. // a. NOTE: Only a single Environment Record is needed for the parameters, since calls to eval in strict mode code cannot create new bindings which are visible outside of the eval.
  377. // b. Let env be the LexicalEnvironment of calleeContext.
  378. environment = callee_context.lexical_environment;
  379. }
  380. // 20. Else,
  381. else {
  382. // a. NOTE: A separate Environment Record is needed to ensure that bindings created by direct eval calls in the formal parameter list are outside the environment where parameters are declared.
  383. // b. Let calleeEnv be the LexicalEnvironment of calleeContext.
  384. auto callee_env = callee_context.lexical_environment;
  385. // c. Let env be NewDeclarativeEnvironment(calleeEnv).
  386. environment = new_declarative_environment(*callee_env);
  387. // d. Assert: The VariableEnvironment of calleeContext is calleeEnv.
  388. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  389. // e. Set the LexicalEnvironment of calleeContext to env.
  390. callee_context.lexical_environment = environment;
  391. }
  392. // 21. For each String paramName of parameterNames, do
  393. for (auto const& parameter_name : parameter_names) {
  394. // a. Let alreadyDeclared be ! env.HasBinding(paramName).
  395. auto already_declared = MUST(environment->has_binding(parameter_name));
  396. // b. NOTE: Early errors ensure that duplicate parameter names can only occur in non-strict functions that do not have parameter default values or rest parameters.
  397. // c. If alreadyDeclared is false, then
  398. if (!already_declared) {
  399. // i. Perform ! env.CreateMutableBinding(paramName, false).
  400. MUST(environment->create_mutable_binding(vm, parameter_name, false));
  401. // ii. If hasDuplicates is true, then
  402. if (has_duplicates) {
  403. // 1. Perform ! env.InitializeBinding(paramName, undefined).
  404. MUST(environment->initialize_binding(vm, parameter_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  405. }
  406. }
  407. }
  408. // 22. If argumentsObjectNeeded is true, then
  409. if (arguments_object_needed) {
  410. Object* arguments_object;
  411. // a. If strict is true or simpleParameterList is false, then
  412. if (strict || !simple_parameter_list) {
  413. // i. Let ao be CreateUnmappedArgumentsObject(argumentsList).
  414. arguments_object = create_unmapped_arguments_object(vm, vm.running_execution_context().arguments);
  415. }
  416. // b. Else,
  417. else {
  418. // i. NOTE: A mapped argument object is only provided for non-strict functions that don't have a rest parameter, any parameter default value initializers, or any destructured parameters.
  419. // ii. Let ao be CreateMappedArgumentsObject(func, formals, argumentsList, env).
  420. arguments_object = create_mapped_arguments_object(vm, *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  421. }
  422. // c. If strict is true, then
  423. if (strict) {
  424. // i. Perform ! env.CreateImmutableBinding("arguments", false).
  425. MUST(environment->create_immutable_binding(vm, vm.names.arguments.as_string(), false));
  426. // ii. NOTE: In strict mode code early errors prevent attempting to assign to this binding, so its mutability is not observable.
  427. }
  428. // b. Else,
  429. else {
  430. // i. Perform ! env.CreateMutableBinding("arguments", false).
  431. MUST(environment->create_mutable_binding(vm, vm.names.arguments.as_string(), false));
  432. }
  433. // c. Perform ! env.InitializeBinding("arguments", ao).
  434. MUST(environment->initialize_binding(vm, vm.names.arguments.as_string(), arguments_object, Environment::InitializeBindingHint::Normal));
  435. // f. Let parameterBindings be the list-concatenation of parameterNames and « "arguments" ».
  436. parameter_names.set(vm.names.arguments.as_string());
  437. }
  438. // 23. Else,
  439. else {
  440. // a. Let parameterBindings be parameterNames.
  441. }
  442. // NOTE: We now treat parameterBindings as parameterNames.
  443. // 24. Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  444. // 25. If hasDuplicates is true, then
  445. // a. Perform ? IteratorBindingInitialization of formals with arguments iteratorRecord and undefined.
  446. // 26. Else,
  447. // a. Perform ? IteratorBindingInitialization of formals with arguments iteratorRecord and env.
  448. // NOTE: The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  449. auto& execution_context_arguments = vm.running_execution_context().arguments;
  450. size_t default_parameter_index = 0;
  451. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  452. auto& parameter = m_formal_parameters[i];
  453. if (parameter.default_value)
  454. ++default_parameter_index;
  455. TRY(parameter.binding.visit(
  456. [&](auto const& param) -> ThrowCompletionOr<void> {
  457. Value argument_value;
  458. if (parameter.is_rest) {
  459. auto array = MUST(Array::create(realm, 0));
  460. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  461. array->indexed_properties().append(execution_context_arguments[rest_index]);
  462. argument_value = array;
  463. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  464. argument_value = execution_context_arguments[i];
  465. } else if (parameter.default_value) {
  466. auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists();
  467. if (static_cast<FunctionKind>(m_kind) == FunctionKind::Generator || static_cast<FunctionKind>(m_kind) == FunctionKind::AsyncGenerator)
  468. bytecode_interpreter = &vm.bytecode_interpreter();
  469. if (bytecode_interpreter) {
  470. auto value_and_frame = bytecode_interpreter->run_and_return_frame(realm, *m_default_parameter_bytecode_executables[default_parameter_index - 1], nullptr);
  471. if (value_and_frame.value.is_error())
  472. return value_and_frame.value.release_error();
  473. // Resulting value is in the accumulator.
  474. argument_value = value_and_frame.frame->registers.at(0);
  475. } else if (interpreter) {
  476. argument_value = TRY(parameter.default_value->execute(*interpreter)).release_value();
  477. }
  478. } else {
  479. argument_value = js_undefined();
  480. }
  481. Environment* used_environment = has_duplicates ? nullptr : environment;
  482. if constexpr (IsSame<NonnullRefPtr<Identifier const> const&, decltype(param)>) {
  483. if ((vm.bytecode_interpreter_if_exists() || kind() == FunctionKind::Generator || kind() == FunctionKind::AsyncGenerator) && param->is_local()) {
  484. // NOTE: Local variables are supported only in bytecode interpreter
  485. callee_context.local_variables[param->local_variable_index()] = argument_value;
  486. return {};
  487. } else {
  488. Reference reference = TRY(vm.resolve_binding(param->string(), used_environment));
  489. // Here the difference from hasDuplicates is important
  490. if (has_duplicates)
  491. return reference.put_value(vm, argument_value);
  492. else
  493. return reference.initialize_referenced_binding(vm, argument_value);
  494. }
  495. }
  496. if constexpr (IsSame<NonnullRefPtr<BindingPattern const> const&, decltype(param)>) {
  497. // Here the difference from hasDuplicates is important
  498. return vm.binding_initialization(param, argument_value, used_environment);
  499. }
  500. }));
  501. }
  502. GCPtr<Environment> var_environment;
  503. HashTable<DeprecatedFlyString> instantiated_var_names;
  504. if (scope_body)
  505. instantiated_var_names.ensure_capacity(scope_body->var_declaration_count());
  506. // 27. If hasParameterExpressions is false, then
  507. if (!has_parameter_expressions) {
  508. // a. NOTE: Only a single Environment Record is needed for the parameters and top-level vars.
  509. // b. Let instantiatedVarNames be a copy of the List parameterBindings.
  510. // NOTE: Done in implementation of step 27.c.i.1 below
  511. if (scope_body) {
  512. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  513. // an exception should not result from `for_each_var_declared_name`.
  514. // c. For each element n of varNames, do
  515. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  516. // i. If instantiatedVarNames does not contain n, then
  517. if (!parameter_names.contains(id.string()) && instantiated_var_names.set(id.string()) == AK::HashSetResult::InsertedNewEntry) {
  518. // 1. Append n to instantiatedVarNames.
  519. // 2. Perform ! env.CreateMutableBinding(n, false).
  520. // 3. Perform ! env.InitializeBinding(n, undefined).
  521. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  522. callee_context.local_variables[id.local_variable_index()] = js_undefined();
  523. } else {
  524. MUST(environment->create_mutable_binding(vm, id.string(), false));
  525. MUST(environment->initialize_binding(vm, id.string(), js_undefined(), Environment::InitializeBindingHint::Normal));
  526. }
  527. }
  528. }));
  529. }
  530. // d.Let varEnv be env
  531. var_environment = environment;
  532. }
  533. // 28. Else,
  534. else {
  535. // a. NOTE: A separate Environment Record is needed to ensure that closures created by expressions in the formal parameter list do not have visibility of declarations in the function body.
  536. // b. Let varEnv be NewDeclarativeEnvironment(env).
  537. var_environment = new_declarative_environment(*environment);
  538. // c. Set the VariableEnvironment of calleeContext to varEnv.
  539. callee_context.variable_environment = var_environment;
  540. // d. Let instantiatedVarNames be a new empty List.
  541. // NOTE: Already done above.
  542. if (scope_body) {
  543. // NOTE: Due to the use of MUST with `create_mutable_binding`, `get_binding_value` and `initialize_binding` below,
  544. // an exception should not result from `for_each_var_declared_name`.
  545. // e. For each element n of varNames, do
  546. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  547. // i. If instantiatedVarNames does not contain n, then
  548. if (instantiated_var_names.set(id.string()) == AK::HashSetResult::InsertedNewEntry) {
  549. // 1. Append n to instantiatedVarNames.
  550. // 2. Perform ! varEnv.CreateMutableBinding(n, false).
  551. MUST(var_environment->create_mutable_binding(vm, id.string(), false));
  552. Value initial_value;
  553. // 3. If parameterBindings does not contain n, or if functionNames contains n, then
  554. if (!parameter_names.contains(id.string()) || function_names.contains(id.string())) {
  555. // a. Let initialValue be undefined.
  556. initial_value = js_undefined();
  557. }
  558. // 4. Else,
  559. else {
  560. // a. Let initialValue be ! env.GetBindingValue(n, false).
  561. initial_value = MUST(environment->get_binding_value(vm, id.string(), false));
  562. }
  563. // 5. Perform ! varEnv.InitializeBinding(n, initialValue).
  564. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  565. // NOTE: Local variables are supported only in bytecode interpreter
  566. callee_context.local_variables[id.local_variable_index()] = initial_value;
  567. } else {
  568. MUST(var_environment->initialize_binding(vm, id.string(), initial_value, Environment::InitializeBindingHint::Normal));
  569. }
  570. // 6. NOTE: A var with the same name as a formal parameter initially has the same value as the corresponding initialized parameter.
  571. }
  572. }));
  573. }
  574. }
  575. // 29. NOTE: Annex B.3.2.1 adds additional steps at this point.
  576. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  577. if (!strict && scope_body) {
  578. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  579. // an exception should not result from `for_each_function_hoistable_with_annexB_extension`.
  580. MUST(scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  581. auto function_name = function_declaration.name();
  582. if (parameter_names.contains(function_name))
  583. return;
  584. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  585. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  586. MUST(var_environment->create_mutable_binding(vm, function_name, false));
  587. MUST(var_environment->initialize_binding(vm, function_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  588. instantiated_var_names.set(function_name);
  589. }
  590. function_declaration.set_should_do_additional_annexB_steps();
  591. }));
  592. }
  593. GCPtr<Environment> lex_environment;
  594. // 30. If strict is false, then
  595. if (!strict) {
  596. // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true:
  597. // 1. there is no direct call to eval() within this function
  598. // 2. there are no lexical declarations that would go into the environment
  599. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  600. if (can_elide_declarative_environment) {
  601. lex_environment = var_environment;
  602. } else {
  603. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  604. // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval
  605. // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level
  606. // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places
  607. // all declarations into a new Environment Record.
  608. lex_environment = new_declarative_environment(*var_environment);
  609. }
  610. }
  611. // 31. Else,
  612. else {
  613. // a. let lexEnv be varEnv.
  614. lex_environment = var_environment;
  615. }
  616. // 32. Set the LexicalEnvironment of calleeContext to lexEnv.
  617. callee_context.lexical_environment = lex_environment;
  618. if (!scope_body)
  619. return {};
  620. // 33. Let lexDeclarations be the LexicallyScopedDeclarations of code.
  621. // 34. For each element d of lexDeclarations, do
  622. // NOTE: Due to the use of MUST in the callback, an exception should not result from `for_each_lexically_scoped_declaration`.
  623. MUST(scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  624. // NOTE: Due to the use of MUST with `create_immutable_binding` and `create_mutable_binding` below,
  625. // an exception should not result from `for_each_bound_name`.
  626. // a. NOTE: A lexically declared name cannot be the same as a function/generator declaration, formal parameter, or a var name. Lexically declared names are only instantiated here but not initialized.
  627. // b. For each element dn of the BoundNames of d, do
  628. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  629. if (vm.bytecode_interpreter_if_exists() && id.is_local()) {
  630. // NOTE: Local variables are supported only in bytecode interpreter
  631. return;
  632. }
  633. // i. If IsConstantDeclaration of d is true, then
  634. if (declaration.is_constant_declaration()) {
  635. // 1. Perform ! lexEnv.CreateImmutableBinding(dn, true).
  636. MUST(lex_environment->create_immutable_binding(vm, id.string(), true));
  637. }
  638. // ii. Else,
  639. else {
  640. // 1. Perform ! lexEnv.CreateMutableBinding(dn, false).
  641. MUST(lex_environment->create_mutable_binding(vm, id.string(), false));
  642. }
  643. }));
  644. }));
  645. // 35. Let privateEnv be the PrivateEnvironment of calleeContext.
  646. auto private_environment = callee_context.private_environment;
  647. // 36. For each Parse Node f of functionsToInitialize, do
  648. for (auto& declaration : functions_to_initialize) {
  649. // a. Let fn be the sole element of the BoundNames of f.
  650. // b. Let fo be InstantiateFunctionObject of f with arguments lexEnv and privateEnv.
  651. 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());
  652. // c. Perform ! varEnv.SetMutableBinding(fn, fo, false).
  653. if ((vm.bytecode_interpreter_if_exists() || kind() == FunctionKind::Generator || kind() == FunctionKind::AsyncGenerator) && declaration.name_identifier()->is_local()) {
  654. callee_context.local_variables[declaration.name_identifier()->local_variable_index()] = function;
  655. } else {
  656. MUST(var_environment->set_mutable_binding(vm, declaration.name(), function, false));
  657. }
  658. }
  659. if (is<DeclarativeEnvironment>(*lex_environment))
  660. static_cast<DeclarativeEnvironment*>(lex_environment.ptr())->shrink_to_fit();
  661. if (is<DeclarativeEnvironment>(*var_environment))
  662. static_cast<DeclarativeEnvironment*>(var_environment.ptr())->shrink_to_fit();
  663. // 37. Return unused.
  664. return {};
  665. }
  666. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  667. ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  668. {
  669. auto& vm = this->vm();
  670. // Non-standard
  671. callee_context.is_strict_mode = m_strict;
  672. // 1. Let callerContext be the running execution context.
  673. // 2. Let calleeContext be a new ECMAScript code execution context.
  674. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  675. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  676. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  677. // 3. Set the Function of calleeContext to F.
  678. callee_context.function = this;
  679. callee_context.function_name = m_name;
  680. // 4. Let calleeRealm be F.[[Realm]].
  681. auto callee_realm = m_realm;
  682. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  683. // every function has a realm - especially in LibWeb that's sometimes not the case
  684. // when a function is created while no JS is running, as we currently need to rely on
  685. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  686. // If there's no 'current realm' either, we can't continue and crash.
  687. if (!callee_realm)
  688. callee_realm = vm.current_realm();
  689. VERIFY(callee_realm);
  690. // 5. Set the Realm of calleeContext to calleeRealm.
  691. callee_context.realm = callee_realm;
  692. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  693. callee_context.script_or_module = m_script_or_module;
  694. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  695. auto local_environment = new_function_environment(*this, new_target);
  696. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  697. callee_context.lexical_environment = local_environment;
  698. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  699. callee_context.variable_environment = local_environment;
  700. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  701. callee_context.private_environment = m_private_environment;
  702. // 11. If callerContext is not already suspended, suspend callerContext.
  703. // FIXME: We don't have this concept yet.
  704. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  705. TRY(vm.push_execution_context(callee_context, {}));
  706. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  707. // 14. Return calleeContext.
  708. // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack.
  709. return {};
  710. }
  711. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  712. void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument)
  713. {
  714. auto& vm = this->vm();
  715. // 1. Let thisMode be F.[[ThisMode]].
  716. auto this_mode = m_this_mode;
  717. // If thisMode is lexical, return unused.
  718. if (this_mode == ThisMode::Lexical)
  719. return;
  720. // 3. Let calleeRealm be F.[[Realm]].
  721. auto callee_realm = m_realm;
  722. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  723. // every function has a realm - especially in LibWeb that's sometimes not the case
  724. // when a function is created while no JS is running, as we currently need to rely on
  725. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  726. // If there's no 'current realm' either, we can't continue and crash.
  727. if (!callee_realm)
  728. callee_realm = vm.current_realm();
  729. VERIFY(callee_realm);
  730. // 4. Let localEnv be the LexicalEnvironment of calleeContext.
  731. auto local_env = callee_context.lexical_environment;
  732. Value this_value;
  733. // 5. If thisMode is strict, let thisValue be thisArgument.
  734. if (this_mode == ThisMode::Strict) {
  735. this_value = this_argument;
  736. }
  737. // 6. Else,
  738. else {
  739. // a. If thisArgument is undefined or null, then
  740. if (this_argument.is_nullish()) {
  741. // i. Let globalEnv be calleeRealm.[[GlobalEnv]].
  742. // ii. Assert: globalEnv is a global Environment Record.
  743. auto& global_env = callee_realm->global_environment();
  744. // iii. Let thisValue be globalEnv.[[GlobalThisValue]].
  745. this_value = &global_env.global_this_value();
  746. }
  747. // b. Else,
  748. else {
  749. // i. Let thisValue be ! ToObject(thisArgument).
  750. this_value = MUST(this_argument.to_object(vm));
  751. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
  752. VERIFY(vm.current_realm() == callee_realm);
  753. }
  754. }
  755. // 7. Assert: localEnv is a function Environment Record.
  756. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
  757. // 9. Perform ! localEnv.BindThisValue(thisValue).
  758. MUST(verify_cast<FunctionEnvironment>(*local_env).bind_this_value(vm, this_value));
  759. // 10. Return unused.
  760. }
  761. // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  762. template<typename T>
  763. void async_function_start(VM& vm, PromiseCapability const& promise_capability, T const& async_function_body)
  764. {
  765. // 1. Let runningContext be the running execution context.
  766. auto& running_context = vm.running_execution_context();
  767. // 2. Let asyncContext be a copy of runningContext.
  768. auto async_context = running_context.copy();
  769. // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context.
  770. // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext).
  771. async_block_start(vm, async_function_body, promise_capability, async_context);
  772. // 5. Return unused.
  773. }
  774. // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart
  775. // 12.7.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-explicit-resource-management/#sec-asyncblockstart
  776. // 1.2.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-array-from-async/#sec-asyncblockstart
  777. template<typename T>
  778. void async_block_start(VM& vm, T const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context)
  779. {
  780. // NOTE: This function is a combination between two proposals, so does not exactly match spec steps of either.
  781. auto& realm = *vm.current_realm();
  782. // 1. Assert: promiseCapability is a PromiseCapability Record.
  783. // 2. Let runningContext be the running execution context.
  784. auto& running_context = vm.running_execution_context();
  785. // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
  786. auto execution_steps = NativeFunction::create(realm, "", [&realm, &async_body, &promise_capability, &async_context](auto& vm) -> ThrowCompletionOr<Value> {
  787. Completion result;
  788. // a. If asyncBody is a Parse Node, then
  789. if constexpr (!IsCallableWithArguments<T, Completion>) {
  790. // a. Let result be the result of evaluating asyncBody.
  791. if (auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists()) {
  792. // FIXME: Cache this executable somewhere.
  793. auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"sv);
  794. if (maybe_executable.is_error())
  795. result = maybe_executable.release_error();
  796. else
  797. result = bytecode_interpreter->run_and_return_frame(realm, *maybe_executable.value(), nullptr).value;
  798. } else {
  799. result = async_body->execute(vm.interpreter());
  800. }
  801. }
  802. // b. Else,
  803. else {
  804. (void)realm;
  805. // i. Assert: asyncBody is an Abstract Closure with no parameters.
  806. static_assert(IsCallableWithArguments<T, Completion>);
  807. // ii. Let result be asyncBody().
  808. result = async_body();
  809. }
  810. // c. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
  811. // 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.
  812. vm.pop_execution_context();
  813. // NOTE: This does not work for Array.fromAsync, likely due to conflicts between that proposal and Explicit Resource Management proposal.
  814. if constexpr (!IsCallableWithArguments<T, Completion>) {
  815. // e. Let env be asyncContext's LexicalEnvironment.
  816. auto env = async_context.lexical_environment;
  817. // f. Set result to DisposeResources(env, result).
  818. result = dispose_resources(vm, verify_cast<DeclarativeEnvironment>(env.ptr()), result);
  819. } else {
  820. (void)async_context;
  821. }
  822. // g. If result.[[Type]] is normal, then
  823. if (result.type() == Completion::Type::Normal) {
  824. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
  825. MUST(call(vm, *promise_capability.resolve(), js_undefined(), js_undefined()));
  826. }
  827. // h. Else if result.[[Type]] is return, then
  828. else if (result.type() == Completion::Type::Return) {
  829. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
  830. MUST(call(vm, *promise_capability.resolve(), js_undefined(), *result.value()));
  831. }
  832. // i. Else,
  833. else {
  834. // i. Assert: result.[[Type]] is throw.
  835. VERIFY(result.type() == Completion::Type::Throw);
  836. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
  837. MUST(call(vm, *promise_capability.reject(), js_undefined(), *result.value()));
  838. }
  839. // j. Return unused.
  840. // NOTE: We don't support returning an empty/optional/unused value here.
  841. return js_undefined();
  842. });
  843. // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  844. auto push_result = vm.push_execution_context(async_context, {});
  845. if (push_result.is_error())
  846. return;
  847. // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  848. auto result = call(vm, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value);
  849. // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  850. VERIFY(&vm.running_execution_context() == &running_context);
  851. // 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.
  852. VERIFY(result.has_value() && result.value().is_undefined());
  853. // 8. Return unused.
  854. }
  855. template void async_block_start(VM&, NonnullGCPtr<Statement const> const& async_body, PromiseCapability const&, ExecutionContext&);
  856. template void async_function_start(VM&, PromiseCapability const&, NonnullGCPtr<Statement const> const& async_function_body);
  857. template void async_block_start(VM&, SafeFunction<Completion()> const& async_body, PromiseCapability const&, ExecutionContext&);
  858. template void async_function_start(VM&, PromiseCapability const&, SafeFunction<Completion()> const& async_function_body);
  859. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  860. // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  861. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  862. {
  863. auto& vm = this->vm();
  864. auto& realm = *vm.current_realm();
  865. auto* bytecode_interpreter = vm.bytecode_interpreter_if_exists();
  866. // The bytecode interpreter can execute generator functions while the AST interpreter cannot.
  867. // This simply makes it create a new bytecode interpreter when one doesn't exist when executing a generator function.
  868. // Doing so makes it automatically switch to the bytecode interpreter to execute any future code until it exits the generator. See below.
  869. // This allows us to keep all of the existing functionality that works in AST while adding generator support on top of it.
  870. // However, this does cause an awkward situation with features not supported in bytecode, where features that work outside of generators with AST
  871. // suddenly stop working inside of generators.
  872. // This is a stop gap until bytecode mode becomes the default.
  873. if ((m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator) && !bytecode_interpreter) {
  874. bytecode_interpreter = &vm.bytecode_interpreter();
  875. }
  876. if (bytecode_interpreter) {
  877. // NOTE: There's a subtle ordering issue here:
  878. // - We have to compile the default parameter values before instantiating the function.
  879. // - We have to instantiate the function before compiling the function body.
  880. // This is why FunctionDeclarationInstantiation is invoked in the middle.
  881. // The issue is that FunctionDeclarationInstantiation may mark certain functions as hoisted
  882. // per Annex B. This affects code generation for FunctionDeclaration nodes.
  883. if (!m_bytecode_executable) {
  884. size_t default_parameter_index = 0;
  885. for (auto& parameter : m_formal_parameters) {
  886. if (!parameter.default_value)
  887. continue;
  888. auto executable = TRY(Bytecode::compile(vm, *parameter.default_value, FunctionKind::Normal, DeprecatedString::formatted("default parameter #{} for {}", default_parameter_index, m_name)));
  889. m_default_parameter_bytecode_executables.append(move(executable));
  890. }
  891. }
  892. auto declaration_result = function_declaration_instantiation(nullptr);
  893. if (m_kind == FunctionKind::Normal || m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator) {
  894. if (declaration_result.is_error())
  895. return declaration_result.release_error();
  896. }
  897. if (!m_bytecode_executable)
  898. m_bytecode_executable = TRY(Bytecode::compile(vm, *m_ecmascript_code, m_kind, m_name));
  899. if (m_kind == FunctionKind::Async) {
  900. if (declaration_result.is_throw_completion()) {
  901. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  902. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  903. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  904. }
  905. }
  906. auto result_and_frame = bytecode_interpreter->run_and_return_frame(realm, *m_bytecode_executable, nullptr);
  907. VERIFY(result_and_frame.frame != nullptr);
  908. if (result_and_frame.value.is_error())
  909. return result_and_frame.value.release_error();
  910. auto result = result_and_frame.value.release_value();
  911. // NOTE: Running the bytecode should eventually return a completion.
  912. // Until it does, we assume "return" and include the undefined fallback from the call site.
  913. if (m_kind == FunctionKind::Normal)
  914. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  915. if (m_kind == FunctionKind::AsyncGenerator) {
  916. auto async_generator_object = TRY(AsyncGenerator::create(realm, result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame)));
  917. return { Completion::Type::Return, async_generator_object, {} };
  918. }
  919. auto generator_object = TRY(GeneratorObject::create(realm, result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame)));
  920. // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise
  921. // See AwaitExpression::generate_bytecode() for the transformation.
  922. if (m_kind == FunctionKind::Async)
  923. return { Completion::Type::Return, TRY(AsyncFunctionDriverWrapper::create(realm, generator_object)), {} };
  924. VERIFY(m_kind == FunctionKind::Generator);
  925. return { Completion::Type::Return, generator_object, {} };
  926. } else {
  927. if (m_kind == FunctionKind::Generator)
  928. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Generator function execution in AST interpreter");
  929. if (m_kind == FunctionKind::AsyncGenerator)
  930. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Async generator function execution in AST interpreter");
  931. OwnPtr<Interpreter> local_interpreter;
  932. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  933. if (!ast_interpreter) {
  934. local_interpreter = Interpreter::create_with_existing_realm(realm);
  935. ast_interpreter = local_interpreter.ptr();
  936. }
  937. VM::InterpreterExecutionScope scope(*ast_interpreter);
  938. // FunctionBody : FunctionStatementList
  939. if (m_kind == FunctionKind::Normal) {
  940. // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
  941. TRY(function_declaration_instantiation(ast_interpreter));
  942. // 2. Let result be result of evaluating FunctionStatementList.
  943. auto result = m_ecmascript_code->execute(*ast_interpreter);
  944. // 3. Let env be the running execution context's LexicalEnvironment.
  945. auto env = vm.running_execution_context().lexical_environment;
  946. VERIFY(is<DeclarativeEnvironment>(*env));
  947. // 4. Return ? DisposeResources(env, result).
  948. return dispose_resources(vm, static_cast<DeclarativeEnvironment*>(env.ptr()), result);
  949. }
  950. // AsyncFunctionBody : FunctionBody
  951. else if (m_kind == FunctionKind::Async) {
  952. // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  953. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  954. // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)).
  955. auto declaration_result = function_declaration_instantiation(ast_interpreter);
  956. // 3. If declResult is an abrupt completion, then
  957. if (declaration_result.is_throw_completion()) {
  958. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « declResult.[[Value]] »).
  959. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  960. }
  961. // 4. Else,
  962. else {
  963. // a. Perform AsyncFunctionStart(promiseCapability, FunctionBody).
  964. async_function_start(vm, promise_capability, m_ecmascript_code);
  965. }
  966. // 5. Return Completion Record { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
  967. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  968. }
  969. }
  970. VERIFY_NOT_REACHED();
  971. }
  972. void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name)
  973. {
  974. VERIFY(!name.is_null());
  975. auto& vm = this->vm();
  976. m_name = name;
  977. MUST(define_property_or_throw(vm.names.name, { .value = PrimitiveString::create(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  978. }
  979. }