MoxyMoxy
Docs contents

Moxy

Moxy is C with the conveniences you reach for every day: real strings, growable lists, hash maps, tagged enums with match, Result errors, closures, futures, namespaces, and automatic memory management. It compiles to plain, readable C11, and ordinary C code works unchanged inside a .mxy file. A few compiler extensions don't parse; Working with C lists them.

#include "std/io.mxy"

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,
    }
}

void main(string[] args) {
    Shape[] shapes = [Shape::Circle(1.0), Shape::Rect(2.0, 3.0)];
    double total = 0;
    for s in shapes { total += area(s); }
    print("total area: \(total)");

    map[string, int] counts = {};
    for word in "the cat and the hat".split(" ") {
        counts[word] = counts.get_or(word, 0) + 1;
    }
    print(counts);   // {"the": 2, "cat": 1, "and": 1, "hat": 1}

    match read_file("config.txt") {
        Ok(text) => print(text.lines().len, "lines"),
        Err(e) => print("no config:", e),
    }
}

No malloc, no free, no leaks: strings, lists, maps and closures are reference counted and freed the moment the last user is done with them. See Memory management.

Why Moxy

C is fast, portable and everywhere, but daily work in it means hand-rolled dynamic arrays, printf format strings, manual tagged unions, and tracking every allocation. Moxy keeps C's types, control flow and mental model, and removes that busywork:

You write Instead 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) } + match a tag enum, a union, and a switch
Result<int> parse(string s) out-parameters and error codes
(int x) => x + k a function plus a context struct
async / Future<T> / await callbacks, event loops, pthread boilerplate
actor Cache { ... } a mutex around every shared field
parallel for, xs.par_map(f), spawn { } a thread pool, work splitting and joins
defer fclose(f); goto cleanup

The generated C is clean enough to read and debug, and moxy emit file.mxy shows it.

Install

# macOS / Linux
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

# asdf
asdf plugin add moxy https://github.com/moxylang/moxy.git
asdf install moxy latest

Debian, Fedora and Arch packages are attached to each release.

From source

You need a C compiler and make. The compiler is written in Moxy; make bootstraps it from bootstrap/moxy.c, the C it generates for itself, so no existing moxy is required. goose, the build and package engine, is a submodule that compiles straight into the moxy binary. moxy is the only executable you need.

git clone --recursive https://github.com/moxylang/moxy.git
cd moxy
git submodule update --init libs/goose   # needed if you cloned without --recursive
make            # builds build/moxy
make test       # runs the test suite
make verify     # checks that build/moxy rebuilds itself identically
make bench      # benchmarks against C (see bench/README.md)
make install    # installs to /usr/local/bin (PREFIX=... to change)
make windows    # cross-builds build/windows/moxy.exe with MinGW-w64

On Windows, build under MSYS2 (UCRT64 or MINGW64 with gcc and make) the same way: make CC=gcc HOSTCC=gcc. Until bootstrap/moxy.c is regenerated from a Windows-aware compiler, add SEED=moxy.c with the build/moxy.c of a build on Linux or macOS.

Quick start

moxy run hello.mxy              # compile and run one file
moxy build hello.mxy -o hello   # build a binary
moxy build --target x86_64-windows-gnu hello.mxy   # cross-compile with zig cc (hello.exe)
moxy hello.mxy                  # print the generated C
moxy check src                  # type-check without building

Projects:

moxy new app && cd app          # src/main.mxy, tests/, moxy.yaml
moxy run                        # build and run
moxy test                       # tests/, test blocks and doc examples
moxy build --release
moxy install --prefix ~/.local

A tour

Values and printing

int age = 30;
double height = 1.82;
string name = "moxy";
bool ok = true;
auto tags = ["fast", "small"];      // inferred: string[]

print(name, age, height, ok, tags); // moxy 30 1.82 true ["fast", "small"]
print("\(name) is \(age)");         // interpolation

Strings

string s = "  Hello, World  ".trim();
print(s.len, s.upper(), s.contains("World"), s.find(","));
string[] parts = "a,b,c".split(",");
string joined = parts.join(" | ");
if (s == "Hello, World") { ... }    // compares contents
Result<long> n = "42".to_int();

Lists and maps

int[] xs = [5, 3, 8];
xs.push(1);
xs.sort();
int[] evens = xs.filter((int x) => x % 2 == 0);
string[] labels = xs.map((int x) => "#\(x)");

map[string, int] stock = {"apples": 3};
stock["pears"] = 7;
for item, qty in stock { print(item, qty); }

Lists and maps are values: int[] b = a; gives b its own copy, made lazily the first time either side changes.

Structs, enums and match

struct Point { int x; int y; }

enum Event {
    Click(Point at),
    Key(char code),
    Quit
}

void handle(Event e) {
    match e {
        Event::Click(p) => print("click at", p.x, p.y),
        Event::Key(c) => print("key", c),
        Event::Quit => print("bye"),
    }
}

match must cover every variant, or include _ =>, or the compiler reports which variant is missing.

