Stories: C Interface

See also: spec/ffi.md — the rules these chapters explain.

A C interface that keeps compile-time evaluation

The math functions had already turned a C interface down once. The math story settled on intrinsics for the square root and left a C interface for the libraries that really are written in C, with a list of questions it would have to answer first: how C code that can write a file with no capability fits an effect model with no ambient authority, where C pointers go in a language of owners and references, how C affects the guarantees a spawned call relies on, and how a program that links C stays a program one machine builds for every target. Those libraries did not stop existing. Compression, hashing, image decoding, SQLite: a language without a route to them has to rewrite each one before its programs can use it.

One more question sat under that list, and its answer set the shape of everything else. The math story had noted in passing that a call into C is opaque to the compiler, so a computation that passes through one can no longer be done at compile time. Every C interface we looked at accepts that. A Rust extern function, a Zig function from @cImport, a cgo call: the compiler sees a declaration, assumes the worst, and evaluates nothing that depends on the call. For those languages it costs little, because a programmer opts into compile-time evaluation by writing const or comptime. In Zane it is not opt-in. The compiler may evaluate any computation that depends on no parameter and no read of capability-backed state (effects.md §5.3), and it does so across package boundaries. An opaque C call would put a wall in the middle of that: a Zane function that computes a checksum through zlib, called with a string literal, would be the one computation in the program that could not fold, and so would everything built on its result.

So we turned the default around. A call into C is a computation like any other unless its declaration marks it as reaching outside the program (ffi.md §5.4). The binding opts into impurity; it gets purity by declaring nothing.

The deciding question was which of the two marks authors would actually write. A default stays right only if the people who must leave it have a reason to, and only one direction gives them one. A binding author whose C function reads the clock, under our default, has every reason: left unmarked, the call folds and the program shows the time it was built, a bug the author will meet the first time they look at the output. A binding author whose C function is pure, under the opposite default, has none: left unmarked, the call merely runs at run time, the program is correct, and nothing ever prompts them to add the mark. GCC’s __attribute__((const)) and D’s pure are that opposite default, a promise of purity a programmer may make and everything else unknown, and they are rarely written for exactly this reason. Opt-in purity would have left nearly every binding opaque, so the wall in front of compile-time evaluation and implicit parallelism would have stood wherever an author never thought of the attribute. Opt-in impurity puts the mark where leaving it out is noticed, so the authors who need it are pushed to write it.

The cost of this default is that it is the dangerous default. A conservative default fails safe: a pure function left unmarked merely runs at run time. Ours fails the other way. A C function that reads the clock or the environment, declared as if it read nothing, is evaluated while the compiler runs, and the value the build machine saw is built into the program. Nothing reports it. The program simply gives the same answer on every machine, forever. We decided that this had to be stated outright in the spec rather than left to be inferred from the folding rule, as a requirement with its consequences listed (ffi.md §5.5): a binding author who forgets will not be warned by the compiler, so the warning has to be in the text they read.

The word for the declarations came quickly. A foreign verb is a function or method whose body is a C function: “foreign” is the established word for code in another language reached through an interface, the F in FFI, and “verb” is already the spec’s word for a function or method. Writing foreign "symbol" where the body goes kept every other part of the declaration ordinary Zane, and the symbol had to be a string because C names are not Zane identifiers: sqlite3_open has an underscore in the middle, and SDL_Init begins with a capital, which Zane’s casing rule reads as a type.

Impurity is a capability, not a comment

With purity the default, the next question was how a binding declares the opposite. The first idea was a doc comment on the C side. A header already documents its functions, so a line like /// @zane reads above a prototype would put the mark next to the code it describes, in the file the binding author is already editing, without touching Zane’s grammar at all.

We moved away from it for three reasons, and the first was the failure mode itself. A comment the compiler reads has to be exact, and a mark spelled @zane read or placed one line too high is not a syntax error; it is a comment. Since the cost of a missing mark is a silently wrong program, the mark is the last place we wanted a typo to be invisible. The second reason was that a comment marks a function as impure without saying who may call it. Any verb anywhere could call a function marked as reading the clock, which is exactly the ambient authority the effect model forbids (effects.md §6.1) and the first question the math story had raised. The third was that Zane already has a mechanism for marking a call that touches outside state. A capability is an object whose methods reach external state, a call through it with : reads that state, and one with ! writes it. Nothing about a C function needed a vocabulary of its own.

