ScriptFunction.cpp 9.6 KB

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