bindings: GLFW and Vulkan, generated with snake_case names

`use glfw` and `use vulkan` load the native libraries and expose every
function with a snake_case name, plus constants, struct sizes and field
offsets.  Generated from the official headers/registry, not hand-written:

- tools/gen_glfw.py: parses glfw3.h -> std/glfw/glfw.cat (124 fns +
  GLFW_* constants + GLFWvidmode/GLFWgammaramp offsets).
- tools/gen_vulkan.py: parses vk.xml -> std/vulkan/vulkan.cat (650
  commands + 1454 struct sizes/offsets + enum constants), with a
  recursive x86-64 layout engine that resolves nested structs and
  macro-sized arrays (sizes verified against the C headers).
- ffi: `memory` values pass their address where a pointer is expected;
  `ffi.pointer(addr, name, sig)` binds a call at a raw address (Vulkan
  dispatch).  `VkResult`/enum returns are ints.
- compiler: a keyword is allowed as a member name after `.` /
  method-call position (glfw.false, glfw.visible).
- vendor/lib/libglfw.so.3: the host has no libglfw, so it is vendored.

Proved live: GLFW 3.4 window + framebuffer under xvfb-run; a Vulkan
1.0 instance + physical-device enumeration on lavapipe (headless).
tests/glfw.cat, tests/vulkan.cat wired into the suite (125 green).
This commit is contained in:
Minus committed 2026-11-17 18:48:32 +00:00
1 parent 210054f46c
commit 04009c3c5e
18 files changed
+13539 -2

No files matched your search

Binary file not shown.
+164
View File
@@ -0,0 +1,164 @@
#!/usr/bin/env python3
"""Generate std/glfw/glfw.cat from the official GLFW header.
Usage: gen_glfw.py <glfw3.h> <libglfw.so path> > glfw.cat
The output is a catscript module that, on import, ffi::load()s libglfw
and binds every GLFWAPI function with a snake_case name, plus the
GLFW_* constants and the struct field offsets (GLFWvidmode,
GLFWgammaramp) so callers can read them out of a `memory` buffer.
"""
import re
import sys
# C type -> ffi signature type. `const char *` is an input string;
# `char *`/`void *`/any other pointer is an address (a `memory` buffer
# passes its address).
def ctype_to_ffi(t, is_return=False):
t = t.strip()
t = re.sub(r'\s+', ' ', t)
# strip 'const', keep track of it for char*
const = t.startswith('const ')
base = t[6:].strip() if const else t
base = base.replace(' *', '*').replace('* ', '*')
if base == 'void':
return 'void'
if base in ('char*',) or base == 'const char*':
return 'string' if (const or is_return) else 'ptr'
if '*' in base:
return 'ptr'
if base == 'float':
return 'float'
if base == 'double':
return 'double'
if base in ('int', 'GLFWbool'):
return 'int'
if base in ('unsigned int', 'unsigned'):
return 'uint32'
if base in ('unsigned char',):
return 'uint8'
if base in ('char',):
return 'int8'
if base in ('long long', 'int64_t'):
return 'int64'
if base in ('unsigned long long', 'uint64_t'):
return 'uint64'
return 'int'
def snake(name):
"""glfwCreateWindow -> create_window (the glfw_ prefix is the
module name, so drop it)."""
if name.startswith('glfw'):
name = name[4:]
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):
"""GLFW_VISIBLE -> visible (drop the GLFW_ prefix)."""
return name[5:].lower() if name.startswith('GLFW_') else name.lower()
def main():
header_path, lib_path = sys.argv[1], sys.argv[2]
src = open(header_path).read()
print("-- std/glfw/glfw.cat -- generated GLFW bindings (snake_case).")
print("-- Generated by tools/gen_glfw.py from the official glfw3.h.")
print("--")
print("-- import it with: use glfw")
print("-- Then call functions as `glfw.init()`, `glfw.create_window(...)`;")
print("-- constants and struct offsets live on `glfw` too (glfw.visible).")
print()
print("local _lib = ffi::load(%r)" % lib_path)
print()
print("glfw = {}")
print("glfw.lib = _lib")
print()
# ---- functions ----
# GLFWAPI <ret> <name>(<args>);
fn_re = re.compile(
r'GLFWAPI\s+([A-Za-z_][A-Za-z0-9_ \*]*?)\s+'
r'(glfw[A-Za-z0-9_]+)\s*\(([^;]*?)\)\s*;', re.S)
count = 0
seen = set()
for m in fn_re.finditer(src):
ret, name, args = m.group(1), m.group(2), m.group(3)
if name in seen:
continue
seen.add(name)
# parse args
arglist = []
args = args.strip()
if args and args != 'void':
for a in args.split(','):
a = a.strip()
# drop the parameter name (last identifier)
a = re.sub(r'[A-Za-z_][A-Za-z0-9_]*$', '', a).strip()
arglist.append(ctype_to_ffi(a))
ret_ffi = ctype_to_ffi(ret, is_return=True)
sig = "%s(%s)" % (ret_ffi, ','.join(arglist))
py_name = snake(name)
print("glfw.%s = _lib:func(%r, %r)" % (py_name, name, sig))
count += 1
print()
# ---- constants: #define GLFW_x value ----
const_re = re.compile(r'^#define\s+(GLFW_[A-Za-z0-9_]+)\s+'
r'(-?0x[0-9A-Fa-f]+|-?[0-9]+)\s*$', re.M)
print("-- constants")
for m in const_re.finditer(src):
key, val = m.group(1), m.group(2)
print("glfw.%s = %s" % (const_name(key), val))
print()
# ---- struct offsets (GLFWvidmode, GLFWgammaramp) ----
# Parse `typedef struct NAME { ... } NAME;`
struct_re = re.compile(r'typedef struct\s+(\w+)\s*\{(.*?)\}\s*\1\s*;', re.S)
uint = lambda n: 'u32'
for m in struct_re.finditer(src):
sname, body = m.group(1), m.group(2)
fields = []
off = 0
for line in body.split(';'):
line = line.strip()
if not line or line.startswith('/*'):
continue
# `int width;` or `const GLFWvidmode* modes;`
fm = re.match(r'(.+?)\s*\*?\s*(\w+)\s*$', line)
if not fm:
continue
ctype, fname = fm.group(1).strip(), fm.group(2)
is_ptr = '*' in line
if is_ptr:
fields.append((fname, off, 8, 'ptr'))
off += 8
elif 'float' in ctype:
fields.append((fname, off, 4, 'f32'))
off += 4
elif 'unsigned short' in ctype or 'short' in ctype:
fields.append((fname, off, 2, 'u16'))
off += 2
elif 'unsigned char' in ctype:
fields.append((fname, off, 1, 'u8'))
off += 1
else:
fields.append((fname, off, 4, 'u32'))
off += 4
if fields:
print("-- struct %s (%d bytes)" % (sname, off))
print("glfw.%s = {" % snake(sname))
for fname, foff, fsz, fkind in fields:
print(" { name = %r, offset = %d, size = %d, kind = %r },"
% (fname, foff, fsz, fkind))
print("}")
print()
sys.stderr.write("glfw: %d functions\n" % count)
if __name__ == '__main__':
main()
+301
View File
@@ -0,0 +1,301 @@
#!/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()