Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Interop Toolchain Boundary

FOL exports a real C ABI and imports real C libraries. A C program links a FOL static or shared library and calls it through a generated header; a FOL package calls a C provider through a manifest that fol tool bind c wrote from that provider’s own header and archive. Both directions are proven by lanes in make verify that compile and run the result, not by reading generated text.

What crosses each way is listed under What crosses, together with what is refused. The exclusions are as load-bearing as the inclusions: FOL rejects a construct it cannot model rather than approximating it.

FOL integrates three independently usable sibling crates and does not copy their native semantics:

build.fol executable + one C header/object import
  -> PARC CompleteSourcePackage
  -> LINC ValidatedLinkAnalysis
  -> GERC GenerationBundle
  -> fol-build generated-file action graph
  -> fol-backend auxiliary Rust crates and exact rustc arguments
  -> linked and executed FOL binary

The stages have fixed ownership:

  • PARC is the only C preprocessor, parser, recovery engine, source extractor, provenance store, and source-contract owner.
  • LINC is the only native artifact inspector, compiler/ABI probe runner, symbol/provider validator, and ordered link-evidence owner.
  • GERC is the only closed-world raw Rust FFI projector and emitter.
  • FOL owns language policy, target and build-graph routing, generated-file materialization, the narrow H7 call anchor, backend process invocation, diagnostics, and eventual safe language wrappers.

The handoff is typed. FOL does not use JSON shape conversion, copied sibling models, a second provider resolver, a second raw extern "C" emitter, shell splitting, or text link-argument parsing. GERC’s typed link atoms remain individual native process arguments when they reach rustc.

Pinned inputs

lang/tooling/fol-interop/Cargo.toml is the machine authority: each component is pinned there by git revision, and Cargo.lock records what cargo resolved from those pins. H7 is certified against this exact snapshot:

StagePackageContractPinned revision
PARCfollang-parc 0.16.0source package schema 297a2dee3453219f928738a1e7f96aad830909e17
LINCfollang-linc 0.1.0 with native-inspectionlink-analysis schema 21a925fa07ce32a6cffa6814ddedafebebf1f22dc
GERCfollang-gerc 0.1.0 with pipeline-nativegeneration domain 1fedd86e77358a54cf2b72815dc69efc8305d72b0

Reading the host’s own system headers

By default the search inputs are exactly what the author wrote: §4.13 disables ambient CPATH/SDK discovery, so a scan cannot quietly depend on the machine. That is also why a header including <stdio.h> does not read – not because the file is missing, but because stdint.h is written against the compiler’s predefined macros (__INT8_TYPE__ and some four hundred others) and nothing else supplies them.

--host-system-headers asks the C compiler for its own include roots and predefines and expands them into explicit roots and defines before the scan runs. The scan keeps its rule, the manifest records every root and macro, and the fingerprint covers them – so two machines whose compilers disagree produce visibly different identities rather than the same identity over different headers. The author’s own --defines are written last and are never displaced.

It is off by default because it trades hermeticity for reach, and that trade should be a decision rather than a default.

A build.fol asks for the same thing with system_headers = "host" on its add_c_import record, and reaches the same expansion – so a header that binds by hand also builds from the graph. Any other value is refused rather than ignored: a declaration nobody reads is one the author believes is in force.

The three components are git dependencies pinned by revision, not sibling path dependencies, so a fresh clone of this repository builds and tests without any of them checked out. A pinned revision is content-binding, which makes provenance a build-time property rather than something to re-observe at run time:

  • fol-interop/build.rs reads the resolved revisions back out of Cargo.lock and hands them to the crate, so the recorded provenance is whatever cargo actually built against.
  • compile-time assertions in fol-interop/src/lib.rs prove those crates still expose the expected contract versions.
  • each component pins the components below it at these same revisions, because two different follang-parc revisions in one graph would produce two incompatible sets of contract types — cargo resolves them as separate crates and every shared type stops matching.

tools/verify-interop-lock.sh checks that nothing loosens a pin to a branch or a path, that no [patch] entry substitutes a component, and that this table still quotes the revisions in force.

The earlier design shelled out to git at run time to check each sibling checkout’s root, HEAD, worktree cleanliness, and origin. That could only pass inside a source tree — a released binary carried the build machine’s paths — so it verified nothing for users.

A provider’s own dependencies

Almost every shared library on Linux needs another one: libexpat.so carries a DT_NEEDED on libm.so.6 and libc.so.6, and those carry more. The resolver satisfies each one from the artifacts it was handed, so they have to be handed to it:

app.add_c_import({
    alias = "xp",
    header = header,
    provider = provider,
    provider_kind = "shared",
    annotations = overlay,
    provider_dependencies = {
        "/nix/store/.../lib/libm.so.6",
        "/nix/store/.../lib/libc.so.6",
        "/nix/store/.../lib/ld-linux-x86-64.so.2",
    },
});

fol tool bind c takes the same thing as a repeatable --provider-dependency.

Each one is an exact path, and that is the whole distinction from library_paths, which is refused. A search path asks the resolver to go looking, and the certified analysis profile resolves exact paths only — refusing it is what keeps the answer reproducible rather than dependent on what happened to be installed. Naming the artifact is the opposite: it is precisely the kind of input that profile accepts, and the build states it once.

The dependencies are digested into the manifest beside the provider, for the same reason the provider is: a swapped one decides what code actually runs, and a path alone would go on looking current.

