Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .machine_readable/contractiles/Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ security-test:
binding-inventory:
bash tests/binding_inventory.sh

# Native-connector pilot: C, Rust and Julia through ps_invoke (proven-amqp).
native-connector-smoke:
bash tests/native_connector_smoke.sh

e2e:
bash tests/e2e.sh

Expand Down
4 changes: 4 additions & 0 deletions Justfile
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ security-test:
binding-inventory:
bash tests/binding_inventory.sh

# Native-connector pilot: C, Rust and Julia through ps_invoke (proven-amqp).
native-connector-smoke:
bash tests/native_connector_smoke.sh

e2e:
bash tests/e2e.sh

Expand Down
190 changes: 190 additions & 0 deletions ffi/zig/connector/ps_connector.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//
// ps_connector.zig -- the uniform native-connector dispatcher (pilot).
//
// A protocol exports three C symbols:
//
// uint32_t ps_abi_version(void);
// const char * ps_manifest(void); // the Idris2-emitted manifest, NUL-terminated
// uint8_t ps_invoke(uint16_t fn_tag, const ps_value *args, uint32_t n,
// ps_value *out);
//
// A connector in any language binds only those three, reads the manifest to
// learn the function table, and calls through ps_invoke. One connector per
// language then serves every protocol that exports this surface.
//
// The function table, kind tags, status tags and value-cell layout all come
// from the protocol's generated `<name>_abi_gen.zig`, which tools/gen-abi.sh
// renders from the Idris2 `<Name>ABI.Connector` module. `Dispatcher` checks
// at comptime that every table entry names a real export whose Zig parameter
// types match the Idris2 kinds, so drift is a build error, not a runtime bug.
//
// The Zig code here is FFI only (pure Zig). The ABI it is checked against is
// pure Idris2.

const std = @import("std");

/// One argument or result cell. 32 bytes on every target (see the
/// PS_VALUE_* layout constants in the generated file).
pub const Value = extern struct {
kind: u8,
_pad: [7]u8 = [_]u8{0} ** 7,
word: u64 align(8) = 0,
addr: u64 = 0,
len: u64 = 0,
};

/// Logical kind of a Zig parameter or result type.
fn kindOf(comptime T: type) []const u8 {
if (T == void) return "VOID";
if (T == c_int or T == i32) return "I32";
if (T == u8) return "U8";
if (T == u16) return "U16";
if (T == u32) return "U32";
if (T == u64) return "U64";
@compileError("ps_connector: unsupported type " ++ @typeName(T));
}

fn isBytesPtr(comptime T: type) bool {
return T == [*]const u8;
}

/// The space-separated logical kinds of a function's parameters. A
/// `[*]const u8` followed by a `u32` is one BYTES argument.
fn paramKinds(comptime F: type) []const u8 {
const params = @typeInfo(F).@"fn".params;
comptime var out: []const u8 = "";
comptime var i: usize = 0;
inline while (i < params.len) {
const P = params[i].type.?;
const k = if (isBytesPtr(P)) blk: {
if (i + 1 >= params.len or params[i + 1].type.? != u32)
@compileError("ps_connector: a [*]const u8 parameter must be followed by its u32 length");
i += 2;
break :blk "BYTES";
} else blk: {
i += 1;
break :blk kindOf(P);
};
out = if (out.len == 0) k else out ++ " " ++ k;
}
return out;
}

fn logicalArity(comptime kinds: []const u8) usize {
if (kinds.len == 0) return 0;
return std.mem.count(u8, kinds, " ") + 1;
}

const empty_bytes = [_]u8{0};

