ECMAScriptFunctionObject.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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 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, 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 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_is_arrow_function(is_arrow_function)
  49. {
  50. // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate
  51. if (m_is_arrow_function)
  52. m_this_mode = ThisMode::Lexical;
  53. else if (m_strict)
  54. m_this_mode = ThisMode::Strict;
  55. else
  56. m_this_mode = ThisMode::Global;
  57. // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist
  58. m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) {
  59. if (parameter.is_rest)
  60. return false;
  61. if (parameter.default_value)
  62. return false;
  63. if (!parameter.binding.template has<FlyString>())
  64. return false;
  65. return true;
  66. });
  67. }
  68. void ECMAScriptFunctionObject::initialize(GlobalObject& global_object)
  69. {
  70. auto& vm = this->vm();
  71. Base::initialize(global_object);
  72. if (!m_is_arrow_function) {
  73. auto* prototype = vm.heap().allocate<Object>(global_object, *global_object.new_ordinary_function_prototype_object_shape());
  74. switch (m_kind) {
  75. case FunctionKind::Regular:
  76. MUST(prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true }));
  77. break;
  78. case FunctionKind::Generator:
  79. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  80. set_prototype(global_object.generator_object_prototype());
  81. break;
  82. }
  83. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  84. }
  85. MUST(define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true }));
  86. MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true }));
  87. }
  88. ECMAScriptFunctionObject::~ECMAScriptFunctionObject()
  89. {
  90. }
  91. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  92. {
  93. Base::visit_edges(visitor);
  94. visitor.visit(m_environment);
  95. visitor.visit(m_realm);
  96. visitor.visit(m_home_object);
  97. for (auto& field : m_fields) {
  98. field.name.visit_edges(visitor);
  99. visitor.visit(field.initializer);
  100. }
  101. }
  102. // 9.1.2.4 NewFunctionEnvironment ( F, newTarget ), https://tc39.es/ecma262/#sec-newfunctionenvironment
  103. FunctionEnvironment* ECMAScriptFunctionObject::new_function_environment(Object* new_target)
  104. {
  105. auto* environment = heap().allocate<FunctionEnvironment>(global_object(), m_environment);
  106. environment->set_function_object(*this);
  107. if (this_mode() == ThisMode::Lexical) {
  108. environment->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);
  109. }
  110. environment->set_new_target(new_target ? new_target : js_undefined());
  111. return environment;
  112. }
  113. // 10.2.11 FunctionDeclarationInstantiation ( func, argumentsList ), https://tc39.es/ecma262/#sec-functiondeclarationinstantiation
  114. ThrowCompletionOr<void> ECMAScriptFunctionObject::function_declaration_instantiation(Interpreter* interpreter)
  115. {
  116. auto& vm = this->vm();
  117. auto& callee_context = vm.running_execution_context();
  118. // Needed to extract declarations and functions
  119. ScopeNode const* scope_body = nullptr;
  120. if (is<ScopeNode>(*m_ecmascript_code))
  121. scope_body = static_cast<ScopeNode const*>(m_ecmascript_code.ptr());
  122. bool has_parameter_expressions = false;
  123. // FIXME: Maybe compute has duplicates at parse time? (We need to anyway since it's an error in some cases)
  124. bool has_duplicates = false;
  125. HashTable<FlyString> parameter_names;
  126. for (auto& parameter : m_formal_parameters) {
  127. if (parameter.default_value)
  128. has_parameter_expressions = true;
  129. parameter.binding.visit(
  130. [&](FlyString const& name) {
  131. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  132. has_duplicates = true;
  133. },
  134. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  135. if (pattern->contains_expression())
  136. has_parameter_expressions = true;
  137. pattern->for_each_bound_name([&](auto& name) {
  138. if (parameter_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  139. has_duplicates = true;
  140. });
  141. });
  142. }
  143. auto arguments_object_needed = m_might_need_arguments_object;
  144. if (this_mode() == ThisMode::Lexical)
  145. arguments_object_needed = false;
  146. if (parameter_names.contains(vm.names.arguments.as_string()))
  147. arguments_object_needed = false;
  148. HashTable<FlyString> function_names;
  149. Vector<FunctionDeclaration const&> functions_to_initialize;
  150. if (scope_body) {
  151. scope_body->for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  152. if (function_names.set(function.name()) == AK::HashSetResult::InsertedNewEntry)
  153. functions_to_initialize.append(function);
  154. });
  155. auto const& arguments_name = vm.names.arguments.as_string();
  156. if (!has_parameter_expressions && function_names.contains(arguments_name))
  157. arguments_object_needed = false;
  158. if (!has_parameter_expressions && arguments_object_needed) {
  159. scope_body->for_each_lexically_declared_name([&](auto const& name) {
  160. if (name == arguments_name) {
  161. arguments_object_needed = false;
  162. return IterationDecision::Break;
  163. }
  164. return IterationDecision::Continue;
  165. });
  166. }
  167. } else {
  168. arguments_object_needed = false;
  169. }
  170. Environment* environment;
  171. if (is_strict_mode() || !has_parameter_expressions) {
  172. environment = callee_context.lexical_environment;
  173. } else {
  174. environment = new_declarative_environment(*callee_context.lexical_environment);
  175. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  176. callee_context.lexical_environment = environment;
  177. }
  178. for (auto const& parameter_name : parameter_names) {
  179. if (environment->has_binding(parameter_name))
  180. continue;
  181. environment->create_mutable_binding(global_object(), parameter_name, false);
  182. if (has_duplicates)
  183. environment->initialize_binding(global_object(), parameter_name, js_undefined());
  184. VERIFY(!vm.exception());
  185. }
  186. if (arguments_object_needed) {
  187. Object* arguments_object;
  188. if (is_strict_mode() || !has_simple_parameter_list())
  189. arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments);
  190. else
  191. arguments_object = create_mapped_arguments_object(global_object(), *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  192. if (is_strict_mode())
  193. environment->create_immutable_binding(global_object(), vm.names.arguments.as_string(), false);
  194. else
  195. environment->create_mutable_binding(global_object(), vm.names.arguments.as_string(), false);
  196. environment->initialize_binding(global_object(), vm.names.arguments.as_string(), arguments_object);
  197. parameter_names.set(vm.names.arguments.as_string());
  198. }
  199. // We now treat parameterBindings as parameterNames.
  200. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  201. auto& execution_context_arguments = vm.running_execution_context().arguments;
  202. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  203. auto& parameter = m_formal_parameters[i];
  204. parameter.binding.visit(
  205. [&](auto const& param) {
  206. Value argument_value;
  207. if (parameter.is_rest) {
  208. auto* array = Array::create(global_object(), 0);
  209. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  210. array->indexed_properties().append(execution_context_arguments[rest_index]);
  211. argument_value = move(array);
  212. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  213. argument_value = execution_context_arguments[i];
  214. } else if (parameter.default_value) {
  215. // FIXME: Support default arguments in the bytecode world!
  216. if (interpreter)
  217. argument_value = parameter.default_value->execute(*interpreter, global_object());
  218. if (vm.exception())
  219. return;
  220. } else {
  221. argument_value = js_undefined();
  222. }
  223. Environment* used_environment = has_duplicates ? nullptr : environment;
  224. if constexpr (IsSame<FlyString const&, decltype(param)>) {
  225. Reference reference = vm.resolve_binding(param, used_environment);
  226. if (vm.exception())
  227. return;
  228. // Here the difference from hasDuplicates is important
  229. if (has_duplicates)
  230. reference.put_value(global_object(), argument_value);
  231. else
  232. reference.initialize_referenced_binding(global_object(), argument_value);
  233. } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) {
  234. // Here the difference from hasDuplicates is important
  235. auto result = vm.binding_initialization(param, argument_value, used_environment, global_object());
  236. if (result.is_error())
  237. return;
  238. }
  239. if (vm.exception())
  240. return;
  241. });
  242. if (auto* exception = vm.exception())
  243. return throw_completion(exception->value());
  244. }
  245. Environment* var_environment;
  246. HashTable<FlyString> instantiated_var_names;
  247. if (scope_body)
  248. instantiated_var_names.ensure_capacity(scope_body->var_declaration_count());
  249. if (!has_parameter_expressions) {
  250. if (scope_body) {
  251. scope_body->for_each_var_declared_name([&](auto const& name) {
  252. if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) {
  253. environment->create_mutable_binding(global_object(), name, false);
  254. environment->initialize_binding(global_object(), name, js_undefined());
  255. }
  256. });
  257. }
  258. var_environment = environment;
  259. } else {
  260. var_environment = new_declarative_environment(*environment);
  261. callee_context.variable_environment = var_environment;
  262. if (scope_body) {
  263. scope_body->for_each_var_declared_name([&](auto const& name) {
  264. if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  265. return IterationDecision::Continue;
  266. var_environment->create_mutable_binding(global_object(), name, false);
  267. Value initial_value;
  268. if (!parameter_names.contains(name) || function_names.contains(name))
  269. initial_value = js_undefined();
  270. else
  271. initial_value = environment->get_binding_value(global_object(), name, false);
  272. var_environment->initialize_binding(global_object(), name, initial_value);
  273. return IterationDecision::Continue;
  274. });
  275. }
  276. }
  277. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  278. if (!m_strict && scope_body) {
  279. scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  280. auto& function_name = function_declaration.name();
  281. if (parameter_names.contains(function_name))
  282. return IterationDecision::Continue;
  283. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  284. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  285. var_environment->create_mutable_binding(global_object(), function_name, false);
  286. VERIFY(!vm.exception());
  287. var_environment->initialize_binding(global_object(), function_name, js_undefined());
  288. instantiated_var_names.set(function_name);
  289. }
  290. function_declaration.set_should_do_additional_annexB_steps();
  291. return IterationDecision::Continue;
  292. });
  293. }
  294. Environment* lex_environment;
  295. if (!is_strict_mode())
  296. lex_environment = new_declarative_environment(*var_environment);
  297. else
  298. lex_environment = var_environment;
  299. callee_context.lexical_environment = lex_environment;
  300. if (!scope_body)
  301. return {};
  302. scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  303. declaration.for_each_bound_name([&](auto const& name) {
  304. if (declaration.is_constant_declaration())
  305. lex_environment->create_immutable_binding(global_object(), name, true);
  306. else
  307. lex_environment->create_mutable_binding(global_object(), name, false);
  308. return IterationDecision::Continue;
  309. });
  310. });
  311. VERIFY(!vm.exception());
  312. for (auto& declaration : functions_to_initialize) {
  313. 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());
  314. var_environment->set_mutable_binding(global_object(), declaration.name(), function, false);
  315. }
  316. return {};
  317. }
  318. Value ECMAScriptFunctionObject::execute_function_body()
  319. {
  320. auto& vm = this->vm();
  321. auto* bytecode_interpreter = Bytecode::Interpreter::current();
  322. if (bytecode_interpreter) {
  323. // FIXME: pass something to evaluate default arguments with
  324. TRY_OR_DISCARD(function_declaration_instantiation(nullptr));
  325. if (!m_bytecode_executable.has_value()) {
  326. m_bytecode_executable = Bytecode::Generator::generate(m_ecmascript_code, m_kind == FunctionKind::Generator);
  327. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  328. passes.perform(*m_bytecode_executable);
  329. if constexpr (JS_BYTECODE_DEBUG) {
  330. dbgln("Optimisation passes took {}us", passes.elapsed());
  331. dbgln("Compiled Bytecode::Block for function '{}':", m_name);
  332. for (auto& block : m_bytecode_executable->basic_blocks)
  333. block.dump(*m_bytecode_executable);
  334. }
  335. }
  336. auto result = bytecode_interpreter->run(*m_bytecode_executable);
  337. if (m_kind != FunctionKind::Generator)
  338. return result;
  339. return GeneratorObject::create(global_object(), result, this, vm.running_execution_context().lexical_environment, bytecode_interpreter->snapshot_frame());
  340. } else {
  341. VERIFY(m_kind != FunctionKind::Generator);
  342. OwnPtr<Interpreter> local_interpreter;
  343. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  344. if (!ast_interpreter) {
  345. local_interpreter = Interpreter::create_with_existing_realm(*realm());
  346. ast_interpreter = local_interpreter.ptr();
  347. }
  348. VM::InterpreterExecutionScope scope(*ast_interpreter);
  349. TRY_OR_DISCARD(function_declaration_instantiation(ast_interpreter));
  350. return m_ecmascript_code->execute(*ast_interpreter, global_object());
  351. }
  352. }
  353. Value ECMAScriptFunctionObject::call()
  354. {
  355. if (m_is_class_constructor) {
  356. vm().throw_exception<TypeError>(global_object(), ErrorType::ClassConstructorWithoutNew, m_name);
  357. return {};
  358. }
  359. return execute_function_body();
  360. }
  361. Value ECMAScriptFunctionObject::construct(FunctionObject&)
  362. {
  363. if (m_is_arrow_function || m_kind == FunctionKind::Generator) {
  364. vm().throw_exception<TypeError>(global_object(), ErrorType::NotAConstructor, m_name);
  365. return {};
  366. }
  367. return execute_function_body();
  368. }
  369. void ECMAScriptFunctionObject::set_name(const FlyString& name)
  370. {
  371. VERIFY(!name.is_null());
  372. auto& vm = this->vm();
  373. m_name = name;
  374. auto success = MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  375. VERIFY(success);
  376. }
  377. // 7.3.31 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
  378. void ECMAScriptFunctionObject::InstanceField::define_field(VM& vm, Object& receiver) const
  379. {
  380. Value init_value = js_undefined();
  381. if (initializer) {
  382. auto init_value_or_error = vm.call(*initializer, receiver.value_of());
  383. if (init_value_or_error.is_error())
  384. return;
  385. init_value = init_value_or_error.release_value();
  386. }
  387. (void)receiver.create_data_property_or_throw(name, init_value);
  388. }
  389. }