-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.py
2276 lines (2073 loc) · 87.1 KB
/
generate.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
from __future__ import annotations
import argparse
import itertools
import pathlib
import re
import xml.etree.ElementTree as etree
from typing import (
Iterable,
Iterator,
Literal,
Self,
Sequence,
SupportsFloat,
SupportsInt
)
import attrs
BUILTIN_TYPE_DICT = {
"void": None, # buffer protocol, absorbing a pointer
"char": None, # str, absorbing a pointer
"short": "int",
"int": "int",
"long": "int",
"unsigned short": "int",
"unsigned int": "int",
"unsigned long": "int",
"size_t": "int",
"float": "float",
"double": "float",
"int8_t": "int",
"int16_t": "int",
"int32_t": "int",
"int64_t": "int",
"uint8_t": "int",
"uint16_t": "int",
"uint32_t": "int",
"uint64_t": "int"
}
BASE_TYPE_DICT = {
"ANativeWindow": "void",
"AHardwareBuffer": "void",
"CAMetalLayer": "void",
"MTLDevice_id": "void *",
"MTLCommandQueue_id": "void *",
"MTLBuffer_id": "void *",
"MTLTexture_id": "void *",
"MTLSharedEvent_id": "void *",
"IOSurfaceRef": "void *",
"VkSampleMask": "uint32_t",
"VkBool32": "uint32_t",
"VkFlags": "uint32_t",
"VkFlags64": "uint64_t",
"VkDeviceSize": "uint64_t",
"VkDeviceAddress": "uint64_t",
"VkRemoteAddressNV": "void *"
}
# Refer to https://github.com/ash-rs/ash/blob/master/ash/src/vk/platform_types.rs
PLATFORM_TYPE_DICT = {
"Display": "void",
"VisualID": "unsigned int",
"Window": "unsigned long",
"RROutput": "unsigned long",
"wl_display": "void",
"wl_surface": "void",
"HINSTANCE": "void *",
"HWND": "void *",
"HMONITOR": "void *",
"HANDLE": "void *",
"SECURITY_ATTRIBUTES": "void",
"DWORD": "unsigned long",
"LPCWSTR": "const uint16_t *", # special convension from str required?
"xcb_connection_t": "void",
"xcb_visualid_t": "uint32_t",
"xcb_window_t": "uint32_t",
"IDirectFB": "void",
"IDirectFBSurface": "void",
"zx_handle_t": "uint32_t",
"GgpStreamDescriptor": "uint32_t",
"GgpFrameToken": "uint64_t",
"_screen_context": "void",
"_screen_window": "void",
"_screen_buffer": "void",
"NvSciSyncAttrList": "void *",
"NvSciSyncObj": "void",
"NvSciSyncFence": "void",
"NvSciBufAttrList": "void *",
"NvSciBufObj": "void"
}
class CType:
__slots__ = (
"_base_type_str",
"_const_specifier",
"_pointer_const_specifiers",
"_array_sizes"
)
#_unresolved_c_types: ClassVar[list[CType]] = []
def __init__(
self: Self,
c_type_str: str,
constant_decimal_literal_dict: dict[str, str] | None = None
) -> None:
super().__init__()
base_type_str, const_specifier, pointer_const_specifiers, array_sizes = type(self)._parse_c_type_str(
c_type_str, constant_decimal_literal_dict
)
self._base_type_str: str = base_type_str
self._const_specifier: bool = const_specifier
self._pointer_const_specifiers: tuple[bool, ...] = pointer_const_specifiers
self._array_sizes: tuple[str, ...] = array_sizes
#if any(
# array_size_str.isidentifier()
# for array_size_str in array_size_strs
#):
# cls = type(self)
# cls._unresolved_c_types.append(self)
@classmethod
def _parse_c_type_str(
cls: type[Self],
c_type_str: str,
constant_decimal_literal_dict: dict[str, str] | None
) -> tuple[str, bool, tuple[bool, ...], tuple[str, ...]]:
base_type_strs: list[str] = []
const_specifier: bool = False
pointer_const_specifiers: list[bool] = []
array_sizes: list[str] = []
tokens = (match.group() for match in re.finditer(r"\w+|\S", c_type_str))
next_token = next(tokens)
if next_token == "const":
const_specifier = True
next_token = next(tokens)
while next_token.isidentifier() and next_token != "const":
base_type_strs.append(next_token)
next_token = next(tokens, "")
if next_token == "const":
const_specifier = True
next_token = next(tokens, "")
while next_token == "*":
pointer_const_specifier = False
next_token = next(tokens, "")
if next_token == "const":
pointer_const_specifier = True
next_token = next(tokens, "")
pointer_const_specifiers.append(pointer_const_specifier)
while next_token == "[":
next_token = next(tokens)
if next_token == "]":
array_size = ""
else:
array_size = next_token
if not array_size.isdecimal():
assert constant_decimal_literal_dict is not None
array_size = constant_decimal_literal_dict[array_size]
assert next(tokens) == "]"
array_sizes.append(array_size)
next_token = next(tokens, "")
assert not next_token
return " ".join(base_type_strs), const_specifier, tuple(pointer_const_specifiers), tuple(array_sizes)
#@classmethod
#def resolve_array_sizes(
# cls: type[Self],
# array_size_values: dict[str, str]
#) -> None:
# while cls._unresolved_c_types:
# c_type = cls._unresolved_c_types.pop()
# c_type._array_size_strs = tuple(
# array_size_values[array_size_str] if array_size_str.isidentifier() else array_size_str
# for array_size_str in c_type._array_size_strs
# )
def format(
self: Self,
name: str | None = None
) -> str:
return f"""{"const " if self._const_specifier else ""}{self._base_type_str}{"".join(
f" *{f" const" if pointer_const_specifier else ""}"
for pointer_const_specifier in self._pointer_const_specifiers
)}{f" {name}" if name is not None else ""}{"".join(
f"[{array_size}]"
for array_size in self._array_sizes
)}"""
@attrs.frozen(kw_only=True)
class Argument:
name: str
c_type: CType
@attrs.frozen(kw_only=True)
class CommandArgument(Argument):
len_attr: str | None
altlen_attr: str | None
optional_attr: str | None
selector_attr: str | None
@attrs.frozen(kw_only=True)
class Field(Argument):
bitwidth: int | None
len_attr: str | None
altlen_attr: str | None
optional_attr: str | None
selector_attr: str | None
selection_attr: str | None
values_attr: str | None
@attrs.frozen(kw_only=True)
class Record:
name: str
#@attrs.frozen(kw_only=True)
#class BlankRecord(Record):
# pass
@attrs.frozen(kw_only=True)
class BuiltinTypeRecord(Record):
pass
#c_type: CType
#py_type_str: str # TODO
@attrs.frozen(kw_only=True)
class TypedefRecord(Record):
c_type_str: str
@attrs.frozen(kw_only=True)
class BitmaskRecord(Record):
type_attr: str
requires_attr: str | None
@attrs.frozen(kw_only=True)
class EnumRecord(Record):
#intrinsic_member_name_list: list[str]
type_attr: str # "enum" | "bitmask"
bitwidth_attr: str | None
@attrs.frozen(kw_only=True)
class HandleRecord(Record):
parent_attr: str | None
@attrs.frozen(kw_only=True)
class StructRecord(Record):
field_list: list[Field]
structextends_attr: str | None
allowduplicate_attr: str | None
@attrs.frozen(kw_only=True)
class UnionRecord(Record):
field_list: list[Field]
@attrs.frozen(kw_only=True)
class FunctionPointerRecord(Record):
return_c_type: CType
argument_list: list[Argument]
@attrs.frozen(kw_only=True)
class MacroRecord(Record):
c_type: CType
@attrs.frozen(kw_only=True)
class FunctionMacroRecord(Record):
return_c_type: CType
argument_list: list[Argument]
@attrs.frozen(kw_only=True)
class ConstantRecord(Record):
c_type: CType
value_attr: str
@attrs.frozen(kw_only=True)
class EnumMemberRecord(Record):
enum_name: str
@attrs.frozen(kw_only=True)
class CommandRecord(Record):
#handle_name: str | None
return_c_type: CType
command_argument_list: list[CommandArgument]
type_attr: str | None # "instance" | "device" | None
#class Requirement:
# __slots__ = (
# "_required",
# "_removed"
# )
# def __init__(
# self: Self
# ) -> None:
# super().__init__()
# self._required: bool = False
# self._removed: bool = False
# def mark_required(
# self: Self
# ) -> None:
# self._required = True
# def mark_removed(
# self: Self
# ) -> None:
# self._removed = True
# def check_requirement(
# self: Self
# ) -> bool:
# return self._required and not self._removed
#class RecordCollection[T: Record, **P](Mapping[str, T]):
# __slots__ = (
# "_record_constructor",
# "_record_dict",
# "_alias_forwardref_dict",
# "_requirement_dict"
# )
# def __init__(
# self: Self,
# record_constructor: Callable[P, T]
# ) -> None:
# super().__init__()
# self._record_constructor: Callable[P, T] = record_constructor
# self._record_dict: dict[str, T] = {}
# self._alias_forwardref_dict: dict[str, list[str]] = {}
# self._requirement_dict: dict[str, Requirement] = {}
# def __len__(
# self: Self
# ) -> int:
# return len(self._record_dict)
# def __iter__(
# self: Self
# ) -> Iterator[str]:
# yield from self._record_dict
# def __getitem__(
# self: Self,
# __name: str
# ) -> T:
# return self._record_dict[__name]
# def new(
# self: Self,
# name: str,
# *args: P.args,
# **kwargs: P.kwargs
# ) -> None:
# assert name not in self._requirement_dict
# self._requirement_dict[name] = Requirement()
# self._record_dict[name] = self._record_constructor(*args, **kwargs)
# resolvable_aliases = [name]
# while resolvable_aliases:
# alias = resolvable_aliases.pop(0)
# for name in self._alias_forwardref_dict.pop(alias, []):
# self._record_dict[name] = self._record_dict[alias]
# resolvable_aliases.append(name)
# def new_alias(
# self: Self,
# name: str,
# alias: str
# ) -> None:
# assert name not in self._requirement_dict
# self._requirement_dict[name] = Requirement()
# if alias in self._record_dict:
# self._record_dict[name] = self._record_dict[alias]
# else:
# self._alias_forwardref_dict.setdefault(alias, []).append(name)
# #def get[DefaultT](
# # self: Self,
# # __name: str,
# # __default: DefaultT
# #) -> T | DefaultT:
# # try:
# # return self[__name]
# # except KeyError:
# # return __default
# def get_requirement(
# self: Self,
# __name: str
# ) -> Requirement:
# try:
# return self._requirement_dict[__name]
# except KeyError:
# raise KeyError(__name) from None
# def finalize(
# self: Self,
# filter: Callable[[T], bool] | None = None
# ) -> None:
# assert not self._alias_forwardref_dict
# self._record_dict = {
# name: record
# for name, record in self._record_dict.items()
# if self._requirement_dict[name].check_requirement()
# and (filter is None or filter(record))
# }
#class Registry:
# __slots__ = (
# "define_list",
# "include_list",
# "tag_list",
# "blank_records",
# "builtin_type_records",
# "macro_records",
# "function_macro_records",
# "typedef_records",
# "bitmask_records",
# "enum_records",
# "handle_records",
# "struct_records",
# "union_records",
# "function_pointer_records",
# "constant_records",
# "enum_member_records",
# "command_records",
# "_records_tuple"
# )
# def __init__(
# self: Self,
# define_list: list[str],
# include_list: list[str],
# tag_list: list[str],
# blank_records: dict[str, BlankRecord],
# builtin_type_records: dict[str, BuiltinTypeRecord],
# macro_records: dict[str, MacroRecord],
# function_macro_records: dict[str, FunctionMacroRecord],
# typedef_records: dict[str, TypedefRecord],
# bitmask_records: dict[str, BitmaskRecord],
# enum_records: dict[str, EnumRecord],
# handle_records: dict[str, HandleRecord],
# struct_records: dict[str, StructRecord],
# union_records: dict[str, UnionRecord],
# function_pointer_records: dict[str, FunctionPointerRecord],
# constant_records: dict[str, ConstantRecord],
# enum_member_records: dict[str, EnumMemberRecord],
# command_records: dict[str, CommandRecord]
# ) -> None:
# super().__init__()
# self.define_list: Final[list[str]] = define_list
# self.include_list: Final[list[str]] = include_list
# self.tag_list: Final[list[str]] = tag_list
# self.blank_records: Final[dict[str, BlankRecord]] = blank_records
# self.builtin_type_records: Final[dict[str, BuiltinTypeRecord]] = builtin_type_records
# self.macro_records: Final[dict[str, MacroRecord]] = macro_records
# self.function_macro_records: Final[dict[str, FunctionMacroRecord]] = function_macro_records
# self.typedef_records: Final[dict[str, TypedefRecord]] = typedef_records
# self.bitmask_records: Final[dict[str, BitmaskRecord]] = bitmask_records
# self.enum_records: Final[dict[str, EnumRecord]] = enum_records
# self.handle_records: Final[dict[str, HandleRecord]] = handle_records
# self.struct_records: Final[dict[str, StructRecord]] = struct_records
# self.union_records: Final[dict[str, UnionRecord]] = union_records
# self.function_pointer_records: Final[dict[str, FunctionPointerRecord]] = function_pointer_records
# self.constant_records: Final[dict[str, ConstantRecord]] = constant_records
# self.enum_member_records: Final[dict[str, EnumMemberRecord]] = enum_member_records
# self.command_records: Final[dict[str, CommandRecord]] = command_records
# self._records_tuple: Final[tuple] = (
# self.builtin_type_records,
# self.blank_records,
# self.typedef_records,
# self.bitmask_records,
# self.enum_records,
# self.handle_records,
# self.struct_records,
# self.union_records,
# self.function_pointer_records,
# self.macro_records,
# self.function_macro_records,
# self.constant_records,
# self.enum_member_records,
# self.command_records
# )
# def __getitem__(
# self: Self,
# __name: str
# ) -> RecordUnionType:
# for records in self._records_tuple:
# try:
# return records[__name]
# except KeyError:
# continue
# raise KeyError(__name)
# def get[DefaultT](
# self: Self,
# __name: str,
# __default: DefaultT
# ) -> RecordUnionType | DefaultT:
# for records in self._records_tuple:
# try:
# return records[__name]
# except KeyError:
# continue
# return __default
@attrs.frozen(kw_only=True)
class Registry:
version: tuple[int, int, int]
defines: list[str]
tags: list[str]
#blank_records: list[BlankRecord]
builtin_type_records: list[BuiltinTypeRecord]
typedef_records: list[TypedefRecord]
bitmask_records: list[BitmaskRecord]
enum_records: list[EnumRecord]
handle_records: list[HandleRecord]
struct_records: list[StructRecord]
union_records: list[UnionRecord]
function_pointer_records: list[FunctionPointerRecord]
macro_records: list[MacroRecord]
function_macro_records: list[FunctionMacroRecord]
constant_records: list[ConstantRecord]
enum_member_records: list[EnumMemberRecord]
command_records: list[CommandRecord]
#type RecordUnionType = Union[
# BlankRecord,
# BuiltinTypeRecord,
# TypedefRecord,
# BitmaskRecord,
# EnumRecord,
# HandleRecord,
# StructRecord,
# UnionRecord,
# FunctionPointerRecord,
# MacroRecord,
# FunctionMacroRecord,
# ConstantRecord,
# EnumMemberRecord,
# CommandRecord
#]
#class Registry(Mapping[str, RecordUnionType]):
# __slots__ = (
# "version_major",
# "version_minor",
# "version_patch",
# "define_list",
# "include_list",
# "tag_list",
# "blank_records",
# "builtin_type_records",
# "macro_records",
# "function_macro_records",
# "typedef_records",
# "bitmask_records",
# "enum_records",
# "handle_records",
# "struct_records",
# "union_records",
# "function_pointer_records",
# "constant_records",
# "enum_member_records",
# "command_records",
# "_records_tuple"
# )
# def __init__(
# self: Self
# ) -> None:
# super().__init__()
# self.version_major: int = 0
# self.version_minor: int = 0
# self.version_patch: int = 0
# self.define_list: Final[list[str]] = []
# self.include_list: Final[list[str]] = []
# self.tag_list: Final[list[str]] = []
# self.blank_records: Final = RecordCollection(BlankRecord)
# self.builtin_type_records: Final = RecordCollection(BuiltinTypeRecord)
# self.typedef_records: Final = RecordCollection(TypedefRecord)
# self.bitmask_records: Final = RecordCollection(BitmaskRecord)
# self.enum_records: Final = RecordCollection(EnumRecord)
# self.handle_records: Final = RecordCollection(HandleRecord)
# self.struct_records: Final = RecordCollection(StructRecord)
# self.union_records: Final = RecordCollection(UnionRecord)
# self.function_pointer_records: Final = RecordCollection(FunctionPointerRecord)
# self.macro_records: Final = RecordCollection(MacroRecord)
# self.function_macro_records: Final = RecordCollection(FunctionMacroRecord)
# self.constant_records: Final = RecordCollection(ConstantRecord)
# self.enum_member_records: Final = RecordCollection(EnumMemberRecord)
# self.command_records: Final = RecordCollection(CommandRecord)
# self._records_tuple: Final[tuple] = (
# self.builtin_type_records,
# self.blank_records,
# self.typedef_records,
# self.bitmask_records,
# self.enum_records,
# self.handle_records,
# self.struct_records,
# self.union_records,
# self.function_pointer_records,
# self.macro_records,
# self.function_macro_records,
# self.constant_records,
# self.enum_member_records,
# self.command_records
# )
# def __len__(
# self: Self
# ) -> int:
# return sum(map(len, self._records_tuple))
# def __iter__(
# self: Self
# ) -> Iterator[str]:
# for records in self._records_tuple:
# yield from records
# def __getitem__(
# self: Self,
# __name: str
# ) -> RecordUnionType:
# for records in self._records_tuple:
# try:
# return records[__name]
# except KeyError:
# continue
# raise KeyError(__name)
# #def get[DefaultT](
# # self: Self,
# # __name: str,
# # __default: DefaultT
# #) -> RecordUnionType | DefaultT:
# # for records in self._records_tuple:
# # try:
# # return records[__name]
# # except KeyError:
# # continue
# # return __default
# def get_requirement(
# self: Self,
# __name: str
# ) -> Requirement:
# for records in self._records_tuple:
# try:
# return records.get_requirement(__name)
# except KeyError:
# continue
# raise KeyError(__name)
# def finalize(
# self: Self
# ) -> None:
# self.blank_records.finalize()
# self.builtin_type_records.finalize()
# self.macro_records.finalize()
# self.function_macro_records.finalize()
# self.typedef_records.finalize()
# self.bitmask_records.finalize()
# self.enum_records.finalize()
# self.handle_records.finalize()
# self.struct_records.finalize()
# self.union_records.finalize()
# self.function_pointer_records.finalize()
# self.constant_records.finalize()
# self.enum_member_records.finalize(
# filter=lambda enum_member:
# self.enum_records.get_requirement(enum_member.enum_name).check_requirement()
# )
# self.command_records.finalize(
# filter=lambda command:
# command.handle_name is None or self.handle_records.get_requirement(command.handle_name).check_requirement()
# )
# CType.resolve_array_sizes({
# name: value
# for name, constant in self.constant_records.items()
# if (value := constant.value_attr).isdecimal()
# })
class Program:
__slots__ = ()
@classmethod
def _join_xml_text(
cls: type[Self],
xml: etree.Element,
*,
ignored_tags: list[str] | None = None
) -> str:
def itertext(
xml: etree.Element,
ignored_tags: list[str] | None
) -> Iterator[str]:
if xml.text is not None:
yield xml.text
for child in xml:
if ignored_tags is None or child.tag not in ignored_tags:
yield from itertext(child, ignored_tags)
if child.tail is not None:
yield child.tail
return "".join(itertext(xml, ignored_tags))
@classmethod
def _check_api(
cls: type[Self],
xml: etree.Element,
api: str
) -> bool:
api_attr = xml.get("api")
return api_attr is None or api in api_attr.split(",")
@classmethod
def _check_supported(
cls: type[Self],
xml: etree.Element,
api: str
) -> bool:
supported_attr = xml.get("supported")
return supported_attr is None or supported_attr != "disabled" and api in supported_attr.split(",")
@classmethod
def _check_platform(
cls: type[Self],
xml: etree.Element,
platforms: list[str] | None
) -> bool:
platform_attr = xml.get("platform")
return platform_attr is None or platforms is None or platform_attr in platforms
#@classmethod
#def _read_enum_xml(
# cls: type[Self],
# name: str,
# enum_xml: etree.Element
# #enum_name: str | None
#) -> Iterator[Record]:
# if enum_name is None:
# if (alias := enum_xml.get("alias")) is not None:
# registry.constant_records.new_alias(name, alias)
# return
# value_attr = enum_xml.get("value", "")
# if (c_type_str := enum_xml.get("type")) is not None:
# c_type = CType(f"const {c_type_str}")
# elif value_attr.isidentifier():
# c_type = CType("const uint32_t")
# elif re.fullmatch(r"\d+|0x[\dA-F]+", value_attr):
# c_type = CType("const uint32_t")
# elif re.fullmatch(r"\"\w+\"", value_attr) is not None:
# c_type = CType("const char[]")
# else:
# assert False
# registry.constant_records.new(
# name=name,
# c_type=c_type,
# value_attr=value_attr
# )
# else:
# if (alias := enum_xml.get("alias")) is not None:
# registry.enum_member_records.new_alias(name, alias)
# return
# if (protect := enum_xml.get("protect")) is not None and protect not in registry.define_list:
# return
# registry.enum_member_records.new(
# name=name,
# enum_name=enum_name
# )
@classmethod
def _read_registry_xml(
cls: type[Self],
registry_xml: etree.Element,
api: str,
platforms: list[str] | None,
defines: list[str]
) -> Iterator[Record]:
def resolve_alias(
name: str,
xml_dict: dict[str, etree.Element]
) -> etree.Element:
while (alias := (result := xml_dict[name]).get("alias")) is not None:
name = alias
return result
#for name in xml_dict:
# alias = name
# while (next_alias := xml_dict[alias].get("alias")) is not None:
# alias = next_alias
# xml_dict[name] = xml_dict[alias]
#return xml_dict
#xml = xml_dict[name]
#while (alias := xml.get("alias")) is not None:
# name = alias
# xml = xml_dict[name]
#return name, xml
#removed_sets: dict[str, set[str]] = {tag: set() for tag in tags}
#required_dicts: dict[str, dict[str, tuple[etree.Element, str | None]]] = {tag: {} for tag in tags}
required_types: list[str] = []
required_enums: list[str] = []
required_commands: list[str] = []
removed_types: list[str] = []
removed_enums: list[str] = []
removed_commands: list[str] = []
type_xml_dict: dict[str, etree.Element] = {}
enum_xml_dict: dict[str, etree.Element] = {}
command_xml_dict: dict[str, etree.Element] = {}
enums_xml_dict: dict[str, etree.Element] = {}
enum_enums_name_dict: dict[str, str | None] = {}
command_type_attr_dict: dict[str, str | None] = {}
requirement_items = [
(removed, requirement_unit_xml_tag, requirement_unit_xml.get("name", ""), requirement_unit_xml, type_attr)
for requirement_xml, type_attr in itertools.chain((
(feature_xml, None)
for feature_xml in registry_xml.iterfind("feature")
if cls._check_api(feature_xml, api)
), (
(extension_xml, extension_xml.get("type"))
for extensions_xml in registry_xml.iterfind("extensions")
for extension_xml in extensions_xml.iterfind("extension")
if cls._check_api(extension_xml, api)
and cls._check_supported(extension_xml, api)
and cls._check_platform(extension_xml, platforms)
))
for requirement_batch_xml in requirement_xml
if requirement_batch_xml.tag in ("require", "remove")
and cls._check_api(requirement_batch_xml, api)
and ((removed := requirement_batch_xml.tag == "remove") or True)
for requirement_unit_xml in requirement_batch_xml
if (requirement_unit_xml_tag := requirement_unit_xml.tag) in ("type", "enum", "command")
and cls._check_api(requirement_unit_xml, api)
]
for removed, requirement_unit_xml_tag, name, _, _ in requirement_items:
if not removed:
continue
match requirement_unit_xml_tag:
case "type":
removed_types.append(name)
case "enum":
removed_enums.append(name)
case "command":
removed_commands.append(name)
for removed, requirement_unit_xml_tag, name, requirement_unit_xml, type_attr in requirement_items:
if removed:
continue
match requirement_unit_xml_tag:
case "type":
if name in removed_types:
continue
required_types.append(name)
case "enum":
if name in removed_enums:
continue
required_enums.append(name)
enum_xml_dict[name] = requirement_unit_xml
enum_enums_name_dict[name] = requirement_unit_xml.get("extends")
case "command":
if name in removed_commands:
continue
required_commands.append(name)
command_type_attr_dict[name] = type_attr
for xml in registry_xml:
match xml.tag:
case "types":
for type_xml in xml.iterfind("type"):
if not cls._check_api(type_xml, api):
continue
name = type_xml.get("name", type_xml.findtext("name", ""))
if type_xml.get("category") is None:
yield TypedefRecord(
name=name,
c_type_str=PLATFORM_TYPE_DICT.get(name, "void")
)
continue
if name not in required_types:
continue
type_xml_dict[name] = type_xml
case "enums":
enums_name = xml.get("name", "")
if enums_name == "API Constants":
enums_name = None
elif enums_name not in required_types:
continue
else:
enums_xml_dict[enums_name] = xml
for enum_xml in xml.iterfind("enum"):
if not cls._check_api(enum_xml, api):
continue
name = enum_xml.get("name", "")
if enums_name is not None:
required_enums.append(name)
enum_xml_dict[name] = enum_xml
enum_enums_name_dict[name] = enums_name
case "commands":
for command_xml in xml.iterfind("command"):
if not cls._check_api(command_xml, api):
continue
name = command_xml.get("name", command_xml.findtext("proto/name", ""))
if name not in required_commands:
continue
command_xml_dict[name] = command_xml
#enums_xml_item_dict = {
# enums_name: (enums_xml, {
# enum_xml.get("name", ""): enum_xml
# for enum_xml in enums_xml.iterfind("enum")
# if cls._check_api(enum_xml, api)
# })
# for enums_xml in registry_xml.iterfind("enums")
# if (enums_name := enums_xml.get("name", "")) in required_dicts["type"] or enums_name == "API Constants"
#}
#xml_dicts = {
# "type": {
# name: type_xml
# for type_xml in registry_xml.iterfind("types/type")
# if cls._check_api(type_xml, api)
# and (name := type_xml.get("name", type_xml.findtext("name", ""))) in required_dicts["type"]
# },
# "enum": dict(itertools.chain(
# (
# (name, enum_xml)
# for name, (enum_xml, _) in required_dicts["enum"].items()
# ),
# itertools.chain.from_iterable(
# enums_enum_xml_dict.items()
# for _, enums_enum_xml_dict in enums_xml_item_dict.values()
# )
# )),
# "command": {
# name: command_xml
# for command_xml in registry_xml.iterfind("commands/command")
# if cls._check_api(command_xml, api)
# and (name := command_xml.get("name", command_xml.findtext("proto/name", ""))) in required_dicts["command"]
# }
#}
#enums_xml_dict = {
# name if name != "API Constants" else None: enums_xml
# for enums_xml in registry_xml.iterfind("enums")
# if (name := enums_xml.get("name", "")) in required_type_dict or name == "API Constants"
#}
#intrinsic_enum_xml_dict_dict = {
# enums_name: {
# enum_xml.get("name", ""): enum_xml
# for enum_xml in enums_xml.iterfind("enum")
# if cls._check_api(enum_xml, api)
# }
# for enums_name, enums_xml in enums_xml_dict.items()
#}
#enum_xml_dict = required_enum_dict.copy()
#enum_xml_dict.update(itertools.chain.from_iterable(
# enum_xml_dict.items()
# for _, _, enum_xml_dict in enums_item_dict.values()
#))
#enum_xml_dict_dict = {
# enum_name: {