Skip to content

Hooks Pipeline

Headerkit provides a unified, priority-ordered hook pipeline (headerkit.hooks) for intercepting and customizing parsing, IR transformation, and output generation.

Priority Tiers

Hooks execute according to integer priority tiers defined in Priority. Higher numeric values execute first:

Tier Value Intended Usage
Priority.FALLBACK 10 Default fallback handlers (e.g. Tree-sitter fallback when system libclang is unavailable)
Priority.STANDARD 50 Built-in backends and writers
Priority.PROJECT 100 Local repository customizations and pyproject.toml extensions
Priority.OVERRIDE 1000 Explicit hard overrides that take absolute precedence

Execution Modes

The HookDispatcher supports two execution modes:

  • First-Result Dispatch (first_result): Queries matching candidate hooks sorted from highest priority to lowest. The first hook to return a non-None value wins. If a hook returns None, the dispatcher cascades to the next candidate.
  • Waterfall Pipeline (waterfall): Passes an initial value sequentially through all matching hooks in priority order, threading the transformed output through each stage.

Pattern Matching with Globs

Hooks can filter invocation contexts by specifying attribute matchers:

from headerkit.hooks import hook, Priority, PipelineContext
from headerkit.ir import SourceUnit


@hook("parse_unit", backend="tree-sitter", priority=Priority.STANDARD)
def custom_parser(code: str, filename: str, context: PipelineContext) -> SourceUnit | None: ...


@hook("write_output", writer="ctypes", priority=Priority.STANDARD)
def write_ctypes(unit: SourceUnit, context: PipelineContext) -> str: ...


@hook("write_output", writer="*", target="*windows*", priority=Priority.PROJECT)
def windows_override(unit: SourceUnit, context: PipelineContext) -> str: ...

Backend and Writer Unification

All parser backends and output writers register into the unified hook pipeline: - Backends register at parse_unit and get_backend. - Writers register at write_output and get_writer. - Calling get_backend() and get_writer() queries the highest-priority matching hook. - Custom plugins can override built-in backends or writers by registering hooks at Priority.PROJECT (100) or Priority.OVERRIDE (1000).

3-Stage Pipeline: Ingestion to Output

The pipeline executes in three stages: 1. parse_unit (first_result): Parses raw source into a SourceUnit Intermediate Representation. 2. transform_unit (waterfall): Passes the SourceUnit through sequential AST transformations (such as runtime lifecycle injections, macro expansion, or dialect conversions). 3. write_output (first_result): Generates code for the requested writer target.

execute_pipeline automates this three-stage flow:

from headerkit.hooks import execute_pipeline, PipelineContext
from headerkit.ir import InputSpec

spec = InputSpec.from_path("api.h", content="int compute(int x);")
ctx = PipelineContext(backend="tree-sitter", writer="json", runtime="nim")
unit, output = execute_pipeline(spec, context=ctx)

Symbol Renaming: rename_symbol and resolve_collision

Two hook points govern the identifiers a writer emits.

rename_symbol (waterfall) transforms one symbol's name:

def renamer(name: str, *, context: PipelineContext, kind: str) -> str: ...

kind is one of function, struct, union, enum, enumerator, field, typedef, param, macro. It is what makes a case rule expressible at all: Nim spells types in PascalCase and procs in camelCase, which is one rule per kind and not one rule for the module.

A waterfall runs highest priority first, and that ordering is the design. A project renamer registers at Priority.PROJECT; a writer registers its language's grammar rules at Priority.FALLBACK and therefore runs last. Whatever a project renames a symbol to must still survive the target language's lexer, and no configuration can bypass that floor. The Nim writer registers _nim_legality_renamer (headerkit.writers.nim) exactly the way it registers write_output.

resolve_collision (first_result) decides what to do when two source symbols collapse onto one identifier:

def resolver(
    collided: tuple[Symbol, ...],
    target: str,
    *,
    context: PipelineContext,
) -> dict[Symbol, str] | None: ...

Return an identifier for every member of collided, or None to decline. The default is to raise, naming both source symbols. An automatic disambiguator -- a counter suffix, first-wins, longest-wins -- is the writer deciding which symbol the caller meant, and it fails silently: the caller gets bindings that compile and call the wrong function.

The returned mapping is re-checked rather than trusted. A partial mapping is an error, every returned identifier is re-validated against the language grammar, and the results are re-tested for collisions under the target language's own identity function. A resolver that answers a collision with another collision fails loudly.

Renaming is not injective, and neither is the C-to-Nim spelling: __sig and _sig collapse under underscore repair, and to Nim fooBar and foo_bar are one identifier whatever the header called them (_nim_ident_identity in headerkit.writers.nim is the function that says so). Equality on the emitted string is the wrong test.

Known limitation: collision checking is module-scope

