ECMAScriptFunctionObject.cpp 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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/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, 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));
  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));
  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. // 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. // NOTE: This loop performs step 5, 6, and 8.
  107. for (auto const& parameter : formals) {
  108. if (parameter.default_value)
  109. m_has_parameter_expressions = true;
  110. parameter.binding.visit(
  111. [&](Identifier const& identifier) {
  112. if (m_parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  113. m_has_duplicates = true;
  114. },
  115. [&](NonnullRefPtr<BindingPattern const> const& pattern) {
  116. if (pattern->contains_expression())
  117. m_has_parameter_expressions = true;
  118. // NOTE: Nothing in the callback throws an exception.
  119. MUST(pattern->for_each_bound_identifier([&](auto& identifier) {
  120. if (m_parameter_names.set(identifier.string()) != AK::HashSetResult::InsertedNewEntry)
  121. m_has_duplicates = true;
  122. }));
  123. });
  124. }
  125. // 15. Let argumentsObjectNeeded be true.
  126. m_arguments_object_needed = m_might_need_arguments_object;
  127. // 16. If func.[[ThisMode]] is lexical, then
  128. if (this_mode() == ThisMode::Lexical) {
  129. // a. NOTE: Arrow functions never have an arguments object.
  130. // b. Set argumentsObjectNeeded to false.
  131. m_arguments_object_needed = false;
  132. }
  133. // 17. Else if parameterNames contains "arguments", then
  134. else if (m_parameter_names.contains(vm().names.arguments.as_string())) {
  135. // a. Set argumentsObjectNeeded to false.
  136. m_arguments_object_needed = false;
  137. }
  138. HashTable<DeprecatedFlyString> function_names;
  139. // 18. Else if hasParameterExpressions is false, then
  140. // a. If functionNames contains "arguments" or lexicalNames contains "arguments", then
  141. // i. Set argumentsObjectNeeded to false.
  142. // NOTE: The block below is a combination of step 14 and step 18.
  143. if (scope_body) {
  144. // NOTE: Nothing in the callback throws an exception.
  145. MUST(scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  146. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  147. m_functions_to_initialize.append(function);
  148. }));
  149. auto const& arguments_name = vm().names.arguments.as_string();
  150. if (!m_has_parameter_expressions && function_names.contains(arguments_name))
  151. m_arguments_object_needed = false;
  152. if (!m_has_parameter_expressions && m_arguments_object_needed) {
  153. // NOTE: Nothing in the callback throws an exception.
  154. MUST(scope_body->for_each_lexically_declared_identifier([&](auto const& identifier) {
  155. if (identifier.string() == arguments_name)
  156. m_arguments_object_needed = false;
  157. }));
  158. }
  159. } else {
  160. m_arguments_object_needed = false;
  161. }
  162. size_t* environment_size = nullptr;
  163. size_t parameter_environment_bindings_count = 0;
  164. // 19. If strict is true or hasParameterExpressions is false, then
  165. if (m_strict || !m_has_parameter_expressions) {
  166. // 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.
  167. // b. Let env be the LexicalEnvironment of calleeContext
  168. // NOTE: Here we are only interested in the size of the environment.
  169. environment_size = &m_function_environment_bindings_count;
  170. }
  171. // 20. Else,
  172. else {
  173. // 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.
  174. // b. Let calleeEnv be the LexicalEnvironment of calleeContext.
  175. // c. Let env be NewDeclarativeEnvironment(calleeEnv).
  176. environment_size = &parameter_environment_bindings_count;
  177. }
  178. *environment_size += m_parameter_names.size();
  179. HashTable<DeprecatedFlyString> parameter_bindings;
  180. // 22. If argumentsObjectNeeded is true, then
  181. if (m_arguments_object_needed) {
  182. // f. Let parameterBindings be the list-concatenation of parameterNames and « "arguments" ».
  183. parameter_bindings = m_parameter_names;
  184. parameter_bindings.set(vm().names.arguments.as_string());
  185. (*environment_size)++;
  186. } else {
  187. parameter_bindings = m_parameter_names;
  188. // a. Let parameterBindings be parameterNames.
  189. }
  190. HashTable<DeprecatedFlyString> instantiated_var_names;
  191. size_t* var_environment_size = nullptr;
  192. // 27. If hasParameterExpressions is false, then
  193. if (!m_has_parameter_expressions) {
  194. // b. Let instantiatedVarNames be a copy of the List parameterBindings.
  195. instantiated_var_names = parameter_bindings;
  196. if (scope_body) {
  197. // c. For each element n of varNames, do
  198. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  199. // i. If instantiatedVarNames does not contain n, then
  200. if (instantiated_var_names.set(id.string()) == AK::HashSetResult::InsertedNewEntry) {
  201. // 1. Append n to instantiatedVarNames.
  202. // Following steps will be executed in function_declaration_instantiation:
  203. // 2. Perform ! env.CreateMutableBinding(n, false).
  204. // 3. Perform ! env.InitializeBinding(n, undefined).
  205. m_var_names_to_initialize_binding.append({
  206. .identifier = id,
  207. .parameter_binding = parameter_bindings.contains(id.string()),
  208. .function_name = function_names.contains(id.string()),
  209. });
  210. if (!id.is_local())
  211. (*environment_size)++;
  212. }
  213. }));
  214. }
  215. // d. Let varEnv be env
  216. var_environment_size = environment_size;
  217. } else {
  218. // 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.
  219. // b. Let varEnv be NewDeclarativeEnvironment(env).
  220. // NOTE: Here we are only interested in the size of the environment.
  221. var_environment_size = &m_var_environment_bindings_count;
  222. // 28. Else,
  223. // NOTE: Steps a, b, c and d are executed in function_declaration_instantiation.
  224. // e. For each element n of varNames, do
  225. if (scope_body) {
  226. MUST(scope_body->for_each_var_declared_identifier([&](auto const& id) {
  227. // 1. Append n to instantiatedVarNames.
  228. // Following steps will be executed in function_declaration_instantiation:
  229. // 2. Perform ! env.CreateMutableBinding(n, false).
  230. // 3. Perform ! env.InitializeBinding(n, undefined).
  231. if (instantiated_var_names.set(id.string()) == AK::HashSetResult::InsertedNewEntry) {
  232. m_var_names_to_initialize_binding.append({
  233. .identifier = id,
  234. .parameter_binding = parameter_bindings.contains(id.string()),
  235. .function_name = function_names.contains(id.string()),
  236. });
  237. if (!id.is_local())
  238. (*var_environment_size)++;
  239. }
  240. }));
  241. }
  242. }
  243. // 29. NOTE: Annex B.3.2.1 adds additional steps at this point.
  244. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  245. if (!m_strict && scope_body) {
  246. MUST(scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  247. auto function_name = function_declaration.name();
  248. if (parameter_bindings.contains(function_name))
  249. return;
  250. if (!instantiated_var_names.contains(function_name) && function_name != vm().names.arguments.as_string()) {
  251. m_function_names_to_initialize_binding.append(function_name);
  252. instantiated_var_names.set(function_name);
  253. (*var_environment_size)++;
  254. }
  255. function_declaration.set_should_do_additional_annexB_steps();
  256. }));
  257. }
  258. size_t* lex_environment_size = nullptr;
  259. // 30. If strict is false, then
  260. if (!m_strict) {
  261. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  262. if (can_elide_declarative_environment) {
  263. lex_environment_size = var_environment_size;
  264. } else {
  265. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  266. lex_environment_size = &m_lex_environment_bindings_count;
  267. }
  268. } else {
  269. // a. let lexEnv be varEnv.
  270. // NOTE: Here we are only interested in the size of the environment.
  271. lex_environment_size = var_environment_size;
  272. }
  273. if (scope_body) {
  274. MUST(scope_body->for_each_lexically_declared_identifier([&](auto const& id) {
  275. if (!id.is_local())
  276. (*lex_environment_size)++;
  277. }));
  278. }
  279. }
  280. void ECMAScriptFunctionObject::initialize(Realm& realm)
  281. {
  282. auto& vm = this->vm();
  283. Base::initialize(realm);
  284. // Note: The ordering of these properties must be: length, name, prototype which is the order
  285. // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances .
  286. // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
  287. // which must give the properties in chronological order which in this case is the order they
  288. // are defined in the spec.
  289. m_name_string = PrimitiveString::create(vm, m_name);
  290. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true }));
  291. MUST(define_property_or_throw(vm.names.name, { .value = m_name_string, .writable = false, .enumerable = false, .configurable = true }));
  292. if (!m_is_arrow_function) {
  293. Object* prototype = nullptr;
  294. switch (m_kind) {
  295. case FunctionKind::Normal:
  296. prototype = vm.heap().allocate<Object>(realm, realm.intrinsics().new_ordinary_function_prototype_object_shape());
  297. MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true }));
  298. break;
  299. case FunctionKind::Generator:
  300. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  301. prototype = Object::create(realm, realm.intrinsics().generator_function_prototype_prototype());
  302. break;
  303. case FunctionKind::Async:
  304. break;
  305. case FunctionKind::AsyncGenerator:
  306. prototype = Object::create(realm, realm.intrinsics().async_generator_function_prototype_prototype());
  307. break;
  308. }
  309. // 27.7.4 AsyncFunction Instances, https://tc39.es/ecma262/#sec-async-function-instances
  310. // AsyncFunction instances do not have a prototype property as they are not constructible.
  311. if (m_kind != FunctionKind::Async)
  312. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  313. }
  314. }
  315. // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  316. ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, ReadonlySpan<Value> arguments_list)
  317. {
  318. auto& vm = this->vm();
  319. // 1. Let callerContext be the running execution context.
  320. // NOTE: No-op, kept by the VM in its execution context stack.
  321. auto callee_context = ExecutionContext::create(heap());
  322. callee_context->locals.resize(m_local_variables_names.size());
  323. // Non-standard
  324. callee_context->arguments.append(arguments_list.data(), arguments_list.size());
  325. callee_context->instruction_stream_iterator = vm.bytecode_interpreter().instruction_stream_iterator();
  326. // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
  327. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  328. TRY(prepare_for_ordinary_call(*callee_context, nullptr));
  329. // 3. Assert: calleeContext is now the running execution context.
  330. VERIFY(&vm.running_execution_context() == callee_context);
  331. // 4. If F.[[IsClassConstructor]] is true, then
  332. if (m_is_class_constructor) {
  333. // a. Let error be a newly created TypeError object.
  334. // b. NOTE: error is created in calleeContext with F's associated Realm Record.
  335. auto throw_completion = vm.throw_completion<TypeError>(ErrorType::ClassConstructorWithoutNew, m_name);
  336. // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  337. vm.pop_execution_context();
  338. // d. Return ThrowCompletion(error).
  339. return throw_completion;
  340. }
  341. // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  342. ordinary_call_bind_this(*callee_context, this_argument);
  343. // 6. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  344. auto result = ordinary_call_evaluate_body();
  345. // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  346. vm.pop_execution_context();
  347. // 8. If result.[[Type]] is return, return result.[[Value]].
  348. if (result.type() == Completion::Type::Return)
  349. return *result.value();
  350. // 9. ReturnIfAbrupt(result).
  351. if (result.is_abrupt()) {
  352. VERIFY(result.is_error());
  353. return result;
  354. }
  355. // 10. Return undefined.
  356. return js_undefined();
  357. }
  358. // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget
  359. ThrowCompletionOr<NonnullGCPtr<Object>> ECMAScriptFunctionObject::internal_construct(ReadonlySpan<Value> arguments_list, FunctionObject& new_target)
  360. {
  361. auto& vm = this->vm();
  362. // 1. Let callerContext be the running execution context.
  363. // NOTE: No-op, kept by the VM in its execution context stack.
  364. // 2. Let kind be F.[[ConstructorKind]].
  365. auto kind = m_constructor_kind;
  366. GCPtr<Object> this_argument;
  367. // 3. If kind is base, then
  368. if (kind == ConstructorKind::Base) {
  369. // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
  370. this_argument = TRY(ordinary_create_from_constructor<Object>(vm, new_target, &Intrinsics::object_prototype, ConstructWithPrototypeTag::Tag));
  371. }
  372. auto callee_context = ExecutionContext::create(heap());
  373. callee_context->locals.resize(m_local_variables_names.size());
  374. // Non-standard
  375. callee_context->arguments.append(arguments_list.data(), arguments_list.size());
  376. callee_context->instruction_stream_iterator = vm.bytecode_interpreter().instruction_stream_iterator();
  377. // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
  378. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  379. TRY(prepare_for_ordinary_call(*callee_context, &new_target));
  380. // 5. Assert: calleeContext is now the running execution context.
  381. VERIFY(&vm.running_execution_context() == callee_context);
  382. // 6. If kind is base, then
  383. if (kind == ConstructorKind::Base) {
  384. // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  385. ordinary_call_bind_this(*callee_context, this_argument);
  386. // b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)).
  387. auto initialize_result = this_argument->initialize_instance_elements(*this);
  388. // c. If initializeResult is an abrupt completion, then
  389. if (initialize_result.is_throw_completion()) {
  390. // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  391. vm.pop_execution_context();
  392. // ii. Return ? initializeResult.
  393. return initialize_result.throw_completion();
  394. }
  395. }
  396. // 7. Let constructorEnv be the LexicalEnvironment of calleeContext.
  397. auto constructor_env = callee_context->lexical_environment;
  398. // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  399. auto result = ordinary_call_evaluate_body();
  400. // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  401. vm.pop_execution_context();
  402. // 10. If result.[[Type]] is return, then
  403. if (result.type() == Completion::Type::Return) {
  404. // FIXME: This is leftover from untangling the call/construct mess - doesn't belong here in any way, but removing it breaks derived classes.
  405. // Likely fixed by making ClassDefinitionEvaluation fully spec compliant.
  406. if (kind == ConstructorKind::Derived && result.value()->is_object()) {
  407. auto prototype = TRY(new_target.get(vm.names.prototype));
  408. if (prototype.is_object())
  409. TRY(result.value()->as_object().internal_set_prototype_of(&prototype.as_object()));
  410. }
  411. // EOF (End of FIXME)
  412. // a. If Type(result.[[Value]]) is Object, return result.[[Value]].
  413. if (result.value()->is_object())
  414. return result.value()->as_object();
  415. // b. If kind is base, return thisArgument.
  416. if (kind == ConstructorKind::Base)
  417. return *this_argument;
  418. // c. If result.[[Value]] is not undefined, throw a TypeError exception.
  419. if (!result.value()->is_undefined())
  420. return vm.throw_completion<TypeError>(ErrorType::DerivedConstructorReturningInvalidValue);
  421. }
  422. // 11. Else, ReturnIfAbrupt(result).
  423. else if (result.is_abrupt()) {
  424. VERIFY(result.is_error());
  425. return result;
  426. }
  427. // 12. Let thisBinding be ? constructorEnv.GetThisBinding().
  428. auto this_binding = TRY(constructor_env->get_this_binding(vm));
  429. // 13. Assert: Type(thisBinding) is Object.
  430. VERIFY(this_binding.is_object());
  431. // 14. Return thisBinding.
  432. return this_binding.as_object();
  433. }
  434. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  435. {
  436. Base::visit_edges(visitor);
  437. visitor.visit(m_environment);
  438. visitor.visit(m_private_environment);
  439. visitor.visit(m_realm);
  440. visitor.visit(m_home_object);
  441. visitor.visit(m_bytecode_executable);
  442. for (auto& executable : m_default_parameter_bytecode_executables)
  443. visitor.visit(executable);
  444. for (auto& field : m_fields) {
  445. if (auto* property_key_ptr = field.name.get_pointer<PropertyKey>(); property_key_ptr && property_key_ptr->is_symbol())
  446. visitor.visit(property_key_ptr->as_symbol());
  447. }
  448. for (auto& private_element : m_private_methods)
  449. visitor.visit(private_element.value);
  450. m_script_or_module.visit(
  451. [](Empty) {},
  452. [&](auto& script_or_module) {
  453. visitor.visit(script_or_module);
  454. });
  455. }
  456. // 10.2.7 MakeMethod ( F, homeObject ), https://tc39.es/ecma262/#sec-makemethod
  457. void ECMAScriptFunctionObject::make_method(Object& home_object)
  458. {
  459. // 1. Set F.[[HomeObject]] to homeObject.
  460. m_home_object = &home_object;
  461. // 2. Return unused.
  462. }
  463. // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  464. ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation()
  465. {
  466. auto& vm = this->vm();
  467. auto& realm = *vm.current_realm();
  468. // 1. Let calleeContext be the running execution context.
  469. auto& callee_context = vm.running_execution_context();
  470. // 2. Let code be func.[[ECMAScriptCode]].
  471. ScopeNode const* scope_body = nullptr;
  472. if (is<ScopeNode>(*m_ecmascript_code))
  473. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  474. // NOTE: Following steps were executed in ECMAScriptFunctionObject constructor.
  475. // 3. Let strict be func.[[Strict]].
  476. // 4. Let formals be func.[[FormalParameters]].
  477. // 5. Let parameterNames be the BoundNames of formals.
  478. // 6. If parameterNames has any duplicate entries, let hasDuplicates be true. Otherwise, let hasDuplicates be false.
  479. // 7. Let simpleParameterList be IsSimpleParameterList of formals.
  480. bool const simple_parameter_list = has_simple_parameter_list();
  481. // NOTE: Following steps were executed in ECMAScriptFunctionObject constructor.
  482. // 8. Let hasParameterExpressions be ContainsExpression of formals.
  483. // 9. Let varNames be the VarDeclaredNames of code.
  484. // 10. Let varDeclarations be the VarScopedDeclarations of code.
  485. // 11. Let lexicalNames be the LexicallyDeclaredNames of code.
  486. // 12. Let functionNames be a new empty List.
  487. // 13. Let functionsToInitialize be a new empty List.
  488. // 14. For each element d of varDeclarations, in reverse List order, do
  489. // 15. Let argumentsObjectNeeded be true.
  490. // 16. If func.[[ThisMode]] is lexical, then
  491. // 17. Else if parameterNames contains "arguments", then
  492. // 18. Else if hasParameterExpressions is false, then
  493. GCPtr<Environment> environment;
  494. // 19. If strict is true or hasParameterExpressions is false, then
  495. if (m_strict || !m_has_parameter_expressions) {
  496. // 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.
  497. // b. Let env be the LexicalEnvironment of calleeContext.
  498. environment = callee_context.lexical_environment;
  499. }
  500. // 20. Else,
  501. else {
  502. // 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.
  503. // b. Let calleeEnv be the LexicalEnvironment of calleeContext.
  504. auto callee_env = callee_context.lexical_environment;
  505. // c. Let env be NewDeclarativeEnvironment(calleeEnv).
  506. environment = new_declarative_environment(*callee_env);
  507. // d. Assert: The VariableEnvironment of calleeContext is calleeEnv.
  508. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  509. // e. Set the LexicalEnvironment of calleeContext to env.
  510. callee_context.lexical_environment = environment;
  511. }
  512. // 21. For each String paramName of parameterNames, do
  513. for (auto const& parameter_name : m_parameter_names) {
  514. // a. Let alreadyDeclared be ! env.HasBinding(paramName).
  515. // 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.
  516. // c. If alreadyDeclared is false, then
  517. // NOTE: alreadyDeclared is always false because we use hash table for parameterNames
  518. // i. Perform ! env.CreateMutableBinding(paramName, false).
  519. MUST(environment->create_mutable_binding(vm, parameter_name, false));
  520. // ii. If hasDuplicates is true, then
  521. if (m_has_duplicates) {
  522. // 1. Perform ! env.InitializeBinding(paramName, undefined).
  523. MUST(environment->initialize_binding(vm, parameter_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  524. }
  525. }
  526. // 22. If argumentsObjectNeeded is true, then
  527. if (m_arguments_object_needed) {
  528. Object* arguments_object;
  529. // a. If strict is true or simpleParameterList is false, then
  530. if (m_strict || !simple_parameter_list) {
  531. // i. Let ao be CreateUnmappedArgumentsObject(argumentsList).
  532. arguments_object = create_unmapped_arguments_object(vm, vm.running_execution_context().arguments);
  533. }
  534. // b. Else,
  535. else {
  536. // 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.
  537. // ii. Let ao be CreateMappedArgumentsObject(func, formals, argumentsList, env).
  538. arguments_object = create_mapped_arguments_object(vm, *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  539. }
  540. // c. If strict is true, then
  541. if (m_strict) {
  542. // i. Perform ! env.CreateImmutableBinding("arguments", false).
  543. MUST(environment->create_immutable_binding(vm, vm.names.arguments.as_string(), false));
  544. // ii. NOTE: In strict mode code early errors prevent attempting to assign to this binding, so its mutability is not observable.
  545. }
  546. // b. Else,
  547. else {
  548. // i. Perform ! env.CreateMutableBinding("arguments", false).
  549. MUST(environment->create_mutable_binding(vm, vm.names.arguments.as_string(), false));
  550. }
  551. // c. Perform ! env.InitializeBinding("arguments", ao).
  552. MUST(environment->initialize_binding(vm, vm.names.arguments.as_string(), arguments_object, Environment::InitializeBindingHint::Normal));
  553. // f. Let parameterBindings be the list-concatenation of parameterNames and « "arguments" ».
  554. }
  555. // 23. Else,
  556. else {
  557. // a. Let parameterBindings be parameterNames.
  558. }
  559. // NOTE: We now treat parameterBindings as parameterNames.
  560. // 24. Let iteratorRecord be CreateListIteratorRecord(argumentsList).
  561. // 25. If hasDuplicates is true, then
  562. // a. Perform ? IteratorBindingInitialization of formals with arguments iteratorRecord and undefined.
  563. // 26. Else,
  564. // a. Perform ? IteratorBindingInitialization of formals with arguments iteratorRecord and env.
  565. // NOTE: The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  566. auto const& execution_context_arguments = vm.running_execution_context().arguments;
  567. size_t default_parameter_index = 0;
  568. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  569. auto& parameter = m_formal_parameters[i];
  570. if (parameter.default_value)
  571. ++default_parameter_index;
  572. TRY(parameter.binding.visit(
  573. [&](auto const& param) -> ThrowCompletionOr<void> {
  574. Value argument_value;
  575. if (parameter.is_rest) {
  576. auto array = MUST(Array::create(realm, 0));
  577. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  578. array->indexed_properties().append(execution_context_arguments[rest_index]);
  579. argument_value = array;
  580. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  581. argument_value = execution_context_arguments[i];
  582. } else if (parameter.default_value) {
  583. auto value_and_frame = vm.bytecode_interpreter().run_and_return_frame(*m_default_parameter_bytecode_executables[default_parameter_index - 1], nullptr);
  584. if (value_and_frame.value.is_error())
  585. return value_and_frame.value.release_error();
  586. // Resulting value is in the accumulator.
  587. argument_value = value_and_frame.frame->registers()[0];
  588. } else {
  589. argument_value = js_undefined();
  590. }
  591. Environment* used_environment = m_has_duplicates ? nullptr : environment;
  592. if constexpr (IsSame<NonnullRefPtr<Identifier const> const&, decltype(param)>) {
  593. if (param->is_local()) {
  594. callee_context.locals[param->local_variable_index()] = argument_value;
  595. return {};
  596. }
  597. Reference reference = TRY(vm.resolve_binding(param->string(), used_environment));
  598. // Here the difference from hasDuplicates is important
  599. if (m_has_duplicates)
  600. return reference.put_value(vm, argument_value);
  601. return reference.initialize_referenced_binding(vm, argument_value);
  602. }
  603. if constexpr (IsSame<NonnullRefPtr<BindingPattern const> const&, decltype(param)>) {
  604. // Here the difference from hasDuplicates is important
  605. return vm.binding_initialization(param, argument_value, used_environment);
  606. }
  607. }));
  608. }
  609. GCPtr<Environment> var_environment;
  610. // 27. If hasParameterExpressions is false, then
  611. if (!m_has_parameter_expressions) {
  612. // a. NOTE: Only a single Environment Record is needed for the parameters and top-level vars.
  613. // b. Let instantiatedVarNames be a copy of the List parameterBindings.
  614. // NOTE: Done in implementation of step 27.c.i.1 below
  615. if (scope_body) {
  616. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  617. // an exception should not result from `for_each_var_declared_name`.
  618. // c. For each element n of varNames, do
  619. for (auto const& variable_to_initialize : m_var_names_to_initialize_binding) {
  620. auto const& id = variable_to_initialize.identifier;
  621. // NOTE: Following steps were executed in ECMAScriptFunctionObject constructor.
  622. // i. If instantiatedVarNames does not contain n, then
  623. // 1. Append n to instantiatedVarNames.
  624. if (id.is_local()) {
  625. callee_context.locals[id.local_variable_index()] = js_undefined();
  626. } else {
  627. // 2. Perform ! env.CreateMutableBinding(n, false).
  628. // 3. Perform ! env.InitializeBinding(n, undefined).
  629. MUST(environment->create_mutable_binding(vm, id.string(), false));
  630. MUST(environment->initialize_binding(vm, id.string(), js_undefined(), Environment::InitializeBindingHint::Normal));
  631. }
  632. }
  633. }
  634. // d.Let varEnv be env
  635. var_environment = environment;
  636. }
  637. // 28. Else,
  638. else {
  639. // 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.
  640. // b. Let varEnv be NewDeclarativeEnvironment(env).
  641. var_environment = new_declarative_environment(*environment);
  642. static_cast<DeclarativeEnvironment*>(var_environment.ptr())->ensure_capacity(m_var_environment_bindings_count);
  643. // c. Set the VariableEnvironment of calleeContext to varEnv.
  644. callee_context.variable_environment = var_environment;
  645. // d. Let instantiatedVarNames be a new empty List.
  646. // NOTE: Already done above.
  647. if (scope_body) {
  648. // NOTE: Due to the use of MUST with `create_mutable_binding`, `get_binding_value` and `initialize_binding` below,
  649. // an exception should not result from `for_each_var_declared_name`.
  650. // e. For each element n of varNames, do
  651. for (auto const& variable_to_initialize : m_var_names_to_initialize_binding) {
  652. auto const& id = variable_to_initialize.identifier;
  653. // NOTE: Following steps were executed in ECMAScriptFunctionObject constructor.
  654. // i. If instantiatedVarNames does not contain n, then
  655. // 1. Append n to instantiatedVarNames.
  656. // 2. Perform ! varEnv.CreateMutableBinding(n, false).
  657. // NOTE: We ignore locals because they are stored in ExecutionContext instead of environment.
  658. if (!id.is_local())
  659. MUST(var_environment->create_mutable_binding(vm, id.string(), false));
  660. Value initial_value;
  661. // 3. If parameterBindings does not contain n, or if functionNames contains n, then
  662. if (!variable_to_initialize.parameter_binding || variable_to_initialize.function_name) {
  663. // a. Let initialValue be undefined.
  664. initial_value = js_undefined();
  665. }
  666. // 4. Else,
  667. else {
  668. // a. Let initialValue be ! env.GetBindingValue(n, false).
  669. if (id.is_local()) {
  670. initial_value = callee_context.locals[id.local_variable_index()];
  671. } else {
  672. initial_value = MUST(environment->get_binding_value(vm, id.string(), false));
  673. }
  674. }
  675. // 5. Perform ! varEnv.InitializeBinding(n, initialValue).
  676. if (id.is_local()) {
  677. // NOTE: Local variables are supported only in bytecode interpreter
  678. callee_context.locals[id.local_variable_index()] = initial_value;
  679. } else {
  680. MUST(var_environment->initialize_binding(vm, id.string(), initial_value, Environment::InitializeBindingHint::Normal));
  681. }
  682. // 6. NOTE: A var with the same name as a formal parameter initially has the same value as the corresponding initialized parameter.
  683. }
  684. }
  685. }
  686. // 29. NOTE: Annex B.3.2.1 adds additional steps at this point.
  687. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  688. if (!m_strict && scope_body) {
  689. // NOTE: Due to the use of MUST with `create_mutable_binding` and `initialize_binding` below,
  690. // an exception should not result from `for_each_function_hoistable_with_annexB_extension`.
  691. for (auto const& function_name : m_function_names_to_initialize_binding) {
  692. MUST(var_environment->create_mutable_binding(vm, function_name, false));
  693. MUST(var_environment->initialize_binding(vm, function_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  694. }
  695. }
  696. GCPtr<Environment> lex_environment;
  697. // 30. If strict is false, then
  698. if (!m_strict) {
  699. // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true:
  700. // 1. there is no direct call to eval() within this function
  701. // 2. there are no lexical declarations that would go into the environment
  702. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  703. if (can_elide_declarative_environment) {
  704. lex_environment = var_environment;
  705. } else {
  706. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  707. // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval
  708. // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level
  709. // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places
  710. // all declarations into a new Environment Record.
  711. lex_environment = new_declarative_environment(*var_environment);
  712. static_cast<DeclarativeEnvironment*>(lex_environment.ptr())->ensure_capacity(m_lex_environment_bindings_count);
  713. }
  714. }
  715. // 31. Else,
  716. else {
  717. // a. let lexEnv be varEnv.
  718. lex_environment = var_environment;
  719. }
  720. // 32. Set the LexicalEnvironment of calleeContext to lexEnv.
  721. callee_context.lexical_environment = lex_environment;
  722. if (!scope_body)
  723. return {};
  724. // 33. Let lexDeclarations be the LexicallyScopedDeclarations of code.
  725. // 34. For each element d of lexDeclarations, do
  726. // NOTE: Due to the use of MUST in the callback, an exception should not result from `for_each_lexically_scoped_declaration`.
  727. if (scope_body->has_lexical_declarations()) {
  728. MUST(scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  729. // NOTE: Due to the use of MUST with `create_immutable_binding` and `create_mutable_binding` below,
  730. // an exception should not result from `for_each_bound_name`.
  731. // 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.
  732. // b. For each element dn of the BoundNames of d, do
  733. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  734. if (id.is_local()) {
  735. // NOTE: Local variables are supported only in bytecode interpreter
  736. return;
  737. }
  738. // i. If IsConstantDeclaration of d is true, then
  739. if (declaration.is_constant_declaration()) {
  740. // 1. Perform ! lexEnv.CreateImmutableBinding(dn, true).
  741. MUST(lex_environment->create_immutable_binding(vm, id.string(), true));
  742. }
  743. // ii. Else,
  744. else {
  745. // 1. Perform ! lexEnv.CreateMutableBinding(dn, false).
  746. MUST(lex_environment->create_mutable_binding(vm, id.string(), false));
  747. }
  748. }));
  749. }));
  750. }
  751. // 35. Let privateEnv be the PrivateEnvironment of calleeContext.
  752. auto private_environment = callee_context.private_environment;
  753. // 36. For each Parse Node f of functionsToInitialize, do
  754. for (auto& declaration : m_functions_to_initialize) {
  755. // a. Let fn be the sole element of the BoundNames of f.
  756. // b. Let fo be InstantiateFunctionObject of f with arguments lexEnv and privateEnv.
  757. 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());
  758. // c. Perform ! varEnv.SetMutableBinding(fn, fo, false).
  759. if (declaration.name_identifier()->is_local()) {
  760. callee_context.locals[declaration.name_identifier()->local_variable_index()] = function;
  761. } else {
  762. MUST(var_environment->set_mutable_binding(vm, declaration.name(), function, false));
  763. }
  764. }
  765. if (is<DeclarativeEnvironment>(*lex_environment))
  766. static_cast<DeclarativeEnvironment*>(lex_environment.ptr())->shrink_to_fit();
  767. if (lex_environment != var_environment && is<DeclarativeEnvironment>(*var_environment))
  768. static_cast<DeclarativeEnvironment*>(var_environment.ptr())->shrink_to_fit();
  769. // 37. Return unused.
  770. return {};
  771. }
  772. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  773. ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  774. {
  775. auto& vm = this->vm();
  776. // Non-standard
  777. callee_context.is_strict_mode = m_strict;
  778. // 1. Let callerContext be the running execution context.
  779. // 2. Let calleeContext be a new ECMAScript code execution context.
  780. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  781. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  782. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  783. // 3. Set the Function of calleeContext to F.
  784. callee_context.function = this;
  785. callee_context.function_name = m_name_string;
  786. // 4. Let calleeRealm be F.[[Realm]].
  787. auto callee_realm = m_realm;
  788. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  789. // every function has a realm - especially in LibWeb that's sometimes not the case
  790. // when a function is created while no JS is running, as we currently need to rely on
  791. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  792. // If there's no 'current realm' either, we can't continue and crash.
  793. if (!callee_realm)
  794. callee_realm = vm.current_realm();
  795. VERIFY(callee_realm);
  796. // 5. Set the Realm of calleeContext to calleeRealm.
  797. callee_context.realm = callee_realm;
  798. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  799. callee_context.script_or_module = m_script_or_module;
  800. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  801. auto local_environment = new_function_environment(*this, new_target);
  802. local_environment->ensure_capacity(m_function_environment_bindings_count);
  803. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  804. callee_context.lexical_environment = local_environment;
  805. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  806. callee_context.variable_environment = local_environment;
  807. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  808. callee_context.private_environment = m_private_environment;
  809. // 11. If callerContext is not already suspended, suspend callerContext.
  810. // FIXME: We don't have this concept yet.
  811. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  812. TRY(vm.push_execution_context(callee_context, {}));
  813. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  814. // 14. Return calleeContext.
  815. // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack.
  816. return {};
  817. }
  818. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  819. void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument)
  820. {
  821. auto& vm = this->vm();
  822. // 1. Let thisMode be F.[[ThisMode]].
  823. auto this_mode = m_this_mode;
  824. // If thisMode is lexical, return unused.
  825. if (this_mode == ThisMode::Lexical)
  826. return;
  827. // 3. Let calleeRealm be F.[[Realm]].
  828. auto callee_realm = m_realm;
  829. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  830. // every function has a realm - especially in LibWeb that's sometimes not the case
  831. // when a function is created while no JS is running, as we currently need to rely on
  832. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  833. // If there's no 'current realm' either, we can't continue and crash.
  834. if (!callee_realm)
  835. callee_realm = vm.current_realm();
  836. VERIFY(callee_realm);
  837. // 4. Let localEnv be the LexicalEnvironment of calleeContext.
  838. auto local_env = callee_context.lexical_environment;
  839. Value this_value;
  840. // 5. If thisMode is strict, let thisValue be thisArgument.
  841. if (this_mode == ThisMode::Strict) {
  842. this_value = this_argument;
  843. }
  844. // 6. Else,
  845. else {
  846. // a. If thisArgument is undefined or null, then
  847. if (this_argument.is_nullish()) {
  848. // i. Let globalEnv be calleeRealm.[[GlobalEnv]].
  849. // ii. Assert: globalEnv is a global Environment Record.
  850. auto& global_env = callee_realm->global_environment();
  851. // iii. Let thisValue be globalEnv.[[GlobalThisValue]].
  852. this_value = &global_env.global_this_value();
  853. }
  854. // b. Else,
  855. else {
  856. // i. Let thisValue be ! ToObject(thisArgument).
  857. this_value = MUST(this_argument.to_object(vm));
  858. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
  859. VERIFY(vm.current_realm() == callee_realm);
  860. }
  861. }
  862. // 7. Assert: localEnv is a function Environment Record.
  863. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
  864. // 9. Perform ! localEnv.BindThisValue(thisValue).
  865. MUST(verify_cast<FunctionEnvironment>(*local_env).bind_this_value(vm, this_value));
  866. // 10. Return unused.
  867. }
  868. // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  869. template<typename T>
  870. void async_function_start(VM& vm, PromiseCapability const& promise_capability, T const& async_function_body)
  871. {
  872. // 1. Let runningContext be the running execution context.
  873. auto& running_context = vm.running_execution_context();
  874. // 2. Let asyncContext be a copy of runningContext.
  875. auto async_context = running_context.copy();
  876. // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context.
  877. // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext).
  878. async_block_start(vm, async_function_body, promise_capability, *async_context);
  879. // 5. Return unused.
  880. }
  881. // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart
  882. // 12.7.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-explicit-resource-management/#sec-asyncblockstart
  883. // 1.2.1.1 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/proposal-array-from-async/#sec-asyncblockstart
  884. template<typename T>
  885. void async_block_start(VM& vm, T const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context)
  886. {
  887. // NOTE: This function is a combination between two proposals, so does not exactly match spec steps of either.
  888. auto& realm = *vm.current_realm();
  889. // 1. Assert: promiseCapability is a PromiseCapability Record.
  890. // 2. Let runningContext be the running execution context.
  891. auto& running_context = vm.running_execution_context();
  892. // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
  893. auto execution_steps = NativeFunction::create(realm, "", [&async_body, &promise_capability, &async_context](auto& vm) -> ThrowCompletionOr<Value> {
  894. Completion result;
  895. // a. If asyncBody is a Parse Node, then
  896. if constexpr (!IsCallableWithArguments<T, Completion>) {
  897. // a. Let result be the result of evaluating asyncBody.
  898. // FIXME: Cache this executable somewhere.
  899. auto maybe_executable = Bytecode::compile(vm, async_body, FunctionKind::Async, "AsyncBlockStart"sv);
  900. if (maybe_executable.is_error())
  901. result = maybe_executable.release_error();
  902. else
  903. result = vm.bytecode_interpreter().run_and_return_frame(*maybe_executable.value(), nullptr).value;
  904. }
  905. // b. Else,
  906. else {
  907. // i. Assert: asyncBody is an Abstract Closure with no parameters.
  908. static_assert(IsCallableWithArguments<T, Completion>);
  909. // ii. Let result be asyncBody().
  910. result = async_body();
  911. }
  912. // c. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
  913. // 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.
  914. vm.pop_execution_context();
  915. // NOTE: This does not work for Array.fromAsync, likely due to conflicts between that proposal and Explicit Resource Management proposal.
  916. if constexpr (!IsCallableWithArguments<T, Completion>) {
  917. // e. Let env be asyncContext's LexicalEnvironment.
  918. auto env = async_context.lexical_environment;
  919. // f. Set result to DisposeResources(env, result).
  920. result = dispose_resources(vm, verify_cast<DeclarativeEnvironment>(env.ptr()), result);
  921. } else {
  922. (void)async_context;
  923. }
  924. // g. If result.[[Type]] is normal, then
  925. if (result.type() == Completion::Type::Normal) {
  926. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
  927. MUST(call(vm, *promise_capability.resolve(), js_undefined(), js_undefined()));
  928. }
  929. // h. Else if result.[[Type]] is return, then
  930. else if (result.type() == Completion::Type::Return) {
  931. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
  932. MUST(call(vm, *promise_capability.resolve(), js_undefined(), *result.value()));
  933. }
  934. // i. Else,
  935. else {
  936. // i. Assert: result.[[Type]] is throw.
  937. VERIFY(result.type() == Completion::Type::Throw);
  938. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
  939. MUST(call(vm, *promise_capability.reject(), js_undefined(), *result.value()));
  940. }
  941. // j. Return unused.
  942. // NOTE: We don't support returning an empty/optional/unused value here.
  943. return js_undefined();
  944. });
  945. // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  946. auto push_result = vm.push_execution_context(async_context, {});
  947. if (push_result.is_error())
  948. return;
  949. // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  950. auto result = call(vm, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value);
  951. // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  952. VERIFY(&vm.running_execution_context() == &running_context);
  953. // 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.
  954. VERIFY(result.has_value() && result.value().is_undefined());
  955. // 8. Return unused.
  956. }
  957. template void async_block_start(VM&, NonnullRefPtr<Statement const> const& async_body, PromiseCapability const&, ExecutionContext&);
  958. template void async_function_start(VM&, PromiseCapability const&, NonnullRefPtr<Statement const> const& async_function_body);
  959. template void async_block_start(VM&, SafeFunction<Completion()> const& async_body, PromiseCapability const&, ExecutionContext&);
  960. template void async_function_start(VM&, PromiseCapability const&, SafeFunction<Completion()> const& async_function_body);
  961. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  962. // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  963. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  964. {
  965. auto& vm = this->vm();
  966. auto& realm = *vm.current_realm();
  967. // NOTE: There's a subtle ordering issue here:
  968. // - We have to compile the default parameter values before instantiating the function.
  969. // - We have to instantiate the function before compiling the function body.
  970. // This is why FunctionDeclarationInstantiation is invoked in the middle.
  971. // The issue is that FunctionDeclarationInstantiation may mark certain functions as hoisted
  972. // per Annex B. This affects code generation for FunctionDeclaration nodes.
  973. if (!m_bytecode_executable) {
  974. size_t default_parameter_index = 0;
  975. for (auto& parameter : m_formal_parameters) {
  976. if (!parameter.default_value)
  977. continue;
  978. if (parameter.bytecode_executable.is_null()) {
  979. auto executable = TRY(Bytecode::compile(vm, *parameter.default_value, FunctionKind::Normal, DeprecatedString::formatted("default parameter #{} for {}", default_parameter_index++, m_name)));
  980. const_cast<FunctionParameter&>(parameter).bytecode_executable = executable;
  981. m_default_parameter_bytecode_executables.append(move(executable));
  982. } else {
  983. m_default_parameter_bytecode_executables.append(*parameter.bytecode_executable);
  984. }
  985. }
  986. }
  987. auto declaration_result = [&]() -> ThrowCompletionOr<void> {
  988. if (is_module_wrapper())
  989. return {};
  990. return function_declaration_instantiation();
  991. }();
  992. if (m_kind == FunctionKind::Normal || m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator) {
  993. if (declaration_result.is_error())
  994. return declaration_result.release_error();
  995. }
  996. if (!m_bytecode_executable) {
  997. if (!m_ecmascript_code->bytecode_executable())
  998. const_cast<Statement&>(*m_ecmascript_code).set_bytecode_executable(TRY(Bytecode::compile(vm, *m_ecmascript_code, m_kind, m_name)));
  999. m_bytecode_executable = m_ecmascript_code->bytecode_executable();
  1000. }
  1001. if (m_kind == FunctionKind::Async) {
  1002. if (declaration_result.is_throw_completion()) {
  1003. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  1004. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  1005. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  1006. }
  1007. }
  1008. auto result_and_frame = vm.bytecode_interpreter().run_and_return_frame(*m_bytecode_executable, nullptr);
  1009. VERIFY(result_and_frame.frame != nullptr);
  1010. if (result_and_frame.value.is_error())
  1011. return result_and_frame.value.release_error();
  1012. auto result = result_and_frame.value.release_value();
  1013. // NOTE: Running the bytecode should eventually return a completion.
  1014. // Until it does, we assume "return" and include the undefined fallback from the call site.
  1015. if (m_kind == FunctionKind::Normal)
  1016. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  1017. if (m_kind == FunctionKind::AsyncGenerator) {
  1018. auto async_generator_object = TRY(AsyncGenerator::create(realm, result, this, vm.running_execution_context().copy(), result_and_frame.frame.release_nonnull()));
  1019. return { Completion::Type::Return, async_generator_object, {} };
  1020. }
  1021. auto generator_object = TRY(GeneratorObject::create(realm, result, this, vm.running_execution_context().copy(), result_and_frame.frame.release_nonnull()));
  1022. // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise
  1023. // See AwaitExpression::generate_bytecode() for the transformation.
  1024. if (m_kind == FunctionKind::Async)
  1025. return { Completion::Type::Return, AsyncFunctionDriverWrapper::create(realm, generator_object), {} };
  1026. VERIFY(m_kind == FunctionKind::Generator);
  1027. return { Completion::Type::Return, generator_object, {} };
  1028. }
  1029. void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name)
  1030. {
  1031. VERIFY(!name.is_null());
  1032. auto& vm = this->vm();
  1033. m_name = name;
  1034. m_name_string = PrimitiveString::create(vm, m_name);
  1035. MUST(define_property_or_throw(vm.names.name, { .value = m_name_string, .writable = false, .enumerable = false, .configurable = true }));
  1036. }
  1037. }