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/Format.h>
  9. #include <AK/String.h>
  10. #include <AK/Types.h>
  11. namespace JS {
  12. struct Attribute {
  13. enum {
  14. Writable = 1 << 0,
  15. Enumerable = 1 << 1,
  16. Configurable = 1 << 2,
  17. };
  18. };
  19. // 6.1.7.1 Property Attributes, https://tc39.es/ecma262/#sec-property-attributes
  20. class PropertyAttributes {
  21. public:
  22. PropertyAttributes(u8 bits = 0)
  23. : m_bits(bits)
  24. {
  25. }
  26. [[nodiscard]] bool is_writable() const { return m_bits & Attribute::Writable; }
  27. [[nodiscard]] bool is_enumerable() const { return m_bits & Attribute::Enumerable; }
  28. [[nodiscard]] bool is_configurable() const { return m_bits & Attribute::Configurable; }
  29. void set_writable(bool writable = true)
  30. {
  31. if (writable)
  32. m_bits |= Attribute::Writable;
  33. else
  34. m_bits &= ~Attribute::Writable;
  35. }
  36. void set_enumerable(bool enumerable = true)
  37. {
  38. if (enumerable)
  39. m_bits |= Attribute::Enumerable;
  40. else
  41. m_bits &= ~Attribute::Enumerable;
  42. }
  43. void set_configurable(bool configurable = true)
  44. {
  45. if (configurable)
  46. m_bits |= Attribute::Configurable;
  47. else
  48. m_bits &= ~Attribute::Configurable;
  49. }
  50. bool operator==(const PropertyAttributes& other) const { return m_bits == other.m_bits; }
  51. bool operator!=(const PropertyAttributes& 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. void format(FormatBuilder& builder, JS::PropertyAttributes const& property_attributes)
  62. {
  63. Vector<String> parts;
  64. parts.append(String::formatted("[[Writable]]: {}", property_attributes.is_writable()));
  65. parts.append(String::formatted("[[Enumerable]]: {}", property_attributes.is_enumerable()));
  66. parts.append(String::formatted("[[Configurable]]: {}", property_attributes.is_configurable()));
  67. Formatter<StringView>::format(builder, String::formatted("PropertyAttributes {{ {} }}", String::join(", ", parts)));
  68. }
  69. };
  70. }