Collision checking covers the flat module-level namespace -- functions, structs, unions, enums, enumerators, typedefs and macros. It does not yet cover two fields of one record, or two parameters of one proc.

That is a gap, not a safe exclusion. Nim rejects a colliding field or parameter exactly as it rejects a colliding module-level symbol: an object declaring both fooBar and foo_bar is attempt to redefine: 'foo_bar', and so is a proc taking both as parameters. So a header whose collision sits at field or parameter level still produces a module its compiler refuses -- you get the error from Nim rather than from headerkit, without the source symbol names.

Do not read a module-level refusal as evidence that the writer checks collisions generally. Detecting field- and parameter-level collisions needs the per-record and per-proc symbol identity that the IR contract work introduces. Both cases are pinned in tests/test_rename.py as strict xfails, so they turn red on the day that lands.

Declarative configuration

[rename] in .headerkit.toml covers the common cases without code:

[rename]
collision_policy = "error"          # the default; see below for the others

[[rename.rules]]
kinds = ["function"]                # omit to apply to every kind
strip_prefix = "juce_"
case = "camel"                      # snake | camel | pascal | preserve
collapse_underscores = true
add_prefix = ""
add_suffix = ""

Steps within one rule apply in a fixed order: strip_prefix, case, collapse_underscores, add_prefix, add_suffix. Rules apply in declared order. A rename that needs the symbol's type, its header, or a lookup table is not expressible here -- that is what the Python hook is for.

collision_policy is one of error (default), suffix_header_stem, prefer_shortest, prefer_longest, prefer_first_declared. Every one but error is opt-in, each is deterministic given the same input set, and each is re-checked like any other resolver. suffix_header_stem separates symbols that came from different headers and cannot separate two declarations in one header: appending the same stem twice resolves nothing, and the re-check says so rather than emitting a module the compiler rejects.

Who applies a [rename] section

The CLI reads .headerkit.toml and registers the section's hooks; nothing else does. generate(), generate_all() and batch_generate() take their inputs as arguments and read no config file at all -- store directory, plugins and writer options work the same way -- so a library consumer relying on a [rename] section on disk gets the default naming and no diagnostic.

A library consumer applies it explicitly:

from headerkit import generate, load_config, register_config_hooks

register_config_hooks(load_config(".headerkit.toml").rename, writer="nim")
generate("api.h", "nim")

Registration is global and idempotent: registering the same config twice is a no-op, and registering a different one adds to the waterfall rather than replacing what is there.

Renaming and the cache

Renaming changes generated output, so the registered hooks enter the output cache key via rename_cache_fingerprint. A hook built from declarative config carries its config's digest, so two different rename configs cannot share a key. A hook written in Python is identified by module and qualified name: editing that function's body does not move the key, the same limitation writer plugins have with cache_version.

Documentation Hooks: preprocess_doc and parse_doc

DocParserTransform dispatches two hook points when converting raw doc strings into structured ParsedDoc nodes:

  1. preprocess_doc (waterfall): Transforms or normalizes raw comment strings (such as expanding custom company macro banners or stripping legacy annotations) before structured parsing.
  2. parse_doc (first_result): Parses the preprocessed comment string into a ParsedDoc instance. Matched on doc_format ("doxygen", "rst", "sphinx", "jsdoc", "google", "numpy", "rustdoc", "markdown", "plain", "auto") and language.
from typing import Any
from headerkit.hooks import PipelineContext, Priority, hook
from headerkit.ir import ParamDoc, ParsedDoc


@hook("preprocess_doc", priority=Priority.PROJECT)
def expand_custom_macros(raw_doc: str, decl: Any, *, context: PipelineContext) -> str:
    return raw_doc.replace("@MY_DEPRECATED", "@deprecated Use the v2 API.")


@hook("parse_doc", priority=Priority.PROJECT, doc_format="custom-dsl")
def parse_custom_dsl(
    raw_doc: str,
    decl: Any,
    *,
    context: PipelineContext,
    doc_format: str = "custom-dsl",
    on_error: str = "lenient",
) -> ParsedDoc:
    return ParsedDoc(
        summary=raw_doc.strip(),
        params=(ParamDoc(name="x", description="Input value"),),
        source_format=doc_format,
    )

API Reference

Priority

Bases: IntEnum

Execution priority tiers for registered hooks.

Higher numeric values execute first.

PipelineContext dataclass

PipelineContext(backend=None, writer=None, target=None, layout=None, language=None, classification=None, runtime=None, options=None)

Contextual metadata passed to hooks during dispatch.

HookRegistry

HookRegistry()

Registry maintaining registered hooks organized by hook point with O(1) indexing.

register

register(point, func, priority=STANDARD, **matchers)

Register a hook implementation.

register_global classmethod

register_global(point, func, priority=STANDARD, **matchers)

Register a hook implementation globally.

