Memory management
Moxy manages memory automatically. You never call malloc or free for Moxy values, nothing leaks, and nothing is freed while you can still reach it. This page explains the model, why it was chosen over the alternatives, and the exact rules the compiler follows.
The short version
string,T[](lists) andmap[K, V]are values. Assigning or passing one gives the other side its own copy, the way anintworks. Copies are cheap because they share storage until one side writes (copy-on-write).ref structtypes are shared objects. Every variable that holds one points at the same object, and the object is freed when the last reference disappears.weakfields point at a ref object without keeping it alive. Use them for back-pointers (parent, owner, delegate) so cycles can't keep objects alive forever.unownedfields do the same with no counting at all, for back-pointers whose object always outlives the holder.- The compiler warns about
ref structtypes that can form a strong cycle, and debug builds list the objects still alive whenmainreturns. Programs that would rather not break every cycle by hand can build with--cycles, which adds a collector forref structcycles (The cycle collector). - Closures, futures and
Result<T>are managed the same way. deferruns a statement when the current scope ends (however it ends), for resources Moxy doesn't own, such as files, sockets and locks.gate { ... }makes everything inside come from one arena that is freed in one step at the closing brace; values that leave are copied out (see Gates).- Plain C is untouched: pointers,
malloc, arrays and structs of C types behave exactly as they do in C.
ref struct Node {
string name;
Node[] children;
weak Node? parent;
}
void main() {
int[] a = [1, 2, 3];
int[] b = a; // shares storage with a
b.push(4); // b gets its own copy here; a is still [1, 2, 3]
Node root = Node{ .name = "root" };
Node child = Node{ .name = "child", .parent = root };
root.children.push(child); // root keeps child alive; child.parent does not keep root alive
} // everything above is released here
How other languages do it
Moxy is a C superset, so whatever it does has to work with code that passes raw pointers around and calls C libraries. That rules out some designs. Here's how the main families compare.
| Approach | Examples | Pauses | Deterministic cleanup | C interop | Cost to the programmer |
|---|---|---|---|---|---|
| Manual | C, Zig, Odin | none | yes | native | high: leaks, double frees, use-after-free |
| Tracing GC | Go, Java, C#, JS, D | yes (short in modern collectors) | no (finalizers run "eventually") | awkward: GC must see every pointer, C can't hold GC memory safely | low |
| Ownership and borrowing | Rust | none | yes | good, through unsafe |
high: lifetimes, borrow checker |
| Reference counting with value semantics | Swift, Objective-C ARC | none | yes | good | low; cycles need weak |
| RC plus cycle collector | Python, PHP, Nim ORC | small, for the cycle collector | mostly | good | low |
| RC with compile-time optimizations | Lean and Koka (Perceus), Lobster | none | yes | good | low |
| Generational references | Vale | none | yes | good | low; checks at dereference |
Manual memory (C, Zig). Full control and zero runtime cost, but every allocation is a liability. Zig improves the ergonomics with defer and explicit allocators, and Moxy borrows defer. Moxy keeps manual memory available for C code, but doesn't make it the default.
Tracing garbage collection (Go, Java). Easiest for the programmer. But a tracing collector has to find every live pointer, which means stack maps or conservative scanning, and C code holding Moxy pointers would be invisible to it. Memory is reclaimed late, finalizers are unreliable for closing files, and the runtime is large. A conservative collector (Boehm) would work, but it gives up on determinism and makes "when is this file closed?" unanswerable.
Ownership and borrowing (Rust). Zero-cost and safe, but it changes how every function signature is written, and it rejects many ordinary C patterns. Moxy is meant to be C with conveniences, not a new discipline.
Swift's ARC. The compiler inserts retain and release calls, so the program frees memory deterministically, with no collector and no pauses. Two ideas make it pleasant:
- Collections and strings are values with copy-on-write, so aliasing bugs ("I changed my list and yours changed too") can't happen, and copies cost almost nothing until someone writes.
- Shared mutable state is opt-in (
class), and cycles are broken withweak/unowned.
Nim's ORC, Python. ARC plus a cycle collector, so cycles are reclaimed even without weak, at the cost of an occasional collection pass.
Perceus (Koka, Lean), Lobster. Reference counting where the compiler removes most retain/release pairs and reuses memory in place when a value is uniquely owned. These are optimizations on top of RC, not a different user-facing model.
What Moxy chose and why
Moxy follows Swift's model: automatic reference counting with value semantics for collections, plus opt-in shared objects with weak references.
- It works with C. Memory is freed at known points and nothing scans the stack. A
stringis still aconst char *that any C function can read. C code can keep a Moxy object alive by calling its retain function. - It's predictable. Memory is released at the end of the scope that owns it, in reverse declaration order, with no pauses.
- It's hard to misuse. Values copy like
int, so passing a list to a function can't change it behind your back. Bounds are checked, and a missing map key is a clear error, not garbage. - Cycles only happen where you asked for sharing. Values can't form cycles: a list containing itself is impossible because putting it in copies it. Only
ref structobjects can form cycles, andweakfields are the tool for that. - It's thread-safe where values cross. Values passed to
Futurefunctions, returned from them or sent on channels are marked shared and counted with atomics from then on; everything else is counted with plain increments. A plainref structcan't cross at all, and ashared ref struct's fields are written, and its counted fields read, underlockon that object, so no thread frees a value another is reading (Sharing between threads). Raw pointers into a shared object are outside this, as everywhere.
The trade-offs are honest ones:
- Retain and release cost an increment and a decrement, atomic ones for values that crossed a thread boundary (about 14 ns a pair against 2 to 5 ns on an M1 Max). The compiler skips them for borrowed values (parameters that aren't modified, loop variables, temporaries consumed in place), moves a variable at its last use instead of copying it, and reuses memory it holds alone (What the compiler removes); the remaining cost is small next to the allocation it protects.
- A strong reference cycle between
ref structobjects leaks unless one side isweakorunowned. By default there's no cycle collector; the compiler warns about the likely cycles and debug builds report what leaked.--cyclesturns on an opt-in collector for the programs that want one (Cycles). - Writing to a shared list copies it once. That's the price of value semantics, and you can avoid it by keeping one owner.
The rules
Managed types
These types are reference counted:
stringT[](lists)map[K, V]fn(A) -> RclosuresFuture<T>chan<T>ref structobjects
These are value types whose contents are managed:
Result<T>- structs with managed fields
- Moxy enums with managed payloads
- fixed C arrays of managed types
The compiler generates copy and release functions for them.
Everything else (numbers, pointers, C structs of C types, C enums) is plain C.
Ownership conventions
The compiler tracks whether each expression owns a reference (+1) or borrows one (+0):
| Expression | Ownership |
|---|---|
| variable, field, list element, map value | borrowed |
| function call result | owned |
literal list, map, struct with managed fields, Ok/Err, enum with payload |
owned |
string concatenation, interpolation, string(x) |
owned |
| string literal | borrowed (literals are immortal static objects) |
await f |
owned (a copy of the future's result) |
reading a weak field |
owned (a strong reference, or null if the object is gone) |
reading an unowned field |
borrowed (debug builds first check the object is alive) |
From that:
- Storing a value (into a variable, field, list, map, or a returned value) needs an owned reference. Borrowed values are retained first. Owned values are moved in.
- Passing an argument lends it (+0). The callee retains a parameter only if it modifies, reassigns or takes the address of it, so ordinary calls cost nothing. The caller keeps what it lends alive until the call returns: an argument read from a place the callee could change (a
ref structfield, a global, a local whose address the callee has, an element of a slice) is retained for the call, but only when the callee, or something it calls, may write such places. A callee that only reads gets it as is. - Temporaries that are owned but only read (
print(make_list()),f(a + b)) are released at the end of the statement. - Returning a local moves it out without a retain/release pair.
- Leaving a scope releases its locals in reverse order.
return,breakandcontinuerelease exactly the scopes they leave, then rundeferstatements in reverse order. - Iterating with
for x in xsholds a reference to the collection for the duration of the loop. Changingxsinside the loop modifies a copy, so the iteration stays consistent. When nothing can changexswhile the loop runs (a local the function never changes, or a parameter of a function that writes nothing outside itself), the loop reads it in place and holds nothing. Amatchon a variable works the same way. - The last use of a local moves it: storing a variable that is never read again hands its reference on instead of retaining a copy and releasing the original later.
Copy-on-write
Every list and map carries a reference count. A mutating operation (push, insert, remove, set, xs[i] = v, m[k] = v, sort, clear) first checks it:
- count of 1: the operation mutates in place;
- count above 1: the operation copies the storage, releases the shared one, then mutates the copy.
Strings are immutable. Operations that "change" a string return a new one. The one exception is invisible: s = s + x and s += x append into s's own buffer when s holds the only reference to it, so building a string in a loop is linear rather than quadratic. If anything else shares the string, it is copied as usual.
NULL is a valid empty list or map, so zero-initialized structs need no special setup.
Ref structs and weak references
ref struct T { ... } defines a heap object with a 16-byte header: one 64-bit word holding the strong count (low 32 bits) and the weak count (high 32 bits), and a pointer to a static descriptor for T (its drop and print functions, name and size). T{ .field = value } allocates one with a strong count of 1.
- Assigning or storing a
Tretains it. Releasing the last strong reference releases its fields and then frees the memory, unless weak references remain. - Releasing never recurses deeply: a million-node linked list is freed without growing the stack, and so are deeply nested lists and maps.
- A
weak Tfield adds to the weak count only. Reading it yields aT?: a strong reference if the object is still alive, ornullif it's gone. Memory is reclaimed once both counts reach zero. - Reading through a weak field (
n.parent.name) may meet null. Check a local copy (Node? p = n.parent; if (p != null) ...), or usen.parent?.name, orn.parent!.name, which panics with the location when the object is gone. Writingn.parent.nameon aweak Nodefield is a warning in 0.4 (W0207, an error from 0.5) and checked like!. See Weak fields. ==on ref objects compares identity.
Cycles
Reference counting can't free objects that hold each other: a parent that owns its children and children that point strongly back at the parent keep each other's counts above zero forever. One million two-node cycles leak about 63 MB (release build) without a word. Moxy has three tools for this, and an opt-in collector for when they aren't enough.
The cycle warning
The compiler builds a graph of ref struct types. Each strong field that can hold another ref struct, directly or through a list, map, array, value struct, enum payload, Result or generic instance, is an edge. An edge is to-many when a collection sits on the way (Node[] children, map[string, Node]) and to-one otherwise (Node next, an enum payload).
A type that can reach itself is not enough to warn: linked lists, binary trees and n-ary trees all can, and their values are almost never cyclic. The rule looks at each group of types that can reach each other (a strongly connected component):
- To-many and to-one edges in the same group: warn at every to-one field in it. A collection owns children; a to-one strong field from a child back into the group is the back-pointer that closes the loop. This catches
Node[] childrenwithNode parent, andAlbum { Track[] tracks }withTrack { Album album }. - Two or more types that only point at each other one-to-one: warn at the field that closes the loop, found by walking the fields from the type declared first; a type's links to itself are left alone.
Person { Flat home }withFlat { Person tenant }warns attenant. - One type that only points at itself one way: no warning.
Node next,Tree left, right,Tree[] kids,map[int, Table] next.
warning[W0202]: strong reference cycle: Track.album -> Album.tracks -> Track
--> src/main.mxy:6:40
|
6 | ref struct Track { string title; Album album; }
| ^^^^^
= help: make it weak: weak Album album; (or mark it strong to keep it)
The language server offers both fixes as code actions. Mark a field strong to keep it and silence the warning; strong means exactly what an unqualified field means.
The rule uses only the shape of the types, never field names. What it gets wrong:
- False positives: types that are trees of mixed node kinds, such as
Block { Expr[] body }withExpr { Block inner }, look exactly like a parent pointer. So does a collection plus an unrelated to-one link to the same type (Comment[] replieswithComment pinned). Mark those fieldsstrong. - Misses: a single type with two to-one links that form a cycle at run time (a doubly linked list with a strong
prev), and graphs whose nodes list their incoming edges strongly. The leak report catches these when they happen. - A
weakfield inside a plainstructis currently strong (onlyref structfields honour it), so the check counts it as strong.
On the repository's own tests, examples, benchmarks and debugger sample (15 ref struct types in 12 files, written before this check existed) the rule warns zero times. None of them has a real strong cycle either, so that measures noise, not recall; tests/memory/cycles.mxy and tests/memory/nocycles.mxy pin down which shapes warn.
The leak report
Debug builds (the default for moxy run, moxy build and moxy test; anything compiled without optimization or NDEBUG) keep a count of live objects per allocation site. When main returns, globals are released and every site with objects left is printed to stderr:
leak: 3 Node objects still alive, allocated at src/main.mxy:12
leak: 1 Box<int> object still alive, allocated at src/main.mxy:21
= help: objects that hold each other strongly are never freed; make the back-pointer weak or unowned (MOXY_LEAKS=0 turns this report off)
- It costs a site pointer per object (8 bytes, after the fields) and an increment and decrement per object. On binary-trees, which does nothing but allocate 16-byte objects, a debug build runs about 35% slower (380 ms against 280 ms) and peaks 40% higher with it. Release builds track nothing and run as before.
- It runs only when
mainreturns.exit(), a panic or a fault skip it, since locals are still alive then. moxy testfails a test whose program reports a leak.MOXY_LEAKS=0turns it off. Static locals and objects reachable only from C are reported, since Moxy can't release them.- Objects made by debug code and freed by release code in a different C file are reported as leaks: release code skips the bookkeeping. A Moxy program is one C file, so this only affects mixing separately built libraries.
unowned
ref struct Account { string name; Card[] cards; }
ref struct Card { int number; unowned Account owner; }
An unowned field is a plain pointer. Storing, reading and releasing it touch no counts in release builds, so it is cheaper than weak, which keeps a weak count and checks it on every read. Use it when the object always outlives the holder: an account owns its cards, so a card's owner is alive whenever the card is.
If that assumption is wrong, debug builds catch it. In debug builds the field also holds a weak count, so when the object's last strong reference goes its fields are dropped but its memory stays as a tombstone until the unowned references are gone. Reading the field checks the strong count and panics with the location instead of reading freed memory:
panic: read through a dead unowned reference
at src/main.mxy:13:13
A generation check was the alternative: it needs a word in every object's header (the header is 16 bytes and full) or a side table, and the memory still can't be reused while a stale pointer might be read. The tombstone reuses the weak count the header already has and costs nothing in release builds. In release builds a dead unowned read is a use-after-free, as in C, so test in debug.
unowned is only allowed in ref structs.
The cycle collector (--cycles)
moxy run --cycles app.mxy
moxy build --cycles app.mxy
moxy test --cycles tests
or, for a project, in moxy.yaml:
build:
cycles: true
With --cycles, objects that only hold each other are found and freed while the program runs. It is for programs whose object graphs are cyclic by nature and where finding every back-pointer is more trouble than it is worth: UI trees whose views point at their window and whose handlers capture the view they belong to, observers that hold the thing they observe, graphs. Without the flag nothing changes: the generated program compiles to the same machine code as before, byte for byte.
How it works. It is synchronous trial deletion (Bacon and Rajan, 2001) over ref struct objects only. When a release leaves an object with references, that object may now be held only by a cycle, so it goes in a buffer of possible roots. When the buffer reaches 10,000 entries (or the number of live objects the last collection looked at, if that is larger) the next ref struct allocation runs a collection: it subtracts every reference the buffered objects and what they reach hold on each other; whatever still has references left is reached from outside and stays; the rest is garbage. A collection also runs when main returns, before the leak report, and on a worker thread when a task ends. cycles::collect() from std/cycles.mxy runs one now and returns how many objects it freed.
What it covers:
- Cycles of any length and shape between
ref structobjects, including an object that holds itself. - Cycles that close through what a field holds: lists, maps, optionals, enum payloads, value structs,
Results, closures (their captures) anddynvalues. weakfields into a collected cycle read asnullafterwards, as for an object freed by counting.unownedfields into it are dead, and debug builds still panic on a read.Drop. All objects in a garbage cycle are dropped together, in this order: everyDropin the cycle runs first, with all fields intact (aDropmay read its peers' strong andunownedfields;weakreferences to anything in the cycle already read asnull); then every field of every object is released, so what only the cycle held is freed after all of the cycle'sDrops; then the memory. The order among the cycle's ownDrops is the order the collector found them in; don't depend on it. ADropthat stores a reference to an object in the cycle somewhere else (resurrecting it) panics: its fields are about to go.- Gates. An object made in a gate is never in the thread's buffer and never walked by its collections; nothing older can hold one (it is copied out first), so no heap cycle runs through it. A gate keeps its own buffer instead, collected as the gate closes, so the
Drops of cycles made in the gate run and what they held from outside the gate is released. In a release build a gate that never held anything older skips that step, since its cycles hold only its own memory, which goes at the closing brace.
What it doesn't cover:
- Objects other threads can reach. A
shared ref structthat crossed into a task, and everything reachable from it, is never collected: another thread could change its counts during a collection. Cycles of shared objects still needweakor breaking by hand. Each thread collects only the objects it made and buffered. - A list, map or closure held twice. The collector looks into a list, map, closure or
dynvalue only when the object holds it alone. If another variable holds the same list too, what's in it counts as reachable from outside, which is the safe answer; the object is looked at again at later collections, and the cycle is freed once the other holder lets go. Two objects in the same cycle sharing one list (a copy that was never written) keep that cycle forever. - Channels and futures are not looked into, so a cycle that closes through a value waiting in a channel or a future's result is not found.
- Types the compiler proves can't cycle are never looked at: a type that can't reach itself through strong fields and holds no closure or
dynvalue. Their objects carry no extra word and are never buffered. - Garbage another thread still has buffered when
mainreturns (a worker in the middle of a task) is not collected, and the leak report may list it. Workers collect when each task ends.
What it costs. Objects of types that can be part of a cycle carry one more word after their fields (their colour and whether they are buffered); the 16-byte header doesn't change. A release that leaves such an object with references costs a check and, the first time, a buffer append and a weak reference. Collections walk what the buffered objects reach. Measured on an M1 Max under load (load average 10 to 16), moxy build --release:
without --cycles |
with --cycles |
|
|---|---|---|
| binary-trees (depth 16) | 158 ms, 9.8 MB peak | 183 ms (+16%), 13.9 MB peak |
| list churn (10,000 nodes x 400) | 102 ms, 2.1 MB | 125 ms (+23%), 2.7 MB |
| 1,000,000 two-node cycles | 25 ms, 63 MB peak, all leaked | 103 ms, 3.9 MB peak, all freed |
Both benchmarks are worst cases: every object is a candidate (a Node that holds a Node can form a ring) and nothing in them is ever cyclic. The weak fix stays the cheaper one; --cycles is for when it isn't practical.
Closures
A lambda that refers to local variables captures them by value when it is created, retaining managed captures. The captured values are released when the closure is released.
A lambda that captures nothing compiles to a static, immortal object with no allocation. A lambda that captures nothing can also be passed where C expects a plain function pointer.
Futures and channels
A Future<T> call becomes a task on the thread pool, and an async call a task that runs on the calling thread. The arguments are retained for the task and released when it finishes. The future handle is reference counted:
- Awaiting returns a copy of the result; the task keeps its own until the last handle goes.
- Dropping the last handle cancels the task (see Cancellation). A task that never started releases its arguments without running.
A channel is reference counted like a future handle. send moves its value into the channel, and recv moves it out to the receiver; a value that is never delivered (the channel was closed, or the task cancelled) is released by the send. Values still buffered when the last reference to the channel goes are released with it.
An async call's arguments, captures and result stay on the thread that made the call, so they are not marked: they keep plain counts, and the caller and the async call change the same objects. Between two waits only one of them runs, and the compiler treats a call that may wait (await, a channel operation, select, an async or Future call) as one that may change anything the caller can reach, so a value lent to such a call is retained first.
Arguments, results and sent values of pool tasks and channels are marked shared as they cross, with everything they hold, and are counted with atomics from then on (a value marked once stays shared). Marking stops at values already marked, so each value is walked once in its life, and it uses a worklist rather than the C stack. A shared list or map is copied before it is changed, even when this is its last reference, so a thread that was handed it never sees it change. Globals any thread may read are marked when the thread that wrote them next crosses: it starts a task, sends on or closes a channel, finishes a task or leaves a lock.
defer
FILE *f = fopen(path, "r");
defer fclose(f);
A deferred statement runs when the enclosing scope ends: at the closing brace, or at any return, break or continue that leaves the scope. Deferred statements run in reverse order, interleaved correctly with releases of managed locals. They can't themselves return, break or continue.
Gates
A gate is a block whose values all come from one arena, freed in a single step when the block ends. Use one around work that makes a lot of short-lived values and keeps few of them: parsing a request, transforming a document, one frame, one batch.
string[] titles(string path) {
gate {
Doc d = parse(read_file(path).unwrap()); // every value parse makes comes from the gate
return d.headings.map((Heading h) => h.title); // copied out to the caller's region
} // the whole arena goes here
}
gate is a keyword only directly in front of {; a variable, field or function named gate keeps working.
Inside the block. Every string, list, map, ref struct object, closure and dyn box made while the block runs comes from its arena, including the ones made by the functions it calls. Allocation is a pointer bump. Reference counts still run on these values, since copy-on-write needs them, but no memory is freed until the closing brace. While the gate holds nothing from outside itself, the last release of one of its values doesn't even walk what the value holds: that all goes with the arena. A shared ref struct, a channel and a future handle are made on the heap, since other threads may hold them.
Leaving the block. A value is copied out at the point it leaves, into wherever it is going, with everything it holds that the gate made (a deep copy):
- returned from inside the gate, or from
?; - stored into a variable declared outside the gate, or a field or element of one;
- stored into a global;
- stored into an object, list or map that was made outside the gate, by the gate's own code or by any function it calls;
- stored through a Moxy pointer (
*out = s); - sent on a channel, passed to a future or captured by a closure passed to one (these go to the heap).
Values made outside the gate are never copied: storing one anywhere is the same as without a gate. A value the gate stores into one of its own variables or objects isn't copied either. With nested gates, a value stored into a variable of an enclosing gate is copied into that gate's arena, not to the heap.
The copy is the hidden cost of a gate. It is proportional to the value: one block for a string or a list of plain values ("flat"), a block for every value held for anything deeper ("deep"). moxy lint lists every copy the compiler can see, with its class, and moxy emit --explain-gates file.mxy > /dev/null prints each decision:
main.mxy:14:9: copies the returned string[] out of the gate (deep)
main.mxy:29:9: copies the string stored into 'kept' out of the gate (flat)
main.mxy:33:13: checks at run time where the string stored into 'h' must live (flat)
main.mxy:41:7: stores into a field of 't', made here (no check)
Calls. A function needs nothing special to be called inside a gate. In a program that uses gates, every store into a field, an element of a list or map held elsewhere, a global or through a pointer checks, when it runs, whether the value is younger than the memory it goes into, and copies it out if so. Outside a gate the check is a compare; inside one, two table lookups. Stores into the fields of an object the function itself just made skip it. A program without gates gets none of this code. A program with a gate anywhere pays for the checks in code that never runs in one: about 10 to 18% on allocation-heavy benchmarks (an empty gate added to binarytrees, listchurn and jsonroundtrip), most of it in the retains and drops, which check whether a gate that holds nothing older is open.
ref struct objects have identity, so they can't be copied out. Returning one made inside the gate, or storing it somewhere outside, is a compile error that names the line:
error[E0908]: a ref struct Node made inside a gate can't leave it: ref structs have identity and can't be copied out
--> main.mxy:16:9
= help: move the allocation out of the gate: create it before `gate {` and fill it inside
The compiler counts a value as made outside only when it is read straight from something declared outside the gate (a variable, parameter or global, or a field or element of one), or from a gate-local variable that is never changed and was initialized that way. A function's result counts as made inside, even when the function returns an existing object: call it before the gate instead. When a function called inside the gate stores an object the gate made somewhere older, the run-time check panics with both places:
panic: a ref struct Node made inside the gate at main.mxy:18:5 would outlive it here; it can't be copied out. Make it before the gate opens
at main.mxy:12:13
A weak or unowned reference to an object of the gate follows the same rule.
Ways out. The arena is freed at the closing brace and on every return, break, continue and ? that leaves the block, after the block's own variables and defers. A panic ends the program. goto, labels and case labels of a switch outside the gate are compile errors inside one, since they would jump past its start or end.
Threads. A task never allocates in a gate, not even one run in place by an await inside a gate. A task can have gates of its own; when it waits inside one, the worker runs other tasks meanwhile, and the task gets its gate back when it resumes. What crosses into a task, out of one or through a channel is copied to the heap first, so no other thread sees gate memory.
Async calls. An async call runs on the calling thread, but it can outlive the gate it was made in: a Future started inside a gate may be stored outside it and awaited later. So an async body never allocates in its caller's gate either, and an async call made inside a gate copies its arguments out to the heap (an async lambda's captures too). A ref struct made inside the gate can't be passed to one, a compile error like the others (a ref struct Box made inside a gate can't be passed to async 'read'). await inside a gate parks the caller, which finds its gate again when it resumes; other code that runs on the thread meanwhile has no gate open. An async body can have gates of its own and wait inside them.
in gate functions. Every function called inside a gate allocates in it, and its result comes back without a copy; nothing has to be declared for that. in gate after a function's parameters makes it a contract the compiler checks:
string[] tokens(string src) in gate {
string[] out = [];
gate { // scratch work, gone at its brace
for w in src.split(" ") { if (w.len() > 0) out.push(w.trim()); }
}
return out; // made in the caller's gate: no copy
}
Its body is checked as if it were inside its caller's gate, with its parameters counted as the caller's: a ref struct it makes can't be stored into a global, and stores into globals show up in moxy lint as copy-outs. A return from inside one of its own gates is an error, since that would copy the result out; declare the result before the inner gate, as above. Called outside any gate it is an ordinary function whose values go on the heap. async and Future functions can't be in gate, since their bodies never run in a caller's gate. moxy emit --explain-gates notes each one.
Arenas as values. gate { ... } frees its memory at the closing brace. For code that wants to decide when memory goes, or hold an arena across calls the way C code does, std/arena.mxy has Arena:
#include "std/arena.mxy"
Arena frame = Arena::new();
while (running) {
gate (frame) { update(world); } // what update makes comes from frame
gate (frame) { draw(world); } // and so does this, after it
frame.reset(); // both go here, in one step
}
frame.free(); // or let the last reference to it go
A gate (a) { ... } block follows every rule of gate { ... }: values that leave it are copied out to where they are going, ref struct objects made in it can't leave, and it nests with other gates. What differs is that its closing brace keeps the memory: a.reset() gives back everything the arena's blocks made and keeps the arena for more, and a.free(), or the last reference to the Arena going away, gives the memory back for good. Since anything that leaves a block is copied out, nothing one block makes is reachable from the next: an arena chooses when memory is released, it doesn't carry data between blocks. Rules checked when the program runs: one block of an arena is open at a time (on any thread), and reset() or free() inside one of its blocks, or any use after free(), panics:
panic: entered an arena after its free()
at main.mxy:8:5
An arena's blocks always run drops (a plain gate puts them off while it holds nothing from outside itself), and its memory isn't made inaccessible between blocks, only at reset() and free() in debug builds. An Arena is a shared ref struct, made on the heap, so it may be stored anywhere and passed to other threads.
What isn't checked.
- C pointers into gate memory.
const char *p = s;inside a gate, used after it, is a dangling pointer, as with any C pointer to memory that was freed. So is gate memory kept by C code (a C library holding a string it was handed). - Moxy values that C code stores somewhere: the checks are in the code Moxy generates.
longjmpout of a gate skips its closing, as it skips any other cleanup; don't.- Memory is not reused inside a gate. A loop that runs many rounds inside one gate keeps everything every round made until the gate closes; put the gate inside the loop instead.
Debug builds don't reuse a closed gate's memory right away: its pages are made inaccessible for a while (the most recent 256 MB), so reading through a pointer that escaped panics with the gate's location instead of reading freed memory:
panic: a value from the gate at main.mxy:9:5 was used after the gate closed; it escaped without being copied out
at main.mxy:13:5
Release builds reuse the memory at once and don't check. moxy test --gate-stress (or MOXY_GATE_STRESS=1 for any command) makes every function body a gate, with ref struct objects on the heap, so a value escape the compiler missed shows up as that panic in the test suite. make test runs tests/memory and tests/collections that way.
Where C rules still apply
- Raw pointers aren't tracked.
string *p = &s;is fine, butpmust not outlives. - A struct that contains managed fields must be zero-initialized before Moxy assigns to those fields. Use
calloc, a Moxy local, or aref struct, never uninitializedmallocmemory. gotojumps don't run cleanup. The compiler warns when a function mixesgotowith managed locals ordefer.- A managed local declared directly under a
caselabel is an error. Give the case body its own block. - Unions can't hold managed values. Use a Moxy
enumwith payloads instead.
What the compiler removes
The rules above say where references are counted. On top of them, code generation removes counting it can prove unnecessary, one function at a time (Perceus, as in Koka and Lean, adapted to statements and C):
Last use moves. A backward liveness pass over each function body finds the reads after which a variable's value is dead on every path: through
if, loops (to a fixed point),break,continue,return,matcharms and?. When such a read is stored (into a variable, field, list, map, returned value, literal, enum payload or channel), the reference moves:- if the read runs whenever the variable's scope is entered and nothing in the scope mentions the variable again, its release at the end of the scope is dropped;
- otherwise the variable is read through
mxy_take, which leaves itNULL, so its release later does nothing. This covers values moved in one branch, in a loop, or just before the variable is reassigned (prev = cur; cur = next;).
A variable is left alone when its address is taken, a
deferreads it, a closure captures it later, the function usesgoto, or the statement has a?(it could leave before the store runs). A list that a slice still views is copied at the move, as a retain would copy it. A move into a crossing is marked shared like a copy: a channel marks what it is sent, a future its arguments and result, and leaving alockwhat the object's fields now hold.Fields read just before they are overwritten.
Node? next = cur.next; cur.next = prev;takes the field instead of retaining it for the store to release a moment later, when the store's value is a plain variable or constant (nothing that could read the field runs in between). A field of ashared ref structis never taken.Dead pairs. A string literal is never freed, so storing one needs no retain. A temporary that a statement would release at its end is handed to whatever consumes it instead (the value of
?,!and.unwrap()on a temporary, a lowered?:), unless a?could leave the statement before the consumer runs.Borrowing across calls. Every function gets an effect: it writes nothing outside its own locals, writes only through its own pointer parameters (
string *out, a value method'sself), or may write anything. Effects spread from callees to callers to a fixed point. Arguments read from places a writing callee could change are retained for the call (the rule under Passing above), and loops and matches over parameters of functions that write nothing read them in place. Arguments read from places another thread may change are retained whatever the callee does: once the program starts threads, a global, and a field reached through one. A field of ashared ref structis read only inside alockon the variable it is reached through, so no other thread can change it during the call and it follows the ordinary rule: lent as is to a callee that writes nothing, retained for one that may write it (tests/memory/lendshared.own).Strings built once.
a + b + callocates the result once instead of once per+. An interpolation ("w\(id)") formats into a stack buffer and allocates only the finished string (a long one moves to the heap as it grows).xs.join(sep)on astring[]measures the pieces and copies them once. Integers are formatted withoutprintf.Split loops.
for w in s.split(sep)walks the pieces without building the list. Each piece is a normal string; when the loop body kept no reference to the last one (stored it, captured it, pushed it, used it as a new map key), the next piece is written into its buffer, so counting words allocates once per distinct word rather than once per word. The source string and separator are held for the loop, so changing the variable inside it doesn't change the pieces.Map updates.
m[k] = m.get_or(k, d) + x, on a map of plain values (numbers,bool,char) with a variable or field as the key, hashes and probes once: the entry is found, or added withd, and updated through its address. Only when the rest of the right side is arithmetic on literals and variables other thanm; a call or a second read ofmkeeps the separate lookup and store.Reuse in place.
x = T{...}on aref structthatxholds alone (no other strong or weak reference) drops the old fields and builds the new object in the same memory;xs = [...]refills the buffer of a listxsholds alone when it is big enough. The new fields are computed first, so they may read the old object. Both check uniqueness when they run and allocate as usual otherwise. An object or list marked shared is never unique, even with one reference left, so it is not reused. A type with its owndrop()is not reused.
To see what was decided for a file:
moxy emit --explain-ownership main.mxy > /dev/null
main.mxy:12:16: moves 'node' (last use; its release is dropped)
main.mxy:22:20: moves 'prev' (last use; the variable is cleared)
main.mxy:30:14: borrows 'xs' for the loop (never changed in this function)
main.mxy:41:17: retains an argument for the call (the callee may change where it was read from)
main.mxy:48:9: reuses the Cell 'c' holds when it is unique
A test x.mxy with an x.own file checks these decisions: each line must appear in the report, and a line starting with ! must not.
Checking it
The test suite includes memory tests (tests/memory/), and CI runs every test under AddressSanitizer, UndefinedBehaviorSanitizer and LeakSanitizer for both the compiler and the generated programs. Run the same locally with:
moxy test --sanitize # programs under ASan/UBSan (LeakSanitizer on Linux)
make sanitize && ./build/asan/moxy test --sanitize tests
On macOS, leaks --atExit -- ./program gives the same answer as LeakSanitizer.
Future work
- Fewer retain/release pairs. Parameters passed owned (+1) where the callee changes them, so a caller's last use can hand over a unique value; reuse across loop rounds (
T t = T{...}in a loop body), not only in one assignment. - Data that lives in an arena across blocks. An
Arenadecides when memory goes, but nothing in one block reaches the next, since what leaves a block is copied out. Keeping a parse tree in an arena between calls would need variables whose values live in a named arena, checked against itsreset(); that isn't designed.