# 20. Living beside C, C++ and Swift

Coax code doesn't run on its own in the OpenAgents app. The app is a UIKit
program written in Swift, and every Coax file it uses arrives as a small C
library: a `.c` file Xcode compiles and a `.h` file Swift imports. When you
tap Start on the home screen, Swift calls a Coax procedure named
`metaverse_camera_dolly_start`, and on every frame until the camera lands it
calls `metaverse_camera_dolly` to find out where the camera is. Neither side knows
much about the other. They agree on a C header, and that header is the
whole contract.

In this chapter we'll build that contract from the Coax side. We'll export
a procedure, generate its header, link it into a C program, and then call
it from Swift. We'll pass structs, views and enums across, call back into C
from Coax with `#foreign`, and look at the mistakes the team actually made
while wiring the iOS app: struct names that clash between headers, and enum
constants Swift can't see. At the end we'll look at how the real app is put
together.

The Coax files in this chapter are in `coax/book/examples` (`ch20_ease.coax`
and `ch20_path.coax`), and the C, C++ and Swift hosts are in
`examples/ch20_interop`, whose `run.sh` builds and runs all of them.

> Note: On the current `coax0`, `#export_c`, `coax lib`, `coax header`,
> `coax c --library`, `#foreign` imports of scalars and borrowed views and `coax metal` all work,
> and everything in this chapter was run to produce the output shown.
> Importing C headers, ownership and nullability annotations in headers,
> and pointers across `#foreign` are designs (spec §17.2), and C++ will
> stay behind `extern "C"` shims. Each is marked where it comes up.

## The C boundary is the contract

C is the one language every toolchain on the Mac can talk to. Swift reads C
headers through its Clang importer, C++ includes them inside
`extern "C"`, and every C compiler links C objects. So Coax doesn't try to
speak Swift or C++ directly. It speaks C, and the other languages meet it
there.

That choice comes with a few rules, and you'll see each of them in the
generated code later in the chapter:

- Integer widths are spelled out. Coax `int` is 64 bits, and C `int`
  usually isn't, so the header writes `int64_t`, never `int`. When you
  design a procedure for C callers, pick `s32`, `s64`, `u8` and friends on
  purpose.
- Lengths travel with data. A Coax view `[] T` or `string` is a pointer and
  a count. It crosses as a two-field struct, never as a bare pointer, and a
  string is never assumed to end in a zero byte.
- Memory that one side owns, the other side refers to by an opaque handle,
  usually an integer. The side that allocates is the side that frees.
- Coax's implicit context (Chapter 6) never appears in a C signature.

## Exporting a procedure

Let's start with the smallest useful export: a single easing function. It
takes a number from 0 to 1 and returns a smoothed version of it, the curve
the iOS camera uses for its dolly.

Filename: ease.coax

```jai
#import "Basic";

clamp01 :: (x: f32) -> f32 {
  if x < 0 { return 0; }
  if x > 1 { return 1; }
  return x;
}

// Smootherstep: 0 at 0, 1 at 1, and flat at both ends.
ease :: (x: f32) -> f32 #export_c {
  t := clamp01(x);
  return t * t * t * (t * (t * 6 - 15) + 10);
}

main :: () {
  for i: 0..<5 {
    x := f32(i) / 4;
    print("ease(%) = %\n", x, ease(x));
  }
}
```

*Listing 20-1: An exported easing function, with a `main` so it also runs on its own*

The only new thing here is `#export_c` after the return type of `ease`.
It tells the compiler three things: keep this procedure's name exactly as
written (`ease`, not a mangled internal name), use the C calling
convention, and declare it in the generated header. `clamp01` has no
`#export_c`, so it stays private to the file.

We can still run the file the ordinary way, which is a good habit: test
the logic in Coax before any C is involved.

```shell
$ coax run ease.coax
ease(0.0) = 0.0
ease(0.25) = 0.103515625
ease(0.5) = 0.5
ease(0.75) = 0.8964844
ease(1.0) = 1.0
```

## Generating a header

Now let's ask for the header a C program would include. `coax header`
prints it, or writes it to a file with `-o`:

```shell
$ coax header ease.coax
```

```c
/* Generated by coax0 from ease.coax. Do not edit: change the .coax file.
   Coax int is int64_t; a Coax string or view is a pointer and a count, not
   NUL-terminated; a failed check inside a call aborts the process. */
#ifndef COAX_EASE_H
#define COAX_EASE_H

#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
#define _Bool bool
#define COAX_LAYOUT(c, m) static_assert(c, m)
#define COAX_ALIGNOF alignof
extern "C" {
#else
#define COAX_LAYOUT(c, m) _Static_assert(c, m)
#define COAX_ALIGNOF _Alignof
#endif

#ifndef COAX_STRING_DEFINED
#define COAX_STRING_DEFINED
typedef struct { const char *data; int64_t count; } coax_string;
#endif


float ease(float x);

#ifdef __cplusplus
}
#undef _Bool
#endif
#undef COAX_LAYOUT
#undef COAX_ALIGNOF
#endif
```

*Listing 20-2: The whole header for ease.coax*

Most of it is scaffolding, and it's the same in every header, so let's go
through it once.

The opening comment is written every time, and it says the three things a
C caller most needs to know and can't learn from the declarations. We'll
see the last one, "a failed check inside a call aborts the process", in
action shortly.

The include guard, `COAX_EASE_H`, comes from the file name. Two files with
the same base name in different folders would share a guard, so keep
exported file names distinct.

