MoxyMoxy

C11 superset compiles to C MIT

TypeScript for C.

Moxy is C with strings, lists, maps, match, Result, closures and automatic memory management added. It compiles to readable C11, and ordinary C compiles unchanged in a .mxy file, so a project can move over one file at a time.

Install MoxyCompile in the browser

shapes.mxy11 lines
enum Shape {
    Circle(double r),
    Rect(double w, double h)
}

double area(Shape s) {
    match s {
        Shape::Circle(r) => return 3.14159 * r * r,
        Shape::Rect(w, h) => return w * h,
    }
}

The C excerpt was written by the compiler when this site was built, and cut only by leaving things out: 6,629 lines of embedded runtime, 56 lines of generated helpers, string literals, prototypes and main(). The runtime is embedded, so the file builds with any C11 compiler and needs no Moxy install.

$ moxy emit shapes.mxyexcerpt of 6,761 lines
typedef enum {
    Shape_Circle,
    Shape_Rect,
} Shape_Tag;
typedef struct Shape Shape;
struct Shape {
    Shape_Tag tag;
    union {
        struct { double r; } Circle;
        struct { double w; double h; } Rect;
    };
};

double area(Shape s) {
    {
        Shape __m1 = s;
        if (__m1.tag == Shape_Circle) {
            double r = __m1.Circle.r;
            (void)r;
            return ((3.14159 * r) * r);
        } else {
            double w = __m1.Rect.w;
            (void)w;
            double h = __m1.Rect.h;
            (void)h;
            return (w * h);
        }
    }
}
Output
One C11 file per .mxy file, runtime included. Your C compiler and flags build it, so sanitizers, cross-compilers and -Werror carry over. Source
Debugging
The C carries #line directives: C compiler errors, breakpoints and stepping point at your .mxy lines. Source
Self-hosted
The compiler is written in Moxy. It turns its own source into C in about 90 ms on an M1 Max, and make bootstraps it from that C. Source
Status
0.4.0, before 1.0: a release can still change anything, and the changelog says what did. Source

What you stop writing

You writeInstead of
string s = "hi " + name;malloc, strcpy, strcat, and remembering to free
print(x, y, list)printf with the right format codes
int[] xs = [1, 2, 3]; xs.push(4);a struct with data/len/cap and realloc
map[string, int] m = {"a": 1};a hash table library
enum Shape { Circle(double r) } + matcha tag enum, a union, and a switch
Result<int> parse(string s)out-parameters and error codes
(int x) => x + ka function plus a context struct
async / Future<T> / awaitcallbacks, event loops, pthread boilerplate
actor Cache { ... }a mutex around every shared field
defer fclose(f);goto cleanup

Strings and maps

words.mxy
map[string, int] count(string text) {
    map[string, int] seen = {};
    for word in text.split(" ") {
        seen[word] = seen.get_or(word, 0) + 1;
    }
    return seen;
}
$ moxy emit words.mxyexcerpt
mxy_map *count(mxy_str text) {
    mxy_map *seen = NULL;
    {
        mxy_str __s1 = mxy_str_retain(text);
        mxy_str __sep2 = ((mxy_str)__mxy_s1.s);
        mxy_split __split3 = mxy_split_of(__s1, __sep2);
        mxy_str __w4 = NULL;
        while (mxy_split_next(&__split3, &__w4)) {
            mxy_str word = __w4;
            mxy_str __t5 = word;
            int *__p6 = mxy_map_upsert__str__int(&seen, &__t5, 0, 0);
            *__p6 = MXY_ADD((*__p6), 1, "words.mxy:4:43");
            (void)(*__p6);
        }
        mxy_str_release(__w4);
        mxy_str_release(__sep2);
        mxy_str_release(__s1);
    }
    return seen;
}

Errors

errors.mxy
Result<int> port(string s) {
    long n = s.to_int()?;
    if (n < 1 || n > 65535) {
        return Err("port out of range: \(n)");
    }
    return Ok((int)n);
}
$ moxy emit errors.mxyexcerpt
typedef struct mxy_res_int mxy_res_int;
typedef struct mxy_res_long mxy_res_long;
struct mxy_res_int {
    bool ok;
    int val;
    mxy_str err;
};
struct mxy_res_long {
    bool ok;
    long val;
    mxy_str err;
};

mxy_res_int port(mxy_str s) {
    long __v1 = 0;
    mxy_res_long __r2 = mxy_str_parse_long(s, &__v1) ? (mxy_res_long){ .ok = 1, .val = __v1 } : (mxy_res_long){ .ok = 0, .err = ((mxy_str)__mxy_s1.s) };
    mxy_res_long __t3 = __r2;
    if (!__t3.ok) {
        mxy_res_int __ret4 = ((mxy_res_int){ .ok = 0, .err = __t3.err });
        return __ret4;
    }
    long n = __t3.val;
    __mxy_rl_res_long(__t3);
    if ((n < 1) || (n > 65535)) {
        char __b5_s[64];
        mxy_buf __b5 = MXY_BUF_ON(__b5_s);
        mxy_buf_put(&__b5, "port out of range: ", sizeof("port out of range: ") - 1);
        mxy_fmtv_long(&__b5, n);
        return ((mxy_res_int){ .ok = 0, .err = mxy_str_from_buf(&__b5) });
    }
    return ((mxy_res_int){ .ok = 1, .val = ((int)n) });
}

