ECMAScriptFunctionObject.cpp 40 KB

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