ECMAScriptFunctionObject.cpp 57 KB

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