ECMAScriptFunctionObject.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/Function.h>
  9. #include <LibJS/AST.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Interpreter.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Runtime/AbstractOperations.h>
  15. #include <LibJS/Runtime/Array.h>
  16. #include <LibJS/Runtime/AsyncFunctionDriverWrapper.h>
  17. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  18. #include <LibJS/Runtime/Error.h>
  19. #include <LibJS/Runtime/ExecutionContext.h>
  20. #include <LibJS/Runtime/FunctionEnvironment.h>
  21. #include <LibJS/Runtime/GeneratorObject.h>
  22. #include <LibJS/Runtime/GlobalObject.h>
  23. #include <LibJS/Runtime/NativeFunction.h>
  24. #include <LibJS/Runtime/PromiseCapability.h>
  25. #include <LibJS/Runtime/PromiseConstructor.h>
  26. #include <LibJS/Runtime/Value.h>
  27. namespace JS {
  28. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> parameters, i32 m_function_length, 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)
  29. {
  30. Object* prototype = nullptr;
  31. switch (kind) {
  32. case FunctionKind::Normal:
  33. prototype = realm.intrinsics().function_prototype();
  34. break;
  35. case FunctionKind::Generator:
  36. prototype = realm.intrinsics().generator_function_prototype();
  37. break;
  38. case FunctionKind::Async:
  39. prototype = realm.intrinsics().async_function_prototype();
  40. break;
  41. case FunctionKind::AsyncGenerator:
  42. prototype = realm.intrinsics().async_generator_function_prototype();
  43. break;
  44. }
  45. return realm.heap().allocate<ECMAScriptFunctionObject>(realm, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, 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));
  46. }
  47. NonnullGCPtr<ECMAScriptFunctionObject> ECMAScriptFunctionObject::create(Realm& realm, DeprecatedFlyString name, Object& prototype, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> parameters, i32 m_function_length, 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)
  48. {
  49. return realm.heap().allocate<ECMAScriptFunctionObject>(realm, move(name), move(source_text), ecmascript_code, move(parameters), m_function_length, parent_environment, private_environment, prototype, kind, is_strict, might_need_arguments_object, contains_direct_call_to_eval, is_arrow_function, move(class_field_initializer_name));
  50. }
  51. ECMAScriptFunctionObject::ECMAScriptFunctionObject(DeprecatedFlyString name, DeprecatedString source_text, Statement const& ecmascript_code, Vector<FunctionParameter> formal_parameters, i32 function_length, 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)
  52. : FunctionObject(prototype)
  53. , m_name(move(name))
  54. , m_function_length(function_length)
  55. , m_environment(parent_environment)
  56. , m_private_environment(private_environment)
  57. , m_formal_parameters(move(formal_parameters))
  58. , m_ecmascript_code(ecmascript_code)
  59. , m_realm(&prototype.shape().realm())
  60. , m_source_text(move(source_text))
  61. , m_class_field_initializer_name(move(class_field_initializer_name))
  62. , m_strict(strict)
  63. , m_might_need_arguments_object(might_need_arguments_object)
  64. , m_contains_direct_call_to_eval(contains_direct_call_to_eval)
  65. , m_is_arrow_function(is_arrow_function)
  66. , m_kind(kind)
  67. {
  68. // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate
  69. // 9. If thisMode is lexical-this, set F.[[ThisMode]] to lexical.
  70. if (m_is_arrow_function)
  71. m_this_mode = ThisMode::Lexical;
  72. // 10. Else if Strict is true, set F.[[ThisMode]] to strict.
  73. else if (m_strict)
  74. m_this_mode = ThisMode::Strict;
  75. else
  76. // 11. Else, set F.[[ThisMode]] to global.
  77. m_this_mode = ThisMode::Global;
  78. // 15. Set F.[[ScriptOrModule]] to GetActiveScriptOrModule().
  79. m_script_or_module = vm().get_active_script_or_module();
  80. // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist
  81. m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) {
  82. if (parameter.is_rest)
  83. return false;
  84. if (parameter.default_value)
  85. return false;
  86. if (!parameter.binding.template has<DeprecatedFlyString>())
  87. return false;
  88. return true;
  89. });
  90. }
  91. void ECMAScriptFunctionObject::initialize(Realm& realm)
  92. {
  93. auto& vm = this->vm();
  94. Base::initialize(realm);
  95. // Note: The ordering of these properties must be: length, name, prototype which is the order
  96. // they are defined in the spec: https://tc39.es/ecma262/#sec-function-instances .
  97. // This is observable through something like: https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
  98. // which must give the properties in chronological order which in this case is the order they
  99. // are defined in the spec.
  100. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true }));
  101. MUST(define_property_or_throw(vm.names.name, { .value = PrimitiveString::create(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true }));
  102. if (!m_is_arrow_function) {
  103. Object* prototype = nullptr;
  104. switch (m_kind) {
  105. case FunctionKind::Normal:
  106. prototype = vm.heap().allocate<Object>(realm, *realm.intrinsics().new_ordinary_function_prototype_object_shape());
  107. MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true }));
  108. break;
  109. case FunctionKind::Generator:
  110. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  111. prototype = Object::create(realm, realm.intrinsics().generator_function_prototype_prototype());
  112. break;
  113. case FunctionKind::Async:
  114. break;
  115. case FunctionKind::AsyncGenerator:
  116. prototype = Object::create(realm, realm.intrinsics().async_generator_function_prototype_prototype());
  117. break;
  118. }
  119. // 27.7.4 AsyncFunction Instances, https://tc39.es/ecma262/#sec-async-function-instances
  120. // AsyncFunction instances do not have a prototype property as they are not constructible.
  121. if (m_kind != FunctionKind::Async)
  122. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  123. }
  124. }
  125. // 10.2.1 [[Call]] ( thisArgument, argumentsList ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-call-thisargument-argumentslist
  126. ThrowCompletionOr<Value> ECMAScriptFunctionObject::internal_call(Value this_argument, MarkedVector<Value> arguments_list)
  127. {
  128. auto& vm = this->vm();
  129. // 1. Let callerContext be the running execution context.
  130. // NOTE: No-op, kept by the VM in its execution context stack.
  131. ExecutionContext callee_context(heap());
  132. // Non-standard
  133. callee_context.arguments.extend(move(arguments_list));
  134. if (auto* interpreter = vm.interpreter_if_exists())
  135. callee_context.current_node = interpreter->current_node();
  136. // 2. Let calleeContext be PrepareForOrdinaryCall(F, undefined).
  137. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  138. TRY(prepare_for_ordinary_call(callee_context, nullptr));
  139. // 3. Assert: calleeContext is now the running execution context.
  140. VERIFY(&vm.running_execution_context() == &callee_context);
  141. // 4. If F.[[IsClassConstructor]] is true, then
  142. if (m_is_class_constructor) {
  143. // a. Let error be a newly created TypeError object.
  144. // b. NOTE: error is created in calleeContext with F's associated Realm Record.
  145. auto throw_completion = vm.throw_completion<TypeError>(ErrorType::ClassConstructorWithoutNew, m_name);
  146. // c. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  147. vm.pop_execution_context();
  148. // d. Return ThrowCompletion(error).
  149. return throw_completion;
  150. }
  151. // 5. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  152. ordinary_call_bind_this(callee_context, this_argument);
  153. // 6. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  154. auto result = ordinary_call_evaluate_body();
  155. // 7. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  156. vm.pop_execution_context();
  157. // 8. If result.[[Type]] is return, return result.[[Value]].
  158. if (result.type() == Completion::Type::Return)
  159. return result.value();
  160. // 9. ReturnIfAbrupt(result).
  161. if (result.is_abrupt()) {
  162. VERIFY(result.is_error());
  163. return result;
  164. }
  165. // 10. Return undefined.
  166. return js_undefined();
  167. }
  168. // 10.2.2 [[Construct]] ( argumentsList, newTarget ), https://tc39.es/ecma262/#sec-ecmascript-function-objects-construct-argumentslist-newtarget
  169. ThrowCompletionOr<NonnullGCPtr<Object>> ECMAScriptFunctionObject::internal_construct(MarkedVector<Value> arguments_list, FunctionObject& new_target)
  170. {
  171. auto& vm = this->vm();
  172. // 1. Let callerContext be the running execution context.
  173. // NOTE: No-op, kept by the VM in its execution context stack.
  174. // 2. Let kind be F.[[ConstructorKind]].
  175. auto kind = m_constructor_kind;
  176. GCPtr<Object> this_argument;
  177. // 3. If kind is base, then
  178. if (kind == ConstructorKind::Base) {
  179. // a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
  180. this_argument = TRY(ordinary_create_from_constructor<Object>(vm, new_target, &Intrinsics::object_prototype, ConstructWithPrototypeTag::Tag));
  181. }
  182. ExecutionContext callee_context(heap());
  183. // Non-standard
  184. callee_context.arguments.extend(move(arguments_list));
  185. if (auto* interpreter = vm.interpreter_if_exists())
  186. callee_context.current_node = interpreter->current_node();
  187. // 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
  188. // NOTE: We throw if the end of the native stack is reached, so unlike in the spec this _does_ need an exception check.
  189. TRY(prepare_for_ordinary_call(callee_context, &new_target));
  190. // 5. Assert: calleeContext is now the running execution context.
  191. VERIFY(&vm.running_execution_context() == &callee_context);
  192. // 6. If kind is base, then
  193. if (kind == ConstructorKind::Base) {
  194. // a. Perform OrdinaryCallBindThis(F, calleeContext, thisArgument).
  195. ordinary_call_bind_this(callee_context, this_argument);
  196. // b. Let initializeResult be Completion(InitializeInstanceElements(thisArgument, F)).
  197. auto initialize_result = this_argument->initialize_instance_elements(*this);
  198. // c. If initializeResult is an abrupt completion, then
  199. if (initialize_result.is_throw_completion()) {
  200. // i. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  201. vm.pop_execution_context();
  202. // ii. Return ? initializeResult.
  203. return initialize_result.throw_completion();
  204. }
  205. }
  206. // 7. Let constructorEnv be the LexicalEnvironment of calleeContext.
  207. auto* constructor_env = callee_context.lexical_environment;
  208. // 8. Let result be Completion(OrdinaryCallEvaluateBody(F, argumentsList)).
  209. auto result = ordinary_call_evaluate_body();
  210. // 9. Remove calleeContext from the execution context stack and restore callerContext as the running execution context.
  211. vm.pop_execution_context();
  212. // 10. If result.[[Type]] is return, then
  213. if (result.type() == Completion::Type::Return) {
  214. // FIXME: This is leftover from untangling the call/construct mess - doesn't belong here in any way, but removing it breaks derived classes.
  215. // Likely fixed by making ClassDefinitionEvaluation fully spec compliant.
  216. if (kind == ConstructorKind::Derived && result.value()->is_object()) {
  217. auto prototype = TRY(new_target.get(vm.names.prototype));
  218. if (prototype.is_object())
  219. TRY(result.value()->as_object().internal_set_prototype_of(&prototype.as_object()));
  220. }
  221. // EOF (End of FIXME)
  222. // a. If Type(result.[[Value]]) is Object, return result.[[Value]].
  223. if (result.value()->is_object())
  224. return result.value()->as_object();
  225. // b. If kind is base, return thisArgument.
  226. if (kind == ConstructorKind::Base)
  227. return *this_argument;
  228. // c. If result.[[Value]] is not undefined, throw a TypeError exception.
  229. if (!result.value()->is_undefined())
  230. return vm.throw_completion<TypeError>(ErrorType::DerivedConstructorReturningInvalidValue);
  231. }
  232. // 11. Else, ReturnIfAbrupt(result).
  233. else if (result.is_abrupt()) {
  234. VERIFY(result.is_error());
  235. return result;
  236. }
  237. // 12. Let thisBinding be ? constructorEnv.GetThisBinding().
  238. auto this_binding = TRY(constructor_env->get_this_binding(vm));
  239. // 13. Assert: Type(thisBinding) is Object.
  240. VERIFY(this_binding.is_object());
  241. // 14. Return thisBinding.
  242. return this_binding.as_object();
  243. }
  244. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  245. {
  246. Base::visit_edges(visitor);
  247. visitor.visit(m_environment);
  248. visitor.visit(m_private_environment);
  249. visitor.visit(m_realm);
  250. visitor.visit(m_home_object);
  251. for (auto& field : m_fields) {
  252. if (auto* property_key_ptr = field.name.get_pointer<PropertyKey>(); property_key_ptr && property_key_ptr->is_symbol())
  253. visitor.visit(property_key_ptr->as_symbol());
  254. }
  255. m_script_or_module.visit(
  256. [](Empty) {},
  257. [&](auto& script_or_module) {
  258. visitor.visit(script_or_module.ptr());
  259. });
  260. }
  261. // 10.2.7 MakeMethod ( F, homeObject ), https://tc39.es/ecma262/#sec-makemethod
  262. void ECMAScriptFunctionObject::make_method(Object& home_object)
  263. {
  264. // 1. Set F.[[HomeObject]] to homeObject.
  265. m_home_object = &home_object;
  266. // 2. Return unused.
  267. }
  268. // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  269. ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter)
  270. {
  271. auto& vm = this->vm();
  272. auto& realm = *vm.current_realm();
  273. auto& callee_context = vm.running_execution_context();
  274. // Needed to extract declarations and functions
  275. ScopeNode const* scope_body = nullptr;
  276. if (is<ScopeNode>(*m_ecmascript_code))
  277. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  278. bool has_parameter_expressions = false;
  279. // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases)
  280. bool has_duplicates = false;
  281. HashTable<DeprecatedFlyString> parameter_names;
  282. for (auto& parameter : m_formal_parameters) {
  283. if (parameter.default_value)
  284. has_parameter_expressions = true;
  285. parameter.binding.visit(
  286. [&](DeprecatedFlyString const& name) {
  287. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  288. has_duplicates = true;
  289. },
  290. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  291. if (pattern->contains_expression())
  292. has_parameter_expressions = true;
  293. pattern->for_each_bound_name([&](auto& name) {
  294. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  295. has_duplicates = true;
  296. });
  297. });
  298. }
  299. auto arguments_object_needed = m_might_need_arguments_object;
  300. if (this_mode() == ThisMode::Lexical)
  301. arguments_object_needed = false;
  302. if (parameter_names.contains(vm.names.arguments.as_string()))
  303. arguments_object_needed = false;
  304. HashTable<DeprecatedFlyString> function_names;
  305. Vector<FunctionDeclaration const&> functions_to_initialize;
  306. if (scope_body) {
  307. scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  308. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  309. functions_to_initialize.append(function);
  310. });
  311. auto const& arguments_name = vm.names.arguments.as_string();
  312. if (!has_parameter_expressions && function_names.contains(arguments_name))
  313. arguments_object_needed = false;
  314. if (!has_parameter_expressions && arguments_object_needed) {
  315. scope_body->for_each_lexically_declared_name([&](auto const& name) {
  316. if (name == arguments_name)
  317. arguments_object_needed = false;
  318. });
  319. }
  320. } else {
  321. arguments_object_needed = false;
  322. }
  323. GCPtr<Environment> environment;
  324. if (is_strict_mode() || !has_parameter_expressions) {
  325. environment = callee_context.lexical_environment;
  326. } else {
  327. environment = new_declarative_environment(*callee_context.lexical_environment);
  328. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  329. callee_context.lexical_environment = environment;
  330. }
  331. for (auto const& parameter_name : parameter_names) {
  332. if (MUST(environment->has_binding(parameter_name)))
  333. continue;
  334. MUST(environment->create_mutable_binding(vm, parameter_name, false));
  335. if (has_duplicates)
  336. MUST(environment->initialize_binding(vm, parameter_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  337. }
  338. if (arguments_object_needed) {
  339. Object* arguments_object;
  340. if (is_strict_mode() || !has_simple_parameter_list())
  341. arguments_object = create_unmapped_arguments_object(vm, vm.running_execution_context().arguments);
  342. else
  343. arguments_object = create_mapped_arguments_object(vm, *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  344. if (is_strict_mode())
  345. MUST(environment->create_immutable_binding(vm, vm.names.arguments.as_string(), false));
  346. else
  347. MUST(environment->create_mutable_binding(vm, vm.names.arguments.as_string(), false));
  348. MUST(environment->initialize_binding(vm, vm.names.arguments.as_string(), arguments_object, Environment::InitializeBindingHint::Normal));
  349. parameter_names.set(vm.names.arguments.as_string());
  350. }
  351. // We now treat parameterBindings as parameterNames.
  352. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  353. auto& execution_context_arguments = vm.running_execution_context().arguments;
  354. size_t default_parameter_index = 0;
  355. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  356. auto& parameter = m_formal_parameters[i];
  357. if (parameter.default_value)
  358. ++default_parameter_index;
  359. TRY(parameter.binding.visit(
  360. [&](auto const& param) -> ThrowCompletionOr<void> {
  361. Value argument_value;
  362. if (parameter.is_rest) {
  363. auto array = MUST(Array::create(realm, 0));
  364. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  365. array->indexed_properties().append(execution_context_arguments[rest_index]);
  366. argument_value = array;
  367. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  368. argument_value = execution_context_arguments[i];
  369. } else if (parameter.default_value) {
  370. if (auto* bytecode_interpreter = Bytecode::Interpreter::current()) {
  371. auto value_and_frame = bytecode_interpreter->run_and_return_frame(*m_default_parameter_bytecode_executables[default_parameter_index - 1], nullptr);
  372. if (value_and_frame.value.is_error())
  373. return value_and_frame.value.release_error();
  374. // Resulting value is in the accumulator.
  375. argument_value = value_and_frame.frame->registers.at(0);
  376. } else if (interpreter) {
  377. argument_value = TRY(parameter.default_value->execute(*interpreter)).release_value();
  378. }
  379. } else {
  380. argument_value = js_undefined();
  381. }
  382. Environment* used_environment = has_duplicates ? nullptr : environment;
  383. if constexpr (IsSame<DeprecatedFlyString const&, decltype(param)>) {
  384. Reference reference = TRY(vm.resolve_binding(param, used_environment));
  385. // Here the difference from hasDuplicates is important
  386. if (has_duplicates)
  387. return reference.put_value(vm, argument_value);
  388. else
  389. return reference.initialize_referenced_binding(vm, argument_value);
  390. } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) {
  391. // Here the difference from hasDuplicates is important
  392. return vm.binding_initialization(param, argument_value, used_environment);
  393. }
  394. }));
  395. }
  396. GCPtr<Environment> var_environment;
  397. HashTable<DeprecatedFlyString> instantiated_var_names;
  398. if (scope_body)
  399. instantiated_var_names.ensure_capacity(scope_body->var_declaration_count());
  400. if (!has_parameter_expressions) {
  401. if (scope_body) {
  402. scope_body->for_each_var_declared_name([&](auto const& name) {
  403. if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) {
  404. MUST(environment->create_mutable_binding(vm, name, false));
  405. MUST(environment->initialize_binding(vm, name, js_undefined(), Environment::InitializeBindingHint::Normal));
  406. }
  407. });
  408. }
  409. var_environment = environment;
  410. } else {
  411. var_environment = new_declarative_environment(*environment);
  412. callee_context.variable_environment = var_environment;
  413. if (scope_body) {
  414. scope_body->for_each_var_declared_name([&](auto const& name) {
  415. if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  416. return;
  417. MUST(var_environment->create_mutable_binding(vm, name, false));
  418. Value initial_value;
  419. if (!parameter_names.contains(name) || function_names.contains(name))
  420. initial_value = js_undefined();
  421. else
  422. initial_value = MUST(environment->get_binding_value(vm, name, false));
  423. MUST(var_environment->initialize_binding(vm, name, initial_value, Environment::InitializeBindingHint::Normal));
  424. });
  425. }
  426. }
  427. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  428. if (!m_strict && scope_body) {
  429. scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  430. auto& function_name = function_declaration.name();
  431. if (parameter_names.contains(function_name))
  432. return;
  433. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  434. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  435. MUST(var_environment->create_mutable_binding(vm, function_name, false));
  436. MUST(var_environment->initialize_binding(vm, function_name, js_undefined(), Environment::InitializeBindingHint::Normal));
  437. instantiated_var_names.set(function_name);
  438. }
  439. function_declaration.set_should_do_additional_annexB_steps();
  440. });
  441. }
  442. GCPtr<Environment> lex_environment;
  443. // 30. If strict is false, then
  444. if (!is_strict_mode()) {
  445. // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true:
  446. // 1. there is no direct call to eval() within this function
  447. // 2. there are no lexical declarations that would go into the environment
  448. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  449. if (can_elide_declarative_environment) {
  450. lex_environment = var_environment;
  451. } else {
  452. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  453. // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval
  454. // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level
  455. // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places
  456. // all declarations into a new Environment Record.
  457. lex_environment = new_declarative_environment(*var_environment);
  458. }
  459. } else {
  460. // 31. Else, let lexEnv be varEnv.
  461. lex_environment = var_environment;
  462. }
  463. // 32. Set the LexicalEnvironment of calleeContext to lexEnv.
  464. callee_context.lexical_environment = lex_environment;
  465. if (!scope_body)
  466. return {};
  467. if (!Bytecode::Interpreter::current()) {
  468. scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  469. declaration.for_each_bound_name([&](auto const& name) {
  470. if (declaration.is_constant_declaration())
  471. MUST(lex_environment->create_immutable_binding(vm, name, true));
  472. else
  473. MUST(lex_environment->create_mutable_binding(vm, name, false));
  474. });
  475. });
  476. }
  477. auto* private_environment = callee_context.private_environment;
  478. for (auto& declaration : functions_to_initialize) {
  479. auto function = ECMAScriptFunctionObject::create(realm, declaration.name(), declaration.source_text(), declaration.body(), declaration.parameters(), declaration.function_length(), lex_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  480. MUST(var_environment->set_mutable_binding(vm, declaration.name(), function, false));
  481. }
  482. if (is<DeclarativeEnvironment>(*lex_environment))
  483. static_cast<DeclarativeEnvironment*>(lex_environment.ptr())->shrink_to_fit();
  484. if (is<DeclarativeEnvironment>(*var_environment))
  485. static_cast<DeclarativeEnvironment*>(var_environment.ptr())->shrink_to_fit();
  486. return {};
  487. }
  488. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  489. ThrowCompletionOr<void> ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  490. {
  491. auto& vm = this->vm();
  492. // Non-standard
  493. callee_context.is_strict_mode = m_strict;
  494. // 1. Let callerContext be the running execution context.
  495. // 2. Let calleeContext be a new ECMAScript code execution context.
  496. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  497. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  498. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  499. // 3. Set the Function of calleeContext to F.
  500. callee_context.function = this;
  501. callee_context.function_name = m_name;
  502. // 4. Let calleeRealm be F.[[Realm]].
  503. auto* callee_realm = m_realm;
  504. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  505. // every function has a realm - especially in LibWeb that's sometimes not the case
  506. // when a function is created while no JS is running, as we currently need to rely on
  507. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  508. // If there's no 'current realm' either, we can't continue and crash.
  509. if (!callee_realm)
  510. callee_realm = vm.current_realm();
  511. VERIFY(callee_realm);
  512. // 5. Set the Realm of calleeContext to calleeRealm.
  513. callee_context.realm = callee_realm;
  514. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  515. callee_context.script_or_module = m_script_or_module;
  516. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  517. auto local_environment = new_function_environment(*this, new_target);
  518. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  519. callee_context.lexical_environment = local_environment;
  520. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  521. callee_context.variable_environment = local_environment;
  522. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  523. callee_context.private_environment = m_private_environment;
  524. // 11. If callerContext is not already suspended, suspend callerContext.
  525. // FIXME: We don't have this concept yet.
  526. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  527. TRY(vm.push_execution_context(callee_context, {}));
  528. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  529. // 14. Return calleeContext.
  530. // NOTE: See the comment after step 2 above about how contexts are allocated on the C++ stack.
  531. return {};
  532. }
  533. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  534. void ECMAScriptFunctionObject::ordinary_call_bind_this(ExecutionContext& callee_context, Value this_argument)
  535. {
  536. auto& vm = this->vm();
  537. // 1. Let thisMode be F.[[ThisMode]].
  538. auto this_mode = m_this_mode;
  539. // If thisMode is lexical, return unused.
  540. if (this_mode == ThisMode::Lexical)
  541. return;
  542. // 3. Let calleeRealm be F.[[Realm]].
  543. auto* callee_realm = m_realm;
  544. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  545. // every function has a realm - especially in LibWeb that's sometimes not the case
  546. // when a function is created while no JS is running, as we currently need to rely on
  547. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  548. // If there's no 'current realm' either, we can't continue and crash.
  549. if (!callee_realm)
  550. callee_realm = vm.current_realm();
  551. VERIFY(callee_realm);
  552. // 4. Let localEnv be the LexicalEnvironment of calleeContext.
  553. auto* local_env = callee_context.lexical_environment;
  554. Value this_value;
  555. // 5. If thisMode is strict, let thisValue be thisArgument.
  556. if (this_mode == ThisMode::Strict) {
  557. this_value = this_argument;
  558. }
  559. // 6. Else,
  560. else {
  561. // a. If thisArgument is undefined or null, then
  562. if (this_argument.is_nullish()) {
  563. // i. Let globalEnv be calleeRealm.[[GlobalEnv]].
  564. // ii. Assert: globalEnv is a global Environment Record.
  565. auto& global_env = callee_realm->global_environment();
  566. // iii. Let thisValue be globalEnv.[[GlobalThisValue]].
  567. this_value = &global_env.global_this_value();
  568. }
  569. // b. Else,
  570. else {
  571. // i. Let thisValue be ! ToObject(thisArgument).
  572. this_value = MUST(this_argument.to_object(vm));
  573. // ii. NOTE: ToObject produces wrapper objects using calleeRealm.
  574. VERIFY(vm.current_realm() == callee_realm);
  575. }
  576. }
  577. // 7. Assert: localEnv is a function Environment Record.
  578. // 8. Assert: The next step never returns an abrupt completion because localEnv.[[ThisBindingStatus]] is not initialized.
  579. // 9. Perform ! localEnv.BindThisValue(thisValue).
  580. MUST(verify_cast<FunctionEnvironment>(local_env)->bind_this_value(vm, this_value));
  581. // 10. Return unused.
  582. }
  583. // 27.7.5.1 AsyncFunctionStart ( promiseCapability, asyncFunctionBody ), https://tc39.es/ecma262/#sec-async-functions-abstract-operations-async-function-start
  584. void ECMAScriptFunctionObject::async_function_start(PromiseCapability const& promise_capability)
  585. {
  586. auto& vm = this->vm();
  587. // 1. Let runningContext be the running execution context.
  588. auto& running_context = vm.running_execution_context();
  589. // 2. Let asyncContext be a copy of runningContext.
  590. auto async_context = running_context.copy();
  591. // 3. NOTE: Copying the execution state is required for AsyncBlockStart to resume its execution. It is ill-defined to resume a currently executing context.
  592. // 4. Perform AsyncBlockStart(promiseCapability, asyncFunctionBody, asyncContext).
  593. async_block_start(vm, m_ecmascript_code, promise_capability, async_context);
  594. // 5. Return unused.
  595. }
  596. // 27.7.5.2 AsyncBlockStart ( promiseCapability, asyncBody, asyncContext ), https://tc39.es/ecma262/#sec-asyncblockstart
  597. void async_block_start(VM& vm, NonnullRefPtr<Statement> const& async_body, PromiseCapability const& promise_capability, ExecutionContext& async_context)
  598. {
  599. auto& realm = *vm.current_realm();
  600. // 1. Assert: promiseCapability is a PromiseCapability Record.
  601. // 2. Let runningContext be the running execution context.
  602. auto& running_context = vm.running_execution_context();
  603. // 3. Set the code evaluation state of asyncContext such that when evaluation is resumed for that execution context the following steps will be performed:
  604. auto execution_steps = NativeFunction::create(realm, "", [&async_body, &promise_capability](auto& vm) -> ThrowCompletionOr<Value> {
  605. // a. Let result be the result of evaluating asyncBody.
  606. auto result = async_body->execute(vm.interpreter());
  607. // b. Assert: If we return here, the async function either threw an exception or performed an implicit or explicit return; all awaiting is done.
  608. // c. 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.
  609. vm.pop_execution_context();
  610. // d. If result.[[Type]] is normal, then
  611. if (result.type() == Completion::Type::Normal) {
  612. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « undefined »).
  613. MUST(call(vm, *promise_capability.resolve(), js_undefined(), js_undefined()));
  614. }
  615. // e. Else if result.[[Type]] is return, then
  616. else if (result.type() == Completion::Type::Return) {
  617. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « result.[[Value]] »).
  618. MUST(call(vm, *promise_capability.resolve(), js_undefined(), *result.value()));
  619. }
  620. // f. Else,
  621. else {
  622. // i. Assert: result.[[Type]] is throw.
  623. VERIFY(result.type() == Completion::Type::Throw);
  624. // ii. Perform ! Call(promiseCapability.[[Reject]], undefined, « result.[[Value]] »).
  625. MUST(call(vm, *promise_capability.reject(), js_undefined(), *result.value()));
  626. }
  627. // g. Return unused.
  628. // NOTE: We don't support returning an empty/optional/unused value here.
  629. return js_undefined();
  630. });
  631. // 4. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  632. auto push_result = vm.push_execution_context(async_context, {});
  633. if (push_result.is_error())
  634. return;
  635. // 5. Resume the suspended evaluation of asyncContext. Let result be the value returned by the resumed computation.
  636. auto result = call(vm, *execution_steps, async_context.this_value.is_empty() ? js_undefined() : async_context.this_value);
  637. // 6. Assert: When we return here, asyncContext has already been removed from the execution context stack and runningContext is the currently running execution context.
  638. VERIFY(&vm.running_execution_context() == &running_context);
  639. // 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.
  640. VERIFY(result.has_value() && result.value().is_undefined());
  641. // 8. Return unused.
  642. }
  643. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  644. // 15.8.4 Runtime Semantics: EvaluateAsyncFunctionBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatefunctionbody
  645. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  646. {
  647. auto& vm = this->vm();
  648. auto& realm = *vm.current_realm();
  649. if (m_kind == FunctionKind::AsyncGenerator)
  650. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Async Generator function execution");
  651. auto* bytecode_interpreter = Bytecode::Interpreter::current();
  652. // The bytecode interpreter can execute generator functions while the AST interpreter cannot.
  653. // This simply makes it create a new bytecode interpreter when one doesn't exist when executing a generator function.
  654. // Doing so makes it automatically switch to the bytecode interpreter to execute any future code until it exits the generator. See below.
  655. // This allows us to keep all of the existing functionality that works in AST while adding generator support on top of it.
  656. // However, this does cause an awkward situation with features not supported in bytecode, where features that work outside of generators with AST
  657. // suddenly stop working inside of generators.
  658. // This is a stop gap until bytecode mode becomes the default.
  659. OwnPtr<Bytecode::Interpreter> temp_bc_interpreter;
  660. if (m_kind == FunctionKind::Generator && !bytecode_interpreter) {
  661. temp_bc_interpreter = make<Bytecode::Interpreter>(realm);
  662. bytecode_interpreter = temp_bc_interpreter.ptr();
  663. }
  664. if (bytecode_interpreter) {
  665. if (!m_bytecode_executable) {
  666. auto compile = [&](auto& node, auto kind, auto name) -> ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> {
  667. auto executable_result = Bytecode::Generator::generate(node, kind);
  668. if (executable_result.is_error())
  669. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, executable_result.error().to_deprecated_string());
  670. auto bytecode_executable = executable_result.release_value();
  671. bytecode_executable->name = name;
  672. auto& passes = Bytecode::Interpreter::optimization_pipeline();
  673. passes.perform(*bytecode_executable);
  674. if constexpr (JS_BYTECODE_DEBUG) {
  675. dbgln("Optimisation passes took {}us", passes.elapsed());
  676. dbgln("Compiled Bytecode::Block for function '{}':", m_name);
  677. }
  678. if (Bytecode::g_dump_bytecode)
  679. bytecode_executable->dump();
  680. return bytecode_executable;
  681. };
  682. m_bytecode_executable = TRY(compile(*m_ecmascript_code, m_kind, m_name));
  683. size_t default_parameter_index = 0;
  684. for (auto& parameter : m_formal_parameters) {
  685. if (!parameter.default_value)
  686. continue;
  687. auto executable = TRY(compile(*parameter.default_value, FunctionKind::Normal, DeprecatedString::formatted("default parameter #{} for {}", default_parameter_index, m_name)));
  688. m_default_parameter_bytecode_executables.append(move(executable));
  689. }
  690. }
  691. TRY(function_declaration_instantiation(nullptr));
  692. auto result_and_frame = bytecode_interpreter->run_and_return_frame(*m_bytecode_executable, nullptr);
  693. VERIFY(result_and_frame.frame != nullptr);
  694. if (result_and_frame.value.is_error())
  695. return result_and_frame.value.release_error();
  696. auto result = result_and_frame.value.release_value();
  697. // NOTE: Running the bytecode should eventually return a completion.
  698. // Until it does, we assume "return" and include the undefined fallback from the call site.
  699. if (m_kind == FunctionKind::Normal)
  700. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  701. auto generator_object = TRY(GeneratorObject::create(realm, result, this, vm.running_execution_context().copy(), move(*result_and_frame.frame)));
  702. // NOTE: Async functions are entirely transformed to generator functions, and wrapped in a custom driver that returns a promise
  703. // See AwaitExpression::generate_bytecode() for the transformation.
  704. if (m_kind == FunctionKind::Async)
  705. return { Completion::Type::Return, TRY(AsyncFunctionDriverWrapper::create(realm, generator_object)), {} };
  706. VERIFY(m_kind == FunctionKind::Generator);
  707. return { Completion::Type::Return, generator_object, {} };
  708. } else {
  709. if (m_kind == FunctionKind::Generator)
  710. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, "Generator function execution in AST interpreter");
  711. OwnPtr<Interpreter> local_interpreter;
  712. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  713. if (!ast_interpreter) {
  714. local_interpreter = Interpreter::create_with_existing_realm(realm);
  715. ast_interpreter = local_interpreter.ptr();
  716. }
  717. VM::InterpreterExecutionScope scope(*ast_interpreter);
  718. // FunctionBody : FunctionStatementList
  719. if (m_kind == FunctionKind::Normal) {
  720. // 1. Perform ? FunctionDeclarationInstantiation(functionObject, argumentsList).
  721. TRY(function_declaration_instantiation(ast_interpreter));
  722. // 2. Return the result of evaluating FunctionStatementList.
  723. return m_ecmascript_code->execute(*ast_interpreter);
  724. }
  725. // AsyncFunctionBody : FunctionBody
  726. else if (m_kind == FunctionKind::Async) {
  727. // 1. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  728. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  729. // 2. Let declResult be Completion(FunctionDeclarationInstantiation(functionObject, argumentsList)).
  730. auto declaration_result = function_declaration_instantiation(ast_interpreter);
  731. // 3. If declResult is an abrupt completion, then
  732. if (declaration_result.is_throw_completion()) {
  733. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « declResult.[[Value]] »).
  734. MUST(call(vm, *promise_capability->reject(), js_undefined(), *declaration_result.throw_completion().value()));
  735. }
  736. // 4. Else,
  737. else {
  738. // a. Perform AsyncFunctionStart(promiseCapability, FunctionBody).
  739. async_function_start(promise_capability);
  740. }
  741. // 5. Return Completion Record { [[Type]]: return, [[Value]]: promiseCapability.[[Promise]], [[Target]]: empty }.
  742. return Completion { Completion::Type::Return, promise_capability->promise(), {} };
  743. }
  744. }
  745. VERIFY_NOT_REACHED();
  746. }
  747. void ECMAScriptFunctionObject::set_name(DeprecatedFlyString const& name)
  748. {
  749. VERIFY(!name.is_null());
  750. auto& vm = this->vm();
  751. m_name = name;
  752. MUST(define_property_or_throw(vm.names.name, { .value = PrimitiveString::create(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  753. }
  754. }