-
Notifications
You must be signed in to change notification settings - Fork 3
/
erupt_dlang.py
1257 lines (968 loc) · 62.2 KB
/
erupt_dlang.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/env python3
"""
D Vulkan bindings generator, based off of and using the Vulkan-Docs code.
to generate bindings run: vkdgen.py path/to/vulcan-docs outputDir
"""
import sys
import re
import os
from os import path
from copy import deepcopy
from textwrap import dedent
from itertools import islice
from templates.dlang.types import *
from templates.dlang.package import *
from templates.dlang.vk_video import *
from templates.dlang.functions import *
from templates.dlang.dispatch_device import *
from templates.dlang.vulkan_lib_loader import *
from templates.dlang.platform_extensions import *
if len( sys.argv ) > 2 and not sys.argv[ 2 ].startswith( '--' ):
sys.path.append( sys.argv[ 1 ] + '/registry/' )
sys.path.append( sys.argv[ 1 ] + '/scripts/' )
sys.path.append( sys.argv[ 1 ] + '/xml/' )
try:
from reg import *
from generator import OutputGenerator, GeneratorOptions, write
from vkconventions import VulkanConventions
except ImportError as e:
print( 'Could not import Vulkan generator; please ensure that the first argument points to Vulkan-Docs directory', file = sys.stderr )
print( '-----', file = sys.stderr )
raise
# set this variable to True and then fill self.tests_file_content with debug data
print_debug = False
test_file = None
# print contents of an elem (sub)tree to file, to examine its content
def printTree( self, elem ):
# test if an element has children: if elem:
current = deepcopy( elem )
ancestors = []
depth = 0
print_current = True
self.tests_file_content += '\n'
while True:
if print_current: # print data of current
indent = depth * ' '
self.tests_file_content += indent + '------\n'
if current.tag: self.tests_file_content += '{0}tag : {1}\n'.format( indent, current.tag )
if current.text: self.tests_file_content += '{0}text : {1}\n'.format( indent, current.text )
if current.attrib: self.tests_file_content += '{0}attr : {1}\n'.format( indent, ', '.join( '\n {0} : {1}'.format( k, v ) for k, v in current.attrib.items()))
if current.tail: self.tests_file_content += '{0}tail : {1}\n'.format( indent, current.tail )
if current: # has children
if not ancestors or ( ancestors and ancestors[ -1 ] != current ): # not last in list
ancestors.append( current )
current = current[ 0 ] # set first child as current
print_current = True
depth += 1
else: # current has no children
if not ancestors: # or ( len( children ) == 1 ) && children[ -1 ] == current:
break
leaf = current
if ancestors[ -1 ] == current: # last in list
ancestors.pop()
if ancestors:
current = ancestors[ -1 ] # set parent as current (last in list)
current.remove( leaf )
print_current = False
depth -= 1
else:
break
def align( length, alignment ):
if length % alignment == 0:
return length
return ( length // alignment + 1 ) * alignment
def getFullType( elem, self = None ):
elem_typ = elem.find( 'type' )
elem_str = ( elem.text or '' ).lstrip()
type_str = elem_typ.text.strip()
tail_str = ( elem_typ.tail or '' ).rstrip()
result = elem_str + type_str + tail_str
# catch const variations
if tail_str.startswith( '* c' ): # double const
result = 'const( {0}* )*'.format( type_str )
elif tail_str == '*' and elem_str: # single const
result = 'const( {0} )*'.format( type_str )
# catch opaque structs, currently it
# converts: struct wl_display* -> wl_display*
# converts: struct wl_surface* -> wl_surface*
if result.startswith( 'struct' ):
result = type_str.lstrip( 'struct ' )
# catch array types
enum = elem.find( 'enum' )
if enum is None: # integral array size
result += ( elem.find( 'name' ).tail or '' )
else: # enum array size
result = '{0}[ {1} ]'.format( result, enum.text )
return result
class DGenerator( OutputGenerator ):
def __init__( self, errFile = sys.stderr, warnFile = sys.stderr, diagFile = sys.stderr ):
super().__init__( errFile, warnFile, diagFile )
self.indent = 4 * ' '
self.max_func_name_len = 0
self.max_g_func_name_len = 0
self.max_i_func_name_len = 0
self.max_d_func_name_len = 0
self.feature_order = []
self.feature_content = dict()
self.platform_extension_order = []
self.platform_protection_order = []
self.platform_extension_protection = dict()
self.platform_name_protection = dict()
self.bitmask_flag_bits_flags = dict() # record occurrence of VkSomeFlags or VkSomeFlagBits for pairing
# start processing
def beginFile( self, genOpts ):
self.genOpts = genOpts
self.indent = genOpts.indentString
try:
os.mkdir( genOpts.directory )
except FileExistsError:
pass
# store print debug in tests_file_content
if print_debug:
self.tests_file_content = ''
# since v1.1.70 we only get platform names per feature, but not their protect string
# these are stored in vk.xml in platform tags, we extract them and map
# platform name to platform protection
for platform in self.registry.tree.findall( 'platforms/platform' ):
self.platform_name_protection[ platform.get( 'name' ) ] = platform.get( 'protect' )
# end processing, store data to files
def endFile( self ):
if self.genOpts.current_xml == 'vk':
types_file_name = 'types.d'
TYPES_OR_VIDEO = TYPES
else:
types_file_name = 'vk_video.d'
TYPES_OR_VIDEO = VK_VIDEO
# --------------------------------- #
# write types.d and vk_video.d file #
# --------------------------------- #
# helper function to join function sections into format substitutions
def typesSection():
result = ''
# some of the sections need formatting before being merged into one code block
# in these cases the substitute parameter will contain the corresponding term
for feature in self.feature_order:
feature_section = self.feature_content[ feature ][ 'Type_Definitions' ]
if feature_section:
result += '\n// - {0} -\n{1}\n'.format( feature, '\n'.join( feature_section ))
return result[:-1]
# types file format string, substitute format tokens with accumulated section data
file_content = TYPES_OR_VIDEO.format(
PACKAGE_PREFIX = self.genOpts.packagePrefix,
TYPE_DEFINITIONS = typesSection(),
)
with open( path.join( self.genOpts.directory, types_file_name ), 'w', encoding = 'utf-8' ) as d_module:
write( file_content, file = d_module )
# vulkan-docs-v1.3.238 introduced a second xml file (video.xml)
# both xml files get parsed, the current file is stored in the generator options
# video.xml contains only type definitions, hence we can exit after types have been written out
# additional xml; files will probably need a more sophisticated approach
if self.genOpts.current_xml != 'vk':
if print_debug:
write( self.tests_file_content, file = tests_file )
return
# -------------------- #
# write package.d file #
# -------------------- #
with open( path.join( self.genOpts.directory, 'package.d' ), 'w', encoding = 'utf-8' ) as d_module:
write( PACKAGE_HEADER.format( PACKAGE_PREFIX = self.genOpts.packagePrefix ), file = d_module )
# ----------------- #
# justify functions #
# ----------------- #
# loop through all functions of all features and align their names
# in the outer loop are three categories, each category has a different per feature count of function items
# we store the function name length in only one function item, it can be reused with the other items in the same category
# the items which store the name length are tuples of ( func item string, func name length )
# the others are simply func item strings
for value in self.feature_content.values():
# function type aliases: alias PFN_vkFuncName = return_type function( params );
# function declarations: PFN_vkFuncName = vkFuncName
for i in range( len( value[ 'Func_Type_Aliases' ] )):
lj = self.max_func_name_len - value[ 'Func_Type_Aliases' ][ i ][ 1 ]
value[ 'Func_Type_Aliases' ][ i ] = value[ 'Func_Type_Aliases' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
value[ 'Func_Declarations' ][ i ] = value[ 'Func_Declarations' ][ i ].format( LJUST_NAME = lj * ' ' )
# global function aliases for extensions merged into vulkan 1.1: alias vkFuncNameKHR = vkFuncName;
for i in range( len( value[ 'Func_Aliases' ] )):
lj = self.max_func_name_len - value[ 'Func_Aliases' ][ i ][ 1 ] + 6 # length of alias_
value[ 'Func_Aliases' ][ i ] = value[ 'Func_Aliases' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
# global level functions: vkFuncName = cast( PFN_vkFuncName ) vkGetInstanceProcAddr( instance, "vkFuncName" );
for i in range( len( value[ 'Load_G_Funcs' ] )):
lj = self.max_g_func_name_len - value[ 'Load_G_Funcs' ][ i ][ 1 ]
value[ 'Load_G_Funcs' ][ i ] = value[ 'Load_G_Funcs' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
# instance level functions: vkFuncName = cast( PFN_vkFuncName ) vkGetInstanceProcAddr( instance, "vkFuncName" );
for i in range( len( value[ 'Load_I_Funcs' ] )):
lj = self.max_i_func_name_len - value[ 'Load_I_Funcs' ][ i ][ 1 ]
value[ 'Load_I_Funcs' ][ i ] = value[ 'Load_I_Funcs' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
# device level functions: vkFuncName = cast( PFN_vkFuncName ) vkGetDeviceProcAddr( device, "vkFuncName" );
# dispatch declarations: return_type FuncName( params ) { return vkFuncName( device, params ); }
for i in range( len( value[ 'Load_D_Funcs' ] )):
lj = self.max_d_func_name_len - value[ 'Load_D_Funcs' ][ i ][ 1 ]
value[ 'Load_D_Funcs' ][ i ] = value[ 'Load_D_Funcs' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
value[ 'Disp_Declarations' ][ i ] = value[ 'Disp_Declarations' ][ i ].format( LJUST_NAME = lj * ' ' )
# dispatch device convenience function aliases for extensions merged into vulkan 1.1: alias FuncNameKHR = FuncName;
for i in range( len( value[ 'Conven_Aliases' ] )):
lj = self.max_d_func_name_len - value[ 'Conven_Aliases' ][ i ][ 1 ] + 6 # length of alias_
value[ 'Conven_Aliases' ][ i ] = value[ 'Conven_Aliases' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
# dispatch device function aliases for extensions merged into vulkan 1.1: alias vkFuncNameKHR = vkFuncName;
for i in range( len( value[ 'Disp_Aliases' ] )):
lj = self.max_d_func_name_len - value[ 'Disp_Aliases' ][ i ][ 1 ] + 6 # length of alias_
value[ 'Disp_Aliases' ][ i ] = value[ 'Disp_Aliases' ][ i ][ 0 ].format( LJUST_NAME = lj * ' ' )
# ---------------------- #
# write functions.d file #
# ---------------------- #
# helper function to join function sections into format substitutions
def functionSection( section, indent, Instance_or_Device = '' ):
result = ''
joiner = '\n' + indent
# some of the sections need formatting before being merged into one code block
# in these cases the substitute parameter will contain the corresponding term
for feature in self.feature_order:
feature_section = self.feature_content[ feature ][ section ]
if feature_section:
result += '\n{0}// {1}\n{0}{2}\n'.format( indent, feature, joiner.join( feature_section ))
# some of the sections need formatting before being merged into one code block
# in these cases the substitute parameter will contain the corresponding term
if Instance_or_Device:
result = result.format( INSTANCE_OR_DEVICE = Instance_or_Device, instance_or_device = Instance_or_Device.lower())
return result[:-1]
# functions file format string, substitute format tokens with accumulated section data
file_content = FUNCS.format(
IND = self.indent,
PACKAGE_PREFIX = self.genOpts.packagePrefix,
FUNC_TYPE_ALIASES = functionSection( 'Func_Type_Aliases', self.indent ),
FUNC_DECLARATIONS = functionSection( 'Func_Declarations', self.indent ) + '\n' \
+ functionSection( 'Func_Aliases' , self.indent ),
GLOBAL_LEVEL_FUNCS = functionSection( 'Load_G_Funcs' , self.indent ),
INSTANCE_LEVEL_FUNCS = functionSection( 'Load_I_Funcs' , self.indent ),
DEVICE_I_LEVEL_FUNCS = functionSection( 'Load_D_Funcs' , self.indent, 'Instance' ),
DEVICE_D_LEVEL_FUNCS = functionSection( 'Load_D_Funcs' , self.indent, 'Device' ),
DISPATCH_MEMBER_FUNCS = functionSection( 'Load_D_Funcs' , self.indent * 2, 'Device' ),
DISPATCH_CONVENIENCE_FUNCS = functionSection( 'Conven_Funcs' , self.indent ),
DISPATCH_FUNC_DECLARATIONS = functionSection( 'Disp_Declarations', self.indent ),
)
# open, write and close functions.d file
with open( path.join( self.genOpts.directory, 'functions.d' ), 'w', encoding = 'utf-8' ) as d_module:
write( file_content, file = d_module )
# ---------------------------- #
# write dispatch_device.d file #
# ---------------------------- #
# functions file format string, substitute format tokens with accumulated section data
file_content = DISPATCH_DEVICE.format(
IND = self.indent,
PACKAGE_PREFIX = self.genOpts.packagePrefix,
DISPATCH_MEMBER_FUNCS = functionSection( 'Load_D_Funcs' , self.indent * 2, 'Device' ),
DISPATCH_CONVENIENCE_FUNCS = functionSection( 'Conven_Funcs' , self.indent ) + '\n' \
+ functionSection( 'Conven_Aliases' , self.indent ),
DISPATCH_FUNC_DECLARATIONS = functionSection( 'Disp_Declarations', self.indent ) + '\n' \
+ functionSection( 'Disp_Aliases' , self.indent ),
)
# open, write and close functions.d file
with open( path.join( self.genOpts.directory, 'dispatch_device.d' ), 'w', encoding = 'utf-8' ) as d_module:
write( file_content, file = d_module )
# -------------------------------- #
# write platform_extensions.d file #
# -------------------------------- #
# helper function to construct AliasSequences of extension enums
def platformProtectionAlias():
if self.platform_protection_order:
max_protect_len = len( max( self.platform_protection_order, key = lambda p: len( p )))
result = ''
for protection in self.platform_protection_order:
result += 'alias {0} = AliasSeq!( {1} );\n'.format( protection[3:].ljust( max_protect_len - 3 ), self.platform_extension_protection[ protection ] )
return result
# helper function to populate a (else) static if block with corresponding code
def platformExtensionSection( sections, indent = '', comment = '', Instance_or_Device = '' ):
result = ''
else_prefix = ''
open_format = ''
close_format = ''
# some sections include additional format strings which we must escape with these
if Instance_or_Device:
open_format = '{'
close_format = '}'
# We want to merge Type_Definitions and Func_Type_Aliases
# hence we wrap each section parameter into a list
joiner = '\n' + indent + self.indent
for extension in self.platform_extension_order:
# We want to merge of Type_Definitions and Func_Type_Aliases into one static if block
# hence we pass each section type as a list so we can combine several of them first
extension_section = []
for section in sections:
extension_section += self.feature_content[ extension ][ section ]
if extension_section:
result += STATIC_IF_EXTENSION.format(
IND = indent,
EXTENSION = extension[3:],
COMMENT = comment,
OPEN_FORMAT = open_format,
ELSE_PREFIX = else_prefix,
SECTIONS = indent + self.indent + joiner.join( extension_section ),
CLOSE_FORMAT = close_format,
)
else_prefix = 'else '
# some of the sections need formatting before being merged into one code block
# in these cases the substitute parameter will contain the corresponding term
if Instance_or_Device:
result = result.format( INSTANCE_OR_DEVICE = Instance_or_Device, instance_or_device = Instance_or_Device.lower())
return result[:-1] # omit the final line break
# platform_extensions file format string, substitute format tokens with accumulated section data
file_content = PLATFORM_EXTENSIONS.format(
IND = self.indent,
PACKAGE_PREFIX = self.genOpts.packagePrefix,
PLATFORM_EXTENSIONS = 'enum {0};'.format( ';\nenum '.join( [ extension[3:] for extension in self.platform_extension_order ] )),
PLATFORM_PROTECTIONS = platformProtectionAlias(),
TYPE_DEFINITIONS = platformExtensionSection( [ 'Type_Definitions', 'Func_Type_Aliases' ], 2 * self.indent, ' : types and function pointer type aliases' ),
FUNC_DECLARATIONS = platformExtensionSection( [ 'Func_Declarations' ] , 3 * self.indent, ' : function pointer decelerations' ),
INSTANCE_LEVEL_FUNCS = platformExtensionSection( [ 'Load_I_Funcs' ] , 3 * self.indent, ' : load instance level function definitions' ),
DEVICE_I_LEVEL_FUNCS = platformExtensionSection( [ 'Load_D_Funcs' ] , 3 * self.indent, ' : load instance based device level function definitions', 'Instance' ),
DEVICE_D_LEVEL_FUNCS = platformExtensionSection( [ 'Load_D_Funcs' ] , 3 * self.indent, ' : load device based device level function definitions' , 'Device' ),
DISPATCH_MEMBER_FUNCS = platformExtensionSection( [ 'Load_D_Funcs' ] , 4 * self.indent, ' : load dispatch device member function definitions' , 'Device' ),
DISPATCH_CONVENIENCE_FUNCS = platformExtensionSection( [ 'Conven_Funcs' ] , 3 * self.indent, ' : dispatch device convenience member functions' ),
DISPATCH_FUNC_DECLARATIONS = platformExtensionSection( [ 'Func_Declarations' ] , 3 * self.indent, ' : dispatch device member function pointer decelerations' )
)
with open( path.join( self.genOpts.directory, 'platform_extensions.d' ), 'w', encoding = 'utf-8' ) as d_module:
write( file_content, file = d_module )
# ------------------------------ #
# write vulkan_lib_loader.d file #
# ------------------------------ #
with open( path.join( self.genOpts.directory, 'vulkan_lib_loader.d' ), 'w', encoding = 'utf-8' ) as d_module:
write( LIB_LOADER.format( PACKAGE_PREFIX = self.genOpts.packagePrefix, IND = self.indent ), file = d_module )
# write and close remaining tests data into tests.txt file
if print_debug:
write( self.tests_file_content, file = tests_file )
#self.tests_file.close()
# This is an ordered list of sections in the header file.
TYPE_SECTIONS = [ 'include', 'define', 'basetype', 'handle', 'enum', 'group', 'bitmask', 'funcpointer', 'struct' ]
ALL_SECTIONS = TYPE_SECTIONS + ['commandPointer', 'command']
# begin parsing of all types and functions of a certain feature / extension
def beginFeature( self, interface, emit ):
OutputGenerator.beginFeature( self, interface, emit )
platform = interface.get( 'platform' )
protection = self.platform_name_protection.get( platform, None )
if protection:
# some features are protected with the same protection, we want them only once in list
if protection not in self.platform_protection_order:
self.platform_protection_order.append( protection )
# collect all features belonging to one protection in a string. Will be used in module platform_extensions
if protection not in self.platform_extension_protection:
self.platform_extension_protection[ protection ] = self.featureName[3:];
else:
self.platform_extension_protection[ protection ] += ', {0}'.format( self.featureName[3:] )
# handle the current feature as platform extension
self.platform_extension_order.append( self.featureName )
else:
# feature is not protected -> handle as normal types and functions
self.feature_order.append( self.featureName )
self.feature_content[ self.featureName ] = {
'Type_Definitions' : [ 'enum {0} = 1;\n'.format( self.featureName ) ],
'Func_Type_Aliases' : [],
'Func_Declarations' : [],
'Func_Aliases' : [],
'Load_G_Funcs' : [],
'Load_I_Funcs' : [],
'Load_D_Funcs' : [],
'Conven_Funcs' : [],
'Conven_Aliases' : [],
'Disp_Declarations' : [],
'Disp_Aliases' : []
}
self.sections = dict( [ ( section, [] ) for section in self.ALL_SECTIONS ] )
# end parsing of all types and functions of a certain feature / extension
def endFeature( self ):
# exit this function if content is not supposed to be emitted
if not self.emit: return
#self.tests_file_content += self.featureName + '\n'
#TYPE_SECTIONS = [
# 'include', 'define', 'basetype', 'handle', 'enum', 'group', 'bitmask', 'funcpointer', 'struct' ]
#self.tests_file_content += '\n'.join( self.sections[ 'basetype' ] )
#self.tests_file_content += '\n'.join( self.sections[ 'handle' ] )
#self.tests_file_content += '\n'.join( self.sections[ 'enum' ] ) + '\n\n'
#self.tests_file_content += '\n'.join( self.sections[ 'group' ] )
#self.tests_file_content += '\n'.join( self.sections[ 'bitmask' ] )
#self.tests_file_content += '\n'.join( self.sections[ 'funcpointer' ] )
#self.tests_file_content += '\n'.join( self.sections[ 'struct' ] )
# combine all type sections
file_content_list = []
for section in self.TYPE_SECTIONS:
if self.sections[ section ]:
file_content_list += self.sections[ section ] + [ '' ]
self.feature_content[ self.featureName ][ 'Type_Definitions' ] += file_content_list
file_content_list = []
# Finish processing in superclass
OutputGenerator.endFeature( self )
# append a definition to the specified section
def appendSection( self, section, text ):
self.sections[ section ].append( text )
# defer generation for bitmasks, so we can pair alias VkSomeFlags with enum VkSomeFlagBits : VkSomeFlags {}
def genEnumsOrFlags( self, group_name, group_elem, type_alias = None ):
is_enum = type_alias is None
#if not is_enum:
# self.tests_file_content += '2 - {0} = {1}\n'.format( '1' if is_enum else '0', str(len(group_elem_requires)))
# printTree( self, type_alias )
SNAKE_NAME = re.sub( r'([0-9a-z_])([A-Z0-9][^A-Z0-9]?)', r'\1_\2', group_name ).upper()
#self.tests_file_content += group_name.ljust( 30 ) + ' : ' + SNAKE_NAME + '\n'
name_prefix = SNAKE_NAME
name_suffix = ''
expand_suffix_match = re.search( r'[A-Z][A-Z]+$', group_name )
if expand_suffix_match:
name_suffix = '_' + expand_suffix_match.group()
# Strip off the suffix from the prefix
name_prefix = SNAKE_NAME.rsplit( name_suffix, 1 )[ 0 ]
#self.tests_file_content += name_suffix + '\n'
#printTree( self, group_elem )
# scoped enums
scoped_group = []
# bitfield Flags alias
if not is_enum:
enum_type = type_alias.attrib[ 'name' ]
# alias corresponding Flags to the underlying (indirect) type
scoped_group.append( 'alias {0} = {1};'.format( enum_type, type_alias.find( 'type' ).text ))
# group scoped enums by their name
scoped_group.append( 'enum {0} : {1} {{'.format( group_name, enum_type ))
#printTree( self, type_alias )
# no Flags for enums
else:
# group scoped enums by their name
scoped_group.append( 'enum {0} {{'.format( group_name ))
# add grouped enums to global scope
global_group = [ '' ]
# Get a list of nested 'enum' tags.
enums = group_elem.findall( 'enum' )
# Check for and report duplicates, and return a list with them
# removed.
enums = self.checkDuplicateEnums( enums )
# source: cgenerator.py
# Loop over the nested 'enum' tags. Keep track of the min_value and
# maximum numeric values, if they can be determined; but only for
# core API enumerants, not extension enumerants. This is inferred
# by looking for 'extends' attributes.
#
# vulkan-docs-v1.1.118 introduced an empty enum group (VkPipelineCompilerControlFlagBitsAMD)
# in this case required_enum_names will be empty and we simply exit this method, but only for enums.
required_enum_names = [ elem.get( 'name' ) for elem in enums if self.isEnumRequired( elem ) ]
if is_enum and not required_enum_names: return
max_global_len = len( max( required_enum_names, key = lambda name: len( name ))) if required_enum_names else 0
max_global_len = align( 5 + max_global_len, 2 * len( self.indent )) # len( 'enum ' ) = 5, len( '_BEGIN_RANGE' ) = 12
max_scoped_len = max_global_len # global enums are one char longer than scoped enums, hence + 1
# some enums elements have been renamed, the old names are aliased with new names
# and the elements added to the end of the enum element lists
scoped_alias = []
global_alias = []
# we store the value range of enums as min_name and max_name
min_name = None
for elem in enums:
# Extension enumerates are only included if they are required
if self.isEnumRequired( elem ):
# Convert the value to an integer and use that to track min/max.
# Values of form -( number ) are accepted but nothing more complex.
# Should catch exceptions here for more complex constructs. Not yet.
( enum_val, enum_str ) = self.enumToValue( elem, True )
name = elem.get( 'name' )
# as of version 1.2.170 two bitmasks have a bitwidth of 64
# (VkPipelineStageFlagBits2KHR and VkAccessFlags2KHR) requiring special treatment
# we need to catch all enum bitfield values ending with ULL and remove the final L
# unfortunately this is true for the enum VK_SAMPLER_YCBCR_RANGE_ITU_FUL as well
# so we also check if the current enum group is an enum or a bitfield
#
# The ULL postfix of VkFlags64 have been removed from vk.xml in version 1.2.174,
# but unnecessarily added back in version 1.3.222.
# This time we keep the code handling, but remove the whole ULL instead of only the last L
if not is_enum and enum_str.endswith( 'ULL' ):
enum_str = enum_str[ : -3 ]
scoped_elem = '{0} = {1},'.format( ( self.indent + name ).ljust( max_scoped_len ), enum_str )
global_elem = '{0} = {1}.{2};'.format( ( 'enum ' + name ).ljust( max_global_len ), group_name, name )
if enum_val != None:
scoped_group.append( scoped_elem )
global_group.append( global_elem )
else:
scoped_alias.append( scoped_elem )
global_alias.append( global_elem )
# Extension enumerates are only included if they are requested
# in addExtensions or match defaultExtensions.
#if ( elem.get( 'extname' ) is None or
# re.match( self.genOpts.addExtensions, elem.get( 'extname' )) is not None or
# self.genOpts.defaultExtensions == elem.get( 'supported' )):
# scoped_elem = '\n{0}{1} = {2},'.format( self.indent, name.ljust( max_scoped_len ), enum_str )
# if scoped_elem not in scoped_elem_set:
# scoped_elem_set.add( scoped_elem )
# scoped_group += scoped_elem
# global_group += '\nenum {0} = {1}.{2};'.format( name.ljust( max_global_len ), group_name, name )
if is_enum and enum_val != None and elem.get( 'extends' ) is None:
if min_name is None:
min_name = max_name = name
min_value = max_value = enum_val
elif enum_val < min_value:
min_name = name
min_value = enum_val
elif enum_val > max_value:
max_name = name
max_value = enum_val
if global_alias: global_group += global_alias
if scoped_alias: scoped_group += scoped_alias
# as of version 1.2.170 two bitmaks have a bitwidth of 64
# (VkPipelineStageFlagBits2KHR and VkAccessFlags2KHR) requiring special treatment
# we need to drop the _MAX_ENUM (final) entry, it is also not present in the c header version
if 'bitwidth' not in group_elem.attrib:
scoped_group.append(( self.indent + name_prefix + '_MAX_ENUM' + name_suffix ).ljust( max_scoped_len ) + ' = 0x7FFFFFFF' )
scoped_group.append( '}' )
global_group.append( '{0} = {1}.{2}{3}{4};'.format( ( 'enum ' + name_prefix + '_MAX_ENUM' + name_suffix ).ljust( max_global_len ), group_name, name_prefix, '_MAX_ENUM' , name_suffix ))
else:
scoped_group.append( '}' )
section = 'group' if is_enum else 'bitmask'
if self.sections[ section ]:
self.appendSection( section, '' ) # this empty string will be terminated with '\n' at the join operation
self.sections[ section ] += scoped_group + global_group # concatenating three lists
#if not is_enum:
# self.tests_file_content += '\n'.join( scoped_group ) + '\n\n'
# categories
def genType( self, typeinfo, name, alias ):
super().genType( typeinfo, name, alias )
elem = typeinfo.elem
#printTree( self, elem )
if 'requires' in elem.attrib:
required = elem.attrib[ 'requires' ]
if required.endswith( '.h' ):
return
elif required == 'vk_platform':
return
if 'category' not in elem.attrib:
#for k, v in elem.attrib.items():
# self.tests_file_content += '{0} : {1}'.format( k, v )
return
category = elem.get( 'category' )
if alias:
self.appendSection( category, 'alias {0} = {1};'.format( name, alias ))
return
# c header and API version
if category == 'define':
#printTree( self, elem )
# extract header version, e.g.: enum VK_HEADER_VERSION = 238;
# the elem.text begins with a comment, which we would like to keep, followed by #define on the next line, which we get rid of
if name == 'VK_HEADER_VERSION':
name_child = elem.find( 'name' )
self.appendSection( 'define', '\n{0} (corresponding c header)\nenum {1} = {2};\n'.format( elem.text.splitlines()[0], name, name_child.tail.strip() ))
# extract header version complete: enum VK_HEADER_VERSION_COMPLETE = VK_MAKE_API_VERSION( 0, 1, 2, VK_HEADER_VERSION )
# the elem.text begins with a comment, which we would like to keep, followed by #define on the next line, which we get rid of
elif name == 'VK_HEADER_VERSION_COMPLETE':
type_child = elem.find( 'type' )
self.appendSection( 'define', '{0} (corresponding c header)\nenum {1} = {2}( {3} );'.format( elem.text.splitlines()[0], name, type_child.text, type_child.tail[ 1 : -1 ] ))
elif name == 'VK_MAKE_API_VERSION':
name_child = elem.find( 'name' )
[ params, body ] = name_child.tail.split( ' \\' )
params = params[ 1 : -1 ].replace( 'v', 'uint v').replace( 'm', 'uint m' ).replace( 'p', 'uint p' )
body = body.strip().replace( '(uint32_t)', '' ).replace( '((variant))', 'variant' ).replace( '((major))', 'major' ).replace( '((minor))', 'minor' ).replace( '((patch))', 'patch' )[ 1 : -1 ]
body = body.replace( 'U', '' ).replace( '(', '( ' ).replace( ')', ' )' )
self.appendSection( 'define', dedent( '''\
pure {{
{0}uint {1}( {2} ) {{ return {3}; }}
{0}uint VK_API_VERSION_VARIANT( uint ver ) {{ return ver >> 29; }}
{0}uint VK_API_VERSION_MAJOR( uint ver ) {{ return ( ver >> 22 ) & 0x7F; }}
{0}uint VK_API_VERSION_MINOR( uint ver ) {{ return ( ver >> 12 ) & 0x3FF; }}
{0}uint VK_API_VERSION_PATCH( uint ver ) {{ return ver & 0xFFF; }}
}}
''' ).format( self.indent, name, params, body ))
elif name == 'VK_MAKE_VERSION': # deprecated
name_child = elem.find( 'name' )
[ params, body ] = name_child.tail.split( ' \\' )
params = params[ 1 : -1 ].replace( 'm', 'uint m' ).replace( 'p', 'uint p' )
body = body.strip().replace( '(uint32_t)', '' ).replace( '((major))', 'major' ).replace( '((minor))', 'minor' ).replace( '((patch))', 'patch' )[ 1 : -1 ]
body = body.replace( 'U', '' ).replace( '(', '( ' ).replace( ')', ' )' )
self.appendSection( 'define', dedent( '''
{4}
deprecated( "These defines have been deprecated, use VK_MAKE_API_VERSION and VK_API_VERSION_ variants instead!" ) {{
{0}pure {{
{0}{0}uint {1}( {2} ) {{ return {3}; }}
{0}{0}uint VK_VERSION_MAJOR( uint ver ) {{ return ver >> 22; }}
{0}{0}uint VK_VERSION_MINOR( uint ver ) {{ return ( ver >> 12 ) & 0x3FF; }}
{0}{0}uint VK_VERSION_PATCH( uint ver ) {{ return ver & 0xFFF; }}
{0}}}
}}
''' ).format( self.indent, name, params, body, elem.text.splitlines()[0] )) # splitlines()[0] gets rid of #define on second line
elif name == 'VK_MAKE_VIDEO_STD_VERSION':
name_child = elem.find( 'name' )
[ params, body ] = name_child.tail.split( ' \\' )
params = params[ 1 : -1 ].replace( 'm', 'uint m' ).replace( 'p', 'uint p' )
body = body.strip().replace( '(uint32_t)', '' ).replace( '((major))', 'major' ).replace( '((minor))', 'minor' ).replace( '((patch))', 'patch' )[ 1 : -1 ]
body = body.replace( '(', '( ' ).replace( ')', ' )' )
self.appendSection( 'define', 'pure uint {0}( {1} ) {{ return {2}; }}'.format( name, params, body ))
elif name.startswith( 'VK_API_VERSION_1' ) or name.startswith( 'VK_STD_VULKAN_VIDEO_CODEC_' ):
comment = elem.text.splitlines()[0] # gets rid of #define on second line of elem.text
if comment:
self.appendSection( 'define', comment )
type_child = elem.find( 'type' )
type_child_tail = type_child.tail.split( '//' )
if len( type_child_tail ) == 2:
type_child_tail = '( {0} );\t//{1}'.format( type_child_tail[0][ 1 : -1 ], type_child_tail[1] )
else:
type_child_tail = '( {0} );'.format( type_child_tail[0][ 1 : -1 ] )
self.appendSection( 'define', 'enum {0} = {1}{2}'.format( elem.find( 'name' ).text, type_child.text, type_child_tail ))
else:
#printTree( self, elem )
pass
# alias VkFlags = uint32_t;
elif category == 'basetype':
type_child = elem.find( 'type' )
if type_child is not None:
self.appendSection( 'basetype', 'alias {0} = {1};'.format( name, type_child.text ))
# mixin( VK_DEFINE_HANDLE!q{VkInstance} );
elif category == 'handle':
self.appendSection( 'handle', 'mixin( {0}!q{{{1}}} );'.format( elem.find( 'type' ).text, name ))
# alias VkFlags with ... Flags corresponding to ...FlagBits: enum VkFormatFeatureFlagBits {...}; alias VkFormatFeatureFlags = VkFlags;
elif category == 'bitmask':
# print fields of an object, object must have __dict__ attribute
#fields = vars( typeinfo )
#self.tests_file_content += '\nTypeinfo:\n '
#self.tests_file_content += '\n '.join( '{0} : {1}'.format( k, v ) for k, v in fields.items() )
#self.tests_file_content += '\n'
group_name = None
if 'requires' in elem.attrib:
group_name = elem.attrib[ 'requires' ]
elif 'bitvalues' in elem.attrib:
group_name = elem.attrib[ 'bitvalues' ]
if group_name:
if group_name in self.bitmask_flag_bits_flags:
# if FlagBits were captured previously we create the Flags and FlagBits pair now
self.genEnumsOrFlags( group_name, self.bitmask_flag_bits_flags[ group_name ], elem )
else:
# else we record this Flags data for deferred use
self.bitmask_flag_bits_flags[ group_name ] = elem
else:
# old behavior still required at some places
self.appendSection( 'bitmask', 'alias {0} = {1};'.format( name, elem.find( 'type' ).text ))
#self.tests_file_content += '\nGenerate Category bitmask:'
#printTree( self, elem )
# alias PFN_vkAllocationFunction = void* function( ... )
elif category == 'funcpointer':
return_type = elem.text[ 8 : -13 ]
#params = ''.join( getFullType( x.replace( 16 * ' ', '', 1 )) for x in islice( elem.itertext(), 2, None ))
params = ''.join( x for x in islice( elem.itertext(), 2, None ))
param_lines = params.splitlines( 1 ) # 1 means include line break
trim_space = True
for i in range( len( param_lines )):
line = param_lines[ i ]
if line.startswith( ' ' ):
line = line.strip( ' ' )
if line.startswith( 'const ' ):
line = line.replace( 'const ', 'const( ') # scope const to next element
line = line.replace( '*', ' )*' ) # end scope before asterisk
line = line.replace( ' ', '', 1 ) # remove three spaces taken by parenthesis and one space before
line = self.indent + line
trim_space = trim_space and 16 * ' ' in line
param_lines[ i ] = line
if trim_space:
params = ''.join( line.replace( 16 * ' ', '', 1 ) for line in param_lines )
else:
params = ''.join( param_lines )
#self.tests_file_content += params + '\n\n'
params.replace( ')', ' )' )
if params == ')(void);' : params = ');'
else: params = params[ 2: ].replace( ');', '\n);' ).replace( ' )', ' )' )
if self.sections[ 'funcpointer' ]:
self.appendSection( 'funcpointer', '' )
self.appendSection( 'funcpointer', 'alias {0} = {1} function({2}'.format( name, return_type, params ))
#self.tests_file_content += 'alias {0} = {1} function{2}'.format( name, return_type, params )
# structs and unions
elif category == 'struct' or category == 'union':
self.genStruct( typeinfo, name, alias )
else:
pass
# structs and unions
def genStruct( self, typeinfo, name, alias ):
super().genStruct( typeinfo, name, alias )
elem = typeinfo.elem
category = elem.attrib[ 'category' ]
if self.sections[ 'struct' ]:
self.appendSection( 'struct', '' )
self.appendSection( 'struct', '{0} {1} {{'.format( category, name ))
member_type_length = 0
member_name_length = 0
member_type_names = []
member_bitfield = []
has_member_scope = False
has_member_module = False
has_member_version = False
has_member_function = False
for member in elem.findall( 'member' ):
member_name = member.find( 'name' ).text
# don't use D keyword module
if member_name == 'module':
member_name = 'Module'
has_member_module = True
# don't use D keyword scope
if member_name == 'scope':
member_name = 'Scope'
has_member_scope = True
# don't use D keyword version
if member_name == 'version':
member_name = 'Version'
has_member_version = True
# don't use D keyword function
if member_name == 'function':
member_name = 'Function'
has_member_function = True
# member default values, not sure if this is supported for bitfields. If not move this into next else clause
if member.get( 'values' ):
member_name += ' = ' + member.get( 'values' )
# v1.2.135 introduced a struct (VkAccelerationStructureInstanceKHR) with bitfields
# DLang bitfields are implemented via std.bitmanip.bitfields, we need extra work to parse the xml data
member_type = getFullType( member ).strip()
member_type_bitcount = member_type.split(':')
if len( member_type_bitcount ) == 2: # bitfields
# printTree( self, elem )
member_bitfield.append( ( member_type_bitcount[ 0 ] + ',', '"{0}",'.format( member_name ), member_type_bitcount[ 1 ] ) )
member_type_length = max( member_type_length, len( member_type ) + len( self.indent ))
member_name_length = max( member_name_length, len( member_name ) + 4 )
else: # non-bitfield processing
if member_bitfield: # store code chunk
member_type_names.append( member_bitfield ) # store all bitfields in a list of tuples
member_bitfield = [] # now we can scan for and process another bitfield in this struct
# get the maximum string length of all member types
member_type_names.append( ( member_type, member_name ) )
member_type_length = max( member_type_length, len( member_type ) + 2 )
#member_type_length = align( max( member_type_length, len( member_type )), len( self.indent ))
# loop second time and use maximum type string length to offset member names
for type_name in member_type_names:
if type( type_name ) is tuple: # normal struct members
#t, n, c = type_name # t(ype), n(ame), c(omment)
#self.appendSection( 'struct', '{0}{1}{2};{3}'.format( self.indent, t.ljust( member_type_length ), n, c ))
t, n = type_name # t(ype), n(ame)
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, t.ljust( member_type_length ), n )) #, c ))
#if c: self.tests_file_content += '{0}{1}{2};{3}'.format( self.indent, t.ljust( member_type_length ), n, c )
else: # bitfields
self.appendSection( 'struct', '{0}mixin( bitfields!('.format( self.indent ))
#for ( t, n, b, c ) in type_name: # t(ype), n(ame), b(itfield), c(omment)
# self.appendSection( 'struct', '{0}{1}{2}{3}{4},'.format( 2 * self.indent, t.ljust( member_type_length - len( self.indent )), n.ljust( member_name_length ), b)) #, c ))
for ( t, n, b ) in type_name: # t(ype), n(ame), b(itfield)
self.appendSection( 'struct', '{0}{1}{2}{3},'.format( 2 * self.indent, t.ljust( member_type_length - len( self.indent )), n.ljust( member_name_length ), b)) #, c ))
#if c: self.tests_file_content += '{0}{1}{2}{3}{4},'.format( 2 * self.indent, t.ljust( member_type_length - len( self.indent )), n.ljust( member_name_length ), b, c )
self.appendSection( 'struct', '{0}));'.format( self.indent ))
if has_member_scope:
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), 'scope_ = Scope' ))
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), '_scope = Scope' ))
if has_member_module:
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), 'module_ = Module' ))
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), '_module = Module' ))
if has_member_version:
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), 'version_ = Version' ))
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), '_version = Version' ))
if has_member_function:
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), 'function_ = Function' ))
self.appendSection( 'struct', '{0}{1}{2};'.format( self.indent, 'alias'.ljust( member_type_length ), '_function = Function' ))
self.appendSection( 'struct', '}' )
# named and global enums and enum flag bits
def genGroup( self, group_info, group_name, alias ):
super().genGroup( group_info, group_name, alias )
if alias:
self.appendSection( group_info.elem.get( 'type' ), 'alias {0} = {1};'.format( group_name, alias ))
# Todo(pp): some aliases are in a wired order, check and fix e.g. VkPointClippingBehavior
#self.tests_file_content += 'alias {0} = {1};\n'.format( group_name, alias )
return # its either alias xor enum group
group_elem = group_info.elem
category = group_elem.get( 'type' )
is_enum = category == 'enum'
#if not is_enum:
# self.tests_file_content += '\nGenerate Group Category {0}: {1}'.format( category, group_name )
# printTree( self, group_elem )
if is_enum: