Skip to content

Platform-Guarded AST Reconciliation & Store Merge

This guide documents the recommended pattern for multi-target header ingestion, preprocessor branch isolation, topological AST reconciliation, and conditional code generation in HeaderKit.


1. The Preprocessor Isolation Invariant (HK-009)

When parsing C and C++ libraries that target multiple operating systems (such as audio libraries, windowing toolkits, or filesystem abstractions), source headers are heavily guarded with preprocessor conditionals:

#if defined(__APPLE__)
    typedef struct { void *audio_queue; } PlatformAudio;
    int mac_audio_start(PlatformAudio *audio);
#elif defined(__linux__)
    typedef struct { void *alsa_handle; } PlatformAudio;
    int linux_audio_start(PlatformAudio *audio);
#elif defined(_WIN32)
    typedef struct { void *wasapi_client; } PlatformAudio;
    int win_audio_start(PlatformAudio *audio);
#endif

HeaderKit strictly enforces the preprocessor mutual exclusion rule:

Parsers and AST extractors must NEVER walk mutually exclusive preprocessor branches simultaneously.

Attempting to scrape or merge branches during a single pass produces malformed IR with duplicate declarations and incorrect type definitions.

Instead, HeaderKit evaluates each target platform in complete preprocessor isolation using target triples, and then reconciles the resulting ASTs via the topological reconciliation engine.


2. Ingestion with Target Triples

Libclang supports target triples via -target arguments. This allows any machine (e.g. macOS host) to parse headers exactly as a Linux or Windows compiler would, without container latency:

from headerkit.backends.libclang import LibclangBackend

backend = LibclangBackend()
header_code = Path("cross_platform.h").read_text()

# macOS (Darwin)
u_mac = backend.parse(header_code, "cross_platform.h", extra_args=["-target", "arm64-apple-darwin"])

# Linux (GNU ABI)
u_linux = backend.parse(header_code, "cross_platform.h", extra_args=["-target", "x86_64-unknown-linux-gnu"])

# Windows (MSVC ABI)
u_win = backend.parse(header_code, "cross_platform.h", extra_args=["-target", "x86_64-pc-windows-msvc"])

Each parsed unit (Header / SourceUnit) reflects only the preprocessor branches active for that target.


3. Topological AST Reconciliation

The headerkit.reconcile module provides reconcile_units:

from headerkit.reconcile import reconcile_units

reconciled = reconcile_units(
    [
        ("darwin", u_mac),
        ("linux", u_linux),
        ("windows", u_win),
    ]
)

How the Reconciliation Algorithm Works:

  1. Structural Equality (declarations_equal): Compares declarations structurally while explicitly ignoring SourceLocation (since #ifdef directives shift source line numbers across platforms).
  2. Anchor-Based Topological Alignment: Identifies common declarations that appear in all compilation units in monotonic order. These act as sequential anchors.
  3. Branch Partitioning: Between consecutive anchors, divergent declarations from each unit are collected into a PlatformGuardedBlock, preserving platform-specific declarations under canonical predicates (defined(macosx), defined(linux), defined(windows)).
  4. Ordering Invariant: Typedefs and struct types always precede the functions and variables that reference them.

4. Safe C Function-Like Macro Wrapping

C function-like macros (such as #define MAKE_FLAG(bit) (1 << (bit)) or #define SAFE_FREE(p) do { ... } while(0)) are captured into HeaderKit IR as MacroFunction nodes.

Nim Code Generation Architecture:

  • Generic C Bridge Procs: proc c_NAME*[T](...): T {.importc: "NAME", header: "...", nodecl.} Using {.nodecl.} instructs Nim not to emit a C function prototype, allowing the C compiler preprocessor to expand the macro directly at the call site.
  • Public Templates: template name*(bit: untyped): untyped = c_NAME(bit) Directing calls through a C bridge procedure prevents infinite template self-recursion in Nim.
  • Statement Macros: Emitted with return type void so statement expressions evaluate cleanly.
  • Token-Pasting (##) Safety: Macros utilizing the preprocessor token-pasting operator cannot be called via FFI; HeaderKit detects them and emits a descriptive diagnostic comment: # Macro NAME skipped: contains preprocessor token-pasting (##) operator

5. Emitting Platform-Guarded Code

Render the ReconciledUnit directly with NimWriter:

from headerkit.writers.nim import NimWriter

writer = NimWriter(header_path="cross_platform.h")
nim_code = writer.write_reconciled(reconciled)

Resulting Output Structure:

# Generated by headerkit

type
  Status* = cint

proc c_MAKE_FLAG*[T](bit: T): T {.importc: "MAKE_FLAG", header: "cross_platform.h", nodecl.}
template make_flag*(bit: untyped): untyped =
  c_MAKE_FLAG(bit)

when defined(macosx):
  type
    PlatformAudio* {.importc: "PlatformAudio", header: "cross_platform.h", bycopy.} = object
      audio_queue*: pointer
      sample_rate*: cint

  proc mac_audio_start*(audio: ptr PlatformAudio): cint {.importc: "mac_audio_start", header: "cross_platform.h", cdecl.}
elif defined(linux):
  type
    PlatformAudio* {.importc: "PlatformAudio", header: "cross_platform.h", bycopy.} = object
      alsa_handle*: pointer
      buffer_size*: cint

  proc linux_audio_start*(audio: ptr PlatformAudio): cint {.importc: "linux_audio_start", header: "cross_platform.h", cdecl.}
elif defined(windows):
  type
    PlatformAudio* {.importc: "PlatformAudio", header: "cross_platform.h", bycopy.} = object
      wasapi_client*: pointer
      channels*: cuint

  proc win_audio_start*(audio: ptr PlatformAudio): cint {.importc: "win_audio_start", header: "cross_platform.h", cdecl.}

type
  AppContext* {.importc: "AppContext", header: "cross_platform.h", bycopy.} = object
    status*: Status
    audio*: pointer

proc app_init*(ctx: ptr AppContext): Status {.importc: "app_init", header: "cross_platform.h", cdecl.}
proc app_shutdown*(ctx: ptr AppContext) {.importc: "app_shutdown", header: "cross_platform.h", cdecl.}

6. Docker Verification & CI Matrix

To verify that generated bindings compile on target operating systems: 1. Local Host Verification: Execute nim check --hints:off bindings.nim on the host machine. 2. Containerized Linux Verification: Run nim check inside a lightweight container matching the host architecture (linux/arm64 or linux/amd64):

docker run --rm -v $(pwd):/workspace -w /workspace nimlang/nim:2.2.8 nim check --hints:off bindings.nim
3. CI Matrix Testing: In GitHub Actions or CI runners, run the integration test suite with:
pytest tests/test_integration/test_cross_platform.py -v
Tests gracefully skip Docker stages when the daemon is unavailable and execute them automatically in container-enabled CI jobs.