forked from KhronosGroup/Vulkan-Docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reg.py
1771 lines (1516 loc) · 82.7 KB
/
reg.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
#!/usr/bin/python3 -i
#
# Copyright 2013-2023 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
"""Types and classes for manipulating an API registry."""
import copy
import re
import sys
import xml.etree.ElementTree as etree
from collections import defaultdict, deque, namedtuple
from generator import GeneratorOptions, OutputGenerator, noneStr, write
from apiconventions import APIConventions
def apiNameMatch(str, supported):
"""Return whether a required api name matches a pattern specified for an
XML <feature> 'api' attribute or <extension> 'supported' attribute.
- str - API name such as 'vulkan' or 'openxr'. May be None, in which
case it never matches (this should not happen).
- supported - comma-separated list of XML API names. May be None, in
which case str always matches (this is the usual case)."""
if str is not None:
return supported is None or str in supported.split(',')
# Fallthrough case - either str is None or the test failed
return False
def matchAPIProfile(api, profile, elem):
"""Return whether an API and profile
being generated matches an element's profile
- api - string naming the API to match
- profile - string naming the profile to match
- elem - Element which (may) have 'api' and 'profile'
attributes to match to.
If a tag is not present in the Element, the corresponding API
or profile always matches.
Otherwise, the tag must exactly match the API or profile.
Thus, if 'profile' = core:
- `<remove>` with no attribute will match
- `<remove profile="core">` will match
- `<remove profile="compatibility">` will not match
Possible match conditions:
```
Requested Element
Profile Profile
--------- --------
None None Always matches
'string' None Always matches
None 'string' Does not match. Cannot generate multiple APIs
or profiles, so if an API/profile constraint
is present, it must be asked for explicitly.
'string' 'string' Strings must match
```
** In the future, we will allow regexes for the attributes,
not just strings, so that `api="^(gl|gles2)"` will match. Even
this is not really quite enough, we might prefer something
like `"gl(core)|gles1(common-lite)"`."""
# Match 'api', if present
elem_api = elem.get('api')
if elem_api:
if api is None:
raise UserWarning("No API requested, but 'api' attribute is present with value '"
+ elem_api + "'")
elif api != elem_api:
# Requested API does not match attribute
return False
elem_profile = elem.get('profile')
if elem_profile:
if profile is None:
raise UserWarning("No profile requested, but 'profile' attribute is present with value '"
+ elem_profile + "'")
elif profile != elem_profile:
# Requested profile does not match attribute
return False
return True
def mergeAPIs(tree, fromApiNames, toApiName):
"""Merge multiple APIs using the precedence order specified in apiNames.
Also deletes <remove> elements.
tree - Element at the root of the hierarchy to merge.
apiNames - list of strings of API names."""
stack = deque()
stack.append(tree)
while len(stack) > 0:
parent = stack.pop()
for child in parent.findall('*'):
if child.tag == 'remove':
# Remove <remove> elements
parent.remove(child)
else:
stack.append(child)
supportedList = child.get('supported')
if supportedList:
supportedList = supportedList.split(',')
for apiName in [toApiName] + fromApiNames:
if apiName in supportedList:
child.set('supported', toApiName)
if child.get('api'):
definitionName = None
definitionVariants = []
# Keep only one definition with the same name if there are multiple definitions
if child.tag in ['type']:
if child.get('name') is not None:
definitionName = child.get('name')
definitionVariants = parent.findall(f"{child.tag}[@name='{definitionName}']")
else:
definitionName = child.find('name').text
definitionVariants = parent.findall(f"{child.tag}/name[.='{definitionName}']/..")
elif child.tag in ['member', 'param']:
definitionName = child.find('name').text
definitionVariants = parent.findall(f"{child.tag}/name[.='{definitionName}']/..")
elif child.tag in ['enum', 'feature']:
definitionName = child.get('name')
definitionVariants = parent.findall(f"{child.tag}[@name='{definitionName}']")
elif child.tag in ['require']:
definitionName = child.get('feature')
definitionVariants = parent.findall(f"{child.tag}[@feature='{definitionName}']")
elif child.tag in ['command']:
definitionName = child.find('proto/name').text
definitionVariants = parent.findall(f"{child.tag}/proto/name[.='{definitionName}']/../..")
if definitionName:
bestMatchApi = None
requires = None
for apiName in [toApiName] + fromApiNames:
for variant in definitionVariants:
# Keep any requires attributes from the target API
if variant.get('requires') and variant.get('api') == apiName:
requires = variant.get('requires')
# Find the best matching definition
if apiName in variant.get('api').split(',') and bestMatchApi is None:
bestMatchApi = variant.get('api')
if bestMatchApi:
for variant in definitionVariants:
if variant.get('api') != bestMatchApi:
# Only keep best matching definition
parent.remove(variant)
else:
# Add requires attribute from the target API if it is not overridden
if requires is not None and variant.get('requires') is None:
variant.set('requires', requires)
variant.set('api', toApiName)
def stripNonmatchingAPIs(tree, apiName, actuallyDelete = True):
"""Remove tree Elements with 'api' attributes matching apiName.
tree - Element at the root of the hierarchy to strip. Only its
children can actually be removed, not the tree itself.
apiName - string which much match a command-separated component of
the 'api' attribute.
actuallyDelete - only delete matching elements if True."""
stack = deque()
stack.append(tree)
while len(stack) > 0:
parent = stack.pop()
for child in parent.findall('*'):
api = child.get('api')
if apiNameMatch(apiName, api):
# Add child to the queue
stack.append(child)
elif not apiNameMatch(apiName, api):
# Child does not match requested api. Remove it.
if actuallyDelete:
parent.remove(child)
class BaseInfo:
"""Base class for information about a registry feature
(type/group/enum/command/API/extension).
Represents the state of a registry feature, used during API generation.
"""
def __init__(self, elem):
self.required = False
"""should this feature be defined during header generation
(has it been removed by a profile or version)?"""
self.declared = False
"has this feature been defined already?"
self.elem = elem
"etree Element for this feature"
def resetState(self):
"""Reset required/declared to initial values. Used
prior to generating a new API interface."""
self.required = False
self.declared = False
def compareKeys(self, info, key, required = False):
"""Return True if self.elem and info.elem have the same attribute
value for key.
If 'required' is not True, also returns True if neither element
has an attribute value for key."""
if required and key not in self.elem.keys():
return False
return self.elem.get(key) == info.elem.get(key)
def compareElem(self, info, infoName):
"""Return True if self.elem and info.elem have the same definition.
info - the other object
infoName - 'type' / 'group' / 'enum' / 'command' / 'feature' /
'extension'"""
if infoName == 'enum':
if self.compareKeys(info, 'extends'):
# Either both extend the same type, or no type
if (self.compareKeys(info, 'value', required = True) or
self.compareKeys(info, 'bitpos', required = True)):
# If both specify the same value or bit position,
# they are equal
return True
elif (self.compareKeys(info, 'extnumber') and
self.compareKeys(info, 'offset') and
self.compareKeys(info, 'dir')):
# If both specify the same relative offset, they are equal
return True
elif (self.compareKeys(info, 'alias')):
# If both are aliases of the same value
return True
else:
return False
else:
# The same enum cannot extend two different types
return False
else:
# Non-<enum>s should never be redefined
return False
class TypeInfo(BaseInfo):
"""Registry information about a type. No additional state
beyond BaseInfo is required."""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
self.additionalValidity = []
self.removedValidity = []
def getMembers(self):
"""Get a collection of all member elements for this type, if any."""
return self.elem.findall('member')
def resetState(self):
BaseInfo.resetState(self)
self.additionalValidity = []
self.removedValidity = []
class GroupInfo(BaseInfo):
"""Registry information about a group of related enums
in an <enums> block, generally corresponding to a C "enum" type."""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
class EnumInfo(BaseInfo):
"""Registry information about an enum"""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
self.type = elem.get('type')
"""numeric type of the value of the <enum> tag
( '' for GLint, 'u' for GLuint, 'ull' for GLuint64 )"""
if self.type is None:
self.type = ''
class CmdInfo(BaseInfo):
"""Registry information about a command"""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
self.additionalValidity = []
self.removedValidity = []
def getParams(self):
"""Get a collection of all param elements for this command, if any."""
return self.elem.findall('param')
def resetState(self):
BaseInfo.resetState(self)
self.additionalValidity = []
self.removedValidity = []
class FeatureInfo(BaseInfo):
"""Registry information about an API <feature>
or <extension>."""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
self.name = elem.get('name')
"feature name string (e.g. 'VK_KHR_surface')"
self.emit = False
"has this feature been defined already?"
self.sortorder = int(elem.get('sortorder', 0))
"""explicit numeric sort key within feature and extension groups.
Defaults to 0."""
# Determine element category (vendor). Only works
# for <extension> elements.
if elem.tag == 'feature':
# Element category (vendor) is meaningless for <feature>
self.category = 'VERSION'
"""category, e.g. VERSION or khr/vendor tag"""
self.version = elem.get('name')
"""feature name string"""
self.versionNumber = elem.get('number')
"""versionNumber - API version number, taken from the 'number'
attribute of <feature>. Extensions do not have API version
numbers and are assigned number 0."""
self.number = 0
self.supported = None
else:
# Extract vendor portion of <APIprefix>_<vendor>_<name>
self.category = self.name.split('_', 2)[1]
self.version = "0"
self.versionNumber = "0"
self.number = int(elem.get('number','0'))
"""extension number, used for ordering and for assigning
enumerant offsets. <feature> features do not have extension
numbers and are assigned number 0, as are extensions without
numbers, so sorting works."""
self.supported = elem.get('supported', 'disabled')
class SpirvInfo(BaseInfo):
"""Registry information about an API <spirvextensions>
or <spirvcapability>."""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
class FormatInfo(BaseInfo):
"""Registry information about an API <format>."""
def __init__(self, elem, condition):
BaseInfo.__init__(self, elem)
# Need to save the condition here when it is known
self.condition = condition
class SyncStageInfo(BaseInfo):
"""Registry information about <syncstage>."""
def __init__(self, elem, condition):
BaseInfo.__init__(self, elem)
# Need to save the condition here when it is known
self.condition = condition
class SyncAccessInfo(BaseInfo):
"""Registry information about <syncaccess>."""
def __init__(self, elem, condition):
BaseInfo.__init__(self, elem)
# Need to save the condition here when it is known
self.condition = condition
class SyncPipelineInfo(BaseInfo):
"""Registry information about <syncpipeline>."""
def __init__(self, elem):
BaseInfo.__init__(self, elem)
class Registry:
"""Object representing an API registry, loaded from an XML file."""
def __init__(self, gen=None, genOpts=None):
if gen is None:
# If not specified, give a default object so messaging will work
self.gen = OutputGenerator()
else:
self.gen = gen
"Output generator used to write headers / messages"
if genOpts is None:
# If no generator is provided, we may still need the XML API name
# (for example, in genRef.py).
self.genOpts = GeneratorOptions(apiname = APIConventions().xml_api_name)
else:
self.genOpts = genOpts
"Options controlling features to write and how to format them"
self.gen.registry = self
self.gen.genOpts = self.genOpts
self.gen.genOpts.registry = self
self.tree = None
"ElementTree containing the root `<registry>`"
self.typedict = {}
"dictionary of TypeInfo objects keyed by type name"
self.groupdict = {}
"dictionary of GroupInfo objects keyed by group name"
self.enumdict = {}
"dictionary of EnumInfo objects keyed by enum name"
self.cmddict = {}
"dictionary of CmdInfo objects keyed by command name"
self.apidict = {}
"dictionary of FeatureInfo objects for `<feature>` elements keyed by API name"
self.extensions = []
"list of `<extension>` Elements"
self.extdict = {}
"dictionary of FeatureInfo objects for `<extension>` elements keyed by extension name"
self.spirvextdict = {}
"dictionary of FeatureInfo objects for `<spirvextension>` elements keyed by spirv extension name"
self.spirvcapdict = {}
"dictionary of FeatureInfo objects for `<spirvcapability>` elements keyed by spirv capability name"
self.formatsdict = {}
"dictionary of FeatureInfo objects for `<format>` elements keyed by VkFormat name"
self.syncstagedict = {}
"dictionary of Sync*Info objects for `<syncstage>` elements keyed by VkPipelineStageFlagBits2 name"
self.syncaccessdict = {}
"dictionary of Sync*Info objects for `<syncaccess>` elements keyed by VkAccessFlagBits2 name"
self.syncpipelinedict = {}
"dictionary of Sync*Info objects for `<syncpipeline>` elements keyed by pipeline type name"
self.emitFeatures = False
"""True to actually emit features for a version / extension,
or False to just treat them as emitted"""
self.breakPat = None
"regexp pattern to break on when generating names"
# self.breakPat = re.compile('VkFenceImportFlagBits.*')
self.requiredextensions = [] # Hack - can remove it after validity generator goes away
# ** Global types for automatic source generation **
# Length Member data
self.commandextensiontuple = namedtuple('commandextensiontuple',
['command', # The name of the command being modified
'value', # The value to append to the command
'extension']) # The name of the extension that added it
self.validextensionstructs = defaultdict(list)
self.commandextensionsuccesses = []
self.commandextensionerrors = []
self.filename = None
def loadElementTree(self, tree):
"""Load ElementTree into a Registry object and parse it."""
self.tree = tree
self.parseTree()
def loadFile(self, file):
"""Load an API registry XML file into a Registry object and parse it"""
self.filename = file
self.tree = etree.parse(file)
self.parseTree()
def setGenerator(self, gen):
"""Specify output generator object.
`None` restores the default generator."""
self.gen = gen
self.gen.setRegistry(self)
def addElementInfo(self, elem, info, infoName, dictionary):
"""Add information about an element to the corresponding dictionary.
Intended for internal use only.
- elem - `<type>`/`<enums>`/`<enum>`/`<command>`/`<feature>`/`<extension>`/`<spirvextension>`/`<spirvcapability>`/`<format>`/`<syncstage>`/`<syncaccess>`/`<syncpipeline>` Element
- info - corresponding {Type|Group|Enum|Cmd|Feature|Spirv|Format|SyncStage|SyncAccess|SyncPipeline}Info object
- infoName - 'type' / 'group' / 'enum' / 'command' / 'feature' / 'extension' / 'spirvextension' / 'spirvcapability' / 'format' / 'syncstage' / 'syncaccess' / 'syncpipeline'
- dictionary - self.{type|group|enum|cmd|api|ext|format|spirvext|spirvcap|sync}dict
The dictionary key is the element 'name' attribute."""
# self.gen.logMsg('diag', 'Adding ElementInfo.required =',
# info.required, 'name =', elem.get('name'))
key = elem.get('name')
if key in dictionary:
if not dictionary[key].compareElem(info, infoName):
self.gen.logMsg('warn', 'Attempt to redefine', key,
'(this should not happen)')
else:
dictionary[key] = info
def lookupElementInfo(self, fname, dictionary):
"""Find a {Type|Enum|Cmd}Info object by name.
Intended for internal use only.
If an object qualified by API name exists, use that.
- fname - name of type / enum / command
- dictionary - self.{type|enum|cmd}dict"""
key = (fname, self.genOpts.apiname)
if key in dictionary:
# self.gen.logMsg('diag', 'Found API-specific element for feature', fname)
return dictionary[key]
if fname in dictionary:
# self.gen.logMsg('diag', 'Found generic element for feature', fname)
return dictionary[fname]
return None
def breakOnName(self, regexp):
"""Specify a feature name regexp to break on when generating features."""
self.breakPat = re.compile(regexp)
def parseTree(self):
"""Parse the registry Element, once created"""
# This must be the Element for the root <registry>
if self.tree is None:
raise RuntimeError("Tree not initialized!")
self.reg = self.tree.getroot()
# Preprocess the tree in one of the following ways:
# - either merge a set of APIs to another API based on their 'api' attributes
# - or remove all elements with non-matching 'api' attributes
# The preprocessing happens through a breath-first tree traversal.
# This is a blunt hammer, but eliminates the need to track and test
# the apis deeper in processing to select the correct elements and
# avoid duplicates.
# Schema validation should prevent duplicate elements with
# overlapping api attributes, or where one element has an api
# attribute and the other does not.
if self.genOpts.mergeApiNames:
mergeAPIs(self.reg, self.genOpts.mergeApiNames.split(','), self.genOpts.apiname)
else:
stripNonmatchingAPIs(self.reg, self.genOpts.apiname, actuallyDelete = True)
# Create dictionary of registry types from toplevel <types> tags
# and add 'name' attribute to each <type> tag (where missing)
# based on its <name> element.
#
# There is usually one <types> block; more are OK
# Required <type> attributes: 'name' or nested <name> tag contents
self.typedict = {}
for type_elem in self.reg.findall('types/type'):
# If the <type> does not already have a 'name' attribute, set
# it from contents of its <name> tag.
if type_elem.get('name') is None:
name_elem = type_elem.find('name')
if name_elem is None or not name_elem.text:
raise RuntimeError("Type without a name!")
type_elem.set('name', name_elem.text)
self.addElementInfo(type_elem, TypeInfo(type_elem), 'type', self.typedict)
# Create dictionary of registry enum groups from <enums> tags.
#
# Required <enums> attributes: 'name'. If no name is given, one is
# generated, but that group cannot be identified and turned into an
# enum type definition - it is just a container for <enum> tags.
self.groupdict = {}
for group in self.reg.findall('enums'):
self.addElementInfo(group, GroupInfo(group), 'group', self.groupdict)
# Create dictionary of registry enums from <enum> tags
#
# <enums> tags usually define different namespaces for the values
# defined in those tags, but the actual names all share the
# same dictionary.
# Required <enum> attributes: 'name', 'value'
# For containing <enums> which have type="enum" or type="bitmask",
# tag all contained <enum>s are required. This is a stopgap until
# a better scheme for tagging core and extension enums is created.
self.enumdict = {}
for enums in self.reg.findall('enums'):
required = (enums.get('type') is not None)
for enum in enums.findall('enum'):
enumInfo = EnumInfo(enum)
enumInfo.required = required
self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
# Create dictionary of registry commands from <command> tags
# and add 'name' attribute to each <command> tag (where missing)
# based on its <proto><name> element.
#
# There is usually only one <commands> block; more are OK.
# Required <command> attributes: 'name' or <proto><name> tag contents
self.cmddict = {}
# List of commands which alias others. Contains
# [ aliasName, element ]
# for each alias
cmdAlias = []
for cmd in self.reg.findall('commands/command'):
# If the <command> does not already have a 'name' attribute, set
# it from contents of its <proto><name> tag.
name = cmd.get('name')
if name is None:
name_elem = cmd.find('proto/name')
if name_elem is None or not name_elem.text:
raise RuntimeError("Command without a name!")
name = cmd.set('name', name_elem.text)
ci = CmdInfo(cmd)
self.addElementInfo(cmd, ci, 'command', self.cmddict)
alias = cmd.get('alias')
if alias:
cmdAlias.append([name, alias, cmd])
# Now loop over aliases, injecting a copy of the aliased command's
# Element with the aliased prototype name replaced with the command
# name - if it exists.
for (name, alias, cmd) in cmdAlias:
if alias in self.cmddict:
aliasInfo = self.cmddict[alias]
cmdElem = copy.deepcopy(aliasInfo.elem)
cmdElem.find('proto/name').text = name
cmdElem.set('name', name)
cmdElem.set('alias', alias)
ci = CmdInfo(cmdElem)
# Replace the dictionary entry for the CmdInfo element
self.cmddict[name] = ci
# @ newString = etree.tostring(base, encoding="unicode").replace(aliasValue, aliasName)
# @elem.append(etree.fromstring(replacement))
else:
self.gen.logMsg('warn', 'No matching <command> found for command',
cmd.get('name'), 'alias', alias)
# Create dictionaries of API and extension interfaces
# from toplevel <api> and <extension> tags.
self.apidict = {}
format_condition = dict()
for feature in self.reg.findall('feature'):
featureInfo = FeatureInfo(feature)
self.addElementInfo(feature, featureInfo, 'feature', self.apidict)
# Add additional enums defined only in <feature> tags
# to the corresponding enumerated type.
# When seen here, the <enum> element, processed to contain the
# numeric enum value, is added to the corresponding <enums>
# element, as well as adding to the enum dictionary. It is no
# longer removed from the <require> element it is introduced in.
# Instead, generateRequiredInterface ignores <enum> elements
# that extend enumerated types.
#
# For <enum> tags which are actually just constants, if there is
# no 'extends' tag but there is a 'value' or 'bitpos' tag, just
# add an EnumInfo record to the dictionary. That works because
# output generation of constants is purely dependency-based, and
# does not need to iterate through the XML tags.
for elem in feature.findall('require'):
for enum in elem.findall('enum'):
addEnumInfo = False
groupName = enum.get('extends')
if groupName is not None:
# self.gen.logMsg('diag', 'Found extension enum',
# enum.get('name'))
# Add version number attribute to the <enum> element
enum.set('version', featureInfo.version)
# Look up the GroupInfo with matching groupName
if groupName in self.groupdict:
# self.gen.logMsg('diag', 'Matching group',
# groupName, 'found, adding element...')
gi = self.groupdict[groupName]
gi.elem.append(copy.deepcopy(enum))
else:
self.gen.logMsg('warn', 'NO matching group',
groupName, 'for enum', enum.get('name'), 'found.')
if groupName == "VkFormat":
format_name = enum.get('name')
if enum.get('alias'):
format_name = enum.get('alias')
format_condition[format_name] = featureInfo.name
addEnumInfo = True
elif enum.get('value') or enum.get('bitpos') or enum.get('alias'):
# self.gen.logMsg('diag', 'Adding extension constant "enum"',
# enum.get('name'))
addEnumInfo = True
if addEnumInfo:
enumInfo = EnumInfo(enum)
self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
sync_pipeline_stage_condition = dict()
sync_access_condition = dict()
self.extensions = self.reg.findall('extensions/extension')
self.extdict = {}
for feature in self.extensions:
featureInfo = FeatureInfo(feature)
self.addElementInfo(feature, featureInfo, 'extension', self.extdict)
# Add additional enums defined only in <extension> tags
# to the corresponding core type.
# Algorithm matches that of enums in a "feature" tag as above.
#
# This code also adds a 'extnumber' attribute containing the
# extension number, used for enumerant value calculation.
for elem in feature.findall('require'):
for enum in elem.findall('enum'):
addEnumInfo = False
groupName = enum.get('extends')
if groupName is not None:
# self.gen.logMsg('diag', 'Found extension enum',
# enum.get('name'))
# Add <extension> block's extension number attribute to
# the <enum> element unless specified explicitly, such
# as when redefining an enum in another extension.
extnumber = enum.get('extnumber')
if not extnumber:
enum.set('extnumber', str(featureInfo.number))
enum.set('extname', featureInfo.name)
enum.set('supported', noneStr(featureInfo.supported))
# Look up the GroupInfo with matching groupName
if groupName in self.groupdict:
# self.gen.logMsg('diag', 'Matching group',
# groupName, 'found, adding element...')
gi = self.groupdict[groupName]
gi.elem.append(copy.deepcopy(enum))
else:
self.gen.logMsg('warn', 'NO matching group',
groupName, 'for enum', enum.get('name'), 'found.')
# This is Vulkan-specific
if groupName == "VkFormat":
format_name = enum.get('name')
if enum.get('alias'):
format_name = enum.get('alias')
if format_name in format_condition:
format_condition[format_name] += "," + featureInfo.name
else:
format_condition[format_name] = featureInfo.name
elif groupName == "VkPipelineStageFlagBits2":
stage_flag = enum.get('name')
if enum.get('alias'):
stage_flag = enum.get('alias')
featureName = elem.get('depends') if elem.get('depends') is not None else featureInfo.name
if stage_flag in sync_pipeline_stage_condition:
sync_pipeline_stage_condition[stage_flag] += "," + featureName
else:
sync_pipeline_stage_condition[stage_flag] = featureName
elif groupName == "VkAccessFlagBits2":
access_flag = enum.get('name')
if enum.get('alias'):
access_flag = enum.get('alias')
featureName = elem.get('depends') if elem.get('depends') is not None else featureInfo.name
if access_flag in sync_access_condition:
sync_access_condition[access_flag] += "," + featureName
else:
sync_access_condition[access_flag] = featureName
addEnumInfo = True
elif enum.get('value') or enum.get('bitpos') or enum.get('alias'):
# self.gen.logMsg('diag', 'Adding extension constant "enum"',
# enum.get('name'))
addEnumInfo = True
if addEnumInfo:
enumInfo = EnumInfo(enum)
self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
# Parse out all spirv tags in dictionaries
# Use addElementInfo to catch duplicates
for spirv in self.reg.findall('spirvextensions/spirvextension'):
spirvInfo = SpirvInfo(spirv)
self.addElementInfo(spirv, spirvInfo, 'spirvextension', self.spirvextdict)
for spirv in self.reg.findall('spirvcapabilities/spirvcapability'):
spirvInfo = SpirvInfo(spirv)
self.addElementInfo(spirv, spirvInfo, 'spirvcapability', self.spirvcapdict)
for format in self.reg.findall('formats/format'):
condition = None
format_name = format.get('name')
if format_name in format_condition:
condition = format_condition[format_name]
formatInfo = FormatInfo(format, condition)
self.addElementInfo(format, formatInfo, 'format', self.formatsdict)
for stage in self.reg.findall('sync/syncstage'):
condition = None
stage_flag = stage.get('name')
if stage_flag in sync_pipeline_stage_condition:
condition = sync_pipeline_stage_condition[stage_flag]
syncInfo = SyncStageInfo(stage, condition)
self.addElementInfo(stage, syncInfo, 'syncstage', self.syncstagedict)
for access in self.reg.findall('sync/syncaccess'):
condition = None
access_flag = access.get('name')
if access_flag in sync_access_condition:
condition = sync_access_condition[access_flag]
syncInfo = SyncAccessInfo(access, condition)
self.addElementInfo(access, syncInfo, 'syncaccess', self.syncaccessdict)
for pipeline in self.reg.findall('sync/syncpipeline'):
syncInfo = SyncPipelineInfo(pipeline)
self.addElementInfo(pipeline, syncInfo, 'syncpipeline', self.syncpipelinedict)
def dumpReg(self, maxlen=120, filehandle=sys.stdout):
"""Dump all the dictionaries constructed from the Registry object.
Diagnostic to dump the dictionaries to specified file handle (default stdout).
Truncates type / enum / command elements to maxlen characters (default 120)"""
write('***************************************', file=filehandle)
write(' ** Dumping Registry contents **', file=filehandle)
write('***************************************', file=filehandle)
write('// Types', file=filehandle)
for name in self.typedict:
tobj = self.typedict[name]
write(' Type', name, '->', etree.tostring(tobj.elem)[0:maxlen], file=filehandle)
write('// Groups', file=filehandle)
for name in self.groupdict:
gobj = self.groupdict[name]
write(' Group', name, '->', etree.tostring(gobj.elem)[0:maxlen], file=filehandle)
write('// Enums', file=filehandle)
for name in self.enumdict:
eobj = self.enumdict[name]
write(' Enum', name, '->', etree.tostring(eobj.elem)[0:maxlen], file=filehandle)
write('// Commands', file=filehandle)
for name in self.cmddict:
cobj = self.cmddict[name]
write(' Command', name, '->', etree.tostring(cobj.elem)[0:maxlen], file=filehandle)
write('// APIs', file=filehandle)
for key in self.apidict:
write(' API Version ', key, '->',
etree.tostring(self.apidict[key].elem)[0:maxlen], file=filehandle)
write('// Extensions', file=filehandle)
for key in self.extdict:
write(' Extension', key, '->',
etree.tostring(self.extdict[key].elem)[0:maxlen], file=filehandle)
write('// SPIR-V', file=filehandle)
for key in self.spirvextdict:
write(' SPIR-V Extension', key, '->',
etree.tostring(self.spirvextdict[key].elem)[0:maxlen], file=filehandle)
for key in self.spirvcapdict:
write(' SPIR-V Capability', key, '->',
etree.tostring(self.spirvcapdict[key].elem)[0:maxlen], file=filehandle)
write('// VkFormat', file=filehandle)
for key in self.formatsdict:
write(' VkFormat', key, '->',
etree.tostring(self.formatsdict[key].elem)[0:maxlen], file=filehandle)
def markTypeRequired(self, typename, required):
"""Require (along with its dependencies) or remove (but not its dependencies) a type.
- typename - name of type
- required - boolean (to tag features as required or not)
"""
self.gen.logMsg('diag', 'tagging type:', typename, '-> required =', required)
# Get TypeInfo object for <type> tag corresponding to typename
typeinfo = self.lookupElementInfo(typename, self.typedict)
if typeinfo is not None:
if required:
# Tag type dependencies in 'alias' and 'required' attributes as
# required. This does not un-tag dependencies in a <remove>
# tag. See comments in markRequired() below for the reason.
for attrib_name in ['requires', 'alias']:
depname = typeinfo.elem.get(attrib_name)
if depname:
self.gen.logMsg('diag', 'Generating dependent type',
depname, 'for', attrib_name, 'type', typename)
# Do not recurse on self-referential structures.
if typename != depname:
self.markTypeRequired(depname, required)
else:
self.gen.logMsg('diag', 'type', typename, 'is self-referential')
# Tag types used in defining this type (e.g. in nested
# <type> tags)
# Look for <type> in entire <command> tree,
# not just immediate children
for subtype in typeinfo.elem.findall('.//type'):
self.gen.logMsg('diag', 'markRequired: type requires dependent <type>', subtype.text)
if typename != subtype.text:
self.markTypeRequired(subtype.text, required)
else:
self.gen.logMsg('diag', 'type', typename, 'is self-referential')
# Tag enums used in defining this type, for example in
# <member><name>member</name>[<enum>MEMBER_SIZE</enum>]</member>
for subenum in typeinfo.elem.findall('.//enum'):
self.gen.logMsg('diag', 'markRequired: type requires dependent <enum>', subenum.text)
self.markEnumRequired(subenum.text, required)
# Tag type dependency in 'bitvalues' attributes as
# required. This ensures that the bit values for a flag
# are emitted
depType = typeinfo.elem.get('bitvalues')
if depType:
self.gen.logMsg('diag', 'Generating bitflag type',
depType, 'for type', typename)
self.markTypeRequired(depType, required)
group = self.lookupElementInfo(depType, self.groupdict)
if group is not None:
group.flagType = typeinfo
typeinfo.required = required
elif '.h' not in typename:
self.gen.logMsg('warn', 'type:', typename, 'IS NOT DEFINED')
def markEnumRequired(self, enumname, required):
"""Mark an enum as required or not.
- enumname - name of enum
- required - boolean (to tag features as required or not)"""
self.gen.logMsg('diag', 'markEnumRequired: tagging enum:', enumname, '-> required =', required)
enum = self.lookupElementInfo(enumname, self.enumdict)
if enum is not None:
# If the enum is part of a group, and is being removed, then
# look it up in that <enums> tag and remove the Element there,
# so that it is not visible to generators (which traverse the
# <enums> tag elements rather than using the dictionaries).
if not required:
groupName = enum.elem.get('extends')
if groupName is not None:
self.gen.logMsg('diag', f'markEnumRequired: Removing extending enum {enum.elem.get("name")}')
# Look up the Info with matching groupName
if groupName in self.groupdict:
gi = self.groupdict[groupName]
gienum = gi.elem.find("enum[@name='" + enumname + "']")
if gienum is not None:
# Remove copy of this enum from the group
gi.elem.remove(gienum)
else:
self.gen.logMsg('warn', 'markEnumRequired: Cannot remove enum',
enumname, 'not found in group',
groupName)
else:
self.gen.logMsg('warn', 'markEnumRequired: Cannot remove enum',
enumname, 'from nonexistent group',
groupName)
else:
# This enum is not an extending enum.
# The XML tree must be searched for all <enums> that
# might have it, so we know the parent to delete from.
enumName = enum.elem.get('name')
self.gen.logMsg('diag', f'markEnumRequired: Removing non-extending enum {enumName}')
count = 0
for enums in self.reg.findall('enums'):
for thisEnum in enums.findall('enum'):
if thisEnum.get('name') == enumName:
# Actually remove it
count = count + 1
enums.remove(thisEnum)
if count == 0:
self.gen.logMsg('warn', f'markEnumRequired: {enumName}) not found in any <enums> tag')
enum.required = required
# Tag enum dependencies in 'alias' attribute as required
depname = enum.elem.get('alias')
if depname:
self.gen.logMsg('diag', 'markEnumRequired: Generating dependent enum',
depname, 'for alias', enumname, 'required =', enum.required)
self.markEnumRequired(depname, required)
else:
self.gen.logMsg('warn', f'markEnumRequired: {enumname} IS NOT DEFINED')
def markCmdRequired(self, cmdname, required):
"""Mark a command as required or not.
- cmdname - name of command
- required - boolean (to tag features as required or not)"""
self.gen.logMsg('diag', 'tagging command:', cmdname, '-> required =', required)