ECMAScriptFunctionObject.cpp 33 KB

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