Errors

Result<Config> load(string path) {
    Result<string> text = read_file(path);
    if (text.is_err()) { return Err("cannot load \(path): \(text.error())"); }
    return Ok(parse(text.unwrap()));
}

Closures

fn(int) -> int scaler(int factor) {
    return (int x) => x * factor;
}

fn(int) -> int triple = scaler(3);
print(triple(5));   // 15

Shared objects

ref struct Node {
    string name;
    Node[] children;
    weak Node parent;
}

Node root = Node{ .name = "root" };
Node leaf = Node{ .name = "leaf", .parent = root };
root.children.push(leaf);

ref struct objects are shared and freed when the last reference goes. weak references break cycles; --cycles (or cycles: true under build: in moxy.yaml) adds a collector for the cycles you'd rather not break by hand (docs/book/memory.md).

Cleanup and concurrency

FILE *f = fopen(path, "r");
defer fclose(f);              // runs however the scope exits

async string fetch(Page p) { ... }   // waits on this thread; shares p freely
string[] pages = await all([fetch(home), fetch(about)]);

actor Counter {                      // state served one message at a time
    long n;
    void add(long k) { self.n += k; } // c.add(1) returns at once
    long get() { return self.n; }     // await c.get()
}

parallel for i in 0..n { out[i] = work(i); }   // every core, results by index
long[] squares = xs.par_map((long x) => x * x);
Future<long> total = spawn { return sum(squares); };
print(await total);

A panic inside an actor's message fails that message (its caller's await gets it) and the actor keeps serving.

Modules

#include "geometry.mxy"       // each file is included once
#include "std/io.mxy"         // standard library
#include <sqlite3.h>          // any C header

namespace geo {
    double dist(Point a, Point b) { ... }
}
geo::dist(p, q);

Projects and packages

A project is a directory with a moxy.yaml:

project:
  name: "app"
  version: "0.1.0"
  type: "bin"                 # or "lib"

build:
  cc: "clang"                 # optional; default cc, or zig cc for a target
  target: "x86_64-linux-musl" # optional; cross-compile (see the reference)
  cflags: "-Wall"
  ldflags: "-lsqlite3"
  includes:
    - "src"
  sources:
    - "src/native.c"          # extra native sources (.c, or .m with an Objective-C compiler)

dependencies:
  geom:
    path: "../geom"
  http:
    git: "https://github.com/user/http.mxy"
    version: "v1.2.0"
