MoxyMoxy
Docs contents

Architecture

moxy is one executable: the compiler, the test runner, the formatter, the linter, and the project and package manager. Project management comes from goose, which is linked in as a library (libgoose.a). Moxy registers callbacks with goose's framework API for building, running, testing and installing, and goose handles moxy.yaml, dependency fetching, lock files, workspaces and the shared commands.

            ┌─────────────── moxy ───────────────┐
 .mxy ───►  load ─► lex ─► parse ─► sema ─► gen  ├──► .c ──► cc ──► binary
            │                                    │
            │  cli: run · build · test · fmt ·   │
            │       lint · check · emit          │
            │  goose: new · init · add · remove ·│
            │         update · workspaces · lock │
            └────────────────────────────────────┘

Pipeline

1. Load (src/load)

load_program reads the entry file and lexes it. For every #include "x.mxy", it resolves the path in this order:

  1. relative to the including file (never the including file itself);
  2. registered include directories (project src/, configured includes, dependency directories);
  3. the standard library embedded in the binary.

The included file's tokens are spliced in place. A set of canonical paths makes each file load once, so diamond includes and include cycles are harmless. Every token remembers its file, so diagnostics always name the right file and line.

2. Lex (src/lex)

The lexer produces tokens with source locations. Notes:

  • Preprocessor lines become single T_DIRECTIVE tokens.
  • String literals keep their escapes verbatim and allow \( ... ) interpolation with nested strings.
  • Only C keywords plus string, bool, true, false and null are reserved. Moxy's other words (match, in, map, defer, ...) are recognized by the parser in context, so C code that uses them as names keeps working.

3. Parse (src/parse)

The parser is a recursive-descent parser for C11 declarations and statements plus Moxy syntax, producing one AST (src/ast/index.mxy). Nothing is passed through as raw text: everything is parsed, so typos are reported at the right place.

File Contents
state.mxy token cursor, and the type-name table: a prescan registers every struct, union and enum tag, typedef and @type name, so declarations parse before their types are defined
types.mxy declaration specifiers, C declarators (pointers, arrays, nested function pointers), Moxy types, struct and enum bodies
expr.mxy precedence climbing, casts and compound literals, lambdas, interpolation (sub-lexed), pipes desugared to calls
stmt.mxy statements, for-in, match arms, defer, lock and gate blocks, labels
pattern.mxy match patterns (N_PAT): literals parsed above | so 1 | 2 is two alternatives, constructor and struct patterns, guards; a ( ... ) just before the arm's => is not a lambda
top.mxy declarations, namespaces, using, and conditional directives
alias.mxy the contextual integer names (i8 ... u64, isize, usize, f32, f64): a prescan drops a name the program declares as a value; elsewhere it is a type where a type can follow
span.mxy the source text between two tokens; an assert call keeps its condition's text for the failure message
generic.mxy a prescan for generic names (struct Name<, name<T>(), type-parameter and type-argument lists (bounds included), and the rule that < after any other name is less-than
impl.mxy impl and interface blocks, a prescan for interface names so dyn Name parses anywhere, dyn types, and the implicit self parameter
slice.mxy a[i..j] and the other range forms inside index brackets (T[..] types are a suffix in types.mxy)
decor.mxy library declaration macros around a function's name (CJSON_PUBLIC(cJSON *) f(, void * CJSON_CDECL f(), kept on the N_FUNC (name2, text) for code generation; a prescan for type names only those spellings and const Name * show

Each top-level declaration records the preprocessor condition it sits under, for example defined(DEBUG) && !(X), so code generation can reproduce #if blocks around everything it emits, even after reordering.

4. Semantic analysis (src/sema)

Sema resolves every name and computes a type for every expression.

File Contents
scope.mxy scope stack and namespace scopes; captures are recorded on lambdas when a name resolves to an enclosing function's local
resolve.mxy type syntax to Type; struct, union and enum registration; typedefs
decl.mxy three passes: declare everything, resolve signatures and fields, then check initializers and bodies
expr.mxy, init.mxy, call.mxy, method.mxy expressions, initializer lists, calls and enum constructors, builtin methods on string, lists, maps and Result
conv.mxy assignability; inserts N_CONV nodes for implicit conversions (C string to string, function to closure, capture-free lambda to C function pointer)
stmt.mxy, match.mxy, lambda.mxy statements, match arms and guards, lambda return inference, lint checks
pattern.mxy, cover.mxy patterns: a bare name becomes a constructor, a binding or a constant; alternatives must bind the same names. Coverage uses the usefulness algorithm over constructor sets (enum variants, Ok/Err, Some/None, true/false, one per struct): an arm useless after the unguarded arms above it is unreachable, and a match is exhaustive when _ would be useless. The missing cases are spelled out from a witness
ints.mxy wrapping_, saturating_ and checked_ methods on integers (checked_ gives a T?)
opt.mxy optionals: conversions to and from T?, !, ??, ?., comparisons with null, and the 0.4 warning for a non-optional ref struct that may be null
narrow.mxy flow-sensitive narrowing: a stack of facts about which optional locals are non-null, pushed by checks, early exits and non-null stores, killed by assignments; code that may run again first forgets what it assigns. A narrowed read becomes an N_UNWRAP that code generation reads as the value
try.mxy postfix ? on a Result (with the error conversion: identity, Into, or Format to string) and on an optional
generic.mxy, infer.mxy generics: declarations, the instance cache, type-argument inference and target matching (see below)
macro.mxy each(x, xs) { ... }, a C loop macro (an N_FOR with op FOR_MACRO, the call in b): checked as a loop, or turned back into a call and a block when the name is a Moxy function
cycle.mxy the strong reference cycle warning: a graph of ref struct types and their strong fields, split into strongly connected components (see memory.md)
iface.mxy interfaces: the standard ones (Eq, Ord, Hash, Format, Into, Drop, and Num, which has no methods and allows arithmetic on a type parameter) built as if written in Moxy, user interfaces, lookup through namespaces, method signatures with Self bound, dyn types
bound.mxy which types implement which interfaces (impls, built-in types, structural Eq/Hash/Format), bounds of type parameters, and bound checks at each instantiation
impl.mxy impl blocks: methods become functions named after their type, impls indexed by target (exact type or generic), clashes between impls, the standard methods each user type gets
conform.mxy an impl of an interface has every required method, nothing extra, and the declared signatures
dispatch.mxy method calls: user methods, bounded type parameters, standard methods on built-in types, Type::name paths, == and < through eq() and cmp()
dyn.mxy conversions to dyn, calls through the vtable, and the methods each vtable needs
gate.mxy gates: each local's gate depth (Sym.gate), the ref struct escape errors (checked when the function's writes are all known), no goto, labels or outer case labels inside a gate, and moxy lint's copy-out notes
race.mxy the data-race rule: which types may cross threads (no plain ref struct, no slice), checked on Future parameters and results, chan<T>(n), lambdas passed to futures and the fields of a shared ref struct; field writes of a shared ref struct, and reads of its counted fields, only inside lock on that variable (reads wait for the end of their statement, so a write reports once); an async call's Future (a TY_FUTURE with local set) passed to, returned from or captured for a Future function, sent, or stored in a shared ref struct; atomic.mxy checks atomic fields
combine.mxy all(fs) and race(fs) when no function of that name exists and the argument is a list or slice of futures, and f.timeout(ms)
slice.mxy slicing, lists and C arrays converted to T[..], slice methods; how each view of a list is taken (SL_PLACE makes the list unique where it is, SL_VALUE owns a temporary, SL_READ for views only read), decided when the statement is checked

