forked from dropbox/stone
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_type.py
More file actions
1632 lines (1354 loc) · 57.3 KB
/
Copy pathdata_type.py
File metadata and controls
1632 lines (1354 loc) · 57.3 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Defines data types for Stone.
The goal of this module is to define all data types that are common to the
languages and serialization formats we want to support.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from abc import ABCMeta, abstractmethod
from collections import OrderedDict, deque
import copy
import datetime
import math
import numbers
import re
import six
from .lang.exception import InvalidSpec
from .lang.parser import (
StoneExampleField,
StoneExampleRef,
StoneTagRef,
)
class ParameterError(Exception):
"""Raised when a data type is parameterized with a bad type or value."""
pass
def generic_type_name(v):
"""
Return a descriptive type name that isn't Python specific. For example, an
int type will return 'integer' rather than 'int'.
"""
if isinstance(v, StoneExampleRef):
return "reference"
elif isinstance(v, numbers.Integral):
# Must come before real numbers check since integrals are reals too
return 'integer'
elif isinstance(v, numbers.Real):
return 'float'
elif isinstance(v, (tuple, list)):
return 'list'
elif isinstance(v, six.string_types):
return 'string'
elif v is None:
return 'null'
else:
return type(v).__name__
class DataType(object):
"""
Abstract class representing a data type.
"""
__metaclass__ = ABCMeta
def __init__(self):
"""No-op. Exists so that introspection can be certain that an init
method exists."""
pass
@property
def name(self):
"""Returns an easy to read name for the type."""
return self.__class__.__name__
@abstractmethod
def check(self, val):
"""
Checks if a value specified in a spec (translated to a Python object)
is a valid Python value for this type. Returns nothing, but can raise
an exception.
Args:
val (object)
Raises:
ValueError
"""
pass
@abstractmethod
def check_example(self, ex_field):
"""
Checks if an example field from a spec is valid. Returns nothing, but
can raise an exception.
Args:
ex_field (StoneExampleField)
Raises:
InvalidSpec
"""
pass
def __repr__(self):
return self.name
class Primitive(DataType):
def check_attr_repr(self, attr_field):
try:
self.check(attr_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], attr_field.lineno, attr_field.path)
return attr_field.value
class Composite(DataType):
"""
Composite types are any data type which can be constructed using primitive
data types and other composite types.
"""
pass
class Nullable(Composite):
def __init__(self, data_type):
self.data_type = data_type
def check(self, val):
if val is not None:
return self.data_type.check(val)
def check_example(self, ex_field):
if ex_field.value is not None:
return self.data_type.check_example(ex_field)
def check_attr_repr(self, attr_field):
if attr_field.value is None:
return None
else:
return self.data_type.check_attr_repr(attr_field)
class Void(Primitive):
def check(self, val):
if val is not None:
raise ValueError('void type can only be null')
def check_example(self, ex_field):
if ex_field.value is not None:
raise InvalidSpec('example of void type must be null',
ex_field.lineno, ex_field.path)
def check_attr_repr(self, attr_field):
raise NotImplementedError
class Bytes(Primitive):
def check(self, val):
if not isinstance(val, (bytes, six.text_type)):
raise ValueError('%r is not valid bytes' % val)
def check_example(self, ex_field):
if not isinstance(ex_field.value, (bytes, six.text_type)):
raise InvalidSpec("'%s' is not valid bytes",
ex_field.lineno, ex_field.path)
def check_attr_repr(self, attr_field):
try:
self.check(attr_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], attr_field.lineno, attr_field.path)
v = attr_field.value
if isinstance(v, six.text_type):
return v.encode('utf-8')
else:
return v
class _BoundedInteger(Primitive):
"""
When extending, specify 'minimum' and 'maximum' as class variables. This
is the range of values supported by the data type.
"""
def __init__(self, min_value=None, max_value=None):
"""
A more restrictive minimum or maximum value can be specified than the
range inherent to the defined type.
"""
if min_value is not None:
if not isinstance(min_value, numbers.Integral):
raise ParameterError('min_value must be an integral number')
if min_value < self.minimum:
raise ParameterError('min_value cannot be less than the '
'minimum value for this type (%s < %s)' %
(min_value, self.minimum))
if max_value is not None:
if not isinstance(max_value, numbers.Integral):
raise ParameterError('max_value must be an integral number')
if max_value > self.maximum:
raise ParameterError('max_value cannot be greater than the '
'maximum value for this type (%s < %s)' %
(max_value, self.maximum))
self.min_value = min_value
self.max_value = max_value
def check(self, val):
if not isinstance(val, numbers.Integral):
raise ValueError('%s is not a valid integer' %
generic_type_name(val))
if not (self.minimum <= val <= self.maximum):
raise ValueError('%d is not within range [%r, %r]'
% (val, self.minimum, self.maximum))
if self.min_value is not None and val < self.min_value:
raise ValueError('%d is less than %d' %
(val, self.min_value))
if self.max_value is not None and val > self.max_value:
raise ValueError('%d is greater than %d' %
(val, self.max_value))
def check_example(self, ex_field):
try:
self.check(ex_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
def __repr__(self):
return '%s()' % self.name
class Int32(_BoundedInteger):
minimum = -2**31
maximum = 2**31 - 1
class UInt32(_BoundedInteger):
minimum = 0
maximum = 2**32 - 1
class Int64(_BoundedInteger):
minimum = -2**63
maximum = 2**63 - 1
class UInt64(_BoundedInteger):
minimum = 0
maximum = 2**64 - 1
class _BoundedFloat(Primitive):
"""
When extending, optionally specify 'minimum' and 'maximum' as class
variables. This is the range of values supported by the data type. For
a float64, there is no need to specify a minimum and maximum since Python's
native float implementation is a float64/double. Therefore, any Python
float will pass the data type range check automatically.
"""
minimum = None
maximum = None
def __init__(self, min_value=None, max_value=None):
"""
A more restrictive minimum or maximum value can be specified than the
range inherent to the defined type.
"""
if min_value is not None:
if not isinstance(min_value, numbers.Real):
raise ParameterError('min_value must be a real number')
if not isinstance(min_value, float):
try:
min_value = float(min_value)
except OverflowError:
raise ParameterError('min_value is too small for a float')
if self.minimum is not None and min_value < self.minimum:
raise ParameterError('min_value cannot be less than the '
'minimum value for this type (%f < %f)' %
(min_value, self.minimum))
if max_value is not None:
if not isinstance(max_value, numbers.Real):
raise ParameterError('max_value must be a real number')
if not isinstance(max_value, float):
try:
max_value = float(max_value)
except OverflowError:
raise ParameterError('max_value is too large for a float')
if self.maximum is not None and max_value > self.maximum:
raise ParameterError('max_value cannot be greater than the '
'maximum value for this type (%f < %f)' %
(max_value, self.maximum))
self.min_value = min_value
self.max_value = max_value
def check(self, val):
if not isinstance(val, numbers.Real):
raise ValueError('%s is not a valid real number' %
generic_type_name(val))
if not isinstance(val, float):
try:
val = float(val)
except OverflowError:
raise ValueError('%r is too large for float' % val)
if math.isnan(val) or math.isinf(val):
# Parser doesn't support NaN or Inf yet.
raise ValueError('%f values are not supported' % val)
if self.minimum is not None and val < self.minimum:
raise ValueError('%f is less than %f' %
(val, self.minimum))
if self.maximum is not None and val > self.maximum:
raise ValueError('%f is greater than %f' %
(val, self.maximum))
if self.min_value is not None and val < self.min_value:
raise ValueError('%f is less than %f' %
(val, self.min_value))
if self.max_value is not None and val > self.max_value:
raise ValueError('%f is greater than %f' %
(val, self.min_value))
def check_example(self, ex_field):
try:
self.check(ex_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
def __repr__(self):
return '%s()' % self.name
class Float32(_BoundedFloat):
# Maximum and minimums from the IEEE 754-1985 standard
minimum = -3.40282 * 10**38
maximum = 3.40282 * 10**38
class Float64(_BoundedFloat):
pass
class Boolean(Primitive):
def check(self, val):
if not isinstance(val, bool):
raise ValueError('%r is not a valid boolean' % val)
def check_example(self, ex_field):
try:
self.check(ex_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
class String(Primitive):
def __init__(self, min_length=None, max_length=None, pattern=None):
if min_length is not None:
if not isinstance(min_length, numbers.Integral):
raise ParameterError('min_length must be an integral number')
if min_length < 0:
raise ParameterError('min_length must be >= 0')
if max_length is not None:
if not isinstance(max_length, numbers.Integral):
raise ParameterError('max_length must be an integral number')
if max_length < 1:
raise ParameterError('max_length must be > 0')
if min_length and max_length:
if max_length < min_length:
raise ParameterError('max_length must be >= min_length')
self.min_length = min_length
self.max_length = max_length
self.pattern = pattern
self.pattern_re = None
if pattern:
if not isinstance(pattern, six.string_types):
raise ParameterError('pattern must be a string')
try:
self.pattern_re = re.compile(pattern)
except re.error as e:
raise ParameterError(
'could not compile regex pattern {!r}: {}'.format(
pattern, e.args[0]))
def check(self, val):
if not isinstance(val, six.string_types):
raise ValueError('%s is not a valid string' %
generic_type_name(val))
elif self.max_length is not None and len(val) > self.max_length:
raise ValueError("'%s' has more than %d character(s)"
% (val, self.max_length))
elif self.min_length is not None and len(val) < self.min_length:
raise ValueError("'%s' has fewer than %d character(s)"
% (val, self.min_length))
elif self.pattern and not self.pattern_re.match(val):
raise ValueError("'%s' did not match pattern '%s'"
% (val, self.pattern))
def check_example(self, ex_field):
try:
self.check(ex_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
class Timestamp(Primitive):
def __init__(self, format):
if not isinstance(format, six.string_types):
raise ParameterError('format must be a string')
self.format = format
def check(self, val):
if not isinstance(val, six.string_types):
raise ValueError('timestamp must be specified as a string')
# Raises a ValueError if val is the incorrect format
datetime.datetime.strptime(val, self.format)
def check_example(self, ex_field):
try:
self.check(ex_field.value)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
def check_attr_repr(self, attr_field):
try:
self.check(attr_field.value)
except ValueError as e:
msg = e.args[0]
if isinstance(msg, six.binary_type):
# For Python 2 compatibility.
msg = msg.decode('utf-8')
raise InvalidSpec(msg, attr_field.lineno, attr_field.path)
return datetime.datetime.strptime(attr_field.value, self.format)
class List(Composite):
def __init__(self, data_type, min_items=None, max_items=None):
self.data_type = data_type
if min_items is not None and min_items < 0:
raise ParameterError('min_items must be >= 0')
if max_items is not None and max_items < 1:
raise ParameterError('max_items must be > 0')
if min_items and max_items and max_items < min_items:
raise ParameterError('max_length must be >= min_length')
self.min_items = min_items
self.max_items = max_items
def check(self, val):
raise NotImplementedError
def check_example(self, ex_field):
try:
self._check_list_container(ex_field.value)
for item in ex_field.value:
new_ex_field = StoneExampleField(ex_field.path,
ex_field.lineno,
ex_field.lexpos,
ex_field.name,
item)
self.data_type.check_example(new_ex_field)
except ValueError as e:
raise InvalidSpec(e.args[0], ex_field.lineno, ex_field.path)
def _check_list_container(self, val):
if not isinstance(val, list):
raise ValueError('%s is not a valid list' % generic_type_name(val))
elif self.max_items is not None and len(val) > self.max_items:
raise ValueError('list has more than %s item(s)' % self.max_items)
elif self.min_items is not None and len(val) < self.min_items:
raise ValueError('list has fewer than %s item(s)' % self.min_items)
def doc_unwrap(raw_doc):
"""
Applies two transformations to raw_doc:
1. N consecutive newlines are converted into N-1 newlines.
2. A lone newline is converted to a space, which basically unwraps text.
Returns a new string, or None if the input was None.
"""
if raw_doc is None:
return None
docstring = ''
consecutive_newlines = 0
# Remove all leading and trailing whitespace in the documentation block
for c in raw_doc.strip():
if c == '\n':
consecutive_newlines += 1
if consecutive_newlines > 1:
docstring += c
else:
if consecutive_newlines == 1:
docstring += ' '
consecutive_newlines = 0
docstring += c
return docstring
class Field(object):
"""
Represents a field in a composite type.
"""
def __init__(self,
name,
data_type,
doc,
token):
"""
Creates a new Field.
:param str name: Name of the field.
:param Type data_type: The type of variable for of this field.
:param str doc: Documentation for the field.
:param token: Raw field definition from the parser.
:type token: stone.stone.parser.StoneField
"""
self.name = name
self.data_type = data_type
self.raw_doc = doc
self.doc = doc_unwrap(doc)
self._token = token
def __repr__(self):
return 'Field(%r, %r)' % (self.name,
self.data_type)
class StructField(Field):
"""
Represents a field of a struct.
"""
def __init__(self,
name,
data_type,
doc,
token,
deprecated=False):
"""
Creates a new Field.
:param str name: Name of the field.
:param Type data_type: The type of variable for of this field.
:param str doc: Documentation for the field.
:param token: Raw field definition from the parser.
:type token: stone.stone.parser.StoneField
:param bool deprecated: Whether the field is deprecated.
"""
super(StructField, self).__init__(name, data_type, doc, token)
self.deprecated = deprecated
self.has_default = False
self._default = None
def set_default(self, default):
self.has_default = True
self._default = default
@property
def default(self):
if not self.has_default:
raise Exception('Type has no default')
else:
return self._default
def check_attr_repr(self, attr):
if attr is not None:
attr = self.data_type.check_attr_repr(attr)
if attr is None:
if self.has_default:
return self.default
_, unwrapped_nullable, _ = unwrap(self.data_type)
if unwrapped_nullable:
return None
else:
raise KeyError(self.name)
return attr
def __repr__(self):
return 'StructField(%r, %r)' % (self.name,
self.data_type)
class UnionField(Field):
"""
Represents a field of a union.
"""
def __init__(self,
name,
data_type,
doc,
token,
catch_all=False):
super(UnionField, self).__init__(name, data_type, doc, token)
self.catch_all = catch_all
def __repr__(self):
return 'UnionField(%r, %r, %r)' % (self.name,
self.data_type,
self.catch_all)
class UserDefined(Composite):
"""
These are types that are defined directly in specs.
"""
DEFAULT_EXAMPLE_LABEL = 'default'
def __init__(self, name, namespace, token):
"""
When this is instantiated, the type is treated as a forward reference.
Only when :meth:`set_attributes` is called is the type considered to
be fully defined.
:param str name: Name of type.
:param stone.api.Namespace namespace: The namespace this type is
defined in.
:param token: Raw type definition from the parser.
:type token: stone.stone.parser.StoneTypeDef
"""
self._name = name
self.namespace = namespace
self._token = token
self._is_forward_ref = True
self.raw_doc = None
self.doc = None
self.fields = None
self._raw_examples = None
self._examples = None
self._fields_by_name = None
def set_attributes(self, doc, fields, parent_type=None):
"""
Fields are specified as a list so that order is preserved for display
purposes only. (Might be used for certain serialization formats...)
:param str doc: Description of type.
:param list(Field) fields: Ordered list of fields for type.
:param Optional[Composite] parent_type: The type this type inherits
from.
"""
self.raw_doc = doc
self.doc = doc_unwrap(doc)
self.fields = fields
self.parent_type = parent_type
self._raw_examples = OrderedDict()
self._examples = OrderedDict()
self._fields_by_name = {} # Dict[str, Field]
# Check that no two fields share the same name.
for field in self.fields:
if field.name in self._fields_by_name:
orig_lineno = self._fields_by_name[field.name]._token.lineno
raise InvalidSpec("Field '%s' already defined on line %s." %
(field.name, orig_lineno),
field._token.lineno)
self._fields_by_name[field.name] = field
# Check that the fields for this type do not match any of the fields of
# its parents.
cur_type = self.parent_type
while cur_type:
for field in self.fields:
if field.name in cur_type._fields_by_name:
lineno = cur_type._fields_by_name[field.name]._token.lineno
raise InvalidSpec(
"Field '%s' already defined in parent '%s' on line %d."
% (field.name, cur_type.name, lineno),
field._token.lineno)
cur_type = cur_type.parent_type
# Indicate that the attributes of the type have been populated.
self._is_forward_ref = False
@property
def all_fields(self):
raise NotImplementedError
def has_documented_type_or_fields(self, include_inherited_fields=False):
"""Returns whether this type, or any of its fields, are documented.
Use this when deciding whether to create a block of documentation for
this type.
"""
if self.doc:
return True
else:
return self.has_documented_fields(include_inherited_fields)
def has_documented_fields(self, include_inherited_fields=False):
"""Returns whether at least one field is documented."""
fields = self.all_fields if include_inherited_fields else self.fields
for field in fields:
if field.doc:
return True
return False
@property
def name(self):
return self._name
def copy(self):
return copy.deepcopy(self)
def prepend_field(self, field):
self.fields.insert(0, field)
def get_examples(self, compact=False):
"""
Returns an OrderedDict mapping labels to Example objects.
Args:
compact (bool): If True, union members of void type are converted
to their compact representation: no ".tag" key or containing
dict, just the tag as a string.
"""
# Copy it just in case the caller wants to mutate the object.
examples = copy.deepcopy(self._examples)
if not compact:
return examples
def make_compact(d):
# Traverse through dicts looking for ones that have a lone .tag
# key, which can be converted into the compact form.
if not isinstance(d, dict):
return
for key in d:
if isinstance(d[key], dict):
inner_d = d[key]
if len(inner_d) == 1 and '.tag' in inner_d:
d[key] = inner_d['.tag']
else:
make_compact(inner_d)
for example in examples.values():
if (isinstance(example.value, dict) and
len(example.value) == 1 and '.tag' in example.value):
# Handle the case where the top-level of the example can be
# made compact.
example.value = example.value['.tag']
else:
make_compact(example.value)
return examples
class Example(object):
"""An example of a struct or union type."""
def __init__(self, label, text, value, token=None):
assert isinstance(label, six.text_type), type(label)
self.label = label
assert isinstance(text, (six.text_type, type(None))), type(text)
self.text = doc_unwrap(text) if text else text
assert isinstance(value, (six.text_type, OrderedDict)), type(value)
self.value = value
self._token = token
def __repr__(self):
return 'Example({!r}, {!r}, {!r})'.format(
self.label, self.text, self.value)
class Struct(UserDefined):
"""
Defines a product type: Composed of other primitive and/or struct types.
"""
composite_type = 'struct'
def set_attributes(self, doc, fields, parent_type=None):
"""
See :meth:`Composite.set_attributes` for parameter definitions.
"""
if parent_type:
assert isinstance(parent_type, Struct)
self.subtypes = []
# These are only set if this struct enumerates subtypes.
self._enumerated_subtypes = None # Optional[List[Tuple[str, DataType]]]
self._is_catch_all = None # Optional[Bool]
super(Struct, self).set_attributes(doc, fields, parent_type)
if self.parent_type:
self.parent_type.subtypes.append(self)
def check(self, val):
raise NotImplementedError
def check_example(self, ex_field):
if not isinstance(ex_field.value, StoneExampleRef):
raise InvalidSpec(
"example must reference label of '%s'" % self.name,
ex_field.lineno, ex_field.path)
def check_attr_repr(self, attrs):
# Since we mutate it, let's make a copy to avoid mutating the argument.
attrs = attrs.copy()
validated_attrs = {}
for field in self.all_fields:
attr = field.check_attr_repr(attrs.pop(field.name, None))
validated_attrs[field.name] = attr
if attrs:
attr_name, attr_field = attrs.popitem()
raise InvalidSpec(
"Route attribute '%s' is not defined in 'stone_cfg.Route'."
% attr_name, attr_field.lineno, attr_field.path)
return validated_attrs
@property
def all_fields(self):
"""
Returns an iterator of all fields. Required fields before optional
fields. Super type fields before type fields.
"""
return self.all_required_fields + self.all_optional_fields
def _filter_fields(self, filter_function):
"""
Utility to iterate through all fields (super types first) of a type.
:param filter: A function that takes in a Field object. If it returns
True, the field is part of the generated output. If False, it is
omitted.
"""
fields = []
if self.parent_type:
fields.extend(self.parent_type._filter_fields(filter_function))
fields.extend(filter(filter_function, self.fields))
return fields
@property
def all_required_fields(self):
"""
Returns an iterator that traverses required fields in all super types
first, and then for this type.
"""
def required_check(f):
return not is_nullable_type(f.data_type) and not f.has_default
return self._filter_fields(required_check)
@property
def all_optional_fields(self):
"""
Returns an iterator that traverses optional fields in all super types
first, and then for this type.
"""
def optional_check(f):
return is_nullable_type(f.data_type) or f.has_default
return self._filter_fields(optional_check)
def has_enumerated_subtypes(self):
"""
Whether this struct enumerates its subtypes.
"""
return bool(self._enumerated_subtypes)
def get_enumerated_subtypes(self):
"""
Returns a list of subtype fields. Each field has a `name` attribute
which is the tag for the subtype. Each field also has a `data_type`
attribute that is a `Struct` object representing the subtype.
"""
assert self._enumerated_subtypes is not None
return self._enumerated_subtypes
def is_member_of_enumerated_subtypes_tree(self):
"""
Whether this struct enumerates subtypes or is a struct that is
enumerated by its parent type. Because such structs are serialized
and deserialized differently, use this method to detect these.
"""
return (self.has_enumerated_subtypes() or
(self.parent_type and
self.parent_type.has_enumerated_subtypes()))
def is_catch_all(self):
"""
Indicates whether this struct should be used in the event that none of
its known enumerated subtypes match a received type tag.
Use this method only if the struct has enumerated subtypes.
Returns: bool
"""
assert self._enumerated_subtypes is not None
return self._is_catch_all
def set_enumerated_subtypes(self, subtype_fields, is_catch_all):
"""
Sets the list of "enumerated subtypes" for this struct. This differs
from regular subtyping in that each subtype is associated with a tag
that is used in the serialized format to indicate the subtype. Also,
this list of subtypes was explicitly defined in an "inner-union" in the
specification. The list of fields must include all defined subtypes of
this struct.
NOTE(kelkabany): For this to work with upcoming forward references, the
hierarchy of parent types for this struct must have had this method
called on them already.
:type subtype_fields: List[UnionField]
"""
assert self._enumerated_subtypes is None, \
'Enumerated subtypes already set.'
assert isinstance(is_catch_all, bool), type(is_catch_all)
self._is_catch_all = is_catch_all
self._enumerated_subtypes = []
if self.parent_type:
raise InvalidSpec(
"'%s' enumerates subtypes so it cannot extend another struct."
% self.name, self._token.lineno, self._token.path)
# Require that if this struct enumerates subtypes, its parent (and thus
# the entire hierarchy above this struct) does as well.
if self.parent_type and not self.parent_type.has_enumerated_subtypes():
raise InvalidSpec(
"'%s' cannot enumerate subtypes if parent '%s' does not." %
(self.name, self.parent_type.name),
self._token.lineno, self._token.path)
enumerated_subtype_names = set() # Set[str]
for subtype_field in subtype_fields:
path = subtype_field._token.path
lineno = subtype_field._token.lineno
# Require that a subtype only has a single type tag.
if subtype_field.data_type.name in enumerated_subtype_names:
raise InvalidSpec(
"Subtype '%s' can only be specified once." %
subtype_field.data_type.name, lineno, path)
# Require that a subtype has this struct as its parent.
if subtype_field.data_type.parent_type != self:
raise InvalidSpec(
"'%s' is not a subtype of '%s'." %
(subtype_field.data_type.name, self.name), lineno, path)
# Check for subtype tags that conflict with this struct's
# non-inherited fields.
if subtype_field.name in self._fields_by_name:
# Since the union definition comes first, use its line number
# as the source of the field's original declaration.
orig_field = self._fields_by_name[subtype_field.name]
raise InvalidSpec(
"Field '%s' already defined on line %d." %
(subtype_field.name, lineno),
orig_field._token.lineno,
orig_field._token.path)
# Walk up parent tree hierarchy to ensure no field conflicts.
# Checks for conflicts with subtype tags and regular fields.
cur_type = self.parent_type
while cur_type:
if subtype_field.name in cur_type._fields_by_name:
orig_field = cur_type._fields_by_name[subtype_field.name]
raise InvalidSpec(
"Field '%s' already defined in parent '%s' (%s:%d)."
% (subtype_field.name, cur_type.name,
orig_field._token.path, orig_field._token.lineno),
lineno, path)
cur_type = cur_type.parent_type
# Note the discrepancy between `fields` which contains only the
# struct fields, and `_fields_by_name` which contains the struct
# fields and enumerated subtype fields.
self._fields_by_name[subtype_field.name] = subtype_field
enumerated_subtype_names.add(subtype_field.data_type.name)
self._enumerated_subtypes.append(subtype_field)
assert len(self._enumerated_subtypes) > 0
# Check that all known subtypes are listed in the enumeration.
for subtype in self.subtypes:
if subtype.name not in enumerated_subtype_names:
raise InvalidSpec(
"'%s' does not enumerate all subtypes, missing '%s'" %
(self.name, subtype.name),
self._token.lineno)
def get_all_subtypes_with_tags(self):
"""
Unlike other enumerated-subtypes-related functionality, this method
returns not just direct subtypes, but all subtypes of this struct. The
tag of each subtype is the list of tags from which the type descends.
This method only applies to structs that enumerate subtypes.
Use this when you need to generate a lookup table for a root struct
that maps a generated class representing a subtype to the tag it needs
in the serialized format.