PropertyAttributes.h 2.4 KB

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