So a foreign verb that reaches outside the program is a method on a capability. Without mut it reads; with mut it writes. A foreign verb that is a plain function, or a method on an object of the program’s own, reaches nothing. The mark the binding opts into is the capability in the signature, which the compiler checks like any other type, and every call to it shows the capability at the call site. Where that capability comes from took us two attempts, and the next chapter recounts them.

We also considered the road the effect model had already turned down for Zane code, two keywords such as reads and writes on a declaration. They would have been checkable, which the comment was not, but they would have been the purity keywords Zane does not have, and they would still have left the ambient-authority question open. The capability answered both.

The cost lies in the capability’s limits. It cannot make a binding author declare it: a C function that reads the environment, written as a plain function, compiles and folds, and that is why the requirement is written out with its consequences rather than left implicit. It is also coarse. Every capability call is taken to touch one shared external state (ffi.md §5.6), so two writes through two different files are serialized as though they might collide. Zane cannot see what C code behind two capabilities shares, so it cannot prove they do not, and we preferred an ordering the compiler can keep to a parallelism it could only presume.

Capabilities come from C

Our first answer to where a C call’s capability comes from was the compiler. The console and the runtime were the only capabilities it supplied, and C code reaches far more than either, so we added a third, @runtime$System, with one instance reached by the root package and passed on like the other two. A C object that stood for outside state, such as a database connection, needed more than that, since every query writes the connection and the file together. So we gave foreign handles a second kind, #capability, beside the #handle of program data, with a rule that only a mut method on a capability could make one.

It did not survive three questions we put to it once it was written down. The first was why the C interface needed two kinds of handle when Zane needs only one kind of object: a capability in Zane is just an object whose methods reach outside state, so an object of C’s should be able to play the part without a kind of its own. The second went deeper. Asked how the C side provides its capability, we had to admit that it provides nothing: @runtime$System belonged to Zane, the C library knew nothing of it, and the binding author’s signature was the only link between the two. The third was about the files. A capability that stands for one open file had always read oddly: the file system reaches outside the program, and a file is an object it hands out.

The design we replaced it with answers all three. The C code declares a global for what it offers, a file system or a clock, and the binding names its type with a handle. The root package takes it up and passes it on. That puts the capability where the access is: the library that reaches the file system offers the object that stands for it, and the program’s root determines who receives it. We weighed an extern mark on each foreign verb on the way there, which would have moved the impurity onto the function, but it still left open where authority came from, and the global answered that as well.

The spelling went through two forms. The first was an intrinsic call, clock Clock = @cffi$PackageVar("clock"). We replaced it with a declaration shaped like a foreign verb, a symbol whose value comes from C in place of an initializer, files fs$Fs foreign "zane_fs" (ffi.md §5.1). The global is looked up in the package that declares the type, which already identifies whose C is meant. Only the root package may write one, for the reason only the root may name @program$console: if any package could declare a foreign variable, any library could make a clock out of nothing, and receiving one as a parameter would grant nothing. With capabilities coming from C, @runtime$System had nothing left to do, and we removed it before it shipped.

A file then took the form we had wanted for it. It is a handle the file system makes, and every operation on it is a method on the file system, files!fs$write(log, data). That needed one rule the old design had not: a mut method on a capability may change the handles it is passed, because the open file is part of the outside state the capability writes (ffi.md §4.4). The distinction between program data and outside state did not go away, but the binding stopped declaring it. A handle that a capability’s method makes is an outside handle, and any other is a data handle, so the compiler reads the handle’s category from its maker (ffi.md §4.1). One declaration form serves all of them, and a handle without a free function, such as a global, is a foreign capability.

The cost is the root’s. A program that reads a file, the clock, and a database declares three foreign variables in its root package and passes each where it is needed, where the first design passed one system. In exchange it can give a library the clock without the file system, which the single system could not express, and the authority each part of the program holds is written in what it receives.