has_point classmethod

has_point(point)

Fast O(1) check if any hook is registered globally for the given point.

get_matching

get_matching(point, context)

Return matching hooks sorted by priority descending and specificity descending.

For ties in priority and specificity, later registered hooks take precedence.

get_global_matching classmethod

get_global_matching(point, context)

Return matching global hooks sorted by priority descending and specificity descending.

snapshot classmethod

snapshot()

Return a copy of all globally registered hooks.

restore classmethod

restore(snapshot)

Restore global hooks from a snapshot, synchronizing fast-path lookup indices.

clear classmethod

clear()

Clear all globally registered hooks and fast-path lookup indices.

hook

hook(point, priority=STANDARD, registry=None, **matchers)

Decorator to register a hook implementation.

HookDispatcher

HookDispatcher(registry=None)

Dispatches calls across registered hooks according to execution mode.

first_result

first_result(point, *args, context, **kwargs)

Execute matching hooks in priority order until one returns a non-None value.

waterfall

waterfall(point, initial_value, *args, context, **kwargs)

Pass a value sequentially through matching hooks in priority order.

HookCaller

HookCaller(point, registry=None)

Convenience caller bound to a specific hook point.

execute_pipeline

execute_pipeline(input_item, code=None, context=None, dispatcher=None, **kwargs)

Execute the 3-stage hook pipeline: parse_unit -> transform_unit -> write_output.

Symbol dataclass

Symbol(index, name, kind, header='', namespace=None)

One source symbol being renamed.

index is declaration order within the unit and header is the file the declaration came from; both exist so a collision policy can be deterministic without reading the IR.

namespace is the enclosing C++ namespace, or None at global scope. It belongs to the symbol's identity rather than being decoration on it: every name in the IR is unqualified, so two declarations in two namespaces reach a writer as one (name, kind) pair while being two symbols competing for a single target identifier.

header_stem property

header_stem

The originating header's filename without directories or extension.

qualified_name property

qualified_name

The source spelling including any enclosing namespace.

RenameConfig dataclass

RenameConfig(rules=(), collision_policy='error')

The declarative half of symbol renaming, as loaded from config.

is_default property

is_default

True when this config asks for nothing beyond headerkit's defaults.

fingerprint

fingerprint()

A stable digest of this config, for the output cache key.

Rename configuration changes generated output, so it has to be part of the key. Without it, editing a rename rule serves the previously cached output under the old names and reports a hit.

RenameRule dataclass

RenameRule(kinds=(), strip_prefix=None, add_prefix=None, add_suffix=None, case='preserve', collapse_underscores=False)

One declarative rename step, optionally restricted to certain kinds.

Steps are applied in the order written: strip_prefix, case, collapse_underscores, add_prefix, add_suffix. The order is fixed rather than configurable so that two configs that list the same fields mean the same thing.

enforce_injectivity

enforce_injectivity(assigned, *, identity, context, validate=None, dispatcher=None)

Check that no two symbols share an identifier under identity.

On a collision the resolve_collision hook is offered the group. The hook must return an identifier for every member -- a partial mapping is a refusal to decide about the rest, and keeping the original name for an uncovered symbol is the exact defect this exists to prevent. The returned identifiers are then re-validated and re-checked for collisions against the whole assignment; a resolver that answers a collision with another collision raises rather than being trusted.

Raises:

Type Description
SymbolCollisionError

when a collision is left unresolved.

RenameError

when a resolver returns an unusable mapping.

rename_cache_fingerprint

rename_cache_fingerprint()

Digest the registered renaming hooks, for the output cache key.

Renaming changes generated output, so a cache key that ignores it serves the previous output under the previous names and reports a hit -- silently, with no diagnostic anywhere. The digest therefore covers every registered rename_symbol and resolve_collision implementation.

A hook built from declarative config carries its config's own digest on headerkit_rename_fingerprint, so two different rename configs cannot share a key. A hook written in Python is identified by module and qualified name: editing that function's body does not move the key, which is the same limitation writer plugins already have with cache_version.

The parts are sorted so that the digest does not depend on the order writer modules happened to be imported in.

register_config_hooks

register_config_hooks(config, **matchers)

Register the declarative rename config as hook implementations.

Registered at :attr:~headerkit.hooks.Priority.PROJECT, above every writer's legality renamer at FALLBACK. The waterfall runs highest priority first, so a project rule is applied and then made legal, never the reverse.

Registering the same config twice is a no-op. It was not, and the second registration was not merely redundant: rename_symbol is a waterfall, so two copies of a prefix rule ran in series and foo came out hkhkfoo. The output cache key digests the registered hooks, so the duplicate also moved the fingerprint and turned every subsequent lookup into a miss. Neither reported anything. Two main() calls in one process is enough to reach it, which is what a library consumer and the test suite both do.