MoxyMoxy

Changes

0.4.0

Upgrading from 0.3

Every change since 0.3.1 that can stop a 0.3 program from compiling, or make it behave differently, and what to do about it. Warnings marked "an error from 0.5" are a migration period: fix them now and 0.5 changes nothing for you.

Diagnostics:

  • Every diagnostic has a code: error[E0805]: message and warning[W0101]: message, where 0.3 printed error: message. Scripts and tests that match compiler output should match the text after ]: , or the code itself, which never changes meaning. moxy explain <code> describes any of them.

Patterns in match:

  • | separates alternatives. 1 | 2 => used to match the value 3 (C's bitwise or); now it matches 1 or 2. Parenthesize to keep the bitwise or: (A | B) =>. An alternative that earlier patterns already cover is error E0803.
  • A lowercase name that isn't a variant binds the value: limit => used to compare against a variable limit, and now matches anything (so the arms after it become unreachable, W0208). Compare with a guard: x if x == limit =>. Names that start with an uppercase letter (Red, MAX) still compare.
  • An unreachable arm is warning W0208 and is left out of the program; 0.3 warned only after _. Nothing to change unless you want the warning gone.

Optionals and ref struct:

  • Reading a weak field gives T?. Reaching through it without a check (w.app.stopping, w.app.stop()) is warning W0207, an error from 0.5; it compiles to a checked read that panics with its location when the object is gone, where 0.3 crashed. A null check on the field doesn't silence it (fields aren't narrowed: w.app != null && w.app.stopping reads the field twice). Fix: App? app = w.app; if (app != null) ..., or w.app?.stopping, or w.app!.stopping to keep the panic.
  • A ref struct variable, parameter or field that is left null or given a value that may be null (Node n;, f(null) for a Node parameter, Node n = w.parent;) is warning W0204 or W0205, an error from 0.5. Fix: declare it optional (Node? n) and check it, or pass a real object.

Enums:

  • The variants of a Moxy enum (no = values and no trailing ;) are reached through the enum: Power::Low. 0.3 also let the variants of an enum without payloads be named bare, as C constants (Low); in 0.4 that is warning W0209, an error from 0.5, and still means the variant when exactly one enum has it (with two, the name is left to C and fails there, as it did in 0.3). Fix: qualify the name, or make it a C enum with a trailing ; (enum Power { Low, High };), whose constants are global.

Threads, futures and locks:

  • A plain ref struct can't cross threads (E1021): passed to or returned from a Future function, sent on a channel, captured by spawn or a parallel loop. 0.3 allowed it. Fix: declare it shared ref struct, and write its fields inside lock (x) { ... }.
  • A field of a shared ref struct that holds a counted value (string, list, map, closure, object, or a struct holding one) is read only inside lock on the variable it is reached through (E1022, E1023). Fix: lock (x) { ... } around the read; scalars and atomic fields need no lock.
  • Dropping the last handle to a Future cancels it. A future started for its effect and never awaited used to run to its end; now it is cancelled when its handle goes away (W0201 when the call is a statement). Fix: keep the handle and await it, or run the work with spawn { ... }.
  • A method that returns Future<T> called on a ref struct gives the Future<T>; 0.3 typed the call as the bare T. Fix: await obj.method().

Names:

  • Functions and globals named mxy_* are error E0304; that prefix belongs to the runtime. 0.3 dropped such globals without a word. Rename them.
  • A name that a using brings in and that is also declared where the using is, or brought in by a second using, is error E0331 in code after the using, listing the candidates. 0.3 silently took the global one: with std/fmt.mxy included (directly or through std/time.mxy) and using ui;, Align::Center meant fmt's Align, and storing it into a ui::Align changed its value. Fix: name the one you mean with its namespace (ui::Align::Center). std/fmt.mxy's Align stays global in 0.4, since Align::Right is its documented spelling.
  • C code that reaches into the runtime's object header (((mxy_obj *)p)->...) breaks: the header is 16 bytes with different fields. It was never API; use Drop for cleanup.