Evaluating C as the target runs it

Defaulting C calls to computations promised that they fold, and a promise of folding is a promise that the compiler can run the C code. The folding rule also limits what running it may do: it may change nothing the program computes (effects.md §5.3). That ruled out the first way we thought of doing it.

The obvious mechanism was to compile the C code for the machine the compiler runs on, load it, and call it. It is fast, and it is wrong whenever the build machine is not the target. C’s own types change size between targets, long most famously, and a compression library computes differently with a 32-bit long than with a 64-bit one. A cross build for Windows from Linux would fold every call with Linux’s answer. The approximate math functions had met the same trap (the math story), and they had settled it by leaving the platform library to run time.

So the compiler evaluates the C code as compiled for the target: the same code the program will run, read in its compiler’s intermediate form with the target’s layout of every type, and executed by an evaluator inside the compiler rather than by the build machine (ffi.md §5.4). A call that reaches a function the build has no body for, such as a function of the platform’s C library, stops the evaluation and is left to run time. That makes the approximate math functions behave in C exactly as they do in Zane: a C routine that calls sin does not fold, because sin is the platform’s.

Two settings of the C compiler had to be fixed for this to hold. A C compiler may contract a multiply and an add into one fused operation, and whether it does can differ between the code it is asked to inspect and the code it finally emits, so the same expression could round once at compile time and twice at run time. A fast-math mode lets it reassociate floating-point arithmetic at will. Either would make a folded result differ from a run one, so both are fixed off for every package’s C code, and no setting a package gives turns them back on (ffi.md §2.2). A library that was written to be compiled with fast math runs slower for it.

The cost is the evaluator itself. Running C’s intermediate form inside the compiler is a substantial piece of machinery, much slower than native code, and it is bounded by the same budget as every other fold, so a large C computation stops folding long before it would have finished natively. It also needs the C code’s bodies, compiled for the target, for every package whose calls it folds. That requirement settled the next question before we had finished asking it.

The toolchain builds the C, and CMake does not

Who builds the C code was the question we had expected to argue about longest. A C library usually arrives with its own build: CMake, Meson, autotools, or a Makefile. The natural reading of “use a C library from Zane” is to let that build system remain in charge, build the library as it always has, and have the Zane compiler link the result. The alternative is for Zane’s toolchain to compile the C itself.

Letting CMake manage the build would have meant one of two shapes. In the first, CMake drives everything and invokes the Zane compiler as one more compiler in the project. That fits a C project adopting some Zane, but not a Zane package: a library published with prebuilt objects for every target (dependencies.md §3.1) would need CMake and a C cross compiler on every machine that builds from source, and a consumer of that package would need its build system before it could compile a line. In the second, the Zane toolchain runs each package’s own build system, the way Cargo runs a crate’s build.rs. That would have made fetching a dependency run whatever program the dependency ships, on the machine that fetched it, which sits badly beside a dependency model that verifies every byte it downloads. It would need the build system installed on the host, it would build for the host unless every build script got cross compilation right, and its output would depend on what else that host had installed.

Neither shape could have given the previous chapter what it needed. Folding a call into C requires the C code’s bodies, compiled for the target, in the compiler’s hands. Checking a foreign verb against its C declaration requires seeing the header with exactly the definitions and include paths the C code was compiled with, for each target (ffi.md §3.7). A library that comes out of someone else’s build as an archive gives the compiler neither.

So the toolchain compiles a package’s C itself, with the C compiler it already carries for every target, from settings stated as data. Zig took the same road with zig cc, and we put the C where Go’s cgo puts it: the .c files in a package’s directory are part of the package, exactly as the .zn files are. Nothing the package supplies runs at build time. Everything else followed from that. The C objects go into the release archive with the Zane objects, so a consumer needs nothing new. The C symbols are renamed into the package’s namespace like its Zane symbols (ffi.md §2.5), so two versions of a package that vendors zlib coexist in one program, as two versions of anything else do.

