ECMAScriptFunctionObject.cpp 43 KB

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