File: extended_attribute.py

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (294 lines) | stat: -rw-r--r-- 9,994 bytes parent folder | download | duplicates (8)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import itertools


class ExtendedAttribute(object):
    """
    Represents a single extended attribute.
    https://webidl.spec.whatwg.org/#dfn-extended-attribute
    """

    # [Key]
    _FORM_NO_ARGS = 'NoArgs'
    # [Key=Value]
    _FORM_IDENT = 'Ident'
    # [Key=(Value1, Value2, ...)]
    _FORM_IDENT_LIST = 'IdentList'
    # [Key(Value1L Value1R, Value2L Value2R, ...)]
    _FORM_ARG_LIST = 'ArgList'
    # [Key=Name(Value1L Value1R, Value2L Value2R, ...)]
    _FORM_NAMED_ARG_LIST = 'NamedArgList'

    def __init__(self, key, values=None, arguments=None, name=None):
        assert isinstance(key, str)
        assert values is None or isinstance(values, str) or (isinstance(
            values,
            (list, tuple)) and all(isinstance(value, str) for value in values))
        assert arguments is None or (isinstance(
            arguments, (list, tuple)) and all(
                isinstance(left, str) and isinstance(right, str)
                for left, right in arguments))
        assert name is None or isinstance(name, str)

        self._format = None
        self._key = key
        self._values = None
        self._arguments = None
        self._name = name

        if name is not None:
            self._format = self._FORM_NAMED_ARG_LIST
            if values is not None or arguments is None:
                raise ValueError('Unknown format for ExtendedAttribute')
            self._arguments = tuple(arguments)
        elif arguments is not None:
            self._format = self._FORM_ARG_LIST
            if values is not None:
                raise ValueError('Unknown format for ExtendedAttribute')
            self._arguments = tuple(arguments)
        elif values is None:
            self._format = self._FORM_NO_ARGS
        elif isinstance(values, str):
            self._format = self._FORM_IDENT
            self._values = values
        else:
            self._format = self._FORM_IDENT_LIST
            self._values = tuple(values)

    @classmethod
    def equals(cls, lhs, rhs):
        """
        Returns True if |lhs| and |rhs| have the same contents.

        Note that |lhs == rhs| evaluates to True if lhs and rhs are the same
        object.
        """
        if lhs is None and rhs is None:
            return True
        if not all(isinstance(x, cls) for x in (lhs, rhs)):
            return False

        return (lhs.key == rhs.key
                and lhs.syntactic_form == rhs.syntactic_form)

    @property
    def syntactic_form(self):
        if self._format == self._FORM_NO_ARGS:
            return self._key
        if self._format == self._FORM_IDENT:
            return '{}={}'.format(self._key, self._values)
        if self._format == self._FORM_IDENT_LIST:
            return '{}=({})'.format(self._key, ', '.join(self._values))
        args_str = '({})'.format(', '.join(
            ['{} {}'.format(left, right) for left, right in self._arguments]))
        if self._format == self._FORM_ARG_LIST:
            return '{}{}'.format(self._key, args_str)
        if self._format == self._FORM_NAMED_ARG_LIST:
            return '{}={}{}'.format(self._key, self._name, args_str)
        assert False, 'Unknown format: {}'.format(self._format)

    @property
    def key(self):
        return self._key

    @property
    def value(self):
        """
        Returns the value for format Ident.  Returns None for format NoArgs.
        Otherwise, raises a ValueError.
        """
        if self._format in (self._FORM_NO_ARGS, self._FORM_IDENT):
            return self._values
        raise ValueError('[{}] does not have a single value.'.format(
            self.syntactic_form))

    @property
    def has_values(self):
        return self._format in (self._FORM_NO_ARGS, self._FORM_IDENT,
                                self._FORM_IDENT_LIST)

    @property
    def values(self):
        """
        Returns a list of values for format Ident and IdentList.  Returns an
        empty list for format NorArgs.  Otherwise, raises a ValueError.
        """
        if self._format == self._FORM_NO_ARGS:
            return ()
        if self._format == self._FORM_IDENT:
            return (self._values, )
        if self._format == self._FORM_IDENT_LIST:
            return self._values
        raise ValueError('[{}] does not have a value.'.format(
            self.syntactic_form))

    @property
    def has_arguments(self):
        return self._format in (self._FORM_ARG_LIST, self._FORM_NAMED_ARG_LIST)

    @property
    def arguments(self):
        """
        Returns a list of value pairs for format ArgList and NamedArgList.
        Otherwise, raises a ValueError.
        """
        if self._format in (self._FORM_ARG_LIST, self._FORM_NAMED_ARG_LIST):
            return self._arguments
        raise ValueError('[{}] does not have an argument.'.format(
            self.syntactic_form))

    @property
    def has_name(self):
        return self._format == self._FORM_NAMED_ARG_LIST

    @property
    def name(self):
        """
        Returns |Name| for format NamedArgList.  Otherwise, raises a ValueError.
        """
        if self._format == self._FORM_NAMED_ARG_LIST:
            return self._name
        raise ValueError('[{}] does not have a name.'.format(
            self.syntactic_form))


