ECMAScriptFunctionObject.cpp 60 KB

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