/// Build the dispatcher for one protocol.
/// impl -- the protocol's Zig file (`@This()`), holding the exports
/// prefix -- the export prefix, e.g. "amqp_"
/// gen -- the generated `<name>_abi_gen.zig`
pub fn Dispatcher(comptime impl: type, comptime prefix: []const u8, comptime gen: type) type {
return struct {
comptime {
if (@sizeOf(Value) != gen.PS_VALUE_SIZE) @compileError("ABI drift: ps_value size");
if (@alignOf(Value) != gen.PS_VALUE_ALIGN) @compileError("ABI drift: ps_value align");
if (@offsetOf(Value, "kind") != gen.PS_VALUE_OFF_KIND) @compileError("ABI drift: ps_value.kind");
if (@offsetOf(Value, "word") != gen.PS_VALUE_OFF_WORD) @compileError("ABI drift: ps_value.word");
if (@offsetOf(Value, "addr") != gen.PS_VALUE_OFF_ADDR) @compileError("ABI drift: ps_value.addr");
if (@offsetOf(Value, "len") != gen.PS_VALUE_OFF_LEN) @compileError("ABI drift: ps_value.len");

@setEvalBranchQuota(200_000);
for (gen.FNS, 0..) |f, i| {
if (f.tag != i + 1) @compileError("ABI drift: FN tags must run 1..n in order, at " ++ f.name);
const sym = prefix ++ f.name;
if (!@hasDecl(impl, sym)) @compileError("ABI drift: Idris2 lists " ++ sym ++ " but Zig has no such export");
const F = @TypeOf(@field(impl, sym));
const ret = kindOf(@typeInfo(F).@"fn".return_type.?);
if (!std.mem.eql(u8, ret, f.ret))
@compileError("ABI drift: " ++ sym ++ " returns " ++ ret ++ ", Idris2 says " ++ f.ret);
const got = paramKinds(F);
if (!std.mem.eql(u8, got, f.kinds))
@compileError("ABI drift: " ++ sym ++ " takes (" ++ got ++ "), Idris2 says (" ++ f.kinds ++ ")");
}
}

fn status(comptime name: []const u8) u8 {
return @field(gen, "STATUS_" ++ name);
}

fn kindTag(comptime name: []const u8) u8 {
return @field(gen, "KIND_" ++ name);
}

fn decodeInt(comptime P: type, comptime kname: []const u8, v: Value) ?P {
if (v.kind != kindTag(kname)) return null;
if (P == c_int or P == i32) {
// I32 travels sign-extended in the u64 word. Decode it with
// plain integer arithmetic: words up to maxInt(i32) are the
// non-negatives, words from 0xFFFF_FFFF_8000_0000 up are the
// two's-complement negatives, and anything between is RANGE.
const max: u64 = std.math.maxInt(i32);
const neg_floor: u64 = 0xFFFF_FFFF_8000_0000;
if (v.word <= max) return @intCast(v.word);
if (v.word < neg_floor) return null;
const mag: i64 = @intCast(~v.word); // 0 ..= maxInt(i32)
return @intCast(-mag - 1);
}
if (v.word > std.math.maxInt(P)) return null;
return @intCast(v.word);
}

fn call(comptime f: gen.FnSig, args: ?[*]const Value, n: u32, out: *Value) u8 {
const func = @field(impl, prefix ++ f.name);
const F = @TypeOf(func);
const params = @typeInfo(F).@"fn".params;
const arity = comptime logicalArity(f.kinds);
if (n != arity) return status("ARITY");
if (arity > 0 and args == null) return status("NULL_PTR");

var tuple: std.meta.ArgsTuple(F) = undefined;
comptime var pi: usize = 0;
comptime var li: usize = 0;
inline while (pi < params.len) {
const P = params[pi].type.?;
const v = args.?[li];
if (comptime isBytesPtr(P)) {
if (v.kind != kindTag("BYTES")) return status("KIND_MISMATCH");
if (v.len > std.math.maxInt(u32)) return status("RANGE");
if (v.addr == 0 and v.len != 0) return status("NULL_PTR");
if (v.addr > std.math.maxInt(usize)) return status("RANGE");
tuple[pi] = if (v.addr == 0) &empty_bytes else @ptrFromInt(@as(usize, @intCast(v.addr)));
tuple[pi + 1] = @intCast(v.len);
pi += 2;
} else {
const kname = comptime kindOf(P);
if (v.kind != kindTag(kname)) return status("KIND_MISMATCH");
tuple[pi] = decodeInt(P, kname, v) orelse return status("RANGE");
pi += 1;
}
li += 1;
}

const R = @typeInfo(F).@"fn".return_type.?;
const r = @call(.auto, func, tuple);
out.* = .{ .kind = kindTag(comptime kindOf(R)) };
if (R == c_int or R == i32) {
// Sign-extend to u64 with plain integer arithmetic.
const wide: i64 = r;
out.word = if (wide >= 0) @intCast(wide) else ~@as(u64, @intCast(-(wide + 1)));
} else if (R != void) {
out.word = r;
}
return status("OK");
}

/// Body of the protocol's `ps_invoke` export.
pub fn invoke(tag: u16, args: ?[*]const Value, n: u32, out: ?*Value) u8 {
const o = out orelse return status("NULL_PTR");
inline for (gen.FNS) |f| {
if (f.tag == tag) return call(f, args, n, o);
}
return status("UNKNOWN_FN");
}
};
}
80 changes: 80 additions & 0 deletions native-connectors/README.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
= Native connectors (pilot)