Run-time behavior:

  • Debug builds panic (exit 101, with a location) on signed integer overflow and integer division by zero; release builds keep C behavior. Use wrapping_*, saturating_* or checked_* where overflow is intended.
  • A null or invalid memory access exits with code 101 and panic: null or invalid memory access instead of dying on a signal (SIGSEGV, shown as 139 by most shells); a stack overflow prints panic: stack overflow.
  • Debug builds print a report of ref struct objects still alive at exit, and moxy test fails a test that leaks. Break the cycle with a weak field, or set MOXY_LEAKS=0.
  • Floats print in shortest round-trip form without an exponent below 1e16: 10.0 where 0.3 printed 1e+01.
  • Integer literals above INT_MAX without a suffix are long long, so they keep their value where long is 32 bits.
  • A failed assert prints the asserted expression and, for a comparison, both values; assert(cond, msg) prints the expression too, with the message on a message: line after it, where 0.3 printed the message in its place. Update .stderr expectations that matched the old text.
  • A test that exits with status 77 fails; 0.3 reported it as left out by #if.

Language

  • Generics: structs, ref structs, Moxy enums and functions take type parameters (struct Pair<A, B>, enum Option<T>, T first<T>(T[] xs)).

  • Type arguments can be written (Pair<int, string>{...}, first<long>(xs), Option<int>::None, id<int> as a function value) or inferred from arguments, struct field values, enum payloads and the expected type. When arguments disagree on a number type, the wider one wins.

  • Each set of type arguments compiles to its own readable C struct, enum or function (Pair__int__string, first__long), made once per program.

  • A generic body is checked once, where it is written. An unbounded type parameter supports copying, passing, storing, printing and interpolation. Bounds such as <T: Ord> are parsed and recorded; they are checked once interfaces exist.

  • Fixed-width integer names i8 … u64, isize, usize, f32, f64, as contextual aliases: C code using them as names keeps compiling.

  • Debug builds panic with a location on signed integer overflow and integer division by zero; release builds keep C behavior. wrapping_* and saturating_* methods on every integer type.

  • Lists and maps of <stdint.h> integer types print, compare, hash and sort.

  • Methods: impl T { ... } on structs, ref structs, enums, generic instances, built-in types and C types, with static methods and Self; each compiles to a plain C function (Point_len(&p)).

  • Interfaces with default bodies and type parameters; generic impls with bounds (impl<T: Eq> Pair<T, T>). Generic bounds are checked at every instantiation.

  • Standard interfaces Eq, Ord, Hash, Format, Into<U> and Drop, wired into ==, <, sort(), map keys, print, interpolation and release. Structs and enums get Eq, Hash and Format structurally. Drop is only allowed on ref struct.

  • dyn Iface: explicit dynamic dispatch through a reference-counted box and a static vtable.

  • Compile-time reflection: static for f in T.fields, T.variants, static if, v.[f], unrolled per type with nothing at run time.

  • Integer literals above INT_MAX without a suffix are long long (so they keep their value where long is 32 bits).

  • A failed assert prints the asserted expression and, for a comparison, both sides' values: assertion failed: x + 1 == 4 (left: 3, right: 4). assert(cond, msg) adds a message line.

  • Floats print in shortest round-trip form without an exponent below 1e16 (10.0, not 1e+01).

  • Slices: T[..] views of lists, C arrays and other slices (xs[1..4], xs[..]), with copy-on-write writes through the view, for-in, and len, to_list, contains, index_of and in-place sort. String slices are strings.

  • Globals named mxy_* are a compile error (the prefix belongs to the runtime); before, they were silently dropped.

  • Optionals: T? for any type, flow-sensitive narrowing (if (x != null), early returns, &&), Some/None in match, ?., ?? and ! (which panics with a location). Reading a weak field gives T?; reaching through one declared without ? (w.app.x), which 0.3 allowed, is warning W0207 until 0.5 and panics with a location when the object is gone.

  • A non-optional ref struct that may be null is a warning with a fix-it; it becomes an error in 0.5.

  • Result<T, E> with typed errors; Result<T> means Result<T, string>. Postfix ? returns an Err (or null) early, converting the error through Into or Format, and runs defers like return.

  • checked_add, checked_sub and checked_mul return T?. A built-in Num interface allows arithmetic on type parameters (<T: Num>).

  • Names starting with mxy_ are reserved for the runtime: defining a function or global with one is a compile error.

  • Richer match patterns. Guards (n if n > 0 =>, seeing the pattern's bindings), alternatives (1 | 2 =>, Circle(x) | Square(x) =>, each binding the same names at the same types), nested patterns in payloads (Some(Ok(v)), Shape::Rect(0, h)), and struct patterns on structs and ref structs (Point{ .x = 0, .y = y }, unlisted fields match anything). Structs can be matched.

  • Exhaustiveness looks through nested patterns and names what is missing (missing Some(Err(_))); a guarded arm never counts as covering its pattern. An unreachable arm (after _, a repeated variant, or anything earlier arms cover) is warning W0208 and is left out of the generated code; an alternative earlier patterns cover is error E0803.

  • Behavior change: in a pattern, | separates alternatives; 1 | 2 => used to match the value 3. Parenthesize for C's bitwise or: (A | B) =>. A lowercase name that isn't a variant now binds the value (x if x > 0 =>) instead of comparing against a variable of that name.

  • None and Some(v) are values where an optional is expected (p = None;, return Some(x);, x == None), as they are patterns in match. Before, None passed the checker and reached the C compiler undeclared.

  • A bare variant of an enum without payloads (Low for Power::Low), which 0.3 compiled as a C constant, is warning W0209 and still means the variant; it becomes an error in 0.5.

  • A defer body keeps the null-check narrowing in effect where the defer is written, for variables nothing after it in the block assigns; it used to drop all narrowing. When a later assignment is the reason a variable isn't narrowed there, the error says so.

  • m.get_or(k, null) where a V? is expected gives a V?, one lookup that is null when k is missing. It used to check the null against the map's non-optional V and warn (W0205).

  • (void)x discards a value of any type, as in C. It rejected optionals and managed values (E0430).

  • A Moxy enum followed by a declaration that starts with a name (namespace, ref struct, impl, a function returning a struct) is no longer read as a C enum with a declarator, which made Color::Blue an unknown name.

Concurrency

  • async functions: async T name(params) { ... } (also async void, methods on ref structs, static methods, and lambdas async (x) => ...). A call runs on the calling thread at once, until it first waits, then returns a Future<T>; the thread switches between its async calls only where they wait. Plain ref structs, slices and any other value may be passed, captured and returned, with no shared or lock. await in main runs the thread's async calls until it has its value; a pool task's async calls stay on its worker. An async call's Future can't cross threads (a compile error where the type shows it, a runtime panic otherwise). Without fibers (-DMXY_NO_FIBERS, other targets) an async call runs to its end inside the call. async is contextual: C code using it as a name still compiles.

  • all(fs), race(fs) (the others are cancelled) and f.timeout(ms) (a Future<T?>, null and f cancelled when it runs late), over async calls and pool futures alike.

  • await f()? now means (await f())?, and await f()! means (await f())!; before, ? and ! applied to the Future and failed to compile.

  • A host run loop (a GUI's) can drive async calls: mxy_async_run(), a pollable mxy_async_fd() and a mxy_async_notify(fn, arg) callback.

  • sleep_ms and time_sleep park an async call, a pool task, or main once it has made an async call, instead of blocking the thread; a cancelled one returns early.

  • Future methods: a method that returns Future<T> (or is async) called on a ref struct now gives the Future; before, its call was typed as the bare T. On a value type it is an error.

  • Timed waits on fibers are kept in a doubly linked list placed from the latest deadline instead of a list walked from the earliest: 10,000 async calls each sleeping 50 ms finish in 91 ms instead of 615 ms (Apple M1 Max).

  • A pool task cancelled before it started can be awaited (it gives the zero value) instead of waiting forever; only race and timeout, which cancel Futures that other handles still hold, could reach that.

  • Task stacks are given back after a burst. A thread keeps at most 16 spare contexts with stacks and unmaps the rest as they come free; before, every stack a burst of waiting tasks made stayed mapped and resident for the life of the program (10,000 async calls each sleeping 20 ms left 167 MB resident; now 8 MB). The contexts themselves are kept, without stacks, for reuse, since their parkers may still be woken.

  • Under ThreadSanitizer, fiber switches are announced (__tsan_switch_to_fiber), so programs that use futures can be checked with -fsanitize=thread.

  • Actors: actor Name { fields; methods }, a reference type whose fields only its own methods touch, one message at a time, on the pool. From outside, a void method call returns at once (a cast) and any other returns a Future<T> (a call); messages from one sender arrive in order; inside its methods self.f and self.m() are direct. Reading a field from outside is a compile error. Arguments, results and literal values follow the crossing rules; actor references cross freely. An idle actor is its object only (about 74 bytes with one field); messages are one allocation and one compare-and-swap. A message that waits keeps its actor busy (no reentrancy); actors awaiting each other in a cycle panic with every await's place instead of hanging. Messages are never cancelled. actor is contextual.

  • Crash isolation: a panic inside an actor message, a spawn block or a parallel loop's chunk is caught at that boundary. A failed call's await raises the panic in the awaiter with both places; f.result() gives a Future<Result<T>> with it as Err; a failed cast is printed and the actor goes on. What the unwound frames held leaks (the debug leak report notes it); gates opened inside are closed; a panic while holding a lock stays fatal. all, race and timeout pass failures on.

  • parallel for i in a..b { ... }, xs.par_map(f) and spawn { ... } on the pool. A parallel body reads what it captures (crossing rules) and writes results only as out[i] = ... into a list from before the loop, by its loop variable. Loops under about 50 µs run on the calling thread alone. A panic in a body stops the loop and is raised in the caller with the loop's place; cancellation stops it between chunks. parallel and spawn are contextual.

  • Reference counts are plain (non-atomic) until a value crosses threads through a future, a channel or a lock; only then is it marked shared and counted atomically. A plain ref struct can't cross threads; declare it shared ref struct.

  • Waiting tasks park on fibers instead of blocking a pool worker. std/net and std/http sockets wait on the pool's event loop (kqueue, epoll; WSAPoll on Windows, untested).

  • Futures run on a work-stealing pool sized to the CPU count (MOXY_THREADS overrides) instead of one OS thread each.

  • chan<T> (buffered or unbuffered) with send, recv (returns T?), close and for v in c; select with send, receive, timeout(ms) and default arms.

  • Dropping the last handle to a Future cancels it; cancelled(), await, channel operations and select observe it. Behavior change: a future that is never awaited no longer keeps running after its handle goes away.

  • Breaking: a field of a shared ref struct that holds a counted value (string, list, map, closure, object, or a value holding one) is read only inside lock on the variable it is reached through; before, such a read raced with a writer that freed the old value. Value methods on its struct fields need the lock too. Scalars may still be read without it.

  • atomic fields in a shared ref struct (atomic long hits;): integers, bool and C pointers read and written without a lock, each access one __atomic builtin.

  • print and string() of a shared ref struct take its lock.

  • Inside lock (x), a field read through x is lent to calls without a retain unless the callee may write it.

  • Fixed: a timed wait (sleep_ms, a select timeout, f.timeout(ms)) on a fiber could run a millisecond long, so of two async calls sleeping equally long the first could wake second. Fibers now park until the deadline itself.

  • Fixed: a parallel for called its body through a function type that differed from the body's own (int64_t against long long, distinct types on 64-bit Linux), which is undefined behaviour; clang's UBSan stopped every parallel loop.

  • Fixed: a thread that waited on a task or actor and then made its first async call lost its earlier parker (a small leak per thread, reported by LeakSanitizer).

Standard library

  • std/net (TCP, UDP, addresses, name lookup) and std/http (a small HTTP/1.1 server and client); examples/webserver uses them.
  • std/sync: Mutex<T> is the object's own lock, the one lock (m) takes, and reentrant; Atomic<T>, Once and the std/net sockets use atomic fields. Behavior change: try_lock() in the task that holds a Mutex now succeeds.
  • std/fs, std/path and std/process with a typed IoError; std/json with reflection-derived mapping; std/sync (Mutex<T>, RwLock<T>, Atomic<T>, Once, WaitGroup); Set, Deque, Heap and OrderedMap.
  • std/hash (wyhash, SipHash-1-3, FNV-1a, a Hasher), std/rand (seedable PRNG, unbiased ranges, shuffle, choice, OS entropy), std/fmt (fixed and precision formatting, separators, hex/bin/oct, padding), and a fuller std/time (Duration, Instant, dates and times, ISO 8601, unix timestamps).
  • Fixed: fs::read_text leaked the whole file on every call: the runtime's string was copied and the original never released.

Memory and runtime

  • gate { ... }: every value made while the block runs, by it or by the functions it calls, comes from an arena freed in one step at the closing brace and on every return, break, continue and ? out of it. A value that leaves (returned, stored into a variable, global, object, list or map from outside, sent on a channel, passed to a future) is copied out deep at that point, into wherever it goes. A ref struct made inside a gate can't leave it: a compile error where the compiler sees it, a panic naming both places where a callee does it. Programs without gates are unchanged. See Gates.
  • moxy emit --explain-gates prints each gate decision; moxy lint lists copy-outs with their size class; moxy test --gate-stress (or MOXY_GATE_STRESS=1) makes every function body a gate to shake out missed escapes. Debug builds make a closed gate's memory inaccessible, so a pointer that escaped panics with the gate's location when read.
  • Gated binary-trees runs in about a third of the time of the same program without the gate; bench/ has gated binarytrees and jsonroundtrip against C versions with a bump arena.
  • T f(...) in gate declares that a function allocates into its caller's gate and returns without a copy (what any function called in a gate does); the compiler checks its body as if it were in that gate, rejects a return from inside a gate of its own, and rejects in gate on async and Future functions.
  • std/arena.mxy: Arena, a gate's memory held in a variable. gate (a) { ... } allocates from it with the usual copy-outs; the memory stays until a.reset(), a.free() or the last reference goes. Entering it twice at once, reset()/free() inside one of its blocks, and use after free() panic.
  • Gates with --cycles: a gate's objects are never roots of the thread's collections; a gate collects its own possible roots as it closes, so Drops of cycles made in it run. Gates with async: an async body never allocates in its caller's gate, its arguments (and an async lambda's captures) are copied out, and a ref struct from inside a gate passed to an async call is a compile error. await inside a gate resumes in the gate.
  • A store into a global no longer turns a gate dirty when it retains a value from the heap, so gated jsonroundtrip's rounds keep putting drops off. Outside every gate, a program with gates allocates straight through malloc again, which takes back part of the 15 to 20% its non-gated code paid (now 10 to 18%).
  • A shared type's Drop (such as Arena's) no longer stops every gate in the program from putting drops off.
  • moxy run through tcc works again: the runtime fills in the __atomic builtins tcc lacks (__atomic_exchange_n, __atomic_add_fetch, __atomic_sub_fetch); since the atomic-fields work every program had fallen back to cc.
  • Ownership inference: a variable's last use moves instead of retaining, dead retain/release pairs are removed, a released value's memory is reused by a same-sized allocation, and arguments are lent across calls when the callee doesn't write them.
  • Integers in interpolation and string() are formatted without printf, into a stack buffer; a + b + c and join allocate once; for w in s.split(sep) doesn't build the list; m[k] = m.get_or(k, d) + x looks the key up once. wordcount went from 2.9x C to 1.2x, jsonroundtrip from 1.7x to 1.2x.
  • Fixed: xs[i] = f() stored into freed memory when f() grew xs.
  • Fixed: arm64 Linux crashed switching fibers (gcc ignores naked there).
  • Fixed: a ref struct literal with a C array field generated invalid C.
  • Fixed: a program with a const string global crashed at exit in debug builds: the release of globals before the leak report cleared it, in read-only memory.
  • Fixed: lists, maps and slices of C enums (enum Mode { A, B };, Mode[]) generated invalid C: the per-element helpers were named from enum Mode.
  • Fixed: the debug leak report sometimes counted objects a finishing task was about to release.
  • List, slice and map operations are generated per element type, with direct element copy, release, equality and hashing (n-body went from 3.9x C to about 1.4x).
  • The compiler warns about ref struct types that can form a strong reference cycle, naming the path and suggesting weak; strong on a field silences it.
  • Debug builds report ref struct objects still alive at exit, grouped by allocation site (MOXY_LEAKS=0 turns it off).
  • unowned fields: a back-pointer with no weak-count bookkeeping; debug builds panic if it's read after its object is gone.
  • Opt-in cycle collector: --cycles on moxy build, run, test and emit (or cycles: true under build: in moxy.yaml) frees ref struct objects that only hold each other, through fields, lists, maps, optionals, enums, closures and dyn values, by synchronous trial deletion. Every Drop in a garbage cycle runs before any of its fields are released; weak references into it read as null. Objects shared with other threads are never collected. std/cycles.mxy has cycles::collect() and cycles::enabled(). Without the flag programs compile to the same code as before; with it binary-trees runs 16% slower, and a million two-node cycles peak at 3.9 MB instead of leaking 63 MB.
  • Dropping very deep structures no longer crashes: a million-node ref struct linked list, or deeply nested lists, maps and closures, is freed without growing the stack.
  • Null and invalid memory accesses are reported like a panic with exit code 101 (panic: null or invalid memory access), with at file.mxy:line:col in debug builds. Stack overflows print panic: stack overflow.
  • Reading through a weak field whose object is gone panics with its location instead of crashing.
  • s = s + x and s += x append in place when the string isn't shared: 100,000 single-character appends take about 1 ms instead of 225 ms.
  • ref struct objects use a 16-byte header instead of 40 (binary-trees peak memory: 35.5 MB to 18.7 MB).
  • Fixed: -DMXY_DEBUG=1 on an optimized build kept the leak report and the other debug checks but dropped the integer overflow and division checks; they now follow MXY_DEBUG too.