Closures

closures.mxy
fn(int) -> int scaler(int factor) {
    return (int x) => x * factor;
}
$ moxy emit closures.mxyexcerpt
struct __mxy_env0 { mxy_fn hdr; int factor; };

static void __mxy_envdrop0(mxy_fn *f) {
    struct __mxy_env0 *e = (struct __mxy_env0 *)f;
    (void)e;
}

static mxy_fn *__mxy_mk0(int factor) {
    struct __mxy_env0 *e = (struct __mxy_env0 *)mxy_valloc(sizeof *e);
    e->hdr.rc = 1;
    e->hdr.fn = (void *)__mxy_lambda0;
    e->hdr.drop = __mxy_envdrop0;
    e->hdr.share = NULL;
    e->hdr.keep = NULL;
    e->factor = factor;
    return &e->hdr;
}

mxy_fn *scaler(int factor) {
    return __mxy_mk0(factor);
}

static int __mxy_lambda0(mxy_fn *__self, int x) {
    (void)__self;
    return MXY_MUL(x, ((struct __mxy_env0 *)__self)->factor, "closures.mxy:2:25");
}

Gates

gates.mxy
string first_word(string text) {
    gate {
        string[] words = text.split(" ");  // every piece comes from the gate's arena
        return words[0];                   // copied out; the rest is freed at the brace
    }
}
$ moxy emit gates.mxyexcerpt
mxy_str first_word(mxy_str text) {
    {
        mxy_gate __g1;
        mxy_gate_open(&__g1, "gates.mxy:2:5");
        mxy_list *words = mxy_str_split(text, ((mxy_str)__mxy_s1.s));
        mxy_str __ret1 = mxy_str_keep(mxy_str_retain((*mxy_list_at__str(words, 0, "gates.mxy:4:21"))), __g1.prev, "gates.mxy:4:9");
        mxy_list_release__str(words);
        mxy_gate_close(&__g1);
        return __ret1;
    }
}

Every feature, with the C each one becomes: the language reference. Learning from zero: the tutorial.

Move a C project over one file at a time

  1. Pick a leaf file and rename it: words.c becomes words.mxy. Keep its header; the rest of the project still compiles against it.

  2. Teach the build to run moxy emit words.mxy -o words.c. The guide has Make, CMake and Meson recipes.

  3. Run moxy fix. It previews the mechanical rewrites as a diff: goto cleanup to defer, realloc-grown arrays to lists, char buffers to strings, printf to print. --write applies them.

  4. Rewrite the rest by hand where it pays, then pick the next file. You can stop after any of them.

Adding Moxy to an existing C project

$ moxy fix combined.mxytests/fix
--- a/combined.mxy
+++ b/combined.mxy
@@ -5,44 +5,38 @@
 /* parse comma-separated numbers: goto cleanup, a growable array and printf together */
 static int parse_numbers(const char *text, long *out_total) {
     int rc = -1;
-    int *nums = NULL;
-    int count = 0, cap = 0;
+    int[] nums = [];
     char *copy = malloc(strlen(text) + 1);
-    if (!copy) goto cleanup;
+    defer {
+        free(copy);
+    }
+    if (!copy) return rc;
     strcpy(copy, text);
     for (char *tok = strtok(copy, ","); tok; tok = strtok(NULL, ",")) {
         int v = atoi(tok);
         if (v < 0) {
-            printf("negative value %d\n", v);
-            goto cleanup;
+            print("negative value \(v)");
+            return rc;
         }
-        if (count == cap) {
-            cap = cap ? cap * 2 : 4;
-            nums = realloc(nums, cap * sizeof *nums);
-        }
-        nums[count++] = v;
+        nums.push(v);
     }
     long total = 0;
-    for (int i = 0; i < count; i++) total += nums[i];
-    printf("%d numbers\n", count);
+    for (int i = 0; i < nums.len; i++) total += nums[i];
+    print("\(nums.len) numbers");
     *out_total = total;
     rc = 0;
-    cleanup:
-    free(nums);
-    free(copy);
     return rc;
 }
 
 static void summary(const char *title, long total) {
-    char line[80];
-    sprintf(line, "%s: %ld", title, total);
-    strcat(line, " (done)");
-    puts(line);
+    string line = "\(title): \(total)";
+    line += " (done)";
+    print(line);
 }
 
 int main(void) {
     long total = 0;
     if (parse_numbers("4,8,15,16,23,42", &total) == 0) summary("sum", total);
-    if (parse_numbers("1,-2,3", &total) != 0) printf("rejected\n");
+    if (parse_numbers("1,-2,3", &total) != 0) print("rejected");
     return 0;
 }

