The generated offsets/sizes were wrong on the 64-bit ABI because of three registry-parsing bugs, which silently broke any struct carrying a handle (swapchain, render pass, framebuffers, ...): - handles: their name lives in a child <name> element, not a `name` attribute (e.g. <type category="handle"><type>VK_DEFINE_HANDLE</type> (<name>VkInstance</name>)</type>), so every handle fell through to the 4-byte default. Read the child element; handles are 8-byte pointers again (VkSwapchainCreateInfoKHR.surface @24, not @20). - duplicated members: vk.xml lists some members once per API variant (api="vulkan" and api="vulkansc"); keep only the default Vulkan ones, else the field is emitted twice and inflates the struct size. - constants: emit bitflags from `bitpos`, extension enums from `offset`+extension `number` (sTypes like ..._SWAPCHAIN_CREATE_INFO_KHR = 1000001000), SPEC_VERSION numerics and EXTENSION_NAME strings from inside <require>, and resolve aliases. Verified against the system Vulkan header: 37 struct sizes/offsets checked, 0 mismatches; suite still 130 green.
369 lines
13 KiB
Python
369 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate std/vulkan/vulkan.cat from the official vk.xml registry.
|
|
|
|
Usage: gen_vulkan.py <vk.xml> [libvulkan.so] > vulkan.cat
|
|
|
|
The output is a catscript module that, on import, ffi::load()s libvulkan
|
|
and binds the Vulkan 1.0 core commands with snake_case names, plus
|
|
struct sizes (for `memory(size)`) and per-struct field offsets, so a
|
|
caller can build and read structs safely through a `memory` buffer.
|
|
"""
|
|
import re
|
|
import sys
|
|
import xml.etree.ElementTree as ET
|
|
|
|
SCALARS = {
|
|
'void': 'void',
|
|
'float': 'float', 'double': 'double',
|
|
'int32_t': 'int', 'uint32_t': 'uint32',
|
|
'int64_t': 'int64', 'uint64_t': 'uint64',
|
|
'int16_t': 'int16', 'uint16_t': 'uint16',
|
|
'int8_t': 'int8', 'uint8_t': 'uint8',
|
|
'size_t': 'uint64', 'char': 'int8',
|
|
'VkBool32': 'uint32', 'VkFlags': 'uint32',
|
|
'VkDeviceSize': 'uint64', 'VkSampleMask': 'uint32',
|
|
'int': 'int', 'unsigned': 'uint32', 'long': 'long',
|
|
}
|
|
|
|
|
|
def snake(name):
|
|
"""vkCreateInstance -> create_instance (vk prefix dropped)."""
|
|
if name.startswith('vk'):
|
|
name = name[2:]
|
|
s = re.sub(r'(?<=[a-z0-9])([A-Z])', r'_\1', name)
|
|
s = re.sub(r'(?<=[A-Z])([A-Z][a-z])', r'_\1', s)
|
|
return s.lstrip('_').lower()
|
|
|
|
|
|
def const_name(name):
|
|
"""VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO -> structure_type_instance_create_info"""
|
|
return name[3:].lower() if name.startswith('VK_') else name.lower()
|
|
|
|
|
|
def align(n, a):
|
|
return (n + a - 1) & ~(a - 1)
|
|
|
|
|
|
C_ALIGN = {
|
|
'int8_t': 1, 'uint8_t': 1, 'char': 1,
|
|
'int16_t': 2, 'uint16_t': 2,
|
|
'int32_t': 4, 'uint32_t': 4, 'float': 4, 'VkBool32': 4, 'VkFlags': 4,
|
|
'VkSampleMask': 4,
|
|
'int64_t': 8, 'uint64_t': 8, 'double': 8, 'VkDeviceSize': 8,
|
|
'size_t': 8,
|
|
}
|
|
C_SIZE = dict(C_ALIGN)
|
|
|
|
|
|
class Layout:
|
|
"""x86-64 sizes/offsets for Vulkan structs and unions.
|
|
|
|
Sizes are resolved recursively and memoized, so a struct that
|
|
embeds another by value gets the real nested size and alignment.
|
|
"""
|
|
|
|
def __init__(self, root):
|
|
self.structs = {}
|
|
self.is_union = {}
|
|
self.enums = set()
|
|
self.bitmasks = set()
|
|
self.handles = set()
|
|
self.funcptrs = set()
|
|
self.constants = {} # VK_MAX_* -> int
|
|
self._size = {}
|
|
self._align = {}
|
|
self._fields = {}
|
|
for t in root.find('types'):
|
|
cat = t.get('category')
|
|
nm = t.get('name')
|
|
if nm is None:
|
|
# Handles (and some other types) carry their name in a
|
|
# child <name> element, not a `name` attribute:
|
|
# <type category="handle"><type>VK_DEFINE_HANDLE</type>(<name>VkInstance</name>)</type>
|
|
child = t.find('name')
|
|
if child is not None and child.text:
|
|
nm = child.text.strip()
|
|
if not nm:
|
|
continue
|
|
if cat in ('struct', 'union'):
|
|
self.structs[nm] = t
|
|
self.is_union[nm] = (cat == 'union')
|
|
elif cat == 'enum':
|
|
self.enums.add(nm)
|
|
elif cat == 'bitmask':
|
|
self.bitmasks.add(nm)
|
|
elif cat == 'handle':
|
|
self.handles.add(nm)
|
|
elif cat == 'funcpointer':
|
|
self.funcptrs.add(nm)
|
|
# numeric constants (array sizes like VK_MAX_PHYSICAL_DEVICE_NAME_SIZE)
|
|
for enums in root.findall('enums'):
|
|
if enums.get('type') != 'constants' and enums.get('name') != 'API Constants':
|
|
continue
|
|
for e in enums.findall('enum'):
|
|
nm, val = e.get('name'), e.get('value')
|
|
if nm and val and re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', val):
|
|
self.constants[nm] = int(val, 0)
|
|
|
|
@staticmethod
|
|
def _member_ctype(m):
|
|
mt = m.find('type')
|
|
if mt is None:
|
|
return None, 0
|
|
lead = (m.text or '').strip()
|
|
tail = (mt.tail or '').strip()
|
|
name_el = m.find('name')
|
|
name_tail = (name_el.tail or '').strip() if name_el is not None else ''
|
|
ctype = ('%s %s %s' % (lead, mt.text, tail)).strip()
|
|
am = re.search(r'\[\s*([A-Za-z0-9_]+)\s*\]', name_tail)
|
|
if am:
|
|
return ctype, am.group(1)
|
|
if name_el is not None:
|
|
enum_el = m.find('enum')
|
|
if enum_el is not None and enum_el.text:
|
|
return ctype, enum_el.text.strip()
|
|
return ctype, None
|
|
|
|
def _array_len(self, expr):
|
|
"""An array length is a literal, a macro, or a `NAME` len attr."""
|
|
if expr is None:
|
|
return 0
|
|
if re.fullmatch(r'\d+', expr):
|
|
return int(expr)
|
|
if expr in self.constants:
|
|
return self.constants[expr]
|
|
return 0
|
|
|
|
def scalar_info(self, base):
|
|
if base in C_SIZE:
|
|
n = C_SIZE[base]
|
|
return n, C_ALIGN[base], ('f32' if base == 'float'
|
|
else 'u%d' % (n * 8))
|
|
if base in self.enums or base in self.bitmasks:
|
|
return 4, 4, 'u32'
|
|
if base in self.handles or base in self.funcptrs:
|
|
return 8, 8, 'ptr'
|
|
if base == 'void':
|
|
return 1, 1, 'u8'
|
|
return None
|
|
|
|
def size(self, name):
|
|
if name in self._size:
|
|
return self._size[name], self._align[name]
|
|
self._compute(name, set())
|
|
return self._size.get(name, 4), self._align.get(name, 4)
|
|
|
|
def _compute(self, name, seen):
|
|
if name in self._size:
|
|
return
|
|
if name in seen or name not in self.structs:
|
|
self._size[name], self._align[name] = 4, 4
|
|
self._fields[name] = []
|
|
return
|
|
seen = seen | {name}
|
|
t = self.structs[name]
|
|
is_union = self.is_union.get(name, False)
|
|
off, maxa, fields = 0, 1, []
|
|
for m in t.findall('member'):
|
|
# vk.xml lists some members twice, once per API variant
|
|
# (e.g. api="vulkan" and api="vulkansc"); keep only the
|
|
# default Vulkan ones, else the field is counted twice.
|
|
api = m.get('api')
|
|
if api is not None and api != 'vulkan':
|
|
continue
|
|
mn = m.find('name')
|
|
if mn is None:
|
|
continue
|
|
ctype, alen = self._member_ctype(m)
|
|
if ctype is None:
|
|
continue
|
|
# a `len="NAME"` attr names a macro-sized array
|
|
if alen is None:
|
|
alen = self._array_len(m.get('len'))
|
|
else:
|
|
alen = self._array_len(alen)
|
|
is_ptr = '*' in ctype
|
|
base = ctype.replace('const', '').replace('*', '').strip()
|
|
if is_ptr:
|
|
esize, ealign, ekind = 8, 8, 'ptr'
|
|
else:
|
|
info = self.scalar_info(base)
|
|
if info is not None:
|
|
esize, ealign, ekind = info
|
|
elif base in self.structs:
|
|
esize, ealign = self.size(base)
|
|
ekind = 'u8'
|
|
else:
|
|
esize, ealign, ekind = 4, 4, 'u32'
|
|
count = alen if alen else 1
|
|
total = esize * count
|
|
if is_union:
|
|
fields.append((mn.text, 0, total, ekind, count))
|
|
off = max(off, total)
|
|
else:
|
|
off = align(off, ealign)
|
|
fields.append((mn.text, off, total, ekind, count))
|
|
off += total
|
|
maxa = max(maxa, ealign)
|
|
self._size[name] = align(off, maxa)
|
|
self._align[name] = maxa
|
|
self._fields[name] = fields
|
|
|
|
def fields(self, name):
|
|
self.size(name)
|
|
return self._fields.get(name, [])
|
|
|
|
|
|
def ffi_type(ctype, lay):
|
|
"""Map a C type to an ffi signature type, using the registry's
|
|
knowledge of enums (4-byte ints) and handles (pointers)."""
|
|
t = re.sub(r'\s+', ' ', ctype.strip())
|
|
if t in SCALARS:
|
|
return SCALARS[t]
|
|
base = t.replace('const', '').replace('*', '').strip()
|
|
if '*' in t:
|
|
return 'ptr'
|
|
if base in lay.enums or base in lay.bitmasks:
|
|
return 'uint32'
|
|
if base in lay.handles or base in lay.funcptrs:
|
|
return 'ptr'
|
|
if base in lay.structs:
|
|
return 'ptr'
|
|
if base.startswith('Vk') or base.startswith('PFN_'):
|
|
return 'ptr'
|
|
return 'int'
|
|
|
|
|
|
def main():
|
|
xml_path = sys.argv[1]
|
|
lib = sys.argv[2] if len(sys.argv) > 2 else 'libvulkan.so.1'
|
|
root = ET.parse(xml_path).getroot()
|
|
|
|
struct_types = {t.get('name') for t in root.find('types')
|
|
if t.get('category') in ('struct', 'union') and t.get('name')}
|
|
lay = Layout(root)
|
|
|
|
commands = []
|
|
for c in root.find('commands'):
|
|
proto = c.find('proto')
|
|
if proto is None:
|
|
continue
|
|
ret_el, name_el = proto.find('type'), proto.find('name')
|
|
if ret_el is None or name_el is None:
|
|
continue
|
|
ret = ((ret_el.text or '') + ' ' + (ret_el.tail or '')).strip()
|
|
params = []
|
|
for p in c.findall('param'):
|
|
pt = p.find('type')
|
|
if pt is None:
|
|
continue
|
|
ptype = ((p.text or '') + ' ' + (pt.text or '') + ' '
|
|
+ (pt.tail or '')).strip()
|
|
params.append(ptype)
|
|
commands.append((name_el.text, ret, params))
|
|
|
|
out = sys.stdout
|
|
out.write("-- std/vulkan/vulkan.cat -- generated Vulkan bindings (snake_case).\n")
|
|
out.write("-- Generated by tools/gen_vulkan.py from the official vk.xml.\n")
|
|
out.write("--\n")
|
|
out.write("-- import it with: use vulkan\n")
|
|
out.write("-- Then: vulkan.create_instance(ci, 0, out), with structs built\n")
|
|
out.write("-- in a `memory(vulkan.size_vk_instance_create_info)` buffer.\n\n")
|
|
out.write("local _lib = ffi::load(%r)\n\n" % lib)
|
|
out.write("vulkan = {}\n")
|
|
out.write("vulkan.lib = _lib\n\n")
|
|
|
|
out.write("-- commands\n")
|
|
for name, ret, params in commands:
|
|
sig = "%s(%s)" % (ffi_type(ret, lay),
|
|
','.join(ffi_type(p, lay) for p in params))
|
|
out.write("vulkan.%s = _lib.func(%r, %r)\n" % (snake(name), name, sig))
|
|
out.write("\n")
|
|
|
|
out.write("-- struct sizes (allocate with memory(vulkan.size_<name>))\n")
|
|
names = sorted(n for n in lay.structs if n.startswith('Vk'))
|
|
for nm in names:
|
|
sz, _ = lay.size(nm)
|
|
out.write("vulkan.size_%s = %d\n" % (snake(nm), sz))
|
|
out.write("\n")
|
|
|
|
# ---- constant values ----
|
|
# Core enums carry `value`; bitflags carry `bitpos`; extension
|
|
# enums carry `offset` and are numbered off the extension's
|
|
# `number` (value = 1000000000 + (number-1)*1000 + offset).
|
|
consts = {}
|
|
|
|
def put(name, v):
|
|
if name not in consts:
|
|
consts[name] = v
|
|
|
|
for enums in root.findall('enums'):
|
|
for e in enums.findall('enum'):
|
|
nm, val, bit = e.get('name'), e.get('value'), e.get('bitpos')
|
|
if not nm:
|
|
continue
|
|
if val is not None and re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', val):
|
|
put(nm, int(val, 0))
|
|
elif bit is not None and re.fullmatch(r'\d+', bit):
|
|
put(nm, 1 << int(bit))
|
|
for ex in root.findall('extensions/extension'):
|
|
num = ex.get('number')
|
|
if not num or not num.isdigit():
|
|
continue
|
|
n = int(num)
|
|
for e in ex.iter('enum'):
|
|
nm, off = e.get('name'), e.get('offset')
|
|
if not nm:
|
|
continue
|
|
if off is not None and re.fullmatch(r'\d+', off):
|
|
v = 1000000000 + (n - 1) * 1000 + int(off)
|
|
if e.get('dir') == '-':
|
|
v = -v
|
|
put(nm, v)
|
|
elif e.get('value') is not None and \
|
|
re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', e.get('value')):
|
|
# numeric constants declared inside an extension <require>
|
|
# (e.g. VK_KHR_*_SPEC_VERSION)
|
|
put(nm, int(e.get('value'), 0))
|
|
# aliases resolve to their target's value once it is known
|
|
for _ in range(3):
|
|
for enums in root.iter('enums'):
|
|
for e in enums.findall('enum'):
|
|
nm, al = e.get('name'), e.get('alias')
|
|
if nm and al and nm not in consts and al in consts:
|
|
put(nm, consts[al])
|
|
|
|
out.write("-- constants\n")
|
|
for nm in sorted(consts):
|
|
if nm.startswith('VK_'):
|
|
out.write("vulkan.%s = %d\n" % (const_name(nm), consts[nm]))
|
|
# extension-name strings ("VK_KHR_swapchain", ...) live inside the
|
|
# extensions' <require> blocks, not the top-level <enums>.
|
|
for enums in root.iter('enums'):
|
|
for e in enums.findall('enum'):
|
|
nm, val = e.get('name'), e.get('value')
|
|
if nm and nm.startswith('VK_') and val and re.fullmatch(r'"[^"]*"', val):
|
|
out.write("vulkan.%s = %s\n" % (const_name(nm), val))
|
|
for ex in root.findall('extensions/extension'):
|
|
for e in ex.iter('enum'):
|
|
nm, val = e.get('name'), e.get('value')
|
|
if nm and nm.startswith('VK_') and val and re.fullmatch(r'"[^"]*"', val):
|
|
out.write("vulkan.%s = %s\n" % (const_name(nm), val))
|
|
out.write("\n")
|
|
|
|
out.write("-- struct field offsets\n")
|
|
for nm in names:
|
|
fields = lay.fields(nm)
|
|
out.write("vulkan.off_%s = {\n" % snake(nm))
|
|
for fname, foff, fsz, fkind, count in fields:
|
|
out.write(" { name = %r, o = %d, sz = %d, kind = %r },\n"
|
|
% (fname, foff, fsz, fkind))
|
|
out.write("}\n")
|
|
out.write("\nreturn vulkan\n")
|
|
sys.stderr.write("vulkan: %d commands, %d structs\n"
|
|
% (len(commands), len(names)))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|