ECMAScriptFunctionObject.cpp 34 KB

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