7 rewrites (preview; apply with --write), 0 suggestions

The test case: cJSON

cJSON is one 3,206-line C file. Renamed to .mxy, it did not compile at first: the port forced four compiler fixes, and two of the problems were silent miscompilations of valid C that only cJSON's own test suite caught. With those fixed, all of its tests pass against the generated C. Then the parser and printer were rewritten in Moxy.

The full port write-up

cJSON ported to Moxy, from docs/port.md
cJSON core (C)Moxy port
Lines, without brace-only lines807430
Allocations, frees and goto fail710
Parse and print, 6.2 MB document1269 ms1277 ms (1.01x)
Parse alone212 ms272 ms (about 1.3x slower)

Where it was worse: moxy fix changed nothing, because cJSON's cleanup runs only on failure and defer runs on every exit. Keeping cJSON's C API on top of the port costs 1.25x the time and 1.5x the memory, and that layer is still manual C. Each emitted file embeds the runtime, so objects are 2.5x the size. Timings are from a shared, loaded machine; the page says how much is noise.

No malloc, no free, and what that costs

Strings, lists, maps, closures and ref struct objects are reference counted and freed when the last reference goes. Lists, maps and strings are values with copy-on-write; ref struct objects are shared, and weak fields break cycles (the compiler warns about types that can form one, and --cycles adds a collector). The compiler removes counting it can prove unneeded: a last use moves instead of retaining, arguments are lent to callees that don't write them, and a uniquely held object is reused in place. A gate { } block puts everything made inside it in one arena, freed in a single step at the closing brace, and copies out whatever leaves. Counts stay plain until a value crosses threads, then become atomic.

What isn't checked: raw C pointers aren't tracked, so a pointer must not outlive what it points at. goto skips cleanup (the compiler warns). Unions can't hold managed values. Memory that C code owns and frees stays manual. A value that escapes a gate in a way the compiler missed is caught only in debug builds and under moxy test --gate-stress; release builds don't check. And a program that uses a gate anywhere pays a run-time check on stores, 10 to 18% on allocation-heavy benchmarks.

Memory management, with the exact rules and a comparison with Swift, Rust and Go.

owned.mxy
ref struct Cell {
    int value;
    Cell? next;
}

Cell? reverse(Cell? head) {
    Cell? prev = null;
    Cell? cur = head;
    while (cur != null) {
        Cell? next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
    }
    return prev;
}
$ moxy emit --explain-ownership owned.mxy
owned.mxy:10:26: moves field 'next' out (it is overwritten next)
owned.mxy:11:20: moves 'prev' (last use; the variable is cleared)
owned.mxy:12:16: moves 'cur' (last use; the variable is cleared)
owned.mxy:13:15: moves 'next' (last use; its release is dropped)

Slower than C, by this much

Five programs written the same way in C, Moxy, Rust and Zig. Moxy is slower than C on all five: about 1.2x on allocation and string work, about 1.4x on tight loops over lists, where every index is bounds-checked. Memory is the bigger gap where text is split into words, because Moxy has no borrowed string view yet and every word is its own allocation.

Median of 21 runs on an Apple M1 Max, wall clock including start-up, on a machine that was not idle (load average 4.6 to 6.6 on 10 cores), so read the ratios, not the milliseconds.

All four languages, memory, and the reasons for each gap

$ bun bench/run.ts --langs moxy,c,rust,zig --runs 21time vs C

binarytrees1.17x the time of C

nbody1.37x the time of C

wordcount1.16x the time of C

jsonroundtrip1.22x the time of C

listchurn1.41x the time of C

The hairline is C (1.0x). moxy --release, cc -O2, 2026-12-02. Peak memory vs C: binarytrees 1.70x, nbody 1.02x, wordcount 4.60x, jsonroundtrip 1.83x, listchurn 1.11x.

Install

Release 0.4.0
# macOS and Linux: the release binary
curl -fsSL https://github.com/moxylang/moxy/releases/latest/download/install.sh \
  | sh

# Homebrew
brew tap moxylang/moxy https://github.com/moxylang/moxy
brew install moxy
From source (main)
git clone --recursive https://github.com/moxylang/moxy.git
cd moxy
make           # needs only cc and make
make test
make install   # or PREFIX=~/.local
Then
moxy run hello.mxy    # build and run
moxy hello.mxy        # print the C
moxy new app          # a project
cd app && moxy test

Gates, generics, methods, interfaces, async functions, actors and moxy fix are all in 0.4.0. Debian, Fedora and Arch packages are attached to each release, and the README also covers asdf and Windows.