The `__cplusplus` block makes the same header work in C and C++. In C++ it
opens `extern "C"` so the names aren't mangled, maps C's `_Bool` to
`bool`, and switches the layout assertions (which this file doesn't have
yet) from `_Static_assert` to `static_assert`. At the end the header
undefines its helper macros so they don't leak into your code.

`coax_string` is how a Coax `string` looks in C: a pointer and a count.
It's guarded so that several Coax headers can be included together.

And then, finally, the one line we asked for: `float ease(float x);`.
Coax `f32` is C `float`. `clamp01` isn't mentioned at all.

## Building a library

The header is half of what a C program needs. The other half is compiled
code. `coax lib` compiles the file to an object file:

```shell
$ coax lib ease.coax -o ease.o
$ nm ease.o
0000000000000064 t _coax_p_clamp01
0000000000000000 T _ease
0000000000000000 t ltmp0
00000000000003a8 s ltmp1
```

`nm` lists the symbols in the object. A capital `T` means a global
function other objects can call, and that's `_ease` (Mach-O puts an
underscore in front of every C name). `clamp01` became `_coax_p_clamp01`
with a lowercase `t`: it's `static`, so it can't collide with a `clamp01`
the host happens to have.

Two other things are different from `coax build`. The object has no C
`main`, even though our file has a Coax `main`: a library is called by
someone else's program, so `coax lib` leaves it out. And like every Coax
build, it keeps all the runtime checks. `--release` compiles the C at `-O2` and makes integer
arithmetic wrap instead of trapping on overflow, but bounds checks, cast
checks, division by zero and `#assert` still trap.

## Calling it from C

Here's a C program that uses the library.

Filename: ease_host.c

```c
#include <stdio.h>
#include "ease.h"

int main(void) {
  for (int i = 0; i <= 4; i++) {
    float x = i / 4.0f;
    printf("ease(%g) = %g\n", x, ease(x));
  }
  return 0;
}
```

*Listing 20-3: A C host calling the exported `ease`*

Compile it with the object and run it:

```shell
$ coax header ease.coax -o ease.h
$ coax lib ease.coax -o ease.o
$ cc -std=c11 -Wall -o ease_host ease_host.c ease.o
$ ./ease_host
ease(0) = 0
ease(0.25) = 0.103516
ease(0.5) = 0.5
ease(0.75) = 0.896484
ease(1) = 1
```

The numbers are the same ones Coax printed; C's `%g` just shows fewer
digits. C++ works the same way, because the header opens `extern "C"` for
it:

```cpp
#include <cstdio>
#include "ease.h"
int main() { std::printf("from C++: %g\n", ease(0.25f)); }
```

```shell
$ c++ -std=c++17 -Wall -o ease_hostpp ease_host.cpp ease.o
$ ./ease_hostpp
from C++: 0.103516
```

That's the whole round trip: a `.coax` file, a header, an object and a host
that links them.

## Structs, views and enums

Real procedures pass more than one float. Let's write something closer to
the iOS camera: a 3D point, a procedure that mixes two points, one that
measures a path through many points, and a small enum for what the camera
is doing.

Filename: path.coax

```jai
#import "Basic";

Point :: struct { x: f32; y: f32; z: f32; }

Mode :: enum u8 { orbit; dolly; follow; }

sub :: (a: Point, b: Point) -> Point { return Point.{x = a.x - b.x, y = a.y - b.y, z = a.z - b.z}; }
length :: (a: Point) -> f32 { return sqrt(a.x * a.x + a.y * a.y + a.z * a.z); }

// The point a share `t` of the way from `a` to `b`.
path_mix :: (a: Point, b: Point, t: f32) -> Point #export_c {
  return Point.{x = a.x + (b.x - a.x) * t, y = a.y + (b.y - a.y) * t, z = a.z + (b.z - a.z) * t};
}

// The length of the path through every point in order.
path_length :: (points: [] Point) -> f32 #export_c {
  total: f32 = 0;
  for i: 1..<points.count {
    total += length(sub(points[i], points[i - 1]));
  }
  return total;
}

// What the camera does after `m` finishes.
path_next :: (m: Mode) -> Mode #export_c {
  if m == Mode.orbit { return Mode.dolly; }
  return Mode.follow;
}

main :: () {
  a := Point.{x = 0, y = 0, z = 0};
  b := Point.{x = 3, y = 4, z = 0};
  print("%\n", path_mix(a, b, 0.5));
  points: [3] Point;
  points[0] = a;
  points[1] = b;
  points[2] = Point.{x = 3, y = 4, z = 12};
  print("length %\n", path_length(points[..]));
  print("after orbit: %\n", path_next(Mode.orbit));
}
```

*Listing 20-4: Exported procedures that take and return a struct, a view and an enum*

```shell
$ coax run path.coax
Point.{x = 1.5, y = 2.0, z = 0.0}
length 17.0
after orbit: dolly
```

The path goes 5 units from `a` to `b` and then 12 straight up, so 17 is
right. Here's the interesting part of its header, from the type
declarations down to the procedures:

