gen_bindings.py¶
scripts/gen_bindings.py
Auto-generate python/src/entropic/_bindings.py from the C header.
Owners: @tvanfossen
check_outputs
int gen_bindings.check_outputs(GeneratedSources src)
Compare generated text against committed files; exit 1 on drift.
scripts/gen_bindings.py:906
Source · 20 lines
def check_outputs(src: GeneratedSources) -> int:
"""Return 0 if checked-in files match generated text, else 1 + diagnostic."""
ok = True
for label, generated, path in (
("_bindings.py", src.bindings_py, BINDINGS_OUT),
("_bindings_manifest.py", src.manifest_py, MANIFEST_OUT),
):
committed = path.read_text() if path.exists() else ""
if committed != generated:
ok = False
print(
f"gen_bindings: drift in {label} — committed file differs"
f" from header-derived output.\n"
f" Path: {path.relative_to(REPO_ROOT)}\n"
f" Fix: run `inv gen-bindings` and commit the result.",
file=sys.stderr,
)
return 0 if ok else 1
Activity · 7 steps
Requirements
Flows
generate
GeneratedSources gen_bindings.generate()
Run the full parse + emit pipeline; return generated sources.
scripts/gen_bindings.py:780
Called by main
Calls parse_callbacks, parse_enum, parse_functions, parse_struct, read, render_bindings, render_manifest
Source · 35 lines
def generate() -> GeneratedSources:
"""Parse all input headers and return generated source text.
Does not write any files. Callers (``inv gen-bindings``,
``inv gen-bindings --check``) decide whether to commit or compare.
"""
enums = [parse_enum(read(p), name) for (p, name) in ENUM_SOURCES]
structs = [
parse_struct(read(p), c_typedef, py_name) for (p, c_typedef, py_name) in STRUCT_SOURCES
]
# Named callbacks live in different headers; parse each. Order is
# explicit (not set-iteration) so generator output is deterministic.
cb_sources = [TYPES_DIR / "hooks.h", ENTROPIC_H]
callbacks: list[CallbackDecl] = []
seen_cb_names: set[str] = set()
for path in cb_sources:
for cb in parse_callbacks(read(path)):
if cb.py_name in seen_cb_names:
continue
callbacks.append(cb)
seen_cb_names.add(cb.py_name)
functions = parse_functions(read(ENTROPIC_H))
# Collect minted CFUNCTYPEs from inline-fnptr params, dedup by name.
inline_cbs: list[CallbackDecl] = []
for fn in functions:
for cb in fn.inline_cbs:
if cb.py_name in seen_cb_names:
continue
inline_cbs.append(cb)
seen_cb_names.add(cb.py_name)
bindings = render_bindings(enums, structs, callbacks, inline_cbs, functions)
manifest = render_manifest(enums, structs, callbacks, inline_cbs, functions)
return GeneratedSources(bindings_py=bindings, manifest_py=manifest)
Activity · 22 steps
Requirements
Flows
main
int gen_bindings.main(list[str] argv)
Module entrypoint.
scripts/gen_bindings.py:931
Source · 9 lines
def main(argv: list[str]) -> int:
"""Top-level CLI: --check vs default write."""
src = generate()
if "--check" in argv:
return check_outputs(src)
write_outputs(src)
return 0
Activity · 5 steps
Requirements
Flows
parse_callbacks
list[CallbackDecl] gen_bindings.parse_callbacks(str text)
Parse all typedef R (*name)(args) callback declarations.
scripts/gen_bindings.py:382
Source · 30 lines
def parse_callbacks(text: str) -> list[CallbackDecl]:
"""Return CallbackDecls for every named callback typedef in text."""
# Pattern: `typedef <ret> (*<name>)(<args>);`. Restype may contain
# spaces and pointer suffix. Bracket-balance the args list with a
# tail re-parse to allow nested parens (rare but possible).
pattern = re.compile(
r"typedef\s+([\w\s\*]+?)\s*\(\s*\*\s*(\w+)\s*\)\s*\(([^)]*)\)\s*;",
re.DOTALL,
)
out: list[CallbackDecl] = []
for m in pattern.finditer(text):
ret_raw, name, args_raw = m.groups()
if name not in NAMED_CB_RENAME:
continue
restype = normalize_ctype(ret_raw)
argtypes = resolve_argtypes(split_args(args_raw))
py_restype = CTYPE_MAP.get(restype)
if py_restype is None:
raise SystemExit(f"gen_bindings: unmapped callback restype {restype!r} for {name}")
out.append(
CallbackDecl(
c_typedef=name,
py_name=NAMED_CB_RENAME[name],
restype=py_restype,
argtypes=argtypes,
)
)
return out
Activity · 13 steps
Flows
parse_enum
EnumDecl gen_bindings.parse_enum(str text, str c_typedef)
Parse a single typedef enum block out of header text.
scripts/gen_bindings.py:313
Source · 26 lines
def parse_enum(text: str, c_typedef: str) -> EnumDecl:
"""Return an EnumDecl with sequential auto-numbering applied."""
pattern = re.compile(
r"typedef\s+enum\s*\{([^}]*)\}\s*" + re.escape(c_typedef) + r"\s*;",
re.DOTALL,
)
m = pattern.search(text)
if m is None:
raise SystemExit(f"gen_bindings: typedef enum {c_typedef} not found")
body = m.group(1)
decl = EnumDecl(c_typedef=c_typedef)
next_value = 0
for raw in body.split(","):
entry = raw.strip()
if not entry:
continue
if "=" in entry:
name, value_expr = (s.strip() for s in entry.split("=", 1))
value = int(value_expr, 0)
else:
name, value = entry, next_value
decl.members.append((name, value))
next_value = value + 1
return decl
Activity · 19 steps
Requirements
Flows
parse_functions
list[FunctionDecl] gen_bindings.parse_functions(str text)
Parse every ENTROPIC_EXPORT function declaration in text.
scripts/gen_bindings.py:567
Source · 35 lines
def parse_functions(text: str) -> list[FunctionDecl]:
"""Return one FunctionDecl per ENTROPIC_EXPORT declaration.
Bracket-balances the argument list so inline function-pointer
params survive. Restype regex stops at the function name; arg
list is captured by paren-depth from the opening ``(``.
"""
# Locate `ENTROPIC_EXPORT <ret> <name>(`. Then walk forward to find
# the matching closing paren of the argument list, then the
# trailing semicolon.
starter = re.compile(r"ENTROPIC_EXPORT\s+([\w\s\*]+?)\s+(\w+)\s*\(", re.DOTALL)
out: list[FunctionDecl] = []
for m in starter.finditer(text):
ret_raw, name = m.group(1), m.group(2)
args_start = m.end()
depth = 1
i = args_start
while i < len(text) and depth > 0:
if text[i] == "(":
depth += 1
elif text[i] == ")":
depth -= 1
i += 1
if depth != 0:
raise SystemExit(f"gen_bindings: unclosed args for {name}")
args_raw = text[args_start : i - 1]
# Require trailing `;` for a declaration (not a definition).
tail = text[i:].lstrip()
if not tail.startswith(";"):
continue
decl = build_function_decl(name, ret_raw, args_raw)
out.append(decl)
return out
Activity · 22 steps
Requirements
Flows
parse_struct
StructDecl gen_bindings.parse_struct(str text, str c_typedef, str py_name)
Parse a typedef struct block out of header text.
scripts/gen_bindings.py:343
Source · 36 lines
def parse_struct(text: str, c_typedef: str, py_name: str) -> StructDecl:
"""Return a StructDecl with resolved ctypes for each field.
Handles both anonymous (``typedef struct { ... } name;``) and named
(``typedef struct tag { ... } name;``) forms — the latter appears
for ``entropic_logprob_result_t`` and a couple of other types whose
inner struct keeps a tag for forward-declaration purposes.
"""
pattern = re.compile(
r"typedef\s+struct(?:\s+\w+)?\s*\{([^}]*)\}\s*" + re.escape(c_typedef) + r"\s*;",
re.DOTALL,
)
m = pattern.search(text)
if m is None:
raise SystemExit(f"gen_bindings: typedef struct {c_typedef} not found")
decl = StructDecl(c_typedef=c_typedef, py_name=py_name)
for line in m.group(1).split(";"):
entry = line.strip()
if not entry:
continue
# Split on the last whitespace before the field name.
parts = entry.rsplit(maxsplit=1)
if len(parts) != 2:
raise SystemExit(f"gen_bindings: cannot parse struct field {entry!r}")
type_raw, name = parts
# Pointer-on-name vs pointer-on-type: fold ``const char* foo``
# vs ``const char *foo`` into the same spelling.
if name.startswith("*"):
type_raw = type_raw + name[: name.rfind("*") + 1]
name = name.lstrip("*")
ctype = normalize_ctype(type_raw)
py_ctype = resolve_one(ctype, type_raw)
decl.fields.append(StructField(name=name, ctype=py_ctype))
return decl
Activity · 20 steps
Requirements
Flows
read
str gen_bindings.read(Path path)
Read a UTF-8 text file; strip comments; return the cleaned text.
scripts/gen_bindings.py:880
Source · 8 lines
def read(path: Path) -> str:
"""Return path.read_text() with C comments stripped."""
return strip_comments(path.read_text())
# ── CLI ───────────────────────────────────────────────────
Activity · 1 steps
Flows
render_bindings
str gen_bindings.render_bindings(list[EnumDecl] enums, list[StructDecl] structs, list[CallbackDecl] callbacks, list[CallbackDecl] inline_cbs, list[FunctionDecl] functions)
Concatenate prologue + emitted sections into the bindings source.
scripts/gen_bindings.py:818
Called by generate
Calls emit_aliases, emit_callback, emit_enum, emit_function, emit_struct
Source · 23 lines
def render_bindings(
enums: list[EnumDecl],
structs: list[StructDecl],
callbacks: list[CallbackDecl],
inline_cbs: list[CallbackDecl],
functions: list[FunctionDecl],
) -> str:
"""Return the full text of python/src/entropic/_bindings.py."""
sections: list[str] = [PROLOGUE]
sections.append("# ── Enums ─────────────────────────────────────\n\n")
sections.extend(emit_enum(e) + "\n" for e in enums)
sections.append("# ── Structs ───────────────────────────────────\n\n")
sections.extend(emit_struct(s) + "\n" for s in structs)
sections.append("# ── Callback typedefs (named) ─────────────────\n\n")
sections.extend(emit_callback(c) for c in callbacks)
sections.append("\n# ── Callback typedefs (from inline params) ────\n\n")
sections.extend(emit_callback(c) for c in inline_cbs)
sections.append("\n" + emit_aliases() + "\n")
sections.append("# ── Bindings ──────────────────────────────────\n\n")
sections.extend(emit_function(f) for f in functions)
return "".join(sections)
Activity · 13 steps
Requirements
Flows
render_manifest
str gen_bindings.render_manifest(list[EnumDecl] enums, list[StructDecl] structs, list[CallbackDecl] callbacks, list[CallbackDecl] inline_cbs, list[FunctionDecl] functions)
Build the manifest module text.
scripts/gen_bindings.py:844
Source · 33 lines
def render_manifest(
enums: list[EnumDecl],
structs: list[StructDecl],
callbacks: list[CallbackDecl],
inline_cbs: list[CallbackDecl],
functions: list[FunctionDecl],
) -> str:
"""Return the text of python/src/entropic/_bindings_manifest.py."""
names: list[str] = []
names.append("entropic_handle_t")
names.extend(ENUM_RENAME[e.c_typedef][0] for e in enums)
names.extend(s.py_name for s in structs)
names.extend(c.py_name for c in callbacks)
names.extend(c.py_name for c in inline_cbs)
names.extend(COMPAT_ALIASES.keys())
names.extend(f.name for f in functions)
quoted = ",\n ".join(f'"{n}"' for n in sorted(names))
return (
"# SPDX-License-Identifier: Apache-2.0\n"
"# AUTO-GENERATED by scripts/gen_bindings.py — do not edit.\n"
'"""Exported names for the entropic ctypes bindings.\n\n'
"This file is imported eagerly by ``entropic.__init__`` to populate\n"
"the public ``_LAZY_EXPORTS`` set without loading ``librentropic.so``.\n"
'"""\n\n'
"from __future__ import annotations\n\n"
"EXPORTS = frozenset(\n"
" {\n"
f" {quoted},\n"
" }\n"
")\n"
)
Activity · 10 steps
Requirements
Flows
write_outputs
None gen_bindings.write_outputs(GeneratedSources src)
Write generated files.
scripts/gen_bindings.py:895
Source · 6 lines
def write_outputs(src: GeneratedSources) -> None:
"""Persist generated text to the canonical output paths."""
BINDINGS_OUT.write_text(src.bindings_py)
MANIFEST_OUT.write_text(src.manifest_py)