ECMAScriptFunctionObject.cpp 40 KB

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