```c
typedef struct coax_t_Point coax_t_Point;
struct coax_t_Point { float x; float y; float z; };
typedef struct { coax_t_Point *data; int64_t count; } coax_v_t_Point;
typedef uint8_t coax_t_Mode;
#define COAX_Mode_orbit ((coax_t_Mode)UINT64_C(0))
#define COAX_Mode_dolly ((coax_t_Mode)UINT64_C(1))
#define COAX_Mode_follow ((coax_t_Mode)UINT64_C(2))
COAX_LAYOUT(sizeof(coax_t_Point) == 12 && COAX_ALIGNOF(coax_t_Point) == 4, "layout of Point");
COAX_LAYOUT(offsetof(coax_t_Point, x) == 0, "offset of Point.x");
COAX_LAYOUT(offsetof(coax_t_Point, y) == 4, "offset of Point.y");
COAX_LAYOUT(offsetof(coax_t_Point, z) == 8, "offset of Point.z");

coax_t_Point path_mix(coax_t_Point a, coax_t_Point b, float t);
float path_length(coax_v_t_Point points);
coax_t_Mode path_next(coax_t_Mode m);
```

*Listing 20-5: How path.coax's types look in C*

Each kind of type has its own spelling.

A struct named `Point` becomes `coax_t_Point`. The `coax_t_` prefix keeps
Coax's type names out of the way of the host's own `Point`, which a
graphics app very likely has. Field names don't get a prefix: C code
writes `p.x`, as you'd hope. C has no field defaults, so a `coax_t_Point`
made in C starts as whatever C puts in it. `Point` declares no defaults, so
zero is its starting value anyway. For a struct that declares defaults, see
"Starting a struct from its defaults" below.

A view `[] Point` becomes `coax_v_t_Point`, a struct with `data` and
`count`. C passes a view by building one of these.

An enum becomes its integer type, here `uint8_t` because we wrote
`enum u8`, plus one macro per member. `COAX_Mode_dolly` is the value `1`
cast to `coax_t_Mode`.

Then come the layout assertions. `COAX_LAYOUT` expands to
`_Static_assert`, so the C compiler checks that its idea of `Point` (12
bytes, aligned to 4, `x` at 0, `y` at 4, `z` at 8) matches Coax's. If they
ever disagree, the host refuses to compile rather than reading `y` where
`z` is. These are the same numbers `coax layout path.coax` prints, and
Chapter 13 covers how Coax lays structs out. We'll see one of these
assertions fire in Chapter 21.

Now the C side.

Filename: path_host.c

```c
#include <stdio.h>
#include "path.h"

int main(void) {
  coax_t_Point a = {0, 0, 0}, b = {3, 4, 0};
  coax_t_Point m = path_mix(a, b, 0.5f);
  printf("mix: %g %g %g\n", m.x, m.y, m.z);

  coax_t_Point points[] = {a, b, {3, 4, 12}};
  coax_v_t_Point view = {points, 3};
  printf("length: %g\n", path_length(view));

  coax_t_Mode next = path_next(COAX_Mode_orbit);
  printf("after orbit: %s\n", next == COAX_Mode_dolly ? "dolly" : "something else");
  return 0;
}
```

*Listing 20-6: A C host passing structs, a view and an enum*

```shell
$ cc -std=c11 -Wall -o path_host path_host.c path.o
$ ./path_host
mix: 1.5 2 0
length: 17
after orbit: dolly
```

Notice how the view is made: C owns the array `points`, and it hands Coax
a pointer to it and its length. Coax reads through that pointer for the
duration of the call and keeps nothing afterward. That's the only lifetime
rule a view has today, and it's on you to follow it: a view must not
outlive the memory it points into.

### Starting a struct from its defaults

When a struct in the header declares a default, directly or in a field, the
header also declares a function that writes those defaults. Suppose
`path.coax` had a camera with defaults:

```jai
Camera :: struct { at: Point; fov: f32 = 60; mode: Mode = Mode.follow; }
camera_fov :: (c: Camera) -> f32 #export_c { return c.fov; }
```

The header then declares `coax_default_t_Camera`:

```c
void coax_default_t_Camera(coax_t_Camera *p);
```

It writes zeros and then every default into `*p`, so `p->fov` is 60 and
`p->mode` is `COAX_Mode_follow`, the same bytes that `c: Camera;` gives in
Coax. It writes in place, so it works on any memory the host owns, even
state too large for the stack. Call it on every value of the type that C
creates:

```c
static coax_t_Camera camera;            // zeros, as C starts a global

int main(void) {
  coax_default_t_Camera(&camera);       // now fov is 60
  printf("%g\n", camera_fov(camera));
  return 0;
}
```

The browser host works the same way. WebAssembly memory starts as zeros,
so a page's C face exports `coaxial_state_init`, which calls
`coax_default_T` on the new state, and the host calls it before the first
frame. Each unit that uses a type defines this function, so the definition
is weak, and the linker keeps one.

Because field names cross unchanged, a field can't be named something C or
C++ has reserved. The compiler stops you early, even in a file that never
exports anything, because any struct might end up in a header:

```shell
$ coax check kw.coax
kw.coax:1:19: error[E0371]: field name 'class' is reserved in C or C++, where this struct also lives
  Thing :: struct { class: s32; }
                    ^
  fix: pick another name
1 error
```

## When a check fails inside a call

The header's opening comment said a failed check inside a call aborts the
process. Let's see what that means. This one-line file indexes the first
element of a view:

Filename: first.coax

```jai
first_x :: (xs: [] f32) -> f32 #export_c { return xs[0]; }
```

And this C host calls it twice, the second time with an empty view:

```c
#include <stdio.h>
#include "first.h"
int main(void) {
  float xs[] = {2.5f};
  printf("%g\n", first_x((coax_v_f32){xs, 1}));
  printf("%g\n", first_x((coax_v_f32){xs, 0}));
  printf("never printed\n");
  return 0;
}
```

```shell
$ ./first_host
2.5
first.coax:1: index out of bounds
$ echo $?
134
```

The bounds check in `xs[0]` failed, Coax printed where, and called
`abort()`; 134 is the shell's code for a process killed by `SIGABRT`.
Building with `coax lib --release` gives exactly the same result, because
release builds keep bounds checks. There's no error value to return and no
way for C to catch it. If a host needs to survive bad input, it has to
check the input before the call, or the Coax procedure has to return a
result the host can test, the way `pay/wallet.coax` returns `-1` for
an amount it won't convert.

Coax also trusts the count it's given. If C says a view has 3 elements
when its array has 2, Coax will read past the end of it, exactly as C
would. Bounds checks protect Coax indexing against the count; they can't
check the count itself.

## Calling it from Swift

Swift doesn't include headers the way C does. An app target has one
bridging header, and everything it includes becomes visible to all the
target's Swift files. For our experiment the bridging header is two lines:

Filename: Bridge.h

```c
// What Swift sees: every generated header the app uses.
#include "ease.h"
#include "path.h"
```

With that, Swift can use the C names directly. A C struct imports as a
Swift struct with a memberwise initializer, and C functions are ordinary
Swift functions.

Filename: main.swift

```swift
let a = coax_t_Point(x: 0, y: 0, z: 0)
let b = coax_t_Point(x: 3, y: 4, z: 0)
let m = path_mix(a, b, 0.5)
print("mix:", m.x, m.y, m.z)

var points = [a, b, coax_t_Point(x: 3, y: 4, z: 12)]
let total = points.withUnsafeMutableBufferPointer { buffer in
  path_length(coax_v_t_Point(data: buffer.baseAddress, count: Int64(buffer.count)))
}
print("length:", total)
```

*Listing 20-7: Swift calling the same procedures*

The view is the only awkward part. A Swift array doesn't promise its
elements stay at one address, so we borrow its storage with
`withUnsafeMutableBufferPointer`, build the `coax_v_t_Point` inside the
closure, and call Coax there. When the closure returns, the pointer is no
longer valid, which suits a view perfectly: Coax only uses it during the
call. The iOS app passes its joint palette and collision bodies to Coax
this way every frame.

Now let's finish the program by calling `path_next`, the way the C host
did:

```swift
let next = path_next(COAX_Mode_orbit)
print(next == COAX_Mode_dolly)
```

```shell
$ swiftc -import-objc-header Bridge.h enum.swift path.o -o swift_enum
enum.swift:1:22: error: cannot find 'COAX_Mode_orbit' in scope
1 | let next = path_next(COAX_Mode_orbit)
  |                      `- error: cannot find 'COAX_Mode_orbit' in scope
2 | print(next == COAX_Mode_dolly)
3 |

/.../path.h:29:9: note: macro 'COAX_Mode_orbit' unavailable: structure not supported
27 | typedef struct { coax_t_Point *data; int64_t count; } coax_v_t_Point;
28 | typedef uint8_t coax_t_Mode;
29 | #define COAX_Mode_orbit ((coax_t_Mode)UINT64_C(0))
   |         `- note: macro 'COAX_Mode_orbit' unavailable: structure not supported
```

