summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/PropertyAttributes.h
blob: dd11fd96fa75af31661d0d4504dfc50b26f275f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
 * Copyright (c) 2020, Matthew Olsson <mattco@serenityos.org>
 * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/DeprecatedString.h>
#include <AK/Format.h>
#include <AK/Types.h>
#include <AK/Vector.h>

namespace JS {

struct Attribute {
    enum {
        Writable = 1 << 0,
        Enumerable = 1 << 1,
        Configurable = 1 << 2,
    };
};

// 6.1.7.1 Property Attributes, https://tc39.es/ecma262/#sec-property-attributes
class PropertyAttributes {
public:
    PropertyAttributes(u8 bits = 0)
        : m_bits(bits)
    {
    }

    [[nodiscard]] bool is_writable() const { return m_bits & Attribute::Writable; }
    [[nodiscard]] bool is_enumerable() const { return m_bits & Attribute::Enumerable; }
    [[nodiscard]] bool is_configurable() const { return m_bits & Attribute::Configurable; }

    void set_writable(bool writable = true)
    {
        if (writable)
            m_bits |= Attribute::Writable;
        else
            m_bits &= ~Attribute::Writable;
    }

    void set_enumerable(bool enumerable = true)
    {
        if (enumerable)
            m_bits |= Attribute::Enumerable;
        else
            m_bits &= ~Attribute::Enumerable;
    }

    void set_configurable(bool configurable = true)
    {
        if (configurable)
            m_bits |= Attribute::Configurable;
        else
            m_bits &= ~Attribute::Configurable;
    }

    bool operator==(PropertyAttributes const& other) const { return m_bits == other.m_bits; }

    [[nodiscard]] u8 bits() const { return m_bits; }

private:
    u8 m_bits;
};

PropertyAttributes const default_attributes = Attribute::Configurable | Attribute::Writable | Attribute::Enumerable;

}

namespace AK {

template<>
struct Formatter<JS::PropertyAttributes> : Formatter<StringView> {
    ErrorOr<void> format(FormatBuilder& builder, JS::PropertyAttributes const& property_attributes)
    {
        Vector<DeprecatedString> parts;
        parts.append(DeprecatedString::formatted("[[Writable]]: {}", property_attributes.is_writable()));
        parts.append(DeprecatedString::formatted("[[Enumerable]]: {}", property_attributes.is_enumerable()));
        parts.append(DeprecatedString::formatted("[[Configurable]]: {}", property_attributes.is_configurable()));
        return Formatter<StringView>::format(builder, DeprecatedString::formatted("PropertyAttributes {{ {} }}", DeprecatedString::join(", "sv, parts)));
    }
};

}