This is the pilot of the uniform connector surface. It is meant to replace
the hand-copied tag tables in `bindings/<language>/`. Nothing there is
deleted yet: the owner reviews this shape first.

== The idea

A protocol library exports three C symbols and nothing else is bound:

[source,c]
----
uint32_t ps_abi_version(void);
const char * ps_manifest(void);
uint8_t ps_invoke(uint16_t fn_tag, const ps_value *args, uint32_t n, ps_value *out);
----

`ps_manifest` returns text emitted by the protocol's Idris2 ABI. It holds
the enum tags, the value-cell layout, the kind and status tags, and one `FN`
line per callable function:

----
FN 2 create I32 vhost:BYTES frame_max:U32 channel_max:U16 heartbeat:U16
----

A connector reads the manifest when it opens the library. So one connector
per language serves every protocol, and adding a protocol or a function
needs no connector change.

== Where each part lives

[cols="1,2",options="header"]
|===
| Part | File
| ABI (pure Idris2) | `protocols/proven-amqp/src/AMQPABI/Connector.idr`, printed by `AMQPABI/Emit.idr`
| Rendering | `tools/gen-abi.sh` writes the `FNS` table and `MANIFEST` into `amqp_abi_gen.zig`, only for protocols that emit `FN` lines
| FFI (pure Zig) | `ffi/zig/connector/ps_connector.zig` (shared dispatcher), plus three exports at the end of `protocols/proven-amqp/ffi/zig/src/amqp.zig`
| Connectors | `c/`, `rust/`, `julia/ProvenConnector/`
|===

The Zig dispatcher checks every Idris2 signature against the real `amqp_*`
export at comptime. A changed parameter type, a missing export or a
reordered table fails `zig build`. It also checks the value-cell layout.

Each connector checks the manifest layout against its own `ps_value` when
it opens the library, and refuses a mismatch.

`ps_invoke` checks arity, kinds, integer ranges and null buffers before it
calls anything. Its statuses are `OK`, `UNKNOWN_FN`, `ARITY`,
`KIND_MISMATCH`, `RANGE` and `NULL_PTR`, with the tags given in the manifest.

== Running the smoke tests

----
# From the repository root.
(cd protocols/proven-amqp/ffi/zig && zig build -Doptimize=ReleaseSafe)
LIB=$PWD/protocols/proven-amqp/ffi/zig/zig-out/lib/libproven_amqp.so
# C
cc -std=c11 -Wall -Wextra -o /tmp/ps-smoke native-connectors/c/smoke.c native-connectors/c/ps_connector.c -ldl && /tmp/ps-smoke "$LIB"
# Rust
PS_AMQP_LIB="$LIB" cargo test --manifest-path native-connectors/rust/Cargo.toml
# Julia
PS_AMQP_LIB="$LIB" julia --project=native-connectors/julia/ProvenConnector -e 'using Pkg; Pkg.test()'
----

`just native-connector-smoke` runs all three.

== Limits of the pilot

* Only proven-amqp exports the surface.
* Loading is POSIX `dlopen` only. Windows `LoadLibrary` is not done.
* Results are integers or void. No function returns a buffer yet.
* Verification: the Rust connector is to be verified with Creusot
(Pearlite contracts) and Verus (`3-practice/PROOF-POLICY.adoc` §1.2 in
standards). Both are PENDING. The first obligation to scope is that
`Library::call` passes `ps_invoke` only cells that match the manifest
signature. The `unsafe` dlopen and FFI seam is a Kani candidate. Today
the evidence is the smoke tests and the Zig comptime guard.
Loading
Loading