This one caught the team while building the wallet. Swift imports simple
C macros as constants, `#define LIMIT 10` and even a plain cast like
`#define LIMIT ((coax_t_Mode)1)`. It gives up on a macro that uses another
macro, and every generated enum macro wraps its value in `UINT64_C(...)`.
`coax_t_Mode` itself imports fine (as Swift's `UInt8`); only the member
names are missing.

The fix is to spell the codes once on the Swift side, typed with the
imported enum type, next to the call:

Filename: path_modes.swift

```swift
// Swift can't import the header's COAX_Mode_* cast macros, so the codes are
// spelled here once, with the type the header gives them.
enum Mode { static let orbit: coax_t_Mode = 0, dolly: coax_t_Mode = 1, follow: coax_t_Mode = 2 }

func describeNext() {
  let next = path_next(Mode.orbit)
  print("after orbit:", next == Mode.dolly ? "dolly" : "something else")
}
```

*Listing 20-8: Enum codes repeated in Swift, because the macros don't import*

Add `describeNext()` to the end of `main.swift` and build both files:

```shell
$ swiftc -import-objc-header Bridge.h main.swift path_modes.swift path.o ease.o -o swift_host
$ ./swift_host
mix: 1.5 2.0 0.0
length: 17.0
after orbit: dolly
```

The cost of Listing 20-8 is that the numbers now live in two places.
Unless you give a member a value (`dolly = 1;`), Coax numbers enum members
from 0 in the order you write them, so adding a member in the middle of a
Coax enum silently shifts the Swift copy. For any enum that crosses the
boundary, either write every value explicitly or add new members only at
the end, and when you change it, check the `#define` lines in the
regenerated header against the Swift table. The shared Apple Breez Spark
wallet host ([`apps/shared/host/apple/SparkWallet.swift`](https://github.com/OpenAgentsInc/openagents/blob/main/apps/shared/host/apple/SparkWallet.swift))
mirrors `pay/wallet.coax`'s enum codes across the Swift/C boundary the same way:

```swift
/// pay/wallet.coax's enum codes, as Wallet.h defines them (Swift can't
/// import the header's cast macros). The header's layout checks pin Flow.
enum Pay { static let idle: coax_t_Pay = 0, quoted: coax_t_Pay = 1, sending: coax_t_Pay = 2, succeeded: coax_t_Pay = 3, notSent: coax_t_Pay = 4, unknown: coax_t_Pay = 5 }
```

> Note: A future `coax header` could emit plain integer constants (an
> anonymous C `enum`, or `static const` values) that Swift imports
> directly. Today it emits cast macros, so the Swift table is required.

## Calling C from Coax

So far C has been calling Coax. The other direction uses `#foreign`. A
`#foreign` procedure has a signature and no body; its body is a C function
with the same name that the host links in.

Here's a meter that summarizes a buffer of audio levels. The host owns the
buffers, and Coax asks for samples one at a time through a handle.

Filename: meter.coax

```jai
// The host owns the samples; Coax asks for them one at a time.
host_sample :: (h: int, index: int) -> f64 #foreign;
host_report :: (h: int, mean: f64, peak: f64) #foreign;

meter_scan :: (h: int, count: int) -> bool #export_c {
  if count <= 0 { return false; }
  sum: f64 = 0;
  peak: f64 = 0;
  for i: 0..<count {
    s := host_sample(h, i);
    sum += s;
    if s > peak { peak = s; }
  }
  host_report(h, sum / f64(count), peak);
  return true;
}
```

*Listing 20-9: Two procedures the host provides, and one Coax exports*

This file has no `main`. Commands that link no program take such a file as
a library without being told: `coax check meter.coax`, `coax test
meter.coax` and `coax c meter.coax` work as they would with `--library`.
`coax run` and `coax build` make a program, so they refuse it, and the
error tells you what to do instead:

```shell
$ coax run meter.coax
meter.coax:1:1: error[E0336]: the program has no 'main'
  // The host owns the samples; Coax asks for them one at a time.
  ^
  fix: build it as a library: coax lib FILE.coax
1 error
```

The header declares both directions. The `#foreign` procedures get their
own section:

```c
_Bool meter_scan(int64_t h, int64_t count);

/* Provided by the host (#foreign). */
double host_sample(int64_t h, int64_t index);
void host_report(int64_t h, double mean, double peak);
```

That section matters more than it looks. The host's C file includes the
same header, so the C compiler compares the host's definitions against
Coax's declarations. Here is the host:

Filename: meter_host.c

```c
#include <stdio.h>
#include <stdbool.h>
#include "meter.h"

// The host's side: a table of buffers, and Coax gets an index into it.
static const double *buffers[4];

double host_sample(int64_t h, int64_t index) { return buffers[h][index]; }

void host_report(int64_t h, double mean, double peak) {
  printf("buffer %lld: mean %.3f, peak %.3f\n", (long long)h, mean, peak);
}

int main(void) {
  static const double levels[] = {0.25, 0.5, 0.125, 0.875};
  buffers[1] = levels;
  bool ok = meter_scan(1, 4);
  printf("scanned: %s\n", ok ? "yes" : "no");
  return 0;
}
```

*Listing 20-10: A host that provides the `#foreign` procedures and calls the export*

```shell
$ cc -std=c11 -Wall -o meter_host meter_host.c meter.o
$ ./meter_host
buffer 1: mean 0.438, peak 0.875
scanned: yes
```

Suppose the host gets a type wrong and returns `float` from
`host_sample`. Without the shared header, that would link and then
quietly read garbage. With it:

```shell
$ cc -std=c11 -c meter_bad.c
meter_bad.c:8:7: error: conflicting types for 'host_sample'
    8 | float host_sample(int64_t h, int64_t index) { return buffers[h][index]; }
      |       ^
./meter.h:29:8: note: previous declaration is here
   29 | double host_sample(int64_t h, int64_t index);
      |        ^
1 error generated.
```

`#foreign` is deliberately narrow. Parameters are integers, floats, `bool`
or *borrowed views* of them; results are scalars or nothing. A view crosses
as the same `{data, count}` struct the exports use, so a host can sum a
buffer Coax owns:

```jai
host_sum :: (xs: [] f32) -> f32 #foreign;
```

```c
float host_sum(coax_v_f32 xs) {
  float s = 0;
  for (int64_t i = 0; i < xs.count; i++) s += xs.data[i];
  return s;
}
```

The view is borrowed for the call only: the host may read and write
`data[0..count)` and must not keep the pointer after it returns. Two view
arguments can be slices of one array, so the host must allow them to
overlap, and an empty view can have a null `data`. Anything else is refused:

```shell
$ coax check bad.coax
bad.coax:1:14: error[E0376]: parameter 'xs' is [] string; #foreign procedures pass integers, floats, bool and views of them
  host_all :: (xs: [] string) -> int #foreign;
               ^
1 error
```

Strings, structs and views of them don't cross, and nothing transfers
ownership: there's no agreed rule yet for memory C keeps. That's why the
meter still uses a handle for buffers the host owns: the host keeps them,
and Coax only ever holds a number that names one.

Compile-time code can't call the host either, because there's no host
while the compiler runs (Chapter 9):

```shell
$ coax check bad2.coax
bad2.coax:2:11: error[E0404]: compile-time execution cannot call the host procedure 'host_now'
  T :: #run host_now();
            ^
1 error
```

The iOS home is built on exactly this pattern. `metaverse/home.coax` begins
with a list of host procedures:

```jai
host_load :: (h: int, slot: int) -> f64 #foreign;
host_store :: (h: int, slot: int, value: f64) #foreign;
host_byte :: (h: int, index: int) -> int #foreign;
host_size :: (h: int) -> int #foreign;
host_dot :: (h: int, x: f64, y: f64, size: f64, light: f64, soft: f64, crisp: f64) #foreign;
host_line :: (h: int, ax: f64, ay: f64, bx: f64, by: f64, light_a: f64, light_b: f64, width: f64) #foreign;
```

`metaverse/platform/host.c` implements them over bounded, generation-checked
storage: `h` is a handle, and a stale or unknown handle makes the call do
nothing instead of touching freed memory.

> Note: Importing a whole C header (`#import_c "stb_image.h";`) is
> planned, not implemented. The design reads declarations through libclang
> and skips, with a message, anything that has no callable symbol: static
> inline functions, `va_list` variants, macros that aren't constants.
> Until then, each C function Coax calls is declared by hand with
> `#foreign`.

## Many files in one program

One Coax file is easy. The iOS app has several, each compiled to its own
library and header, and Swift includes their headers through one
bridging header. That's where the team hit the next problem.

`metaverse-engine/move/player.coax` has a 3D vector type called `Vec3`. When
`metaverse-engine/cam/camera.coax` was written, it needed a 3D vector too. Let's see
what happens when two files both define one. Here are two tiny files:

Filename: walker.coax

```jai
Vec3 :: struct { x: f32; y: f32; z: f32; }
walker_step :: (p: Vec3, dt: f32) -> Vec3 #export_c { return Vec3.{x = p.x + dt, y = p.y, z = p.z}; }
```

Filename: orbit.coax

```jai
Vec3 :: struct { x: f32; y: f32; z: f32; }
orbit_eye :: (t: f32) -> Vec3 #export_c { return Vec3.{x = sin(t), y = 10, z = cos(t)}; }
```

Each one compiles on its own, and each header is fine on its own. Include
both and C sees two definitions of `coax_t_Vec3`:

```shell
$ cc -std=c11 -c both.c
In file included from both.c:2:
./orbit.h:26:8: error: redefinition of 'coax_t_Vec3'
   26 | struct coax_t_Vec3 { float x; float y; float z; };
      |        ^
./walker.h:26:8: note: previous definition is here
   26 | struct coax_t_Vec3 { float x; float y; float z; };
      |        ^
1 error generated.
```

The two structs are identical, but C doesn't care: a struct may be
defined once per translation unit. Each Coax header is generated from one
file and knows nothing about the others, so nothing stops the clash until
a host includes both. The view typedefs for built-in element types, like
`coax_v_f32`, are guarded so they can repeat, but struct types aren't.

The fix in the app was to give the camera's struct a different name.
That's why `metaverse-engine/cam/camera.coax` says `Point` where you'd expect `Vec3`:

```jai
Point :: struct { x: f32; y: f32; z: f32; }
Shot :: struct { eye: Point; at: Point; }
```

Swift then converts between the two where the player's camera hands off
to the dolly, in `HomeViewController.swift`:

```swift
private func point(_ v: coax_t_Vec3) -> coax_t_Point { coax_t_Point(x: v.x, y: v.y, z: v.z) }
```

`#load` now lets files share one declaration within a source graph
(Chapter 10). Independently compiled libraries still need exported struct
names unique across every header one native program includes.

Procedure names have the same problem one level down. If two libraries
both export `tick`, each header is fine, and the linker refuses:

```shell
$ cc m.c a.o b.o -o m
duplicate symbol '_tick' in:
    .../a.o
    .../b.o
ld: 1 duplicate symbols
```

That's why every exported procedure in `metaverse/` carries its file's
name: `metaverse_camera_dolly`, `metaverse_player_feet`,
`metaverse_wallet_sat_to_msat`. It reads long, but C has one namespace, and
the prefix is how you share it.

One thing that does repeat safely is a `#foreign` declaration. Both
`home.coax` and `grid.coax` call `host_line`, so both `Home.h` and
`Grid.h` declare it. C allows a function to be declared any number of
times as long as every declaration agrees, and `host.c` defines it once.

## In the real world: the iOS app

Now we can read the app's build. `apps/openagents-ios/generate.sh` runs as
an Xcode build phase before anything is compiled. After making sure the
compiler is built, its core is this loop:

```shell
out=apps/openagents-ios/Generated
for name in home player grid cast camera wallet haunt hud; do
  # Home, Player, Grid, Cast, Camera, Wallet: one C library and header each. Wallet
  # is #authority, so its checks run in this compile and a failure stops it.
  base="$(printf '%s' "${name:0:1}" | tr a-z A-Z)${name:1}"
  "$compiler" c "metaverse/$name.coax" --library --header "$out/$base.h" > "$out/$base.c.tmp"
  mv "$out/$base.c.tmp" "$out/$base.c"
done
```

It uses `coax c --library --header` rather than `coax lib` and
`coax header`. The header is identical (you can diff them), but instead of
an object file built for the Mac, it produces C source, `Camera.c`. That
matters for an iOS app. The compiler runs on the build Mac, but the code
has to run on an iPhone, an iPad and the simulator, and Xcode already
knows how to compile C for each of them. So Coax hands Xcode C, and Xcode
compiles it with the iOS SDK alongside the rest of the app. `--library`
does what `coax lib` does to the program: the Coax `main`, if there is
one, becomes an unused static function, so there's no C `main` to clash
with the app's.

The comment about the wallet is worth reading twice. `pay/wallet.coax`
is marked `#authority` (Chapter 11), so every compile of it runs its
checks. If a change breaks a payment rule, the `coax c` in this loop fails,
the build phase fails, and Xcode never produces an app with the broken
rule in it.

The project file, `project.yml`, points Swift at one bridging header and
tells Clang where the generated headers are:

```yaml
SWIFT_OBJC_BRIDGING_HEADER: OpenAgents/Platform/Bridge.h
HEADER_SEARCH_PATHS: ["$(SRCROOT)/Generated", "$(SRCROOT)/../../metaverse/platform"]
```

and `Bridge.h` includes the host's header and the generated Coax headers.
Here is the original subset; the current header also includes Haunt,
HauntBuffer and Hud, with an explicit alias for Haunt's fixed-array type:

```c
#include "host.h"
#include "Home.h"
#include "Player.h"
#include "Grid.h"
#include "Cast.h"
#include "Wallet.h"
#include "Camera.h"
```

From there, Swift calls Coax like any C library. Here's the camera, in
`HomeViewController.swift`. When you tap Start, Swift captures the current
shot and starts a dolly, passing the system's Reduce Motion setting so
Coax can turn the swoop into a cut:

```swift
let from = lastShot ?? metaverse_camera_overview(0)
stage = .arriving(metaverse_camera_dolly_start(from, now, UIAccessibility.isReduceMotionEnabled))
```

Swift keeps the returned `coax_t_Dolly` in an enum case, and on every
frame it asks Coax where the camera should be:

```swift
case .arriving(let d):
    shot = metaverse_camera_dolly(d, timestamp, follow)
    if metaverse_camera_dolly_done(d, timestamp) { arrive() }
```

Notice the division of labor. Swift owns the clock, the touches, the
accessibility setting and the stage the screen is in. Coax owns the math:
the curve, the easing, when the dolly is done. The `Dolly` value is just
data that Swift holds and passes back, so Coax has no state of its own to
keep in sync. That's the shape the repository's rules ask for: product
logic in Coax, platform effects in the host.

## Checking it against C

When you move a subsystem from C into Coax, "it seems to work" isn't
enough. The strongest evidence is to run the old code and the new code on
the same input and compare the outputs exactly.

`coax/examples/pulse` does this for a kernel shaped like the per-frame
pulse update in the old engine. This is the kernel, with a `main` added so
it runs on its own:

```jai
// The kernel from examples/pulse/pulse.coax, with a main so it also runs alone.
#import "Basic";

Pulse :: struct {
  position: f32;  // 0 <= position < 1 along the current channel
  speed: f32;     // channel lengths per second
  channel: s32;
  hops: s32;      // channels left to cross; 0 means it has arrived
}

CHANNELS :: 64;

route :: (channel: s32) -> s32 {
  return (channel * 17 + 5) % CHANNELS;
}

advance_pulses :: (pulses: [] Pulse, dt: f32) -> s64 #export_c {
  arrived: s64 = 0;
  for i: 0..<pulses.count {
    p := pulses[i];
    if p.hops == 0 { continue; }
    p.position += p.speed * dt;
    while p.position >= 1 {
      p.position -= 1;
      p.channel = route(p.channel);
      p.hops -= 1;
      if p.hops == 0 {
        arrived += 1;
        break;
      }
    }
    pulses[i] = p;
  }
  return arrived;
}

main :: () {
  pulses: [3] Pulse;
  pulses[0] = Pulse.{position = 0.5, speed = 2, channel = 1, hops = 1};
  pulses[1] = Pulse.{position = 0.25, speed = 1, channel = 7, hops = 3};
  pulses[2] = Pulse.{position = 0.75, speed = 0.5, channel = 9, hops = 0};
  arrived := advance_pulses(pulses[..], 0.5);
  print("arrived %\n", arrived);
  for p: pulses { print("%\n", p); }
}
```

*Listing 20-11: The pulse kernel*

```shell
$ coax run pulse_kernel.coax
arrived 1
Pulse.{position = 0.5, speed = 2.0, channel = 22, hops = 0}
Pulse.{position = 0.75, speed = 1.0, channel = 7, hops = 3}
Pulse.{position = 0.75, speed = 0.5, channel = 9, hops = 0}
```

`coax/examples/pulse/host.c` is a C program that makes 100,000 pulses and
runs them for 600 frames. Every frame it calls the Coax kernel on one copy
and a plain C version of the same loop on another, then compares the two
copies with `memcmp`. `run.sh` builds the header and a release object,
compiles the host at `-O2`, and runs it:

```shell
$ coax/examples/pulse/run.sh
100000 pulses x 600 frames: Coax matches the C reference byte for byte
arrived 61834, still moving 38166
time per frame: Coax 0.202 ms, C 0.202 ms
```

Byte for byte is a strong claim for floating-point code, and it holds for
the reasons in Chapter 16. Coax's generated C begins with
`#pragma STDC FP_CONTRACT OFF`, so the C compiler can't fuse a multiply
and an add into one instruction that rounds once instead of twice. The
host sets the same pragma, so both sides round once per operation, in the
same order. The Coax kernel keeps its bounds checks in the release build,
and at this size they don't show: both take about 0.2 ms a frame on the
Mac this was run on. That's one machine's measurement, not a promise.

## Metal functions

The same procedures can also become Metal Shading Language, for the scalar
math a shader calls. `coax metal` prints it. Take Listing 20-1 without its
`main` (the Metal profile has no loops or printing):

```shell
$ coax metal ease_only.coax
```

The output starts with `#include <metal_stdlib>` and declares both
procedures, keeping `clamp01` static as the C output does. Here is
`ease`:

```c
float ease(float l_x) {
  float l_t = coax_p_clamp01(l_x);
  return (((l_t * l_t) * l_t) * ((l_t * ((l_t * 6.0f) - 15.0f)) + 10.0f));
}
```

Every operation is parenthesized, so the grouping is spelled out rather
than left to Metal's precedence rules.

Try it on the original file and the compiler says why it can't:

```shell
$ coax metal ease.coax
ease.coax:16:3: error[E0377]: a loop is outside the Metal scalar profile
    for i: 0..<5 {
    ^
  fix: Metal libraries use f32 and bool, if/else and calls; no loops, strings, integers or host calls
1 error
```

The app uses this for `metaverse/light.coax`, its sky, dots, glass bar,
bloom and tone mapping. Originally `generate.sh` ran `coax metal
metaverse/light.coax` and appended hand-written stage functions from a
companion Metal stage file (`Stages.metal`); today full Coax graphics shaders
compile directly via `coax metal`, `coax wgsl`, and `coax spirv`. The tests
run the C build of the same file, so one source is checked on the CPU and
drawn on the GPU. Chapter 17 covers GPU programs in general.

## Planned: buffers without copies

> Note: Not implemented. This is roadmap R23 (spec stage 11).

The views above already cross the C boundary without copying, but only
for host memory whose lifetime the caller holds. A simulator and a learning
library that run on the same GPU want the same for device memory. A planned
import would take another component's buffer as a view with its layout,
placement, lifetime and synchronization stated, and refuse to use it after
the exporter releases it. Every transfer between host and device would be an
explicit effect that `coax explain` counts, so a step that quietly reads
state back to the CPU fails its transfer budget instead of just running
slowly. Psionic's leased DLPack views are the first consumer.

## A fallible adapter keeps decisions in Coax

The [file adapter](https://github.com/OpenAgentsInc/openagents/blob/main/coax/lib/sys/read-file.coax)
from Chapter 7 uses four C effects: open, stat, read and close. C reports raw
observations; Coax constructs typed errors and controls cleanup. The native
header and generated header are compiled together in both include orders.
The initial tagged-value ABI has its own schema identity: an old header with
the same size is insufficient. Use the generated active-alternative contract;
inactive payload bytes and padding are not a wire format or equality oracle.

The asynchronous
[System One owner](https://github.com/OpenAgentsInc/openagents/blob/main/coax/lib/systemone/owner.coax)
keeps the same split. The host's process handle is a reusable slot, so callers
retain a generation ticket rather than authority to cancel that raw slot.
Reaping the child ends its buffer access; taking a result copies into separate
caller buffers before their descriptors escape. Destination disjointness,
canonical-owner exclusivity and snapshot lifetime remain explicit caller
preconditions. A generated default constructor must run before the first use;
zero-filled native memory is not a substitute for Coax defaults such as `-1`.

The independent native checks inspect named fields, guarded buffers, process
effects and the real generated constructor. They run at O0, O2 and under fatal
ASan/UBSan. They do not compare padding or infer a complete application's
readiness from one successful C compilation. Follow the complete request in
[Chapter 15](ch15-asynchronous-work.md) and the joined route in
[Chapter 24](ch24-a-complete-boundary.md).

## What isn't here yet

A few parts of the design are still ahead, and it's worth knowing their
shape so you don't wait for them in the wrong place.

> Note: C++ will stay behind `extern "C"` shims. Coax won't parse C++, so
> classes, templates and libraries like metal-cpp get a few lines of C
> wrapper per entry point. This is a decision, not a missing feature.

> Note: Headers are meant to record more than layout: calling convention,
> ownership, nullability, callback lifetimes and which allocator frees
> what. Today they record sizes, alignment and offsets, as checked
> assertions, and the opening comment states the rest in words.

> Note: Pointers in `#foreign` signatures, and so C functions that take
> buffers from Coax, wait on an ownership rule. Use handles until then.

## Summary

Coax meets every other language at C. `#export_c` keeps a procedure's
name and puts it in the generated header; `coax header` writes that
header, `coax lib` compiles an object without a C `main`, and
`coax c --library --header` produces C source for toolchains like Xcode
that build for several targets. Structs cross as `coax_t_Name` with their
layout asserted, views as `{data, count}`, and enums as an integer type
with one macro per member. `#foreign` lets Coax call C functions with scalars and borrowed views,
with the shared header making the C compiler check both sides.

We also met the boundary's sharp edges: a failed check aborts the host,
struct names must be unique across all the headers a program includes,
exported procedure names share C's one namespace, and Swift can't see the
enum macros, so it keeps its own table of codes.

All of this was on one Mac, for one Mac and the iPhone. In the next
chapter we'll look at what it takes for Coax to call a platform supported,
and what we'd have to prove before running it in a browser.

For project boundaries before general source modules exist, see
[Chapter 10](ch10-organizing-programs.md). For native debugging and costs,
see [Chapter 12](ch12-debugging-and-cost.md).