Where those settings live took a second attempt. We first put them in a c block of the project’s zane.coda, one row per setting with a column naming the package it was for. That was the wrong file. zane.coda and zane-lock.coda are written by commands, which keep the two in sync, and nobody edits them by hand (dependencies.md §2.3), while a C build’s source list, include paths and definitions are written by hand, as source is. So the settings moved into a c.coda in the package’s own directory (ffi.md §2.3), and the package column went with the move. The file also travels with the package, so a package moved to another project keeps its C build without anything in the new project’s manifest having to change.

The .h files directly in the package’s directory became its interface headers: the headers that state the interface between the package’s C and its Zane, as distinct from the library’s own headers in its vendored tree, which only the C compiler reads. Keeping the declarations a foreign verb may name to a handful of files the binding author wrote gave the compiler a small surface to check, and gave the binding a place to adapt a C API whose types do not cross, which the next chapter needed.

The cost falls on the libraries with the most elaborate builds. A library that generates source at configure time, or that picks hundreds of files by probing the host, has to have its build written out again as a source list, as the projects that package C libraries for Zig’s build system do. Some will not be worth it, so a package may also link a prebuilt archive or a library of the target system (ffi.md §2.4). Those work, and the C interface would have looked like them everywhere had we taken the other road: the compiler cannot read them, so nothing that calls them folds, and building for a target needs that library built for it.

C never writes Zane memory

The last of the math story’s questions was where C pointers would go. Zane has owners and references, settled and roaming, and a reference is minted only from a place that never moves. A C pointer is none of these, and it can point anywhere, outlive anything, and be written through by anyone who holds it.

Zig’s answer is to let C’s types into the language as they are, pointers included. That works for Zig because Zig has pointers already. Giving Zane a pointer type for C would have given every Zane program one, and every guarantee the memory model makes would have carried an exception for it. Passing addresses as integers was the same answer in disguise. We also looked at letting C write into Zane values passed to it, the out-parameters C APIs are full of. That would have made a parameter writable, and every parameter other than a mut method’s subject is read-only (effects.md §4.1), which is what the overlap rules and the spawn rules are built on.

So nothing Zane owns is ever written by C. Strings, arrays, and lists cross as read-only views that last for the call (ffi.md §3.4), which is exactly what a borrow already is. What C needs to keep between calls lives in C memory, and Zane owns it through a foreign handle: a reference type that holds one C object and calls its free function when it is destroyed (ffi.md §4.2). “Handle” is the word C APIs already use for the opaque pointer they hand out, so a binding author recognizes it at once. Every handle is declared with #handle, whether it holds state of the program’s own or stands for outside state, as the earlier chapter tells. The # it carries is the # every reference type carries: a C object has identity, can be pointed at, and is moved rather than copied, so it sits on the reference side of the axis and gets settled and roaming owners, & references, and deterministic destruction for free. Only a mut method writes its subject, so C receives a writable pointer to a data handle only there and a const one everywhere else, and the header check holds the C declaration to that.

The narrow set of types that cross was a choice made on the same grounds. A type crosses only if it has the same meaning on every target, which is why long does not, and only if Zane can lend or copy it without C keeping hold of anything. The rest of a C API is reached through a small C function in the package that converts it, and that is cheap to write precisely because the toolchain compiles the package’s C: a shim is one more .c file beside the binding.

The costs are concrete. A string returned from C is copied, once, into Zane’s own storage. A C function that changes two data handles at once has to be split into functions that each change one; only a capability’s mut method changes several objects, because they are all part of the outside state it writes. A callback is a function value that does not capture, which is all Zane’s lambdas are, so C APIs that pass a void * of user data back to their callback have no way to carry a Zane object through it. A C object that refers to another, a statement to its connection, is kept alive only if the binding marks the dependency with an & beside the handle (ffi.md §4.5). And the boundary is a promise rather than a proof: C can still write through a const pointer or keep a view it was lent, and when it does the program has no meaning the spec defines (ffi.md §6). What the design buys is that the promise is small enough to state in a list, and that a binding that keeps it leaves every guarantee of the memory model standing on the Zane side.

Replacing a handle in place

The first rule for overwriting a handle was the strictest possible: a settled place that held a handle was never overwritten. We had to ask ourselves why, since a C function that makes a new object should be able to replace an old one like any other assignment.

