Compiling and Running

Monad compiles to native binaries through LLVM. The compiler is written in Monad, lives in lang/, and compiles itself.

To run a program you compile it and execute the binary — monad run does both in one step. There is also monad eval, a built-in interpreter, but only eight pure natives are wired into it, so it is a tool for arithmetic-and-strings programs rather than a way to run real ones.

Getting a Compiler

The compiler is written in the language it compiles, so the first one has to come from somewhere else. That is what the Rust bootstrap host is for:

cargo build --manifest-path rust/Cargo.toml --release
cargo run --manifest-path rust/Cargo.toml --release -- run cli/src/main.mo build cli/src/main.mo -o "$PWD/monad"

That produces monad, a native binary that needs nothing else. Everything below uses it.

The compiler is also expected to build with the last published nightly: CI's scripts/ci-self-compile.sh compiles cli/src/main.mo with it before running the built binary's own check. New language or native support therefore lands in two steps — support first, use in the compiler's own sources after a nightly containing it exists. AGENTS.md's "Bootstrap compatibility" section has the rule.

The absolute -o is not decoration. A relative output name is resolved against the compiler's default output directory, /tmp/monad_out_<pid> — see Where the binary lands.

You will also need llc, clang, and the Boehm GC development files on the system — devenv shell provides all three.

Or install a nightly

Every push to main publishes a prerelease, and monadup installs one:

curl -fsSL https://monad-lang.org/install | bash
export PATH="$HOME/.monad/bin:$PATH"
monadup default       # install the latest nightly and make it active
monadup doctor        # check the compiler and the LLVM/GC build prerequisites
monad version

monadup list / use <tag> / update / uninstall <tag> manage the installed set under ~/.monad. monadup env prints the resolved environment, monadup doctor --json is a machine-readable report, and monadup new <name> scaffolds a project. The bootstrap stub needs curl and either jq or python3; the installed binary parses JSON itself and needs only curl and tar. When a release publishes a <asset>.sha256 beside an artifact, both the stub and the binary verify it with sha256sum or shasum.

The ELF is portable; the build toolchain is not bundled. Linux binaries are fully static and the macOS one links only libSystem, so monad, monadup, version and check run on a plain machine. monad build / run / test still invoke llc, clang, pkg-config and Boehm GC from PATH — monadup doctor checks all of them and tells you what to install.

An install directory holds more than the compiler:

~/.monad/downloads/<tag>/
  monad-nightly-<platform>     the compiler
  commit.txt                   the commit it was built from
  init/  std/  llvm/  runtime/ the mote sources
  mote.toml                    those four, as a workspace

Those motes are what let you use the compiler on a program of your own — use std::map and the C runtime both resolve out of that directory. Without them, only a checkout of the compiler repository can compile anything. Nightlies published before the sources asset existed install the binary alone and say so; re-running monadup install adds the sources once a release ships them.

MONAD_ROOT points the compiler at a different set of sources, for a root that is not a monadup install (an unpacked copy, or a checkout):

MONAD_ROOT=/path/to/tree-with-init-std-runtime monad check

Three artifacts, per platform: monad-nightly-<platform> (the compiler), monadup-<platform> (the toolchain manager), and monad-src-<platform>.tar.gz (the sources above). x86_64-linux and aarch64-darwin are built and verified on the platform they are for; aarch64-linux and riscv64-linux are cross-built from x86_64-linux and verified under QEMU, and riscv64 is experimental. monadup reads the machine with uname -sm and installs that pair, falling back to x86_64-linux on a platform no release has published — which is every tag older than the platform.

Your First Program

open IO {println}

def main (args : List String) : IO Unit := println "Hello, World!"
monad run hello.mo
Hello, World!

Or compile it and keep the binary — with an absolute output path, for the reason just above:

monad build hello.mo -o "$PWD/hello"
./hello

The Commands

The full surface — every command, flag and exit code — is the Command-line Reference; monad <command> --help prints each command's own options. The verbs a build touches:

WebAssembly

Two profiles ride the same LLVM backend:

Profile Triple Runtime Host
wasi wasm32-unknown-wasip1 wasi-libc, wasm32-unknown-wasip1 wasmtime, Node
web wasm32-unknown-unknown freestanding, JS imports (monad module) WebAssembly.instantiate
monad build --target wasm32-unknown-wasip1 fixtures/wasm/fib.mo -o fib.wasm
wasmtime fib.wasm

