ECMAScriptFunctionObject.cpp 62 KB

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