The answer is in what overwriting means. Overwriting a settled owner in Zane writes the replacement at the same address, so every reference to the place sees it. A handle’s place holds only a pointer, and the object lives in memory its C library allocated. A new connection always lives at another address, so overwriting the place means freeing the old connection, and C objects can hold its address without Zane knowing: a prepared statement keeps a pointer to its connection and reads it on its next call. Nothing interrupts C or races with it. The statement’s own memory simply holds an address that the assignment has freed. Zane cannot make C put a new object where an old one was, because it does not make C objects.

We weighed three ways out: allow the overwrite where no & to the place was ever taken, keep the old object alive until the scope drains, or keep the strict rule. We turned down the first because C can hold pointers that no Zane reference reflects, a library’s own table or a registered callback among them, so the absence of a reference proves nothing about C. What replaced them was simpler: when the C library provides a setter, a function that replaces an object’s contents at the address it already has, Zane overwrites through it, and without one the overwrite is an error (ffi.md §4.3). That is Zane’s own meaning of overwriting, kept by the one party that can keep it. A library whose objects cannot be moved between owners, as a statement cannot move to another connection, provides no setter, and its handles stay where they were made. A binding that wraps its objects in a small struct of its own writes one in a few lines.

The setter also settled how a handle is declared. It had been #handle("ctype", "free"), positional, and with a setter and a free function both optional the positions became ambiguous. Named constructors per combination came up and went, and we settled on a field-constructor call, #handle{ cType = "zane_file_t"; set = "zane_file_set"; free = "zane_fclose"; }, which names each entry and leaves out what a handle lacks. The setter comes before the free function because that is the order a program uses them in. A handle with no free function is the foreign capability of an earlier chapter, and naming the C types with a _t keeps them apart from the globals of the same name, which C would otherwise refuse.

C strings, allocated results and callback arguments cross without shims

The earlier chapters argued that a shim is cheap, because the toolchain compiles a package’s C and a shim is one more .c file beside the binding. Once the C interface could build and call real libraries, we wrote bindings to three of them to see what that promise was like to live with: SQLite, vendored as its amalgamation, raylib 5.5, and a file-system library of a few functions written for the purpose. All three worked. All three also carried C that adapted no C API at all. It existed only to get past the boundary, and every binding wrote it the same way. A shim that adapts an API to Zane is the binding’s own work. A shim that every binding copies is work the boundary should be doing, so we went through the bindings and took those away.

The first two were small. SQLite declares sqlite3 in its own header, under vendor/, and a handle’s cType had to be declared by an interface header, so the binding repeated typedef struct sqlite3 sqlite3; in a header of its own. The interface headers exist to keep the C functions a foreign verb may name few and checked, and a handle’s C type is checked for a smaller property: that it names a struct, which the compiler can read from a header the interface header includes as well as from the interface header itself (ffi.md §4.1). So a cType may now come from the C library’s own header, and the functions stay where they were. We could have kept the rule and made its error message suggest the typedef, but that left the line in every binding. Free functions were the same kind of declaration. sqlite3_close returns a status, a free function had to return void, and each handle needed a one-line C function that dropped the status. A free function or a setter may now return an integer, which Zane ignores. The cost is that the status is lost, and a binding that has to act on it still writes the wrapper.

Strings were the shim every binding wrote most often. A Zane string carries its length and no terminator, and most C functions that take a string take a const char *: sqlite3_open, raylib’s DrawText, fopen. So nearly every wrapper began the same way: allocate one byte more than the string, copy it, write the NUL, make the call, free the copy. Zane cannot simply add the NUL itself, because a string’s block is exactly as long as its bytes and there is no room after them. We considered shipping a helper in <zane_ffi.h> that makes the C string, and turned it down because every binding would still write the call. Instead the C declaration determines the form, as it already does when it takes an array as const E * and a list as zane_span: a string parameter that C declares const char * receives its bytes followed by a NUL (ffi.md §3.4), and one declared zane_bytes receives the view and pays nothing. The terminated bytes are a copy, made for the call, in the call’s own frame for a short string. A string that holds a NUL reaches a const char * parameter as the bytes before it. A result stays a zane_bytes, because a const char * gives neither a length nor an owner to free it.

