/
gen_framework.py
executable file
·3099 lines (2755 loc) · 133 KB
/
gen_framework.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
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Vulkan CTS
# ----------
#
# Copyright (c) 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#-------------------------------------------------------------------------
import os
import re
import sys
import copy
import glob
import json
import argparse
from itertools import chain
from collections import OrderedDict
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "..", "scripts"))
from build.common import DEQP_DIR, execute
from khr_util.format import indentLines, writeInlFile
VULKAN_HEADERS_INCLUDE_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "vulkan-docs", "src", "include")
SCRIPTS_SRC_DIR = os.path.join(os.path.dirname(__file__), "src")
DEFAULT_OUTPUT_DIR = { "" : os.path.join(os.path.dirname(__file__), "..", "framework", "vulkan", "generated", "vulkan"),
"SC" : os.path.join(os.path.dirname(__file__), "..", "framework", "vulkan", "generated", "vulkansc") }
INL_HEADER = """\
/* WARNING: This is auto-generated file. Do not modify, since changes will
* be lost! Modify the generating script instead.
* This file was generated by /scripts/gen_framework.py
*/\
"""
DEFINITIONS = [
("VK_MAX_PHYSICAL_DEVICE_NAME_SIZE", "size_t"),
("VK_MAX_EXTENSION_NAME_SIZE", "size_t"),
("VK_MAX_DRIVER_NAME_SIZE", "size_t"),
("VK_MAX_DRIVER_INFO_SIZE", "size_t"),
("VK_UUID_SIZE", "size_t"),
("VK_LUID_SIZE", "size_t"),
("VK_MAX_MEMORY_TYPES", "size_t"),
("VK_MAX_MEMORY_HEAPS", "size_t"),
("VK_MAX_DESCRIPTION_SIZE", "size_t"),
("VK_MAX_DEVICE_GROUP_SIZE", "size_t"),
("VK_ATTACHMENT_UNUSED", "uint32_t"),
("VK_SUBPASS_EXTERNAL", "uint32_t"),
("VK_QUEUE_FAMILY_IGNORED", "uint32_t"),
("VK_QUEUE_FAMILY_EXTERNAL", "uint32_t"),
("VK_REMAINING_MIP_LEVELS", "uint32_t"),
("VK_REMAINING_ARRAY_LAYERS", "uint32_t"),
("VK_WHOLE_SIZE", "vk::VkDeviceSize"),
("VK_TRUE", "vk::VkBool32"),
("VK_FALSE", "vk::VkBool32"),
]
PLATFORM_TYPES = [
# VK_KHR_xlib_surface
(["Display","*"], ["XlibDisplayPtr"], "void*"),
(["Window"], ["XlibWindow"], "uintptr_t",),
(["VisualID"], ["XlibVisualID"], "uint32_t"),
# VK_KHR_xcb_surface
(["xcb_connection_t", "*"], ["XcbConnectionPtr"], "void*"),
(["xcb_window_t"], ["XcbWindow"], "uintptr_t"),
(["xcb_visualid_t"], ["XcbVisualid"], "uint32_t"),
# VK_KHR_wayland_surface
(["struct", "wl_display","*"], ["WaylandDisplayPtr"], "void*"),
(["struct", "wl_surface", "*"], ["WaylandSurfacePtr"], "void*"),
# VK_KHR_mir_surface
(["MirConnection", "*"], ["MirConnectionPtr"], "void*"),
(["MirSurface", "*"], ["MirSurfacePtr"], "void*"),
# VK_KHR_android_surface
(["ANativeWindow", "*"], ["AndroidNativeWindowPtr"], "void*"),
# VK_KHR_win32_surface
(["HINSTANCE"], ["Win32InstanceHandle"], "void*"),
(["HWND"], ["Win32WindowHandle"], "void*"),
(["HANDLE"], ["Win32Handle"], "void*"),
(["const", "SECURITY_ATTRIBUTES", "*"], ["Win32SecurityAttributesPtr"], "const void*"),
(["AHardwareBuffer", "*"], ["AndroidHardwareBufferPtr"], "void*"),
(["HMONITOR"], ["Win32MonitorHandle"], "void*"),
(["LPCWSTR"], ["Win32LPCWSTR"], "const void*"),
# VK_EXT_acquire_xlib_display
(["RROutput"], ["RROutput"], "void*"),
(["zx_handle_t"], ["zx_handle_t"], "uint32_t"),
(["GgpFrameToken"], ["GgpFrameToken"], "int32_t"),
(["GgpStreamDescriptor"], ["GgpStreamDescriptor"], "int32_t"),
(["CAMetalLayer"], ["CAMetalLayer"], "void*"),
# VK_EXT_metal_objects
(["MTLDevice_id"], ["MTLDevice_id"], "void*"),
(["MTLCommandQueue_id"], ["MTLCommandQueue_id"], "void*"),
(["MTLBuffer_id"], ["MTLBuffer_id"], "void*"),
(["MTLTexture_id"], ["MTLTexture_id"], "void*"),
(["IOSurfaceRef"], ["IOSurfaceRef"], "void*"),
(["MTLSharedEvent_id"], ["MTLSharedEvent_id"], "void*"),
]
PLATFORM_TYPE_NAMESPACE = "pt"
TYPE_SUBSTITUTIONS = [
# Platform-specific
("DWORD", "uint32_t"),
("HANDLE*", PLATFORM_TYPE_NAMESPACE + "::" + "Win32Handle*"),
]
EXTENSION_POSTFIXES = ["KHR", "EXT", "NV", "NVX", "KHX", "NN", "MVK", "FUCHSIA", "GGP", "AMD", "QNX"]
EXTENSION_POSTFIXES_STANDARD = ["KHR", "EXT"]
def prefixName (prefix, name):
name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', name[2:])
name = re.sub(r'([a-zA-Z])([0-9])', r'\1_\2', name)
name = name.upper()
name = name.replace("YCB_CR_", "YCBCR_")
name = name.replace("WIN_32_", "WIN32_")
name = name.replace("8_BIT_", "8BIT_")
name = name.replace("16_BIT_", "16BIT_")
name = name.replace("INT_64_", "INT64_")
name = name.replace("D_3_D_12_", "D3D12_")
name = name.replace("IOSSURFACE_", "IOS_SURFACE_")
name = name.replace("MAC_OS", "MACOS_")
name = name.replace("TEXTURE_LOD", "TEXTURE_LOD_")
name = name.replace("VIEWPORT_W", "VIEWPORT_W_")
name = name.replace("_IDPROPERTIES", "_ID_PROPERTIES")
name = name.replace("PHYSICAL_DEVICE_SHADER_FLOAT_16_INT_8_FEATURES", "PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES")
name = name.replace("PHYSICAL_DEVICE_RGBA_10_X_6_FORMATS_FEATURES_EXT", "PHYSICAL_DEVICE_RGBA10X6_FORMATS_FEATURES_EXT")
name = name.replace("_PCIBUS_", "_PCI_BUS_")
name = name.replace("ASTCD", "ASTC_D")
name = name.replace("AABBNV", "AABB_NV")
name = name.replace("IMAGE_PIPE", "IMAGEPIPE")
name = name.replace("SMBUILTINS", "SM_BUILTINS")
name = name.replace("ASTCHDRFEATURES", "ASTC_HDR_FEATURES")
name = name.replace("UINT_8", "UINT8")
name = name.replace("VULKAN_11_FEATURES", "VULKAN_1_1_FEATURES")
name = name.replace("VULKAN_11_PROPERTIES", "VULKAN_1_1_PROPERTIES")
name = name.replace("VULKAN_12_FEATURES", "VULKAN_1_2_FEATURES")
name = name.replace("VULKAN_12_PROPERTIES", "VULKAN_1_2_PROPERTIES")
name = name.replace("VULKAN_13_FEATURES", "VULKAN_1_3_FEATURES")
name = name.replace("VULKAN_13_PROPERTIES", "VULKAN_1_3_PROPERTIES")
name = name.replace("VULKAN_SC_10_FEATURES", "VULKAN_SC_1_0_FEATURES")
name = name.replace("VULKAN_SC_10_PROPERTIES", "VULKAN_SC_1_0_PROPERTIES")
name = name.replace("INT_8_", "INT8_")
name = name.replace("AABBNV", "AABB_NV")
name = name.replace("_H_264_", "_H264_")
name = name.replace("_H_265_", "_H265_")
name = name.replace("RDMAFEATURES", "RDMA_FEATURES")
name = name.replace("RGBA_10_X_6", "RGBA10X6")
name = name.replace("2_D", "2D_")
name = name.replace("3_D", "3D_")
name = name.replace("IOSURFACE", "IO_SURFACE")
return prefix + name
def getApiVariantIndexByName(variantName):
apiVariant = {
None : 0,
'' : 0,
'SC' : 1
}
return apiVariant[variantName]
def getApiVariantNameByIndex(variantIndex):
apiVariant = {
None : '',
0 : '',
1 : 'SC'
}
return apiVariant[variantIndex]
class Version:
def __init__ (self, versionTuple):
self.api = versionTuple[0]
self.major = versionTuple[1]
self.minor = versionTuple[2]
self.patch = versionTuple[3]
def getInHex (self):
if self.patch == 0:
return "VK%s_API_VERSION_%d_%d" % (getApiVariantNameByIndex(self.api), self.major, self.minor)
return '0x%Xu' % (hash(self))
def isStandardVersion (self):
if self.patch != 0:
return False
if self.major != 1:
return False
return True
def getBestRepresentation (self):
if self.isStandardVersion():
return self.getInHex()
return self.getDefineName()
def getDefineName (self):
return 'VERSION_%d_%d_%d' % (self.major, self.minor, self.patch)
def __hash__ (self):
return (self.api << 29) | (self.major << 22) | (self.minor << 12) | self.patch
def __eq__ (self, other):
return self.api == other.api and self.major == other.major and self.minor == other.minor and self.patch == other.patch
def __str__ (self):
return self.getBestRepresentation()
class Handle:
TYPE_DISP = 0
TYPE_NONDISP = 1
def __init__ (self, type, name):
self.type = type
self.name = name
self.alias = None
self.isAlias = False
def getHandleType (self):
return prefixName("HANDLE_TYPE_", self.name)
def checkAliasValidity (self):
pass
def __repr__ (self):
return '%s (%s, %s)' % (self.name, self.alias, self.isAlias)
class Definition:
def __init__ (self, type, name, value):
self.type = type
self.name = name
self.value = value
self.alias = None
self.isAlias = False
def __repr__ (self):
return '%s = %s (%s)' % (self.name, self.value, self.type)
class Enum:
def __init__ (self, name, values):
self.name = name
self.values = values
self.alias = None
self.isAlias = False
def checkAliasValidity (self):
if self.alias != None:
if len(self.values) != len(self.alias.values):
raise Exception("%s has different number of flags than its alias %s." % (self.name, self.alias.name))
for index, value in enumerate(self.values):
aliasVal = self.alias.values[index]
if value[1] != aliasVal[1] or not (value[0].startswith(aliasVal[0]) or aliasVal[0].startswith(value[0])):
raise Exception("Flag %s of %s has different value than %s of %s." % (self.alias.values[index], self.alias.name, value, self.name))
def __repr__ (self):
return '%s (%s) %s' % (self.name, self.alias, self.values)
class Bitfield:
def __init__ (self, name, values):
self.name = name
self.values = values
self.alias = None
self.isAlias = False
def checkAliasValidity (self):
if self.alias != None:
if len(self.values) != len(self.alias.values):
raise Exception("%s has different number of flags than its alias %s." % (self.name, self.alias.name))
for index, value in enumerate(self.values):
aliasVal = self.alias.values[index]
if value[1] != aliasVal[1] or not (value[0].startswith(aliasVal[0]) or aliasVal[0].startswith(value[0])):
raise Exception("Flag %s of %s has different value than %s of %s." % (self.alias.values[index], self.alias.name, value, self.name))
def __repr__ (self):
return '%s (%s)' % (self.name, self.alias)
class Variable:
def __init__ (self, type, name, arraySizeOrFieldWidth):
type = type.replace('*',' *').replace('&',' &')
for src, dst in TYPE_SUBSTITUTIONS:
type = type.replace(src, dst)
self.type = type.split(' ')
for platformType, substitute, compat in PLATFORM_TYPES:
range = self.contains(self.type, platformType)
if range != None:
self.type = self.type[:range[0]]+[PLATFORM_TYPE_NAMESPACE + '::' + substitute[0]] + substitute[1:] + self.type[range[1]:]
break
self.name = name
if len(arraySizeOrFieldWidth) > 0 and arraySizeOrFieldWidth[0] == ':':
self.arraySize = ''
self.fieldWidth = arraySizeOrFieldWidth
else:
self.arraySize = arraySizeOrFieldWidth
self.fieldWidth = ''
def contains(self, big, small):
for i in range(len(big)-len(small)+1):
for j in range(len(small)):
if big[i+j] != small[j]:
break
else:
return i, i+len(small)
return None
def getType (self):
return ' '.join(self.type).replace(' *','*').replace(' &','&')
def getAsString (self, separator):
return '%s%s%s%s%s' % (self.getType(), separator, self.name, self.arraySize, self.fieldWidth)
def getAsStringForArgumentList (self, separator):
return '%s%s%s%s' % (self.getType(), separator, self.name, self.arraySize)
def __repr__ (self):
return '<%s> <%s> <%s>' % (self.type, self.name, self.arraySize)
def __eq__ (self, other):
if len(self.type) != len(other.type):
return False
for index, type in enumerate(self.type):
if "*" == type or "&" == type or "const" == type or "volatile" == type:
if type != other.type[index]:
return False
elif type != other.type[index] and \
type not in map(lambda ext: other.type[index] + ext, EXTENSION_POSTFIXES_STANDARD) and \
other.type[index] not in map(lambda ext: type + ext, EXTENSION_POSTFIXES_STANDARD):
return False
return self.arraySize == other.arraySize
def __ne__ (self, other):
return not self == other
class CompositeType:
CLASS_STRUCT = 0
CLASS_UNION = 1
def __init__ (self, typeClass, name, members, apiVersion = None):
self.typeClass = typeClass
self.name = name
self.members = members
self.alias = None
self.isAlias = False
self.apiVersion = apiVersion
def getClassName (self):
names = {CompositeType.CLASS_STRUCT: 'struct', CompositeType.CLASS_UNION: 'union'}
return names[self.typeClass]
def checkAliasValidity (self):
if self.alias != None:
if len(self.members) != len(self.alias.members):
raise Exception("%s has different number of members than its alias %s." % (self.name, self.alias.name))
for index, member in enumerate(self.members ):
break
#if member != self.alias.members[index]:
#raise Exception("Member %s of %s is different than core member %s in %s." % (self.alias.members[index], self.alias.name, member, self.name))
#raise Exception("Member ",str(self.alias.members[index])," of ", str(self.alias.name)," is different than core member ", str(member)," in ", str(self.name),".")
def __repr__ (self):
return '%s (%s)' % (self.name, self.alias)
class Function:
TYPE_PLATFORM = 0 # Not bound to anything
TYPE_INSTANCE = 1 # Bound to VkInstance
TYPE_DEVICE = 2 # Bound to VkDevice
def __init__ (self, name, returnType, arguments, apiVersion = None):
self.name = name
self.returnType = returnType
self.arguments = arguments
self.alias = None
self.isAlias = False
self.apiVersion = apiVersion
def getType (self):
# Special functions
if self.name == "vkGetInstanceProcAddr":
return Function.TYPE_PLATFORM
assert len(self.arguments) > 0
firstArgType = self.arguments[0].getType()
if firstArgType in ["VkInstance", "VkPhysicalDevice"]:
return Function.TYPE_INSTANCE
elif firstArgType in ["VkDevice", "VkCommandBuffer", "VkQueue"]:
return Function.TYPE_DEVICE
else:
return Function.TYPE_PLATFORM
def checkAliasValidity (self):
if self.alias != None:
if len(self.arguments) != len(self.alias.arguments):
raise Exception("%s has different number of arguments than its alias %s." % (self.name, self.alias.name))
if self.returnType != self.alias.returnType or not (self.returnType.startswith(self.alias.returnType) or self.alias.returnType.startswith(self.returnType)):
raise Exception("%s has different return value's type than its alias %s." % (self.name, self.alias.name))
for index, argument in enumerate(self.arguments):
if argument != self.alias.arguments[index]:
raise Exception("argument %s: \"%s\" of %s is different than \"%s\" of %s." % (index, self.alias.arguments[index].getAsString(' '), self.alias.name, argument.getAsString(' '), self.name))
def __repr__ (self):
return '%s (%s)' % (self.name, self.alias)
class Extension:
def __init__ (self, name, handles, enums, bitfields, compositeTypes, functions, definitions, additionalDefinitions, typedefs, versionInCore):
self.name = name
self.definitions = definitions
self.additionalDefs = additionalDefinitions
self.handles = handles
self.enums = enums
self.bitfields = bitfields
self.compositeTypes = compositeTypes
self.functions = functions
self.typedefs = typedefs
self.versionInCore = versionInCore
def __repr__ (self):
return 'EXT:\n%s ->\nENUMS:\n%s\nCOMPOS:\n%s\nFUNCS:\n%s\nBITF:\n%s\nHAND:\n%s\nDEFS:\n%s\n' % (self.name, self.enums, self.compositeTypes, self.functions, self.bitfields, self.handles, self.definitions, self.versionInCore)
class API:
def __init__ (self, versions, definitions, handles, enums, bitfields, bitfields64, compositeTypes, functions, extensions, additionalExtensionData):
self.versions = versions
self.definitions = definitions
self.handles = handles
self.enums = enums
self.bitfields = bitfields
self.bitfields64 = bitfields64
self.compositeTypes = compositeTypes
self.functions = functions # \note contains extension functions as well
self.extensions = extensions
self.additionalExtensionData = additionalExtensionData # \note contains mandatory features and information about promotion
def readFile (filename):
with open(filename, 'rt') as f:
return f.read()
IDENT_PTRN = r'[a-zA-Z_][a-zA-Z0-9_]*'
WIDTH_PTRN = r'[:0-9]*'
TYPE_PTRN = r'[a-zA-Z_][a-zA-Z0-9_ \t*&]*'
def getInterfaceName (function):
assert function.name[:2] == "vk"
return function.name[2].lower() + function.name[3:]
def getFunctionTypeName (function):
assert function.name[:2] == "vk"
return function.name[2:] + "Func"
def endsWith (str, postfix):
return str[-len(postfix):] == postfix
def splitNameExtPostfix (name):
knownExtPostfixes = EXTENSION_POSTFIXES
for postfix in knownExtPostfixes:
if endsWith(name, postfix):
return (name[:-len(postfix)], postfix)
return (name, "")
def getBitEnumNameForBitfield (bitfieldName):
bitfieldName, postfix = splitNameExtPostfix(bitfieldName)
assert bitfieldName[-1] == "s"
return bitfieldName[:-1] + "Bits" + postfix
def getBitfieldNameForBitEnum (bitEnumName):
bitEnumName, postfix = splitNameExtPostfix(bitEnumName)
assert bitEnumName[-4:] == "Bits"
return bitEnumName[:-4] + "s" + postfix
def parsePreprocDefinedValue (src, name):
value = parsePreprocDefinedValueOptional(src, name)
if value is None:
raise Exception("No such definition: %s" % name)
return value
def parsePreprocDefinedValueOptional (src, name):
definition = re.search(r'#\s*define\s+' + name + r'\s+([^\n]+)\n', src)
if definition is None:
return None
value = definition.group(1).strip()
if value == "UINT32_MAX":
value = "(~0u)"
return value
def parseEnum (name, src):
keyValuePtrn = '(' + IDENT_PTRN + r')\s*=\s*([^\s,\n}]+)\s*[,\n}]'
return Enum(name, re.findall(keyValuePtrn, src))
# \note Parses raw enums, some are mapped to bitfields later
def parseEnums (src):
matches = re.findall(r'typedef enum(\s*' + IDENT_PTRN + r')?\s*{([^}]*)}\s*(' + IDENT_PTRN + r')\s*;', src)
enums = []
for enumname, contents, typename in matches:
enums.append(parseEnum(typename, contents))
return enums
def parseCompositeType (type, name, src):
typeNamePtrn = r'(' + TYPE_PTRN + r')(\s+' + IDENT_PTRN + r')((\[[^\]]+\]|\s*:\s*[0-9]+)*)\s*;'
matches = re.findall(typeNamePtrn, src)
members = [Variable(t.strip(), n.strip(), a.replace(' ', '')) for t, n, a, _ in matches]
return CompositeType(type, name, members)
def parseCompositeTypes (src):
typeMap = { 'struct': CompositeType.CLASS_STRUCT, 'union': CompositeType.CLASS_UNION }
matches = re.findall(r'typedef (struct|union)(\s*' + IDENT_PTRN + r')?\s*{([^}]*)}\s*(' + IDENT_PTRN + r')\s*;', src)
types = []
for type, structname, contents, typename in matches:
types.append(parseCompositeType(typeMap[type], typename, contents))
return types
def parseCompositeTypesByVersion (src, versionsData):
# find occurence of extension is a place where
# we cant assign apiVersion to found structures
extPtrn = r'#define\s+[A-Z0-9_]+_EXTENSION_NAME\s+"([^"]+)"'
versionEnd = re.search(extPtrn, src)
versions = [Version((v[2], v[3], v[4], 0)) for v in versionsData]
versions.append(None)
# construct list of locations where version definitions start, and add the end of the file to it
sectionLocations = [versionDef[1] for versionDef in versionsData]
sectionLocations.append(versionEnd.start())
sectionLocations.append(len(src))
# construct function declaration pattern
ptrn = r'typedef (struct|union)(\s*' + IDENT_PTRN + r')?\s*{([^}]*)}\s*(' + IDENT_PTRN + r')\s*;'
regPtrn = re.compile(ptrn)
types = []
typeMap = { 'struct': CompositeType.CLASS_STRUCT, 'union': CompositeType.CLASS_UNION }
# iterate over all versions and find all structure definitions
for index, v in enumerate(versions):
matches = regPtrn.findall(src, sectionLocations[index], sectionLocations[index+1])
for type, structname, contents, typename in matches:
compositeType = parseCompositeType(typeMap[type], typename, contents)
compositeType.apiVersion = v
types.append(compositeType)
return types
def parseVersions (src):
# returns list of tuples each with four items:
# 1. string with version token (without ' 1' at the end)
# 2. starting point off version specific definitions in vulkan.h.in
# 3. major version number
# 4. minor version number
return [(m.group()[:-2], m.start(), getApiVariantIndexByName(m.group(1)), int(m.group(2)), int(m.group(3))) for m in re.finditer('VK(SC)?_VERSION_([1-9])_([0-9]) 1', src)]
def parseHandles (src):
matches = re.findall(r'VK_DEFINE(_NON_DISPATCHABLE|)_HANDLE\((' + IDENT_PTRN + r')\)[ \t]*[\n\r]', src)
handles = []
typeMap = {'': Handle.TYPE_DISP, '_NON_DISPATCHABLE': Handle.TYPE_NONDISP}
for type, name in matches:
handle = Handle(typeMap[type], name)
handles.append(handle)
return handles
def parseArgList (src):
typeNamePtrn = r'(' + TYPE_PTRN + r')(\s+' + IDENT_PTRN + r')((\[[^\]]+\])*)\s*'
args = []
for rawArg in src.split(','):
m = re.search(typeNamePtrn, rawArg)
args.append(Variable(m.group(1).strip(), m.group(2).strip(), m.group(3)))
return args
def removeTypeExtPostfix (name):
for extPostfix in EXTENSION_POSTFIXES_STANDARD:
if endsWith(name, extPostfix):
return name[0:-len(extPostfix)]
return None
def populateExtensionAliases(allObjects, extensionObjects):
for object in extensionObjects:
withoutPostfix = removeTypeExtPostfix(object.name)
if withoutPostfix != None and withoutPostfix in allObjects:
# max 1 alias is assumed by functions in this file
assert allObjects[withoutPostfix].alias == None
allObjects[withoutPostfix].alias = object
object.isAlias = True
for object in extensionObjects:
object.checkAliasValidity()
def populateAliasesWithTypedefs (objects, src):
objectsByName = {}
for object in objects:
objectsByName[object.name] = object
ptrn = r'\s*typedef\s+' + object.name + r'\s+([^;]+)'
stash = re.findall(ptrn, src)
if len(stash) == 1:
objExt = copy.deepcopy(object)
objExt.name = stash[0]
object.alias = objExt
objExt.isAlias = True
objects.append(objExt)
def removeAliasedValues (enum):
valueByName = {}
for name, value in enum.values:
valueByName[name] = value
def removeDefExtPostfix (name):
for extPostfix in EXTENSION_POSTFIXES:
if endsWith(name, "_" + extPostfix):
return name[0:-(len(extPostfix)+1)]
return None
newValues = []
for name, value in enum.values:
withoutPostfix = removeDefExtPostfix(name)
if withoutPostfix != None and withoutPostfix in valueByName and valueByName[withoutPostfix] == value:
continue
newValues.append((name, value))
enum.values = newValues
def parseFunctions (src):
ptrn = r'VKAPI_ATTR\s+(' + TYPE_PTRN + ')\s+VKAPI_CALL\s+(' + IDENT_PTRN + r')\s*\(([^)]*)\)\s*;'
matches = re.findall(ptrn, src)
functions = []
for returnType, name, argList in matches:
functions.append(Function(name.strip(), returnType.strip(), parseArgList(argList)))
return functions
def parseFunctionsByVersion (src, versions):
# construct list of locations where version definitions start, and add the end of the file to it
sectionLocations = [versionDef[1] for versionDef in versions]
sectionLocations.append(len(src))
# construct function declaration pattern
ptrn = r'VKAPI_ATTR\s+(' + TYPE_PTRN + ')\s+VKAPI_CALL\s+(' + IDENT_PTRN + r')\s*\(([^)]*)\)\s*;'
regPtrn = re.compile(ptrn)
functions = []
# iterate over all versions and find all function definitions
for index, v in enumerate(versions):
matches = regPtrn.findall(src, sectionLocations[index], sectionLocations[index+1])
for returnType, name, argList in matches:
functions.append(Function(name.strip(), returnType.strip(), parseArgList(argList), v[0]))
return functions
def splitByExtension (src):
ptrn = r'#define\s+[A-Z0-9_]+_EXTENSION_NAME\s+"([^"]+)"'
# Construct long pattern that will be used to split whole source by extensions
match = "#define\s+("
for part in re.finditer(ptrn, src):
match += part.group(1)+"|"
match = match[:-1] + ")\s+1"
parts = re.split(match, src)
# First part is core, following tuples contain extension name and all its definitions
byExtension = [(None, parts[0])]
for ndx in range(1, len(parts), 2):
byExtension.append((parts[ndx], parts[ndx+1]))
return byExtension
def parseDefinitions (extensionName, src):
def skipDefinition (extensionName, definition):
if extensionName == None:
return True
extNameUpper = extensionName.upper()
extNameUpper = extNameUpper.replace("VK_KHR_SYNCHRONIZATION2", "VK_KHR_SYNCHRONIZATION_2")
extNameUpper = extNameUpper.replace("VK_INTEL_SHADER_INTEGER_FUNCTIONS2", "VK_INTEL_SHADER_INTEGER_FUNCTIONS_2")
extNameUpper = extNameUpper.replace("VK_EXT_ROBUSTNESS2", "VK_EXT_ROBUSTNESS_2")
extNameUpper = extNameUpper.replace("VK_EXT_FRAGMENT_DENSITY_MAP2", "VK_EXT_FRAGMENT_DENSITY_MAP_2")
extNameUpper = extNameUpper.replace("VK_EXT_SHADER_ATOMIC_FLOAT2", "VK_EXT_SHADER_ATOMIC_FLOAT_2")
extNameUpper = extNameUpper.replace("VK_AMD_SHADER_CORE_PROPERTIES2", "VK_AMD_SHADER_CORE_PROPERTIES_2")
extNameUpper = extNameUpper.replace("VK_EXT_EXTENDED_DYNAMIC_STATE2", "VK_EXT_EXTENDED_DYNAMIC_STATE_2")
# SPEC_VERSION enums
if definition[0].startswith(extNameUpper) and definition[1].isdigit():
return False
if definition[0].startswith(extNameUpper):
return True
if definition[0].endswith("_H_"):
return True
return False
ptrn = r'#define\s+([^\s]+)\s+([^\r\n]+)'
matches = re.findall(ptrn, src)
return [Definition(None, match[0], match[1]) for match in matches if not skipDefinition(extensionName, match)]
def parseTypedefs (src):
ptrn = r'typedef\s+([^\s]+)\s+([^\r\n]+);'
matches = re.findall(ptrn, src)
return [Definition(None, match[0], match[1]) for match in matches]
def parseExtensions (src, versions, allFunctions, allCompositeTypes, allEnums, allBitfields, allHandles, allDefinitions, additionalExtensionData):
# note registeredExtensionDict is also executed for vulkan 1.0 source for which extension name is None
registeredExtensionDict = {None: None}
for extensionName, data in additionalExtensionData:
# make sure that this extension was registered
if 'register_extension' not in data.keys():
continue
# save array containing 'device' or 'instance' string followed by the optional vulkan version in which this extension is core;
# note that register_extension section is also required for partialy promoted extensions like VK_EXT_extended_dynamic_state2
# but those extensions should not fill 'core' tag
registeredExtensionDict[extensionName] = [ data['register_extension']['type'] ]
match = re.match("(\d).(\d).(\d).(\d)", data['register_extension']['core'])
if match != None:
registeredExtensionDict[extensionName].extend( [ int(match.group(1)), int(match.group(2)), int(match.group(3)), int(match.group(4)) ] )
splitSrc = splitByExtension(src)
extensions = []
functionsByName = {function.name: function for function in allFunctions}
compositeTypesByName = {compType.name: compType for compType in allCompositeTypes}
enumsByName = {enum.name: enum for enum in allEnums}
bitfieldsByName = {bitfield.name: bitfield for bitfield in allBitfields}
handlesByName = {handle.name: handle for handle in allHandles}
definitionsByName = {definition.name: definition for definition in allDefinitions}
for extensionName, extensionSrc in splitSrc:
definitions = [Definition("uint32_t", v.getInHex(), parsePreprocDefinedValueOptional(extensionSrc, v.getInHex())) for v in versions]
definitions.extend([Definition(type, name, parsePreprocDefinedValueOptional(extensionSrc, name)) for name, type in DEFINITIONS])
definitions = [definition for definition in definitions if definition.value != None]
additionalDefinitions = parseDefinitions(extensionName, extensionSrc)
handles = parseHandles(extensionSrc)
functions = parseFunctions(extensionSrc)
compositeTypes = parseCompositeTypes(extensionSrc)
rawEnums = parseEnums(extensionSrc)
bitfieldNames = parse32bitBitfieldNames(extensionSrc)
typedefs = parseTypedefs(extensionSrc)
enumBitfieldNames = [getBitEnumNameForBitfield(name) for name in bitfieldNames]
enums = [enum for enum in rawEnums if enum.name not in enumBitfieldNames]
extCoreVersion = None
extData = registeredExtensionDict.get(extensionName, None)
extFunctions = [functionsByName[function.name] for function in functions]
extCompositeTypes = [compositeTypesByName[compositeType.name] for compositeType in compositeTypes]
extEnums = [enumsByName[enum.name] for enum in enums]
extBitfields = [bitfieldsByName[bitfieldName] for bitfieldName in bitfieldNames]
extHandles = [handlesByName[handle.name] for handle in handles]
extDefinitions = [definitionsByName[definition.name] for definition in definitions]
if extData != None:
populateExtensionAliases(functionsByName, extFunctions)
populateExtensionAliases(handlesByName, extHandles)
populateExtensionAliases(enumsByName, extEnums)
populateExtensionAliases(bitfieldsByName, extBitfields)
populateExtensionAliases(compositeTypesByName, extCompositeTypes)
if len(extData) > 1:
extCoreVersion = extData
extensions.append(Extension(extensionName, extHandles, extEnums, extBitfields, extCompositeTypes, extFunctions, extDefinitions, additionalDefinitions, typedefs, extCoreVersion))
return extensions
def parse32bitBitfieldNames (src):
ptrn = r'typedef\s+VkFlags\s(' + IDENT_PTRN + r')\s*;'
matches = re.findall(ptrn, src)
return matches
def parse64bitBitfieldNames (src):
ptrn = r'typedef\s+VkFlags64\s(' + IDENT_PTRN + r')\s*;'
matches = re.findall(ptrn, src)
return matches
def parse64bitBitfieldValues (src, bitfieldNamesList):
bitfields64 = []
for bitfieldName in bitfieldNamesList:
ptrn = r'static const ' + bitfieldName + r'\s*(' + IDENT_PTRN + r')\s*=\s*([a-zA-Z0-9_]+)\s*;'
matches = re.findall(ptrn, src)
bitfields64.append(Bitfield(bitfieldName, matches))
return bitfields64
def parseAPI (src):
versionsData = parseVersions(src)
versions = [Version((v[2], v[3], v[4], 0)) for v in versionsData]
definitions = [Definition("uint32_t", v.getInHex(), parsePreprocDefinedValue(src, v.getInHex())) for v in versions] +\
[Definition(type, name, parsePreprocDefinedValue(src, name)) for name, type in DEFINITIONS]
handles = parseHandles(src)
rawEnums = parseEnums(src)
bitfieldNames = parse32bitBitfieldNames(src)
bitfieldEnums = set([getBitEnumNameForBitfield(n) for n in bitfieldNames if getBitEnumNameForBitfield(n) in [enum.name for enum in rawEnums]])
bitfield64Names = parse64bitBitfieldNames(src)
bitfields64 = parse64bitBitfieldValues(src, bitfield64Names)
enums = []
bitfields = []
compositeTypes = parseCompositeTypesByVersion(src, versionsData)
allFunctions = parseFunctionsByVersion(src, versionsData)
additionalExtensionData = {}
# read all files from extensions directory
for fileName in glob.glob(os.path.join(SCRIPTS_SRC_DIR, "extensions", "*.json")):
extensionName = os.path.basename(fileName)[:-5]
fileContent = readFile(fileName)
try:
additionalExtensionData[extensionName] = json.loads(fileContent)
except ValueError as err:
print("Error in %s: %s" % (os.path.basename(fileName), str(err)))
sys.exit(-1)
additionalExtensionData = sorted(additionalExtensionData.items(), key=lambda e: e[0])
for enum in rawEnums:
if enum.name in bitfieldEnums:
bitfields.append(Bitfield(getBitfieldNameForBitEnum(enum.name), enum.values))
else:
enums.append(enum)
for bitfieldName in bitfieldNames:
if not bitfieldName in [bitfield.name for bitfield in bitfields]:
# Add empty bitfield
bitfields.append(Bitfield(bitfieldName, []))
extensions = parseExtensions(src, versions, allFunctions, compositeTypes, enums, bitfields, handles, definitions, additionalExtensionData)
# Populate alias fields
populateAliasesWithTypedefs(compositeTypes, src)
populateAliasesWithTypedefs(enums, src)
populateAliasesWithTypedefs(bitfields, src)
populateAliasesWithTypedefs(bitfields64, src)
populateAliasesWithTypedefs(handles, src)
for enum in enums:
removeAliasedValues(enum)
# Make generator to create Deleter<VkAccelerationStructureNV>
for f in allFunctions:
if (f.name == 'vkDestroyAccelerationStructureNV'):
f.arguments[1].type[0] = 'VkAccelerationStructureNV'
# Dealias handles VkAccelerationStructureNV and VkAccelerationStructureKHR
for handle in handles:
if handle.name == 'VkAccelerationStructureKHR':
handle.alias = None
if handle.name == 'VkAccelerationStructureNV':
handle.isAlias = False
return API(
versions = versions,
definitions = definitions,
handles = handles,
enums = enums,
bitfields = bitfields,
bitfields64 = bitfields64,
compositeTypes = compositeTypes,
functions = allFunctions,
extensions = extensions,
additionalExtensionData = additionalExtensionData)
def splitUniqueAndDuplicatedEntries (handles):
listOfUniqueHandles = []
duplicates = OrderedDict()
for handle in handles:
if handle.alias != None:
duplicates[handle.alias] = handle
if not handle.isAlias:
listOfUniqueHandles.append(handle)
return listOfUniqueHandles, duplicates
def writeHandleType (api, filename):
uniqeHandles, duplicatedHandles = splitUniqueAndDuplicatedEntries(api.handles)
def genHandles ():
yield "\t%s\t= 0," % uniqeHandles[0].getHandleType()
for handle in uniqeHandles[1:]:
yield "\t%s," % handle.getHandleType()
for duplicate in duplicatedHandles:
yield "\t%s\t= %s," % (duplicate.getHandleType(), duplicatedHandles[duplicate].getHandleType())
yield "\tHANDLE_TYPE_LAST\t= %s + 1" % (uniqeHandles[-1].getHandleType())
def genHandlesBlock ():
yield "enum HandleType"
yield "{"
for line in indentLines(genHandles()):
yield line
yield "};"
yield ""
writeInlFile(filename, INL_HEADER, genHandlesBlock())
def getEnumValuePrefix (enum):
prefix = enum.name[0]
for i in range(1, len(enum.name)):
if enum.name[i].isupper() and not enum.name[i-1].isupper():
prefix += "_"
prefix += enum.name[i].upper()
return prefix
def parseInt (value):
if value[:2] == "0x":
return int(value, 16)
else:
return int(value, 10)
def areEnumValuesLinear (enum):
curIndex = 0
maxIntCount = 0
for name, value in enum.values:
if value[:2] != "VK":
intValue = parseInt(value)
if intValue != curIndex:
# enum is linear when all items are in order
if intValue != 0x7FFFFFFF:
return False
# count number of items with 0x7FFFFFFF value;
# enum containing single 0x7FFFFFFF item are also
# considered as linear (this is usualy *_MAX_ENUM item)
maxIntCount += 1
# enums containing more then one 0x7FFFFFFF value
# are not considered as linear (vulkan video enums)
if maxIntCount > 1:
return False
curIndex += 1
return True
def genEnumSrc (enum):
yield "enum %s" % enum.name
yield "{"
lines = []
if areEnumValuesLinear(enum):
hasMaxItem = parseInt(enum.values[-1][1]) == 0x7FFFFFFF
values = enum.values[:-1] if hasMaxItem else enum.values
lastItem = "\t%s_LAST," % getEnumValuePrefix(enum)
# linear values first, followed by *_LAST
lines += ["\t%s\t= %s," % v for v in values if v[1][:2] != "VK"]
lines.append(lastItem)
# equivalence enums and *_MAX_ENUM
lines += ["\t%s\t= %s," % v for v in values if v[1][:2] == "VK"]
if hasMaxItem:
lines.append("\t%s\t= %s," % enum.values[-1])
else:
lines += ["\t%s\t= %s," % v for v in enum.values]
for line in indentLines(lines):
yield line
yield "};"
def genBitfieldSrc (bitfield):
if len(bitfield.values) > 0:
yield "enum %s" % getBitEnumNameForBitfield(bitfield.name)
yield "{"
for line in indentLines(["\t%s\t= %s," % v for v in bitfield.values]):
yield line
yield "};"
yield "typedef uint32_t %s;" % bitfield.name
def genBitfield64Src (bitfield64):
yield "typedef uint64_t %s;" % bitfield64.name
if len(bitfield64.values) > 0:
ptrn = "static const " + bitfield64.name + " %s\t= %s;"
for line in indentLines([ptrn % v for v in bitfield64.values]):
yield line
yield ""
def genCompositeTypeSrc (type):
yield "%s %s" % (type.getClassName(), type.name)
yield "{"
for line in indentLines(['\t'+m.getAsString('\t')+';' for m in type.members]):
yield line
yield "};"
def genHandlesSrc (handles):
uniqeHandles, duplicatedHandles = splitUniqueAndDuplicatedEntries(handles)
def genLines (handles):
for handle in uniqeHandles:
if handle.type == Handle.TYPE_DISP:
yield "VK_DEFINE_HANDLE\t(%s,\t%s);" % (handle.name, handle.getHandleType())
elif handle.type == Handle.TYPE_NONDISP:
yield "VK_DEFINE_NON_DISPATCHABLE_HANDLE\t(%s,\t%s);" % (handle.name, handle.getHandleType())
for duplicate in duplicatedHandles:
if duplicate.type == Handle.TYPE_DISP:
yield "VK_DEFINE_HANDLE\t(%s,\t%s);" % (duplicate.name, duplicatedHandles[duplicate].getHandleType())
elif duplicate.type == Handle.TYPE_NONDISP:
yield "VK_DEFINE_NON_DISPATCHABLE_HANDLE\t(%s,\t%s);" % (duplicate.name, duplicatedHandles[duplicate].getHandleType())
for line in indentLines(genLines(handles)):
yield line