StringObject.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/GlobalObject.h>
  8. #include <LibJS/Runtime/PrimitiveString.h>
  9. #include <LibJS/Runtime/StringObject.h>
  10. namespace JS {
  11. StringObject* StringObject::create(GlobalObject& global_object, PrimitiveString& primitive_string)
  12. {
  13. return global_object.heap().allocate<StringObject>(global_object, primitive_string, *global_object.string_prototype());
  14. }
  15. StringObject::StringObject(PrimitiveString& string, Object& prototype)
  16. : Object(prototype)
  17. , m_string(string)
  18. {
  19. }
  20. StringObject::~StringObject()
  21. {
  22. }
  23. void StringObject::initialize(GlobalObject& global_object)
  24. {
  25. auto& vm = this->vm();
  26. Object::initialize(global_object);
  27. define_property(vm.names.length, Value(m_string.string().length()), 0);
  28. }
  29. void StringObject::visit_edges(Cell::Visitor& visitor)
  30. {
  31. Object::visit_edges(visitor);
  32. visitor.visit(&m_string);
  33. }
  34. Optional<PropertyDescriptor> StringObject::get_own_property_descriptor(PropertyName const& property_name) const
  35. {
  36. if (!property_name.is_number() || property_name.as_number() >= m_string.string().length())
  37. return Base::get_own_property_descriptor(property_name);
  38. PropertyDescriptor descriptor;
  39. descriptor.value = js_string(heap(), m_string.string().substring(property_name.as_number(), 1));
  40. descriptor.attributes.set_has_configurable();
  41. descriptor.attributes.set_has_enumerable();
  42. descriptor.attributes.set_has_writable();
  43. descriptor.attributes.set_enumerable();
  44. return descriptor;
  45. }
  46. }