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

Show on the map →

Called by main

Calls none

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
lines 908–908ok = Truelines 909–909◇ for label, generated, path in (lines 913–913committed = path.read_text() if path.exists() else ""lines 914–914◇ if committed != generatedlines 915–915ok = Falselines 916–922print( 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, )lines 923–923return 0 if ok else 1

Requirements

REQ-API-014

Flows

generate

GeneratedSources gen_bindings.generate()

Run the full parse + emit pipeline; return generated sources.

scripts/gen_bindings.py:780

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
lines 786–786enums = [parse_enum(read(p), name) for (p, name) in ENUM_SOURCES]lines 787–789structs = [ parse_struct(read(p), c_typedef, py_name) for (p, c_typedef, py_name) in STRUCT_SOURCES ]lines 792–792cb_sources = [TYPES_DIR / "hooks.h", ENTROPIC_H]lines 793–793callbacks: list[CallbackDecl] = []lines 794–794seen_cb_names: set[str] = set()lines 795–795◇ for path in cb_sourceslines 796–796◇ for cb in parse_callbacks(read(path))lines 797–797◇ if cb.py_name in seen_cb_nameslines 798–798continuelines 799–799callbacks.append(cb)lines 800–800seen_cb_names.add(cb.py_name)lines 801–801functions = parse_functions(read(ENTROPIC_H))lines 803–803inline_cbs: list[CallbackDecl] = []lines 804–804◇ for fn in functionslines 805–805◇ for cb in fn.inline_cbslines 806–806◇ if cb.py_name in seen_cb_nameslines 807–807continuelines 808–808inline_cbs.append(cb)lines 809–809seen_cb_names.add(cb.py_name)lines 810–810bindings = render_bindings(enums, structs, callbacks, inline_cbs, functions)lines 811–811manifest = render_manifest(enums, structs, callbacks, inline_cbs, functions)lines 812–812return GeneratedSources(bindings_py=bindings, manifest_py=manifest)

Requirements

REQ-API-014

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
lines 933–933src = generate()lines 934–934◇ if "--check" in argvlines 935–935return check_outputs(src)lines 936–936write_outputs(src)lines 937–937return 0

Requirements

REQ-API-014

Flows

parse_callbacks

list[CallbackDecl] gen_bindings.parse_callbacks(str text)

Parse all typedef R (*name)(args) callback declarations.

scripts/gen_bindings.py:382

Show on the map →

Called by generate

Calls normalize_ctype, resolve_argtypes, split_args

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
lines 387–390pattern = re.compile( r"typedef\s+([\w\s\*]+?)\s*\(\s*\*\s*(\w+)\s*\)\s*\(([^)]*)\)\s*;", re.DOTALL, )lines 391–391out: list[CallbackDecl] = []lines 392–392◇ for m in pattern.finditer(text)lines 393–393ret_raw, name, args_raw = m.groups()lines 394–394◇ if name not in NAMED_CB_RENAMElines 395–395continuelines 396–396restype = normalize_ctype(ret_raw)lines 397–397argtypes = resolve_argtypes(split_args(args_raw))lines 398–398py_restype = CTYPE_MAP.get(restype)lines 399–399◇ if py_restype is Nonelines 400–400raise SystemExit(f"gen_bindings: unmapped callback restype {restype!r} for {name}")lines 401–408out.append( CallbackDecl( c_typedef=name, py_name=NAMED_CB_RENAME[name], restype=py_restype, argtypes=argtypes, ) )lines 409–409return out

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

Show on the map →

Called by generate

Calls none

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
lines 315–318pattern = re.compile( r"typedef\s+enum\s*\{([^}]*)\}\s*" + re.escape(c_typedef) + r"\s*;", re.DOTALL, )lines 319–319m = pattern.search(text)lines 320–320◇ if m is Nonelines 321–321raise SystemExit(f"gen_bindings: typedef enum {c_typedef} not found")lines 322–322body = m.group(1)lines 323–323decl = EnumDecl(c_typedef=c_typedef)lines 324–324next_value = 0lines 325–325◇ for raw in body.split(",")lines 326–326entry = raw.strip()lines 327–327◇ if not entrylines 328–328continuelines 329–329◇ if "=" in entrylines 330–330name, value_expr = (s.strip() for s in entry.split("=", 1))lines 331–331value = int(value_expr, 0)lines 332–332elselines 333–333name, value = entry, next_valuelines 334–334decl.members.append((name, value))lines 335–335next_value = value + 1lines 336–336return decl

Requirements

REQ-API-014

Flows

parse_functions

list[FunctionDecl] gen_bindings.parse_functions(str text)

Parse every ENTROPIC_EXPORT function declaration in text.

scripts/gen_bindings.py:567

Show on the map →

Called by generate

Calls build_function_decl

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
lines 577–577starter = re.compile(r"ENTROPIC_EXPORT\s+([\w\s\*]+?)\s+(\w+)\s*\(", re.DOTALL)lines 578–578out: list[FunctionDecl] = []lines 579–579◇ for m in starter.finditer(text)lines 580–580ret_raw, name = m.group(1), m.group(2)lines 581–581args_start = m.end()lines 582–582depth = 1lines 583–583i = args_startlines 584–584◇ while i < len(text) and depth > 0lines 585–585◇ if text[i] == "("lines 586–586depth += 1lines 587–587◇ elif text[i] == ")"lines 588–588depth -= 1lines 589–589i += 1lines 590–590◇ if depth != 0lines 591–591raise SystemExit(f"gen_bindings: unclosed args for {name}")lines 592–592args_raw = text[args_start : i - 1]lines 594–594tail = text[i:].lstrip()lines 595–595◇ if not tail.startswith(";")lines 596–596continuelines 597–597decl = build_function_decl(name, ret_raw, args_raw)lines 598–598out.append(decl)lines 599–599return out

Requirements

REQ-API-014

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

Show on the map →

Called by generate

Calls normalize_ctype, resolve_one

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
lines 351–354pattern = re.compile( r"typedef\s+struct(?:\s+\w+)?\s*\{([^}]*)\}\s*" + re.escape(c_typedef) + r"\s*;", re.DOTALL, )lines 355–355m = pattern.search(text)lines 356–356◇ if m is Nonelines 357–357raise SystemExit(f"gen_bindings: typedef struct {c_typedef} not found")lines 358–358decl = StructDecl(c_typedef=c_typedef, py_name=py_name)lines 359–359◇ for line in m.group(1).split(";")lines 360–360entry = line.strip()lines 361–361◇ if not entrylines 362–362continuelines 364–364parts = entry.rsplit(maxsplit=1)lines 365–365◇ if len(parts) != 2lines 366–366raise SystemExit(f"gen_bindings: cannot parse struct field {entry!r}")lines 367–367type_raw, name = partslines 370–370◇ if name.startswith("*")lines 371–371type_raw = type_raw + name[: name.rfind("*") + 1]lines 372–372name = name.lstrip("*")lines 373–373ctype = normalize_ctype(type_raw)lines 374–374py_ctype = resolve_one(ctype, type_raw)lines 375–375decl.fields.append(StructField(name=name, ctype=py_ctype))lines 376–376return decl

Requirements

REQ-API-014

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

Show on the map →

Called by generate

Calls strip_comments

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
lines 882–882return strip_comments(path.read_text())

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

Show on the map →

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
lines 826–826sections: list[str] = [PROLOGUE]lines 827–827sections.append("# ── Enums ─────────────────────────────────────\n\n")lines 828–828sections.extend(emit_enum(e) + "\n" for e in enums)lines 829–829sections.append("# ── Structs ───────────────────────────────────\n\n")lines 830–830sections.extend(emit_struct(s) + "\n" for s in structs)lines 831–831sections.append("# ── Callback typedefs (named) ─────────────────\n\n")lines 832–832sections.extend(emit_callback(c) for c in callbacks)lines 833–833sections.append("\n# ── Callback typedefs (from inline params) ────\n\n")lines 834–834sections.extend(emit_callback(c) for c in inline_cbs)lines 835–835sections.append("\n" + emit_aliases() + "\n")lines 836–836sections.append("# ── Bindings ──────────────────────────────────\n\n")lines 837–837sections.extend(emit_function(f) for f in functions)lines 838–838return "".join(sections)

Requirements

REQ-API-014

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

Show on the map →

Called by generate

Calls none

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
lines 852–852names: list[str] = []lines 853–853names.append("entropic_handle_t")lines 854–854names.extend(ENUM_RENAME[e.c_typedef][0] for e in enums)lines 855–855names.extend(s.py_name for s in structs)lines 856–856names.extend(c.py_name for c in callbacks)lines 857–857names.extend(c.py_name for c in inline_cbs)lines 858–858names.extend(COMPAT_ALIASES.keys())lines 859–859names.extend(f.name for f in functions)lines 860–860quoted = ",\n ".join(f'"{n}"' for n in sorted(names))lines 861–874return ( "# 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" )

Requirements

REQ-API-014

Flows

write_outputs

None gen_bindings.write_outputs(GeneratedSources src)

Write generated files.

scripts/gen_bindings.py:895

Show on the map →

Called by main

Calls none

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)

Activity · 2 steps
lines 897–897BINDINGS_OUT.write_text(src.bindings_py)lines 898–898MANIFEST_OUT.write_text(src.manifest_py)

Requirements

REQ-API-014

Flows