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]: messageandwarning[W0101]: message, where 0.3 printederror: 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 variablelimit, 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
weakfield givesT?. 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.stoppingreads the field twice). Fix:App? app = w.app; if (app != null) ..., orw.app?.stopping, orw.app!.stoppingto keep the panic. - A
ref structvariable, parameter or field that is left null or given a value that may be null (Node n;,f(null)for aNodeparameter,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 structcan't cross threads (E1021): passed to or returned from aFuturefunction, sent on a channel, captured byspawnor a parallel loop. 0.3 allowed it. Fix: declare itshared ref struct, and write its fields insidelock (x) { ... }. - A field of a
shared ref structthat holds a counted value (string, list, map, closure, object, or a struct holding one) is read only insidelockon the variable it is reached through (E1022, E1023). Fix:lock (x) { ... }around the read; scalars andatomicfields need no lock. - Dropping the last handle to a
Futurecancels 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 andawaitit, or run the work withspawn { ... }. - A method that returns
Future<T>called on aref structgives theFuture<T>; 0.3 typed the call as the bareT. 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
usingbrings in and that is also declared where theusingis, or brought in by a secondusing, is error E0331 in code after theusing, listing the candidates. 0.3 silently took the global one: withstd/fmt.mxyincluded (directly or throughstd/time.mxy) andusing ui;,Align::Centermeant fmt'sAlign, and storing it into aui::Alignchanged its value. Fix: name the one you mean with its namespace (ui::Align::Center).std/fmt.mxy'sAlignstays global in 0.4, sinceAlign::Rightis 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; useDropfor 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_*orchecked_*where overflow is intended. - A null or invalid memory access exits with code 101 and
panic: null or invalid memory accessinstead of dying on a signal (SIGSEGV, shown as 139 by most shells); a stack overflow printspanic: stack overflow. - Debug builds print a report of
ref structobjects still alive at exit, andmoxy testfails a test that leaks. Break the cycle with aweakfield, or setMOXY_LEAKS=0. - Floats print in shortest round-trip form without an exponent below 1e16:
10.0where 0.3 printed1e+01. - Integer literals above
INT_MAXwithout a suffix arelong long, so they keep their value wherelongis 32 bits. - A failed
assertprints the asserted expression and, for a comparison, both values;assert(cond, msg)prints the expression too, with the message on amessage:line after it, where 0.3 printed the message in its place. Update.stderrexpectations 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_*andsaturating_*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, withstaticmethods andSelf; 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>andDrop, wired into==,<,sort(), map keys,print, interpolation and release. Structs and enums getEq,HashandFormatstructurally.Dropis only allowed onref 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_MAXwithout a suffix arelong long(so they keep their value wherelongis 32 bits).A failed
assertprints 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, not1e+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, andlen,to_list,contains,index_ofand in-placesort. 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/Noneinmatch,?.,??and!(which panics with a location). Reading aweakfield givesT?; 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 structthat 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>meansResult<T, string>. Postfix?returns anErr(ornull) early, converting the error throughIntoorFormat, and runsdefers likereturn.checked_add,checked_subandchecked_mulreturnT?. A built-inNuminterface 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
matchpatterns. 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 andref 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.NoneandSome(v)are values where an optional is expected (p = None;,return Some(x);,x == None), as they are patterns inmatch. Before,Nonepassed the checker and reached the C compiler undeclared.A bare variant of an enum without payloads (
LowforPower::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
deferbody keeps the null-check narrowing in effect where thedeferis 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 aV?is expected gives aV?, one lookup that is null whenkis missing. It used to check thenullagainst the map's non-optionalVand warn (W0205).(void)xdiscards 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 madeColor::Bluean unknown name.
Concurrency
asyncfunctions:async T name(params) { ... }(alsoasync void, methods onref structs,staticmethods, and lambdasasync (x) => ...). A call runs on the calling thread at once, until it first waits, then returns aFuture<T>; the thread switches between its async calls only where they wait. Plainref structs, slices and any other value may be passed, captured and returned, with nosharedorlock.awaitinmainruns the thread's async calls until it has its value; a pool task's async calls stay on its worker. An async call'sFuturecan'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.asyncis contextual: C code using it as a name still compiles.all(fs),race(fs)(the others are cancelled) andf.timeout(ms)(aFuture<T?>, null andfcancelled when it runs late), over async calls and pool futures alike.await f()?now means(await f())?, andawait 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 pollablemxy_async_fd()and amxy_async_notify(fn, arg)callback.sleep_msandtime_sleeppark an async call, a pool task, ormainonce it has made an async call, instead of blocking the thread; a cancelled one returns early.Futuremethods: a method that returnsFuture<T>(or isasync) called on aref structnow gives theFuture; before, its call was typed as the bareT. 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
raceandtimeout, 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, avoidmethod call returns at once (a cast) and any other returns aFuture<T>(a call); messages from one sender arrive in order; inside its methodsself.fandself.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.actoris contextual.Crash isolation: a panic inside an actor message, a
spawnblock or a parallel loop's chunk is caught at that boundary. A failed call'sawaitraises the panic in the awaiter with both places;f.result()gives aFuture<Result<T>>with it asErr; 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,raceandtimeoutpass failures on.parallel for i in a..b { ... },xs.par_map(f)andspawn { ... }on the pool. A parallel body reads what it captures (crossing rules) and writes results only asout[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.parallelandspawnare 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 structcan't cross threads; declare itshared ref struct.Waiting tasks park on fibers instead of blocking a pool worker.
std/netandstd/httpsockets 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_THREADSoverrides) instead of one OS thread each.chan<T>(buffered or unbuffered) withsend,recv(returnsT?),closeandfor v in c;selectwith send, receive,timeout(ms)anddefaultarms.Dropping the last handle to a
Futurecancels it;cancelled(),await, channel operations andselectobserve 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 structthat holds a counted value (string, list, map, closure, object, or a value holding one) is read only insidelockon 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.atomicfields in ashared ref struct(atomic long hits;): integers,booland C pointers read and written without a lock, each access one__atomicbuiltin.printandstring()of ashared ref structtake its lock.Inside
lock (x), a field read throughxis lent to calls without a retain unless the callee may write it.Fixed: a timed wait (
sleep_ms, aselecttimeout,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
forcalled its body through a function type that differed from the body's own (int64_tagainstlong 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) andstd/http(a small HTTP/1.1 server and client);examples/webserveruses them.std/sync:Mutex<T>is the object's own lock, the onelock (m)takes, and reentrant;Atomic<T>,Onceand thestd/netsockets useatomicfields. Behavior change:try_lock()in the task that holds aMutexnow succeeds.std/fs,std/pathandstd/processwith a typedIoError;std/jsonwith reflection-derived mapping;std/sync(Mutex<T>,RwLock<T>,Atomic<T>,Once,WaitGroup);Set,Deque,HeapandOrderedMap.std/hash(wyhash, SipHash-1-3, FNV-1a, aHasher),std/rand(seedable PRNG, unbiased ranges, shuffle, choice, OS entropy),std/fmt(fixed and precision formatting, separators, hex/bin/oct, padding), and a fullerstd/time(Duration,Instant, dates and times, ISO 8601, unix timestamps).- Fixed:
fs::read_textleaked 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 everyreturn,break,continueand?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. Aref structmade 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-gatesprints each gate decision;moxy lintlists copy-outs with their size class;moxy test --gate-stress(orMOXY_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 gatedeclares 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 areturnfrom inside a gate of its own, and rejectsin gateon 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 untila.reset(),a.free()or the last reference goes. Entering it twice at once,reset()/free()inside one of its blocks, and use afterfree()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, soDrops of cycles made in it run. Gates withasync: an async body never allocates in its caller's gate, its arguments (and an async lambda's captures) are copied out, and aref structfrom inside a gate passed to an async call is a compile error.awaitinside 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
mallocagain, which takes back part of the 15 to 20% its non-gated code paid (now 10 to 18%). - A shared type's
Drop(such asArena's) no longer stops every gate in the program from putting drops off. moxy runthrough tcc works again: the runtime fills in the__atomicbuiltins tcc lacks (__atomic_exchange_n,__atomic_add_fetch,__atomic_sub_fetch); since the atomic-fields work every program had fallen back tocc.- 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 withoutprintf, into a stack buffer;a + b + candjoinallocate once;for w in s.split(sep)doesn't build the list;m[k] = m.get_or(k, d) + xlooks 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 whenf()grewxs. - Fixed: arm64 Linux crashed switching fibers (gcc ignores
nakedthere). - Fixed: a
ref structliteral with a C array field generated invalid C. - Fixed: a program with a
const stringglobal 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 fromenum 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 structtypes that can form a strong reference cycle, naming the path and suggestingweak;strongon a field silences it. - Debug builds report
ref structobjects still alive at exit, grouped by allocation site (MOXY_LEAKS=0turns it off). unownedfields: a back-pointer with no weak-count bookkeeping; debug builds panic if it's read after its object is gone.- Opt-in cycle collector:
--cyclesonmoxy build,run,testandemit(orcycles: trueunderbuild:inmoxy.yaml) freesref structobjects that only hold each other, through fields, lists, maps, optionals, enums, closures anddynvalues, by synchronous trial deletion. EveryDropin 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.mxyhascycles::collect()andcycles::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 structlinked 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), withat file.mxy:line:colin debug builds. Stack overflows printpanic: stack overflow. - Reading through a
weakfield whose object is gone panics with its location instead of crashing. s = s + xands += xappend in place when the string isn't shared: 100,000 single-character appends take about 1 ms instead of 225 ms.ref structobjects use a 16-byte header instead of 40 (binary-trees peak memory: 35.5 MB to 18.7 MB).- Fixed:
-DMXY_DEBUG=1on an optimized build kept the leak report and the other debug checks but dropped the integer overflow and division checks; they now followMXY_DEBUGtoo.
Tooling
- Every diagnostic has a stable code, printed as
error[E0805]: ...orwarning[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 --listlists them all. Every code has a docs entry whose examples are compiled bymake test, and at least one test;scripts/diagcheck.mxyfails 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#ifleft out (--moxy-test-left-out) before running any. moxy teston 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, somoxy test stdpasses (the net and http parts don't compile alone) andmake testruns it without--filter "(doc)".- Tests in source:
test "name" { ... }blocks at file scope, run bymoxy testone 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 ofbuild,runandemit.teststays an ordinary identifier everywhere else. - Doc examples:
```moxyfences in///and/** */comments are shown bymoxy docand compiled and run bymoxy test, with optional// prints:output checks;```moxy norunonly compiles. The standard library's examples run in CI. moxy testin a project also coverssrc/files with test blocks or doc examples;--filter textpicks 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 --cacheand--dry-run. moxy fmthandles continuation lines that start with an operator, cast chains on&x,return []andfor 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.mxyfiles as a diff (goto cleanup todefer, realloc-grown arrays toT[],strcpy/sprintfbuffers tostring, simpleprintftoprint), applying them with--writeonly when the program provably behaves the same.--target <triple>forbuild,runandtest, andbuild.targetin moxy.yaml, usingzig ccwhen no compiler is configured. Windows support in the runtime (MinGW-w64 and zig cc);make windowscross-buildsmoxy.exe. Not yet run on Windows.- Faster debug builds: no shell, a cached precompiled runtime header, and tcc for
moxy runwhen it's installed. moxy testsupports.stderrfiles listing lines the program's stderr must contain.moxy doc: HTML or Markdown API docs from///and/** */comments.- Incremental project builds:
moxy build,runandtestskip work when nothing changed. moxy search,moxy add <name>andmoxy publishagainst a git package index.- Language server: go to definition, find references, rename, formatting, inlay type hints for
auto, and quick fixes for mechanicalhelp:suggestions. moxy check --typesprints the inferred type of everyautolocal.- VS Code extension and Neovim plugin in
tools/editors/. - LLDB formatters and GDB pretty-printers in
tools/debugfor strings, lists, maps,Result, enums andref structobjects. 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;assertcompares against a literal,sizeofor a C enum constant as written instead of through aninttemporary; a lambda parameter, or a method'sself, that the body ignores is marked(void).tests/cwarnchecks the C for those cases and a spread of the suite with-Werrorin CI. scripts/matrix.shruns the suite with every C compiler found (gcc, clang, Apple clang, zig cc), at-O0and-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.
makebootstraps frombootstrap/moxy.c, so building from source still needs only a C compiler;make verifychecks 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 3is safe. - A variable or function can share a struct's name:
static struct config config;, orstruct timerbesideint 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. stringandnullcan be used as names (char *string, a field callednull); they keep their Moxy meaning everywhere else.p->fieldworks whenppoints to a type from a C header, as it does for values of those types.- C headers next to any
.mxyfile 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.mxyincludingsrc/words.mxy). _Noreturnis 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-arcand--enable-asyncare 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 = ashared a buffer that could be freed under you; with ARC,b = aaliased. Nowbis an independent copy. stringis a managed, immutable string that is still aconst char *to C.==compares contents, and+concatenates.- New
ref struct(shared objects) withweakfields, and newdefer.
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("..."), andResult<void>, plusunwrap,unwrap_or,is_ok,is_erranderror().- 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, rangesa..banda..=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.
- binds every payload field (
- Lambdas capture variables (by value), and closure types are written
fn(A) -> R.map,filterandeachon 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. printaccepts several values. It printsboolastrue/false, floats in shortest round-trip form (3.14, not3.140000), and lists, maps, structs and enums readably.- String interpolation
"\(expr)",string(x)formatting, andautotype inference. main(string[] args)andint main(int argc, char **argv).returnanywhere insideFuture<T>functions, futures of any type, and future handles that can be stored and awaited later.namespace, nested namespaces, andusing.
Modules and C interop
- Each
.mxyfile 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
.mxylines through#line. #if/#ifdef/#elseare 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
caselabel, or a managed field in a union, is a compile error.
Tooling
moxyis the only executable: goose is linked in as a library. Build moxy withmake.moxy testrunstests/**/*.mxyand*.test.mxy, with.out,.codeand.errexpectations and--sanitize. The_test.mxynaming still works.moxy check,moxy emit,moxy run -- args, and-p memberfor workspaces.- Library projects build
lib<name>.aplus 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 |