Cherimoya is a compiled systems language for the gap between C++ and Rust, built around progressive disclosure of safety. Plain code is as easy to write as C. Stronger guarantees, like ownership tracking, refinement contracts, verified arithmetic, and exhaustive matching, layer on top without changing the base language, and you choose how much of them you want per function, module, or project.
cheri is its compiler. It's written in C++17 and generates code through LLVM.
# counts the steps the Collatz sequence takes to reach 1
let (n :: int {n > 0}) -> steps -> (count :: int) {
let x :: mut <- n;
let taken :: mut <- 0;
repeat (x != 1) {
x <- match (x % 2) {
0 -> { x / 2 -| }
_ -> { 3 * x + 1 -| }
};
taken +<- 1;
}
taken -|
}
let () -> start -> (code :: int) {
27 |> steps -|
}
$ cheri run collatz.moya; echo $?
111
The syntax follows the way data moves:
<-flows values backward into whatever receives them: bindings, assignments, construction, a named argument,f(b <- 2), and an input's default,(b :: int <- 1).->flows definitions forward: from a function's inputs to its name to its outputs, and from a match pattern to its arm.-|yields a value out of a scope or a function, where a scope is a block, amatchor one of its arms, a loop, or achunk. There's noreturn,break, orcontinue. A bare-|leaves the innermost scope, and-| nameleaves the scope or function with that name, so every early exit is visible.|>and<|pipe a value into a function, or into a call that gives the rest of the arguments:x |> clamp(hi <- 10)isclamp(x, hi <- 10).
Brackets have fixed jobs: { } makes scopes, [ ] packs data together, and ( ) is for calls, math, and conditions. There's no if: every conditional is a match, with a subject or with guards.
let (n :: int) -> clamp -> (r :: int) {
match { (n > 100) -> { 100 -| clamp } }
match { (n < 0) -> { 0 -| clamp } }
n -|
}
Bindings are immutable unless they're declared mut, a value can't be silently dropped (_ <- f(x); discards one on purpose), and comments start with #. The book teaches the language from the start, the reference defines it, and design/ explains how the compiler implements it, commit by commit.
Cherimoya is early. What works today:
-
The whole front end: the lexer, the parser for the whole grammar, and diagnostics that say what was expected, what the language does instead, or which rule was broken and how to fix it.
-
Name resolution and type checking: functions (nested, and in any order), bindings, operators, calls and pipes with named arguments and defaults, blocks,
match, loops, yields and their labels, mutability, discards, and the entry point,start, which a program defines the way C's runtime callsmain. -
Characters:
char, one ASCII character, andrune, one Unicode scalar value, with escapes like'\n','\x41', and'\u{1F600}', comparisons,match, and conversions to and from integers, plus annotations,(5 :: i8), which give a value a type without converting it. -
Fixed arrays:
arr[N, T], held inline, written as[1, 2, 3], with sizes known when the program compiles, from a literal or a constant likelet N <- 4;, indexing by unsigned integers that traps past the end,xs.len(), the method arrays have asSized, which a pipe reaches asxs |> .lenor.len <| xs,=and==on whole arrays, andmuton the elements,arr[N, mut T], or in front, to replace the whole array. -
Arrays on the heap and pointers:
arr[T]andptr[T], made witharr[n, mut T](),arr[n, mut T](fill),arr[n, mut T](_),arr[T](xs), andptr[T](v), where a length known when the program compiles makes a fixed array instead, indexed and dereferenced,p[], with checks at run time, and owned: each is freed exactly once at the end of its owner's scope, moving one hands it on, using one after it moved is an error, inputs borrow, anunscopedinput takes it over, and outputs move out, which the test suite checks under valgrind. -
Views and modes:
peekviews any place, a binding, an element, or a pointer's value, reading and writing through it with nothing copied, as a binding, an input, or a function's output, and nothing a live view points into can be freed or moved, checked by dataflow over each function's control-flow graph.unscopedbindings and outputs own heap memory that has to be moved on. -
Addresses:
addr x, anaddr[T], which says whether two places are the same memory and orders them, where=and==on handles compare what they hold, and an address is checked like a view, so it never outlives what it names. -
Strings of three kinds,
arr[char](ASCII),arr[i8u](UTF-8 bytes), andarr[rune], where a literal is the kind its context wants, chars widen into bytes without a cast, andarr[rune](s),arr[i8u](s), andarr[char](s)convert, trapping on what they can't hold. A fixed array is lent without copying to any input that borrows anarr[T], compared with an array of any length by=and==, and strings are matched against string patterns. -
Fuzzy booleans:
boolf, a truth value from 0 to 1 held in a byte, where&&is the minimum,||the maximum,*the product, and!xis 1 - x, with conversions to and from floats, its raw byte, andbool, and a cutoff likex > 0.5to turn one back into abool. -
The numeric model: every integer from 8 to 128 bits, signed or unsigned, trapping or wrapping, and every float from
f16tof128, including bfloat16, NaN-free or NaN-carrying, and both FP8 encodings, stored as bytes and computed in f32. Literals take the type their context wants, and conversions go between any two numbers. -
Code generation through LLVM for all of that, with optimization, native object files, cross-compilation, and linking with a small runtime. Overflow, division by zero, out-of-range shifts, a NaN made in or converted into a NaN-free float, an
f8that overflows, a conversion into a trapping integer, a character, or a boolf that doesn't hold the value, and a failedasserttrap with their line. -
Tests in
.toyafiles, run bycheri test, each in a process of its own, with tests that expect a trap and timeouts. -
Debug info with
-g: DWARF, or CodeView on Windows, for gdb and lldb, with source names, every variable and its type, and printers that gdb loads from the binary for the values C's rules would print wrong, like FP8 andrune. -
A language server,
cheri lsp, with extensions for VS Code, Emacs, and Zed, where Zed reads programs with a tree-sitter grammar that follows cheri's parser exactly: diagnostics as you type, highlighting by meaning, hover with the documentation your comments give a name, where a##documents every declaration below it up to a blank line, go to definition, references, rename, an outline, completion ranked by the type a position expects, signature help, quick fixes for the mistakes that have one, whichcheri check --fixapplies from the command line too, and inlay hints: the types cherimoya inferred, the input each argument goes to, the defaults a call leaves out, the type of each step of a pipe spread over lines, and the name of a long function at its closing brace, along with a Run test lens above every test in a.toyafile.
Not yet: printing, joining strings, packs of different types, ranges, comprehensions, and folds, for-each loops, records, sums, protocols, generics, closures and functions as values, operator overloading and the extra operators, modules, and verification with Z3.
You need:
- a C++17 compiler (the build uses clang)
- CMake 3.20 or newer, and Ninja if you have it
- LLVM 21.1 with its development files (
llvm21-develon Void,llvm-21-devon Debian and Ubuntu), withllvm-configon your path
Catch2 is downloaded during the first build.
./scripts/build.sh # configures with clang on the first run, then builds into build/
./scripts/test.sh # builds, then runs every test
./scripts/clean.sh # removes the build
The compiler ends up at build/cheri.
cheri build prog.moya # an executable named prog
cheri run prog.moya # build, run, and exit with the program's exit code
cheri check prog.moya # check without building
cheri test tests/ # run the tests in every .toya file under tests/
cheri guide S001 # explain an error by its code, or list every code
cheri lsp # the language server, which an editor starts
cheri help # every command and option
The most useful options:
| Option | What it does |
|---|---|
-o <path> |
where the output goes |
--emit exe|obj|asm|llvm|bc |
what to produce; -c, -S, and --emit-llvm are shorthands |
-O0 … -O3, -Os, -Oz |
how hard to optimize, -O3 by default |
--target <triple> |
cross-compile, like --target aarch64-linux-gnu -c |
--cpu <name>, --features <list> |
tune for a cpu, or --cpu native for this machine |
-g, -gline-tables-only |
debug info: everything, or just lines and function names, for backtraces |
--linker <program>, --static |
how to link |
-L<dir>, -l<lib>, --link-arg <arg> |
passed straight to the linker |
cheri build prog.moya --emit-llvm -O0 prints the IR exactly as the compiler wrote it, before any optimization.
Every error and warning has a code, like error[S001], and cheri guide S001 explains the rule behind it with a program that breaks it and the same program fixed. The explanations are in docs/errors/.
Tests go in .toya files, which hold functions marked @test, along with any helpers they share, and cheri test runs them: cheri test math.toya runs one file's, cheri test tests/ every .toya file's under a directory, and cheri test math.toya overflow only the tests whose names hold overflow, or with --exact, the one named exactly that.
let (n :: int) -> square -> (r :: int) { n * n -| }
@test
let () -> squares -> () {
assert (square(-3) = 9);
}
@test(traps <- "overflowed int", timeout <- 5)
let () -> overflows -> () {
_ <- square(4294967296);
}
A test passes when it finishes, and fails when it traps, which a failed assert does. A test given traps passes only by trapping with that text in the trap's message, and one given timeout fails once it runs longer than that many seconds. Each test runs in a process of its own, as many at once as there are cores, so a trap or a crash only fails its own test, and cheri test exits with 1 when anything failed:
math.toya
ok squares
ok overflows (trapped as expected)
2 passed, 0 failed
A .toya file stands alone until modules can import, so it holds the code it tests, and it has no start, since cheri test runs its tests instead. Tests build like cheri build, at -O3 unless an -O says otherwise, and with -g, a failing test can be run under a debugger. --runner runs each test binary under a command, split at its spaces, like cheri test tests/ --runner 'valgrind -q'.
cheri build prog.moya -g -O0 builds a program a debugger can see all of: every function by its source name, every binding and input with its type, a nested function as outer.inner, and an input's default as clamp.lo<-. Immutable bindings show as const, a boolf prints as its fraction, and the program starts at start, which the runtime's C main calls. -g works at any -O, where the optimizer can inline functions and leave some variables <optimized out>.
$ gdb ./prog
(gdb) break clamp
(gdb) run
Breakpoint 1, clamp (n=150, lo=0) at prog.moya:3
(gdb) info locals
fuzzy = 0.70196078431
tiny = 1.75
gdb can't decode FP8, bfloat16, or f128 on its own, prints 1-byte integers as C chars, and prints a rune as a hex escape, so a -g build carries pretty-printers for those inside it, which gdb runs once it trusts the binary's directory. Add this to ~/.gdbinit, with your own path:
add-auto-load-safe-path ~/projects
editors/vscode/ is a VS Code extension that runs cheri lsp for every .moya and .toya file, gives them a cherimoya icon, with a check on a .toya, and puts a Run test lens above every test. To build and install it:
cd editors/vscode
npm install
npm run package
code --install-extension cherimoya.vsix
Then set cherimoya.compilerPath to your build/cheri, unless cheri is on your path, and restart VS Code.
editors/emacs/cherimoya-mode.el is an Emacs mode for .moya and .toya files that starts cheri lsp with eglot, which is built into Emacs, or with lsp-mode, if it's installed. Eglot colors the code from Emacs 31 on, and lsp-mode does once lsp-semantic-tokens-enable is set, and lsp-mode shows the Run test lenses, which run the test with compile. To use it:
(add-to-list 'load-path "/path/to/cherimoya/editors/emacs")
(require 'cherimoya-mode)
(setopt cherimoya-compiler-path "/path/to/cherimoya/build/cheri") ; unless cheri is on your path
(add-hook 'cherimoya-mode-hook #'eglot-ensure) ; or #'lspeditors/zed/ is a Zed extension that runs cheri lsp for every .moya and .toya file, colors, indents, and outlines them with the tree-sitter grammar in tree-sitter/, and puts a Run test button beside every top-level test. To install it, run zed: install dev extension from the command palette and pick editors/zed, which needs Rust installed through rustup. Zed colors the code with the grammar alone until it's told to layer the server's colors on top, which is also what marks a mutable binding apart from an immutable one, in its settings:
{
"languages": { "Cherimoya": { "semantic_tokens": "combined" } },
"lsp": { "cheri": { "binary": { "path": "/path/to/cherimoya/build/cheri", "arguments": ["lsp"] } } }
}where the lsp part is only needed when cheri isn't on your path, and needs its arguments, since Zed starts a binary its settings name with exactly the arguments they give.
Any other editor that speaks the Language Server Protocol can start cheri lsp the same way.
| Path | What's there |
|---|---|
src/source, src/diagnostics |
the source buffer, and diagnostics with notes |
src/lexer |
the lexer and the operator table |
src/parser |
the parser and the AST |
src/sema |
name resolution and type checking |
src/codegen |
lowering to LLVM IR |
src/lsp |
the language server |
runtime/ |
the C runtime every program links with, and the entry points of a program and of a file of tests |
tools/cheri/ |
the cheri driver |
editors/vscode/ |
the VS Code extension |
editors/zed/ |
the Zed extension |
tree-sitter/ |
the tree-sitter grammar, which Zed and other editors read programs with |
tests/unit/ |
Catch2 tests for the lexer, parser, sema, runtime, and language server |
tests/run/ |
whole programs, each checked by its exit code |
tests/features/ |
.toya files testing each part of the language, run once the basics pass |
tests/debug/ |
programs built with debug info, checked with llvm-dwarfdump and gdb |
tests/test/ |
.toya files with every outcome a test can have, which cheri test has to report exactly as expected.out says |
docs/ |
the book, the language reference, and stdcheri's docs |
design/ |
how the compiler works, by concept, with a design doc for every commit |
The tests come in three tiers. The unit tests, in C++ under tests/unit/, check the lexer, parser, sema, runtime, and language server. The runtime basics check what everything else leans on, as .moya programs in tests/run/ and as the check of cheri test itself in tests/test/. Every feature of the language is then tested in tests/features/, once the first two tiers pass, since a feature test checks itself with assert and runs under cheri test, so a broken basic would make its results mean nothing, and ctest leaves the feature tests unrun when any test in the first two tiers fails. When valgrind is installed, every program and every feature test runs under it, so a leak or a double free fails the test too.
The programs in tests/run/ check what only a whole program can: start and its exit code, the top level running first, and an assert and a trap seen from outside. Each one is a .moya file whose first line is the exit code it should produce, and the test suite builds it with cheri at -O0 and at -O3, runs it, and compares. A program that should trap names the trap on a # trap: line, and its stderr has to contain it.
# exit: 134
# trap: trap at line 5: assert (n % 2 = 0);
# checks that a false assertion traps with its line, which aborts the program
let (n :: int) -> half -> (r :: int) { ... }
Debug info is tested the same way, through programs in tests/debug/, each built with -g -O0 unless a # flags: line says otherwise. Every # dwarf: line has to appear in what llvm-dwarfdump shows of the debug info, and the # gdb: lines run as one gdb session whose output has to contain every # expect: line, which is skipped when gdb isn't installed.
# gdb: break clamp
# gdb: run
# expect: clamp (n=150, lo=0) at
# checks that a breakpoint on a function stops once its inputs are stored
let (n :: int, lo :: int <- 0) -> clamp -> (r :: int) { ... }
cheri test itself is tested on tests/test/, whose .toya files have every outcome a test can have, and whose run has to print exactly what expected.out holds.
The feature tests are .toya files in tests/features/, one per part of the language, with one test for each behavior, which the test suite runs with cheri test at -O0 and at -O3:
@test(traps <- "'a / b' divided by zero")
let () -> divideByZero -> () {
_ <- div(7, 0);
}
Adding a test means adding a file, or a test to one.