ECMAScriptFunctionObject.cpp 41 KB

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