FunctionObject.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. : Object(prototype)
  13. {
  14. }
  15. FunctionObject::~FunctionObject()
  16. {
  17. }
  18. BoundFunction* FunctionObject::bind(Value bound_this_value, Vector<Value> arguments)
  19. {
  20. auto& vm = this->vm();
  21. FunctionObject& target_function = is<BoundFunction>(*this) ? static_cast<BoundFunction&>(*this).bound_target_function() : *this;
  22. auto bound_this_object = [&vm, bound_this_value, this]() -> Value {
  23. if (is<BoundFunction>(*this) && !static_cast<BoundFunction&>(*this).bound_this().is_empty())
  24. return static_cast<BoundFunction&>(*this).bound_this();
  25. switch (bound_this_value.type()) {
  26. case Value::Type::Undefined:
  27. case Value::Type::Null:
  28. if (vm.in_strict_mode())
  29. return bound_this_value;
  30. return &global_object();
  31. default:
  32. return bound_this_value.to_object(global_object());
  33. }
  34. }();
  35. i32 computed_length = 0;
  36. auto length_property = get(vm.names.length);
  37. if (vm.exception())
  38. return nullptr;
  39. if (length_property.is_number())
  40. computed_length = max(0, length_property.as_i32() - static_cast<i32>(arguments.size()));
  41. Object* constructor_prototype = nullptr;
  42. auto prototype_property = target_function.get(vm.names.prototype);
  43. if (vm.exception())
  44. return nullptr;
  45. if (prototype_property.is_object())
  46. constructor_prototype = &prototype_property.as_object();
  47. Vector<Value> all_bound_arguments;
  48. if (is<BoundFunction>(*this))
  49. all_bound_arguments.extend(static_cast<BoundFunction&>(*this).bound_arguments());
  50. all_bound_arguments.extend(move(arguments));
  51. return heap().allocate<BoundFunction>(global_object(), global_object(), target_function, bound_this_object, move(all_bound_arguments), computed_length, constructor_prototype);
  52. }
  53. }