PropertyAttributes.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/ByteString.h>
  9. #include <AK/Format.h>
  10. #include <AK/Types.h>
  11. #include <AK/Vector.h>
  12. namespace JS {
  13. struct Attribute {
  14. enum {
  15. Writable = 1 << 0,
  16. Enumerable = 1 << 1,
  17. Configurable = 1 << 2,
  18. };
  19. };
  20. // 6.1.7.1 Property Attributes, https://tc39.es/ecma262/#sec-property-attributes
  21. class PropertyAttributes {
  22. public:
  23. PropertyAttributes(u8 bits = 0)
  24. : m_bits(bits)
  25. {
  26. }
  27. [[nodiscard]] bool is_writable() const { return m_bits & Attribute::Writable; }
  28. [[nodiscard]] bool is_enumerable() const { return m_bits & Attribute::Enumerable; }
  29. [[nodiscard]] bool is_configurable() const { return m_bits & Attribute::Configurable; }
  30. void set_writable(bool writable = true)
  31. {
  32. if (writable)
  33. m_bits |= Attribute::Writable;
  34. else
  35. m_bits &= ~Attribute::Writable;
  36. }
  37. void set_enumerable(bool enumerable = true)
  38. {
  39. if (enumerable)
  40. m_bits |= Attribute::Enumerable;
  41. else
  42. m_bits &= ~Attribute::Enumerable;
  43. }
  44. void set_configurable(bool configurable = true)
  45. {
  46. if (configurable)
  47. m_bits |= Attribute::Configurable;
  48. else
  49. m_bits &= ~Attribute::Configurable;
  50. }
  51. bool operator==(PropertyAttributes const& other) const { return m_bits == other.m_bits; }
  52. [[nodiscard]] u8 bits() const { return m_bits; }
  53. private:
  54. u8 m_bits;
  55. };
  56. PropertyAttributes const default_attributes = Attribute::Configurable | Attribute::Writable | Attribute::Enumerable;
  57. }
  58. namespace AK {
  59. template<>
  60. struct Formatter<JS::PropertyAttributes> : Formatter<StringView> {
  61. ErrorOr<void> format(FormatBuilder& builder, JS::PropertyAttributes const& property_attributes)
  62. {
  63. Vector<ByteString> parts;
  64. parts.append(ByteString::formatted("[[Writable]]: {}", property_attributes.is_writable()));
  65. parts.append(ByteString::formatted("[[Enumerable]]: {}", property_attributes.is_enumerable()));
  66. parts.append(ByteString::formatted("[[Configurable]]: {}", property_attributes.is_configurable()));
  67. return Formatter<StringView>::format(builder, ByteString::formatted("PropertyAttributes {{ {} }}", ByteString::join(", "sv, parts)));
  68. }
  69. };
  70. }