✓
Passing This code compiles and runs correctly.
Code
// PINS: how a run of NUMBERS crosses the C boundary under `koruc lib`.
//
// Text already crosses as a pointer and a length (140_018). A numeric buffer
// is the same move, because C has exactly one way to hand over a run of values
// it does not own:
//
// pub tor apply-gain { input: []const f32, output: []f32, gain: f32 }
// export fn apply_gain(input_ptr: [*]const f32, input_len: usize,
// output_ptr: [*]f32, output_len: usize, gain: f32) void
//
// The MUTABLE side is the load-bearing half: `[]f32` becomes `[*]f32`, and the
// callee writes back through it. That is the entire calling convention of every
// audio and signal-processing C API — a host owns both buffers, hands over
// borrowed views, and reads the result out afterwards.
//
// `u8` is deliberately NOT a buffer element here: a run of bytes is text, it is
// spelled `string`, and two Koru spellings reaching one C shape would leave an
// exported header ambiguous about which one a caller is looking at.
//
// This runs as a PROGRAM, pinning the shapes still work normally. `post.sh`
// then builds the SAME file as a library, links hand-written C against it, and
// checks the samples — the C boundary is checked at the boundary, not by
// reading the emitted source.
~import std/io
~pub tor apply-gain { input: []const f32, output: []f32, gain: f32 }
~proc apply-gain|zig {
for (input, output) |s, *o| {
o.* = s * gain;
}
}
~pub tor sum-buffer { values: []const f32 } -> f32
~proc sum-buffer|zig {
var total: f32 = 0;
for (values) |v| total += v;
return total;
}
~sum-buffer(values: [0.5, 0.25, 0.25]): t |> std/io:print.ln("sum is {{ t:f }}")
Supporting Files
/* Hand-written C. No generated header is included — this is the declaration a
plugin author writes by hand, which is the whole point of a C ABI. */
#include <stdio.h>
#include <stddef.h>
void apply_gain(const float *input, size_t input_len,
float *output, size_t output_len, float gain);
float sum_buffer(const float *values, size_t values_len);
int main(void) {
float in[8] = {0.0f, 0.25f, 0.5f, -0.5f, 1.0f, -1.0f, 0.125f, -0.75f};
float out[8] = {0};
apply_gain(in, 8, out, 8, 0.5f);
for (int i = 0; i < 8; i++) {
float want = in[i] * 0.5f;
if (out[i] != want) {
printf("FAIL: sample %d is %f, expected %f\n", i, out[i], want);
return 1;
}
}
float s = sum_buffer(in, 8);
if (s != -0.375f) { printf("FAIL: sum is %f, expected -0.375\n", s); return 1; }
printf("PASS: C wrote through a Koru-owned gain stage and read a scalar back\n");
return 0;
}
~proc apply-gain|cs {
for (long __koru_i = 0; __koru_i < input.Length; __koru_i++) {
output[__koru_i] = input[__koru_i] * gain;
}
}
~proc sum-buffer|cs {
float total = 0f;
foreach (var v in values) total += v;
return total;
}Actual
sum is 1
Expected output
✓ Zig✓ C#sum is 1
Emitted Zig source
// Access compiler flags via the per-user compiler_env module
const CompilerEnv = @import("compiler_env").CompilerEnv;
pub const panic = if (@import("builtin").mode == .Debug)
@import("std").debug.FullPanic(@import("std").debug.defaultPanic)
else
@import("std").debug.simple_panic;
const __koru_bare = struct {
extern fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
extern fn free(ptr: ?*anyopaque) void;
fn bareAlloc(_: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, _: usize) ?[*]u8 {
var p: ?*anyopaque = null;
const a = @max(alignment.toByteUnits(), @sizeOf(usize));
if (posix_memalign(&p, a, len) != 0) return null;
return @ptrCast(p);
}
fn bareResize(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) bool { return false; }
fn bareRemap(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) ?[*]u8 { return null; }
fn bareFree(_: *anyopaque, memory: []u8, _: @import("std").mem.Alignment, _: usize) void { free(@ptrCast(memory.ptr)); }
const vtable = @import("std").mem.Allocator.VTable{ .alloc = bareAlloc, .resize = bareResize, .remap = bareRemap, .free = bareFree };
const allocator = @import("std").mem.Allocator{ .ptr = undefined, .vtable = &vtable };
};
const __koru_backing = if (@import("builtin").link_libc) @import("std").heap.c_allocator else if (@import("builtin").os.tag == .freestanding) __koru_bare.allocator else @import("std").heap.page_allocator;
var __koru_leak_count: @import("std").atomic.Value(usize) = .init(0);
fn __koru_alloc(ctx: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, ret_addr: usize) ?[*]u8 {
_ = ctx;
const r = __koru_backing.rawAlloc(len, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
if (r != null) _ = __koru_leak_count.fetchAdd(1, .monotonic);
}
return r;
}
fn __koru_resize(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
return __koru_backing.rawResize(memory, alignment, new_len, ret_addr);
}
fn __koru_remap(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
_ = ctx;
return __koru_backing.rawRemap(memory, alignment, new_len, ret_addr);
}
fn __koru_free(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, ret_addr: usize) void {
_ = ctx;
__koru_backing.rawFree(memory, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
_ = __koru_leak_count.fetchSub(1, .monotonic);
}
}
const __koru_vtable = @import("std").mem.Allocator.VTable{ .alloc = __koru_alloc, .resize = __koru_resize, .remap = __koru_remap, .free = __koru_free };
pub fn koru_allocator() @import("std").mem.Allocator {
return .{ .ptr = undefined, .vtable = &__koru_vtable };
}
pub inline fn __koru_intcast(comptime T: type, x: anytype) T {
if (comptime (@import("builtin").mode == .Debug or @import("builtin").mode == .ReleaseSafe))
return @as(T, @intCast(x));
const dst = @typeInfo(T);
const src = @typeInfo(@TypeOf(x));
if (comptime (dst == .int and src == .int and dst.int.bits == src.int.bits and dst.int.signedness != src.int.signedness))
return @as(T, @bitCast(x));
return @as(T, @intCast(x));
}
pub fn koru_leak_check() void {
if (comptime @import("builtin").mode != .Debug) return;
if (__koru_leak_count.load(.acquire) == 0) return;
if (comptime @import("builtin").target.os.tag == .freestanding) {
if (comptime @import("builtin").cpu.arch == .wasm32 or @import("builtin").cpu.arch == .wasm64) {
@panic("KORU LEAK CHECK FAILED: the produced program leaked");
} else {
const __klc = struct { extern var stdout: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; };
var __lb: [128]u8 = undefined;
const __lm = "KORU LEAK CHECK FAILED: allocations still outstanding at end of run: ";
@memcpy(__lb[0..__lm.len], __lm);
var __ln: usize = __lm.len;
var __lv = __koru_leak_count.load(.acquire);
var __ld: [20]u8 = undefined;
var __lk: usize = 0;
while (__lv > 0) : (__lk += 1) { __ld[__lk] = @intCast('0' + __lv % 10); __lv /= 10; }
for (0..__lk) |__li| { __lb[__ln] = __ld[__lk - 1 - __li]; __ln += 1; }
__lb[__ln] = '\n'; __ln += 1; __lb[__ln] = 0;
_ = __klc.fputs(@as([*:0]const u8, @ptrCast(&__lb)), __klc.stdout);
@trap();
}
} else {
@import("std").debug.print("KORU LEAK CHECK FAILED: the produced program leaked (trace above)\n", .{});
@import("std").process.exit(1);
}
}
pub const main_module = struct {
pub const sum_buffer_event = struct {
pub const Input = struct {
values: []const f32,
};
pub const Output = f32;
pub fn handler(__koru_event_input: @This().Input) @This().Output {
// >>> PROC: sum_buffer [tests/regression/100_MODULE_SYSTEM/140_FILE_LAYOUT/140_019_lib_mode_numeric_buffers_cross_as_pointer_and_length/input.kz:37]
const values = __koru_event_input.values;
_ = &values;
_ = &__koru_event_input;
var total: f32 = 0;
for (values) |v| total += v;
return total;
}
};
// >>> FLOW: tests/regression/100_MODULE_SYSTEM/140_FILE_LAYOUT/140_019_lib_mode_numeric_buffers_cross_as_pointer_and_length/input.kz:43 ~input:sum_buffer()
pub fn flow0() void {
const t = main_module.sum_buffer_event.handler(.{ .values = &[_]f32{ 0.5, 0.25, 0.25 } });
(struct { fn __kout(__fd: i32, __b: []const u8) void { if (@import("builtin").os.tag == .freestanding) { const __kc = struct { extern var stdout: ?*anyopaque; extern var stderr: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; }; var __kt: [4096]u8 = undefined; for (0..(__b.len + __kt.len - 2) / (__kt.len - 1)) |__ki| { const __kn = @min(__kt.len - 1, __b.len - __ki * (__kt.len - 1)); @memcpy(__kt[0..__kn], __b[__ki * (__kt.len - 1)..][0..__kn]); __kt[__kn] = 0; @import("std").mem.doNotOptimizeAway(__kc.fputs(@as([*:0]const u8, @ptrCast(&__kt)), if (__fd == 2) __kc.stderr else __kc.stdout)); } } else { @import("std").mem.doNotOptimizeAway(@import("std").posix.write(__fd, __b) catch @as(usize, 0)); } } fn __kw(comptime __f: []const u8, __a: anytype) void { var __kb: [65536]u8 = undefined; const __ks = @import("std").fmt.bufPrint(&__kb, __f, __a) catch __kb[0..0]; __kout(1, __ks); } }).__kw("sum is {}\n", .{t});
}
pub fn koru_start_flow() void {
const result_0 = koru_koru.start_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
}
pub fn koru_end_flow() void {
const result_0 = koru_koru.end_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
}
};
pub const koru_koru = struct {
pub const start_event = struct {
pub const Input = struct {
};
pub const Output = union(enum(u8)) {
done: struct {
},
};
pub fn handler(__koru_event_input: @This().Input) @This().Output {
_ = &__koru_event_input;
return .{ .done = .{} };
}
};
pub const end_event = struct {
pub const Input = struct {
};
pub const Output = union(enum(u8)) {
done: struct {
},
};
pub fn handler(__koru_event_input: @This().Input) @This().Output {
_ = &__koru_event_input;
return .{ .done = .{} };
}
};
};
pub fn main() void {
main_module.koru_start_flow();
main_module.flow0();
main_module.koru_end_flow();
if (comptime @import("builtin").mode == .Debug) koru_leak_check();
}
test {
@import("std").testing.refAllDeclsRecursive(@This());
}
Emitted C# source
static class main_module {
public static void __koru_stdout_write(dynamic s) => global::System.Console.Out.Write(s);
public static void __koru_stderr_write(dynamic s) => global::System.Console.Error.Write(s);
// The mutable handle carrier — `*String`-style resources are
// `new __KoruBox { data = … }` because C# anonymous types are
// read-only: `s.data = …` (std/string append/clear, handle
// mutation generally) needs a settable member.
public class __KoruBox { public dynamic data; }
// Textification for `{{ … }}` operands: C# bool ToStrings as
// `True` where Koru prints `true`, and the operand's static type
// is unknown at this boundary — a `(x) is bool` inline test would
// be a compile error on statically-typed operands instead. Generic
// on purpose: `dynamic` boxed every value-type operand — measured
// ~1s/10M elements on 012_threat_scanner — while T specializes to
// the operand's own ToString() with no box.
public static string __koru_str<T>(T v) => v is bool b ? (b ? "true" : "false") : v?.ToString();
public static class sum_buffer_event {
public struct Input {
public dynamic values;
}
public static float handler(Input __koru_input) {
var values = __koru_input.values;
float total = 0f;
foreach (var v in values) total += v;
return total;
return default;
}
}
public static class koru_start_event {
public struct Input {
}
public struct Output {
public string tag;
public dynamic done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static class koru_end_event {
public struct Input {
}
public struct Output {
public string tag;
public dynamic done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static void flow0() {
var t = main_module.sum_buffer_event.handler(new sum_buffer_event.Input { values = new dynamic[] {0.5, 0.25, 0.25}});
__koru_stdout_write("sum is " + __koru_str(t) + "\n");
}
public static void flow1() {
main_module.koru_start_event.handler(new koru_start_event.Input { });
}
public static void flow2() {
main_module.koru_end_event.handler(new koru_end_event.Input { });
}
}
static class Program {
static void Main() {
main_module.flow1();
main_module.flow0();
main_module.flow2();
}
}
Flows
flow ~sum-buffer click a branch to expand · @labels scroll to their anchor
sum-buffer (values: [0.5, 0.25, 0.25])
Test Configuration
MUST_RUN LANGUAGES: zig cs
Post-validation Script:
#!/bin/bash
# Check the C boundary AT the boundary: build this same file as a library,
# link hand-written C against it, and compare the samples. Reading the emitted
# Zig would only prove the emitter wrote what the emitter meant to write.
set -e
cd "$(dirname "$0")"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
cp input.kz host.c "$work"/
cd "$work"
koruc lib input.kz > lib.out 2>&1 || { echo "FAIL: koruc lib did not build"; cat lib.out; exit 1; }
# Both buffers must arrive as a pointer AND a length, and the OUTPUT one must
# be mutable — that is the half an audio plugin writes back through.
sig=$(grep -m1 '^export fn apply_gain' output_emitted.zig || true)
if [ -z "$sig" ]; then
echo "FAIL: apply_gain was not exported at all"
grep -A4 'C ABI exports' output_emitted.zig || true
exit 1
fi
case "$sig" in
*"input_ptr: [*]const f32, input_len: usize"*) ;;
*) echo "FAIL: the const buffer did not cross as pointer+length"; echo " $sig"; exit 1 ;;
esac
case "$sig" in
*"output_ptr: [*]f32, output_len: usize"*) ;;
*) echo "FAIL: the mutable buffer did not cross as a writable pointer+length"; echo " $sig"; exit 1 ;;
esac
zig build-lib output_emitted.zig -dynamic -lc -O ReleaseFast --name korugain > build.out 2>&1 || {
echo "FAIL: the emitted library did not build"; tail -20 build.out; exit 1; }
cc host.c -L. -lkorugain -Wl,-rpath,. -o host 2> link.err || {
echo "FAIL: hand-written C did not link against the Koru library"; cat link.err; exit 1; }
./host