FunctionObject.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Interpreter.h>
  7. #include <LibJS/Runtime/BoundFunction.h>
  8. #include <LibJS/Runtime/FunctionObject.h>
  9. #include <LibJS/Runtime/GlobalObject.h>
  10. namespace JS {
  11. FunctionObject::FunctionObject(Object& prototype)
  12. : FunctionObject({}, {}, prototype)
  13. {
  14. }
  15. FunctionObject::FunctionObject(Value bound_this, Vector<Value> bound_arguments, Object& prototype)
  16. : Object(prototype)
  17. , m_bound_this(bound_this)
  18. , m_bound_arguments(move(bound_arguments))
  19. {
  20. }
  21. FunctionObject::~FunctionObject()
  22. {
  23. }
  24. BoundFunction* FunctionObject::bind(Value bound_this_value, Vector<Value> arguments)
  25. {
  26. auto& vm = this->vm();
  27. FunctionObject& target_function = is<BoundFunction>(*this) ? static_cast<BoundFunction&>(*this).target_function() : *this;
  28. auto bound_this_object = [&vm, bound_this_value, this]() -> Value {
  29. if (!m_bound_this.is_empty())
  30. return m_bound_this;
  31. switch (bound_this_value.type()) {
  32. case Value::Type::Undefined:
  33. case Value::Type::Null:
  34. if (vm.in_strict_mode())
  35. return bound_this_value;
  36. return &global_object();
  37. default:
  38. return bound_this_value.to_object(global_object());
  39. }
  40. }();
  41. i32 computed_length = 0;
  42. auto length_property = get(vm.names.length);
  43. if (vm.exception())
  44. return nullptr;
  45. if (length_property.is_number())
  46. computed_length = max(0, length_property.as_i32() - static_cast<i32>(arguments.size()));
  47. Object* constructor_prototype = nullptr;
  48. auto prototype_property = target_function.get(vm.names.prototype);
  49. if (vm.exception())
  50. return nullptr;
  51. if (prototype_property.is_object())
  52. constructor_prototype = &prototype_property.as_object();
  53. auto all_bound_arguments = bound_arguments();
  54. all_bound_arguments.extend(move(arguments));
  55. return heap().allocate<BoundFunction>(global_object(), global_object(), target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
  56. }
  57. void FunctionObject::visit_edges(Visitor& visitor)
  58. {
  59. Object::visit_edges(visitor);
  60. visitor.visit(m_home_object);
  61. visitor.visit(m_bound_this);
  62. for (auto argument : m_bound_arguments)
  63. visitor.visit(argument);
  64. }
  65. }