PropertyAttributes.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // AD-HOC: This is used for reporting unimplemented IDL interfaces.
  19. Unimplemented = 1 << 3,
  20. };
  21. };
  22. // 6.1.7.1 Property Attributes, https://tc39.es/ecma262/#sec-property-attributes
  23. class PropertyAttributes {
  24. public:
  25. PropertyAttributes(u8 bits = 0)
  26. : m_bits(bits)
  27. {
  28. }
  29. [[nodiscard]] bool is_writable() const { return m_bits & Attribute::Writable; }
  30. [[nodiscard]] bool is_enumerable() const { return m_bits & Attribute::Enumerable; }
  31. [[nodiscard]] bool is_configurable() const { return m_bits & Attribute::Configurable; }
  32. [[nodiscard]] bool is_unimplemented() const { return m_bits & Attribute::Unimplemented; }
  33. void set_writable(bool writable = true)
  34. {
  35. if (writable)
  36. m_bits |= Attribute::Writable;
  37. else
  38. m_bits &= ~Attribute::Writable;
  39. }
  40. void set_enumerable(bool enumerable = true)
  41. {
  42. if (enumerable)
  43. m_bits |= Attribute::Enumerable;
  44. else
  45. m_bits &= ~Attribute::Enumerable;
  46. }
  47. void set_configurable(bool configurable = true)
  48. {
  49. if (configurable)
  50. m_bits |= Attribute::Configurable;
  51. else
  52. m_bits &= ~Attribute::Configurable;
  53. }
  54. bool operator==(PropertyAttributes const& other) const { return m_bits == other.m_bits; }
  55. [[nodiscard]] u8 bits() const { return m_bits; }
  56. private:
  57. u8 m_bits;
  58. };
  59. PropertyAttributes const default_attributes = Attribute::Configurable | Attribute::Writable | Attribute::Enumerable;
  60. }
  61. namespace AK {
  62. template<>
  63. struct Formatter<JS::PropertyAttributes> : Formatter<StringView> {
  64. ErrorOr<void> format(FormatBuilder& builder, JS::PropertyAttributes const& property_attributes)
  65. {
  66. Vector<ByteString> parts;
  67. parts.append(ByteString::formatted("[[Writable]]: {}", property_attributes.is_writable()));
  68. parts.append(ByteString::formatted("[[Enumerable]]: {}", property_attributes.is_enumerable()));
  69. parts.append(ByteString::formatted("[[Configurable]]: {}", property_attributes.is_configurable()));
  70. return Formatter<StringView>::format(builder, ByteString::formatted("PropertyAttributes {{ {} }}", ByteString::join(", "sv, parts)));
  71. }
  72. };
  73. }