ECMAScriptFunctionObject.cpp 33 KB

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