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:
1 parent
210054f46c
commit
04009c3c5e
18 files changed
+13539
-2
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user