Command What it does
moxy add <git-url> [--name n] [--version v] fetch a dependency into packages/, pinned in moxy.lock
moxy add <name> [--version tag] the same, resolving the name through the package index
moxy search [words] search the package index by name, description and keywords
moxy publish [--index-dir dir] check the project and write its index entry (you open the pull request)
moxy remove <name>, moxy update remove or refresh dependencies
moxy build [--release] [--cycles] [--target t] build src/main.mxy (bin) or src/lib.mxy (lib)
moxy run [--release] [--cycles] [-- args] build and run
moxy test [--cycles] [--target t] [--filter text] run tests/, the test blocks and doc examples in src/ (only built, not run, for a target this machine can't run)
moxy clean [--cache] [--dry-run] remove build/; --cache also empties ~/.cache/moxy; --dry-run shows what would go and its size
moxy install [--prefix dir], moxy task <name> housekeeping

A dependency's .mxy files can be included by name (#include "lib.mxy"). Libraries build to build/<mode>/lib<name>.a, along with a C header (<name>.h) so plain C programs can call them too.

Package index. The index is a git repository of JSON entries (packages/<name>.json) pointing at each package's own repository and tags; see docs/design/packages.md. Set another one with MOXY_INDEX or index: under build: in moxy.yaml. The default, github.com/moxylang/index, has not been created yet, so for now moxy search and moxy add <name> need MOXY_INDEX to point at an index you host.

Disk use. Every cache Moxy keeps is capped: 8 precompiled runtimes (about 2 MB each) in ~/.cache/moxy, 256 MB of cached test binaries per project, and temporary directories removed even when a command fails or is interrupted. See Disk use.

Workspaces. A root moxy.yaml with workspace: members: [...] builds every member in dependency order. moxy build -p member builds one member.

Testing

moxy test runs every .mxy file under tests/ (and any *.test.mxy file) that has a main, then test blocks and doc examples:

Next to name.mxy Meaning
nothing the test passes if it exits 0 (use assert)
name.out standard output must match exactly
name.code expected exit code (for example 101 for a panic)
name.err compilation must fail with each listed message
name.stderr standard error must contain each listed line (with name.code, checks a failed assert or a panic)
name.fix moxy fix must print exactly this diff and these suggestions, and the fixed program must pass the same checks

Tests can also live next to the code. A test "name" { ... } block at file scope runs in moxy test, in its own process, and sees the file's static functions; moxy build and run leave it out. A ```moxy fence in a /// doc comment is an example that moxy doc shows and moxy test compiles and runs (```moxy norun only compiles it):

/// ```moxy
/// assert(clamp(5, 0, 3) == 3);
/// ```
int clamp(int x, int lo, int hi) { return x < lo ? lo : x > hi ? hi : x; }

test "below the range" {
    assert(clamp(-1, 0, 3) == 0);
}

moxy test --filter text runs the tests whose name contains text. See Testing.

moxy test --sanitize runs the tests under AddressSanitizer and UndefinedBehaviorSanitizer. On Linux it also runs LeakSanitizer. moxy test --cycles builds them with the cycle collector.

Tooling

Command
moxy fmt [paths] [--check] format source (configure with moxyfmt.yaml)
moxy lint [paths] unused variables, shadowing, empty blocks
moxy fix [--write] [paths] modernize C (goto cleanup, realloc arrays, char buffers, printf); previews a diff, applies with --write
moxy check [--types] [paths] type-check only; --types also prints the inferred type of each auto local, for editors
moxy emit file.mxy [-o out.c] the generated C
moxy doc [paths] [-o dir] [--format html|md] API docs from /// comments
moxy explain <code> | --list what an error code means, with an example and the fix

Errors look like this, and C compiler errors in generated code point back to your .mxy lines:

error[E0805]: match is not exhaustive; missing Color::Blue
  --> src/main.mxy:4:5
   |
 4 |     match c {
   |     ^^^^^
  = help: add the missing arms or a '_ =>' arm

Editor support

Language server. tools/moxylsp speaks LSP over stdio and uses the compiler for everything that needs types. It provides:

  • diagnostics (errors and warnings with their codes, notes as related information, and the compiler's help: line)
  • hover, completion and document symbols
  • go to definition, find references and rename (scope-aware for locals, parameters and match bindings; across #included .mxy files and open documents)
  • format document, using moxy fmt
  • inlay type hints for auto declarations (from moxy check --types)
  • quick fixes for the mechanical help: suggestions: add a missing ;, close an unclosed (/[/{, fix a misspelled name, wrap a value in string(...)

Build it with the moxy you're using and put it on your PATH; MOXY_PATH tells it which compiler to run:

make -C tools/moxylsp MOXY=moxy        # or MOXY=../../build/moxy from a source checkout
cp tools/moxylsp/moxylsp ~/.local/bin/
make -C tools/moxylsp test             # drives the server over stdio with JSON-RPC (needs bun)

VS Code. tools/editors/vscode is an extension with a TextMate grammar (C plus Moxy keywords and \(...) interpolation), language configuration and a client for moxylsp. Package it with bun install && bun run package and install the .vsix; see its README.

Neovim. tools/editors/nvim is a plugin with filetype detection, a Vim syntax file (no Tree-sitter needed) and moxylsp setup for the built-in LSP client or nvim-lspconfig; see its README.

Zed. Copy the extension into Zed's extensions directory. It uses moxylsp from your PATH:

cp -r tools/editors/zed ~/.config/zed/extensions/moxy

Other editors can use any C syntax mode for .mxy files and connect to moxylsp over stdio.

Debuggers. Programs are built with #line directives, so breakpoints and stepping work in .mxy files. tools/debug adds formatters that show strings, lists, maps, Result values, enums and ref struct objects the way print would:

lldb -o 'command script import tools/debug/moxylldb.py' ./prog     # or add the import to ~/.lldbinit
gdb -ex 'source tools/debug/moxygdb.py' ./prog                      # or add it to ~/.gdbinit
(mxy_list *) shapes = 0x600003 len=2 [Shape::Rect(1, 2), Shape::Dot]
(mxy_map *) m = 0x600005 len=2 {"a": 1, "b": 2}
(mxy_res_int) e = Err("odd")
(Person *) ann = 0x6000a0 Person(strong=2, weak=2) {name: "ann", buddy: null, kids: len=1 [Person@0x6000e0]}

See tools/debug/README.md.

Playground

playground/ is a browser page that compiles Moxy to C as you type. The compiler's source-to-C pipeline (everything but the CLI and goose) is built to wasm32-wasi with zig cc and run by a small WASI host written in TypeScript. It shows the generated C and the compiler's diagnostics; it does not run programs yet, since that would need a C compiler in the browser.

make playground          # needs zig and bun; writes playground/dist
make playground-test     # the wasm build must emit exactly what build/moxy emits

Serve playground/dist with any static file server.

Documentation

Tutorial learn Moxy step by step
Adopting Moxy in a C project add Moxy to a Make or CMake build, one file at a time
Porting cJSON a real C library moved to Moxy: what compiled unchanged, line counts, removed cleanup code, speed and memory, and where Moxy was worse
Language reference every feature in detail
Memory management the ownership model, and how it compares to Swift, Rust, Go and others
Architecture how the compiler works
Errors diagnostics and what they mean
Grammar formal syntax
Compiler internals source layout for contributors
Changes what changed between releases
Stability and 1.0 what the compatibility promise will cover
Contributing build, test, and send a change; starter tasks

License

MIT

Edit this page on GitHub