Language additions: design
Status: decided 2026-11-30, for ROADMAP.md Phase 1 and Phase 5. Every feature here keeps three rules:
- Valid C keeps meaning what it means in C. New syntax appears only where C would be a syntax error, or behind a name the compiler already knows is Moxy's.
- Each feature compiles to plain, readable C with no runtime type information.
- Compile time stays linear in program size. Generic instantiation is cached.
Generics
struct Pair<A, B> { A first; B second; }
enum Option<T> { Some(T value), None }
ref struct Tree<T> { T value; Tree<T>? left; Tree<T>? right; }
T first<T>(T[] xs) { return xs[0]; }
T max<T: Ord>(T a, T b) { return a.cmp(b) > 0 ? a : b; }
Pair<int, string> p = Pair<int, string>{ .first = 1, .second = "a" };
auto q = Pair{ .first = 1, .second = "a" }; // inferred from fields
int x = first([1, 2, 3]); // inferred from arguments
long y = first<long>(xs); // explicit
- Type parameters follow the declared name:
struct Name<T>,enum Name<T>,R name<T>(...). <after a name is a type-argument list only when that name is a known generic type or function. Otherwise it's C's less-than. This is the same rule Moxy already uses forResult<T>.- Bounds:
<T: Ord>,<T: Hash + Eq>. A bound names an interface (below). Without a bound, a type parameter supports only what every type supports: copying, assignment, passing, and storing in collections. - Monomorphization: one C definition per distinct instantiation, named
Pair__int__string,first__long. Pointer and qualifier spellings mangle top/c(char *→pchar). Instantiations are deduplicated program-wide. - Generic bodies are type-checked once against their bounds, at definition time, and again per instantiation only for code generation. An error inside a generic body is reported at the body, not at every use.
T[],map[K, V],Result<T, E>andFuture<T>keep their syntax but are implemented on this machinery. Element copy, drop, equality, hashing and formatting become direct calls through the instantiation.
Methods and interfaces
struct Point { double x; double y; }
impl Point {
double len() { return sqrt(self.x * self.x + self.y * self.y); }
void scale(double k) { self.x *= k; self.y *= k; }
static Point origin() { return Point{}; }
}
interface Shape {
double area();
string name(); // required
}
interface Named {
string name();
string greet() { return "hello, \(self.name())"; } // default body
}
impl Shape for Point {
double area() { return 0; }
string name() { return "point"; }
}
double total<T: Shape>(T[] xs) { double t = 0; for x in xs { t += x.area(); } return t; }
dyn Shape s = p; // explicit vtable, boxed
print(s.area());
impl Type { ... }adds methods;impl Interface for Type { ... }implements an interface. Both work for structs, enums,ref structs, generic types (impl<T> Pair<T, T> { ... }), and C types (impl FILE { ... }is allowed; methods on C types are plain functions).- Inside a method,
selfis the receiver. For a value type it is a pointer (Point *self), written with.(Moxy already allows.through pointers to its own types). For aref structit is the reference.staticmethods have noselfand are calledPoint::origin(). p.len()compiles toPoint_len(&p). Built-in methods on strings, lists and maps take priority only where no user method of that name exists on that type.- Interfaces are compile-time by default: a bounded generic calls the concrete function directly.
dyn Ifaceis the only dynamic dispatch: a fat value of (pointer to boxed copy, pointer to static vtable), reference counted like a closure. - Standard interfaces the compiler knows:
Eq(bool eq(T other)),Ord(int cmp(T other)),Hash(uint64_t hash()),Format(void format(Buf *b), used byprintand interpolation),Into<U>(U into(), used by?),Drop(void drop(),ref structonly, runs before fields are released). Built-in types implement the first four; user types get structuralEq,HashandFormatautomatically when every field has them, and can override.
Optionals
ref struct Node { string name; Node? parent; Node[] children; }
Node? find(Node root, string name) { ... }
Node? n = find(root, "x");
if (n != null) { print(n.name); } // n is Node inside this branch
string label = n?.name ?? "none";
match n { Some(v) => print(v.name), None => print("missing") }
Node m = n!; // panics with a location if null
T?is allowed for any Moxy type. Forref structand closures it's a nullable pointer with no extra storage; for value types it'sOption<T>(a tag and the value).- A
T?value can't be used as aTuntil the compiler has proved it isn't null: insideif (x != null), afterif (x == null) return ...;, inside aSomearm, through?.,??, or!. Narrowing is flow-sensitive and ends at any assignment to the variable. - Reading a
weakfield yieldsT?. ref structreferences are non-optional: aNodeis never null. Fields ofref structtype that aren't optional must be initialized in the struct literal. For one release (0.4) a non-optionalref structthat may be null is a warning with a fix-it to add?; from 0.5 it's an error.- C pointers stay C.
T *is unchecked, as in C, so existing C code keeps compiling. The SIGSEGV handler (Phase 0) reports where a null C pointer was dereferenced. An optional--strict-pointerslint flags unchecked dereferences of pointers returned from C functions.
Errors
enum ParseError { Empty, BadDigit(char c, int at) }
Result<int, ParseError> parse(string s) { ... return Err(ParseError::Empty); }
Result<Config> load(string path) { // Result<T> == Result<T, string>
string text = read_file(path)?; // returns early on Err
int port = parse(text)?; // ParseError → string through Format
return Ok(Config{ .port = port });
}
Result<T, E>;Result<T>is shorthand forResult<T, string>.- Postfix
?on aResultinside a function returningResult<U, F>: onErr(e)it returnsErr(conv(e)), otherwise yields theOkvalue.convis the identity whenE == F;E.into()whenE: Into<F>; and formatting whenFisstringandE: Format. Anything else is a compile error naming the missing conversion. - Postfix
?on aT?inside a function returningU?returnsnullearly. ?runsdefers and releases likereturn.
Slices
int[] xs = [1, 2, 3, 4, 5];
int[..] mid = xs[1..4]; // a view: [2, 3, 4]
int[..] all = xs[..];
int buf[64];
int[..] b = buf[0..n]; // views of C arrays too
for x in mid { ... }
mid[0] = 9; // writes through to xs (xs is made unique first)
string s = "hello"[1..3]; // "el": strings are immutable, so a string slice is a string
T[..]is a non-owning view: a pointer, a length, and a retained reference to the owner when the owner is a Moxy list (so the storage can't be freed under it). Views of C arrays hold no reference and follow C lifetime rules.- Range forms
a..b,a..=b,a..,..b,... Out-of-range bounds panic with a location. - Lists, slices and C arrays all accept
T[..]parameters, so one function serves all three.
Integers
i8 i16 i32 i64 u8 u16 u32 u64 isize usize f32 f64are predefined aliases for<stdint.h>/<stddef.h>types. They're contextual names: a C variable namedu8still works.- Signed overflow is undefined in C, so Moxy may check it: debug builds panic with a location on signed
+ - *overflow and on division by zero; release builds keep C behavior. Unsigned arithmetic wraps, as in C, always. wrapping_add,checked_add(returnsT?) andsaturating_add(andsub,mul) on every integer type.
Compile-time reflection
string to_json<T>(T v) {
string out = "{";
static for f in T.fields {
static if (f.index > 0) { out += ","; }
out += "\"\(f.name)\":\(json(v.[f]))";
}
return out + "}";
}
static if (T: Hash) { ... } // does T implement an interface
static for c in Shape.variants { print(c.name, c.fields.len); }
static forandstatic ifare not valid C, so they can't change the meaning of existing code (the same spelling D uses).static for x in T.fieldsunrolls the body once per field at compile time, per instantiation, like generics.f.nameis a string literal,f.typecan be used anywhere a type can (f.type tmp = v.[f];),f.indexis an integer constant.v.[f]reads or writes the fieldfnames. It is an lvalue.T.fieldsworks on structs andref structs,T.variantson Moxy enums (each with.nameand.fields),T.namegives the type's display name.static if (cond)takes a compile-time condition: integer constants,f.type == int,T: Iface,&&,||,!. The branch not taken is parsed but not type-checked, so it may use operations the type doesn't support.- Nothing exists at run time: no type objects, no tables.
Gates (Phase 2, M3)
string[] titles(string path) {
gate {
Doc d = parse(read_file(path).unwrap()); // every value made here comes from the gate's arena
return d.headings.map((Heading h) => h.title); // copied out to the caller's region
} // the arena goes here, in one step
}
gateis contextual: it is a keyword only directly before{at statement position. A variable, field or function namedgatekeeps working, andgate(x);is still a call.- Every managed value made while the block runs, in this function or any it calls, comes from a bump arena owned by the block: strings, lists, maps,
ref structobjects, closures anddynboxes. Ashared ref struct, a channel and a future handle are always made on the heap. - The arena is freed at the closing brace and on every way out of the block:
return,break,continue,?. A panic ends the process.goto, labels and a case label of a switch outside the gate are errors inside one. - A value that leaves is copied out where it leaves (returned, stored into a variable declared outside the gate, a global, an object, list or map from outside, sent on a channel, passed to a future), with everything it holds that the gate owns. Nested gates each have an arena, and a value stored into a variable of an enclosing gate is copied into that gate.
- A
ref structhas identity and can't be copied: one made inside a gate that a return or a store would carry out is a compile error, and the run-time check panics with both locations when a callee does it.weakandunownedreferences follow the same rule. moxy emit --explain-gatesprints each decision;moxy lintlists copy-outs with their size class.T f(...) in gate(decided 2026-12-01) marks a function that allocates into its caller's gate. Every function called inside a gate already does that, since the allocation target follows the thread, and returns without a copy;in gatemakes it a checked contract. Its body is checked as if it were inside the caller's gate, with its parameters counted as the caller's: aref structit makes can't be stored into a global (stores into globals are copy-outs, listed bymoxy lint), and areturnfrom inside one of its own gates, which would copy the result out, is an error. Called outside any gate it is an ordinary heap function.asyncandFuturefunctions can't bein gate: their bodies never run in a caller's gate.- Arenas as values (decided 2026-12-01):
Arena a = Arena::new();(std/arena.mxy), thengate (a) { ... }allocates from it with the same copy-outs asgate { ... }. The closing brace keeps the memory;a.reset()gives back everything its blocks made anda.free()(or the last reference going) gives back the memory for good. Under the escape rules nothing made in one block is reachable from the next, so an arena lets C-style code pick when memory goes and hold one across calls (a frame arena reset once a frame); it does not keep data across blocks. Only one block of an arena may be open at a time;reset()orfree()inside one, and any use afterfree(), panic. AnArenais ashared ref structon the heap.
Concurrency (Phase 5)
async string fetch(Client c, string path) { // waiting: runs on the calling thread
TcpStream s = TcpStream::connect(c.addr).unwrap(); // parks; other async calls run meanwhile
...
}
Future<string> a = fetch(client, "/a"); // runs until its first wait, then returns
string page = await a;
Future<long> crunch(long[] xs) { ... } // parallel CPU work: a task on the pool
string[] pages = await all([fetch(client, "/a"), fetch(client, "/b")]);
string? quick = await fetch(client, "/slow").timeout(100);
chan<int> c = chan<int>(16); // buffered; chan<int>() is unbuffered
Future<void> producer() { for i in 0..10 { c.send(i); } c.close(); }
for v in c { print(v); }
select {
v = a.recv() => print("a", v),
b.send(1) => print("sent"),
timeout(100) => print("idle"),
}
shared ref struct Counter { // may cross threads
long n; // written under lock (c) { ... }
string[] log; // written and read under lock (c) { ... }
atomic long hits; // read and written without a lock
}
asyncis for waiting,Future<T>functions for parallel CPU work. Both calls return aFuture<T>;awaitgives theT.- An
asynccall runs on the calling thread, at once, until it first waits; then the call returns. Its thread switches between its async calls only where they wait, so they never run in parallel with each other or their caller: anything, plainref structs and slices included, may be passed in, captured or returned, withoutsharedorlock. ItsFuturestays on that thread (a compile error where the type shows it, a runtime panic elsewhere). Code that isn't an async call and awaits (main) runs the thread's async calls until it gets its value. A pool task's async calls stay on its worker. A host run loop drives them throughmxy_async_runandmxy_async_fd. Without fibers an async call runs to its end inside the call. all(fs),race(fs)andf.timeout(ms)combine Futures of either kind; race's losers and a timed-out Future are cancelled.await f()?is(await f())?.Future<T>calls run on a work-stealing pool sized to the CPU count (MOXY_THREADSto override), not one thread each.- Values crossing into a future or a channel are marked thread-shared (memory design, layer 2).
- A plain
ref structcan't be sent to another thread; ashared ref structcan. Its fields are written only insidelock (obj) { ... }, whereobjis the variable the field is reached through; so is a value method called on a struct field, which receives it by address. A field holding a counted value (string, list, map, closure, object, or a value holding one, or a type parameter) is also read only inside that lock, since another thread may replace it and free the old value. Plain scalar fields may be read without the lock, as a data race in C's sense. Each is a compile error with a fix-it. atomicfields (integers,bool, C pointers) of ashared ref structare read and written without a lock, each access one sequentially consistent__atomicbuiltin;+= -= &= |= ^= ++ --are single read-modify-writes and the other compound assignments are errors.- Not checked: raw pointers into a shared object used after its lock, a global named by
lockthat another thread reassigns, plain scalar fields read racily, deadlocks. The exact rule is in Sharing between threads. - Dropping a
Futurecancels it:await, channel operations andcancelled()checks in the callee return early. This holds for async calls too, so an async call made as a statement stops at its first wait (a warning), unlike JavaScript's fire-and-forget; whenmainreturns the program ends. std/netoperations andsleep_mscalled inside a future or an async call park it on the shared poller (kqueue, epoll, WSAPoll) and timer threads instead of blocking the thread.
Simpler concurrency (decided 2026-12-01)
After comparing JS/TypeScript and Swift async, Elixir's processes and GenServer, and Grand Central Dispatch: waiting is async, state owned by one thread of control is an actor, and parallelism is explicit.
async User load(Session s, int id) { // s is a plain ref struct: fine
string body = await http_get("/users/\(id)")?;
s.hits += 1; // no lock: same thread, no await in between
return parse_user(body);
}
actor Cache {
map[string, User] users;
void put(string k, User u) { self.users[k] = u; } // c.put(...) returns at once
User? get(string k) { return self.users.get_or(k, null); } // await c.get(k)
}
parallel for i in 0..n { out[i] = work(i); }
int[] squares = xs.par_map((int x) => x * x);
Future<int> f = spawn { return heavy(); };
asyncfunctions run on the calling thread: synchronously until the first wait, then as a fiber resumed by that thread's loop. They never run alongside other code on their thread, so they take any value and need no locks. Their futures are bound to that thread.Future<T>functions,spawnandparallel forrun on the work-stealing pool, with the crossing rules.- An
actoris a reference type with a mailbox. Calls from outside are messages handled one at a time in arrival order (per sender) on the pool; inside its methods,self's fields are accessed directly. Avoidmethod is a cast (fire and forget, ordered); any other method returnsFuture<T>(a call). Arguments and results cross threads, so they follow the crossing rules; an actor reference itself may cross. Calls from an actor to itself are direct. - A panic inside an actor message is caught at the message boundary: the caller's future fails (awaiting it yields the panic as an error, or re-panics in the awaiter if its type can't carry one) and the actor serves the next message. Memory allocated by the failed message may leak and C resources may stay open; the actor's own fields are left as the message left them. Restarting from a fresh state is a std library concern (supervisors), after 1.0.
await f()?is(await f())?.all,raceand.timeout(ms)work on both kinds of future.
Actors and parallel helpers as built (2026-12-01)
- Syntax.
actor Name { fields; methods }at file scope (or in a namespace);actoris contextual (before an identifier and{). Methods useself.fieldlike any method;impl Name { ... }may add more. Construction is a ref struct literal; noinit.parallel for i in a..b { }(ranges only),xs.par_map(f),spawn { ... }(an expression;parallelandspawnare contextual too). - Messages. A call from anywhere but the actor's own methods is a message;
self.m()inside one of its methods is a direct call. Inside a lambda in a method,self.m()is a message andself.fis an error, since the lambda may run elsewhere later. Arguments, results and literal field values follow the crossing rules; checks are at the call site, so a method only ever called onselfmay take plain ref structs. - Reentrancy: none. A message that awaits keeps its actor busy until it returns (Swift's actors interleave at awaits; Moxy doesn't). This keeps "one message at a time" literally true, at the price of deadlock when actors await each other in a cycle. Such a cycle is detected when the closing await starts (each actor notes which actor its running message awaits, under one global lock taken only by actor-to-actor awaits) and panics with every await's place; awaiting a call to oneself panics at once. Cycles through tasks or channels aren't detected.
- Messages are never cancelled. Dropping a call's Future gives up the result only; the method may change state, so skipping it silently would be worse. Unused call results aren't warned about.
- Crash API. A panic inside a message (panic, assert, bounds,
!on null, runtime crossing checks) is caught at the message boundary with setjmp/longjmp.awaitre-raises it in the awaiter with both places;f.result()givesFuture<Result<T>>with the panic text asErr, never raising. One API, usable with?. A cast's failure is printed once; so is a call's that nobody awaits. The design text above said "awaiting it yields the panic as an error … if its type can carry one"; that was dropped: makingResult-returning methods special would change what a type means depending on where a panic happens. - What a caught panic costs. Frames between the panic and the boundary are abandoned: no defers, no releases. Leaks are accepted and documented; the debug leak report notes caught panics. Gates opened inside are closed and the drop/share worklists reset before the jump (on the panicking stack, while the gate records still exist). A panic while holding a lock stays fatal (releasing would expose half-written shared state; Rust poisons instead). A panic in a pool task or an async call stays fatal even if an actor started it, as do memory faults.
- Lifetime. The scheduled mailbox holds the actor strongly while messages are pending; a message's Future holds it weakly, so a leaked or kept handle doesn't pin the fields.
- Scheduling. Senders push onto a lock-free stack (one CAS) and count
pending; the 0-to-1 sender schedules the mailbox as a tagged entry in the pool's deques. The runner reverses the stack into arrival order and handles up to 64 messages before yielding to the shared queue. - Parallel-for writes. Only
out[i] = vwithouta list declared before the loop andithe loop variable; no other use ofoutin the body. The list is made unique before the loop and its closure borrows it, so writes land in place. Everything else from outside is read-only. Results that aren't per index go throughpar_mapor are combined after the loop. - Parallel cost. About 32 chunks per worker (fine enough that a panic or cancel waits for little), claimed with an atomic counter. The first chunk runs inline and is timed; under about 50 µs of estimated remaining work no worker is woken. Each chunk runs inside a panic boundary; the first panic stops the loop and is raised in the caller after the running chunks end.
- spawn is a pool task whose body is a closure, run inside a boundary (unlike a
Futurefunction's task, whose panic stays fatal). Dropping its Future cancels it, as with any task.
Pattern matching additions (decided 2026-12-01)
- Guards:
pattern if cond =>; the guard sees the pattern's bindings. - Alternatives:
p1 | p2 =>; every alternative binds the same names with the same types. - Nested patterns: payloads may hold patterns (
Some(Ok(v)),Shape::Rect(0, h)), and struct patternsPoint{ .x = 0, .y = y }match fields by name, unlisted fields ignored. - Exhaustiveness accounts for guards conservatively (a guarded arm never counts as covering its pattern).
Tests in source (decided 2026-12-01)
test "name" { ... }at file scope declares a test.moxy testruns a file's test blocks (each in isolation, reporting the name on failure);moxy build/runleave them out entirely.testis contextual: only at file scope before a string literal.- Doc-comment examples in fenced
```moxyblocks are shown bymoxy docand compiled and run bymoxy test; an example that should not run is fenced```moxy norun.