Files
catscript/tools/gen_vulkan.py
T
Minus 6f6f444beb selectors: a.b sends with self, a::b without; drop a:b
The `.` and `::` selectors swap meaning and `a:b` is removed, so every
access is one of:

  a.b          read the member
  a.b(args)    call the member WITH a as self
  a::b         static read (no self)
  a::b(args)   call the member WITHOUT self

- compiler: postfix `.` emits CALLMETHOD (with self) when followed by
  `(`, else GETATTR; `::` emits GETATTR + CALL (no self); the `:` form
  is gone (with a helpful error suggesting `.`/`::`).
- `:` remains only for type hints (local x : int), unchanged.
- ffi: `lib.func(...)` (with self) and `ffi::load(...)` (no self); the
  native loaders no longer skip a receiver.
- file: `File::open` is static, so cm_open reads args[0]/args[1].
- lexer: fix cat_lexer_kind_name, whose table had drifted from the enum
  (missing `nil`), mislabelling tokens.
- self-hosted parser (std/lang/parser.cat): `.name(` -> method (self),
  `::name(` -> call (no self); compiler/checker unchanged.
- tools/migrate_selectors.py: one-pass migration of the call forms.
- regenerated std/glfw and std/vulkan; migrated examples/tests/std and
  the README; new tests/selectors.cat (130 green).

Verified live: GLFW window + Vulkan device still work; `a:b` now errors.
2026-11-17 18:55:18 +00:00

302 lines
10 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, nm = t.get('category'), t.get('name')
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'):
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")
# enum constants (VK_SUCCESS, VK_STRUCTURE_TYPE_*, VK_FORMAT_*, ...)
out.write("-- constants\n")
for enums in root.findall('enums'):
for e in enums.findall('enum'):
nm, val = e.get('name'), e.get('value')
if not nm or not val:
continue
if nm.startswith('VK_') and re.fullmatch(r'-?0x[0-9A-Fa-f]+|-?\d+', 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()