Returned strings had the opposite problem. The call copies a returned string, so its bytes have to outlive the C function, and nothing frees them afterwards. The file-system binding kept its last result in a per-thread buffer, only so that it could free the buffer on the next call. We could have had Zane free the bytes it was given, but then Zane would have had to know which allocator made them, and we could have added a returned view that carries its owner, but that would be a second string type at the boundary. What we chose instead is an allocator in <zane_ffi.h>, zane_bytes_alloc. It gives C bytes in the memory the string will live in, and a returned view that starts at those bytes becomes the string with no copy at all (ffi.md §3.5). This retires the copy the previous chapter counted among the costs, for C that asks for it. C now writes Zane memory in exactly one place: the bytes it allocated for the string it is about to return, and nothing else Zane owns is any more writable than before. Bytes that C allocates and does not return are released when the call returns, since C keeps nothing Zane gives it. The cost is that only the call’s last allocation is taken without a copy. And the allocator works only on the thread that made the foreign call.

Callbacks had been held to numbers, @primitives$Bool and C-compatible value types, so “call me with each file name” or “with each row’s text” could not be written. We had asked whether a callback could take any Zane type, and the honest answer was that it can take the types C has a type for, which are the types a foreign verb already takes. So a function value now takes strings, lists and arrays, which C lends and the function value receives copies of before it runs, and data handles: a borrowed one, or a roaming owner ^H, in which case C gives up the object and Zane releases it (ffi.md §3.6). Variants, enums and other reference types have no C form, and capabilities stay out. A capability reached from inside a call that is otherwise capability-free could be folded at compile time, against everything the impurity chapter set up. A string reaches a callback only as a zane_bytes, because the C function a lambda is passed to is not known when the lambda is compiled, and its entry has to have one shape. The other limit a callback has, that a lambda captures nothing, is a language question, not a C question, so it stayed unchanged. Every lambda whose type C can now call gets the entry and the adapter, whether or not it is ever passed to C, and every argument C lends it is copied once.

Last, the C compiler’s warnings had never been shown, an uninitialized read among them. Showing all of them would bury a binding in what its vendored library’s thousands of lines produce. So we show the warnings of the sources directly in a package’s directory, the binding author’s own files, and only for the project being built (ffi.md §2.2). A warning still fails no build.

Two of the shims stayed. raylib’s Color is four bytes, so it needs 8-bit fields, and Zane has no 8- or 16-bit numbers that would lay out the same way. That is a change to the type system, not to the boundary, and it is a round of its own. A helper that writes to two capabilities at once, such as the console and a database, cannot be written either, because only a method’s subject is writable, and that holds throughout Zane, not just at the boundary. There we decided that the right tool is the tool the boundary already has: the programmer writes one more C function, made for Zane, that does both writes.

C state is independent per handle

Once a worker pool’s element could hold constants, a hundred sessions could each send on their own socket, and they still took turns. Every call that reads or writes capability-backed state through a foreign capability was taken to touch one external state, whatever capability it was made through (ffi.md §5.6). Reads could run together, but a write waited for every other access, and sending and receiving are both writes. A session in the middle of a receive held the one slot every other session needed, so the workers ran in parallel and their I/O did not.

The rule was as wide as it was because the compiler cannot see inside C. Two sockets are two Zane objects, but the C behind them may share state the declarations never mention: a library that frames every message in one static buffer before writing it would, if two sends overlapped, deliver one client’s message to the other and lose the first. Treating all of C as one state is the assumption that is safe when nothing is known.

Our first answer was to let a package say otherwise, with an entry on a handle’s declaration asserting that calls on two of its handles share no C state. Writing it down showed that the spec already made that promise on every package’s behalf, for every call that touches no capability: such a call may run in parallel with any other work, including another call to the same C function, so its C code is already called from several threads at once (ffi.md §5.6). The old rule did protect one case that rule does not: a library whose shared buffer only its capability methods touch, which the single external state kept in order. Making independence the rule takes that protection away, and we chose to, because holding capability calls to a stricter standard than the rest of C asked every binding to pay for the libraries that share state, where the binding of such a library can keep the order itself. So we made independence the rule rather than an option: C state is independent per handle (ffi.md §5.6).

