ECMAScriptFunctionObject.cpp 63 KB

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