ECMAScriptFunctionObject.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. vm.ordinary_call_bind_this(*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. vm.ordinary_call_bind_this(*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 = constructor_env->get_this_binding(global_object);
  215. if (auto* exception = vm.exception())
  216. return throw_completion(exception->value());
  217. return &this_binding.as_object();
  218. }
  219. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  220. {
  221. Base::visit_edges(visitor);
  222. visitor.visit(m_environment);
  223. visitor.visit(m_realm);
  224. visitor.visit(m_home_object);
  225. for (auto& field : m_fields) {
  226. field.name.visit_edges(visitor);
  227. visitor.visit(field.initializer);
  228. }
  229. }
  230. // 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/ecma262/#sec-newfunctionenvironment
  231. FunctionEnvironment* ECMAScriptFunctionObject::new_function_environment(Object* new_target)
  232. {
  233. auto* environment = heap().allocate<FunctionEnvironment>(global_object(), m_environment);
  234. environment->set_function_object(*this);
  235. if (this_mode() == ThisMode::Lexical) {
  236. environment->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);
  237. }
  238. environment->set_new_target(new_target ? new_target : js_undefined());
  239. return environment;
  240. }
  241. // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  242. ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter)
  243. {
  244. auto& vm = this->vm();
  245. auto& callee_context = vm.running_execution_context();
  246. // Needed to extract declarations and functions
  247. ScopeNode const* scope_body = nullptr;
  248. if (is<ScopeNode>(*m_ecmascript_code))
  249. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  250. bool has_parameter_expressions = false;
  251. // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases)
  252. bool has_duplicates = false;
  253. HashTable<FlyString> parameter_names;
  254. for (auto& parameter : m_formal_parameters) {
  255. if (parameter.default_value)
  256. has_parameter_expressions = true;
  257. parameter.binding.visit(
  258. [&](FlyString const& name) {
  259. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  260. has_duplicates = true;
  261. },
  262. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  263. if (pattern->contains_expression())
  264. has_parameter_expressions = true;
  265. pattern->for_each_bound_name([&](auto& name) {
  266. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  267. has_duplicates = true;
  268. });
  269. });
  270. }
  271. auto arguments_object_needed = m_might_need_arguments_object;
  272. if (this_mode() == ThisMode::Lexical)
  273. arguments_object_needed = false;
  274. if (parameter_names.contains(vm.names.arguments.as_string()))
  275. arguments_object_needed = false;
  276. HashTable<FlyString> function_names;
  277. Vector<FunctionDeclaration const&> functions_to_initialize;
  278. if (scope_body) {
  279. scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  280. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  281. functions_to_initialize.append(function);
  282. });
  283. auto const& arguments_name = vm.names.arguments.as_string();
  284. if (!has_parameter_expressions && function_names.contains(arguments_name))
  285. arguments_object_needed = false;
  286. if (!has_parameter_expressions && arguments_object_needed) {
  287. scope_body->for_each_lexically_declared_name([&](auto const& name) {
  288. if (name == arguments_name) {
  289. arguments_object_needed = false;
  290. return IterationDecision::Break;
  291. }
  292. return IterationDecision::Continue;
  293. });
  294. }
  295. } else {
  296. arguments_object_needed = false;
  297. }
  298. Environment* environment;
  299. if (is_strict_mode() || !has_parameter_expressions) {
  300. environment = callee_context.lexical_environment;
  301. } else {
  302. environment = new_declarative_environment(*callee_context.lexical_environment);
  303. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  304. callee_context.lexical_environment = environment;
  305. }
  306. for (auto const& parameter_name : parameter_names) {
  307. if (environment->has_binding(parameter_name))
  308. continue;
  309. environment->create_mutable_binding(global_object(), parameter_name, false);
  310. if (has_duplicates)
  311. environment->initialize_binding(global_object(), parameter_name, js_undefined());
  312. VERIFY(!vm.exception());
  313. }
  314. if (arguments_object_needed) {
  315. Object* arguments_object;
  316. if (is_strict_mode() || !has_simple_parameter_list())
  317. arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments);
  318. else
  319. arguments_object = create_mapped_arguments_object(global_object(), *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  320. if (is_strict_mode())
  321. environment->create_immutable_binding(global_object(), vm.names.arguments.as_string(), false);
  322. else
  323. environment->create_mutable_binding(global_object(), vm.names.arguments.as_string(), false);
  324. environment->initialize_binding(global_object(), vm.names.arguments.as_string(), arguments_object);
  325. parameter_names.set(vm.names.arguments.as_string());
  326. }
  327. // We now treat parameterBindings as parameterNames.
  328. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  329. auto& execution_context_arguments = vm.running_execution_context().arguments;
  330. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  331. auto& parameter = m_formal_parameters[i];
  332. parameter.binding.visit(
  333. [&](auto const& param) {
  334. Value argument_value;
  335. if (parameter.is_rest) {
  336. auto* array = Array::create(global_object(), 0);
  337. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  338. array->indexed_properties().append(execution_context_arguments[rest_index]);
  339. argument_value = move(array);
  340. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  341. argument_value = execution_context_arguments[i];
  342. } else if (parameter.default_value) {
  343. // FIXME: Support default arguments in the bytecode world!
  344. if (interpreter)
  345. argument_value = parameter.default_value->execute(*interpreter, global_object());
  346. if (vm.exception())
  347. return;
  348. } else {
  349. argument_value = js_undefined();
  350. }
  351. Environment* used_environment = has_duplicates ? nullptr : environment;
  352. if constexpr (IsSame<FlyString const&, decltype(param)>) {
  353. Reference reference = vm.resolve_binding(param, used_environment);
  354. if (vm.exception())
  355. return;
  356. // Here the difference from hasDuplicates is important
  357. if (has_duplicates)
  358. reference.put_value(global_object(), argument_value);
  359. else
  360. reference.initialize_referenced_binding(global_object(), argument_value);
  361. } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) {
  362. // Here the difference from hasDuplicates is important
  363. auto result = vm.binding_initialization(param, argument_value, used_environment, global_object());
  364. if (result.is_error())
  365. return;
  366. }
  367. if (vm.exception())
  368. return;
  369. });
  370. if (auto* exception = vm.exception())
  371. return throw_completion(exception->value());
  372. }
  373. Environment* var_environment;
  374. HashTable<FlyString> instantiated_var_names;
  375. if (scope_body)
  376. instantiated_var_names.ensure_capacity(scope_body->var_declaration_count());
  377. if (!has_parameter_expressions) {
  378. if (scope_body) {
  379. scope_body->for_each_var_declared_name([&](auto const& name) {
  380. if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) {
  381. environment->create_mutable_binding(global_object(), name, false);
  382. environment->initialize_binding(global_object(), name, js_undefined());
  383. }
  384. });
  385. }
  386. var_environment = environment;
  387. } else {
  388. var_environment = new_declarative_environment(*environment);
  389. callee_context.variable_environment = var_environment;
  390. if (scope_body) {
  391. scope_body->for_each_var_declared_name([&](auto const& name) {
  392. if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  393. return IterationDecision::Continue;
  394. var_environment->create_mutable_binding(global_object(), name, false);
  395. Value initial_value;
  396. if (!parameter_names.contains(name) || function_names.contains(name))
  397. initial_value = js_undefined();
  398. else
  399. initial_value = environment->get_binding_value(global_object(), name, false);
  400. var_environment->initialize_binding(global_object(), name, initial_value);
  401. return IterationDecision::Continue;
  402. });
  403. }
  404. }
  405. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  406. if (!m_strict && scope_body) {
  407. scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  408. auto& function_name = function_declaration.name();
  409. if (parameter_names.contains(function_name))
  410. return IterationDecision::Continue;
  411. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  412. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  413. var_environment->create_mutable_binding(global_object(), function_name, false);
  414. VERIFY(!vm.exception());
  415. var_environment->initialize_binding(global_object(), function_name, js_undefined());
  416. instantiated_var_names.set(function_name);
  417. }
  418. function_declaration.set_should_do_additional_annexB_steps();
  419. return IterationDecision::Continue;
  420. });
  421. }
  422. Environment* lex_environment;
  423. // 30. If strict is false, then
  424. if (!is_strict_mode()) {
  425. // Optimization: We avoid creating empty top-level declarative environments in non-strict mode, if both of these conditions are true:
  426. // 1. there is no direct call to eval() within this function
  427. // 2. there are no lexical declarations that would go into the environment
  428. bool can_elide_declarative_environment = !m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_lexical_declarations());
  429. if (can_elide_declarative_environment) {
  430. lex_environment = var_environment;
  431. } else {
  432. // a. Let lexEnv be NewDeclarativeEnvironment(varEnv).
  433. // b. NOTE: Non-strict functions use a separate Environment Record for top-level lexical declarations so that a direct eval
  434. // can determine whether any var scoped declarations introduced by the eval code conflict with pre-existing top-level
  435. // lexically scoped declarations. This is not needed for strict functions because a strict direct eval always places
  436. // all declarations into a new Environment Record.
  437. lex_environment = new_declarative_environment(*var_environment);
  438. }
  439. } else {
  440. // 31. Else, let lexEnv be varEnv.
  441. lex_environment = var_environment;
  442. }
  443. // 32. Set the LexicalEnvironment of calleeContext to lexEnv.
  444. callee_context.lexical_environment = lex_environment;
  445. if (!scope_body)
  446. return {};
  447. scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  448. declaration.for_each_bound_name([&](auto const& name) {
  449. if (declaration.is_constant_declaration())
  450. lex_environment->create_immutable_binding(global_object(), name, true);
  451. else
  452. lex_environment->create_mutable_binding(global_object(), name, false);
  453. return IterationDecision::Continue;
  454. });
  455. });
  456. VERIFY(!vm.exception());
  457. for (auto& declaration : functions_to_initialize) {
  458. 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());
  459. var_environment->set_mutable_binding(global_object(), declaration.name(), function, false);
  460. }
  461. return {};
  462. }
  463. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  464. void ECMAScriptFunctionObject::prepare_for_ordinary_call(ExecutionContext& callee_context, Object* new_target)
  465. {
  466. auto& vm = this->vm();
  467. // Non-standard
  468. callee_context.is_strict_mode = m_strict;
  469. // 1. Let callerContext be the running execution context.
  470. // 2. Let calleeContext be a new ECMAScript code execution context.
  471. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  472. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  473. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  474. // 3. Set the Function of calleeContext to F.
  475. callee_context.function = this;
  476. callee_context.function_name = m_name;
  477. // 4. Let calleeRealm be F.[[Realm]].
  478. auto* callee_realm = m_realm;
  479. // NOTE: This non-standard fallback is needed until we can guarantee that literally
  480. // every function has a realm - especially in LibWeb that's sometimes not the case
  481. // when a function is created while no JS is running, as we currently need to rely on
  482. // that (:acid2:, I know - see set_event_handler_attribute() for an example).
  483. // If there's no 'current realm' either, we can't continue and crash.
  484. if (!callee_realm)
  485. callee_realm = vm.current_realm();
  486. VERIFY(callee_realm);
  487. // 5. Set the Realm of calleeContext to calleeRealm.
  488. callee_context.realm = callee_realm;
  489. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  490. // FIXME: Our execution context struct currently does not track this item.
  491. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  492. auto* local_environment = new_function_environment(new_target);
  493. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  494. callee_context.lexical_environment = local_environment;
  495. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  496. callee_context.variable_environment = local_environment;
  497. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  498. // FIXME: We currently don't support private environments.
  499. // 11. If callerContext is not already suspended, suspend callerContext.
  500. // FIXME: We don't have this concept yet.
  501. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  502. vm.push_execution_context(callee_context, global_object());
  503. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  504. // 14. Return calleeContext. (See NOTE above about how contexts are allocated on the C++ stack.)
  505. }
  506. // 10.2.1.4 OrdinaryCallEvaluateBody ( F, argumentsList ), https://tc39.es/ecma262/#sec-ordinarycallevaluatebody
  507. Completion ECMAScriptFunctionObject::ordinary_call_evaluate_body()
  508. {
  509. auto& vm = this->vm();
  510. auto* bytecode_interpreter = Bytecode::Interpreter::current();
  511. if (bytecode_interpreter) {
  512. // FIXME: pass something to evaluate default arguments with
  513. TRY(function_declaration_instantiation(nullptr));
  514. if (!m_bytecode_executable.has_value()) {
  515. m_bytecode_executable = Bytecode::Generator::generate(m_ecmascript_code, m_kind == FunctionKind::Generator);
  516. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  517. passes.perform(*m_bytecode_executable);
  518. if constexpr (JS_BYTECODE_DEBUG) {
  519. dbgln("Optimisation passes took {}us", passes.elapsed());
  520. dbgln("Compiled Bytecode::Block for function '{}':", m_name);
  521. for (auto& block : m_bytecode_executable->basic_blocks)
  522. block.dump(*m_bytecode_executable);
  523. }
  524. }
  525. auto result = bytecode_interpreter->run(*m_bytecode_executable);
  526. if (auto* exception = vm.exception())
  527. return throw_completion(exception->value());
  528. // NOTE: Running the bytecode should eventually return a completion.
  529. // Until it does, we assume "return" and include the undefined fallback from the call site.
  530. if (m_kind != FunctionKind::Generator)
  531. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  532. return normal_completion(GeneratorObject::create(global_object(), result, this, vm.running_execution_context().lexical_environment, bytecode_interpreter->snapshot_frame()));
  533. } else {
  534. VERIFY(m_kind != FunctionKind::Generator);
  535. OwnPtr<Interpreter> local_interpreter;
  536. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  537. if (!ast_interpreter) {
  538. local_interpreter = Interpreter::create_with_existing_realm(*realm());
  539. ast_interpreter = local_interpreter.ptr();
  540. }
  541. VM::InterpreterExecutionScope scope(*ast_interpreter);
  542. TRY(function_declaration_instantiation(ast_interpreter));
  543. auto result = m_ecmascript_code->execute(*ast_interpreter, global_object());
  544. if (auto* exception = vm.exception())
  545. return throw_completion(exception->value());
  546. // NOTE: Running the AST node should eventually return a completion.
  547. // Until it does, we assume "return" and include the undefined fallback from the call site.
  548. return { Completion::Type::Return, result.value_or(js_undefined()), {} };
  549. }
  550. VERIFY_NOT_REACHED();
  551. }
  552. void ECMAScriptFunctionObject::set_name(const FlyString& name)
  553. {
  554. VERIFY(!name.is_null());
  555. auto& vm = this->vm();
  556. m_name = name;
  557. auto success = MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  558. VERIFY(success);
  559. }
  560. // 7.3.31 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
  561. void ECMAScriptFunctionObject::InstanceField::define_field(VM& vm, Object& receiver) const
  562. {
  563. Value init_value = js_undefined();
  564. if (initializer) {
  565. auto init_value_or_error = vm.call(*initializer, receiver.value_of());
  566. if (init_value_or_error.is_error())
  567. return;
  568. init_value = init_value_or_error.release_value();
  569. }
  570. (void)receiver.create_data_property_or_throw(name, init_value);
  571. }
  572. }