StringObject.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. // 10.4.3.4 StringCreate ( value, prototype ), https://tc39.es/ecma262/#sec-stringcreate
  12. StringObject* StringObject::create(GlobalObject& global_object, PrimitiveString& primitive_string, Object& prototype)
  13. {
  14. return global_object.heap().allocate<StringObject>(global_object, primitive_string, prototype);
  15. }
  16. StringObject::StringObject(PrimitiveString& string, Object& prototype)
  17. : Object(prototype)
  18. , m_string(string)
  19. {
  20. }
  21. StringObject::~StringObject()
  22. {
  23. }
  24. void StringObject::initialize(GlobalObject& global_object)
  25. {
  26. auto& vm = this->vm();
  27. Object::initialize(global_object);
  28. define_property(vm.names.length, Value(m_string.string().length()), 0);
  29. }
  30. void StringObject::visit_edges(Cell::Visitor& visitor)
  31. {
  32. Object::visit_edges(visitor);
  33. visitor.visit(&m_string);
  34. }
  35. Optional<PropertyDescriptor> StringObject::get_own_property_descriptor(PropertyName const& property_name) const
  36. {
  37. if (!property_name.is_number() || property_name.as_number() >= m_string.string().length())
  38. return Base::get_own_property_descriptor(property_name);
  39. PropertyDescriptor descriptor;
  40. descriptor.value = js_string(heap(), m_string.string().substring(property_name.as_number(), 1));
  41. descriptor.attributes.set_has_configurable();
  42. descriptor.attributes.set_has_enumerable();
  43. descriptor.attributes.set_has_writable();
  44. descriptor.attributes.set_enumerable();
  45. return descriptor;
  46. }
  47. }