ECMAScriptFunctionObject.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 arguments_object_needed = this_mode() != ThisMode::Lexical;
  143. if (parameter_names.contains(vm.names.arguments.as_string()))
  144. arguments_object_needed = 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. arguments_object_needed = false;
  155. if (!has_parameter_expressions && arguments_object_needed) {
  156. scope_body->for_each_lexically_declared_name([&](auto const& name) {
  157. if (name == arguments_name) {
  158. arguments_object_needed = false;
  159. return IterationDecision::Break;
  160. }
  161. return IterationDecision::Continue;
  162. });
  163. }
  164. } else {
  165. arguments_object_needed = false;
  166. }
  167. Environment* environment;
  168. if (is_strict_mode() || !has_parameter_expressions) {
  169. environment = callee_context.lexical_environment;
  170. } else {
  171. environment = new_declarative_environment(*callee_context.lexical_environment);
  172. VERIFY(callee_context.variable_environment == callee_context.lexical_environment);
  173. callee_context.lexical_environment = environment;
  174. }
  175. for (auto const& parameter_name : parameter_names) {
  176. if (environment->has_binding(parameter_name))
  177. continue;
  178. environment->create_mutable_binding(global_object(), parameter_name, false);
  179. if (has_duplicates)
  180. environment->initialize_binding(global_object(), parameter_name, js_undefined());
  181. VERIFY(!vm.exception());
  182. }
  183. if (arguments_object_needed) {
  184. Object* arguments_object;
  185. if (is_strict_mode() || !has_simple_parameter_list())
  186. arguments_object = create_unmapped_arguments_object(global_object(), vm.running_execution_context().arguments);
  187. else
  188. arguments_object = create_mapped_arguments_object(global_object(), *this, formal_parameters(), vm.running_execution_context().arguments, *environment);
  189. if (is_strict_mode())
  190. environment->create_immutable_binding(global_object(), vm.names.arguments.as_string(), false);
  191. else
  192. environment->create_mutable_binding(global_object(), vm.names.arguments.as_string(), false);
  193. environment->initialize_binding(global_object(), vm.names.arguments.as_string(), arguments_object);
  194. parameter_names.set(vm.names.arguments.as_string());
  195. }
  196. // We now treat parameterBindings as parameterNames.
  197. // The spec makes an iterator here to do IteratorBindingInitialization but we just do it manually
  198. auto& execution_context_arguments = vm.running_execution_context().arguments;
  199. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  200. auto& parameter = m_formal_parameters[i];
  201. parameter.binding.visit(
  202. [&](auto const& param) {
  203. Value argument_value;
  204. if (parameter.is_rest) {
  205. auto* array = Array::create(global_object(), 0);
  206. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  207. array->indexed_properties().append(execution_context_arguments[rest_index]);
  208. argument_value = move(array);
  209. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  210. argument_value = execution_context_arguments[i];
  211. } else if (parameter.default_value) {
  212. // FIXME: Support default arguments in the bytecode world!
  213. if (interpreter)
  214. argument_value = parameter.default_value->execute(*interpreter, global_object());
  215. if (vm.exception())
  216. return;
  217. } else {
  218. argument_value = js_undefined();
  219. }
  220. Environment* used_environment = has_duplicates ? nullptr : environment;
  221. if constexpr (IsSame<FlyString const&, decltype(param)>) {
  222. Reference reference = vm.resolve_binding(param, used_environment);
  223. if (vm.exception())
  224. return;
  225. // Here the difference from hasDuplicates is important
  226. if (has_duplicates)
  227. reference.put_value(global_object(), argument_value);
  228. else
  229. reference.initialize_referenced_binding(global_object(), argument_value);
  230. } else if (IsSame<NonnullRefPtr<BindingPattern> const&, decltype(param)>) {
  231. // Here the difference from hasDuplicates is important
  232. auto result = vm.binding_initialization(param, argument_value, used_environment, global_object());
  233. if (result.is_error())
  234. return;
  235. }
  236. if (vm.exception())
  237. return;
  238. });
  239. if (auto* exception = vm.exception())
  240. return throw_completion(exception->value());
  241. }
  242. Environment* var_environment;
  243. HashTable<FlyString> instantiated_var_names;
  244. if (!has_parameter_expressions) {
  245. if (scope_body) {
  246. scope_body->for_each_var_declared_name([&](auto const& name) {
  247. if (!parameter_names.contains(name) && instantiated_var_names.set(name) == AK::HashSetResult::InsertedNewEntry) {
  248. environment->create_mutable_binding(global_object(), name, false);
  249. environment->initialize_binding(global_object(), name, js_undefined());
  250. }
  251. });
  252. }
  253. var_environment = environment;
  254. } else {
  255. var_environment = new_declarative_environment(*environment);
  256. callee_context.variable_environment = var_environment;
  257. if (scope_body) {
  258. scope_body->for_each_var_declared_name([&](auto const& name) {
  259. if (instantiated_var_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  260. return IterationDecision::Continue;
  261. var_environment->create_mutable_binding(global_object(), name, false);
  262. Value initial_value;
  263. if (!parameter_names.contains(name) || function_names.contains(name))
  264. initial_value = js_undefined();
  265. else
  266. initial_value = environment->get_binding_value(global_object(), name, false);
  267. var_environment->initialize_binding(global_object(), name, initial_value);
  268. return IterationDecision::Continue;
  269. });
  270. }
  271. }
  272. // B.3.2.1 Changes to FunctionDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  273. if (!m_strict && scope_body) {
  274. scope_body->for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  275. auto& function_name = function_declaration.name();
  276. if (parameter_names.contains(function_name))
  277. return IterationDecision::Continue;
  278. // The spec says 'initializedBindings' here but that does not exist and it then adds it to 'instantiatedVarNames' so it probably means 'instantiatedVarNames'.
  279. if (!instantiated_var_names.contains(function_name) && function_name != vm.names.arguments.as_string()) {
  280. var_environment->create_mutable_binding(global_object(), function_name, false);
  281. VERIFY(!vm.exception());
  282. var_environment->initialize_binding(global_object(), function_name, js_undefined());
  283. instantiated_var_names.set(function_name);
  284. }
  285. function_declaration.set_should_do_additional_annexB_steps();
  286. return IterationDecision::Continue;
  287. });
  288. }
  289. Environment* lex_environment;
  290. if (!is_strict_mode())
  291. lex_environment = new_declarative_environment(*var_environment);
  292. else
  293. lex_environment = var_environment;
  294. callee_context.lexical_environment = lex_environment;
  295. if (!scope_body)
  296. return {};
  297. scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  298. declaration.for_each_bound_name([&](auto const& name) {
  299. if (declaration.is_constant_declaration())
  300. lex_environment->create_immutable_binding(global_object(), name, true);
  301. else
  302. lex_environment->create_mutable_binding(global_object(), name, false);
  303. return IterationDecision::Continue;
  304. });
  305. });
  306. VERIFY(!vm.exception());
  307. for (auto& declaration : functions_to_initialize) {
  308. auto* function = ECMAScriptFunctionObject::create(global_object(), declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), lex_environment, declaration.kind(), declaration.is_strict_mode());
  309. var_environment->set_mutable_binding(global_object(), declaration.name(), function, false);
  310. }
  311. return {};
  312. }
  313. Value ECMAScriptFunctionObject::execute_function_body()
  314. {
  315. auto& vm = this->vm();
  316. auto* bytecode_interpreter = Bytecode::Interpreter::current();
  317. if (bytecode_interpreter) {
  318. // FIXME: pass something to evaluate default arguments with
  319. TRY_OR_DISCARD(function_declaration_instantiation(nullptr));
  320. if (!m_bytecode_executable.has_value()) {
  321. m_bytecode_executable = Bytecode::Generator::generate(m_ecmascript_code, m_kind == FunctionKind::Generator);
  322. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  323. passes.perform(*m_bytecode_executable);
  324. if constexpr (JS_BYTECODE_DEBUG) {
  325. dbgln("Optimisation passes took {}us", passes.elapsed());
  326. dbgln("Compiled Bytecode::Block for function '{}':", m_name);
  327. for (auto& block : m_bytecode_executable->basic_blocks)
  328. block.dump(*m_bytecode_executable);
  329. }
  330. }
  331. auto result = bytecode_interpreter->run(*m_bytecode_executable);
  332. if (m_kind != FunctionKind::Generator)
  333. return result;
  334. return GeneratorObject::create(global_object(), result, this, vm.running_execution_context().lexical_environment, bytecode_interpreter->snapshot_frame());
  335. } else {
  336. VERIFY(m_kind != FunctionKind::Generator);
  337. OwnPtr<Interpreter> local_interpreter;
  338. Interpreter* ast_interpreter = vm.interpreter_if_exists();
  339. if (!ast_interpreter) {
  340. local_interpreter = Interpreter::create_with_existing_realm(*realm());
  341. ast_interpreter = local_interpreter.ptr();
  342. }
  343. VM::InterpreterExecutionScope scope(*ast_interpreter);
  344. TRY_OR_DISCARD(function_declaration_instantiation(ast_interpreter));
  345. return m_ecmascript_code->execute(*ast_interpreter, global_object());
  346. }
  347. }
  348. Value ECMAScriptFunctionObject::call()
  349. {
  350. if (m_is_class_constructor) {
  351. vm().throw_exception<TypeError>(global_object(), ErrorType::ClassConstructorWithoutNew, m_name);
  352. return {};
  353. }
  354. return execute_function_body();
  355. }
  356. Value ECMAScriptFunctionObject::construct(FunctionObject&)
  357. {
  358. if (m_is_arrow_function || m_kind == FunctionKind::Generator) {
  359. vm().throw_exception<TypeError>(global_object(), ErrorType::NotAConstructor, m_name);
  360. return {};
  361. }
  362. return execute_function_body();
  363. }
  364. void ECMAScriptFunctionObject::set_name(const FlyString& name)
  365. {
  366. VERIFY(!name.is_null());
  367. auto& vm = this->vm();
  368. m_name = name;
  369. auto success = MUST(define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true }));
  370. VERIFY(success);
  371. }
  372. // 7.3.31 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
  373. void ECMAScriptFunctionObject::InstanceField::define_field(VM& vm, Object& receiver) const
  374. {
  375. Value init_value = js_undefined();
  376. if (initializer) {
  377. auto init_value_or_error = vm.call(*initializer, receiver.value_of());
  378. if (init_value_or_error.is_error())
  379. return;
  380. init_value = init_value_or_error.release_value();
  381. }
  382. (void)receiver.create_data_property_or_throw(name, init_value);
  383. }
  384. }