Contents

C FFI is discouraged in Haze. The reasons are not stylistic. An extern function has no Haze contracts, cannot be marked pure, and operates on C types rather than on Haze's managed values. Every property that the rest of the language works to establish has to be re-established by hand at the boundary, or trusted without evidence.

The policy is therefore simple: use FFI only when the language and the standard library do not provide the capability, keep the extern surface as small as possible, and expose a checked Haze API on top.

When FFI Is Justified#

Situation FFI appropriate Reason
A platform API has no standard-library wrapper Yes The capability is genuinely outside the language
An existing C library implements the required algorithm Yes, if adopting it is cheaper than reimplementing Interoperation is the point
A binary ABI must be matched exactly Yes The layout and calling convention are the specification
A Haze library already provides the operation No Use the library
The C version is assumed to be faster No Measure first; the boundary has real costs
The author prefers C syntax No The program loses contracts, safety, and portability
A temporary shortcut to avoid designing a Haze type No The shortcut becomes permanent

A performance argument is only credible after measurement. The FFI boundary involves a foreign call, marshalling, and a loss of compiler knowledge about effects. A Haze implementation is often faster than expected and is always easier to verify.

The Shape of a Boundary#

A good boundary has three layers. The innermost layer is the extern declaration. The middle layer converts between C and Haze representations. The outer layer is an ordinary Haze function with contracts, precise types, and Result errors.

extern (C) getenv(name cstr) cstr = "getenv"

type EnvError =
    | Missing(name str)
    | Invalid(name str)

fn require_env(name str) Result[str, EnvError] {
    const value = getenv(cstr::from_str(name))
    if cstr::is_null(value) {
        return Error(Missing(name))
    }
    return match cstr::to_str(value) {
        Success(text) => Success(text)
        Error(_) => Error(Invalid(name))
    }
}

The extern declaration is one line and is not exported from the module. require_env is the public API; it takes a Haze string, returns a Haze Result, and names its error cases. A caller never sees a cstr or a null pointer.

This is the pattern to follow for every foreign call. The raw declaration is private, the conversion is immediate, and the public function states the Haze-level contract.

Extern Functions#

An extern function is declared with the C calling convention, a parameter list, an optional return type, and the symbol name as a string.

extern (C) abs(x i32) i32 = "abs"
extern (C) puts(text cstr) i32 = "puts"
extern (C) getpid() i32 = "getpid"

Only extern (C) is supported. An omitted return type means void. The symbol string is required. Extern functions cannot have a body, contracts, generic parameters, or the pure modifier. They also cannot be used as first-class function values, because there is no Haze function body to call through a closure.

The lack of contracts is notable here. A Haze caller cannot rely on a postcondition, and the compiler cannot fold a call. The wrapper must validate the result and translate it into a Haze type.

Extern Records#

A C-layout struct is declared with the extern keyword in the type body.

type DivResult extern {
    quot i32
    rem i32
}

extern (C) div(num i32, den i32) DivResult = "div"

Fields must be scalar, ptr, or cstr. Managed types such as List, records, sums, and Option are not allowed. Extern records cannot be generic and cannot declare invariants. They are copied by value when stored in a local, which matches the C semantics but differs from ordinary Haze records.

Extern values are not allowed inside ordinary records, sum variants, or lists. The restriction prevents a managed value from accidentally holding an unmanaged C-layout value whose lifetime the collector does not understand.

type Pair extern {
    left  i32
    right i32
}

fn sum(pair Pair) i32 => pair.left + pair.right

The function above is fine because Pair is passed by value and never stored in a managed container. A function that needs a collection of C-layout values should copy them into Haze records at the boundary.

C Strings and Pointers#

cstr is a nullable pointer to a null-terminated byte sequence. It is the type for C string parameters. cstr::from_str creates a cstr view of a Haze string, cstr::to_str converts back and returns Result[str, CStrError], and cstr::is_null tests for null.

const value = getenv(cstr::from_str("HOME"))
if !cstr::is_null(value) {
    match cstr::to_str(value) {
        Success(text) => print(text)
        Error(_) => print("invalid UTF-8")
    }
}

ptr is an opaque pointer. It supports equality and ptr::add, and it can be created from a cstr or from a byte buffer. There is no dereference syntax and no pointer arithmetic operator; the built-in helpers are the entire interface.

The lifetime of a C pointer is not tracked by Haze. If a C function returns a pointer to memory that the caller must free, the wrapper must document that ownership and expose a Haze API that performs the free. If a C function retains a pointer after the call, the wrapper must ensure the pointee outlives the retention. The collector does not know about either case.

Linking#

The compiler invokes a C compiler to assemble and link the generated code. Additional libraries are passed with -l and search directories with -L.

hz app.hz -L/usr/local/lib -lexample

The default is static linking. -d requests dynamic linking. On Unix, -lm is added automatically. The runtime archive is found next to the compiler, through HAZE_RUNTIME, or through -runtime. These flags are documented in the Command-Line Tool reference.

Platform Variation#

A foreign API often differs by platform. Use @cfg to select the declaration and the wrapper, rather than defining a single extern that only works on one operating system.

@cfg(family == unix)
extern (C) getuid() u32 = "getuid"

@cfg(family == windows)
fn user_id() u32 => 0

The @cfg condition is evaluated at compile time, so the unused declaration is not part of the program. The Conditional Compilation chapter lists the available keys and operators.

Rules for the Boundary#

Rule Reason
Keep extern declarations private Callers should depend on the Haze API, not the C ABI
Convert to Haze types immediately Managed values and contracts do not cross the boundary
Return Result for foreign failures C error codes and null pointers are expected failures
Validate lengths and ranges before the call The C function will not check Haze preconditions
Document ownership of returned pointers Haze does not track foreign lifetimes
Do not expose cstr or ptr in a public signature They leak an unmanaged representation into the domain
Wrap platform variation in @cfg A single declaration cannot be portable
Do not pass managed values through an opaque pointer The collector cannot see the foreign use
Measure before claiming a performance benefit The call and marshalling have costs

A Wrapper Checklist#

Question Required answer
Is the capability unavailable in Haze? Yes, or use the Haze library
Is the extern declaration private? Yes
Does the public function take and return Haze types? Yes
Are foreign errors translated to Result? Yes
Are null, length, and range checks performed? Yes
Is pointer ownership documented and enforced? Yes
Is platform variation handled with @cfg? Yes, where needed
Is the wrapper tested on every supported platform? Yes
Is the FFI isolated in a module with a small surface? Yes

What FFI Costs#

The boundary gives up four things. Contracts no longer describe the foreign call. Purity no longer means anything, because the compiler cannot see the effects. Managed values cannot cross, so every list, string, record, and sum must be converted. And the foreign memory model is not the Haze memory model, so lifetime and ownership become manual.

A program can still use FFI well. It does so by treating the boundary as a small, carefully tested adaptor and keeping the rest of the program in Haze. The mistake is letting the C representation leak into the domain, so that every function starts to look like the ABI it was meant to hide.

Summary#

Layer Responsibility Example
Extern declaration Name the symbol and the C signature extern (C) getenv(name cstr) cstr = "getenv"
Conversion Translate between C and Haze representations cstr::to_str
Checked API State contracts, return Result, hide raw types require_env(name str) Result[str, EnvError]

The final chapter, Review Checklist, collects the questions from this section into a compact review guide.