Generics are monomorphized in sema. A generic declaration itself is never checked; ast/copy.mxy copies it. One copy is checked against the type parameters as opaque TY_PARAM types, so errors in a generic body are reported once, at the body. Each distinct argument list gets another copy, resolved under a scope that binds the parameter names to the arguments, and named Pair__int__string or first__long; from then on it is an ordinary struct, enum or (static) function in prog, so code generation knows nothing about generics. Each generic keeps a cache of its instances keyed by the arguments, so every instantiation in the program happens once.

Methods are ordinary functions too. An impl block's methods are declared after every type is known, each named after its target (Point_len), with the receiver as the first parameter. A method of a generic impl is a generic function whose parameters are the impl's; looking a method up on Pair<int, int> matches the impl's target against the instance and instantiates the method for the bound arguments. Bounds are checked whenever a generic is instantiated, once the impls are known. Interfaces are compile-time: a bounded generic's instance calls the concrete method directly, and only a conversion to dyn records a vtable.

Identifiers that Moxy can't resolve are treated as C (TY_UNKNOWN): they pass through, and the C compiler checks them. Values of unknown type can't become lists, maps or other managed values.

5. Code generation (src/gen)

Code generation writes one C file in sections, assembled in a fixed order:

feature macros, user #include/#define (with their #if conditions)
runtime (embedded from runtime/*.h)
string literals (immortal static objects)
type forward declarations, then definitions in dependency order
value witnesses and copy/release helpers
list, map and slice operations specialized per element type
prototypes and globals
glue: closure thunks, lambda environments, async launchers, main wrapper
program: functions with #line directives

Functions are generated first and type definitions last, so every type a function needs (such as Result<Point>) is known when the types section is written.

Expressions (expr.mxy, call.mxy, lvalue.mxy) return the C text plus whether the value is owned (+1) or borrowed (+0). Each statement has a context holding a prelude (statements that must run first) and temporaries to release afterwards. &&, || and ?: with preludes on one side are lowered to if statements to keep short-circuit evaluation. assert (assert.mxy) stores both sides of a comparison in temporaries, tests them, and formats them and the message only inside the failure branch.

Statements (stmt.mxy, loop.mxy, match.mxy) keep a stack of cleanup scopes (managed locals and defer statements):

  • leaving a block releases its scope;
  • return releases all scopes, moving out a returned local;
  • break and continue release only the scopes they leave.

A match becomes an if/else if chain over a copy of the value. A pattern turns into a condition on it (tags, flags and comparisons joined with &&, alternatives with ||) and its bindings into declarations of the parts it names; a binding from alternatives reads t1 ? v1 : v2. A guard joins the condition, with each binding's name temporarily standing for that part of the value (as ?. does); a guard that needs a prelude runs into a bool flag inside an if on the pattern's condition, and the chain continues under an else. The last unguarded arm is a plain else, since sema proved the match exhaustive.

Ownership inference (src/own, move.mxy, reuse.mxy; see memory.md):

  • own/effect.mxy runs once per program, before any function is generated: one walk per function records what it writes outside its own locals (nothing, only through its pointer parameters, or anything) and whom it calls, and the levels spread backwards along calls to a fixed point (Sym.heapwrite). A call to a writing callee retains arguments read from places it could change (lend in call.mxy).
  • own/infer.mxy runs per function (gen_function, gen_lambda): it collects the owned candidates (locals, parameters, loop and arm bindings; not ones whose address is taken or that a defer reads; nothing in a function with goto), and own/live.mxy runs a backward liveness pass over the statements for each one, marking reads after which the value is dead (F_MOVE) and, of those, the ones that run whenever the variable's scope is entered with nothing after them mentioning it (F_MOVEFREE). own/occur.mxy counts reads and checks positions.
  • move.mxy carries the marks into code: reading an F_MOVE identifier offers its variable; consume, a push or a map or list set claims the offer by its C text and either drops the variable's release (Cleanup.moved) or reads it through mxy_take. A read that's only borrowed is never claimed. own_take also treats string literals as owned and hands a statement's temporaries to their consumer (own_steal) when no ? can leave first. own_borrowable lets for-in and match read a variable in place.
  • take.mxy spots a field read whose next statement overwrites the field, and the read takes the field instead.
  • reuse.mxy turns x = T{...} and xs = [...] on a local into mxy_obj_reuse and mxy_list_refill.
  • own_note records each decision when GenOptions.explain is set; moxy emit --explain-ownership prints them, and test files with an .own file check them.

Integer arithmetic (arith.mxy): signed + - *, all integer / %, compound assignments and ++/-- become MXY_ADD(a, b, loc)-style macros from runtime/arith.h, which check in debug builds (MXY_DEBUG: on unless the C is optimized or NDEBUG is set, and forced on with -DMXY_DEBUG=1) and are the plain operators otherwise. Constant expressions (static initializers, case, sizeof, _Static_assert) and bounded for steps stay plain.

Optionals (opt.mxy): a T? for a ref struct, closure or pointer is the pointer itself; any other T? is a struct mxy_opt_T { bool some; T val; }. ??, ?., ? and ! on a tagged optional are lowered into the statement's prelude (a temporary, a test, then the value); ? releases the statement's temporaries and every scope, running defers, as return does. x! on a pointer optional is mxy_unwrap(x, loc, name), which panics on NULL.

Types and helpers (types.mxy, helpers.mxy): user structs, tagged enums, optionals and Result<T, E> structs are emitted in dependency order. Every type that is stored in a collection or printed gets a value witness, a table of copy, drop, equality, hash, compare and format functions, which the runtime's type-erased list and map code (sorting, printing, insert and remove, copying a shared map) and C callers use. A generated struct's, enum's, Result's or optional's own eq and hash call their fields' functions directly.

Specialized collections (elem.mxy, listops.mxy, mapops.mxy): the hot list, slice and map operations are written per element type, on first use: mxy_list_at__Point, mxy_list_at_mut__Point, mxy_list_push__str, mxy_list_pop__T, mxy_list_set__T, mxy_list_index_of__T, mxy_list_unique__T and mxy_list_clone__T (copy-on-write), mxy_list_release__T, mxy_slice_at__T, and mxy_map_find__K, mxy_map_has__K, mxy_map_get__K__V, mxy_map_lookup__K__V, mxy_map_get_mut__K__V, mxy_map_set__K__V, mxy_map_release__K__V. They work on the runtime's mxy_list, mxy_slice and mxy_map (which still carry their witnesses, for the debugger formatters and the type-erased paths), index with sizeof(T), copy and drop elements with retain_of/release_expr (nothing at all for plain values), and compare and hash with the function the witness holds (elem_eq, elem_hash), so a key hashed by mxy_map_set__str__int is found by the runtime's mxy_map_remove. Values are passed to them owned; a borrowed value is retained first. Prototypes go with the helpers' (a struct's release helper can call mxy_list_release__T) and bodies in their own section after them. release_expr uses the specialized release for lists and maps whose elements need dropping.

Methods (method.mxy, dyn.mxy): a method call is a plain call with the receiver first (Point_len(&p); a receiver that isn't a variable is stored in a temporary first). A user type's eq, hash, cmp, format and drop methods go into its value witness and release helper, so lists, maps, printing and releases use them. Each dyn interface gets a vtable struct (mxy_vt_Shape), and each interface and type a static vtable of thunks that take the boxed value as void *.

Slices (slice.mxy): a[i..j] becomes mxy_slice_list(&xs, ...), mxy_slice_array, mxy_slice_sub or mxy_str_range with the range mode (MXY_RANGE, MXY_RANGE_INCL, MXY_RANGE_OPEN); s[i] is *(T *)mxy_slice_at(s, i, loc), read or written.

Sharing (own.mxy share_expr, helpers.mxy, types.mxy): programs that start threads get a share helper per managed type (__mxy_sh_T, the witness's share entry, __mxy_sharef_T in a ref type's descriptor, a closure's share), which marks what a value holds as shared (memory design, layer 2). Future launchers mark their arguments, the pool marks results, channels mark sent values. A statement that writes a managed global is followed by mxy_global_written. A shared ref struct has a hidden __lock field after the header; a lock block takes it and its cleanup scope gives it back on every exit. While the block is generated, its variable is in own_locks, so a field read through it is lent to a call like any other place rather than retained as one another thread may change. An atomic field is a plain C member that every access reaches through an __atomic builtin (atomic.mxy).

Gates (gate.mxy; the runtime side is arena.h and gate.h): a gate block opens a mxy_gate on the stack and closes it as a cleanup of the block's scope, so every exit closes it. Programs with gates get MXY_GATES, and a store into a slot decides whether the value must be kept for that slot's region (keep_expr, deep copies through per-type __mxy_kp_T helpers): a local of the current gate needs nothing, a local declared outside it gets the region its gate opened in (__g1.prev), a global the heap, and anything else (a field, an element, through a pointer) the region of the slot's memory, found when it runs (mxy_gate_at) unless the object is one the function just made. List and map operations on a place outside the current region run with the allocation target switched to it, and keep what they store for the list itself (mxy_gate_for). Returns from inside a gate keep the value for the caller. Each decision goes to gate_report() (--explain-gates). --gate-stress makes every function body a gate.

Functions (func.mxy):

  • Lambdas become functions that take their closure as the first argument; captured variables live in an environment struct after the closure header.
  • Named functions used as closures get a thunk and a static, immortal closure object.
  • Future<T> functions are split into a body, an argument struct, a task entry, and a launcher that submits the task to the pool and returns the future handle. An async function is split the same way, but its launcher calls mxy_async_spawn, which starts the body on the calling thread, and marks nothing shared; an async lambda gets the same pieces around its body (__mxy_alambdaN), with the closure in the argument struct.

Channels (chan.mxy, select.mxy): send, recv and close are runtime calls; a value to send is first moved into a temporary the runtime consumes, and recv's status becomes a Result<T>. A select evaluates its channels and sent values into an array of mxy_case, calls mxy_select, and branches on the case that went.

Libraries (header.mxy): library builds also write a C header exposing plain structs and the functions whose signatures C can express.

6. Runtime (runtime/*.h)

The runtime is C, embedded into every generated program (scripts/genembed.sh turns it into src/embed/data.mxy). All functions are static, so separate translation units never collide.

File Contents
core.h reference counts (plain unless marked MXY_RC_SHARED, then atomic), panics, the release worklist (mxy_drop_deep) and the same worklist for marking values shared (mxy_share_deep), globals noted for marking at the thread's next crossing, MXY_DEBUG and the current statement for fault reports (MXY_HERE), mxy_buf, value witnesses (with a share entry), mxy_take (a move that leaves NULL)
win.h Windows only: declarations of the few Win32 functions the runtime calls, matching the SDK's so <windows.h> can still be included, without its macros
arith.h checked integer arithmetic (MXY_ADD, MXY_SET, ...), plain operators when optimized; wrapping_ and saturating_ methods
str.h strings: header {rc, len} before the bytes; literals have rc −1 (immortal)
fmt.h printing and value witnesses for builtin types; MXY_FMT_ANY uses _Generic for C values of unknown type
list.h copy-on-write lists, bounds checks, sort, slice() copies; a count of the slices viewing each list, so copying (or moving, mxy_list_moved) a viewed list copies its storage; mxy_list_refill for reuse in place. Generated code uses the per-element-type operations above for the hot paths; these type-erased versions serve the rest and C callers
slice.h T[..] views (data pointer, length, element witness, retained owner list or NULL), range checks, string ranges
map.h insertion-ordered hash maps (an entry array plus an open-addressing index); mxy_map_add and mxy_map_missing are shared with the specialized operations
arena.h gates (programs with MXY_GATES only): one reserved span of address space cut into 16 KB slots, a slot table giving the gate of any pointer, chunks per gate with a per-thread cache, the value allocators (mxy_valloc, mxy_vzalloc, mxy_vrealloc, mxy_vfree) that follow the thread's allocation target, clean gates that put drops off until something older reaches them, and in debug builds closed memory kept inaccessible for the fault report
gate.h copying values out of a gate for an older region (mxy_str_keep, mxy_list_keep, mxy_map_keep, mxy_slice_keep, mxy_fn_keep, mxy_dyn_keep), and the panic for a ref struct that would outlive its gate
leak.h the debug-build leak report: live counts per allocation site (MXY_SITE), printed by mxy_leaks when main returns
obj.h ref objects: a 16-byte header (count word, pointer to a static mxy_type descriptor); weak and unowned fields; marking an object and its fields shared, and the panic for a plain ref struct found crossing inside a closure or dyn value; mxy_obj_reuse (never an object marked shared)
fn.h closures
dyn.h dyn values: a reference-counted box holding a copy of the value, and the vtable head (drop, format, name, size) every vtable starts with
thread.h threads, locks, condition variables and per-thread parkers: pthreads, or Win32 threads, SRW locks and condition variables
fiber.h the contexts tasks run on: each worker's loop runs on a context, and a task that waits parks its context (mxy_park) while the worker switches to a spare one; woken contexts go on their worker's ready list and resume only there. The switch is assembly on x86_64 and arm64 and Win32 fibers on Windows (MXY_FIBERS); stacks are mmaped with a guard page and told to AddressSanitizer; past 16 spare contexts a thread unmaps the others' stacks (mxy_fibers_trim) and keeps the contexts bare for reuse. Timed parks share one timer thread
pool.h the task pool behind futures: workers started on first use (one per CPU, or MOXY_THREADS), Chase-Lev work-stealing deques plus a shared queue for tasks from outside the pool, ready fibers resumed before new tasks, stand-in workers while one sleeps in a blocking call (only without fibers), and cancellation (mxy_cancelled)
loop.h async calls: mxy_async_spawn starts the body on a spare context of the calling thread with the caller first in line to resume; a thread outside the pool gets a loop (its stack becomes a context, its spares run mxy_loop_main) on its first async call; inline bodies without fibers or under a lock; the host run loop API (mxy_async_run, mxy_async_fd, mxy_async_notify); settling async calls before the leak report
future.h future handles: spawning a task, await (runs an unstarted task in place, otherwise sleeps; an async call's handle only on its own thread), cancel on the last release, the share hook that stops an async call's handle crossing threads, and all, race and timeout as async calls over mxy_future_any
chan.h channels and select: a lock, a ring buffer and queues of sleeping senders and receivers per channel; every operation is a select over its cases. Channels are shared from birth; a sent value is marked shared
lock.h lock (x) { ... }: a re-entrant mutex per shared ref struct, made on first use, and re-marking the fields shared on the way out
io.h what std/net needs from the pool: mxy_io_park and mxy_io_fire (a task parks until its poller fires a flag, a timeout or a cancel), a lock and a helper thread for std code, mxy_future_done
process.h args(), assertions, file reading, std/os run() (sh, or cmd.exe /d /s /c on Windows)
fault.h SIGSEGV/SIGBUS handlers (an unhandled-exception filter on Windows), installed by main, that report faults as panics

Command line (src/cli, src/main.mxy)

main.mxy handles the commands that work on files (moxy file.mxy, run file.mxy, build file.mxy, check, test, fmt, lint, fix, emit, doc) and clean, and hands everything else to goose_main. -p member changes into a workspace member first.

File Contents
project.mxy the goose callbacks: on_build compiles the entry file (src/main.mxy, or src/lib.mxy for libraries) with include paths from configured includes and dependencies, adds extra C sources and dependency C sources, and links or archives; also on_run, on_test, on_install, the new template, and the build: keys cc, target, cflags, ldflags. --target is taken out of the arguments before goose sees them
cc.mxy the C compiler command: build.cc, $CC, zig cc -target <triple>, or the platform's cc; the matching archiver
target.mxy --target parsing, the host triple, whether a target runs here, .exe names
doc/ moxy doc: docs.mxy finds /// and /** */ blocks in the source text (the lexer drops comments), collect.mxy walks the parsed top-level declarations and attaches the block that ends on the line above each one, spell.mxy prints type syntax, md.mxy and html.mxy render
cache/ incremental builds: hash.mxy (FNV-1a), manifest.mxy (key plus per-file hashes, one text file per step), deps.mxy (parses cc -MMD rules), step.mxy (cc_cached); project.mxy and test.mxy consult them. evict.mxy bounds the caches: entries are directories ordered by modification time, touched on use, and removed by renaming them aside first, so concurrent processes never see half an entry (see Disk budget below)
clean.mxy moxy clean [--cache] [--dry-run]: the project's build directories, and with --cache the entries of cache_root() that moxy writes and stale temporary directories
compile.mxy (also) source_files lists the .mxy files of the last compile for the cache; source_dirs lists the directory of every loaded .mxy file; builds pass them as -I so C headers next to sources resolve
test.mxy finds tests, compiles each in-process, runs it, and compares against .out, .code, .stderr, .err, .warn or .own (ownership decisions) files; a program that reports leaked objects fails
compile.mxy the pipeline in one call; errors jump back with longjmp instead of exiting, so one bad file doesn't stop a test run
fix/ moxy fix: each pass parses and checks the file, rules turn proven-equivalent patterns into text edits (statements carry their token range, Node.start/stop), and passes repeat until nothing changes; diff.mxy prints the unified diff. A test x.mxy with x.fix checks the diff, then runs the fixed program against the same .out
fast.mxy debug builds on POSIX hosts: the compiler runs without a shell (spawn.mxy, over sys_spawnp), the macOS xcrun shims are resolved once (xcrun.mxy), and the runtime prefix of the generated C is compiled into a precompiled header kept under cache_root() (pch.mxy, cache/root.mxy). Release builds, --target and Windows compilers keep cc.mxy's shell command
tcc.mxy debug moxy run through tcc, compiled and run in memory, when tcc is installed; never for --target or on Windows

Process handling lives in src/sys: posix.mxy (fork/exec, posix_spawnp, system, popen, mkdtemp) and win.mxy (the C runtime's _spawnv, cmd.exe /d /s /c, _popen, _mkdir) implement the same functions, each under its own #ifdef: spawning with captured output, the shell and its quoting and null device, temporary directories (tracked in temps.mxy so they are removed at exit and on signals), the executable's path (for the build cache key) and the home directory (for the package index cache). sys_spawnp, which runs a program from PATH with extra environment variables and no shell, is POSIX only; the fast debug path that uses it is compiled out on Windows. win.mxy uses only C runtime headers, since <windows.h> defines macros (cdecl, LockFile) that collide with names in the compiler and goose. Paths inside the compiler always use /.

Disk budget

Moxy should stay small on disk: no cache grows with the number of builds, and one command removes everything it keeps. The caps and where they are enforced:

Location Contents Cap Enforced in
~/.cache/moxy/pch/<key> precompiled runtime, ~2 MB per runtime/compiler/flag set 8 most recently used (MOXY_PCH_KEEP) pch.mxy, after building a new entry
build/<mode>/cache/tests/<hash> one project test's C and binary, ~200 KB tests that still exist, then 256 MB LRU (MOXY_TEST_CACHE_MB) test.mxy, after a run
build/gen, build/<mode>/cache, build/<mode>/obj the project's generated C, step records, objects the current configuration's files project.mxy, after a build that did work
~/.cache/moxy/xcrun*, index* compiler lookup, package index clones one per compiler name, one per index URL —
$TMPDIR/moxy<pid>.XXXXXX scratch for single-file commands and tests removed at exit, on SIGINT/SIGTERM/SIGHUP (sys/temps.mxy), and swept when the pid is dead sys/, pch.mxy, clean.mxy

Rules for new caches: an entry is a directory whose modification time is its last use; eviction runs only when something new is written, never on a fully fresh build; removal renames the entry to .gone<pid>.<name> before deleting it; and entries used in the last minute are never evicted, which also keeps one large test run from thrashing a small cap. A cache that cannot follow these needs its own line in this table and in moxy clean.

Diagnostics (src/diag)

diag.mxy prints errors, warnings, notes and help: lines with the source line and a caret. A diagnostic's code is not passed at the call site: codes.mxy maps each message template (the format string given to diag_error, diag_warn or the parser's fail) to its code, so a message keeps its code wherever it is reported, and several templates can share one. A template that goes away keeps its row with a NULL template, so its code is never handed out again; a new message takes the next free number in its phase's range. scripts/diagcheck.mxy (run by tests/diag/run.sh in make test) fails when a call site's template isn't registered, a code has no entry in docs/errors.md (whose two examples it compiles, expecting the code and then none), or no test expects it. moxy explain prints the entries, which scripts/genembed.sh embeds from docs/errors.md.

ice.mxy turns a crash of the compiler into an internal compiler error. While a compile runs (diag_busy), the parser, checker and generator record each statement and expression they enter (diag_at), and a fault, an abort or a runtime panic is reported at that location as a bug in Moxy (exit 70). A stack overflow there is the user's code nesting too deeply, reported as E0003. Paths that can only be reached through a compiler bug call diag_ice.

Resource budgets

make budget (bench/budget.ts) measures what building and running Moxy programs costs and fails when a limit in bench/budget.json is exceeded. CI runs it on Linux and macOS after the tests. Limits are per platform and were set from measured values with headroom; bun bench/budget.ts --update records this machine's values as its platform's limits, which a change that legitimately costs more should do in the same commit, saying why.

Recorded 2026-12-01 (macOS: Apple M1 Max, Apple clang; Linux: arm64 Debian 13 under a VM, gcc 14, 4 CPUs):

Budget macOS now macOS limit Linux now Linux limit
self-compile, moxy emit src/main.mxy / C lexer pass 1.56x 2x — 2x
compiler peak memory, self-compile 100 MB 126 MB 110 MB 137 MB
hello world, stripped release binary 50 KB 57 KB 66 KB 83 KB
std/http server, stripped release binary 169 KB 195 KB 198 KB 248 KB
C emitted for hello world (the runtime) 249 KB 274 KB 249 KB 274 KB
hello world idle: resident, threads 1.7 MB, 1 2.6 MB, 1 1.1 MB, 1 1.7 MB, 1
std/http server idle: resident, threads beyond CPUs 2.1 MB, 2 3.1 MB, 3 1.6 MB, 1 2.4 MB, 3
per-user cache after make test 21 MB 48 MB — 48 MB

The Linux binaries have 25% headroom rather than 15%, since CI builds them on x86_64 Ubuntu. The server's threads beyond its CPUs are main, the socket poller, and the timer thread once anything waits with a timeout.

Times depend on the machine, so of them only the self-compile ratio is checked: moxy emit src/main.mxy against a C lexer-only pass over src/ (the selfcompile benchmark), at most 2x. The roadmap's target is under 100 ms for the self-compile; wall and CPU milliseconds are printed for reference. Threads are counted beyond the CPU count, since the pool starts one worker per CPU (MOXY_THREADS sets another number). Binaries are release builds (-O2 -DNDEBUG) stripped; the C emitted for a hello world is nearly all runtime. The cache is the per-user one (MOXY_CACHE, else ~/.cache/moxy), measured after make test: every entry in it has a cap (Disk budget, above).

Soak tests

bench/soak/ holds long-running workloads, and bench/soak.ts runs them while sampling the process from outside: resident memory, open descriptors, threads (ps and lsof on macOS, /proc on Linux), plus the task stacks the runtime has mapped, which each workload prints. After a warm-up (the first fifth, at least a minute) a series is flat when the rise of its least-squares line across the run, and the change between its first and last quarters, are both within 2 MB or 5% (memory), 2 (descriptors, threads), or 16 or 10% (stacks), or twice the series' own noise when that is larger.

Workload What it does each round
http.mxy an std/http server and its clients in one process: 16 kept-alive connections of 20 requests each, 16 clients making a fresh connection for one request and another for a missing route (404), and every fourth round a client that sends garbage (400), oversized headers (431) and times out on a slow route; meanwhile 4 clients keep connecting and saying nothing until the server's idle timeout closes them. Handlers build replies inside a gate. Rounds are paced to about 250 new connections a second: each one a client closes holds an ephemeral port in TIME_WAIT, and macOS has about 16,000 of them for 30 s
actors.mxy 16 tasks casting and calling 32 standing actors and a relay actor that calls another, 200 short-lived actors made, called and dropped, and 200 calls to an actor of which some panic and are caught
chans.mxy 8 producer, stage and consumer pipelines over buffered and unbuffered channels; 8 more dropped half way, so their tasks are cancelled in send, recv and select; race, timeout, and every tenth round 2,000 async calls sleeping on timers at once
make soak                                   # every workload at once for 2 minutes: a smoke test
make soak SOAKMIN=240                       # four hours
bun bench/soak.ts --minutes 60 --only http --every 30

Each run writes build/soak/<name>.csv (seconds, rss, fds, threads, stacks) and prints start, end, slope and verdict per series. On a Linux machine without bun, sh bench/soak/sample.sh build/soak/http 14400 build/soak/http.csv samples from /proc after moxy build --release bench/soak/http.mxy -o build/soak/http; judge the file anywhere with bun bench/soak.ts --judge build/soak/http.csv. For a multi-hour run, use a machine that is otherwise idle, start it under nohup (or tmux), and keep the CSVs: a slow leak is a straight line in them. The workloads bind to 127.0.0.1 on a port the system picks and stop on their own when the time is up.

Runs so far (2026-12-01 and 02), each 35 minutes on macOS (Apple M1 Max, the machine shared with other builds) and 33 on Linux (arm64 VM, 4 CPUs, heavily loaded), judged after warm-up. Memory is resident MB, start → end of the judged part:

Run Workload Memory Descriptors Threads Stacks Verdict
macOS, 10 workers http 16.5 → 17.7 (rise 1.2) 8 → 8 13 162 flat
actors 5.7 → 5.9 3 11 162 flat
chans 6.1 → 6.3 (bursts to 36.5) 3 12 145 → 154 flat
macOS, MOXY_THREADS=4 actors 3.9 → 4.2 3 5 66 flat
chans 4.8 → 4.9 (bursts to 35.8) 3 6 73 → 76 flat
http, paced 10.2 → 12.8 (rise 3.1) 13 → 13 7 73 → 70 growing
Linux, MOXY_THREADS=2 http 14.0 → 7.9 91 → 17 (noise) 5 44 → 43 flat
chans 16.5 → 6.6 3 4 41 → 43 flat

The macOS http server's resident memory creeps (1 to 3 MB in half an hour, in steps, slowing) while its heap doesn't: counting live malloc bytes over a 5-minute run gave 170 to 200 KB throughout, and vmmap showed the default malloc zone 7.5 MB dirty of which 97% was free. That is the system allocator keeping freed small-region pages (64 KB bodies and read buffers churn through them), not something the program holds, but only a run of several hours on an idle machine will show whether it levels off. Descriptors and threads never grew in any run, and no request failed once the http workload was paced (unpaced, it ran macOS out of ephemeral ports).

Formatter and linter

  • src/fmt is token-based: it keeps your line breaks and comments, and normalizes spacing and indentation. It is idempotent.
  • The linter runs sema with lint flags (unused variables, shadowing, empty blocks); moxyfmt.yaml toggles them.

Self-hosting

The compiler is written in Moxy. Each directory under src/ is a module: index.mxy holds its types and declarations and includes the module's implementation files, and src/main.mxy pulls in the rest. The whole compiler is one translation unit, so static names must be unique across src/.

bootstrap/moxy.c is the C that an earlier moxy generated from src/. make builds from it in three steps:

Step Built from By
build/stage0/moxy bootstrap/moxy.c $(HOSTCC)
build/stage1/moxy src/ stage0, then $(HOSTCC)
build/moxy src/ stage1, then $(CC)

The bootstrap stages always build for the host, so CC, CFLAGS and LDFLAGS only affect build/moxy, and cross builds work as before. make verify checks that build/moxy regenerates exactly the C it was built from. make seed copies that C to bootstrap/moxy.c.

make windows compiles that same build/moxy.c with MinGW-w64 (WINCC, default x86_64-w64-mingw32-gcc) into build/windows/moxy.exe. goose is built unchanged with compat/win/goose.h force-included, which maps its mkdir(path, mode), realpath and <sys/wait.h> onto the C runtime. On Windows itself (MSYS2), make does the same for goose and names the programs .exe. bootstrap/moxy.c predates the Windows port, so until it is reseeded a Windows build needs SEED= pointing at C generated from the current src/ on another machine (CI does this).

src/ may only use features that the compiler in bootstrap/moxy.c understands. To use a new language feature in the compiler itself, land the feature, run make seed, then use it. If a change breaks the compiler's ability to build itself, bootstrap/moxy.c is the known-good starting point.

Testing the compiler

make test                                          # build, then run tests/ and examples
sh tests/diag/run.sh                               # every diagnostic has a code, a docs entry and a test
sh tests/cwarn/run.sh                              # generated C compiles clean under -Wall -Wextra -Werror
make verify                                        # build/moxy reproduces its own C
make sanitize && ./build/asan/moxy test --sanitize tests
make budget                                        # resource budgets (bench/budget.json)
make soak                                          # soak workloads, 2 minutes; SOAKMIN=240 for hours
sh scripts/emitsame.sh old-moxy build/moxy         # a speedup changed no emitted C or warning

CI runs the suite on Linux and macOS, plus an ASan/UBSan build of the compiler running every test with sanitizers (and LeakSanitizer) enabled for the generated programs. A Windows job builds and tests under MSYS2 (UCRT64 gcc), starting from C that a Linux job generates, and a cross job compiles every test for x86_64-linux-musl (run), x86_64-windows-gnu and aarch64-linux-gnu (built only) with zig cc.

Fuzzing

tools/fuzz holds two fuzzers. make fuzz runs both briefly (FUZZTIME seconds each, 60 by default), and CI runs it on every push.

  • libFuzzer, in process. tools/fuzz/main.mxy is the compiler's pipeline with LLVMFuzzerTestOneInput in place of main, built to build/fuzz/moxyfuzz with -fsanitize=fuzzer,address,undefined (FUZZCC, by default Homebrew's LLVM clang when present, since Apple's clang has no libFuzzer). Each input is a source file; errors jump back through diag_set_recover as they do in moxy test, so only crashes, sanitizer reports, hangs and runaway memory are findings. MOXY_FUZZ_STAGE stops after lex, parse or check, or goes through emit (the default). tools/fuzz/run.sh <stage> <seconds> <jobs> runs it with -fork, because the compiler never frees a program's AST and memory grows with each input; the corpus is kept in build/fuzz/corpus/<stage> and merged down when it passes 64 MB, and findings land in build/fuzz/crashes/. Run one again with build/fuzz/moxyfuzz <file>.
  • Structural mutations, out of process. bun tools/fuzz/oracle.ts mutates the programs in tests/, examples/ and std/ a few edits at a time (whole declarations and balanced blocks spliced between files, token ranges dropped or repeated, names, literals and operators swapped, groups nested deeply), so most cases still parse and reach the checker and code generator. A case is a finding when moxy emit exits with anything but 0 or 1, prints a sanitizer report or runs past --timeout, or when it accepts the program and the C it prints fails cc -std=c11 -fsyntax-only. That last check is the invalid C oracle. An error at a line of the program can be C that the program wrote, which the C compiler is there to report (unknown names are C; see Working with C), so those are listed as line findings for a person to judge; an error anywhere else is in C the compiler made up. Findings go to build/fuzz/findings/, one per signature. Crashes and hangs fail the run; invalid C fails it only with --strict.

bun tools/fuzz/reduce.ts finding.mxy -I dir shrinks a finding to a small program that fails the same way; it becomes a test in tests/fuzz/ (a compile error gets an .err file), next to the fix.

Long runs, with the corpus carried over between them:

make build/fuzz/moxyfuzz
FUZZ_KEEPGOING=1 sh tools/fuzz/run.sh emit 3600 4     # an hour, four workers, past the first finding
FUZZ_KEEPGOING=1 sh tools/fuzz/run.sh parse 1800 2
make sanitize && bun tools/fuzz/oracle.ts --time 3600 --jobs 6 --moxy build/asan/moxy

run.sh limits each input to 10 s and a single allocation to 2 GB, each worker to 4 GB (the compiler keeps every input's tree, so an oom- finding that runs alone in little memory is that growth, not the input), and output files to 2 GB. The oracle limits each moxy emit to --timeout seconds and, where the kernel supports it (not macOS), 4 GB of address space.

Edit this page on GitHub