class ExtendedAttributes(object):
    """
    ExtendedAttributes is a dict-like container for ExtendedAttribute instances.
    With a key string, you can get an ExtendedAttribute or a list of them.

    For an IDL fragment
      [A, A=(foo, bar), B=baz]
    an ExtendedAttributes instance will be like
      {
        'A': (ExtendedAttribute('A'),
              ExtendedAttribute('A', values=('foo', 'bar'))),
        'B': (ExtendedAttribute('B', value='baz')),
      }

    https://webidl.spec.whatwg.org/#idl-extended-attributes
    """

    def __init__(self, extended_attributes=None):
        assert (extended_attributes is None
                or isinstance(extended_attributes, ExtendedAttributes)
                or (isinstance(extended_attributes, (list, tuple)) and all(
                    isinstance(attr, ExtendedAttribute)
                    for attr in extended_attributes)))

        sorted_ext_attrs = sorted(
            extended_attributes or [], key=lambda x: x.key)

        self._ext_attrs = {
            key: tuple(sorted(ext_attrs, key=lambda x: x.syntactic_form))
            for key, ext_attrs in itertools.groupby(
                sorted_ext_attrs, key=lambda x: x.key)
        }
        self._keys = None
        self._length = None
        self._on_ext_attrs_updated()

    def _on_ext_attrs_updated(self):
        self._keys = tuple(sorted(self._ext_attrs.keys()))
        self._length = 0
        for ext_attrs in self._ext_attrs.values():
            self._length += len(ext_attrs)

    @classmethod
    def equals(cls, lhs, rhs):
        """
        Returns True if |lhs| and |rhs| have the same contents.

        Note that |lhs == rhs| evaluates to True if lhs and rhs are the same
        object.
        """
        if lhs is None and rhs is None:
            return True
        if not all(isinstance(x, cls) for x in (lhs, rhs)):
            return False

        if lhs.keys() != rhs.keys():
            return False
        if len(lhs) != len(rhs):
            return False
        for l, r in zip(lhs, rhs):
            if not ExtendedAttribute.equals(l, r):
                return False
        return True

    def __contains__(self, key):
        """Returns True if this has an extended attribute with the |key|."""
        return key in self._ext_attrs

    def __iter__(self):
        """Yields all ExtendedAttribute instances in a certain sorted order."""
        for key in self._keys:
            for ext_attr in self._ext_attrs[key]:
                yield ext_attr

    def __len__(self):
        return self._length

    @property
    def syntactic_form(self):
        return '[{}]'.format(', '.join(
            [ext_attr.syntactic_form for ext_attr in self]))

    def keys(self):
        return self._keys

    def get(self, key):
        """
        Returns an exnteded attribute whose key is |key|, or None if not found.
        If there are multiple extended attributes with |key|, raises an error.
        """
        values = self.get_list_of(key)
        if len(values) == 0:
            return None
        if len(values) == 1:
            return values[0]
        raise ValueError(
            "There are multiple extended attributes for the key '{}'.".format(
                key))

    def get_list_of(self, key):
        """
        Returns a list of extended attributes whose keys are |key|.
        """
        return self._ext_attrs.get(key, ())

    def value_of(self, key):
        """Returns self.get(key).value if the key exists or None."""
        ext_attr = self.get(key)
        return ext_attr.value if ext_attr else None

    def values_of(self, key):
        """Returns self.get(key).values if the key exists or an empty list."""
        ext_attr = self.get(key)
        return ext_attr.values if ext_attr else ()

    def _append(self, ext_attr):
        assert isinstance(ext_attr, ExtendedAttribute)

        if ext_attr.key not in self._ext_attrs:
            self._ext_attrs[ext_attr.key] = (ext_attr, )
        else:
            self._ext_attrs[ext_attr.key] = (tuple(
                sorted(
                    self._ext_attrs[ext_attr.key] + (ext_attr, ),
                    key=lambda x: x.syntactic_form)))
        self._on_ext_attrs_updated()


class ExtendedAttributesMutable(ExtendedAttributes):
    def __getstate__(self):
        assert False, "ExtendedAttributesMutable must not be pickled."

    def __setstate__(self, state):
        assert False, "ExtendedAttributesMutable must not be pickled."

    def append(self, ext_attr):
        self._append(ext_attr)