monad build --target wasm32-unknown-unknown fixtures/wasm/hello.mo -o hello.wasm
node wasm/web/smoke/smoke.mjs hello.wasm

The web profile is freestanding: it links -nostdlib, has no sysroot and needs no wasi-sdk, so WASI_SDK_PATH is not required. The C compiler is MONAD_WEB_CC if set, else $WASI_SDK_PATH/bin/clang when that is set, else the host clang (plus wasm-ld). A nixpkgs wrapped clang injects hardening flags the wasm target rejects; point MONAD_WEB_CC at clang-unwrapped there (the dev shell's gate does).

The wasi profile needs WASI_SDK_PATH to name a wasi-sdk installation (the directory containing bin/clang and share/wasi-sysroot); devenv.nix pins one. The output name gets .wasm when it does not already end in it.

There is no Boehm GC on wasm32. On wasi the runtime uses malloc and never frees, so one-shot programs are the supported shape. On web the runtime has its own conservative mark-sweep collector (runtime/src/gc_wasm.c). It collects when an #[export "c"] call returns to JS, so an event-driven app stays bounded; a main that never returns cannot be collected. On web, heap exhaustion calls the host's oom import (a diagnostic) and traps, and web_wasm::Memory exposes the committed/used sizes.

A reachable native the target cannot serve is a compile error naming the native and the target, not a link failure or a trap. The wasm profiles omit OS threads/processes/sockets/files (fork_io, exec_cmd, tcp_*, file_exists, get_env, stream_open -- so IO.read_file/write_file too, ...); the web profile additionally omits C-library float formatting (f64_to_string, f64_of_string). Console I/O (IO.println, IO.write_stdout, IO.read_line) and std_fd/stream_read/stream_write are available on both.

Running monad with no arguments prints the usage screen and exits 2.

Flags are position-independent — monad build -v hello.mo and monad build hello.mo -v are the same command. A long option takes its value either as a separate argument (--output NAME) or joined with = (--output=NAME); a valueless flag rejects the = form.

monad test with no paths covers the mote containing the working directory, so it enumerates that mote's sources; --workspace covers every member. Pass explicit paths for anything else. With no paths and no mote above the working directory it says so and exits 1, exactly as check does — there is nothing to test, and reporting a pass for it would read as one. Resolution keys off the mote doing the use, so an invocation from inside a mote finds its own init/std dependencies — there is no need to run it from the workspace root.

monad test reads each driver's failure count from a result file the driver itself writes, not from its exit code, so a file's test count is no longer capped at 255. Every file in the corpus runs self-hosted; CI's sweep carries no exclusion list.

monad eval and monad repl are not general interpreters. Their shared native table covers the pure integer and string primitives (arithmetic, comparison, conversion, and the String operations); IO, files, processes, environment access and concurrency are not wired, so a program that reaches them stops with unknown native. eval evaluates the file's main and prints Eval result <value>; use monad run for a real program.

The REPL

monad repl is an interactive loop over the same evaluator (eval::run, shared with monad eval and the web REPL at /try). It has no line editing or history, and it does not trap interrupts: a runaway expression has to be stopped with Ctrl-C at the shell. Prompts go to stderr; results and diagnostics go to stdout (the CLI's convention), so a scripted session can pipe stdin and diff stdout.

$ monad repl
Monad (self-hosted) -- type :help for commands
>> 2 + 3
5 : I64
>> def twice (n : I64) : I64 := n + n
ok
>> twice 21
42 : I64
>> use init::foldable {}
ok
>> :type twice
twice : (I64 -> I64)
>> :quit

Expressions are evaluated against the declarations entered so far and are never kept; def/type/struct/class/instance/use/open inputs join the session only after they check cleanly, and a rejected definition leaves every earlier one intact. use is an ordinary declaration, resolved through the standard filesystem loader (so use init::list, a std module, or a mote in the workspace all work as they do under monad check). :help lists the commands, :reset forgets every definition, and :type <expr> prints an expression's type without evaluating it. A def whose body starts on the next line continues on the .. prompt.

Where the binary lands

build resolves the output name against the target directory: the nearest [build] target-dir in a .monad/config.toml above the source, else plain target/. MONAD_TARGET_DIR overrides that, and --target-dir overrides both. The setting lives in the tool's config rather than in a mote's mote.toml: where output goes is not a property of the thing being built, and a script-mode file in no mote at all still needs an answer. This repository holds two toolchains, so it names their output apart: cargo's is rust/target/ and monad's is target-monad/ — they must not eat each other, because a cargo clean must not delete a monad binary.

Debug info is on by default, so a plain build is a debug build:

monad build hello.mo -o hello            # -> target-monad/debug/hello
monad build hello.mo -o hello --release  # -> target-monad/release/hello
monad build hello.mo -o "$PWD/hello"     # -> ./hello

An absolute output name replaces the directory outright; a relative one — including one with slashes in it — is placed inside it, because -o is a NAME, not a path. A relative name that looks like a path is nested rather than rejected:

monad build hello.mo -o sub/hello        # -> target-monad/debug/sub/hello

This surprises everyone once. When you want the binary somewhere specific, say so with an absolute path.

monad run is the exception: it compiles to /tmp/monad_out_<pid>, the pid being there so parallel invocations cannot collide.

The build cache

Artifacts are input-addressed. build hashes the source file's own bytes, its mote's whole declared closure, the compiler binary itself, the profile and the target triple, and if the store already holds a binary under that hash it copies it out instead of compiling — so rebuilding an unchanged tree is a file copy, not a build, and cached: <dest> (<hash>) is what a hit prints.

The file's bytes are in the key because the closure alone does not name the file. A .mo with no mote.toml above it roots at the directory it sits in, so one.mo and two.mo side by side share a root and a closure digest — keyed on that alone they shared an entry, and building two.mo after one.mo printed cached: and handed back one's binary. The directory is still hashed as well, since a file's siblings are reachable from it and its #![mote {…}] dependency list is a property of the file, not of the tree above it.

The key is the whole name: nothing you type with -o is part of it. Keeping that true took a fix upstream of the cache. The intermediate .ll used to be named after -o, and llc records its input file's name in the object it emits, so two builds of one unchanged source under two output names differed by a byte. The IR is now named by the cache key and kept in the store (<target-dir>/store/<hash>.ll), which makes the artifact a function of the key alone; the .ll your -o implies is still written beside the binary as a convenience copy, for anyone reading the IR by hand. A cache hit writes it too — from the copy in the store, and only when the bytes there differ — so a build leaves the same two files behind whether or not it had to compile.

check caches the same way, one entry per file, under <target-dir>/check/<hash>: a corpus check that takes minutes cold takes about a second warm, and a hit replays the recorded output byte for byte.

Two properties are worth knowing before you trust it. The key covers the compiler as well, so editing the compiler invalidates everything it built — and where an input cannot be determined the cache turns itself off rather than answering from a weaker key, because a stale binary is worse than a slow build. On Darwin that is every build: one of the key's inputs is the running compiler's own bytes, read from /proc/<pid>/exe, and a platform with no procfs has no such input at all. monad store and monad gc are inert there for the same reason. And the key is coarse by direction, not by accident: it covers the file's entire declared closure, so a one-line edit can re-check more files than it changed. Anything that needs the real work to happen — a gate that inspects the emitted IR, say — says so with one of two switches, which mean the same thing: nothing is read, and nothing is written.

monad build hello.mo --no-cache
MONAD_NO_CACHE=1 monad check init std

--verbose on check turns the cache off too: its trace is a record of what the checker did, and a replayed entry has no trace to show.

Debug info and --release

DWARF debug info is emitted by default, with a distinct source location per term. --release turns it off; an explicit --debug/-g turns it back on and wins over --release in either order.

The cost of debug info is real: every module is re-parsed with source positions before codegen. Pass --release for a build you are not going to debug — the nightly and the CI bootstrap both do.

--verbose

--verbose/-v is accepted by every command that does work. It prints each module as it loads (before loading it, so a hang names the culprit), one line per pipeline stage, and the elapsed time for each:

  loading module: lang.parser
-> stage: load + elaborate modules
   load + elaborate modules 1843ms
-> stage: typecheck target

Success and failure lines print with or without it. Colour comes from std.ansi, which honours NO_COLOR (always off), then FORCE_COLOR (on), then TERM=dumb (off). There is no tty check, so piped output is coloured unless you set NO_COLOR=1.

monad version

Prints the git commit the binary was built from. The hash is baked in at link time by the compiler that built it, read from the working directory it was invoked in — build outside a git checkout and you get unknown.

main and Exit Codes

main may return IO Unit, or I64 — in which case it becomes the process exit code:

def main : I64 := 42
monad build main.mo -o "$PWD/main" && ./main; echo $?   # 42

It may also take the command line, which the C runtime builds from argc/argv:

def main (args : List String) : I64 := 0

What the Pipeline Does

  1. Parse and type-check the source — the same front end as check
  2. Lower to the codegen IR and emit LLVM IR
  3. Run llc to produce an object file
  4. Link with clang, against the C runtime and -lgc

Bootstrapping

Once you have a monad binary, it can build its own successor:

monad build cli/src/main.mo -o "$PWD/monad-next" --release
./monad-next check cli/src/main.mo

CI runs exactly this on every push, and the second step is the one with teeth: compile succeeding only says llc and clang were happy with the emitted IR. Making the result type-check the compiler's own source — the largest input in the tree — exercises the whole front end.

The bootstrap has reached a fixpoint: the compiler compiles itself, that binary compiles itself again, and the output is identical.

Memory

Compiled binaries use the Boehm conservative garbage collector, and this is explicitly a stopgap. Memory Model describes the intended Owned/Region/Static model, what Copy and Shared mean for lifetimes, and which parts are implemented today.

Every heap object carries a header with a refcount, and monad_retain / monad_release exist — but codegen never emits calls to them, so before the GC was added nothing was ever freed. Measured on check cli/src/main.mo, that meant 5.99 GiB allocated of which 98.24% was garbage, and compiling cli/src/main.mo was OOM-killed at 29.7 GB.

So monad_alloc calls GC_malloc, string buffers go through GC_malloc_atomic (so the collector does not scan text bytes and mistake them for pointers), and monad_release deliberately does not free — that would corrupt the Boehm heap. The refcount field is currently vestigial.

The intended replacement is for the compiler to track ownership through the affine usage rule the language is designed around, at which point the allocator gets real frees and the GC dependency goes away. The first step of that is available now: a MONAD_OWNERSHIP=1 build routes monomorphic, non-Copy constructors through calloc and frees them with generated drop_<T> glue at definition exits (unused binders only). Everything else stays region-owned and leaks; the mode refuses any mote still in [affine] mode = "warn". See plans/bootstrapping/ownership-regions-memory.md.

Fail-Fast Gates

Before emitting anything, the backend runs four validation passes over the reachable declarations. Each exists because the silent miscompile it catches actually shipped once:

Gate Catches
unwired natives a bodyless #[native X] where X is wired nowhere — would compile to a "return Unit" stub and SIGSEGV at run time
undesugared struct literals a struct literal elaboration never desugared — it used to compile to a void placeholder; today codegen aborts in a deliberately named function instead
symbol collisions two definitions sharing an LLVM symbol — one is silently dropped and its callers re-pointed at the other
undefined symbols a call to a symbol nothing defines — otherwise surfaces as llc: undefined value at the end of a 15–25 minute self-compile, naming one symbol and no call site

All four run only on reachable declarations, so a problem in dead code cannot block a build that never touches it.

The undefined symbols gate is a backstop, and one case used to reach it that should never have: a class-method call naming a method its class does not declare (Map.get — class Map declares empty/insert/lookup/delete). The resolver rewrites a class-method reference to a mangled name built from the class's declared method list, so such a call produced a name nothing emits and landed here as call to undefined symbol(s): std.map::Map_BTreeMap_get — a symbol and no call site. The gate's own reasoning assumes a successful resolution implies the definition exists; class_method_ref (lang/src/scope.mo) now requires the qualifier's class to declare the method, so that assumption holds and the call is rejected during typecheck instead, naming the reference exactly as written (unknown variable 'Map.get').

Native Coverage

There are 171 natives declared across init/ and std/. The backend wires I64 arithmetic and comparison, string operations, the file and directory natives, get_env, current_time, process_id, exec_cmd, the five tcp_* socket natives (tcp_connect_timeout is the connect primitive; blocking tcp_connect is composed from it in std/io.mo), std.stream's byte streams (including stream_poll and stream_set_timeout), and std.bytebuf's ByteBuf.

Not wired: the entire concurrency surface — see Concurrency. A program that reaches one of those fails to compile with a clear message rather than producing a broken binary.

The tcp_* natives are wired here and nowhere else. The Rust bootstrap host has no TCP implementation, so a socket test cannot run under cargo run -- test; motes/moon and motes/moose are exercised by the self-hosted runner.

One native is declared but unimplemented in both implementations -- eq_rec -- and fails at run time with unknown native.

A few natives are not written in C at all: runtime/src/natives.mo emits LLVM IR directly for thirteen simple operations.

Known Rough Edges

See the Maturity Matrix.