OrdinaryFunctionObject.cpp 11 KB

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