PropertyAttributes.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. #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==(const PropertyAttributes& other) const { return m_bits == other.m_bits; }
  52. bool operator!=(const PropertyAttributes& other) const { return m_bits != other.m_bits; }
  53. [[nodiscard]] u8 bits() const { return m_bits; }
  54. private:
  55. u8 m_bits;
  56. };
  57. PropertyAttributes const default_attributes = Attribute::Configurable | Attribute::Writable | Attribute::Enumerable;
  58. }
  59. namespace AK {
  60. template<>
  61. struct Formatter<JS::PropertyAttributes> : Formatter<StringView> {
  62. void format(FormatBuilder& builder, JS::PropertyAttributes const& property_attributes)
  63. {
  64. Vector<String> parts;
  65. parts.append(String::formatted("[[Writable]]: {}", property_attributes.is_writable()));
  66. parts.append(String::formatted("[[Enumerable]]: {}", property_attributes.is_enumerable()));
  67. parts.append(String::formatted("[[Configurable]]: {}", property_attributes.is_configurable()));
  68. Formatter<StringView>::format(builder, String::formatted("PropertyAttributes {{ {} }}", String::join(", ", parts)));
  69. }
  70. };
  71. }