ECMAScriptFunctionObject.cpp 19 KB

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