Tooling

  • Every diagnostic has a stable code, printed as error[E0805]: ... or warning[W0101]: ..., grouped by phase and never reused. moxy explain <code> prints its entry from docs/errors.md (what it means, a program that gets it, the fix); moxy explain --list lists them all. Every code has a docs entry whose examples are compiled by make test, and at least one test; scripts/diagcheck.mxy fails the build when a diagnostic is added without a code, a docs entry or a test. The language server reports the code and links to its entry.
  • A crash inside the compiler is an internal compiler error (exit 70) naming the location being compiled and asking for a bug report, instead of a panic: that pointed into the compiler's own source. Code nested too deeply for the compiler's stack is error E0003 instead of a crash.
  • Fixed: ? in a global's initializer crashed the compiler; it is error E0644. An error found while generating C (gates nested more than 64 deep, E0901) was printed but the build still succeeded.
  • A test block that exits with status 77 fails like any other non-zero exit; it used to be reported as left out by #if. The runner now asks the test binary which blocks a false #if left out (--moxy-test-left-out) before running any.
  • moxy test on a directory treats a file another file in the run includes as a part of it: it is built through its includer instead of on its own, so moxy test std passes (the net and http parts don't compile alone) and make test runs it without --filter "(doc)".
  • Tests in source: test "name" { ... } blocks at file scope, run by moxy test one process per block (a failed assert, panic, crash or leak fails only that block, reported by name with its message and location), and left out of build, run and emit. test stays an ordinary identifier everywhere else.
  • Doc examples: ```moxy fences in /// and /** */ comments are shown by moxy doc and compiled and run by moxy test, with optional // prints: output checks; ```moxy norun only compiles. The standard library's examples run in CI.
  • moxy test in a project also covers src/ files with test blocks or doc examples; --filter text picks tests by name. The project test cache covers both.
  • Bounded caches: precompiled runtimes keep the 8 most recently used (MOXY_PCH_KEEP), the project test cache drops deleted tests and caps at 256 MB, temporary directories are removed on exit, on signals and when their process is gone. moxy clean --cache and --dry-run.
  • moxy fmt handles continuation lines that start with an operator, cast chains on &x, return [] and for x in [..]; the whole tree is formatted and CI checks it.
  • The debugger formatters show optionals as Some(v)/None.
  • The compiler compiles itself in about 60 ms again, and CI checks the budget.
  • docs/benchmarks.md: every benchmark in C, Moxy, Rust and Zig.
  • moxy fix: previews mechanical modernizations of C in .mxy files as a diff (goto cleanup to defer, realloc-grown arrays to T[], strcpy/sprintf buffers to string, simple printf to print), applying them with --write only when the program provably behaves the same.
  • --target <triple> for build, run and test, and build.target in moxy.yaml, using zig cc when no compiler is configured. Windows support in the runtime (MinGW-w64 and zig cc); make windows cross-builds moxy.exe. Not yet run on Windows.
  • Faster debug builds: no shell, a cached precompiled runtime header, and tcc for moxy run when it's installed.
  • moxy test supports .stderr files listing lines the program's stderr must contain.
  • moxy doc: HTML or Markdown API docs from /// and /** */ comments.
  • Incremental project builds: moxy build, run and test skip work when nothing changed.
  • moxy search, moxy add <name> and moxy publish against a git package index.
  • Language server: go to definition, find references, rename, formatting, inlay type hints for auto, and quick fixes for mechanical help: suggestions.
  • moxy check --types prints the inferred type of every auto local.
  • VS Code extension and Neovim plugin in tools/editors/.
  • LLDB formatters and GDB pretty-printers in tools/debug for strings, lists, maps, Result, enums and ref struct objects.
  • bench/: benchmarks with C baselines, make bench, and a regression check in CI.
  • Resource budgets, checked in CI (make budget, bench/budget.json): the compiler's peak memory and time compiling itself, stripped release binaries of a hello world and an std/http server, the C a hello world emits, idle memory and threads of both, and the per-user cache after the tests.
  • Soak workloads (make soak, bench/soak/): an std/http server under mixed load, actor traffic with churn and caught panics, and channel pipelines with cancellation and timer bursts, sampled for memory, descriptors, threads and task stacks, failing on growth.
  • Browser playground (make playground): the compiler built to WebAssembly, showing the generated C and diagnostics as you type.
  • Fewer C compiler warnings in generated C under -Wall -Wextra: static closure objects and, with --cycles, type descriptors give every field; an unused type descriptor is marked unused; assert compares against a literal, sizeof or a C enum constant as written instead of through an int temporary; a lambda parameter, or a method's self, that the body ignores is marked (void). tests/cwarn checks the C for those cases and a spread of the suite with -Werror in CI.
  • scripts/matrix.sh runs the suite with every C compiler found (gcc, clang, Apple clang, zig cc), at -O0 and -O2, plain and under ASan with LeakSanitizer, UBSan and TSan, and CI runs it on Linux x86_64 and arm64, macOS and Windows. See CONTRIBUTING.md.

Documentation

  • docs/port.md: cJSON ported to Moxy, with line counts and benchmarks. Compiling cJSON.c unchanged forced four compiler fixes, two of them silent miscompilations of valid C.
  • Adopting Moxy in an existing C project (docs/guide/adoption.md), CONTRIBUTING.md, a language change process (docs/proposals/), a stability policy (docs/stability.md), starter tasks (docs/starter.md), and the site generator (site/) for moxy.codes: the docs, a home page whose C is generated by the compiler at build time, benchmarks, changelog, search and the playground.

0.3.1

Compiler

  • The compiler is written in Moxy and compiles itself. make bootstraps from bootstrap/moxy.c, so building from source still needs only a C compiler; make verify checks that the result reproduces itself exactly.
  • 0.3.0's release binaries failed to build against an outdated goose; goose is now pinned to a version that also builds with gcc 14.

C compatibility

  • A macro that is redefined or #undef'd means what it meant where it is used, as in C; before, the last definition applied everywhere. Macros defined once stay visible to the whole program.
  • Your macros no longer reach Moxy's runtime, so a name like #define len 3 is safe.
  • A variable or function can share a struct's name: static struct config config;, or struct timer beside int timer().
  • Structs, unions and typedefs defined inside a function belong to that function, so two functions can each define their own struct item. Defining a struct inside a function no longer crashes the compiler.
  • A struct that is only declared (struct handle;) and used through pointers compiles; its name was missing from the generated C.
  • string and null can be used as names (char *string, a field called null); they keep their Moxy meaning everywhere else.
  • p->field works when p points to a type from a C header, as it does for values of those types.
  • C headers next to any .mxy file are found, in single-file builds, tests and projects.
  • An include never resolves to the including file, so a test can share its module's name (tests/words.mxy including src/words.mxy).
  • _Noreturn is kept in the generated C, and assignments used as conditions keep their parentheses, so the generated C compiles without warnings under -Wall -Wextra.

Tooling

  • The formatter keeps the spaces in closure types and designated initializers: fn(int) -> int, Point{ .x = 1, .y = 2 }.

0.3.0

A rewrite of the compiler and runtime. Most 0.2 programs compile unchanged; the behavior changes below are deliberate.

Memory management

  • Automatic memory management is always on; --enable-arc and --enable-async are accepted and ignored. Strings, lists, maps, closures and futures are reference counted and freed when no longer used. See memory.md.
  • Lists and maps are values (copy-on-write). In 0.2 without ARC, b = a shared a buffer that could be freed under you; with ARC, b = a aliased. Now b is an independent copy.
  • string is a managed, immutable string that is still a const char * to C. == compares contents, and + concatenates.
  • New ref struct (shared objects) with weak fields, and new defer.

Language

  • Full C parsing, with no raw passthrough: struct and union definitions, declarators, switch, goto, compound literals, designated initializers. Typos are reported at the right place.
  • A real semantic pass: every expression has a type, and names are scoped per function and block.
  • Result<T> works as a return type: return Ok(x), return Err("..."), and Result<void>, plus unwrap, unwrap_or, is_ok, is_err and error().
  • Lists of structs, structs with string, list and map fields, and methods on fields (user.tags.push(x)).
  • for x in <any expression>, for i, x in list, ranges a..b and a..=b, iteration over strings and C arrays.
  • match:
    • binds every payload field (Rect(w, h)), and _ skips one;
    • accepts shorthand patterns (Circle(r)) and literal patterns (numbers, chars, strings, bools);
    • matches any expression;
    • is checked for exhaustiveness at compile time, naming the missing variants.
  • Lambdas capture variables (by value), and closure types are written fn(A) -> R. map, filter and each on lists.
  • Reassigning collections: xs = [..], m = {..}, s += "...", xs += ys.
  • Map literals {"k": v}, m[k] indexing and assignment, get_or, remove, keys, values.
  • String methods: split, trim, upper, lower, replace, find, slice, lines, to_int, to_float, repeat, chars.
  • print accepts several values. It prints bool as true/false, floats in shortest round-trip form (3.14, not 3.140000), and lists, maps, structs and enums readably.
  • String interpolation "\(expr)", string(x) formatting, and auto type inference.
  • main(string[] args) and int main(int argc, char **argv).
  • return anywhere inside Future<T> functions, futures of any type, and future handles that can be stored and awaited later.
  • namespace, nested namespaces, and using.

Modules and C interop

  • Each .mxy file is included once, so diamond includes and include cycles work.
  • Errors report the right file and line after includes, and C compiler errors map back to .mxy lines through #line.
  • #if/#ifdef/#else are honored around declarations and inside functions, so each branch can define the same function.
  • String literals passed to C functions stay plain C literals (format checking works).
  • Types can be passed to C macros (va_arg(ap, int), offsetof(T, f)).

Safety

  • No fixed-size limits in the compiler: programs of any size, any number of declarations, statements, list items, enum variants, parameters, or string length.
  • List indexing is bounds-checked, and missing map keys panic with the key, instead of reading garbage.
  • A managed local declared directly under a case label, or a managed field in a union, is a compile error.

Tooling

  • moxy is the only executable: goose is linked in as a library. Build moxy with make.
  • moxy test runs tests/**/*.mxy and *.test.mxy, with .out, .code and .err expectations and --sanitize. The _test.mxy naming still works.
  • moxy check, moxy emit, moxy run -- args, and -p member for workspaces.
  • Library projects build lib<name>.a plus a C header.
  • The token-based formatter is idempotent and keeps Result<T> intact; the linter reports unused variables, shadowing and empty blocks.
  • CI runs the suite on Linux and macOS, plus a sanitizer job.

Behavior changes to check when upgrading

0.2 0.3
print(true) printed 1 prints true
print(3.14) printed 3.140000 prints 3.14
m.get(missing) returned 0 panics; use get_or
list aliasing (with --enable-arc) lists are values
string + pointer arithmetic (s + 3) not allowed on string; cast to const char * first
tests named *_test.mxy still found; tests/<area>/<name>.mxy preferred

Edit this page on GitHub