Files
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

165 lines
5.6 KiB
Python

#!/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()