ECMAScriptFunctionObject.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  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 <andreas@ladybird.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/Runtime/AbstractOperations.h>
  16. #include <LibJS/Runtime/Array.h>
  17. #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h>
  18. #include <LibJS/Runtime/AsyncGenerator.h>
  19. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  20. #include <LibJS/Runtime/Error.h>
  21. #include <LibJS/Runtime/ExecutionContext.h>
  22. #include <LibJS/Runtime/FunctionEnvironment.h>
  23. #include <LibJS/Runtime/GeneratorObject.h>
  24. #include <LibJS/Runtime/GlobalEnvironment.h>
  25. #include <LibJS/Runtime/GlobalObject.h>
  26. #include <LibJS/Runtime/NativeFunction.h>
  27. #include <LibJS/Runtime/PromiseCapability.h>
  28. #include <LibJS/Runtime/PromiseConstructor.h>
  29. #include <LibJS/Runtime/Value.h>
  30. namespace JS {
  31. JS_DEFINE_ALLOCATOR(ECMAScriptFunctionObject);
  32. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, ByteString 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, FunctionParsingInsights parsing_insights, 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.create<ECMAScriptFunctionObject>(move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, *prototype, kind, is_strict, parsing_insights, is_arrow_function, move(class_field_initializer_name));
  50. }
  51. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, Object& prototype, ByteString 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, FunctionParsingInsights parsing_insights, bool is_arrow_function, Variant<PropertyKey, PrivateName, Empty> class_field_initializer_name)
  52. {
  53. return realm.create<ECMAScriptFunctionObject>(move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, move(local_variables_names), parent_environment, private_environment, prototype, kind, is_strict, parsing_insights, is_arrow_function, move(class_field_initializer_name));
  54. }
  55. ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, ByteString 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, FunctionParsingInsights parsing_insights, 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(parsing_insights.might_need_arguments_object)
  69. , m_contains_direct_call_to_eval(parsing_insights.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. // NOTE: The following steps are from FunctionDeclarationInstantiation that could be executed once
  96. // and then reused in all subsequent function instantiations.
  97. // 2. Let code be func.[[ECMAScriptCode]].
  98. ScopeNode const* scope_body = nullptr;
  99. if (is<ScopeNode>(*m_ecmascript_code))
  100. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  101. // 3. Let strict be func.[[Strict]].
  102. // 4. Let formals be func.[[FormalParameters]].
  103. auto const& formals = m_formal_parameters;
  104. // 5. Let parameterNames be the BoundNames of formals.
  105. // 6. If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false.
  106. size_t parameters_in_environment = 0;
  107. // NOTE: This loop performs step 5, 6, and 8.
  108. for (auto const& parameter : formals) {
  109. if (parameter.default_value)
  110. m_has_parameter_expressions = true;
  111. parameter.binding.visit(
  112. [&](Identifier const& identifier) {
  113. if (m_parameter_names.set(identifier.string(), identifier.is_local() ? ParameterIsLocal::Yes : ParameterIsLocal::No) != AK::HashSetResult::InsertedNewEntry)
  114. m_has_duplicates = true;
  115. else if (!identifier.is_local())
  116. ++parameters_in_environment;
  117. },
  118. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  119. if (pattern->contains_expression())
  120. m_has_parameter_expressions = true;
  121. // NOTE: Nothing in the callback throws an exception.
  122. MUST(pattern->for_each_bound_identifier([&](auto& identifier) {
  123. if (m_parameter_names.set(identifier.string(), identifier.is_local() ? ParameterIsLocal::Yes : ParameterIsLocal::No) != AK::HashSetResult::InsertedNewEntry)
  124. m_has_duplicates = true;
  125. else if (!identifier.is_local())
  126. ++parameters_in_environment;
  127. }));
  128. });
  129. }
  130. // 15. Let argumentsObjectNeeded be true.
  131. m_arguments_object_needed = m_might_need_arguments_object;
  132. // 16. If func.[[ThisMode]] is lexical, then
  133. if (this_mode() == ThisMode::Lexical) {
  134. // a. NOTE: Arrow functions never have an arguments object.
  135. // b. Set argumentsObjectNeeded to false.
  136. m_arguments_object_needed = false;
  137. }
  138. // 17. Else if parameterNames contains "arguments", then
  139. else if (m_parameter_names.contains(vm().names.arguments.as_string())) {
  140. // a. Set argumentsObjectNeeded to false.
  141. m_arguments_object_needed = false;
  142. }
  143. HashTable<DeprecatedFlyString> function_names;
  144. // 18. Else if hasParameterExpressions is false, then
  145. // a. If functionNames contains "arguments" or lexicalNames contains "arguments", then
  146. // i. Set argumentsObjectNeeded to false.
  147. // NOTE: The block below is a combination of step 14 and step 18.
  148. if (scope_body) {
  149. // NOTE: Nothing in the callback throws an exception.
  150. MUST(scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  151. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  152. m_functions_to_initialize.append(function);
  153. }));
  154. auto const& arguments_name = vm().names.arguments.as_string();
  155. if (!m_has_parameter_expressions && function_names.contains(arguments_name))
  156. m_arguments_object_needed = false;
  157. if (!m_has_parameter_expressions && m_arguments_object_needed) {
  158. // NOTE: Nothing in the callback throws an exception.
  159. MUST(scope_body->for_each_lexically_declared_identifier([&](auto const& identifier) {
  160. if (identifier.string() == arguments_name)
  161. m_arguments_object_needed = false;
  162. }));
  163. }
  164. } else {
  165. m_arguments_object_needed = false;
  166. }
  167. size_t* environment_size = nullptr;
  168. size_t parameter_environment_bindings_count = 0;
  169. // 19. If strict is true or hasParameterExpressions is false, then
  170. if (m_strict || !m_has_parameter_expressions) {
  171. // 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.
  172. // b. Let env be the LexicalEnvironment of calleeContext
  173. // NOTE: Here we are only interested in the size of the environment.
  174. environment_size = &m_function_environment_bindings_count;
  175. }
  176. // 20. Else,
  177. else {
  178. // 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.
  179. // b. Let calleeEnv be the LexicalEnvironment of calleeContext.
  180. // c. Let env be NewDeclarativeEnvironment(calleeEnv).
  181. environment_size = &parameter_environment_bindings_count;
  182. }
  183. *environment_size += parameters_in_environment;
  184. HashMap<DeprecatedFlyString, ParameterIsLocal> parameter_bindings;
  185. auto arguments_object_needs_binding = m_arguments_object_needed && !m_local_variables_names.contains_slow(vm().names.arguments.as_string());
  186. // 22. If argumentsObjectNeeded is true, then
  187. if (m_arguments_object_needed) {
  188. // f. Let parameterBindings be the list-concatenation of parameterNames and « "arguments" ».
  189. parameter_bindings = m_parameter_names;
  190. parameter_bindings.set(vm().names.arguments.as_string(), ParameterIsLocal::No);
  191. if (arguments_object_needs_binding)
  192. (*environment_size)++;
  193. } else {
  194. parameter_bindings = m_parameter_names;
  195. // a. Let parameterBindings be parameterNames.
  196. }
  197. HashMap<DeprecatedFlyString, ParameterIsLocal> instantiated_var_names;
  198. size_t* var_environment_size = nullptr;
  199. // 27. If hasParameterExpressions is false, then
  200. if (!m_has_parameter_expressions) {
  201. // b. Let instantiatedVarNames be a copy of the List parameterBindings.
  202. instantiated_var_names = parameter_bindings;
  203. if (scope_body) {
  204. // c. For each element n of varNames, do
  205. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  206. // i. If instantiatedVarNames does not contain n, then
  207. if (instantiated_var_names.set(id.string(), id.is_local() ? ParameterIsLocal::Yes : ParameterIsLocal::No) == AK::HashSetResult::InsertedNewEntry) {
  208. // 1. Append n to instantiatedVarNames.
  209. // Following steps will be executed in function_declaration_instantiation:
  210. // 2. Perform ! env.CreateMutableBinding(n, false).
  211. // 3. Perform ! env.InitializeBinding(n, undefined).
  212. m_var_names_to_initialize_binding.append({
  213. .identifier = id,
  214. .parameter_binding = parameter_bindings.contains(id.string()),
  215. .function_name = function_names.contains(id.string()),
  216. });
  217. if (!id.is_local())
  218. (*environment_size)++;
  219. }
  220. }));
  221. }
  222. // d. Let varEnv be env
  223. var_environment_size = environment_size;
  224. } else {
  225. // 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.
  226. // b. Let varEnv be NewDeclarativeEnvironment(env).
  227. // NOTE: Here we are only interested in the size of the environment.
  228. var_environment_size = &m_var_environment_bindings_count;
  229. // 28. Else,
  230. // NOTE: Steps a, b, c and d are executed in function_declaration_instantiation.
  231. // e. For each element n of varNames, do
  232. if (scope_body) {
  233. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  234. // 1. Append n to instantiatedVarNames.
  235. // Following steps will be executed in function_declaration_instantiation:
  236. // 2. Perform ! env.CreateMutableBinding(n, false).
  237. // 3. Perform ! env.InitializeBinding(n, undefined).
  238. if (instantiated_var_names.set(id.string(), id.is_local() ? ParameterIsLocal::Yes : ParameterIsLocal::No) == AK::HashSetResult::InsertedNewEntry) {
  239. m_var_names_to_initialize_binding.append({
  240. .identifier = id,
  241. .parameter_binding = parameter_bindings.contains(id.string()),
  242. .function_name = function_names.contains(id.string()),
  243. });
  244. if (!id.is_local())
  245. (*var_environment_size)++;
  246. }
  247. }));
  248. }
  249. }
  250. // 29. NOTE: Annex B.3.2.1 adds additional steps at this point.
  251. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  252. if (!m_strict && scope_body) {
  253. MUST(scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  254. auto function_name = function_declaration.name();
  255. if (parameter_bindings.contains(function_name))
  256. return;
  257. if (!instantiated_var_names.contains(function_name) && function_name != vm().names.arguments.as_string()) {
  258. m_function_names_to_initialize_binding.append(function_name);
  259. instantiated_var_names.set(function_name, ParameterIsLocal::No);
  260. (*var_environment_size)++;
  261. }
  262. function_declaration.set_should_do_additional_annexB_steps();
  263. }));
  264. }
  265. size_t* lex_environment_size = nullptr;
  266. // 30. If strict is false, then
  267. if (!m_strict) {
  268. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_non_local_lexical_declarations());
  269. if (can_elide_declarative_environment) {
  270. lex_environment_size = var_environment_size;
  271. } else {
  272. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  273. lex_environment_size = &m_lex_environment_bindings_count;
  274. }
  275. } else {
  276. // a. let lexEnv be varEnv.
  277. // NOTE: Here we are only interested in the size of the environment.
  278. lex_environment_size = var_environment_size;
  279. }
  280. if (scope_body) {
  281. MUST(scope_body->for_each_lexically_declared_identifier([&](auto const& id) {
  282. if (!id.is_local())
  283. (*lex_environment_size)++;
  284. }));
  285. }
  286. m_function_environment_needed = arguments_object_needs_binding || m_function_environment_bindings_count > 0 || m_var_environment_bindings_count > 0 || m_lex_environment_bindings_count > 0 || parsing_insights.uses_this_from_environment || m_contains_direct_call_to_eval;
  287. m_uses_this = parsing_insights.uses_this;
  288. }
  289. void ECMAScriptFunctionObject::initialize(Realm& realm)
  290. {
  291. auto& vm = this->vm();
  292. Base::initialize(realm);
  293. // Note: The ordering of these properties must be: length, name, prototype which is the order
  294. // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances .
  295. // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
  296. // which must give the properties in chronological order which in this case is the order they
  297. // are defined in the spec.
  298. m_name_string = PrimitiveString::create(vm, m_name);
  299. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true }));
  300. MUST(define_property_or_throw(vm.names.name, { .value = m_name_string, .writable = false, .enumerable = false, .configurable = true }));
  301. if (!m_is_arrow_function) {
  302. Object* prototype = nullptr;
  303. switch (m_kind) {
  304. case FunctionKind::Normal:
  305. prototype = Object::create_prototype(realm, realm.intrinsics().object_prototype());
  306. MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true }));
  307. break;
  308. case FunctionKind::Generator:
  309. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  310. prototype = Object::create_prototype(realm, realm.intrinsics().generator_function_prototype_prototype());
  311. break;
  312. case FunctionKind::Async:
  313. break;
  314. case FunctionKind::AsyncGenerator:
  315. prototype = Object::create_prototype(realm, realm.intrinsics().async_generator_function_prototype_prototype());
  316. break;
  317. }
  318. // 27.7.4 AsyncFunction Instances, https://tc39.es/ecma262/#sec-async-function-instances
  319. // AsyncFunction instances do not have a prototype property as they are not constructible.
  320. if (m_kind != FunctionKind::Async)
  321. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  322. }
  323. }
  324. // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  325. ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, ReadonlySpan<Value> arguments_list)
  326. {
  327. auto& vm = this->vm();
  328. // 1. Let callerContext be the running execution context.
  329. // NOTE: No-op, kept by the VM in its execution context stack.
  330. auto callee_context = ExecutionContext::create();
  331. // Non-standard
  332. callee_context->arguments.ensure_capacity(max(arguments_list.size(), m_formal_parameters.size()));
  333. callee_context->arguments.append(arguments_list.data(), arguments_list.size());
  334. callee_context->passed_argument_count = arguments_list.size();
  335. if (arguments_list.size() < m_formal_parameters.size()) {
  336. for (size_t i = arguments_list.size(); i < m_formal_parameters.size(); ++i)
  337. callee_context->arguments.append(js_undefined());
  338. }
  339. // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
  340. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  341. TRY(prepare_for_ordinary_call(*callee_context, nullptr));
  342. // 3. Assert: calleeContext is now the running execution context.
  343. VERIFY(&vm.running_execution_context() == callee_context);
  344. // 4. If F.[[IsClassConstructor]] is true, then
  345. if (m_is_class_constructor) {
  346. // a. Let error be a newly created TypeError object.
  347. // b. NOTE: error is created in calleeContext with F's associated Realm Record.
  348. auto throw_completion = vm.throw_completion<TypeError>(ErrorType::ClassConstructorWithoutNew, m_name);
  349. // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  350. vm.pop_execution_context();
  351. // d. Return ThrowCompletion(error).
  352. return throw_completion;
  353. }
  354. // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  355. if (m_uses_this)
  356. ordinary_call_bind_this(*callee_context, this_argument);
  357. // 6. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  358. auto result = ordinary_call_evaluate_body();
  359. // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  360. vm.pop_execution_context();
  361. // 8. If result.[[Type]] is return, return result.[[Value]].
  362. if (result.type() == Completion::Type::Return)
  363. return *result.value();
  364. // 9. ReturnIfAbrupt(result).
  365. if (result.is_abrupt()) {
  366. VERIFY(result.is_error());
  367. return result;
  368. }
  369. // 10. Return undefined.
  370. return js_undefined();
  371. }
  372. // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget
  373. ThrowCompletionOr<NonnullGCPtr<Object>> ECMAScriptFunctionObject::internal_construct(ReadonlySpan<Value> arguments_list, FunctionObject& new_target)
  374. {
  375. auto& vm = this->vm();
  376. // 1. Let callerContext be the running execution context.
  377. // NOTE: No-op, kept by the VM in its execution context stack.
  378. // 2. Let kind be F.[[ConstructorKind]].
  379. auto kind = m_constructor_kind;
  380. GCPtr<Object> this_argument;
  381. // 3. If kind is base, then
  382. if (kind == ConstructorKind::Base) {
  383. // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
  384. this_argument = TRY(ordinary_create_from_constructor<Object>(vm, new_target, &Intrinsics::object_prototype, ConstructWithPrototypeTag::Tag));
  385. }
  386. auto callee_context = ExecutionContext::create();
  387. // Non-standard
  388. callee_context->arguments.ensure_capacity(max(arguments_list.size(), m_formal_parameters.size()));
  389. callee_context->arguments.append(arguments_list.data(), arguments_list.size());
  390. callee_context->passed_argument_count = arguments_list.size();
  391. if (arguments_list.size() < m_formal_parameters.size()) {
  392. for (size_t i = arguments_list.size(); i < m_formal_parameters.size(); ++i)
  393. callee_context->arguments.append(js_undefined());
  394. }
  395. // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
  396. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  397. TRY(prepare_for_ordinary_call(*callee_context, &new_target));
  398. // 5. Assert: calleeContext is now the running execution context.
  399. VERIFY(&vm.running_execution_context() == callee_context);
  400. // 6. If kind is base, then
  401. if (kind == ConstructorKind::Base) {
  402. // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  403. if (m_uses_this)
  404. ordinary_call_bind_this(*callee_context, this_argument);
  405. // b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)).
  406. auto initialize_result = this_argument->initialize_instance_elements(*this);
  407. // c. If initializeResult is an abrupt completion, then
  408. if (initialize_result.is_throw_completion()) {
  409. // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  410. vm.pop_execution_context();
  411. // ii. Return ? initializeResult.
  412. return initialize_result.throw_completion();
  413. }
  414. }
  415. // 7. Let constructorEnv be the LexicalEnvironment of calleeContext.
  416. auto constructor_env = callee_context->lexical_environment;
  417. // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  418. auto result = ordinary_call_evaluate_body();
  419. // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  420. vm.pop_execution_context();
  421. // 10. If result.[[Type]] is return, then
  422. if (result.type() == Completion::Type::Return) {
  423. // a. If Type(result.[[Value]]) is Object, return result.[[Value]].
  424. if (result.value()->is_object())
  425. return result.value()->as_object();
  426. // b. If kind is base, return thisArgument.
  427. if (kind == ConstructorKind::Base)
  428. return *this_argument;
  429. // c. If result.[[Value]] is not undefined, throw a TypeError exception.
  430. if (!result.value()->is_undefined())
  431. return vm.throw_completion<TypeError>(ErrorType::DerivedConstructorReturningInvalidValue);
  432. }
  433. // 11. Else, ReturnIfAbrupt(result).
  434. else if (result.is_abrupt()) {
  435. VERIFY(result.is_error());
  436. return result;
  437. }
  438. // 12. Let thisBinding be ? constructorEnv.GetThisBinding().
  439. auto this_binding = TRY(constructor_env->get_this_binding(vm));
  440. // 13. Assert: Type(thisBinding) is Object.
  441. VERIFY(this_binding.is_object());
  442. // 14. Return thisBinding.
  443. return this_binding.as_object();
  444. }
  445. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  446. {
  447. Base::visit_edges(visitor);
  448. visitor.visit(m_environment);
  449. visitor.visit(m_private_environment);
  450. visitor.visit(m_realm);
  451. visitor.visit(m_home_object);
  452. visitor.visit(m_name_string);
  453. visitor.visit(m_bytecode_executable);
  454. for (auto& field : m_fields) {
  455. visitor.visit(field.initializer);
  456. if (auto* property_key_ptr = field.name.get_pointer<PropertyKey>(); property_key_ptr && property_key_ptr->is_symbol())
  457. visitor.visit(property_key_ptr->as_symbol());
  458. }
  459. for (auto& private_element : m_private_methods)
  460. visitor.visit(private_element.value);
  461. m_script_or_module.visit(
  462. [](Empty) {},
  463. [&](auto& script_or_module) {
  464. visitor.visit(script_or_module);
  465. });
  466. }
  467. // 10.2.7 MakeMethod ( F, homeObject ), https://tc39.es/ecma262/#sec-makemethod
  468. void ECMAScriptFunctionObject::make_method(Object& home_object)
  469. {
  470. // 1. Set F.[[HomeObject]] to homeObject.
  471. m_home_object = &home_object;
  472. // 2. Return unused.
  473. }
  474. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  475. ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  476. {
  477. auto& vm = this->vm();
  478. // Non-standard
  479. callee_context.is_strict_mode = m_strict;
  480. // 1. Let callerContext be the running execution context.
  481. // 2. Let calleeContext be a new ECMAScript code execution context.
  482. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  483. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  484. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  485. // 3. Set the Function of calleeContext to F.
  486. callee_context.function = this;
  487. callee_context.function_name = m_name_string;
  488. // 4. Let calleeRealm be F.[[Realm]].
  489. auto callee_realm = m_realm;
  490. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  491. // every function has a realm - especially in LibWeb that's sometimes not the case
  492. // when a function is created while no JS is running, as we currently need to rely on
  493. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  494. // If there's no 'current realm' either, we can't continue and crash.
  495. if (!callee_realm)
  496. callee_realm = vm.current_realm();
  497. VERIFY(callee_realm);
  498. // 5. Set the Realm of calleeContext to calleeRealm.
  499. callee_context.realm = callee_realm;
  500. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  501. callee_context.script_or_module = m_script_or_module;
  502. if (m_function_environment_needed) {
  503. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  504. auto local_environment = new_function_environment(*this, new_target);
  505. local_environment->ensure_capacity(m_function_environment_bindings_count);
  506. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  507. callee_context.lexical_environment = local_environment;
  508. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  509. callee_context.variable_environment = local_environment;
  510. } else {
  511. callee_context.lexical_environment = environment();
  512. callee_context.variable_environment = environment();
  513. }
  514. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  515. callee_context.private_environment = m_private_environment;
  516. // 11. If callerContext is not already suspended, suspend callerContext.
  517. // FIXME: We don't have this concept yet.
  518. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  519. TRY(vm.push_execution_context(callee_context, {}));
  520. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  521. // 14. Return calleeContext.
  522. // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack.
  523. return {};
  524. }
  525. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  526. void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument)
  527. {
  528. auto& vm = this->vm();
  529. // 1. Let thisMode be F.[[ThisMode]].
  530. auto this_mode = m_this_mode;
  531. // If thisMode is lexical, return unused.
  532. if (this_mode == ThisMode::Lexical)
  533. return;
  534. // 3. Let calleeRealm be F.[[Realm]].
  535. auto callee_realm = m_realm;
  536. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  537. // every function has a realm - especially in LibWeb that's sometimes not the case
  538. // when a function is created while no JS is running, as we currently need to rely on
  539. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  540. // If there's no 'current realm' either, we can't continue and crash.
  541. if (!callee_realm)
  542. callee_realm = vm.current_realm();
  543. VERIFY(callee_realm);
  544. // 4. Let localEnv be the LexicalEnvironment of calleeContext.
  545. auto local_env = callee_context.lexical_environment;
  546. Value this_value;
  547. // 5. If thisMode is strict, let thisValue be thisArgument.
  548. if (this_mode == ThisMode::Strict) {
  549. this_value = this_argument;
  550. }
  551. // 6. Else,
  552. else {
  553. // a. If thisArgument is undefined or null, then
  554. if (this_argument.is_nullish()) {
  555. // i. Let globalEnv be calleeRealm.[[GlobalEnv]].
  556. // ii. Assert: globalEnv is a global Environment Record.
  557. auto& global_env = callee_realm->global_environment();
  558. // iii. Let thisValue be globalEnv.[[GlobalThisValue]].
  559. this_value = &global_env.global_this_value();
  560. }
  561. // b. Else,
  562. else {
  563. // i. Let thisValue be ! ToObject(thisArgument).
  564. this_value = MUST(this_argument.to_object(vm));
  565. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
  566. VERIFY(vm.current_realm() == callee_realm);
  567. }
  568. }
  569. // 7. Assert: localEnv is a function Environment Record.
  570. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
  571. // 9. Perform ! localEnv.BindThisValue(thisValue).
  572. callee_context.this_value = this_value;
  573. if (m_function_environment_needed)
  574. MUST(verify_cast<FunctionEnvironment>(*local_env).bind_this_value(vm, this_value));
  575. // 10. Return unused.
  576. }
  577. // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  578. template<typename T>
  579. void async_function_start(VM& vm, PromiseCapability const& promise_capability, T const& async_function_body)
  580. {
  581. // 1. Let runningContext be the running execution context.
  582. auto& running_context = vm.running_execution_context();
  583. // 2. Let asyncContext be a copy of runningContext.
  584. auto async_context = running_context.copy();
  585. // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context.
  586. // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext).
  587. async_block_start(vm, async_function_body, promise_capability, *async_context);
  588. // 5. Return unused.
  589. }
  590. // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart
  591. // 12.7.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-explicit-resource-management/#sec-asyncblockstart
  592. // 1.2.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-array-from-async/#sec-asyncblockstart
  593. template<typename T>
  594. void async_block_start(VM& vm, T const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context)
  595. {
  596. // NOTE: This function is a combination between two proposals, so does not exactly match spec steps of either.
  597. auto& realm = *vm.current_realm();
  598. // 1. Assert: promiseCapability is a PromiseCapability Record.
  599. // 2. Let runningContext be the running execution context.
  600. auto& running_context = vm.running_execution_context();
  601. // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
  602. auto execution_steps = NativeFunction::create(realm, "", [&async_body, &promise_capability, &async_context](auto& vm) -> ThrowCompletionOr<Value> {
  603. Completion result;
  604. // a. If asyncBody is a Parse Node, then
  605. if constexpr (!IsSame<T, HeapFunction<Completion()>>) {
  606. // a. Let result be the result of evaluating asyncBody.
  607. // FIXME: Cache this executable somewhere.
  608. auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"sv);
  609. if (maybe_executable.is_error())
  610. result = maybe_executable.release_error();
  611. else
  612. result = vm.bytecode_interpreter().run_executable(*maybe_executable.value(), {}).value;
  613. }
  614. // b. Else,
  615. else {
  616. // i. Assert: asyncBody is an Abstract Closure with no parameters.
  617. // ii. Let result be asyncBody().
  618. result = async_body.function()();
  619. }
  620. // c. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
  621. // 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.
  622. vm.pop_execution_context();
  623. // NOTE: This does not work for Array.fromAsync, likely due to conflicts between that proposal and Explicit Resource Management proposal.
  624. if constexpr (!IsCallableWithArguments<T, Completion>) {
  625. // e. Let env be asyncContext's LexicalEnvironment.
  626. auto env = async_context.lexical_environment;
  627. // f. Set result to DisposeResources(env, result).
  628. result = dispose_resources(vm, verify_cast<DeclarativeEnvironment>(env.ptr()), result);
  629. } else {
  630. (void)async_context;
  631. }
  632. // g. If result.[[Type]] is normal, then
  633. if (result.type() == Completion::Type::Normal) {
  634. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
  635. MUST(call(vm, *promise_capability.resolve(), js_undefined(), js_undefined()));
  636. }
  637. // h. Else if result.[[Type]] is return, then
  638. else if (result.type() == Completion::Type::Return) {
  639. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
  640. MUST(call(vm, *promise_capability.resolve(), js_undefined(), *result.value()));
  641. }
  642. // i. Else,
  643. else {
  644. // i. Assert: result.[[Type]] is throw.
  645. VERIFY(result.type() == Completion::Type::Throw);
  646. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
  647. MUST(call(vm, *promise_capability.reject(), js_undefined(), *result.value()));
  648. }
  649. // j. Return unused.
  650. // NOTE: We don't support returning an empty/optional/unused value here.
  651. return js_undefined();
  652. });
  653. // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  654. auto push_result = vm.push_execution_context(async_context, {});
  655. if (push_result.is_error())
  656. return;
  657. // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  658. auto result = call(vm, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value);
  659. // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  660. VERIFY(&vm.running_execution_context() == &running_context);
  661. // 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.
  662. VERIFY(result.has_value() && result.value().is_undefined());
  663. // 8. Return unused.
  664. }
  665. template void async_block_start(VM&, NonnullRefPtr<Statement const> const& async_body, PromiseCapability const&, ExecutionContext&);
  666. template void async_function_start(VM&, PromiseCapability const&, NonnullRefPtr<Statement const> const& async_function_body);
  667. template void async_block_start(VM&, HeapFunction<Completion()> const& async_body, PromiseCapability const&, ExecutionContext&);
  668. template void async_function_start(VM&, PromiseCapability const&, HeapFunction<Completion()> const& async_function_body);
  669. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  670. // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  671. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  672. {
  673. auto& vm = this->vm();
  674. auto& realm = *vm.current_realm();
  675. if (!m_bytecode_executable) {
  676. if (!m_ecmascript_code->bytecode_executable()) {
  677. if (is_module_wrapper()) {
  678. const_cast<Statement&>(*m_ecmascript_code).set_bytecode_executable(TRY(Bytecode::compile(vm, *m_ecmascript_code, m_kind, m_name)));
  679. } else {
  680. const_cast<Statement&>(*m_ecmascript_code).set_bytecode_executable(TRY(Bytecode::compile(vm, *this)));
  681. }
  682. }
  683. m_bytecode_executable = m_ecmascript_code->bytecode_executable();
  684. }
  685. vm.running_execution_context().registers_and_constants_and_locals.resize(m_local_variables_names.size() + m_bytecode_executable->number_of_registers + m_bytecode_executable->constants.size());
  686. auto result_and_frame = vm.bytecode_interpreter().run_executable(*m_bytecode_executable, {});
  687. if (result_and_frame.value.is_error())
  688. return result_and_frame.value.release_error();
  689. auto result = result_and_frame.value.release_value();
  690. // NOTE: Running the bytecode should eventually return a completion.
  691. // Until it does, we assume "return" and include the undefined fallback from the call site.
  692. if (m_kind == FunctionKind::Normal)
  693. return { Completion::Type::Return, result.value_or(js_undefined()) };
  694. if (m_kind == FunctionKind::AsyncGenerator) {
  695. auto async_generator_object = TRY(AsyncGenerator::create(realm, result, this, vm.running_execution_context().copy()));
  696. return { Completion::Type::Return, async_generator_object };
  697. }
  698. auto generator_object = TRY(GeneratorObject::create(realm, result, this, vm.running_execution_context().copy()));
  699. // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise
  700. // See AwaitExpression::generate_bytecode() for the transformation.
  701. if (m_kind == FunctionKind::Async)
  702. return { Completion::Type::Return, AsyncFunctionDriverWrapper::create(realm, generator_object) };
  703. VERIFY(m_kind == FunctionKind::Generator);
  704. return { Completion::Type::Return, generator_object };
  705. }
  706. void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name)
  707. {
  708. auto& vm = this->vm();
  709. m_name = name;
  710. m_name_string = PrimitiveString::create(vm, m_name);
  711. MUST(define_property_or_throw(vm.names.name, { .value = m_name_string, .writable = false, .enumerable = false, .configurable = true }));
  712. }
  713. }