A definition of independence has to name which state a call touches, or two sends on two sockets would still meet at the one capability they are both made through. A mut method on a foreign capability that takes an outside handle writes that handle’s state and only reads the capability’s own; one that takes no outside handle writes the capability’s own state. So sends on two sockets run together, two calls on one socket stay ordered, and a call that takes no socket, such as opening a listener, is ordered against everything else made through that capability. That gives C the granularity Zane’s own memory already has, one writer per handle as there is one writer per location, with the difference that for memory the compiler proves it and for C a package’s author is trusted with it. We will add networking to the language as an intrinsic, and its sockets will not reach through C at all, but C libraries for audio, graphics and databases need the rule either way.

The cost falls on bindings to C libraries that do share state between handles, as many older ones not written for threads do. Their calls now race unless the binding routes every call that touches the shared state through methods that the rule orders: methods of one capability that take no outside handle. Destroying an outside handle counts as a write to the capability that made it as well as to the handle, so a free function that touches the shared state stays in that order too. A binding that misses one has a data race the compiler cannot find. The rule is also silent on libraries that must always be called from the same thread, as many graphics and user-interface libraries must; that was true before it and is still open.

C holds a Zane object in a scope of its own

A plugin instance lives between calls: the host creates it, calls into it for as long as the user keeps the plugin open, and destroys it, in any order relative to the other instances. No Zane scope fits that, because Zane scopes nest and drain last-in-first-out. So an owner that an exported lambda returns to C settles in a top-level scope of its own, nested in no other (packages.md §8.5). C keeps an opaque pointer, never reads or writes through it, and passes it back only to exported lambdas. C writes nothing of the object, so the one place C writes Zane memory stays the bytes it allocates for a returned string.

Ending the object took a decision. An exported lambda that takes the object as ^T ends it, and our first reading made that an ordinary ^T parameter, which the body could move into some other object. But the object is settled while C holds it, because C keeps its address, and the memory model never turns a settled owner back into a roaming one. Allowing it would have forbidden every C-held type from holding an & into its own parts. We kept the simpler rule: the body may read the object but never moves it, and the object dies when the lambda’s scope drains. Every example we had, a destroy and a deactivate, only ever ended the object anyway.

The top-level scopes also settle the question of aliasing for free. Neither of two of them outlives the other, so the store rule already rejects an & from one C-held object into another, and the argument C passes is the only path to each object. The concurrency story builds on that single path.

A callback reaches its state through the subject

A window’s event loop calls back into the program while the user drags its edge, and the app has to draw a frame for every resize. Zane could already pass a function value to C, but a lambda captures nothing, so the callback had no way to reach the app it should draw. C libraries solve this with a pointer the caller supplies and the callback receives back, usually named userdata.

We made that pointer the foreign method’s own subject (ffi.md §3.8). A foreign method whose subject is of a reference type that is not a handle passes its subject to C as an opaque void *, the context, and a function value the call is passed may declare the same subject, which C hands back as its first argument. We considered a separately marked parameter, such as context App, but a parameter is read-only, and a resize callback has to write the app. The subject already carries mut: the callback may write the context only when the foreign method is itself mut on it, and what the callback writes counts as the foreign call writing its subject, which the effect rules already cover. No new keyword was needed.

We first let every subject that was not a handle be a context. A C-compatible struct such as Vec3 then had two forms, the copy C reads and the pointer C only passes back, and the form of an existing binding would have depended on a rule written for callbacks. We tied the form to the kind of type instead. A C-compatible value type crosses as a copy, a reference type that is not a handle as a context, and no other value type crosses as a subject at all. A context stands for an object in its place, as a reference type does, so the rule follows the line the language already draws. State of a value type that C cannot read, such as a GUI app, goes in a #struct that holds it, and a runner writes that wrapper once for every app.

The cost is that the context must be the subject, so a foreign call has at most one, and a C function that takes two user pointers is reached through a C shim. A context also lives only for the call, as every function value C receives does.