This says nothing about the runtime loader. A shared provider still has to be findable when the program starts, which is LD_LIBRARY_PATH, an RPATH, or an installed library — the same as for any program that links one.

Certified platforms

Two lanes are promoted:

x86_64-unknown-linux-gnu     ELF, LP64
x86_64-unknown-linux-musl    ELF, LP64
explicit GCC or clang executable and observed compiler identity
one executable artifact with one C object provider

glibc and musl are the same System V AMD64 ABI — only the libc differs — and LINC measures every layout by compiling probes with the caller’s own compiler rather than modelling it, so the same evidence certifies both. Each lane has its own link-and-run smoke; neither stands in for the other.

The caller supplies normalized absolute paths for the compiler and the bounded LINC probe workspace. LINC observes and fingerprints the compiler rather than FOL guessing its identity, and accepts the GCC and clang families. The selected FOL target must equal every sibling target fingerprint before generated files or backend compilation are allowed.

Other Linux architectures, Apple targets, Windows targets, frameworks, import libraries, and multiple imports per artifact remain uncertified.

What crosses

The two directions are not symmetric, and the asymmetry is real rather than an accident of what has been tested. Everything below is exercised by a lane in make verify that compiles and runs it; nothing is listed on the strength of the code appearing to support it.

Exporting, FOL to C — a C program links a FOL library and calls it:

ShapeCrosses as
integers int[8..64], unsigned, flt[32]/flt[64]the exact-width C scalar
bolfol_bool_t (uint8_t); only 0 and 1 are valid, and imports validate
chrfol_char_t (uint32_t); validated as a Unicode scalar value
recordsa C struct whose layout C agrees with, field order preserved
entriesa C enum with the discriminants the variants state
resourcesan opaque fol_<domain>_t * token, released by a paired destroy; a second destroy, a use after destroy, or a pointer the library never produced is refused with FOL_STATUS_INVALID_ARGUMENT, and a handle C never releases shows up as a leak under LeakSanitizer
a routine parametera C function pointer plus its own void * context
recoverable errorsfol_status_t plus a typed error out-parameter
a FOL paniccontained and reported as FOL_STATUS_PANIC
borrowed text, inboundfol_str_view_t, caller-owned and call-scoped

Importing, C to FOL — FOL calls a C provider through a checked manifest:

ShapeCrosses as
scalars, including through typedef chainsthe measured FOL scalar
named structs and enums, as parametersa FOL record, and the enum’s measured storage scalar
a C enum’s enumerators (enum color { RED, GREEN = 4 })constants of the import (prb::GREEN), typed at that scalar; a value naming no enumerator crosses unchanged
a struct the provider fills through a pointera FOL record passed as a mutable loan, its writes landing in FOL’s value
a derived struct where C declares its base (uv_close(uv_handle_t *) handed a timer)upcast / upcast_from: the derived record, accepted once its fields are checked to begin with every field of the base
a tagged union behind a pointer (SDL_Event *)a FOL record whose one named field is the tag, the rest opaque cells at the union’s size and alignment
a record aligned past its fields (aligned(64), even under #pragma pack)a FOL record whose struct carries the same alignment, built with {} when no field is worth naming
pointers and out-parametersa FOL value on the success channel
a pointer/length pairone borrowed FOL vector, its length derived
several pointer/length pairs in one routinebuffer = ["out", "in"] with buffer_length in the same order: each pair its own borrowed FOL vector
a list of handles with its count (const git_commit *parents[])a buffer whose elements are a domain’s handles: a borrowed vec[D[bor]] of loans, crossing as an array of their addresses
an output buffer whose written count comes back through a pointer (EVP_DigestFinal_ex), or whose count carries the room in and back under a status (zlib’s compress)written_buffer / written_length / written_capacity (and written_length_in = "capacity"): a mutable loan of a FOL vector with at least the declared room, shortened to what the provider wrote
a provider-allocated buffera FOL vector, copied and released in the call
status codesFOL’s ordinary or recoverable channel, per the overlay
opaque handlesa lin linear resource with a paired destroy routine
a handle’s public fields (face->num_glyphs, face->glyph->outline)fields on the domain: one getter per field through a borrowed handle – a scalar copied out, a pointer or embedded record handed back as a borrow-only domain’s handle
one synchronous callback shapea FOL closure invoked by the provider
a callback whose first and last parameters both have the context’s type (GLib’s GFunc)callback_context_slot = "first" or "last": refused without it, because the type cannot say which end is the context; a context typed as something other than void * is handed to the provider at its own pointee type
a callback the provider keepsa FOL closure owned by the handle that keeps it (callback_kept_by)
a callback kept by a record the caller owns (uv_timer_t)callback_kept_by naming a record parameter: the record’s address is the key, handed back as the callback’s first argument, and the closure is released after the routine the overlay names with releases_kept
a kept callback found by its keepercallback_context = "keeper": the closure receives the keeping handle, borrowed
a kept callback found through user datacontext_setter on the handle domain: FOL owns the slot and installs the keeper there
text inside a callback signaturecallback_strings: a const char * position reaches the closure as its own str
a list of text inside a callback signaturecallback_string_lists: a NULL-terminated const char ** position reaches the closure as its own vec[str]
several callbacks installed by one callcallback = ["start", "end"]: each gets its own trampoline; the context, keeper, and text positions are shared
a struct of callbacks the caller fills (FT_Outline_Funcs)callback_table naming the struct parameter: one FOL closure per named field, the struct built by the adapter with its other scalar fields zero

Both directions now carry named aggregates, opaque handles, and the one callback shape. What is still refused, rather than approximated:

  • Importing a self-referential struct’s pointed-to type. The pointer crosses as an opaque handle; the shape behind it does not.
  • A struct field that is a pointer at something FOL cannot read – an incomplete type, or a function pointer – crosses as an address token: the record carries it at its offset, and FOL hands it back without reading it. lua_Debug’s private CallInfo * and sqlite3_vfs’s method pointers are the shape.
  • Variadics, bitfields, records #pragma pack or packed actually narrows, flexible-array members, unions by value or without a lone scalar tag, C++ linkage, and unknown calling conventions.
  • A function pointer as a parameter: the adapter could hand the provider an address only by reinterpreting it as a signature it was not built with. The one reinterpretation this tree performs is narrower: a callback trampoline whose context slot is *mut c_void handed to a provider that declares that slot at another pointee type, which Rust’s ABI rules make the same call. As a result or a struct field it crosses as an address token FOL carries and never calls – Option<fn> casts to a raw pointer with as, which the parameter direction cannot do.
  • Adopting a provider’s allocation rather than copying it: FOL’s allocator did not make it and must not free it.
  • Raw pointers in an ordinary export: a raw pointer with no declared ownership and destroy pairing is refused, not defaulted.
  • An opaque handle inside a callback’s signature. A declared domain is read for a routine’s own parameters and result, but not for the parameters and result of a callback it takes, so a callback returning Widget * is refused as incomplete while the same Widget * binds as the routine’s own result. A callback returning a scalar beside it binds.

Evidence and failure policy

The required smoke test starts from the real build.fol graph route. It compiles a C provider object, scans its header through PARC, certifies the provider through LINC, projects raw Rust through GERC, materializes the raw and FOL-owned anchor crates through fol-build, passes exact ordered link arguments to fol-backend, and runs the linked executable. Its reported evidence contains:

  • the three locked sibling revisions;
  • source, target, link-analysis, generation, and provider fingerprints;
  • the exact certified target.

The checked build separately retains the exact generated raw-binding and anchor crate roots passed to the backend. The system test inspects the fixed anchor source, builds both crates, executes the final binary, and verifies the provider’s per-run return value.

Required negative cases prove that partial PARC source, unresolved LINC providers, and GERC generation rejection stop before generated/backend files are written. Target mismatch is rejected before compiler or output-directory I/O. A skipped system test is not success: the required Make target sets FOL_H7_REQUIRED=1 and supplies an explicit canonical GCC path.

The annotation overlay

C cannot say which of its declarations FOL may call, what a return code means, or who releases a pointer. The overlay is where a header author states those facts explicitly; the compiler never guesses them. It is a strict subset of TOML, and every key it does not recognize is refused rather than ignored.

version = 1

[routine.c_math_add_one]
error = "infallible"

[routine.c_math_checked_div]
error = "status"
status_ok = [0]
status_error = [1, 2]
out = "result"
effects = ["allocates"]

error admits exactly two conventions. errno, a last-error slot, an undocumented sentinel, unwind, and longjmp are each refused by name, with the reason, rather than falling through to “unknown value”: a convention FOL cannot check is one FOL will get wrong.

Handle domains

A pointer to an incomplete type is C’s opaque handle, and the pointer itself carries no ownership information at all. A domain declares one:

[handle.Widget]
destroy = "widget_free"

[routine.widget_new]
error = "infallible"
handle = "Widget"
handle_role = "produces"

[routine.widget_size]
error = "infallible"
handle = "Widget"
handle_role = "borrows"

[routine.widget_free]
error = "infallible"
handle = "Widget"
handle_role = "consumes"

The role is per routine, not per type, because the same Widget * is produced by one call, lent to many, and released by one. A producer’s handle is its result; a borrower’s or consumer’s is its single pointer parameter, and a routine with more than one pointer parameter is refused rather than having its handle chosen by position.

A producer that reports a status instead of returning the handle writes it through an out-parameter, which is how most C libraries actually spell it:

int sqlite3_open(const char *filename, sqlite3 **ppDb);

That needs no extra key. error = "status" must already name its out parameter, so that parameter is where the handle is taken from, and it must be a pointer to the handle – a single pointer would be the handle itself, which is what borrowing looks like. FOL never passes it: the adapter owns the storage, and reads it only for a status the overlay called success. examples/v4_c_sqlite is the whole path against a real database.

A routine that touches more than one domain names the extra ones. A statement is prepared from a connection, so sqlite3_prepare_v2 is handed one handle and produces another; libgit2 spells nearly its whole API that way:

int st_make(DB *db, ST **out);
[routine.st_make]
error = "status"
status_ok = [0]
out = "out"
handle = "ST"
handle_role = "produces"
handle_borrows = ["db"]

Only the parameters are named, never their domains. Which domain a pointer belongs to was measured from the header – a domain’s record is the pointee of its own destroy – so restating it would be a second spelling that could disagree with the first. What cannot be measured, and so is declared, is that the pointer is a handle at all rather than a struct FOL should read through. A parameter named here that is not a pointer to some domain’s record is refused, not guessed: the author has said “handle” about something that is not one, and treating it as an address anyway is how a destroy reaches the wrong thing.

Every handle named this way is borrowed. A routine may consume at most one, and that one is the handle_role = "consumes" handle, so a release always has exactly one place to look.

The domain is the identity. It becomes a distinct ABI type, so a handle from one provider can never reach another provider’s destroy — that is a type error rather than a runtime hazard. Four ways of making the identity incoherent are refused: a domain whose destroy is not a selected routine, a destroy that does not declare itself the consumer, a second consumer of one domain, and a routine naming a domain no [handle.<Name>] table declares.

Which routine owes the release is part of the interface fingerprint, so changing borrows to consumes invalidates every caller.

On the FOL side a handle is a linear resource: consumed exactly once, explicitly, on every path. The domain becomes a FOL type in the import’s namespace, so a program writes wid::Widget and the compiler proves the release. examples/v4_c_opaque_handle is the whole path, and the four examples/fail_v4_c_handle_* packages are the misuses C would compile.

A handle’s public fields

Some handles are not opaque at all: FreeType’s FT_Face points at a record whose num_glyphs and glyph a program is meant to read. A domain lists them, and names its record so the scan asks for the definition:

[handle.FT_Face]
destroy = "FT_Done_Face"
record = "FT_FaceRec_"
fields = ["num_glyphs", "glyph"]

[handle.FT_GlyphSlot]
record = "FT_GlyphSlotRec_"
fields = ["outline"]

Each field becomes a routine named <domain>_<field> that borrows the handle and reads the field, with no provider call behind it:

var glyphs: i64 = ft::FT_Face_num_glyphs([bor]face);
var slot: ft::FT_GlyphSlot = ft::FT_Face_glyph([bor]face);
var outline: ft::FT_Outline = ft::FT_GlyphSlot_outline([bor]slot);

A scalar field is copied out. A pointer to another domain’s record is handed back as that domain’s handle, and an embedded record as a handle to its address – but only for a borrow-only domain: what a record points at is the provider’s to free, so a domain with a destroy is refused as a field’s type. A field that is neither a scalar nor such a record has no value FOL could copy, and is refused too. See examples/v4_c_handle_fields.

A struct the provider fills in

stat(path, &st) is the shape: the caller supplies the storage and C writes into it. It reaches FOL through the status convention, because that is what says when the writes are worth reading:

int probe(int32_t v, struct S *out);
[routine.probe]
error = "status"
status_ok = [0]
status_error = [1]
out = "out"

The record comes back as FOL’s own value. The call site hands over the address of its own storage — FOL’s struct has the provider’s layout, checked at compile time — and the provider writes through it. The value is taken only on a code the overlay called success; on any other code it is discarded, because an unenumerated status means the provider did not say it wrote anything.

A record crosses by address, in every direction. FOL’s struct for an imported record is emitted #[repr(C)] with its fields in the header’s declaration order, so the address of FOL’s own value is an address of the provider’s struct: an argument is passed as that address, an out-parameter is written through it, and a value returned by C is written into storage the call site owns. Nothing is copied field by field, nothing is rebuilt, and the adapter never names FOL’s type.

A mutable struct T * is an out-parameter the provider writes through: the routine gets a [mut, bor] of a FOL value, and the writes land in it – the shape stat and lua_getinfo use. An imported record whose field FOL cannot spell – an opaque pointer, a wide char array – is built with a partial initializer: FOL names the fields it can, and the rest default, because the value exists to be filled. When no field is worth naming, the initializer is empty – {} – and every field defaults. This relaxation is imported-record-only; FOL’s own records still require every field. See examples/v4_c_out_record.

A derived struct where C declares its base

libuv declares uv_close(uv_handle_t *), and every handle type begins with the same UV_HANDLE_FIELDS, so C code casts: uv_close((uv_handle_t *)&timer, cb). The overlay says which record a parameter accepts instead:

[routine.uv_close]
error = "infallible"
upcast = ["handle"]
upcast_from = ["uv_timer_t"]

The bind checks that the derived record begins with every field of the base, by name, offset, and size, and refuses it otherwise; the parameter then takes the derived record, and the adapter hands C the same address typed as its base. See examples/v4_c_record_upcast.

A state aligned past its fields

libsodium’s streaming hash takes a crypto_generichash_state the caller owns:

#pragma pack(push, 1)
typedef struct __attribute__((aligned(64))) state { unsigned char opaque[384]; } state;
#pragma pack(pop)

The aligned(64) raises the record’s alignment past anything its bytes need and pads its size to a multiple of it, and the provider may rely on that alignment for every address it is handed. FOL’s struct for the record carries the same alignment – #[repr(C, align(64))] – so any value FOL owns is one the provider accepts, and the size and alignment assertions above still compare it with the provider’s own struct. #pragma pack is kept too: a record defined under it is measured under it, and packing that narrows nothing – a byte array – binds as ordinary layout. One that does narrow a field is refused, because FOL reads fields by address and a packed field has none that is aligned.

var state: dg::digest_state = {};
var started: i32 = dg::digest_init([mut, bor]state);

See examples/v4_c_aligned_state, whose provider refuses any state not 64-byte aligned.

That is a promise about layout, and it is checked rather than argued. The adapter re-exports the provider’s own struct, and the generated crate asserts its twin against it at compile time — size, alignment, and the offset of every field. Size and alignment alone would pass two structs whose fields were merely reordered, which is exactly the silent transposition this boundary produced once before; offset_of! per field is the check that cannot. A layout that drifted would fail the build naming the field, not hand C a wrong answer.

The declaration order is the part FOL’s type system does not keep — a checked record keys its fields by name — so it is carried down from the header separately, for imported records only. FOL’s own records stay Rust’s to lay out.

A field that is itself a struct needs nothing more: it is inline at its offset, with the same guarantee one level down. A field that is a fixed array needs nothing more either — char name[256] is 256 elements inline, which is what FOL’s arr[chr, 256] is — and this is the reason the address route was worth building: no flattening could have carried it.

An anonymous member is still refused, for a different reason. C makes its fields part of the outer struct, so o.x is valid there, while the projection puts them behind a generated name that is a content hash: FOL’s view of the struct would not be C’s, and the name is not one a program could write. Give the member a name, or lift it into a named struct.

An array parameter is refused as before: it decays to a pointer whose length C does not carry, and that is a different shape from an array inside a record.

Slots FOL does not pass

C carries parameters its own documentation tells callers to leave null: optional out-parameters nobody wants the answer from, reserved slots kept for a future version. sqlite3_prepare_v2 has one – pzTail is where the unused tail of the SQL would go, and there is none when the string holds one statement.

[routine.sqlite3_prepare_v2]
pass_null = ["pzTail"]

The parameter leaves FOL’s signature entirely. The adapter passes a null typed by the provider’s own declaration, which is the only place the pointee is named. Only a pointer may be declared this way – nothing else has a null a provider would recognise – and it is part of the interface, so adding or removing one invalidates every caller, exactly as unpairing a buffer does.

This is not a way to skip a parameter FOL cannot yet spell. It says the provider is being given nothing, and the provider has to be one that accepts nothing there.

Text coming back

A returned const char * is how every C library reports what went wrong: sqlite3_errmsg, lua_tostring, curl_easy_strerror, git_error_last.

[routine.sqlite3_errmsg]
error = "infallible"
string_result = true
handle = "sqlite3"
handle_role = "borrows"

It is declared for the same reason a string parameter is: const char * is how C spells text and equally how it spells a pointer to one byte, so nothing measured tells them apart, and a declaration the header cannot bear – a result that is not a pointer to characters – is refused rather than believed.

The difference from a parameter is ownership, and it is why this is a distinct type rather than the same one read by position. A parameter is lent to the provider for the length of one call. A result points into memory the provider owns and may reuse the moment you call it again – SQLite documents exactly that for sqlite3_errmsg – so lending it to FOL would be lending something with no lifetime to bound it. FOL is handed a copy instead, made before the call returns, and the question never arises. That is also why sqlite3_libversion, whose string is static and immortal, needs no second rule: copying makes the two lifetimes indistinguishable.

Two decisions the copy forces, both taken where C leaves them open. A NULL result is the empty string, the same reading a produced buffer gives it. And the bytes are decoded lossily, because C guarantees no encoding at all and one bad byte in an error message is not a reason to end a process.

Buffers

C carries a buffer as two parameters with nothing joining them: checksum(const uint8_t *bytes, size_t count) could as easily be a pointer and an unrelated tally. The overlay pairs them:

[routine.digest_sum]
error = "infallible"
buffer = "bytes"
buffer_length = "count"
reads = ["bytes"]

count then stops being a FOL parameter. The length is derived from the value FOL passes, so there is no second number a caller can get wrong and no way to describe a buffer longer than the one that exists. On FOL’s side it is a borrowed vector – bor[vec[u8]] when the provider only reads, a mutable loan when it writes.

A list of handles is a buffer whose elements point at a declared domain’s record – git_commit_create(..., size_t parent_count, const git_commit *parents[]). The same two keys pair it, and on FOL’s side it is a vector of loans, so each handle stays with the binding that owns it and is released there:

var parents: vec[g::git_commit[bor]] = {[bor]parent};
var created: i32 = g::git_commit_create([mut, bor]made, [bor]repo, [bor]who,
    [bor]who, [bor]message, [bor]tree, [bor]parents);

The call site builds an array of the handles’ addresses for the call and drops it after; the provider only reads it. See examples/v4_c_handle_array.

A written buffer has no length going in, only a count coming out – EVP_DigestFinal_ex(ctx, unsigned char *md, unsigned int *s) writes up to EVP_MAX_MD_SIZE bytes and says through s how many. The overlay names the buffer, the pointer the count returns through, and the room the provider needs:

[routine.EVP_DigestFinal_ex]
error = "infallible"
handle_borrows = ["ctx"]
written_buffer = "md"
written_length = "s"
written_capacity = 64

The caller passes a mutable loan of a vector with at least that much room; a shorter one is refused before the call, since C would write past its end. The adapter owns the count, refuses a report larger than the vector, and the vector comes back shortened to exactly what was written. See examples/v4_c_written_buffer.

When the count also carries the room in, as zlib’s compress(Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) does, written_length_in = "capacity" starts the count at the vector’s length. A written buffer may sit under a status convention; its out is then the count, and the count is the success value:

[routine.compress]
error = "status"
status_ok = [0]
status_error = [-2, -4, -5]
out = "destLen"
written_buffer = "dest"
written_length = "destLen"
written_length_in = "capacity"
written_capacity = 1
buffer = "source"
buffer_length = "sourceLen"
var packed_length: u64 = zz::compress([mut, bor]packed, [bor]data) || 0;

The vector is shortened to the count only on a success status; on a failure it comes back empty, because nothing the provider wrote may be read. See examples/v4_c_zlib.

Direction is declared, not read off constness. reads, writes, and reads_writes name the parameters they apply to. Constness stays the default, but it is a poor witness: void *base in qsort is read and written, char *dst in strcpy is only written, and a mutable pointer a provider never writes looks like either. A declaration C contradicts – writes on a const pointee, or any direction on a by-value parameter – is refused.

An owned buffer is memory the provider allocated, and it gets a domain and a release, exactly like a handle:

[buffer.Bytes]
destroy = "digest_release"

[routine.digest_take]
error = "infallible"
buffer_domain = "Bytes"
buffer_role = "produces"
buffer_length = "out_len"
buffer_capacity = "out_capacity"

[routine.digest_release]
error = "infallible"
buffer_domain = "Bytes"
buffer_role = "consumes"
buffer_length = "count"

FOL never adopts that memory. Its allocator did not make the allocation and must not free it, so the adapter validates the report, copies out of it, and calls the release before returning. What FOL holds afterwards is its own vector pointing nowhere near the provider’s heap, and the destroy is not mountable: there is nothing left for a program to release, and no address to release it with.

Two ways a provider can contradict itself are refused rather than read: a null address with a nonzero length, which describes memory that does not exist, and a length past the capacity it reported, which describes memory it did not allocate. Copying on either reads whatever happened to be there. The capacity is what makes the second checkable – a length on its own is unfalsifiable.

The domain gets the same four cross-checks a handle domain does: a destroy that is not a selected routine, a destroy that does not declare itself the consumer, a domain with no producer or more than one, and a routine naming a domain no [buffer.<Name>] table declares.

examples/v4_c_buffer runs all three shapes and asks the provider how many allocations are outstanding afterwards – the answer is 0, and FOL cannot see C’s heap any other way. examples/fail_v4_c_buffer_capacity and fail_v4_c_buffer_null are the two contradictions.

C enums

A C enum crosses as the integer the provider’s compiler stores it in. That storage is measured, not read off the spelling: GCC stores enum color { RED, GREEN = 4, BLUE = 9 } as u32 because no enumerator is negative, and an enum with a negative enumerator as i32. The enumerators are constants of the import, so FOL code names them instead of writing their numbers:

enum color { RED, GREEN = 4, BLUE = 9 };
int32_t paint(enum color c);
var painted: i32 = prb::paint(prb::GREEN);

prb::GREEN is a u32 holding 4, the type paint declares for its parameter. Each value is the one the provider’s compiler measured – GERC refuses an enumerator whose written value disagrees with the measurement – and the manifest records it under constants, so a changed value moves the interface fingerprint and a build against the old manifest is refused as stale. A constant is a value, not a binding: assigning to one is refused.

The constants carried are those of every enum the bound surface reaches: one a bound routine takes or returns, or one a field of a record it passes is declared with. An enum no bound routine reaches is not carried, by the same rule that keeps a header’s other declarations out of the surface. A routine that declares int and documents an enum beside it, as libgit2’s error codes are spelled, reaches no enum.

A value naming no enumerator crosses unchanged. C gives an enum no closed set of values: any value of its storage type is a valid enum color, and providers rely on that for flag combinations and for codes newer than the caller’s header. So an imported enum is a FOL scalar, not an entry, and a value outside its enumerators is neither refused nor clamped, in either direction: prb::paint(42) hands C 42, and a provider returning (enum color)77 hands FOL 77. A FOL entry is the opposite case: its variants are closed, so an exported entry whose tag arrives from C naming no variant is refused with FOL_STATUS_INVALID_ARGUMENT (below).

FOL names ignore case and underscores, so JSON_OBJECT and json_object are one name. A bound routine keeps such a name and the enumerator is not mounted. Two enumerators that fold to one name are both mounted, and a use of either is reported as ambiguous, naming both. test/v4_c_shapes.rs runs all of this against a provider.

Entry discriminants

An entry crosses as a C enum, and a C enum’s values are part of the ABI: they are written to files and sent over wires. So FOL will not pick them. Each variant states its own tag:

typ[exp] Lookup: ent = {
    con[tag = 4] MISSING;
    con[tag = 1] FOUND;
    con[tag = 9] DENIED;
};

[tag = N] is not a default value. con NAME: int = 7 gives the variant a default payload of 7, and var Ok: int = 1 beside var Err: str = "broken" shows why that cannot double as a tag — both variants would land on 1. The two are different things and are now spelled differently.

An entry with no tags is refused outbound with UnstableEntryTag, naming the entry. Its variants are numbered by position, which is fine inside FOL and cannot be promised to anyone holding a stored value: inserting a variant would renumber every later one.

Three ways of tagging incoherently are refused at parse time: a duplicate tag, a tag outside the 32-bit range the discriminant carries, and a partially tagged entry, where the untagged variants would fall back to the position the tags exist to escape.

Because a tag is stated rather than positional, reordering the declaration is a no-op: the manifest is byte-identical, and fol tool abi check reports the surface unchanged. Changing a tag is the opposite — a breaking change, refused without --allow-breaking. examples/v4_c_export_entry crosses both directions; examples/fail_v4_c_entry_error is the untagged refusal.

Synchronous callbacks

A C routine that calls back needs a function pointer and somewhere to keep the caller’s state. C cannot say which void * belongs to which function pointer, so the overlay does:

[routine.tally_range]
error = "infallible"
callback = "step"
callback_context = "context"

Neither position is a FOL parameter. FOL passes a closure and fills the context itself, with that closure’s address, so the pairing cannot be got wrong:

var total: int[32] = tal::tally_range(4, fun(a: int[32], v: int[32]): int[32] = {
    return a + v;
});

Bridging the two is a generated trampoline — a monomorphic extern "C" shim nested inside the one call site, which recovers the closure from the context and calls it. A Rust closure carries an environment and a C function pointer has nowhere to put one; the trampoline is where that gap is closed.

Two shapes are imported. The function pointer hands the context back as its first parameter (expat, SQLite) or its last (libgit2, curl):

int tally_range(int upto,
                int (*step)(void *context, int accumulator, int value),
                void *context);
int tally_range(int upto,
                int (*step)(int accumulator, int value, void *context),
                void *context);

The context is the parameter whose type is the context argument’s own type, not merely a pointer: git_reference_foreach_cb(git_reference *ref, void *payload) hands back its payload last, and the reference first is an argument the closure receives. A context anywhere else is refused at bind time rather than guessed at, because guessing wrong hands the closure the wrong arguments – examples/fail_v4_c_callback_shape.

The trampoline enforces two rules rather than documenting them. A null context means the callback was invoked outside the call that lent the closure. A fault inside the callback cannot travel further: unwinding out of extern "C" is undefined, and a callback has no status channel — the provider is mid-call and takes only a return value. Both end the process, naming the symbol, rather than returning a value nobody computed.

What FOL does not enforce is what the provider does after the call returns. Retention, reentry, and cross-thread invocation are all provider behaviour that nothing on FOL’s side observes. FOL’s half of the contract holds structurally — the closure is a local, so the context cannot outlive the call — and the null-context check catches the one detectable case. A real guarantee would need a generation counter in the context and a provider-side destroyer, which V4 does not build.

See examples/v4_c_callback, examples/v4_c_callback_context_last, examples/fail_v4_c_callback_panic, and examples/fail_v4_c_callback_shape.

A callback the provider keeps

The synchronous model has one window: the closure is reachable while the call that lent it is on the stack, and a provider that invokes it later finds the slot empty and is refused. Real libraries keep callbacks on purpose. SQLite’s busy handler and hooks, expat’s element handlers, and Lua’s C functions are all installed by one call and invoked by others, and every one of them binds today and ends the process on first use. The overlay says who keeps it:

[routine.relay_on]
error = "infallible"
handle_borrows = ["r"]
callback = "handler"
callback_context = "context"
callback_kept_by = "r"

A routine that installs several callbacks at once – expat’s XML_SetElementHandler(parser, start, end) – names them as a list: callback = ["start", "end"]. Each gets its own trampoline and, if kept, its own slot on the keeper; the context, the keeper, and the text positions are shared, and a text position one of them lacks is simply not that one’s.

callback_kept_by names a handle this routine borrows. Three things follow:

  • The closure is moved, not lent. Its captures must be owned ([mov], [cpy], [cln]); a closure holding [bor] captures is refused, because nothing bounds how long the provider will hold it.
  • The keeper owns it. FOL boxes the closure into storage keyed by the keeper’s address and passes that box’s address as the context. The trampoline reads the closure through the context, so there is no window: any later call on that handle may invoke it. Installing a second handler keeps both until the handle is released.
  • The destroy releases it. The consumes call on that domain drops every closure the handle kept, after the provider’s own destroy has run, so a destroy that invokes the handler one last time still finds it.

A kept callback needs a real context: callback_context = "none" with callback_kept_by is refused, because without a context there is nothing the provider hands back to find the closure by. A provider that keeps its context somewhere other than the call that installs the callback — expat’s XML_SetUserData — is not yet importable.

See examples/v4_c_callback_kept, and examples/v4_c_sqlite, whose progress handler is one: SQLite keeps it on the connection and fires it from inside sqlite3_step.

Found by its keeper

Some providers hand a kept callback no context at all, only the handle that keeps it. Lua’s C functions are the shape: int (*)(lua_State *), installed by lua_pushcclosure(L, fn, 0) and invoked with the same L. The overlay says the keeper is the key:

[routine.lua_pushcclosure]
error = "infallible"
handle_borrows = ["L"]
callback = "fn"
callback_context = "keeper"
callback_kept_by = "L"

callback_context = "keeper" requires callback_kept_by, and the callback’s first parameter must be a pointer to the keeper’s own record; it is refused otherwise. Nothing is hidden from the closure: it receives that handle as a borrowed lua_State[bor], because the provider still owns it, and reads and writes the Lua stack through it. A handle handed to any callback is typed as a loan for the same reason.

See examples/v4_c_lua, where Lua code calls twice(21) and the answer is computed inside a FOL closure.

Found through user data a setter installs

expat is the third shape: its handlers receive a void *userData, but no handler setter takes one – XML_SetUserData(parser, p) installs it once, and the parser hands it to every handler. The overlay says the slot is FOL’s:

[handle.XML_Parser]
destroy = "XML_ParserFree"
context_setter = "XML_SetUserData"

[routine.XML_SetStartElementHandler]
error = "infallible"
handle_borrows = ["parser"]
callback = "handler"
callback_context = "keeper"
callback_kept_by = "parser"

context_setter names a selected routine that takes exactly the domain’s handle and a void *; anything else is refused. Installing a kept handler installs the keeper’s own address through it, before the installing call, and the trampoline finds the closure by that address as it would through any context. The setter itself is not mounted: a program that could call it could overwrite the slot every kept handler on the parser is found through. The handler’s void * is hidden from the closure, as a context always is.

See examples/v4_c_callback_user_data.

A struct of callbacks the caller fills

FreeType walks an outline through FT_Outline_Decompose(outline, const FT_Outline_Funcs *funcs, void *user): the callbacks are fields of a struct the caller fills, all handed user back. callback_table names that parameter, and callback then names its fields:

[routine.FT_Outline_Decompose]
error = "infallible"
handle_borrows = ["outline"]
callback_table = "func_interface"
callback = ["move_to", "line_to", "conic_to", "cubic_to"]
callback_context = "user"

FOL passes one closure per named field, in that order. The adapter builds the struct around their trampolines, leaves every other field – which must be a scalar – zero, and hands C its address. A callback’s const FT_Vector * arrives as a borrowed handle of a declared domain, read through its fields:

var walked: i32 = ft::FT_Outline_Decompose([bor]outline,
    pro(to: ft::FT_Vector[bor]): i32 = {
        std::io::echo_int(ft::FT_Vector_x(to));
        return 0;
    }, ...);

The struct the adapter fills is its own repr(C) mirror of the provider’s, asserted field by field against it: FOL spells a callback’s pointer arguments its own way, and Rust casts no function pointer to another. See examples/v4_c_callback_table.

Text inside a callback signature

A parser reports element names to its handler as const char *, and the provider’s bytes are valid only during the callback. A function pointer’s parameters have no names, so the overlay names the text by position in the C signature, counting from zero with the context slot included:

[routine.XML_SetStartElementHandler]
error = "infallible"
handle_borrows = ["parser"]
callback = "handler"
callback_context = "keeper"
callback_kept_by = "parser"
callback_strings = [1]

A NULL-terminated list of text – expat’s attribute pairs, const char ** – is callback_string_lists, and reaches the closure as a vec[str] of its own, each element copied; a null list is an empty one.

The closure receives that position as a str of its own, copied for the invocation. Copied rather than lent, for the same reason a returned string is: there is nothing to lend from once the provider reuses its buffer, and a copy has no lifetime to spell. A position that is not const char *, or is the hidden context, is refused; a provider that passes NULL where it declared text ends the process, naming the routine.

See examples/v4_c_callback_text, and the expat lane in test/v4_c_expat.rs, where a kept comment handler on a real libexpat.so receives the comment’s text through all three keys at once.

Verification commands

Run these on GNU/Linux from the FOL root with parc, linc, and gerc as sibling checkouts:

make interop-check interop-locked test-interop
  • make interop-check runs the offline tier: every component pinned to a 40-character revision rather than a branch or a path, no [patch] entry substituting one, this page still quoting the revisions in force, and compilation of the typed integration. It needs no network.
  • make interop-locked adds --locked resolution, proving the pins resolve exactly as committed with no network access and no manifest edit.
  • make test-interop depends on the locked check, requires Linux and GCC, and runs the positive and fail-closed native H7 tests without an optional-skip path.

CI checks out only FOL and invokes the same Make-owned locked smoke gate; cargo fetches the pinned components. Moving a component means updating fol-interop/Cargo.toml, Cargo.lock, and this snapshot together — the check fails the moment the book stops quoting the revisions in force.

Working on a component locally without editing the pins:

# ~/.cargo/config.toml
[patch."https://github.com/fol-lang/parc"]
follang-parc = { path = "/absolute/path/to/parc" }

This boundary does not expose general foreign declaration syntax, general pointers or ownership, C++ ABI support, Rust facade generation, or a stable Rust binary ABI. C export and bounded header import are built on top of it and are described above.

ABI versioning

A library that other people link needs to say when its surface changed, and to distinguish that from having been rebuilt. An exporting artifact declares a version beside its exports:

lib.set_abi_version({ major = 1, minor = 0 });
lib.add_abi_export({ routine = "add_i32", symbol = "fol_slice_add_i32" });

The installed manifest carries two fingerprints, and the split is the whole point. The interface fingerprint covers what a caller can see: symbols, types, layouts, error contracts, ownership. The build fingerprint covers how the surface was produced — compiler, component revisions, link inputs. A new compiler moves the build fingerprint and leaves the interface fingerprint alone, so a toolchain upgrade does not read as an ABI event.

fol tool abi check --baseline <MANIFEST> --candidate <MANIFEST> compares a checked-in baseline against a freshly built manifest and reports one of four verdicts:

VerdictMeaning
unchangedthe interface is identical; if the build fingerprint moved, it says so
compatiblesymbols were added and nothing existing changed
breakingan existing symbol, type, layout, or contract changed
target mismatchthe two manifests describe different targets

A break is accepted only with --allow-breaking, which says this break is intended and belongs in the command that ran rather than in a file someone edited. A target mismatch is never accepted by that flag: nothing about the source changed, so treating it as an intended break would send a reader looking for a change that is not there.

Both commands read written manifests and nothing else — no package root, no compilation — because an installed prefix and an extracted release archive are exactly where a consumer needs to ask what a library’s C surface is, and neither has a source tree. Reading recomputes both recorded fingerprints, so a hand-edited manifest is refused rather than compared.

fol tool abi package --prefix <DIR> --out <ARCHIVE> turns an installed prefix into a release archive carrying the headers, libraries, manifests, a CHECKSUMS.sha256 any consumer can verify with sha256sum -c, a PROVENANCE record, and an SBOM naming the pinned components that measured the layouts. It refuses a prefix containing generated Rust or a Cargo manifest rather than filtering them out: that is implementation, not interface, and a prefix holding it is a bug worth reporting rather than papering over.