ECMAScriptFunctionObject.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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/Array.h>
  14. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  15. #include <LibJS/Runtime/Error.h>
  16. #include <LibJS/Runtime/FunctionEnvironment.h>
  17. #include <LibJS/Runtime/GeneratorObject.h>
  18. #include <LibJS/Runtime/GeneratorObjectPrototype.h>
  19. #include <LibJS/Runtime/GlobalObject.h>
  20. #include <LibJS/Runtime/NativeFunction.h>
  21. #include <LibJS/Runtime/Value.h>
  22. namespace JS {
  23. 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)
  24. {
  25. Object* prototype = nullptr;
  26. switch (kind) {
  27. case FunctionKind::Regular:
  28. prototype = global_object.function_prototype();
  29. break;
  30. case FunctionKind::Generator:
  31. prototype = global_object.generator_function_prototype();
  32. break;
  33. }
  34. 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);
  35. }
  36. 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)
  37. : FunctionObject(prototype)
  38. , m_environment(parent_scope)
  39. , m_formal_parameters(move(formal_parameters))
  40. , m_ecmascript_code(ecmascript_code)
  41. , m_realm(vm().interpreter_if_exists() ? &vm().interpreter().realm() : nullptr)
  42. , m_strict(strict)
  43. , m_name(move(name))
  44. , m_function_length(function_length)
  45. , m_kind(kind)
  46. , m_is_arrow_function(is_arrow_function)
  47. {
  48. // NOTE: This logic is from OrdinaryFunctionCreate, https://tc39.es/ecma262/#sec-ordinaryfunctioncreate
  49. if (m_is_arrow_function)
  50. m_this_mode = ThisMode::Lexical;
  51. else if (m_strict)
  52. m_this_mode = ThisMode::Strict;
  53. else
  54. m_this_mode = ThisMode::Global;
  55. // 15.1.3 Static Semantics: IsSimpleParameterList, https://tc39.es/ecma262/#sec-static-semantics-issimpleparameterlist
  56. m_has_simple_parameter_list = all_of(m_formal_parameters, [&](auto& parameter) {
  57. if (parameter.is_rest)
  58. return false;
  59. if (parameter.default_value)
  60. return false;
  61. if (!parameter.binding.template has<FlyString>())
  62. return false;
  63. return true;
  64. });
  65. }
  66. void ECMAScriptFunctionObject::initialize(GlobalObject& global_object)
  67. {
  68. auto& vm = this->vm();
  69. Base::initialize(global_object);
  70. if (!m_is_arrow_function) {
  71. auto* prototype = vm.heap().allocate<Object>(global_object, *global_object.new_ordinary_function_prototype_object_shape());
  72. switch (m_kind) {
  73. case FunctionKind::Regular:
  74. prototype->define_property_or_throw(vm.names.constructor, { .value = this, .writable = true, .enumerable = false, .configurable = true });
  75. break;
  76. case FunctionKind::Generator:
  77. // prototype is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  78. (void)prototype->internal_set_prototype_of(global_object.generator_object_prototype());
  79. break;
  80. }
  81. define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  82. }
  83. define_property_or_throw(vm.names.length, { .value = Value(m_function_length), .writable = false, .enumerable = false, .configurable = true });
  84. define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name.is_null() ? "" : m_name), .writable = false, .enumerable = false, .configurable = true });
  85. }
  86. ECMAScriptFunctionObject::~ECMAScriptFunctionObject()
  87. {
  88. }
  89. void ECMAScriptFunctionObject::visit_edges(Visitor& visitor)
  90. {
  91. Base::visit_edges(visitor);
  92. visitor.visit(m_environment);
  93. visitor.visit(m_realm);
  94. visitor.visit(m_home_object);
  95. for (auto& field : m_fields) {
  96. field.name.visit_edges(visitor);
  97. visitor.visit(field.initializer);
  98. }
  99. }
  100. FunctionEnvironment* ECMAScriptFunctionObject::create_environment(FunctionObject& function_being_invoked)
  101. {
  102. HashMap<FlyString, Variable> variables;
  103. for (auto& parameter : m_formal_parameters) {
  104. parameter.binding.visit(
  105. [&](const FlyString& name) { variables.set(name, { js_undefined(), DeclarationKind::Var }); },
  106. [&](const NonnullRefPtr<BindingPattern>& binding) {
  107. binding->for_each_bound_name([&](const auto& name) {
  108. variables.set(name, { js_undefined(), DeclarationKind::Var });
  109. });
  110. });
  111. }
  112. if (is<ScopeNode>(ecmascript_code())) {
  113. for (auto& declaration : static_cast<const ScopeNode&>(ecmascript_code()).variables()) {
  114. for (auto& declarator : declaration.declarations()) {
  115. declarator.target().visit(
  116. [&](const NonnullRefPtr<Identifier>& id) {
  117. variables.set(id->string(), { js_undefined(), declaration.declaration_kind() });
  118. },
  119. [&](const NonnullRefPtr<BindingPattern>& binding) {
  120. binding->for_each_bound_name([&](const auto& name) {
  121. variables.set(name, { js_undefined(), declaration.declaration_kind() });
  122. });
  123. });
  124. }
  125. }
  126. }
  127. auto* environment = heap().allocate<FunctionEnvironment>(global_object(), m_environment, move(variables));
  128. environment->set_function_object(static_cast<ECMAScriptFunctionObject&>(function_being_invoked));
  129. if (m_is_arrow_function) {
  130. environment->set_this_binding_status(FunctionEnvironment::ThisBindingStatus::Lexical);
  131. if (is<FunctionEnvironment>(m_environment))
  132. environment->set_new_target(static_cast<FunctionEnvironment*>(m_environment)->new_target());
  133. }
  134. return environment;
  135. }
  136. Value ECMAScriptFunctionObject::execute_function_body()
  137. {
  138. auto& vm = this->vm();
  139. Interpreter* ast_interpreter = nullptr;
  140. auto* bytecode_interpreter = Bytecode::Interpreter::current();
  141. auto prepare_arguments = [&] {
  142. auto& execution_context_arguments = vm.running_execution_context().arguments;
  143. for (size_t i = 0; i < m_formal_parameters.size(); ++i) {
  144. auto& parameter = m_formal_parameters[i];
  145. parameter.binding.visit(
  146. [&](const auto& param) {
  147. Value argument_value;
  148. if (parameter.is_rest) {
  149. auto* array = Array::create(global_object(), 0);
  150. for (size_t rest_index = i; rest_index < execution_context_arguments.size(); ++rest_index)
  151. array->indexed_properties().append(execution_context_arguments[rest_index]);
  152. argument_value = move(array);
  153. } else if (i < execution_context_arguments.size() && !execution_context_arguments[i].is_undefined()) {
  154. argument_value = execution_context_arguments[i];
  155. } else if (parameter.default_value) {
  156. // FIXME: Support default arguments in the bytecode world!
  157. if (!bytecode_interpreter)
  158. argument_value = parameter.default_value->execute(*ast_interpreter, global_object());
  159. if (vm.exception())
  160. return;
  161. } else {
  162. argument_value = js_undefined();
  163. }
  164. vm.assign(param, argument_value, global_object(), true, vm.lexical_environment());
  165. });
  166. if (vm.exception())
  167. return;
  168. }
  169. };
  170. if (bytecode_interpreter) {
  171. prepare_arguments();
  172. if (!m_bytecode_executable.has_value()) {
  173. m_bytecode_executable = Bytecode::Generator::generate(m_ecmascript_code, m_kind == FunctionKind::Generator);
  174. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  175. passes.perform(*m_bytecode_executable);
  176. if constexpr (JS_BYTECODE_DEBUG) {
  177. dbgln("Optimisation passes took {}us", passes.elapsed());
  178. dbgln("Compiled Bytecode::Block for function '{}':", m_name);
  179. for (auto& block : m_bytecode_executable->basic_blocks)
  180. block.dump(*m_bytecode_executable);
  181. }
  182. }
  183. auto result = bytecode_interpreter->run(*m_bytecode_executable);
  184. if (m_kind != FunctionKind::Generator)
  185. return result;
  186. return GeneratorObject::create(global_object(), result, this, vm.running_execution_context().lexical_environment, bytecode_interpreter->snapshot_frame());
  187. } else {
  188. VERIFY(m_kind != FunctionKind::Generator);
  189. OwnPtr<Interpreter> local_interpreter;
  190. ast_interpreter = vm.interpreter_if_exists();
  191. if (!ast_interpreter) {
  192. local_interpreter = Interpreter::create_with_existing_realm(*realm());
  193. ast_interpreter = local_interpreter.ptr();
  194. }
  195. VM::InterpreterExecutionScope scope(*ast_interpreter);
  196. prepare_arguments();
  197. if (vm.exception())
  198. return {};
  199. return ast_interpreter->execute_statement(global_object(), m_ecmascript_code, ScopeType::Function);
  200. }
  201. }
  202. Value ECMAScriptFunctionObject::call()
  203. {
  204. if (m_is_class_constructor) {
  205. vm().throw_exception<TypeError>(global_object(), ErrorType::ClassConstructorWithoutNew, m_name);
  206. return {};
  207. }
  208. return execute_function_body();
  209. }
  210. Value ECMAScriptFunctionObject::construct(FunctionObject&)
  211. {
  212. if (m_is_arrow_function || m_kind == FunctionKind::Generator) {
  213. vm().throw_exception<TypeError>(global_object(), ErrorType::NotAConstructor, m_name);
  214. return {};
  215. }
  216. return execute_function_body();
  217. }
  218. void ECMAScriptFunctionObject::set_name(const FlyString& name)
  219. {
  220. VERIFY(!name.is_null());
  221. auto& vm = this->vm();
  222. m_name = name;
  223. auto success = define_property_or_throw(vm.names.name, { .value = js_string(vm, m_name), .writable = false, .enumerable = false, .configurable = true });
  224. VERIFY(success);
  225. }
  226. // 7.3.31 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield
  227. void ECMAScriptFunctionObject::InstanceField::define_field(VM& vm, Object& receiver) const
  228. {
  229. Value init_value = js_undefined();
  230. if (initializer) {
  231. auto init_value_or_error = vm.call(*initializer, receiver.value_of());
  232. if (init_value_or_error.is_error())
  233. return;
  234. init_value = init_value_or_error.release_value();
  235. }
  236. receiver.create_data_property_or_throw(name, init_value);
  237. }
  238. }