zplugin 0.3.1

Project Z native plugin ABI and optional fuel-metered WebAssembly sandbox
Documentation
# C, C++, and Zig plugins

The shared Rust interface is the source of truth for every language. `ForeignApi::write_c_header` generates the argument records, return records, complete method signatures, stable value layouts, and descriptor initializers. C11 and C++17 include the resulting header. Zig imports the module produced by `zig translate-c` from that same header.

## Run the complete example

From the repository root, with Rust and Python 3.12 or newer:

```sh
python scripts/foreign.py --install-zig
```

The script downloads the official Zig archive into `target/`, verifies its pinned SHA-256 checksum before extraction, generates the declarations, builds three native dynamic libraries, and loads all three with the Rust host. The compiler pins are **Zig 0.15.2 on macOS** and **Zig 0.17.1 on Linux/Windows**. It uses the platform C/C++ compilers when available on Linux and macOS; Zig's C/C++ drivers provide the Windows fallback. No compiler or runtime is added to the published Rust runtime dependencies.

The macOS pin is a compiler compatibility choice. Zig 0.17.1's native macOS `translate-c` exceeded the 300-second command deadline [in CI](https://github.com/LIghtJUNction/zplugin/actions/runs/43374671134/job/131718250206), before any Zig plugin could be built or loaded. This is a translation-stage failure, not a failing plugin ABI assertion. The macOS job still generates declarations, builds and loads all three native libraries, and must pass the same contracts; no language test is skipped.

On macOS, Zig emits position-independent object code with its compiler helpers, and the platform C driver links the final `.dylib` against the installed Apple SDK. This separates Zig code generation from SDK library resolution; the older Zig linker's unresolved `libSystem` symbols [were observed in CI](https://github.com/LIghtJUNction/zplugin/actions/runs/43375797132/job/131721913397). Linux and Windows use Zig's shared-library linker directly.

To use an existing installation matching the platform's pinned version:

```sh
python scripts/foreign.py --zig /path/to/zig
```

Build products and the generated `foreign.h` / `foreign.zig` files are in `target/foreign/`. The test writes machine, compiler, and contract results to `artifacts/foreign-<platform>.json` only after all three libraries pass. CI runs the same script on Linux, macOS, and Windows for stable Rust.

## Generate declarations for your interface

`interface/src/lib.rs` contains ordinary shared Rust definitions:

```rust
#[zplugin::abi_type(id = "foreign.point", version = 1)]
#[derive(Clone, Copy)]
pub struct Point {
    pub x: i32,
    pub y: i32,
}

#[zplugin::interface(id = "my.plugin", version = 1)]
pub trait Calculator {
    fn add(&mut self, point: Point) -> zplugin::Result<i64>;
}
```

In a small build tool that depends on the shared crate, call `CalculatorApi::write_c_header(&mut writer)`. The writer implements `core::fmt::Write`; the generator itself does not require `alloc` or `std`. The example host exposes this operation directly:

```sh
cargo run --locked -p zplugin-foreign-tests -- --header target/foreign/foreign.h
```

The C header names each method's input record `Foreign_<method>_args` and its output `Foreign_<method>_out`. Fields are `arg_0`, `arg_1`, and so on. `Foreign_<method>_METHOD(function)` initializes a method entry with its exact generated signature. `Foreign_INTERFACE_INIT(methods, create, destroy)` initializes the complete interface descriptor. The plugin exports only the version-fixed `zplugin_entry_v1` entry required by the loader.

`plugin.c` implements these adapters in C11. `plugin.cpp` compiles the shared implementation as C++17 and contains an exception boundary that invalidates the affected object. `plugin.zig` implements the same methods in Zig. Its C declarations are generated by the following build operation, which `scripts/foreign.py` executes automatically:

```sh
zig translate-c -lc -I target/foreign examples/foreign/zig_api.h
```

The command writes a Zig module to stdout. The test script saves it as `foreign.zig` and supplies it as the `cabi` module when compiling `plugin.zig`. Translation and compilation use the same native target. For cross-compilation, both operations and the Rust host must use matching target ABI settings.

## Contracts exercised

| Interface operation | Wire representation and assertion |
| --- | --- |
| `calculate` | Named `Point` struct and validated `u32` enum; sum and product |
| `echo` | Tagged union with empty, numeric, and nested-struct payloads; all variants round-trip |
| `transform` | Borrowed input and caller-owned output; empty input, short output, unchanged short buffer |
| `owned` | Origin-allocated bytes and matching release function; retained after the object drops |
| `start` | Independent task handle; Pending, retained waker, wake, Ready, cancellation, release |
| `resource` | Typed opaque resource; ID/version checks, operation dispatch, independent library lease |
| `callback` | Borrowed callback with explicit retain/invoke/release; Rust panic becomes an error and poisons the callback |

The task examples intentionally wake during the first poll and complete on the next poll. This tests the cross-library poll/waker protocol without relying on timer scheduling; the task performs no blocking wait. Rust worker-thread tests cover delayed cross-thread wakeups separately. General callbacks and resource calls remain serialized on the creating thread. The waker protocol alone permits concurrent wake/retain/release operations.

## Ownership and trust

The caller owns borrowed input and output buffers for the duration of a call. Each returned buffer, resource, and task owns its origin allocation and must invoke its matching release function. The host wrappers keep the library loaded until those releases finish. A stored waker or callback must first be retained and later released exactly once. The examples count every plugin-owned allocation; cooperative quiescence returns Busy until that count reaches zero.

Output records are initialized only on success. A successful task poll initializes its typed output only when its state is Ready. C/C++ and Zig implementations must initialize the selected tagged-union payload, reject unknown tags, contain exceptions or panics before an ABI return, and obey pointer, aliasing, thread, and descriptor-size contracts. Native libraries run with the host process's privileges; ABI validation provides compatibility checks, not execution isolation.