/
_xt_builder.py
1879 lines (1601 loc) · 77.7 KB
/
_xt_builder.py
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
"""
* Copyright(c) 2021 to 2022 ZettaScale Technology and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
"""
from inspect import isclass
from typing import List, Set, Tuple, Type, Optional, Union, Any, Dict
from collections import deque
from dataclasses import dataclass
from hashlib import md5
from ._typesupport.DDS import XTypes as xt
from . import types as pt
from . import annotations as annotate
from . import IdlStruct, IdlUnion, IdlBitmask, IdlEnum, make_idl_struct, make_idl_union, make_idl_enum, make_idl_bitmask
from ._support import Endianness
from ._type_helper import get_origin, get_args
from ._type_normalize import get_extended_type_hints, get_idl_annotations, get_idl_field_annotations, WrapOpt
uint32_max = 2 ** 32 - 1
def _is_optional(_type: Any) -> bool:
return isinstance(_type, WrapOpt)
def kosaraju(graph: List[List[int]]) -> Tuple[List[int], Dict[int, int], List[Set[int]]]:
# https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm
number_of_nodes = len(graph)
# 1. For each vertex u of the graph, mark u as unvisited. Let L be empty.
visited = [False] * number_of_nodes
L = []
reverse_graph: List[List[int]] = [[] for _ in range(number_of_nodes)]
def visit(u):
if not visited[u]:
visited[u] = True
for v in graph[u]:
visit(v)
reverse_graph[v] += [u]
# we keep L in normal order instead of prepend
# and reverse iterate instead
L.append(u)
# 2. For each vertex u of the graph do visit(u)
for u in range(number_of_nodes):
visit(u)
roots = [0] * number_of_nodes
rootset: Set[int] = set()
def assign(u, root):
if visited[u]:
visited[u] = False
roots[u] = root
rootset.add(root)
for v in reverse_graph[u]:
assign(v, root)
# 3: For each element u of l in order, do assign(u, u)
for u in reversed(L):
assign(u, u)
# Busywork: turn root node into component id + component index
roots_to_components = {r: i for i, r in enumerate(sorted(rootset))}
component_sizes = {r: 0 for r in range(len(rootset))}
component_ids = [0] * number_of_nodes
component_graph: List[Set[int]] = [set() for _ in range(len(rootset))]
for i in range(number_of_nodes):
component_id = roots_to_components[roots[i]]
component_sizes[component_id] += 1
component_ids[i] = component_id
for i in range(number_of_nodes):
c = component_ids[i]
for u in graph[i]:
if component_ids[u] != c:
component_graph[c].add(component_ids[u])
# component indexes - component sizes - component adjecency graph
return component_ids, component_sizes, component_graph
class TypeHash:
def __init__(
self, *, cls: Type[Any],
minimal_type_object: Union[xt.TypeObject, xt.MinimalTypeObject, pt.NoneType] = None,
complete_type_object: Union[xt.TypeObject, xt.CompleteTypeObject, pt.NoneType] = None,
minimal_type_identifier: Optional[xt.TypeIdentifier] = None,
complete_type_identifier: Optional[xt.TypeIdentifier] = None,
minimal_type_object_serialized: Optional[bytes] = None,
complete_type_object_serialized: Optional[bytes] = None,
minimal_hash: Optional[xt.TypeObjectHashId] = None,
complete_hash: Optional[xt.TypeObjectHashId] = None
) -> None:
self.cls: Type[Any] = cls
if minimal_type_object is not None and complete_type_object is not None:
self.minimal_type_object: xt.TypeObject = (
xt.TypeObject(minimal=minimal_type_object) if isinstance(minimal_type_object, xt.MinimalTypeObject)
else minimal_type_object
)
self.complete_type_object: xt.TypeObject = (
xt.TypeObject(complete=complete_type_object) if isinstance(complete_type_object, xt.CompleteTypeObject)
else complete_type_object
)
self.minimal_type_object_serialized: bytes = (
minimal_type_object_serialized or self.minimal_type_object.serialize(endianness=Endianness.Little, use_version_2=True)[4:]
)
self.complete_type_object_serialized: bytes = (
complete_type_object_serialized or self.complete_type_object.serialize(endianness=Endianness.Little, use_version_2=True)[4:]
)
self.minimal_hash: xt.TypeObjectHashId = minimal_hash or xt.TypeObjectHashId(
discriminator=xt.EK_MINIMAL,
value=md5(self.minimal_type_object_serialized).digest()[:14]
)
self.complete_hash: xt.TypeObjectHashId = complete_hash or xt.TypeObjectHashId(
discriminator=xt.EK_COMPLETE,
value=md5(self.complete_type_object_serialized).digest()[:14]
)
self.minimal_type_identifier: xt.TypeIdentifier = minimal_type_identifier or xt.TypeIdentifier(
discriminator=xt.EK_MINIMAL,
value=self.minimal_hash.value
)
self.complete_type_identifier: xt.TypeIdentifier = complete_type_identifier or xt.TypeIdentifier(
discriminator=xt.EK_COMPLETE,
value=self.complete_hash.value
)
class _StrongComponentResolver:
def __init__(self, names, types, component_ids, component_size, component_id) -> None:
self.cnames = [name for i, name in enumerate(names) if component_ids[i] == component_id]
self.ctypes = [type for i, type in enumerate(types) if component_ids[i] == component_id]
# 4.b If the Strongly Connected Component (SCC) has multiple types, then sort them
# using the lexicographic order of their fully qualified type name
self.ctypes = [value for i, value in sorted(enumerate(self.ctypes), key=lambda x: self.cnames[x[0]])]
self.cnames = list(sorted(self.cnames))
# 4.b.i
self.minimal_components = [
xt.StronglyConnectedComponentId(
sc_component_id=xt.TypeObjectHashId(
discriminator=xt.EK_MINIMAL,
value=b"\0" * 14
),
scc_length=component_size,
scc_index=i + 1
)
for i, name in enumerate(self.cnames)
]
self.complete_components = [
xt.StronglyConnectedComponentId(
sc_component_id=xt.TypeObjectHashId(
discriminator=xt.EK_COMPLETE,
value=b"\0" * 14
),
scc_length=component_size,
scc_index=i + 1
)
for i, name in enumerate(self.cnames)
]
self.minimal_typemap_by_name = {
name: self.minimal_components[i]
for i, name in enumerate(self.cnames)
}
self.complete_typemap_by_name = {
name: self.complete_components[i]
for i, name in enumerate(self.cnames)
}
self.minimal_typemap_by_type = {
type: self.minimal_components[i]
for i, type in enumerate(self.ctypes)
if '.' not in self.cnames[i]
}
self.complete_typemap_by_type = {
type: self.complete_components[i]
for i, type in enumerate(self.ctypes)
if '.' not in self.cnames[i]
}
def resolve(self, name, type):
if name in self.minimal_typemap_by_name:
return self.minimal_typemap_by_name.get(name), self.complete_typemap_by_name.get(name)
if type in self.minimal_typemap_by_type:
return self.minimal_typemap_by_type.get(type), self.complete_typemap_by_type.get(type)
return None, None
class XTBuilder:
_default_extensibility = "final"
_type_hash_db: Dict[Union[type, Tuple[str, type]], TypeHash] = {}
_current_sc_resolver: Optional[_StrongComponentResolver] = None
@classmethod
def process_type(cls, topic_type) -> Tuple[xt.TypeInformation, xt.TypeMapping]:
_names, _types, _graph, no_dependency_types = cls.gather_types(topic_type)
no_dependency_hashes = [cls._resolve_typehash('', _type) for _type in no_dependency_types]
if not _graph:
# Hurray our graph was fully resolved by no_deps types, which means our type is a no_dep type
hash: TypeHash = cls._resolve_typehash('', topic_type)
return xt.TypeInformation(
minimal=xt.TypeIdentifierWithDependencies(
typeid_with_size=xt.TypeIdentifierWithSize(
type_id=hash.minimal_type_identifier,
typeobject_serialized_size=len(hash.minimal_type_object_serialized)
),
dependent_typeid_count=0,
dependent_typeids=[]
),
complete=xt.TypeIdentifierWithDependencies(
typeid_with_size=xt.TypeIdentifierWithSize(
type_id=hash.complete_type_identifier,
typeobject_serialized_size=len(hash.complete_type_object_serialized)
),
dependent_typeid_count=0,
dependent_typeids=[]
)
), xt.TypeMapping(
identifier_object_pair_minimal=[
xt.TypeIdentifierTypeObjectPair(
type_identifier=hash.minimal_type_identifier,
type_object=hash.minimal_type_object
)
],
identifier_object_pair_complete=[
xt.TypeIdentifierTypeObjectPair(
type_identifier=hash.complete_type_identifier,
type_object=hash.complete_type_object
)
],
identifier_complete_minimal=[
xt.TypeIdentifierPair(
type_identifier1=hash.complete_type_identifier,
type_identifier2=hash.minimal_type_identifier
)
]
)
_type_component_ids, _component_sizes, _component_graph = kosaraju(_graph)
# Top level type is at position 0 in component 0, guaranteed by gather_types
assert _names[0] == topic_type.__idl_typename__.replace('.', '::')
scc_typeids = cls._handle_component(_names, _types, _graph, _type_component_ids, _component_sizes, _component_graph, 0)
# Construct xt.TypeInformation
dependent_typeids: List[Tuple[xt.TypeIdentifierWithSize, xt.TypeIdentifierWithSize]] = [
(
xt.TypeIdentifierWithSize(
type_id=dhash.minimal_type_identifier,
typeobject_serialized_size=len(dhash.minimal_type_object_serialized)
),
xt.TypeIdentifierWithSize(
type_id=dhash.complete_type_identifier,
typeobject_serialized_size=len(dhash.complete_type_object_serialized)
),
)
for dhash in no_dependency_hashes
]
dependent_typeids += [
(
xt.TypeIdentifierWithSize(
type_id=dhash.minimal_type_identifier,
typeobject_serialized_size=len(dhash.minimal_type_object_serialized)
),
xt.TypeIdentifierWithSize(
type_id=dhash.complete_type_identifier,
typeobject_serialized_size=len(dhash.complete_type_object_serialized)
),
)
for dhash in scc_typeids if dhash.cls != topic_type
]
# TODO redo this
full_list_typehashes: List[TypeHash] = []
for (name, _type) in zip(_names, _types):
if _type in cls._type_hash_db:
full_list_typehashes.append(cls._type_hash_db[_type])
elif '.' in name and (name, _type) in cls._type_hash_db:
# member
full_list_typehashes.append(cls._type_hash_db[(name, _type)])
else:
full_list_typehashes.append(cls._resolve_typehash(name, _type))
for _type in no_dependency_types:
full_list_typehashes.append(cls._resolve_typehash("", _type))
hash = full_list_typehashes[0]
minimal_seen = set()
minimal_dependend_typeids = [
d[0] for d in dependent_typeids
if not (d[0].type_id in minimal_seen or minimal_seen.add(d[0].type_id))
]
return xt.TypeInformation(
minimal=xt.TypeIdentifierWithDependencies(
typeid_with_size=xt.TypeIdentifierWithSize(
type_id=hash.minimal_type_identifier,
typeobject_serialized_size=len(hash.minimal_type_object_serialized)
),
dependent_typeid_count=len(minimal_dependend_typeids),
dependent_typeids=minimal_dependend_typeids
),
complete=xt.TypeIdentifierWithDependencies(
typeid_with_size=xt.TypeIdentifierWithSize(
type_id=hash.complete_type_identifier,
typeobject_serialized_size=len(hash.complete_type_object_serialized)
),
dependent_typeid_count=len(dependent_typeids),
dependent_typeids=[d[1] for d in dependent_typeids]
)
), xt.TypeMapping(
identifier_object_pair_minimal=[
xt.TypeIdentifierTypeObjectPair(
type_identifier=dhash.minimal_type_identifier,
type_object=dhash.minimal_type_object
)
for dhash in full_list_typehashes
],
identifier_object_pair_complete=[
xt.TypeIdentifierTypeObjectPair(
type_identifier=dhash.complete_type_identifier,
type_object=dhash.complete_type_object
)
for dhash in full_list_typehashes
],
identifier_complete_minimal=[
xt.TypeIdentifierPair(
type_identifier1=dhash.complete_type_identifier,
type_identifier2=dhash.minimal_type_identifier
)
for dhash in full_list_typehashes
]
)
@classmethod
def _deep_gather_type(cls, _type, deep=False):
# TODO: maps are a problem...
if isclass(_type) and issubclass(_type, (IdlStruct, IdlUnion, IdlEnum, IdlBitmask)):
return _type, deep
if isinstance(_type, pt.sequence) or isinstance(_type, pt.array):
return cls._deep_gather_type(_type.subtype, False)
if isinstance(_type, pt.typedef):
return _type, True
if isinstance(_type, pt.case) or isinstance(_type, pt.default):
return cls._deep_gather_type(_type.subtype, False)
if _is_optional(_type):
return cls._deep_gather_type(_type.inner, False)
return None, False
@classmethod
def gather_types(cls, _type):
toscan = deque()
toscan.append(_type)
# Start with graph with single node no connections
graph = {
_type.__idl_typename__.replace('.', '::'): set()
}
graph_types = {
_type.__idl_typename__.replace('.', '::'): _type
}
# 1. Let TypeDependencyDG(T) be the dependency digraph that contains only the types that are reachable from T
while toscan:
_ctype = toscan.pop()
my_node_name = _ctype.__idl_typename__.replace('.', '::')
if isclass(_ctype) and issubclass(_ctype, IdlUnion):
# get_extended_type_hints will not inspect the discriminator, and that can be an enum
discriminator_type = _ctype.__idl_discriminator__
if isclass(discriminator_type) and issubclass(discriminator_type, IdlEnum):
scan_node_name = discriminator_type.__idl_typename__.replace('.', '::')
if scan_node_name not in graph:
graph[scan_node_name] = set()
graph_types[scan_node_name] = discriminator_type
graph[my_node_name].add(scan_node_name)
if isclass(_ctype) and issubclass(_ctype, IdlStruct):
# get_extended_type_hints will not inspect the base type, which is a struct
base_type = _ctype.__base__
if base_type is None or base_type == IdlStruct:
pass
else:
scan_node_name = base_type.__idl_typename__.replace('.', '::')
if scan_node_name not in graph:
graph[scan_node_name] = set()
graph_types[scan_node_name] = base_type
graph[my_node_name].add(scan_node_name)
for name, fieldtype in get_extended_type_hints(_ctype).items():
m, deep = cls._deep_gather_type(fieldtype)
plain = cls._impl_xt_is_plain(fieldtype)
# m is None if primitive or a type with fields
if m is not None:
if not plain and not isinstance(_ctype, pt.typedef):
scan_node_name = m.__idl_typename__.replace('.', '::')
depending_name = f"{my_node_name}.{name}"
if scan_node_name not in graph:
graph[scan_node_name] = set()
graph_types[scan_node_name] = m
toscan.append(m)
graph[depending_name] = set([scan_node_name])
graph[my_node_name].add(depending_name)
graph_types[depending_name] = fieldtype
else:
scan_node_name = m.__idl_typename__.replace('.', '::')
if scan_node_name not in graph:
graph[scan_node_name] = set()
graph_types[scan_node_name] = m
toscan.append(m)
graph[my_node_name].add(scan_node_name)
# 2. Let ReducedDependencyDG(T) be the subdigraph of TypeDependencyDG(T) where all
# the vertices that have no outgoing edges are removed.
no_dependency_types = []
for name, edges in graph.copy().items():
if not edges:
del graph[name]
no_dependency_types.append(graph_types[name])
del graph_types[name]
# Busywork, need graph made of indexes
node_names = list(graph.keys())
node_indexes = {name: i for i, name in enumerate(node_names)}
node_graph = [[node_indexes[name] for name in graph[nname] if name in node_indexes] for nname in node_names]
node_types = [graph_types[name] for name in node_names]
return node_names, node_types, node_graph, no_dependency_types
@classmethod
def _resolve_typehash(cls, name: str, _type: Type[Any]) -> TypeHash:
if _type in cls._type_hash_db:
return cls._type_hash_db[_type]
minimal_scc, complete_scc = (
(None, None) if (cls._current_sc_resolver is None or name == "")
else cls._current_sc_resolver.resolve(name, _type)
)
if minimal_scc is not None and complete_scc is not None:
return TypeHash(
cls=_type,
minimal_type_identifier=xt.TypeIdentifier(sc_component_id=minimal_scc),
complete_type_identifier=xt.TypeIdentifier(sc_component_id=complete_scc)
)
minimal_object = cls._xt_minimal_type_object(_type)
complete_object = cls._xt_complete_type_object(_type)
hash = TypeHash(
cls=_type,
minimal_type_object=minimal_object,
complete_type_object=complete_object
)
cls._type_hash_db[_type] = hash
return hash
@dataclass
@annotate.final
class _TypeSeqWrap(IdlStruct):
seq: pt.sequence[xt.TypeObject]
@classmethod
def _handle_component(cls, _names, _types, _graph, _type_component_ids, _component_sizes, _component_graph, component_id):
# Because the component graph has no cycles depth first is guaranteed to be non-infinite
scc_typeids = sum([
cls._handle_component(
_names, _types, _graph, _type_component_ids, _component_sizes, _component_graph, subcomponent_id
)
for subcomponent_id in _component_graph[component_id]
], [])
if _component_sizes[component_id] == 1:
# 4.a. If the Strongly Connected Component (SCC) has a single type, then use the
# regular algorithm to compute its xt.TypeIdentifier
# EXCEPTION: type depends on itself (struct Node {@optional Node n;};)
for i in range(len(_types)):
if _type_component_ids[i] == component_id:
if i not in _graph[i]: # Catch the exception of self dependence
hash: TypeHash = cls._resolve_typehash(_names[i], _types[i])
scc_typeids.append(hash)
return scc_typeids
break
cls._current_sc_resolver = _StrongComponentResolver(
_names,
_types,
_type_component_ids,
_component_sizes[component_id],
component_id
)
minimal_type_objects = [None] * _component_sizes[component_id]
complete_type_objects = [None] * _component_sizes[component_id]
# 4.b.ii
for i, (name, _type) in enumerate(zip(_names, _types)):
if _type_component_ids[i] == component_id:
minimal_type_objects[cls._current_sc_resolver.cnames.index(name)] = xt.TypeObject(minimal=cls._xt_minimal_type_object(_type))
complete_type_objects[cls._current_sc_resolver.cnames.index(name)] = xt.TypeObject(complete=cls._xt_complete_type_object(_type))
# 4.c, 4.d
# Note: the [4:] is to skip the XCDR header
minimal_bytes = cls._TypeSeqWrap(seq=minimal_type_objects).serialize(endianness=Endianness.Little, use_version_2=True)[4:]
complete_bytes = cls._TypeSeqWrap(seq=complete_type_objects).serialize(endianness=Endianness.Little, use_version_2=True)[4:]
# 4.e
minimal_hash = xt.TypeObjectHashId(
discriminator=xt.EK_MINIMAL,
value=md5(minimal_bytes).digest()[:14]
)
complete_hash = xt.TypeObjectHashId(
discriminator=xt.EK_COMPLETE,
value=md5(complete_bytes).digest()[:14]
)
# 4.f
for i, (name, _type) in enumerate(zip(_names, _types)):
if _type_component_ids[i] == component_id:
if '.' in name:
key = (name, _type)
else:
key = _type
index = cls._current_sc_resolver.cnames.index(name)
cls._type_hash_db[key] = TypeHash(
cls=_type,
minimal_type_object=minimal_type_objects[index],
complete_type_object=complete_type_objects[index],
minimal_type_identifier=xt.TypeIdentifier(
sc_component_id=xt.StronglyConnectedComponentId(
sc_component_id=minimal_hash,
scc_length=_component_sizes[component_id],
scc_index=index + 1
)
),
complete_type_identifier=xt.TypeIdentifier(
sc_component_id=xt.StronglyConnectedComponentId(
sc_component_id=complete_hash,
scc_length=_component_sizes[component_id],
scc_index=index + 1
)
)
)
for comp in cls._current_sc_resolver.complete_components:
comp.sc_component_id = complete_hash
for comp in cls._current_sc_resolver.minimal_components:
comp.sc_component_id = minimal_hash
cls._current_sc_resolver = None
# Index 0 is used to indicate the full StronglyConnectedComponent
scc_typeids.append(TypeHash(
cls=None,
minimal_type_object=minimal_type_objects,
minimal_type_object_serialized=minimal_bytes,
minimal_hash=minimal_hash,
minimal_type_identifier=xt.TypeIdentifier(
sc_component_id=xt.StronglyConnectedComponentId(
sc_component_id=minimal_hash,
scc_length=_component_sizes[component_id],
scc_index=0
)
),
complete_type_object=complete_type_objects,
complete_type_object_serialized=complete_bytes,
complete_hash=complete_hash,
complete_type_identifier=xt.TypeIdentifier(
sc_component_id=xt.StronglyConnectedComponentId(
sc_component_id=complete_hash,
scc_length=_component_sizes[component_id],
scc_index=0
)
)
))
return scc_typeids
@classmethod
def _impl_xt_is_fully_descriptive(cls, _type: type) -> bool:
"""Check if a type is fully descriptive, e.g. does not contain any type hashes"""
if _type in pt._type_code_align_size_default_mapping:
return True
if _type in [str, pt.char]:
return True
if isinstance(_type, pt.bounded_str):
return True
if isinstance(_type, pt.array) or isinstance(_type, pt.sequence):
return cls._impl_xt_is_fully_descriptive(_type.subtype)
if get_origin(_type) == Dict:
args = get_args(_type)
return cls._impl_xt_is_fully_descriptive(args[0]) and cls._impl_xt_is_fully_descriptive(args[1])
if _is_optional(_type):
return cls._impl_xt_is_fully_descriptive(_type.inner)
return False
@classmethod
def _impl_xt_is_plain(cls, _type: type) -> bool:
"""Check if a type is fully descriptive, e.g. does not contain any type hashes"""
if _type in pt._type_code_align_size_default_mapping:
return True
if _type in [str, pt.char]:
return True
if isinstance(_type, pt.bounded_str):
return True
if isinstance(_type, pt.array):
inner = _type
while isinstance(inner, pt.array):
inner = inner.subtype
return cls._impl_xt_is_plain(inner)
if isinstance(_type, pt.sequence):
return cls._impl_xt_is_plain(_type.subtype)
if get_origin(_type) == Dict:
args = get_args(_type)
return cls._impl_xt_is_plain(args[0]) and cls._impl_xt_is_plain(args[1])
if isclass(_type) and issubclass(_type, (IdlStruct, IdlUnion, IdlEnum, IdlBitmask)):
return True
if isinstance(_type, pt.typedef):
return True
if isinstance(_type, (pt.case, pt.default)):
return cls._impl_xt_is_plain(_type.subtype)
if isinstance(_type, WrapOpt):
return cls._impl_xt_is_plain(_type.inner)
return False
@classmethod
def _xt_type_identifier(cls, name: str, entity: Any, minimal: bool) -> xt.TypeIdentifier:
if entity is None or entity == object:
return xt.TypeIdentifier(discriminator=xt.TK_NONE, value=None)
if _is_optional(entity):
# turned into annotation one level up
entity = entity.inner
if entity == pt.char:
return xt.TypeIdentifier(discriminator=xt.TK_CHAR8, value=None)
if entity in pt._type_code_align_size_default_mapping:
return {
bool: xt.TypeIdentifier(discriminator=xt.TK_BOOLEAN, value=None),
float: xt.TypeIdentifier(discriminator=xt.TK_FLOAT64, value=None),
int: xt.TypeIdentifier(discriminator=xt.TK_INT64, value=None),
pt.int8: xt.TypeIdentifier(discriminator=xt.TK_INT8, value=None),
pt.int16: xt.TypeIdentifier(discriminator=xt.TK_INT16, value=None),
pt.int32: xt.TypeIdentifier(discriminator=xt.TK_INT32, value=None),
pt.int64: xt.TypeIdentifier(discriminator=xt.TK_INT64, value=None),
pt.byte: xt.TypeIdentifier(discriminator=xt.TK_BYTE, value=None),
pt.uint8: xt.TypeIdentifier(discriminator=xt.TK_UINT8, value=None),
pt.uint16: xt.TypeIdentifier(discriminator=xt.TK_UINT16, value=None),
pt.uint32: xt.TypeIdentifier(discriminator=xt.TK_UINT32, value=None),
pt.uint64: xt.TypeIdentifier(discriminator=xt.TK_UINT64, value=None),
pt.char: xt.TypeIdentifier(discriminator=xt.TK_CHAR8, value=None),
pt.wchar: xt.TypeIdentifier(discriminator=xt.TK_CHAR16, value=None),
pt.float32: xt.TypeIdentifier(discriminator=xt.TK_FLOAT32, value=None),
pt.float64: xt.TypeIdentifier(discriminator=xt.TK_FLOAT64, value=None)
}[entity]
if cls._impl_xt_is_plain(entity):
if entity is str:
return xt.TypeIdentifier(string_sdefn=xt.StringSTypeDefn(bound=0))
elif isinstance(entity, pt.bounded_str):
if entity.max_length <= 255:
return xt.TypeIdentifier(string_sdefn=xt.StringSTypeDefn(bound=entity.max_length))
else:
return xt.TypeIdentifier(string_ldefn=xt.StringLTypeDefn(bound=entity.max_length))
elif isinstance(entity, pt.sequence):
fully_descriptive = cls._impl_xt_is_fully_descriptive(entity)
header = xt.PlainCollectionHeader(
equiv_kind=xt.EK_BOTH if fully_descriptive else (xt.EK_MINIMAL if minimal else xt.EK_COMPLETE),
element_flags=xt.MemberFlag(TRY_CONSTRUCT1=True) # TODO: elements can be external, try_construct
)
if entity.max_length is None:
return xt.TypeIdentifier(
seq_sdefn=xt.PlainSequenceSElemDefn(
header=header,
bound=0,
element_identifier=cls._xt_type_identifier(name, entity.subtype, minimal)
)
)
elif entity.max_length <= 255:
return xt.TypeIdentifier(
seq_sdefn=xt.PlainSequenceSElemDefn(
header=header,
bound=entity.max_length,
element_identifier=cls._xt_type_identifier(name, entity.subtype, minimal)
)
)
else:
return xt.TypeIdentifier(
seq_ldefn=xt.PlainSequenceLElemDefn(
header=header,
bound=entity.max_length or uint32_max,
element_identifier=cls._xt_type_identifier(name, entity.subtype, minimal)
)
)
elif isinstance(entity, pt.array):
fully_descriptive = cls._impl_xt_is_fully_descriptive(entity)
header = xt.PlainCollectionHeader(
equiv_kind=xt.EK_BOTH if fully_descriptive else (xt.EK_MINIMAL if minimal else xt.EK_COMPLETE),
element_flags=xt.MemberFlag(TRY_CONSTRUCT1=True) # TODO: elements can be external, try_construct
)
inner: Type[Any] = entity
bounds: List[int] = []
while isinstance(inner, pt.array):
bounds.append(inner.length)
inner = inner.subtype
if all(b < 256 for b in bounds):
return xt.TypeIdentifier(
array_sdefn=xt.PlainArraySElemDefn(
header=header,
array_bound_seq=bounds,
element_identifier=cls._xt_type_identifier(name, inner, minimal)
)
)
else:
return xt.TypeIdentifier(
array_ldefn=xt.PlainArrayLElemDefn(
header=header,
array_bound_seq=bounds,
element_identifier=cls._xt_type_identifier(name, inner, minimal)
)
)
elif get_origin(entity) == Dict:
fully_descriptive = cls._impl_xt_is_fully_descriptive(entity)
keytype, valuetype = get_args(entity)
header = xt.PlainCollectionHeader(
equiv_kind=xt.EK_BOTH if fully_descriptive else (xt.EK_MINIMAL if minimal else xt.EK_COMPLETE),
element_flags=xt.MemberFlag() # TODO: elements can be external, try_construct
)
# No small maps
return xt.TypeIdentifier(
map_ldefn=xt.PlainMapLTypeDefn(
header=header,
bound=uint32_max,
element_identifier=cls._xt_type_identifier(name, valuetype, minimal),
key_flags=xt.MemberFlag(), # TODO: keys can be external, try_construct
key_identifier=cls._xt_type_identifier(name, keytype, minimal)
)
)
typehash = cls._resolve_typehash(name, entity)
if minimal:
return typehash.minimal_type_identifier
else:
return typehash.complete_type_identifier
@classmethod
def _xt_minimal_type_object(cls, entity: Any) -> xt.MinimalTypeObject:
if _is_optional(entity):
return cls._xt_minimal_type_object(entity.inner)
if isinstance(entity, pt.typedef):
return xt.MinimalTypeObject(alias_type=cls._xt_minimal_alias_type(entity))
elif False:
# python has no annotation types yet
return xt.MinimalTypeObject(annotation_type=None)
elif isclass(entity) and issubclass(entity, IdlStruct):
entity.__idl__.populate()
return xt.MinimalTypeObject(struct_type=cls._xt_minimal_struct_type(entity))
elif isclass(entity) and issubclass(entity, IdlUnion):
entity.__idl__.populate()
return xt.MinimalTypeObject(union_type=cls._xt_minimal_union_type(entity))
elif isinstance(entity, pt.sequence):
return xt.MinimalTypeObject(sequence_type=cls._xt_minimal_sequence_type(entity))
elif isinstance(entity, pt.array):
return xt.MinimalTypeObject(array_type=cls._xt_minimal_array_type(entity))
elif isinstance(entity, Dict):
return xt.MinimalTypeObject(map_type=cls._xt_minimal_map_type(entity))
elif isclass(entity) and issubclass(entity, IdlEnum):
return xt.MinimalTypeObject(enumerated_type=cls._xt_minimal_enumerated_type(entity))
elif isclass(entity) and issubclass(entity, IdlBitmask):
return xt.MinimalTypeObject(bitmask_type=cls._xt_minimal_bitmask_type(entity))
raise Exception(f"Cannot construct typeobject for entity {entity}")
@classmethod
def _xt_complete_type_object(cls, entity: Any) -> xt.CompleteTypeObject:
if _is_optional(entity):
return cls._xt_complete_type_object(entity.inner)
if isinstance(entity, pt.typedef):
return xt.CompleteTypeObject(alias_type=cls._xt_complete_alias_type(entity))
elif False:
# python has no annotation types yet
return xt.CompleteTypeObject(annotation_type=None)
elif isclass(entity) and issubclass(entity, IdlStruct):
entity.__idl__.populate()
return xt.CompleteTypeObject(struct_type=cls._xt_complete_struct_type(entity))
elif isclass(entity) and issubclass(entity, IdlUnion):
entity.__idl__.populate()
return xt.CompleteTypeObject(union_type=cls._xt_complete_union_type(entity))
elif isinstance(entity, pt.sequence):
return xt.CompleteTypeObject(sequence_type=cls._xt_complete_sequence_type(entity))
elif isinstance(entity, pt.array):
return xt.CompleteTypeObject(array_type=cls._xt_complete_array_type(entity))
elif isinstance(entity, Dict):
return xt.CompleteTypeObject(map_type=cls._xt_complete_map_type(entity))
elif isclass(entity) and issubclass(entity, IdlEnum):
return xt.CompleteTypeObject(enumerated_type=cls._xt_complete_enumerated_type(entity))
elif isclass(entity) and issubclass(entity, IdlBitmask):
return xt.CompleteTypeObject(bitmask_type=cls._xt_complete_bitmask_type(entity))
raise Exception(f"Cannot construct typeobject for entity {entity}")
@classmethod
def _xt_minimal_alias_type(cls, entity: Any) -> xt.MinimalAliasType:
return xt.MinimalAliasType(
alias_flags=xt.TypeFlag(), # unused, no flags apply
header=xt.MinimalAliasHeader(), # empty...
body=xt.MinimalAliasBody(
common=xt.CommonAliasBody(
related_flags=xt.MemberFlag(), # unused, no flags apply
related_type=cls._xt_type_identifier('', entity.subtype, True)
)
)
)
@classmethod
def _xt_complete_alias_type(cls, entity: Any) -> xt.CompleteAliasType:
return xt.CompleteAliasType(
alias_flags=xt.TypeFlag(), # unused, no flags apply
header=xt.CompleteAliasHeader(
detail=xt.CompleteTypeDetail(
ann_builtin=None,
ann_custom=None,
type_name=entity.__idl_typename__.replace('.', '::')
)
),
body=xt.CompleteAliasBody(
common=xt.CommonAliasBody(
related_flags=xt.MemberFlag(), # unused, no flags apply
related_type=cls._xt_type_identifier('', entity.subtype, False)
),
ann_builtin=None,
ann_custom=None
)
)
@classmethod
def _xt_minimal_struct_type(cls, entity: Type[IdlStruct]) -> xt.MinimalStructType:
return xt.MinimalStructType(
struct_flags=cls._xt_type_flag(entity),
header=cls._xt_minimal_struct_header(entity),
member_seq=cls._xt_minimal_struct_member_seq(entity)
)
@classmethod
def _xt_complete_struct_type(cls, entity: Type[IdlStruct]) -> xt.CompleteStructType:
return xt.CompleteStructType(
struct_flags=cls._xt_type_flag(entity),
header=cls._xt_complete_struct_header(entity),
member_seq=cls._xt_complete_struct_member_seq(entity)
)
@classmethod
def _xt_type_flag(cls, entity: Any) -> xt.TypeFlag:
flag = xt.TypeFlag()
cls_a = get_idl_annotations(entity)
extensibility = cls_a.get("extensibility", cls._default_extensibility)
if extensibility == "final":
flag.IS_FINAL = True
elif extensibility == "appendable":
flag.IS_APPENDABLE = True
elif extensibility == "mutable":
flag.IS_MUTABLE = True
if cls_a.get("nested", False):
flag.IS_NESTED = True
if cls_a.get("autoid", "sequential") == "hash":
flag.IS_AUTOID_HASH = True
return flag
@classmethod
def _xt_minimal_struct_header(cls, entity: Type[IdlStruct]) -> xt.MinimalStructHeader:
if entity.__base__ is None or entity.__base__ == IdlStruct:
return xt.MinimalStructHeader(
base_type=xt.TypeIdentifier(discriminator=xt.TK_NONE, value=None),
detail=cls._xt_minimal_type_detail(entity)
)
return xt.MinimalStructHeader(
base_type=cls._xt_type_identifier("_base_", entity.__base__, True),
detail=cls._xt_minimal_type_detail(entity)
)
@classmethod
def _xt_complete_struct_header(cls, entity: Type[IdlStruct]) -> xt.CompleteStructHeader:
if entity.__base__ is None or entity.__base__ == IdlStruct:
return xt.CompleteStructHeader(
base_type=xt.TypeIdentifier(discriminator=xt.TK_NONE, value=None),
detail=cls._xt_complete_type_detail(entity)
)
return xt.CompleteStructHeader(
base_type=cls._xt_type_identifier("_base_", entity.__base__, False),
detail=cls._xt_complete_type_detail(entity)
)
@classmethod
def _xt_minimal_type_detail(cls, entity: Any) -> xt.MinimalTypeDetail:
# xtypes spec: left for future expansion
return xt.MinimalTypeDetail()
@classmethod
def _xt_complete_type_detail(cls, entity: Any) -> xt.CompleteTypeDetail:
return xt.CompleteTypeDetail(
ann_builtin=None,
ann_custom=None,
type_name=entity.__idl_typename__.replace(".", "::") if hasattr(entity, "__idl_typename__") else "anonymous"
)
@classmethod
def _xt_minimal_struct_member_seq(cls, entity: Type[IdlStruct]) -> xt.MinimalStructMemberSeq:
parent_fields = set(
get_extended_type_hints(entity.__base__).keys()
) if entity.__base__ not in (IdlStruct, None) else set()
return [
cls._xt_minimal_struct_member(entity, name, _type)
for name, _type in get_extended_type_hints(entity).items()
if name not in parent_fields
]
@classmethod
def _xt_complete_struct_member_seq(cls, entity: Type[IdlStruct]) -> xt.CompleteStructMemberSeq:
parent_fields = set(
get_extended_type_hints(entity.__base__).keys()
) if entity.__base__ not in (IdlStruct, None) else set()
return [
cls._xt_complete_struct_member(entity, name, _type)
for name, _type in get_extended_type_hints(entity).items()
if name not in parent_fields
]
@classmethod
def _xt_minimal_struct_member(cls, entity: Type[IdlStruct], name: str, _type: type) -> xt.MinimalStructMember:
return xt.MinimalStructMember(
common=cls._xt_common_struct_member(entity, name, _type, True),
detail=cls._xt_minimal_member_detail(entity, name, _type)
)
@classmethod
def _xt_complete_struct_member(cls, entity: Type[IdlStruct], name: str, _type: type) -> xt.CompleteStructMember:
# Reserved Python keywords support (#105)
annotations = get_idl_field_annotations(entity).get(name)
realName = annotations["name"] if annotations and "name" in annotations else name
#######################
return xt.CompleteStructMember(
common=cls._xt_common_struct_member(entity, name, _type, False),
#Reserved Python keywords support (Issue 105):
detail=cls._xt_complete_member_detail(entity, realName, _type)
#######################