Introduction
The Crush Language Guide
Open as a notebook (.crush-nb, how to run it)
Crush is a capability-based scripting language with polyglot blocks, plus the toolchain that runs it: a compiler to bytecode, a sandboxed VM, and an intermediate representation (CAST) that other languages can be translated into.
Alpha. This guide documents what the toolchain does today, verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03): everycrushexample on these pages is compiled and run byscripts/check-examples.py, and a corpus of 130 standalone programs with their exact output lives inexamples/verified/(The Verified Corpus). Features that exist in the design but not in the implementation are marked not yet implemented, with the crush-ast ticket; behaviour that is wrong today links the crush-ast issue.
What this guide covers
| Section | What you’ll learn |
|---|---|
| Getting Started | Build the toolchain, run a program, embed the VM from Rust |
| Crush Language | Syntax, types, control flow, functions, closures, structs and methods, concurrency, capabilities, polyglot blocks, engines |
| Examples | Runnable programs |
| CAST | The AST format that walkers and the compiler share |
| CASM | The bytecode formats the VM executes |
| Appendix | Glossary, quick reference, language comparisons |
The compilation pipeline
Crush source (.crush) Other languages (.py / .rs / .go / ...)
│ │
crush-frontend walker (language-specific)
parse · check · optimize │
│ │
└───────────────► CAST (JSON AST) ◄──────────┘
│
compiler
│
CASM (bytecode: JSON IR or CVM1 text)
│
assembler → CVM1 binary (.cvm1)
│
crush-vm (portable VM · FastVM · JIT · AOT backends)
crush run prog.crush runs the whole left-hand path in one step.
Hello, Crush
fn main() {
io.print("Hello, Crush!")
}
Hello, Crush!
io.print is a capability call: a call that crosses the VM boundary to the
host, and so only works if the host grants it. Capability calls are written like
any other dotted call — there is no @ prefix. (The @ sigil in Crush
introduces polyglot blocks such as @python { ... }, and annotations.)
Press Run under the example to run it in your browser, or Edit to change it first. Running the Examples explains the buttons and labels, and what the in-browser runtime can and cannot do.
Where the source lives
The language implementation is the standalone crush-ast repository, extracted from the exosphere agent-native OS monorepo on 2026-06-12. It contains the CAST intermediate representation, tree-sitter grammar, polyglot walkers, compiler frontend, VM runtime, package manager, and installer.
The upstream exosphere project retains
a subprocess-based walker registry that invokes the crush-ast walker binaries,
and its own crush-cast/casm/nanovm crates for the Crush language
compiler running inside the agent-native OS.
License
Licensed under either of MIT or Apache License 2.0 at your option.
Getting Started
Open as a notebook (.crush-nb, how to run it)
Crush is alpha software. This page gets you from a clean machine to a running program, and then shows how to embed the VM in a Rust application.
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03), built from source as the guide’s CI does. That commit is newer than the latest release, v0.11.2 (2026-11-07): a few things on these pages (catching run-time faults,a.pop(), calling any expression, the struct-name clash error,--max-wall-ms, thenet.*/tcp.*timeouts) are on main only until the next release.
1. Install the toolchain
The language is implemented in crush-ast.
There are two ways to get it. Both give you the same crush, crushc, crush-run,
crush-compile, crush-repl and crush-debug.
From crates.io (needs Rust 1.95 or newer):
cargo install crush-lang-sdk
Not
cargo install crush. Thecrushcrate on crates.io is an unrelated project. The toolchain is published ascrush-lang-sdk. There is nocrush-astcrate either; that is the repository’s name.
Prebuilt Linux binaries. Since v0.9.0 every vX.Y.Z tag has a GitHub release
(a pre-release until 1.0) with a Linux x86_64 tarball, a tarball of the browser
runtime, and a SHA256SUMS file. The newest is v0.11.2:
gh release download v0.11.2 --repo nixpt/crush-ast
sha256sum -c SHA256SUMS
tar -xzf crush-0.11.2-x86_64-unknown-linux-gnu.tar.gz
export PATH="$PWD/crush-0.11.2-x86_64-unknown-linux-gnu:$PATH"
The tarball holds crush, crushc, crush-run, crush-compile, crush-repl,
crush-debug, crush-pkg and crush-gui. crush doctor then tells you which
interpreters your polyglot blocks can use.
From source, to build a particular commit (this is how the guide’s CI builds
the commit in CRUSH_AST_COMMIT):
git clone https://github.com/nixpt/crush-ast
git clone https://github.com/nixpt/buckets # must sit NEXT TO crush-ast
cd crush-ast
cargo build --release -p crush-lang-sdk # crush, crush-run, crushc, ...
cargo build --release -p crush-aot # optional: crush-aotc (native AOT)
Two things to know:
bucketsmust be a sibling directory.crush-vmhas an optional path-dependency on../buckets(the sandbox provisioner), and Cargo resolves it even when the feature is off, so a lonecrush-astcheckout fails withfailed to read .../buckets/Cargo.toml.- The standard library is built in by default (crush-ast CRUSH-113):
str.*,math.*,conv.*,collections.*,json.*and friends need no flag. As of 0.9.0 the HTTP client (net.*) and raw TCP sockets (tcp.*) are compiled in by default too; they are still refused unless you pass--net/--tcp/--tcp-listen. Onlydbandgraphicsstill need--features db,graphics.
The binaries:
| Binary | What it does |
|---|---|
crush | The front door: crush run FILE, crush build FILE, crush repl, crush debug FILE, crush gui run FILE --ui, crush doctor |
crush-run | Run a .crush, .casm or .cvm1 file (all the capability flags live here) |
crushc | Compile .crush to bytecode (.cvm1), or --emit casm|ast|types; -C only checks |
crush-compile | Assemble CASM text into a .cvm1 binary |
crush-repl | Interactive REPL (crush repl; commands are .help, .quit) |
crush-debug | The debugger (crush debug): see Debugging |
crush-gui | Programs that draw a window (crush gui run): a separate package, see Windows |
crush-diff | (from a source build) run programs on several engines and report where they disagree |
crush-aotc | (from -p crush-aot) compile .crush to a native library via Rust or C, or crush-aotc run FILE |
Source builds need Rust 1.95 or newer (crush-ast’s CI checks that MSRV).
Crates.io. The newest release on crates.io is
0.11.2(2026-11-07), published forcrush-lang-sdk(which installscrush,crushc,crush-run,crush-compile,crush-repl,crush-debugandcrush-diff) and the library crates, all released together at the workspace version (the guide’s pinned commit is newer; see the note at the top). Releases before0.9.0(0.7.1,0.8.0) lack things this guide describes: slices on strings, hex and binary literals, the debugger,tcp.*, and the single diagnostics format. Never depend oncrush-lang-sdk0.2: that line has been yanked, and it runs@langblocks without the--polyglotgate.
2. Hello, Crush
Save this as hello.crush:
let name = "Crush"
print("Hello, " + name + "!")
Hello, Crush!
Run it:
crush run hello.crush
Hello, Crush!
[steps=6, stack=0]
The [steps=…] line is a run summary on standard error. Compile-only checking is
crushc -C hello.crush; to see the bytecode, crushc --emit casm hello.crush.
Three file types
crush run (and crush-run run) takes source, CAST, CASM, assembly or bytecode,
one extension per format (crush-ast #365, since v0.10.0):
crushc hello.crush -o hello.cvm1 # compile to CVM1 bytecode
crush run hello.cvm1 # run the bytecode
crushc --emit casm hello.crush -o hello.casm # CASM IR as JSON
crush run hello.casm
crushc --emit cvms hello.crush -o hello.cvms # CVM1 assembly text, with `.cap` lines
crush run hello.cvms
Assembly you write by hand (.cvms) has no manifest unless you add .cap NAME
lines, so every capability it calls must be named with --cap (without it:
capability not declared in manifest: io.print). Assembly text in a .casm file
still runs, with a note asking you to rename it to .cvms.
Arguments after the file name reach the program as sys.args():
crush run prog.crush a b → [a, b].
Capabilities need flags
A program can only reach the outside world through capabilities, and each group is off until you switch it on:
crush run prog.crush # str.* math.* conv.* json.* ... need nothing
crush run --fs --fs-root ./data prog.crush # fs.read / fs.write / fs.exists / fs.list
crush run --polyglot prog.crush # @python / @javascript / @bash blocks
crush run --net prog.crush # net.http_get / http_post / ... (HTTP only)
crush run --tcp prog.crush # tcp.connect / send / recv (client sockets)
crush-run caps prog.crush # what does it need? (runs nothing)
For example, this reads a file, so it needs --fs:
print(fs.read("notes.txt"))
Run it without the flag and nothing runs: needs capabilities this run does not grant; nothing was run: --fs: fs.read. The full flag list is in
Capability System (crush-run run --help prints it
too).
Limits worth knowing on day one
crush doctorreports which polyglot interpreters (python3,node,bash) it can find.- Defaults: 1,000,000 instructions, 256 call frames, 1 MiB of output, 30 s per polyglot block (all in Capability System).
- Named functions can’t see top-level variables (lambdas can), and
importdoesn’t load code yet — see Variables and Syntax.
3. The crates
Embedding Crush in a Rust program means depending on the SDK; the lower-level crates give direct access to the IR, bytecode, or VM.
| Crate | What it gives you |
|---|---|
crush-lang-sdk | Start here. Runtime, ProgramBuilder, host-capability registration, and the compile module that turns Crush source into a runnable program. |
crush-frontend | Parser, semantic analyzer, optimizer, and CASM compiler (parse_source). |
crush-vm | The CVM1 runtime: assembler/disassembler and the sandboxed interpreter with quotas + capability gates; also the FastVM. |
crush-cast | The CAST intermediate representation. |
casm | The CASM IR (casm::Program, JSON and MessagePack) — see CASM. |
crush-errors | Shared error types. |
tree-sitter-crush | Tree-sitter grammar (editor tooling, syntax highlighting). |
SDK Cargo features: the defaults stdlib (the standard library), net (the HTTP
client), tcp and tcp-tls (raw sockets), debug (the debugger),
native-plugins, polyglot-python, polyglot-javascript and polyglot-rust (the
analyses that marshal values into and out of @lang blocks), plus the optional
db, graphics, gpu, repl-helper and polyglot-typescript. A default feature
only compiles the capability in; the program still needs the matching flag at run time.
4. Embedding
Compile Crush source and run it on the VM — the same thing crush run does:
use crush_lang_sdk::compile::compile_crush_source;
use crush_lang_sdk::Runtime;
fn main() -> anyhow::Result<()> {
let program = compile_crush_source(r#"print("hello from crush")"#)?;
let result = Runtime::new().run(&program)?;
assert_eq!(result.output, "hello from crush\n");
Ok(())
}
Or hand-write CVM1 assembly (what crushc --emit casm prints) with
ProgramBuilder:
use crush_lang_sdk::{ProgramBuilder, Runtime};
fn main() -> anyhow::Result<()> {
let program = ProgramBuilder::new()
.permission("io.print")
.line(r#".func main"#)
.line(r#"PUSH_STR "hello, cvm1""#)
.line(r#"CAP_CALL "io.print" 1"#)
.line(r#"HALT"#)
.build()?;
let result = Runtime::new().run(&program)?;
assert_eq!(result.output, "hello, cvm1\n");
Ok(())
}
Both snippets are compiled and run against crush-ast dc0d0278 by
scripts/check-examples.py --crush-ast. Runtime::new() registers only the
built-in primitives (io.print, io.read, …); to expose more — the standard
library, filesystem, polyglot — build a HostCaps with HostCapsBuilder and pass
it with Runtime::with_quotas(..).with_host_caps(..), which is exactly what
crush-run does for its flags. The permission names a program may call are part of
its manifest (CASM structure).
5. Where next
- The language: syntax, types, control flow, functions
- Capability System and Polyglot: the security model — read the “what is not enforced” sections
- Examples: runnable programs
- CAST and CASM: the compiler’s formats
Running the Examples
Most code blocks in this guide can be run right on the page. Each Crush example carries one of four markings, worked out when the book is built from the same checks that keep the guide’s code honest (nothing is labelled by hand):
| Marking | What you get |
|---|---|
| Run · Edit · Playground ↗ | The example runs in your browser. Run shows its output under the block and, where the guide prints the expected output, whether yours matches the guide’s output. Edit turns the block into an editor (Ctrl+Enter runs it); Reset puts the original back. Playground opens it on crushlang.org/playground. |
| expected to fail | The example is meant to fail: a compile error, a refused capability, or a feature that is not implemented yet. Run demonstrates the failure and says whether it fails as the guide says. |
| needs the host | The example uses something the browser cannot give it; the label says what (a @bash block, fs.read, an @python block that reads files). Run it with crush-run and the flags shown on the page; see Getting Started. |
| not runnable | A fragment or a program that needs special setup; the label says which. |
An example whose crush-run flags the browser can honour carries a grants
label saying what its runs are granted, and nothing else is: @javascript and
@python (--polyglot with only @javascript / @python blocks), the
clock (--time), the environment (--env) or the filesystem (--fs).
Edited code keeps the example’s grants.
What runs in the browser
The Run button uses crush-web, the WebAssembly build of the Crush VM that also
powers the playground. It is the same compiler
and VM as crush-run (the book’s copy is built from crush-ast dc0d0278, the commit this guide is
verified against), and it grants the same way:
- Always granted: what
crush rungrants with no flags:print/io.print, the whole standard library (str.*,math.*,conv.*,collections.*,json.*,regex.*, …), andsys.args()(empty). - Standard input. When a program calls
io.read, an input line opens under the block: Enter sends one line, End input (or Ctrl+D) ends the input, and every laterio.readreturns"", as at the end of a file. Where the guide shows the input it ran an example with, the input line suggests it, and the output is compared with the guide’s only when you typed that input. - Granted per example (the grants label):
@javascriptblocks (below); the clock,time.*, read from your browser (time.now_isohas millisecond precision;time.sleepwaits and counts as running time); and the environment,env.*, which in a browser is empty:env.getreturnsnullandenv.all()is{}, as underenv -i crush-run --env. - Never available:
@pythonand@bashblocks, the filesystem, the network, processes and cryptography. An example that prints facts about the machine (env.os(),env.arch()) is labelled as needing the host too: in a browser they describe the browser (wasm32), so its output could not match the page. - Refused before running. Like
crush-run, the runtime works out every capability a program can reach and, if one is not granted, refuses the whole run before anything prints, naming thecrush-runflag that would grant it. - Every run starts fresh. Examples do not share variables, even on the same page. To build on one example in the next, open the chapter as a notebook (see Chapters as Notebooks).
- Limits. One million VM instructions per run, a bounded call depth, and 8 seconds of running time; a runaway loop is stopped, not your tab. Both cover the whole run, however many lines it reads, and time spent waiting for you to type does not count.
- Errors keep earlier output. When a run fails, what the program printed
before the error is shown above it, as
crush-runprints it. Errors readcompile error: …/runtime error: …wherecrush-runprints[compile] …/[runtime] …; the messages are the same.
@javascript blocks
Natively, crush-run --polyglot runs a @javascript block with node -e. In the
browser, a block granted polyglot.javascript runs in JavaScript inside the same
isolated worker as the VM, and behaves like that node -e run:
- Crush variables go in and
->outputs come back as JSON, as natively; every block starts with a fresh scope, and globals it creates are removed afterwards. - It runs as node runs a script: top-level
await, promises,asyncfunctions,queueMicrotaskand timers (setTimeout,setInterval,setImmediate) all work, and the block finishes when nothing is left to run, in node’s order. An uncaught exception (also in a timer or a promise), an unhandled rejection, orprocess.exit/process.exitCodewith a non-zero status fails it, as it makes node exit non-zero. - What it prints with
console.log(andinfo/debug/dir/group/count,process.stdout.write) is its output, formatted by node’s ownutil.inspectandutil.format(Map(1) { 'a' => 1 }, class instances, long arrays in columns, …), so it reads exactly as node prints it;require('util')is that module.console.error/warn/assertgo to its error output, which is shown if the block fails.process.envholds its inputs. - Where only node can answer, the block is refused, never approximated: node
modules other than
util, the network (fetch,XMLHttpRequest,WebSocket), the process’s own details (process.argv,platform,nextTick, …), and printing a Promise or a timer object (node shows their internals). Run such a program withcrush-run --polyglot. - The block runs with no authority: the worker sits in a sandboxed frame with an opaque origin and a content security policy that allows no network, so the block has no access to this page, its cookies or storage, or the network.
- A block that never finishes is stopped with the run at the time limit; what the run printed before the stop is lost with the stopped runtime.
@python blocks
Natively, crush-run --polyglot runs a @python block with python3 -c. In the
browser, a block granted polyglot.python runs in Pyodide
314.0.7, which is CPython 3.14 (the Python this guide’s examples were checked
with) compiled to WebAssembly, inside the same isolated worker as the VM, and
behaves like that python3 -c run:
- Downloaded on first use. The first time you run a
@pythonexample on a page, the page downloads Pyodide from its CDN (about 6.3 MB compressed) and checks every file against the sha256 the guide pins (play/pyodide.json) before using it. Pages without a@pythonrun never download it, and a page loads it once however many examples you run. - Crush variables go in and
->outputs come back as JSON, as natively. Every block starts in a fresh__main__; modules it imports and changes it makes toos.environare undone afterwards. - What it prints is its output; standard input is empty (natively it is
/dev/null, soinput()raisesEOFError). A block that raises fails the run with the tracebackpython3prints, at the block’s.crushline. - Where only the host can answer, the block is refused, never answered
differently: opening files and
osfile and directory calls, running processes (subprocess,os.system, …) and the network (socket,urllib.request,http.client, …). Pyodide’s own bridges to JavaScript (import js,import pyodide) do not exist, as inpython3. Packages (pypi:) need the host. Run such a program withcrush-run --polyglot. - The block has the same lack of authority as a
@javascriptblock, and a block that never finishes is stopped at the time limit the same way; the next@pythonrun loads Python again from the downloaded files.
The filesystem
Natively, crush-run --fs works on real files under --fs-root, and the guide’s
--fs examples are checked in an empty one.
Off for now. The book does not grant the filesystem yet, so
--fsexamples are labelled as needing the host. The crush-web crash with the in-memory filesystem is fixed in crush-ast v0.13.0 (#534, seesrc/play/pkg/PROVENANCE.md); turning the grant on is a follow-up. What follows is how the grant works when it is on.
In the browser, a run granted the filesystem gets an empty directory of its own, in memory, which disappears
when the run ends. The fs.* and text.* capabilities are the same code as
natively, over that directory instead of the disk. They give the same results
and the same errors (No such file or directory (os error 2)), and they keep
the same sandbox: a path that leaves the directory, with .. or as an absolute
path, is refused. Nothing is saved between runs, and nothing on your computer is
reachable.
Why not @bash, processes or the network
@bashhas no browser equivalent, andcrush-runnever sandboxes it either.- Processes (
process.exec) run programs on the host, and the network (net.*) reaches the host’s network; a browser page has neither to give.
Ungranted capabilities are refused, not ignored: that is the capability system working, and the page says so.
Without JavaScript the guide is a plain book: the code blocks are all there, just without the buttons.
Chapters as Notebooks
Every chapter with Crush examples is also published as a
crush-notebook (a .crush-nb file):
the chapter’s prose becomes Markdown cells, each Crush example a cell you can
run, edit and extend. Use the Open as a notebook link under a chapter’s
title, or pick one from the list below.
The notebooks are generated from the guide each time the book is built, so they
always match the pages. Each example cell keeps what the guide knows about it in
its metadata: the page and line it came from, its marking (runnable,
expected-failure, needs-host) as a tag, and the output or error the page
shows (meta.extra.guide). The notebooks ship without outputs: running them is
up to you.
Open a notebook on your machine
A .crush-nb file is plain JSON. To run one you need the notebook kernel; to
read one as a page, the renderer. Both are on crates.io:
cargo install --locked crush-notebook-kernel crush-notebook-render
Run it with the kernel. crush-notebook-kernel is an
MCP server over stdio, so any MCP client (an
editor, an agent harness) can open a notebook, run its cells, read the session’s
variables and add cells of its own. Register it with your client:
{
"mcpServers": {
"crush-notebook": { "command": "crush-notebook-kernel" }
}
}
and call notebook_open with the file’s path, then notebook_eval_all (or
notebook_eval_cell for one cell) and notebook_list_vars. Or drive it by hand:
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"notebook_open","arguments":{"path":"types.crush-nb"}}}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"notebook_eval_all","arguments":{}}}' \
| crush-notebook-kernel
The kernel saves each cell’s result back into the file, so work on a copy if you want to keep the original.
Read it as a page. crush-notebook-render types.crush-nb writes
types.html next to it: one self-contained page (no external assets) with the
cells and, if you have run the notebook, their outputs.
The kernel’s other tools, the agent workflow (@wip cell claims, delegation)
and the cell kinds it does not run yet are described in the
crush-notebook README.
What runs where
| Run button on the page | Notebook kernel | crush-run | |
|---|---|---|---|
| Where it runs | your browser (crush-web, WebAssembly) | your machine | your machine |
| Granted | print, the standard library and io.read (you type each line), plus what an example’s grants label says: @javascript, @python, the clock, the (empty) environment (the filesystem grant is off at the pinned commit, see Running the Examples) | print, the standard library, caison.parse: what crush run grants with no flags | the standard library, plus whatever its flags grant (--fs, --polyglot, …) |
@python/@javascript, filesystem | when the example’s label grants them | refused | with the matching flag |
@bash, processes, network | refused | refused | with the matching flag |
| Between examples | every run starts fresh | cells share a session | one program per file |
The kernel is crush-notebook-kernel 0.3.0, built on crush-ast 0.9.0 (the newest
published kernel), while the guide is verified against crush-ast dc0d0278, which is
newer. Cells that use something added since 0.9.0 (catching run-time faults,
a.pop(), calling any expression, regex.match, exponent literals,
process.exec’s result map) behave in the notebook as in 0.9.0 until a kernel built
on a newer crush-ast is published. The 0.3.0 kernel also predates imports
(crush-ast 0.9.0 refused every import).
The examples marked needs the host are refused in the notebook too, and so
are the ones the page runs only because it grants them something (@python,
@javascript, the filesystem, the clock): the kernel grants what crush run
grants with no flags. Run those with crush-run
and the flags their page shows (see Getting Started).
In a notebook, cells share a session: a cell’s top-level lets, functions and
structs are visible to the cells after it, which makes a notebook a good place to
build on an example. The examples that are meant to fail (expected-failure)
are the one exception: each is wrapped in its own fn main() { … }, so a
variable an earlier cell left behind cannot hide the error the example is there
to show. Because of that wrapper, the line and column numbers in their compile
errors differ from the page’s.
Every notebook is run through the kernel in the guide’s CI: each runnable cell has to finish and print what the page shows, each expected failure has to fail, and each host-only cell has to be refused.
The notebooks
index.crush-nb, from Introductionappendix/comparison.crush-nb, from Language Comparisonsappendix/quick_reference.crush-nb, from Quick Referencecasm/index.crush-nb, from Overviewcasm/examples.crush-nb, from Examplescasm/instructions.crush-nb, from Instruction Referencecrush/index.crush-nb, from Overviewcrush/annotations.crush-nb, from Annotationscrush/capabilities.crush-nb, from Capability Systemcrush/closures.crush-nb, from Closures and Function Valuescrush/concurrency.crush-nb, from Concurrencycrush/control_flow.crush-nb, from Control Flowcrush/debugging.crush-nb, from Debuggingcrush/diagnostics.crush-nb, from Errors and Diagnosticscrush/functions.crush-nb, from Functionscrush/modules.crush-nb, from Modules, Packages and Visibilitycrush/operators.crush-nb, from Operatorscrush/polyglot.crush-nb, from Polyglot Programmingcrush/stdlib.crush-nb, from Standard Librarycrush/structs.crush-nb, from Structs, Methods and Kindscrush/syntax.crush-nb, from Syntax & Grammarcrush/types.crush-nb, from Typescrush/variables.crush-nb, from Variables & Scopingexamples/arrays-loops.crush-nb, from Arrays & Loopsexamples/async-dom.crush-nb, from Polyglot Pipelineexamples/build-pipeline.crush-nb, from Build Pipelineexamples/concurrency-structs.crush-nb, from Structs (and Concurrency)examples/exceptions.crush-nb, from Exception Handlingexamples/fibonacci.crush-nb, from Fibonacci & Functionsexamples/imports.crush-nb, from Import Stylesexamples/lambdas.crush-nb, from Lambdas & Pipesexamples/sysinfo.crush-nb, from System Info Reportgetting-started.crush-nb, from Getting Started
The Verified Corpus
Besides the examples on its pages, this guide keeps a corpus of small, standalone
Crush programs in examples/verified/,
one behaviour per program, each stored next to the exact output it produces. It is
the evidence behind the chapters: every claim about the language was first
observed by running one of these programs.
Verified against crush-ast
dc0d0278(the commit in the repository’sCRUSH_AST_COMMITfile). 150 programs.
| Area | Programs | Covers |
|---|---|---|
basics/ | 13 | literals (including hex and binary), print vs io.print, semicolons, one-line expressions, comments, return values, scoping, annotations, Nepali keywords |
operators/ | 10 | arithmetic, comparison, and/or/not, short-circuit, string +, |>, overflow, division by zero |
strings/ | 8 | indexing, str.*, conv.chr/ord, escapes, string and array slices (s[a:b], s[::step]), string methods that don’t exist |
collections/ | 11 | arrays, array.pop and a.pop(), maps (insertion order, subscripts, iteration), collections.*, json.* |
control-flow/ | 9 | if, while/break/continue, ranges, match as expression and statement |
functions/ | 5 | definitions, arity checks, no defaults, top-level visibility, the call-depth quota |
closures/ | 11 | lambdas, function values, calling any expression, capture by reference, counters, loop capture, recursion |
structs/ | 11 | literals, sealing, equality, impl, traits, value semantics, C3, bound methods, constructors |
match/ | 3 | struct patterns, and their compile errors |
errors/ | 7 | try/catch/throw, rethrow, catching run-time faults, what catch can’t catch, result.* |
modules/ | 21 | the import forms, -L and CRUSH_PATH, module rules and errors, structs across files, the struct/trait name clash, pub and __, export |
capabilities/ | 12 | refusal before running, --fs and --fs-root, @capabilities, io.read, sys.args, math.random |
polyglot/ | 15 | --polyglot, -> outputs, JavaScript, chaining, use @lang, isolation, errors, bash |
concurrency/ | 7 | spawn/yield/await, async fn, parallel_map and its rules |
annotations/ | 3 | manifest annotations, @wip, @capabilities |
ai-native/ | 2 | the refused semantic_switch, AI expressions not in source |
casm/ | 2 | running assembly text (.cvms) with --cap |
The files
For each program NAME:
| File | Meaning |
|---|---|
NAME.crush / NAME.cvms | the program; its first comment lines say what it shows |
NAME.out | its exact standard output |
NAME.err | present when the program must fail: every line of it must appear in the error output |
NAME.flags | the crush-run flags it needs (--polyglot, --fs --fs-root ., …) |
NAME.stdin | what it reads from standard input (otherwise it reads end-of-file) |
NAME.needs | host programs it needs (python3, node); skipped, not failed, without them |
NAME.env | environment variables for the run, NAME=value per line (CRUSH_PATH=shared) |
NAME.files/ | the other files the program needs, such as the modules it imports; copied next to it for the run, and not programs of their own |
Programs whose first line says PITFALL show behaviour that is wrong today and link the crush-ast issue: when the issue is fixed, the program’s expected output changes and the corpus fails, which is the signal to update the guide.
| Pitfall | Issue |
|---|---|
polyglot/header-comment-pitfall: // on a block header → Undefined variable | #266 |
Running it
# crush-ast at the pinned commit, with buckets beside it
git clone https://github.com/nixpt/crush-ast && git -C crush-ast checkout "$(cat CRUSH_AST_COMMIT)"
git clone https://github.com/nixpt/buckets
(cd crush-ast && cargo build -p crush-lang-sdk)
scripts/verify-examples --bin-dir crush-ast/target/debug # the corpus
scripts/check-examples.py --bin-dir crush-ast/target/debug \
--crush-ast crush-ast # every block on the pages
verify-examples runs each program in a fresh temporary directory with
crush-run run <flags> --max-steps 50000000 and a 60-second timeout, and prints
a diff for any output that changed. --bless rewrites the .out files from a run;
read the new output before committing it. The repository’s CI runs both scripts
against the pinned crush-ast commit on every pull request.
Crush Overview
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush is a small, capability-based scripting language with polyglot blocks, and the toolchain around it: a parser, a compiler to bytecode, a sandboxed VM, and an intermediate representation (CAST) that other languages can be translated into. It is alpha software — this guide documents what runs today and says so when something doesn’t.
What Crush is
- A language.
let,fn,if/while/for,match,try/catch, arrays and objects, closures and function values, structs withimplmethods andtraits, green tasks, a pipeline operator. Dynamically typed at run time with optional compile-time type hints. See Syntax. - Capability-gated. A program can’t print files, open sockets or start
processes unless the host turns the matching capability on. Capability calls
are ordinary dotted calls —
fs.read("x"),io.print("y"). See Capability System. - Polyglot.
@python -> out { },@javascript { }and@bash { }blocks run other languages and exchange variables with Crush. They currently run as ordinary subprocesses outside the capability model unless you build the optional sandbox. See Polyglot Programming. - A pipeline. Source becomes CAST (an AST in JSON), then CASM (bytecode), then
runs on a VM (
crush-vm), with a faster VM, a JIT and ahead-of-time backends also in the repository (Engines, AOT and Walkers). Walkers translate Python, JavaScript, Rust and other languages into the same CAST.
New since 0.9.0
Up to the pinned commit (v0.13.0); each item links to its page.
- Imports and packages.
import a.b [as x] [{ f }]loads.crushfiles at compile time, through-L,CRUSH_PATHand crush-pkg dependencies;pub fnis enforced per package (since v0.12.0) and a dependency’s own dependencies resolve (v0.13.0); a struct or trait name declared in two files is a compile error. (Modules) catchcatches run-time faults: division by zero, a bad index, a failing capability. (Control Flow)- Calls on any expression (
fs[0](1),make()(2),S { n: 3 }.size()), the method forma.pop(),regex.matchcallable, exponent literals (1.5e3). (Closures, Types) process.execreturns a map{exit_code, stdout, stderr}. (Capability System)- Quotas and networking.
--max-wall-ms N|unlimitedbounds the whole run,--max-steps unlimited;net.*andtcp.recv/tcp.accepttake{timeout_ms};net.http_requestreturns response headers. (Capability System)
New in 0.9.0
Each item links to the page that documents it (and every example there was run).
- Slices on strings, and steps.
s[0:5],s[-5:],s[::2],s[::-1]on strings and arrays; they lower toseq.slice. (Types) - Hex and binary literals.
0xff,0b101. (Syntax) - A debugger.
crush debug FILE --step --inspect: breakpoints by line, step, watch, print, with the inspection itself a grant. (Debugging) - Windows.
crush gui run FILE --uiand theui.*API, from the separatecrush-guipackage. (Windows) - Raw sockets.
tcp.*behind--tcp(client) and--tcp-listen(server);--netstays HTTP-only.net.*is compiled into the default build, and the oldhttp.*names are refused with their replacement. (Capability System) - One diagnostics format.
--message-format jsongives one schema across the tools, and semantic errors carry a line and column. (Diagnostics) - Easier install.
cargo install crush-lang-sdk(notcargo install crush, which is an unrelated crate), or the prebuilt Linux binaries on the GitHub release; v0.9.0 is the first release to have them. (Getting Started) @bashblocks can read Crush variables again, by$name. (Polyglot)
Hello, Crush
print("Hello, Crush!")
Hello, Crush!
Run it with the toolchain built from crush-ast (see Getting Started):
crush run hello.crush
A taste
struct Point { x: Int, y: Int }
impl Point {
fn distance_sq(self) { return self.x * self.x + self.y * self.y }
}
let points = [Point { x: 3, y: 4 }, Point { x: 1, y: 1 }]
let far = |p| p.distance_sq() > 10
let i = 0
while i < len(points) {
let p = points[i]
if far(p) {
print("far: " + p.distance_sq())
}
i = i + 1
}
far: 25
Security model, in short
- Deny by default. Every capability group (
--fs,--net,--process,--polyglot, …) is off until you enable it on the command line (or register it, when embedding). - Quotas. Instruction count, stack depth, output size, call depth and wall-clock time for polyglot blocks are bounded.
- Honest limits. Polyglot blocks run with the host’s authority in the default build; the bubblewrap sandbox is opt-in at build time. The capability chapter lists what is not enforced.
Where things stand
| Area | Status |
|---|---|
Core language (functions, loops, try/catch, match) | works |
| Closures and function values | works on the VM; AOT refuses them by name |
Structs, impl, trait, @kind, struct patterns | works on the VM; AOT refuses method calls by name |
spawn / yield / await, parallel_map | works on the VM |
import (multi-file programs), crush-pkg packages | works, resolved at compile time; visibility is per package, a private function used from another package is the warning W-VIS01 (Modules) |
Capabilities, @capabilities, the standard library | works; the standard library is on by default |
Polyglot: Python, JavaScript (declared -> outputs), Bash | works (host authority by default); @bash reads the Crush variables it names as $name |
| Polyglot sandbox | opt-in build, verified on Linux with bwrap |
| CAST / CASM formats | documented in their own sections |
Next Steps
- Syntax & Grammar
- Types
- Closures and Structs, Methods and Kinds
- Capability System
- Polyglot Programming
Syntax and Grammar
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03): every runnable block on this page was compiled and run with that build.
This chapter covers the lexical structure and grammar that the Crush parser
(crush-frontend) accepts today. Every crush example in this guide is run
through the real toolchain by scripts/check-examples.py; where something is
described in the design but the parser does not accept it yet, the page says so
and links the crush-ast ticket.
Status: alpha. The language is small and still moving. If a feature isn’t in this chapter, assume it doesn’t exist yet.
A program
A Crush file is a sequence of statements. There are two styles, and they can be mixed:
- Script style — bare top-level statements run top to bottom.
fn main()— an explicit entry function.
When a file has both, the top-level statements run first and then main’s body
runs.
print("top-level runs first")
fn main() {
print("then main")
}
top-level runs first
then main
Functions can be called before they are defined:
print(seven())
fn seven() {
return 7
}
7
Comments
Single-line comments start with // or #. There are no block comments —
/* ... */ is a parse error.
// a slash comment
# a hash comment
print("hello") // trailing comments work too
hello
Identifiers
Identifiers start with a letter or underscore and continue with letters, digits and underscores. Hyphens are not allowed, and a name can’t be a keyword.
let counter1 = 1
let _private = 2
let my_variable = 3
print(counter1 + _private + my_variable)
6
Keywords
let fn if else while for in
return break continue struct new try catch
throw match use import export capability
async await spawn yield lang mut
and or not true false null
and, or and not are keyword spellings of &&, || and !. mut and
capability are reserved, but let mut x = ... is not accepted (see
Variables), and capability has no usable statement form yet.
impl and trait are contextual keywords: they start a declaration only at
the top level of a file (see Structs, Methods and Kinds), so a
variable may still be called impl.
The lexer also recognises a handful of localised keyword aliases —
karya/manau/yadi/natra/farkau/jaba_samma/sahi/galat (Nepali) plus a
few Chinese and Japanese forms — which map to fn/let/if/else/return/
while/true/false:
karya sign(x) {
yadi x > 0 { farkau "positive" } natra { farkau "not positive" }
}
manau r = sign(1)
print(r)
positive
Literals
| Kind | Examples | Notes |
|---|---|---|
| Integer | 42, -7, 0x2A, 0b101 | hex (0x/0X, any digit case) and binary (0b) literals, 0.9.0; 0o17 and 1_000 do not lex, and 0x with no digits is Invalid number literal |
| Float | 3.14, 0.5, 1.5e3, 2.5e+3, 1e-7 | a decimal exponent, since 0.11 (CRUSH-221); a malformed one (1e, 1.e5) is Invalid number literal |
| String | "hello", 'hello' | single or double quotes; escapes \n \t \" \\ |
| Boolean | true, false | |
| Null | null | |
| Array | [1, 2, 3] | see Types |
| Object | {"a": 1, b: 2} | see Types |
Hex and binary literals are ordinary integers, so they mix freely with decimal ones:
print(0xff)
print(0b101)
print(0xFF + 0b11)
print(-0x10)
255
5
258
-16
Triple-quoted strings are parse errors, and bytes literals (b"...") are refused
with bytes literals (b"...") are not supported yet. A string literal may
contain a raw newline.
let n = 42
let pi = 3.14
let s = "tab:\there"
print(n)
print(pi)
print(s)
print(0x2A + 0b101)
print('single "quotes" work too')
42
3.14
tab: here
47
single "quotes" work too
Statements and semicolons
Semicolons are optional. A statement ends at a newline, or you may write ;
(and a; b on one line) if you prefer. Both of these are the same program:
let a = 1; let b = 2;
print(a + b);
3
let a = 1
let b = 2
print(a + b)
3
An expression cannot continue onto the next line, even inside (), [] or
{}: the newline ends it, so a multi-line array, map or argument list is a parse
error (unexpected token in expression: newline). Keep such expressions on one
line, or build them with several statements. Blocks (fn/if/while bodies,
lambda bodies, match arms) do span lines.
let a = [1,
2]
print(a)
Return values
A function returns a value only through an explicit return. A bare final
expression is not an implicit return — it yields null:
fn explicit() { return 5 }
fn implicit() { 5 }
print(explicit())
print(implicit())
5
null
Blocks
Blocks are delimited by { } and are used by functions, if, loops and
try/catch. A bare block as a statement is not supported; use if true { ... }
if you need one.
Names resolve at function level, not per block: after a let inside an if
or loop body, the name refers to that binding for the rest of the function (see
Variables). Each execution of a let does create a fresh
binding, which is what a closure captures.
Variables and functions
let x = 42
let name: String = "Alice"
fn add(a: Int, b: Int) -> Int {
return a + b
}
print(add(x, 1))
print(name)
43
Alice
Type annotations on variables, parameters and return values are checked at compile time — see Types.
Operators
Full tables are in Operators. In short: + - * / %,
== != < > <= >=, && || ! (also spelled and, or, not), unary -, and the
pipeline |>. There is no **, //, +=/-=, or ternary ? :.
Precedence (high → low)
- Calls, field access, indexing:
f(),obj.field,a[i] - Unary:
-,! - Multiplicative:
*,/,% - Additive:
+,- - Comparison:
<,>,<=,>= - Equality:
==,!= - Logical AND:
&& - Logical OR:
|| - Pipeline:
|>
print(1 + 2 * 3)
print((1 + 2) * 3)
print(1 < 2 && 2 < 3)
7
9
true
Control flow
let x = 5
if x > 3 {
print("big")
} else if x > 1 {
print("medium")
} else {
print("small")
}
let i = 0
while i < 3 {
i = i + 1
}
print(i)
for n in 0..3 {
print(n)
}
for n in 1..=2 {
print(n * 10)
}
big
3
0
1
2
10
20
break and continue work in while and for. See Control Flow.
Capability calls
A capability call looks like an ordinary dotted call — no @ prefix:
io.print("Hello, ", "Crush")
Hello, Crush
(io.print accepts any number of arguments and concatenates them with no
separator; the built-in print(x) takes exactly one.) Which capabilities exist,
and which command-line flags grant them, is covered in
Capability System.
Language blocks
Another language’s code is embedded with @language { ... }. The @ here is
required; it is what introduces the block. Polyglot execution is off by
default and needs --polyglot:
@python {
print("Hello from Python")
}
A block that sends values back to Crush names them after ->:
@python -> total { ... }.
Hello from Python
See Polyglot Programming for the supported languages, how variables cross the boundary, and the (important) security caveats.
Imports and exports
import a.b loads a/b.crush at compile time and binds the qualifier b
(import a.b as x binds x, import a.b { f, g } binds the bare names). The file
is looked for in the importing file’s directory, then each -L DIR, then
CRUSH_PATH. Imports go at the top level of a file, and a module contains only
definitions. See Modules, Packages and Visibility for the rules,
packages and pub. There is no std.* module tree: a module that is not found is
a compile error listing the directories searched.
use @lang python "math" is different: it writes import math into every later
@python block (see Polyglot).
import std.io
print("never reached")
export name parses and marks an existing variable or function for export. It
is not an expression-level declaration:
let result = 6 * 7
export result
print(result)
42
export let x = ... and export fn f() {...} are parse errors. export has
nothing to do with modules: every function of a module is importable without it,
and a module that contains an export statement is refused.
Annotations
@name also introduces annotations:
@capabilities [fs.read, time.now_ms]declares what the program may use, and the compiler enforces it (Capability System).@kind(...)before astructchooses its object semantics (Structs, Methods and Kinds).@module,@decision,@invariant,@wip,@temporary,@errorsare metadata for tools and agents, attached to the next declaration; they don’t change what the program does (Annotations).
Style
snake_casefor functions and variables,PascalCasefor structs.- Four-space indentation; keep lines under ~100 characters.
- Omit semicolons unless you are putting two statements on one line.
Grammar summary
This is the grammar the parser implements, simplified (from
crates/crush-frontend/src/parser/mod.rs):
program = ( statement | impl_block | trait_def | annotation )* ;
statement = let_stmt | fn_def | struct_def | if_stmt | while_stmt
| for_stmt | return_stmt | break | continue
| try_stmt | throw_stmt | export_stmt | import_stmt | use_stmt
| lang_block | match_expr | expr_stmt ;
let_stmt = "let" IDENT ( ":" type )? "=" expression ";"? ;
fn_def = "async"? "fn" IDENT "(" params? ")" ( "->" type )? block ;
struct_def = kind_annot? "struct" IDENT "{" ( IDENT ( ":" type )? ","? )* "}" ; (* one line *)
kind_annot = "@kind" "(" IDENT ":" value ( "," IDENT ":" value )* ")" ;
impl_block = "impl" ( IDENT "for" )? IDENT "{" fn_def* "}" ;
trait_def = "trait" IDENT "{" ( "fn" IDENT "(" params ")" ( ";" | block ) )* "}" ;
if_stmt = "if" expression block ( "else" ( if_stmt | block ) )? ;
while_stmt = "while" expression block ;
for_stmt = "for" IDENT "in" expression block ; (* a..b, a..=b, arrays, strings, maps *)
try_stmt = "try" block "catch" IDENT block ;
throw_stmt = "throw" expression ;
export_stmt = "export" IDENT ;
use_stmt = "use" "@lang" IDENT STRING ( "as" IDENT )? ;
lang_block = "@" IDENT ( "[" deps "]" )? ( "->" ( IDENT | "(" IDENT ( "," IDENT )* ")" ) )?
"{" raw source "}" ;
block = "{" statement* "}" ;
expression = literal | IDENT | expression binop expression
| unop expression | call | field | index | slice
| lambda | struct_lit | "new" IDENT "(" ")" | IDENT "::" IDENT
| match_expr | "spawn" call | "await" expression ;
lambda = "|" params? "|" ( expression | block ) ;
struct_lit = IDENT "{" ( IDENT ":" expression ","? )* "}" ;
match_expr = "match" expression "{" ( pattern ( "=>" | "->" ) ( expression | block ) ","? )* "}" ;
pattern = literal | IDENT | "_" | IDENT "{" ( IDENT ":" pattern ","? )* "}" ;
call = IDENT "(" args? ")" | expression "." IDENT "(" args? ")" ;
A call’s callee must be a name (or value.method): fs[0](1) and f()(x) are
parse errors today (crush-ast CRUSH-zorro-24).
Next Steps
- Data Types: the type system and collections
- Closures and Structs, Methods and Kinds
- Variables: declaration and scope
- Control Flow: loops,
match, errors - Functions: parameters, returns, recursion
Data Types
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush is dynamically typed at run time, with a static checker that catches obvious mismatches at compile time when you add type annotations. This chapter covers the values you can build today.
Primitive types
| Type | Literal | Notes |
|---|---|---|
| Int | 42, -7, 0x2A, 0b101 | 64-bit signed; overflow is a runtime error |
| Float | 3.14, 1.5e3, 1e-7 | 64-bit IEEE 754. Exponent literals since 0.11 (CRUSH-221); 1e alone is Invalid number literal |
| String | "hello", 'hello' | len counts bytes |
| Bool | true, false | |
| Null | null | absence of a value |
let count = 42
let pi = 3.14
let name = "Alice"
let active = true
let nothing = null
print(count)
print(pi)
print(name)
print(active)
print(nothing)
42
3.14
Alice
true
null
Numbers
+ - * / % work on Int and Float. Mixing the two promotes to Float.
/ on two Ints is integer division:
print(10 / 4)
print(10.0 / 4)
print(1 + 2.5)
print(7 % 3)
2
2.5
3.5
1
Dividing by zero is a runtime error ([runtime] division by zero), for
Float too (there is no inf or NaN). It is raised by the VM rather than thrown
as a Crush value, so try/catch does not intercept it.
Int arithmetic is checked: a result outside i64 stops the program with
[runtime] arithmetic overflow. It never wraps.
let big = 9223372036854775807
print(big + 1)
Strings
Concatenate with +. Adding a number to a string converts the number:
let first = "Ada"
let last = "Lovelace"
print(first + " " + last)
print("Count: " + 42)
print("Pi is " + 3.14)
Ada Lovelace
Count: 42
Pi is 3.14
len(s) is the byte length and s[i] yields a one-character string (a negative
index counts from the end). The standard library’s str.* capabilities add
str.split, str.trim, str.to_upper, str.substring and friends — see
Standard Library. Strings have no methods: s.to_upper() fails at run time
(`.to_upper(…)` on a str: member calls resolve on struct instances (COSM Records) and maps); call str.to_upper(s).
let s = "hello"
print(len(s))
print(s[1])
print(s[-1])
print(str.to_upper(s))
print(str.substring(s, 1, 3))
5
e
o
HELLO
el
Slicing strings
s[start:stop] slices a string by characters (since 0.9.0; before it, a string
slice compiled and then failed with expected array, got str). Either bound may
be left out, a negative bound counts from the end, and a bound past the end is
clamped rather than an error. stop is exclusive, and the result is a new string.
The slice counts characters, not bytes, so it never splits a multi-byte character
(unlike len, which counts bytes):
let s = "hello world"
print(s[0:5])
print(s[6:])
print(s[:5])
print(s[-5:])
print(s[3:100])
print("héllo"[1:3])
hello
world
hello
world
lo world
él
A third part is a step: s[::2] takes every second character and a negative step
walks backwards, so s[::-1] reverses. The step form works the same on arrays (see
Arrays). A step of 0 is a runtime error
(expected non-zero slice step, got 0).
let s = "hello world"
print(s[::2])
print(s[::-1])
print("日本語🎉!"[::-1])
hlowrd
dlrow olleh
!🎉語本日
Every bracket slice lowers to the standard-library capability seq.slice(target, start, stop, step), where null means “from the edge”; str.substring still
works and takes its bounds as arguments.
Collections
Arrays
Ordered, mixed-type, zero-indexed. Index, assign by index, and len:
let numbers = [10, 20, 30]
print(numbers[0])
numbers[1] = 99
print(numbers)
print(len(numbers))
let nested = [[1, 2], [3]]
print(nested[0][1])
10
[10, 99, 30]
3
2
Append with array.push(arr, value) or the method form arr.push(value); +
joins two arrays:
let a = [1, 2]
a.push(3)
array.push(a, 4)
print(a)
print([1] + [2])
[1, 2, 3, 4]
[1, 2]
Iterate with for:
for item in ["a", "b"] {
print(item)
}
a
b
array.pop(a) removes and returns the last element, a.append(v) is an alias for
push, and slices a[start:end] work (end exclusive):
let a = [1, 2, 3, 4]
let last = array.pop(a)
print(last)
print(a)
print(a[0:2])
4
[1, 2, 3]
[1, 2]
Reading past the end is a runtime error (array index out of range), and so is
a[-1] on an empty array; a[-1] on a non-empty one is the last element. The
method form a.pop() does the same as array.pop(a) (crush-ast CRUSH-391, on main
after v0.11.2).
Negative slice bounds count from the end, as an index does: with
let a = [1, 2, 3, 4], a[1:-1] is [2, 3], a[-3:] is [2, 3, 4] and
a[:-1] is [1, 2, 3]. (Before crush-ast
#254 they were silently clamped.)
Slices take a step too (0.9.0): a[::2] is every second element, a[::-1] is the
array reversed, a[1:5:2] starts at 1 and takes every second element before 5, and
a[:] is a copy:
let a = [1, 2, 3, 4, 5, 6]
print(a[::2])
print(a[::-1])
print(a[1:5:2])
print(a[:])
[1, 3, 5]
[6, 5, 4, 3, 2, 1]
[2, 4]
[1, 2, 3, 4, 5, 6]
Objects (maps)
Key–value pairs written {"key": value}. Keys may be bare identifiers or
strings. Read and write fields with dot notation or a string subscript:
let person = {"name": "Alice", "age": 30}
print(person.name)
person.age = 31
person.email = "alice@example.com"
print(person.age)
print(person.email)
Alice
31
alice@example.com
Nested objects chain:
let cfg = {"db": {"port": 5432}}
print(cfg.db.port)
cfg.db.port = 5433
print(cfg.db.port)
5432
5433
Objects keep insertion order: printing, for k in obj and
collections.keys(obj) all list keys in the order they were first set.
let person = {"name": "Alice"}
person["age"] = 30
let field = "name"
print(person[field])
print(person)
for k in person {
print(k)
}
Alice
{name: Alice, age: 30}
name
age
Reading a key that isn’t there is a runtime error (expected present map key, got absent key), not null. len(obj) is rejected (expected array or string, got map); count collections.keys(obj) instead.
Structs
Declare a struct with its field names (optionally with type hints) on one
line, then build one with a literal that names every field, or with
new Name() and assign fields individually:
struct Point { x: Float, y: Float }
let a = Point { x: 1.0, y: 2.0 }
let p = new Point()
p.x = 1.5
p.y = 2.5
print(a)
print(p.x + p.y)
{x: 1.0, y: 2.0}
4.0
Structs are sealed: writing a field the struct doesn’t declare stops the
program (`Point` is sealed: it has no field `z` (fields: x, y)), and a
literal with a missing or unknown field is a compile error. Field type hints are
not enforced at run time today, and an unassigned field reads as null.
Methods, traits, value semantics and @kind are in
Structs, Methods and Kinds.
A struct body that spans several lines is still rejected: the parser doesn’t skip
newlines inside struct { ... } (gap GAP-STRUCT-MULTILINE, listed in crush-ast’s
CRUSH-192 ticket):
struct Point {
x: Float,
y: Float
}
Type annotations
You may annotate variables, parameters and return types with Int, Float,
String, Bool, or Any. The compiler checks them statically:
fn double(n: Int) -> Int {
return n * 2
}
let label: String = "answer"
print(label)
print(double(21))
answer
42
Mismatches are rejected at compile time:
let x: Int = "not a number"
fn double(n: Int) -> Int {
return n * 2
}
print(double("seven"))
Annotations are optional. Not available: generic forms (Array<Int>), array
shorthand (Int[]), nullable T?, and Function/Array/Map as hint names —
all fail with a parse or Unknown type error.
Conversion and inspection
The standard library’s conv.* capabilities convert between types and report
them:
print(conv.to_int("42") + 1)
print(conv.to_str(5) + "x")
print(conv.to_float(2))
print(conv.type_of([1]))
print(conv.type_of(null))
43
5x
2.0
array
null
conv.type_of returns int, float, string, bool, null, array or
map. There is no type.of.
Conditions must be Bool
if and while conditions are type-checked: an Int or String is not
silently truthy. Compare explicitly (x != 0, s != "").
if 1 {
print("yes")
}
Comparison
==/!= compare values of the same type; comparing a string to an int is a
compile error (Cannot compare types string and int). 1 == 1.0 is true.
Not available yet
| Feature | Status |
|---|---|
Bytes literals (b"...") | refused: bytes literals (b"...") are not supported yet |
Error(...) values | undefined |
Optional types T?, ?? | not parsed |
| Enums, type aliases, generics | not in the grammar |
Function as a type hint | Unknown type (function values themselves work: Closures) |
Next Steps
- Variables: scope and mutation
- Operators: the operator reference
- Functions: calls, recursion, hints
- Control Flow: loops,
match,try/catch
Variables and Scoping
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
This chapter covers declaration, assignment, and the scoping rules the compiler enforces today.
Declaration
Every variable is introduced with let and must be initialised:
let x = 42
let name = "Alice"
let active = true
print(x)
42
A bare let x (no value) is a parse error. So is let mut x = 0 — mut is a
reserved word, but it is not accepted in a declaration, and there is no const.
Every let variable is simply reassignable.
let x
let mut counter = 0
Type hints
let age: Int = 30
let score: Float = 95.5
let message: String = "Hello"
let flag: Bool = true
print(age)
30
The initial value is checked against the hint at compile time
(let x: Int = "s" is rejected). The hint is not re-checked on later
assignment today.
Assignment
Reassign with =:
let counter = 0
counter = counter + 1
counter = counter + 1
print(counter)
2
Compound assignment (+=, -=, *=, /=) and ++/-- are not implemented:
use counter = counter + 1. Assigning to a name that was never declared is a
compile error (Undefined variable).
counter += 1
Variables are dynamically typed at run time, so a let-declared name can later
hold a value of a different type (unless the compiler can see the mismatch for a
hinted parameter or initialiser).
Scoping rules
Function scope
Variables declared in a function are local to it, and parameters are local copies:
fn bump(n) {
n = n + 1
return n
}
let v = 1
print(bump(v))
print(v)
2
1
Arrays and objects are passed by reference, so a function can mutate its argument in place:
fn add_nine(items) {
items.push(9)
}
let xs = [1]
add_nine(xs)
print(xs)
[1, 9]
Using a function’s local outside it is a compile error:
fn example() {
let x = 10
print(x)
}
example()
print(x)
Module-level variables are not visible inside functions
Top-level statements form the program’s entry body, not a shared global scope. A function cannot read a variable declared at the top level — pass it as an argument:
let LEVEL = "production"
fn get_level() {
return LEVEL
}
print(get_level())
let level = "production"
fn describe(l) {
return "running in " + l
}
print(describe(level))
running in production
(If you need shared state across functions today, thread it through parameters, or keep it in an object/array you pass around.)
This applies to named functions. A lambda written at the top level does see top-level variables: it captures them (see Closures).
let level = "production"
let report = || "running in " + level
print(report())
running in production
Block scope
A name first declared inside an if, while or for body is not visible after
the block ends. A for loop variable is likewise local to the loop:
if true {
let y = 2
}
print(y)
for i in 0..3 {
print(i)
}
print(i)
Shadowing
Across functions a local simply hides nothing — each function has its own variables:
let x = 10
fn show() {
let x = 20
print(x)
}
show()
print(x)
20
10
Within one function, re-declaring an outer name inside a block is not a
shadow limited to that block: after the block, the name x means the new
binding for the rest of the function. So this program prints 2:
let x = 1
if true {
let x = 2
}
print(x)
2
Each let still creates a fresh binding, which only shows when a closure
captured the earlier one: it keeps seeing the old variable.
let x = 1
let get = || x
if true {
let x = 2
}
print(x)
print(get())
2
1
Choose distinct names for inner variables rather than relying on shadowing.
Exporting a variable
export name marks an already-declared variable or function for export. See
Syntax; importing it from another file is not
possible yet (crush-ast CRUSH-110).
Best practices
- Initialise at declaration and keep scopes narrow.
- Pass state explicitly: functions can’t see top-level variables.
- Prefer new names over shadowing.
Next Steps
Operators
Open as a notebook (.crush-nb, how to run it)
Crush’s operators are deliberately few.
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Arithmetic
| Operator | Meaning | Example |
|---|---|---|
+ | add / string concatenation | 5 + 3, "a" + "b" |
- | subtract / unary negate | 10 - 4, -x |
* | multiply | 6 * 7 |
/ | divide (Int / Int truncates toward zero) | 20 / 4, -7 / 2 |
% | remainder | 17 % 5 |
print(5 + 3)
print(10 - 4)
print(6 * 7)
print(20 / 4)
print(17 % 5)
print(-7 / 2)
print(-(3 + 2))
8
6
42
5
2
-3
-5
Mixing Int and Float promotes to Float (1 + 2.5 is 3.5). + between a
string and a number concatenates ("n=" + 5 is "n=5"); * on a string does
not repeat it.
There is no exponent operator (**), floor-division (//), or compound
assignment (+=, -=, …) — use math.pow(a, b) (standard library) and
x = x + 1. See Variables.
Int overflow is a runtime error (arithmetic overflow), never a silent wrap,
and so is division by zero, for Float as well as Int.
Comparison
==, !=, <, >, <=, >= return Bool. Operands must be of compatible
types; comparing a string with an int is a compile error. Strings compare
lexicographically; arrays compare element-wise with ==.
let a = 10
let b = 20
print(a == b)
print(a != b)
print(a < b)
print(a >= b)
print("apple" < "banana")
print([1, 2] == [1, 2])
print(1 == 1.0)
false
true
true
false
true
true
true
Logical
Logic uses &&, ||, !, or the keyword spellings and, or, not (they
are the same operators). && and || short-circuit (crush-ast CRUSH-125):
fn noisy() {
print("evaluated")
return true
}
print(false && noisy())
print(true || noisy())
print(!(1 > 2))
false
true
true
print(true and false)
print(not false or false)
false
true
Conditions in if/while must be Bool — see Types.
Range
a..b is a half-open range (a inclusive, b exclusive) and a..=b includes
b. Ranges are used by for, and also evaluate to an array of the integers in
the range:
for i in 2..5 {
print(i)
}
let r = 1..5
print(r)
print(1..=3)
2
3
4
[1, 2, 3, 4]
[1, 2, 3]
An empty or reversed range (5..2) produces no iterations. Both bounds may be
expressions: for i in 0..len(items). There is no range() function.
Pipeline
x |> f calls f(x); x |> f(y) calls f(x, y). Chains read left to right.
The right side must be a name: a user-defined function, or a variable holding a
function value such as a lambda (an inline |x| ... literal on the right is a
parse error; bind it with let first):
fn inc(x) {
return x + 1
}
fn dbl(x) {
return x * 2
}
fn add(a, b) {
return a + b
}
let triple = |x| x * 3
print(3 |> inc |> dbl)
print(3 |> add(4))
print(3 |> triple)
8
7
9
Piping into a capability such as str.trim or conv.to_str is rejected
(Pipeline right side must be function); wrap it in a function first:
print(" hi " |> str.trim)
Not available
Bitwise operators (&, ^, ~, <<, >>, and | outside a lambda’s
parameter list) are not part of the Crush language today: they are parse
errors, even though CASM has bit_* opcodes
(CASM reference). There is no ternary
a ? b : c, no null-coalescing ??, and no **.
Precedence (high → low)
| Level | Operators |
|---|---|
| 1 | (), ., [] — call, field access, indexing |
| 2 | unary -, ! |
| 3 | * / % |
| 4 | + - |
| 5 | < > <= >= |
| 6 | == != |
| 7 | && / and |
| 8 | || / or |
| 9 | |> |
print(2 + 3 * 4)
print((2 + 3) * 4)
print(1 + 1 == 2 && 2 * 2 == 4)
14
20
true
Next Steps
Control Flow
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush has if/else, while, for, break/continue, a match expression,
and try/catch/throw. Conditions are type-checked and must be Bool.
If
let score = 85
if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else {
print("C or below")
}
B
if is a statement, not an expression: let y = if c { 1 } else { 2 } is a
parse error. Use a function or match to select a value.
While
let i = 0
while i < 3 {
print(i)
i = i + 1
}
0
1
2
Loop with break
let counter = 0
while true {
if counter >= 3 {
break
}
counter = counter + 1
}
print(counter)
3
For
Over an array
for n in [10, 20, 30] {
print(n)
}
10
20
30
Over a range
a..b is half-open (excludes b); a..=b includes b. There is no range()
function:
for i in 0..3 {
print(i)
}
let items = ["x", "y"]
for i in 0..len(items) {
print(items[i])
}
0
1
2
x
y
for i in 1..=3 {
print(i)
}
1
2
3
Over a string or a map
A string yields its characters; a map yields its keys, in insertion order:
for c in "abc" {
print(c)
}
let ages = {"ada": 36, "alan": 41}
for name in ages {
print(name + " is " + ages[name])
}
a
b
c
ada is 36
alan is 41
The loop variable is a local like any let, so methods work on it:
for s in shapes { print(s.area()) }, or row.push(x) on each row of an array of
arrays. (Before crush-ast #256
such a call was compiled as a capability named s.area and the program was
refused.)
Break and continue
continue skips to the next iteration; break leaves the innermost loop:
for i in 0..5 {
if i % 2 == 0 {
continue
}
print(i)
}
for i in 0..10 {
if i == 3 {
break
}
}
1
3
Match
match selects among arms by comparing a value to literal patterns, with _ as
the wildcard. It is an expression: bind its result with let.
let v = 2
let word = match v {
1 => "one",
2 => "two",
_ => "many"
}
print(word)
two
Supported patterns: integer, string and bool literals, _, a bare identifier
that binds the scrutinee (n => "got " + n), and struct patterns that test a
value’s struct type and bind or compare its fields (Point { x: 0, y: y } => ...,
see Structs, Methods and Kinds). Arm bodies
can be an expression or a { ... } block whose last expression is the value:
let n = 5
let msg = match n {
0 => "zero",
other => "got " + other
}
print(msg)
got 5
match also works as a statement, with arms that only have side effects:
let v = 2
match v {
1 => print("one")
2 => { print("two"); print("still two") }
_ => print("other")
}
two
still two
A match can be returned directly (before crush-ast
#253, return match ... silently
returned null):
fn name(v) {
return match v {
0 => "zero",
_ => "other"
}
}
print(name(0))
print(name(3))
zero
other
Current limitations (alpha):
- A
matchwith no matching arm evaluates tonull; there is no exhaustiveness error. - No guards (
x if x > 3 => ...), no range patterns (0..3 => ...), no alternatives (1 | 2 => ...), no negative or float literal patterns, and no comma after a{ ... }arm body (2 => { 7 }, _ => 0is a parse error; the last three are listed in crush-ast’s CRUSH-192 ticket).
Errors: try / catch / throw
throw raises any value; catch name { ... } receives it. There is no
finally, and the parenthesised form catch (e) is not accepted.
fn divide(a, b) {
if b == 0 {
throw "division by zero"
}
return a / b
}
try {
print(divide(4, 2))
print(divide(1, 0))
print("not reached")
} catch err {
print("Error: " + err)
}
print("done")
2
Error: division by zero
done
A throw crosses function-call boundaries (fixed in crush-ast CRUSH-126),
catch can rethrow, and thrown values can be any type:
try {
try {
throw "inner"
} catch e {
throw "re-" + e
}
} catch outer {
print(outer)
}
try {
throw {"code": 7}
} catch e {
print(e.code)
}
re-inner
7
An uncaught throw ends the program with [runtime] uncaught error: <value>.
What catch catches
try/catch handles values raised with throw, and, since crush-ast
CRUSH-393 (v0.12.0 and later), also runtime faults: division by zero, an out-of-range index, a
runtime type error, a failing host capability (a missing file for fs.read, a
network timeout). The caught value is an error value that prints as
error(<message>):
try {
print(1 / 0)
} catch e {
print("caught: " + e)
}
try {
print([1][3])
} catch e {
print(conv.type_of(e))
}
print("after")
caught: error(division by zero)
error
after
Some failures are not catchable and still end the program even inside try:
running out of a quota (--max-steps, --max-stack, --max-output,
--max-wall-ms, call depth), a capability the run does not grant (refused before
anything runs), sys.exit, an uncaught throw, and a polyglot block that raises:
try {
let i = 0
while true { i = i + 1 }
} catch e {
print("never reached")
}
Next Steps
Functions
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
This chapter covers defining and calling functions. Named functions are top-level declarations, and they are also values: you can store one in a variable, pass it as an argument and return it. Lambdas and closures have their own chapter, Closures and Function Values.
Defining functions
fn greet(name: String) {
print("Hello, " + name + "!")
}
fn add(a: Int, b: Int) -> Int {
return a + b
}
greet("Alice")
print(add(5, 3))
Hello, Alice!
8
- Parameter and return type hints are optional. When present they are checked
at compile time at call sites (
add("x", 1)is a compile error). - The number of arguments is checked at compile time:
add(1)→Function 'add' expects 2 arguments, found 1. - There are no default parameter values (
fn f(x = 1)is a parse error) and no variadic parameters. - A function may be called before its definition appears in the file.
Returning values
Return with return. A function that falls off the end — or uses a bare
return — yields null. A final expression is not an implicit return:
fn check_sign(x: Int) -> String {
if x > 0 {
return "positive"
} else if x < 0 {
return "negative"
}
return "zero"
}
fn log_message(msg: String) {
print("[LOG] " + msg)
}
print(check_sign(5))
print(check_sign(-2))
print(check_sign(0))
log_message("done")
print(log_message("again"))
positive
negative
zero
[LOG] done
[LOG] again
null
The return-type hint is not checked against what the body actually returns
today: fn f() -> Int { return "s" } compiles.
Recursion
fn factorial(n: Int) -> Int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
fn fib(n) {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
print(factorial(5))
print(fib(15))
120
610
Mutual recursion works too. Recursion depth is capped by the VM’s call-depth
quota — 256 frames by default (--max-call-depth N on crush-run); exceeding
it ends the program with call depth quota exceeded. The other default quotas are
1,000,000 instructions (--max-steps), a 4096-slot stack (--max-stack), 1 MiB of
output (--max-output), and a 30-second wall-clock budget for the whole run
(--max-wall-ms).
fn d(n) {
return d(n - 1)
}
print(d(1))
Higher-order functions and lambdas
A function name is a value. Store it, pass it, call it through the variable:
fn double(n) {
return n * 2
}
fn apply(f, x) {
return f(x)
}
let f = double
print(f(21))
print(apply(double, 4))
42
8
Anonymous functions are written |params| expression or |params| { block }:
let double = |x| { return x * 2 }
let add = |a, b| a + b
print(double(21))
print(add(2, 3))
42
5
They capture variables from where they are written; that, and the rules for
calling function values, is in Closures and Function Values. The
built-ins print and len are not values (let g = len is a compile error that
says so, crush-ast #257); wrap them:
|x| len(x).
The pipeline operator (x |> f) takes a function name or a variable holding one:
fn double(n) {
return n * 2
}
fn inc(n) {
return n + 1
}
print(5 |> double |> inc)
11
Concurrency: spawn, yield, async, await
spawn f(args) starts a green task, yield lets other tasks run, and await h
waits for a task and returns its result. They are covered in
Concurrency. In short:
fn worker() {
print("worker")
}
spawn worker()
yield
print("main")
worker
main
Best practices
- Keep functions small and give parameters type hints — they document the interface and catch mistakes at compile time.
- Pass data in as parameters: named functions cannot see top-level variables (Variables); a top-level lambda can.
- Prefer descriptive names (
calculate_total_price, notcalc).
Next Steps
Closures and Function Values
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03). New since the 0.3 line (crush-ast CRUSH-251).
Functions in Crush are values. A named function can be stored, passed and returned; a lambda is a function written inline; and a lambda captures the variables around it, which makes it a closure.
Function values
A function’s name, used without calling it, is a value:
fn double(n) { return n * 2 }
fn apply(f, x) { return f(x) }
fn twice(f) {
return |x| f(f(x))
}
let g = double
print(g(5))
print(apply(double, 21))
let quad = twice(double)
print(quad(3))
10
42
12
Function values go in arrays and maps like anything else, and they print as
<fn name>:
fn double(n) { return n * 2 }
let fs = [double, |n| n - 1]
let first = fs[0]
let second = fs[1]
print(first(10))
print(second(10))
print(first)
20
9
<fn double>
Lambdas
A lambda is |params| expression, or |params| { ... } with a block that uses
return. || is a lambda with no parameters.
let sq = |x| x * x
let add = |a, b| a + b
let clamp = |v| {
if v > 10 {
return 10
}
return v
}
let hello = || "no params"
print(sq(4))
print(add(2, 3))
print(clamp(42))
print(hello())
16
5
10
no params
A let-bound lambda can call itself by name:
let fact = |n| {
if n <= 1 {
return 1
}
return n * fact(n - 1)
}
print(fact(6))
720
Capture
A lambda captures the variables it uses from the function (or top-level script) around it. Capture is by reference: the closure and its surroundings share the variable.
fn make_adder(a) {
return |b| a + b
}
let add3 = make_adder(3)
let add10 = make_adder(10)
print(add3(4))
print(add10(4))
7
14
Because the variable is shared, a closure can keep state, and each call of the factory makes a new variable:
fn make_counter() {
let c = 0
return || {
c = c + 1
return c
}
}
let a = make_counter()
let b = make_counter()
print(a())
print(a())
print(b())
print(a())
1
2
1
3
Writes go both ways: the function sees what the closure wrote, and the closure sees later writes by the function.
fn main() {
let x = 1
let get = || x
let set = |v| {
x = v
}
x = 5
print(get())
set(9)
print(x)
print(get())
}
5
9
9
A top-level lambda captures top-level variables the same way. (A named function can’t see top-level variables at all; see Variables.)
let k = 3
let mul = |x| x * k
print(mul(2))
k = 10
print(mul(2))
6
20
Closures made in a loop
A loop variable is one variable, so closures that capture it all see its last
value (Python’s late binding). A let in the loop body is a fresh binding each
time round, so capture that when you want each closure to keep its own value:
fn main() {
let late = []
let fresh = []
let i = 0
while i < 3 {
late.push(|| i)
let j = i
fresh.push(|| j)
i = i + 1
}
let l0 = late[0]
let f0 = fresh[0]
let f2 = fresh[2]
print(l0())
print(f0())
print(f2())
}
3
0
2
Calling a function value
Any expression that yields a function can be called: an element of an array, a map entry, or the result of another call (crush-ast CRUSH-363; before it, only a name could be called):
let fs = [|x| x + 1, |x| x * 2]
print(fs[0](1))
fn adder(n) { return |x| x + n }
print(adder(10)(5))
2
15
The built-ins (print, len, parallel_map, …) are not function values:
let g = len is a compile error that names the fix, `len` is a built-in, not a function value; wrap it in a lambda: `|x| len(x)` (crush-ast
#257; before, it compiled and
failed at run time). Wrap them in a lambda:
let size = |x| len(x)
print(size([1, 2, 3]))
3
With the pipeline, spawn and parallel_map
The pipeline operator takes any function value bound to a name, and so do
spawn and parallel_map:
let inc = |n| n + 1
print(3 |> inc |> inc)
print(parallel_map([1, 2, 3], |n| n * n))
5
[1, 4, 9]
Engines
Closures run on the CVM1 VM (crush run) and in the browser build. The AOT
backends refuse them by name rather than miscompiling them: crush-aotc reports
the Rust AOT backend cannot compile: `make_closure`. See
Engines and AOT.
Next Steps
- Structs, Methods and Kinds: methods as values (
bound_self) - Concurrency
Structs, Methods and Kinds
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03). New since the 0.3 line:impl,trait,@kindand struct patterns (crush-ast CRUSH-zorro-41/43, the COSM object model).
A struct declares a record type. impl blocks give it methods, traits give
several structs a shared interface with default methods, and @kind(...)
chooses its object semantics (reference or value, how self is bound, how
lookup works). Under the hood each struct is a Kind of COSM, the Crush Object
Semantic Model that crush-ast also uses to lower other languages’ classes; see
crush-ast’s docs/design/object-model.md.
Declaring and building
Write the fields on one line (a struct body spread over several lines is a
parse error today, gap GAP-STRUCT-MULTILINE). Build one with a literal that
names every field, or with new Name() and assign the fields later:
struct Point { x: Int, y: Int }
let p = Point { y: 2, x: 1 }
print(p)
print(p.x + p.y)
p.x = 10
print(p)
let q = new Point()
print(q)
q.y = 5
print(q)
print(q.x)
{y: 2, x: 1}
3
{y: 2, x: 10}
{}
{y: 5}
null
An instance prints like a map, its fields in the order they were first set. A
field not yet set reads as null. Field type hints are not checked at run time.
A literal that misses a field or names an unknown one is a compile error:
struct Point { x: Int, y: Int }
let p = Point { x: 1, z: 2 }
[compile] Parse errors: Unexpected token at line 2, column 15: struct Point has no field `z` (fields: x, y), Unexpected token at line 2, column 15: missing field(s) `y` in Point { ... }
Structs are sealed
Writing a field the struct does not declare stops the program, on every engine:
struct P { x: Int }
let p = P { x: 1 }
print(p)
p.z = 2
print("not reached")
{x: 1}
[runtime] `P` is sealed: it has no field `z` (fields: x)
(@kind(storage: open_dict) makes a struct that accepts extra fields; see
the table below.)
Methods: impl
An impl block attaches methods. self is an explicit first parameter. A
method without self is called through the type, Type::name(...), which is the
convention for constructors; Type::method(value) also calls an instance method
as a plain function.
struct Point { x: Int, y: Int }
impl Point {
fn new(x, y) { return Point { x: x, y: y } }
fn norm2(self) { return self.x * self.x + self.y * self.y }
fn shift(self, d) {
self.x = self.x + d
return self
}
}
let p = Point::new(3, 4)
print(p.norm2())
p.shift(1)
print(p.x)
print(Point::norm2(p))
25
4
32
p.shift(1) changed p itself: by default self is the instance, not a copy.
value.method(...) always resolves on the receiver’s struct, never on a global
function or capability. Calling a method the struct doesn’t have is a run-time
error:
struct S { n: Int }
impl S { fn size(self) { return self.n } }
struct T { n: Int }
let s = S { n: 3 }
print(s.size())
let t = T { n: 1 }
print(t.size())
3
[runtime] `T` has no method `size`
The receiver can be any expression: S { n: 3 }.size() works (it was a parse
error before crush-ast CRUSH-363). A for loop variable is a name
like any other, so for s in items { s.area() } works (it was refused before
crush-ast #256).
Traits
A trait lists method signatures, and may give some of them a default body.
impl Trait for Struct supplies the rest:
struct Square { side: Int }
struct Circle { r: Int }
trait Shape {
fn area(self);
fn describe(self) { return "a shape with area " + self.area() }
}
impl Shape for Square { fn area(self) { return self.side * self.side } }
impl Shape for Circle {
fn area(self) { return 3 * self.r * self.r }
fn describe(self) { return "a circle" }
}
let sq = Square { side: 2 }
let c = Circle { r: 1 }
print(sq.describe())
print(c.describe())
a shape with area 4
a circle
Leaving out a method that has no default is a compile error:
trait T { fn need(self); }
struct S { }
impl T for S { }
[compile] line 3, col 1: `impl T for S` is missing `need`: trait `T` declares it without a default body
impl and trait are only allowed at the top level of a file.
Equality
== on structs compares fields (structural equality). It does not compare
the struct type: two different structs with equal fields are ==, and so is a
plain map with the same entries. @kind(equality: identity) makes == mean “the
same instance”.
struct A { x: Int }
struct B { x: Int }
let a = A { x: 1 }
print(a == A { x: 1 })
print(a == A { x: 2 })
print(a == B { x: 1 })
print(a == {"x": 1})
true
false
true
true
To ask which struct a value is, use a struct pattern.
(conv.type_of reports map for any struct instance.)
Reference and value semantics
By default a struct is a reference: assignment and argument passing share one
instance. @kind(semantics: value(copy)) makes a value type that is copied on
assignment, argument passing and return. x.clone() deep-copies either kind.
@kind(semantics: value(copy))
struct V { x: Int }
struct R { x: Int }
fn bump(v) {
v.x = v.x + 1
return v
}
let a = V { x: 1 }
let b = a
b.x = 2
print(a.x)
let r = R { x: 1 }
let s = r
s.x = 2
print(r.x)
bump(a)
print(a.x)
bump(r)
print(r.x)
let t = r.clone()
t.x = 99
print(r.x)
1
2
1
3
3
Struct patterns in match
A struct pattern tests the value’s struct type first, then compares or binds its
fields. Write field: pattern (there is no { x } shorthand); patterns nest:
struct P { x: Int }
struct Q { x: Int }
struct Wrap { inner: Int }
fn describe(v) {
match v {
Wrap { inner: P { x: a } } => { return "wrap of P " + a }
P { x: 1 } => { return "P one" }
P { x: a } => { return "P " + a }
Q { x: b } => { return "Q " + b }
_ => { return "something else" }
}
}
print(describe(P { x: 1 }))
print(describe(P { x: 5 }))
print(describe(Q { x: 5 }))
print(describe(Wrap { inner: P { x: 2 } }))
print(describe(42))
P one
P 5
Q 5
wrap of P 2
something else
So unlike ==, a pattern does distinguish P { x: 5 } from Q { x: 5 }. A
pattern naming a struct that isn’t declared is a compile error (no struct Nope is declared, so no value can match it).
@kind: choosing object semantics
@kind(key: value, ...) written directly before a struct picks a strategy for
each aspect of the type. Unset keys keep Crush’s defaults (in bold). An unknown
key or value is a compile error that lists the valid ones.
| Key | Values | What it controls |
|---|---|---|
storage | sealed, open_dict, open_dict_with_slots | whether undeclared fields may be added |
semantics | reference, value(copy), value(move), value(clone_explicit) | sharing vs copying on assignment |
receiver | dynamic_this, bound_self, bound_cls, explicit_value, explicit_ref, explicit_ref_mut | what self is, and what obj.method (unbound) gives |
construct | literal, ctor(f), js_new(f), py_new_init(init) / py_new_init(new, init) | what Name(args) does |
resolution | none, single, c3, prototype_chain, embedding_promotion | how methods are looked up through parents |
parents | a list of structs, [Base, Mixin] | the inheritance graph for resolution |
equality | identity, structural | what == compares |
These are the object models of the languages crush-ast lowers (Python classes,
JS objects, Rust and Go values), which Crush can write directly. Strategies no
engine runs yet are refused at compile time rather than half-implemented:
resolution: embedding_promotion (Go’s embedding) gives struct `Z` declares `@kind(resolution: embedding_promotion)`, which no engine runs yet.
A constructor (construct: ctor(init)) runs init on a new instance when the
struct is called like a function. (crushc and crush build accept it too
since crush-ast #260; before, they
rejected it with Undefined function: Acc.)
@kind(construct: ctor(init))
struct Acc { total: Int }
impl Acc {
fn init(self, start) { self.total = start }
fn add(self, n) {
self.total = self.total + n
return self
}
}
let a = Acc(10)
a.add(5)
print(a.total)
print(a)
15
{total: 15}
Multiple inheritance with a C3 method resolution order (Python’s):
@kind(resolution: c3)
struct Base { }
impl Base {
fn who(self) { return "base" }
fn hello(self) { return "hello from base" }
}
@kind(resolution: c3, parents: [Base])
struct Left { }
impl Left { fn who(self) { return "left" } }
@kind(resolution: c3, parents: [Base])
struct Right { }
impl Right {
fn who(self) { return "right" }
fn only_right(self) { return "right only" }
}
@kind(resolution: c3, parents: [Left, Right])
struct Bottom { }
let b = Bottom { }
print(b.who())
print(b.only_right())
print(b.hello())
left
right only
hello from base
Bound methods: with receiver: bound_self, reading c.inc (without calling it)
gives a function value bound to c. With the default receiver it gives the plain
function, which takes the instance as its first argument:
@kind(receiver: bound_self)
struct Counter { n: Int }
impl Counter {
fn inc(self) {
self.n = self.n + 1
return self.n
}
}
struct P { x: Int }
impl P { fn get(self) { return self.x } }
let c = Counter { n: 0 }
let f = c.inc
print(f())
print(f())
print(c.n)
let p = P { x: 7 }
let g = p.get
print(g(p))
1
2
2
7
Open storage accepts fields the struct doesn’t declare:
@kind(storage: open_dict)
struct O { x: Int }
let o = O { x: 1 }
o.extra = 2
print(o)
{x: 1, extra: 2}
Engines
Structs, impl, traits and every @kind above run on the CVM1 VM (crush run,
the portable VM and the browser build). The AOT backends build sealed structs
(and enforce the seal) but refuse method calls by name, e.g. the Rust AOT backend cannot compile: `call_member`; see Engines and AOT.
Next Steps
Modules, Packages and Visibility
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03). Every behaviour on this page was run with that build. The programs live in the verified corpus,examples/verified/modules/, each with the modules it imports in aNAME.files/directory beside it, andscripts/verify-examplesre-runs them.
A Crush program can be split over several files. import loads another .crush
file at compile time (crush-ast CRUSH-110): the compiler parses it and merges
its definitions into the program before checking it, so imported functions are
checked like your own, and the capability check sees imported code exactly as if
it were local. Nothing is loaded at run time, and no capability is involved.
Because an import needs a file to search from, it works when you compile or run a
file (crush run, crush-run run, crushc, crush-debug, the REPL from its
working directory). It does not work in the browser: the Run buttons in this book
compile a string, and an import there is refused with “import x was not
resolved: … this compile has no file path to search from”. The examples on this
page are therefore shown, not runnable; their output is the corpus’s.
The three forms
Given geom.crush and util/strings.crush next to the program:
// geom.crush
fn area(w, h) { return w * h }
fn scaled(x) { return __unit() * x }
fn __unit() { return 10 }
// util/strings.crush
fn shout(s) { return str.to_upper(s) + "!" }
fn twice(s) { return s + s }
import geom
import util.strings as s
import util.strings { twice }
print(geom.area(3, 4))
print(geom.scaled(2))
print(s.shout("hi"))
print(twice("ab"))
let f = geom.area
print(f(2, 5))
12
20
HI!
abab
10
| Form | Binds | Call |
|---|---|---|
import geom | the qualifier geom (the last segment of the path) | geom.area(3, 4) |
import util.strings | the qualifier strings; loads util/strings.crush | strings.shout("hi") |
import util.strings as s | the qualifier s instead | s.shout("hi") |
import util.strings { twice } | the bare name twice (and the qualifier only when as x is also given) | twice("ab") |
geom.area without a call is a function value, as for a local function. Inside a
module, a bare call finds the module’s own functions first (scaled calls
__unit above), then the module’s own imports, then the built-ins and
capabilities.
What a module may contain
A module is definitions only: fn, struct, impl, trait (with @kind),
and imports of other modules. Its main, if it has one, is ignored. Any other
top-level statement is a compile error naming the file and line, so a module has
no init code and there is no hidden init order. Write a function for a constant
(fn limit() { return 10 }):
[compile] state.crush:2:1: a top-level `let` in imported module `state`: a module may only define functions, structs, impls and traits, and import other Crush modules — it has no init code (move the statement into a function)
export is such a statement too: a module that contains export f is refused
(a top-level statement in imported module). Exporting is not how modules work
in Crush; see Visibility for what decides what another file
can call.
Imports go at the top level of a file. One inside a function, fn main
included, is refused (`import` inside `fn main`: imports go at the top level of a file; corpus modules/import-in-main). Up to v0.11 an import inside fn main
was accepted; it is an error since v0.12.0.
Where modules are found
import a.b looks for a/b.crush, in this order; the first hit wins:
- the directory of the file that contains the
import; - each
-L DIR(--lib-path) given tocrush-run,crushc,crush-debugorcrush-repl(crush runand friends pass it on), in order; - each directory in
CRUSH_PATH(colon-separated).
There is no a/b/mod.crush form. A module that is not found is a compile error
that lists every directory searched:
[compile] main.crush:1:1: `import consts`: module not found — no consts.crush in any of:
. (/home/me/proj)
libdir (/home/me/proj/libdir)
crush-run run -L lib main.crush # lib/text/greet.crush for `import text.greet`
CRUSH_PATH=shared crush-run run main.crush # shared/consts.crush for `import consts`
(Corpus: modules/lib-path, modules/crush-path, modules/import-not-found.)
Each file is loaded once per compile, so two modules that import a third share one
copy. Two modules that import each other are a compile error that shows the cycle
(import cycle: ca.crush → cb.crush → ca.crush).
Errors that name the problem
A name the module does not define lists what it does define (names starting with
__ are left out of the list):
[compile] main.crush:5:7: `geom.perimeter`: module `geom` (geom.crush) defines no function `perimeter` (it defines: area, scaled)
A selectively imported name that collides with a function of the importing file is refused, naming both:
[compile] main.crush:3:1: `import geom { area }` collides with `fn area` (line 4) of the same name in this file
Structs across files
A module’s structs and their methods work in the importer. Build values through
a function of the module: a struct literal is recognised only in the file that
declares the struct, so Rect { w: 1, h: 2 } in the importer is
[compile] Undefined variable: Rect.
// shapes.crush
struct Rect { w: Int, h: Int }
impl Rect {
fn area(self) { return self.w * self.h }
}
fn rect(w, h) { return Rect { w: w, h: h } }
import shapes
let r = shapes.rect(2, 3)
print(r)
print(r.area())
r.w = 10
print(r.area())
{w: 2, h: 3}
6
30
Fields are public: the importer can read and write them (r.w = 10 above).
One namespace for struct and trait names
Function names are qualified by their module, but struct and trait names are
one global namespace across all the files of a program. The same name declared
in two files, whether two modules or a module and the file that imports it, is a
compile error that names both files (crush-ast #527):
// plane.crush
struct Point { x: Int, y: Int }
fn origin() { return Point { x: 0, y: 0 } }
// map.crush
struct Point { lat: Float, lon: Float }
fn here() { return Point { lat: 27.7, lon: 85.3 } }
import plane
import map
print(plane.origin())
[compile] map.crush:1:1: struct `Point` is also declared in plane.crush:1:1: struct and trait names are one global namespace across imports, so two files cannot both declare `Point` (rename one; per-module Kinds are planned, #523)
Before #527 this compiled, the later Point silently replaced the earlier one,
and plane.origin() failed at run time. Rename one of the two. A redeclaration
inside a single file is not covered by this rule. Per-module kind names are
planned (crush-ast #523).
Packages
crush-pkg (crush-ast’s package manager) builds a package from a capsule.toml.
crush-pkg new NAME scaffolds an application, crush-pkg new NAME --lib a library
whose entry is src/lib.crush. A package lists its dependencies as
[[dependencies]] rows with a path (a local directory) or a git source:
[capsule]
name = "app"
version = "0.1.0"
entry = "src/main.crush"
language = "crush"
[[dependencies]]
name = "mathlib"
path = "../mathlib"
When the entry file has an import, every dependency, and the package itself,
can be imported by name (crush-ast CRUSH-367): import mathlib loads the
dependency’s entry file, and import mathlib.extra loads extra.crush in the
directory of that entry. The entry’s own directory (src/) is searched for the
package’s other files, as for any file. A package name wins over a file of the same
name on the search path.
// app/src/main.crush
import mathlib { greet } // ../mathlib/src/lib.crush
import mathlib.extra // ../mathlib/src/extra.crush
import util // src/util.crush
fn main() {
print(greet("app"))
print(extra.twice(21))
print(util.shout("ok"))
}
$ crush-pkg run
building app v0.1.0
resolved dep mathlib -> …/mathlib/src/lib.crush
…
running app v0.1.0
hello, app
42
ok!
This was run by hand at the pinned commit (the corpus runs crush-run only), with
mathlib/src/lib.crush as crush-pkg new mathlib --lib writes it
(pub fn greet(who) { return "hello, " + who }; the scaffold marks it pub since
v0.12.0, see Visibility), mathlib/src/extra.crush defining
twice, and app/src/util.crush defining shout. Package names resolve only
through crush-pkg: crush-run run src/main.crush in the same directory says
`import mathlib`: module not found. An entry file with no import at all is
built the older way, with the dependencies’ entry files pasted into one source.
Dependencies of dependencies
Since v0.13.0 (crush-ast #613) crush-pkg follows each dependency’s own
[[dependencies]] (path or git) recursively into one graph. With app depending on
mid and mid depending on base, only app/capsule.toml needs the mid row:
$ cd app && crush-pkg run
building app v0.1.0
resolved dep mid -> /tmp/tp/app/../mid/src/lib.crush
resolved dep base -> /tmp/tp/app/../mid/../base/src/lib.crush
compiled /tmp/tp/app/src/main.crush -> 3 function(s), 47 byte(s)
deps: mid, base
wrote /tmp/tp/app/target/app.cvm1
wrote /tmp/tp/app/target/app.casm
running app v0.1.0
hello, app!
hello, direct
(mid/src/lib.crush has import base { greet } and pub fn shout(who) { return greet(who) + "!" };
app/src/main.crush has import mid { shout } and import base { greet } and prints
shout("app") and greet("direct").) The graph is flat: app can import base
directly, although it does not list it. Two cases are refused:
crush-pkg[E-BUILDER]: dependency cycle detected: mid -> base -> mid
crush-pkg[E-BUILDER]: dependency 'base' conflict: 'mid' requires path /tmp/tp/base but 'app' requires path /tmp/tp/base2
(a cycle, and the same dependency name required from two different sources, tags
or revisions). Run by hand with crush-pkg built from v0.13.0; as with the rest of
this section, the corpus cannot re-check it.
Visibility and pub
Visibility is per package (crush-ast #519, since v0.12.0). A package is a property of the file, not of how it was imported: the longest of these roots that contains the file’s real path.
- the root package: the directory of the file you run, and everything under it;
- each crush-pkg package (a dependency’s own directory);
- each
-L/CRUSH_PATHdirectory: one package per directory.
So main.crush and a sibling util.crush share a package, and a library found
through -L lib is another one.
- Without
pub, a function is visible to every file of its own package. pub fn(andpub async fn) exports it to other packages.- Inside one package
pubchanges nothing, so a function withpuband one without behave the same for a sibling file (corpusmodules/pub-fn).
pub fn add(a, b) { return a + b }
fn sub(a, b) { return a - b }
print(add(2, 3))
print(sub(2, 3))
5
-1
// shapes.crush, next to this file, has `pub fn square(n)` and plain `fn cube(n)`:
// the same package, so both are callable
import shapes
print(shapes.square(3))
print(shapes.cube(2))
9
8
Using a private function from another package
A use of a function that is not pub, from another package (q.f(…), a reference
q.f, import q { f }), is the warning W-VIS01. It goes to stderr, and the
program compiles and runs exactly as before (corpus modules/pub-cross-package: a
library under -L lib with pub fn square, pub fn use_cube and a private
fn cube, used from the program). The compiler prints:
[warning] [W-VIS01] m1.crush:4: `cube` is not `pub` in lib/shapes/shapes.crush, so it is private to the library directory lib; this use (the call `shapes.cube(…)`) is in the root package
hint: add `pub` to `fn cube` in lib/shapes/shapes.crush if other packages may use it (this warning becomes an error before 1.0, #524)
lib/shapes/shapes.crush has a `pub`, so the names it does not mark are private to the library directory lib: cube, twice_square (`pub`: square, use_cube)
and the program’s stdout is still 9, 8, 8. crushc -C --deny-warnings fails
on W-VIS01; crush-run has no such flag, so its run goes on.
Two more diagnostics:
N-VIS01, a note: a module with nopubanywhere stays all-public (the legacy rule, so old libraries keep working) and gets one note when another package uses it (corpusmodules/pub-legacy). As soon as the module marks one functionpub, the others are private.W-VIS02:pub fn __x. The__prefix says “internal”,pubsays “exported”, so it is flagged. A leading__is otherwise only a naming convention: it hides the name from the “it defines: …” lists in error messages (corpusmodules/private-convention).
pub struct, pub trait, and what pub does not cover
pub struct and pub trait parse and run (they were Undefined variable: pub
before v0.12.0; corpus modules/pub-struct, modules/pub-trait). pub is still a
contextual word, not a keyword: it means something only in front of fn,
async fn, struct and trait.
- Only functions are checked. Kind (
struct/trait) names stay one global namespace and are not visibility-checked yet (crush-ast #523). - Fields cannot be marked
pub:struct P { pub x: Int }is a parse error (Expected `}` but found `x`), becausepubis read as a field name with no type.struct P { pub: Int }is legal and declares a field calledpub. Member visibility is crush-ast #525; fields are writable from anywhere.
The stage-2 gate for library authors
If you publish a library, check that it has no hidden reliance on the legacy rule:
-
crushc --list-exports FILE|DIRlists each module’spuband private names, orlegacy: no pub, everything public:lib/legacy/legacy.crush: legacy: no pub, everything public public: area lib/shapes/shapes.crush: pub pub: square, use_cube private: cube, twice_square -
crushc -C --deny-legacy-visibility [-L DIR] FILEturnsW-VIS01into an error and a used legacy module intoE-VIS01(exit 1); with--list-exportsit fails on every importable legacy module.crush-pkg build --deny-legacy-visibilitydoes both for a package.crush-pkg new --libscaffolds apub fn greet, so a new library passes it.
Before 1.0 (feature freeze 2026-12-31) the legacy rule is to end and W-VIS01 to
become an error (crush-ast #524; both are still warnings and notes at v0.13.0). Mark
every function other packages should call with pub now.
Remote imports and other forms
import @http "…", import @git "…", import @file "…" and use @mcp "…" are
compile errors: they are not supported yet. use @lang python "math" is a
different thing that works: it writes import math into every later @python
block (see Polyglot). See Import Styles
for each form with its current result.
Concurrency
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03). New since the 0.3 line (crush-ast #161, #174/#177, #175, CRUSH-251 step 5).
Crush has two kinds of concurrency:
- Green tasks:
spawn,yield,awaitandasync fn. Tasks run inside one VM, take turns atyield/await, and share the variables they capture. parallel_map(items, f): real parallelism for pure computation. Each item runs in its own share-nothing VM (a thread on the native VM).
spawn, yield, await
spawn f(args) starts a task and returns a handle; await h waits for the task
and gives its return value; yield lets the other tasks run.
fn worker(name, n) {
let i = 0
while i < n {
print(name + " step " + i)
yield
i = i + 1
}
return name + " done"
}
fn main() {
let a = spawn worker("a", 2)
let b = spawn worker("b", 2)
print(await a)
print(await b)
}
a step 0
b step 0
a step 1
b step 1
a done
b done
spawn takes any function value, including a closure. A spawned closure shares
the variables it captured with the function that made it, so the main task sees
its writes:
fn main() {
let n = 0
let inc = || {
n = n + 1
return n
}
let h = spawn inc()
await h
print(n)
}
1
An async fn runs as a task when called; await its result:
async fn sub(a, b) {
return a - b
}
fn main() {
let r = await sub(10, 3)
print(r)
}
7
Calling it without await gives the handle itself (it prints as <handle 1>).
When the program ends
The program ends when the main task ends, as in Go: a spawned task that has not
run by then is abandoned. Give it a chance with yield, or await it.
fn worker() {
print("worker")
}
fn main() {
spawn worker()
print("main ends")
}
main ends
await on a value that is not a task handle gives the value back, as in JavaScript:
let v = await 5 sets v to 5. (crush-ast builds before
#265 gave null; see
#251.)
parallel_map
parallel_map(items, f) calls f on every item, each in its own VM, and returns
the results in input order. Anything the workers print also comes out in input
order:
fn fib(n) {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
fn main() {
print(parallel_map([1, 2, 3, 4], |n| n * n))
print(parallel_map([10, 15, 20], fib))
let k = 10
let r = parallel_map([3, 1, 2], |x| {
print("item " + x)
return x * k
})
print(r)
}
[1, 4, 9, 16]
[55, 610, 6765]
item 3
item 1
item 2
[30, 10, 20]
Workers share nothing: each gets its own copy of the item and of anything it captured. A worker may read a captured variable but not change it, because the change would be lost, so that is an error:
fn main() {
let total = 0
parallel_map([1, 2], |x| {
total = total + x
return x
})
print(total)
}
[runtime] parallel_map: item 0: parallel_map: the function changed something it captured (a variable it or a function it calls captured, or a captured array/map); a parallel_map worker shares nothing, so the change would be lost — return the value instead
If several items fail, the first failing item in input order is reported:
fn main() {
print(parallel_map([2, 0, 1, 0], |x| 10 / x))
}
Engines
The native VM (crush run) runs tasks and parallel_map workers; the portable
VM (the browser build) runs the same programs with the same output, running
parallel_map items one after another. The AOT backends refuse spawn by name
instead of dropping it: `spawn` (green tasks) isn't supported on the Rust AOT backend yet (#161). See Engines and AOT.
Next Steps
Capability System
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush programs can’t touch the outside world directly. Every interaction with the host — printing, reading a file, making an HTTP request, spawning a process, running another language — is a capability call, and a capability only exists if the host that is running the program has explicitly turned it on. There is no ambient authority.
Status: alpha. The model below is real and enforced, but the set of capabilities is small and the permission granularity is coarse (on/off per group, with a directory root for the filesystem). Read What is not enforced before relying on it for isolation.
Calling a capability
A capability call looks like an ordinary dotted function call — no @ prefix:
io.print("Hello, ", "Crush")
let upper = str.concat("a", "b")
print(upper)
Hello, Crush
ab
io.print(a, b, ...) takes any number of arguments, joins them with no
separator, and appends a newline. The built-in print(x) takes exactly one.
(The @ sigil exists in Crush, but it introduces polyglot blocks and
annotations, never capability calls — see Syntax.)
Always available
These work with no flags:
| Capability | Description |
|---|---|
io.print(...) | print to stdout |
io.read() | read one line from stdin (empty string at EOF) |
str.concat(...), str.len(s) | concatenate / byte length |
conv.chr(n), conv.ord(s) | codepoint ↔ one-character string |
print(conv.chr(65))
print(conv.ord("A"))
print(str.len("héllo"))
A
65
6
io.read reads a line from standard input. On this page, Run asks you for each
line; type Ada to get the output below:
let name = io.read()
io.print("Hello, " + name)
Hello, Ada
Enabling more capabilities
With the CLI, each group of capabilities is switched on by a flag on
crush-run run (or crush run). Anything not switched on is simply not
registered. Before running anything, crush-run works out every capability the
compiled program can reach and refuses the whole run if one isn’t granted, listing
the flag that would grant each:
| Flag | Capabilities enabled |
|---|---|
| (none: on by default) | the standard library: str.*, math.*, conv.*, collections.*, json.*, path.*, regex.*, bytes.*, buffer.*, binary.*, result.*, time.format/parse, env.os/arch, system.*, plus sys.args() / sys.exit(code); pure computation, see Standard Library. --no-stdlib removes it |
--fs | fs.read, fs.write, fs.exists, fs.list, fs.ls/cat/pwd/cd/mkdir/rm/cp/mv/touch/find, text.head/tail/wc/cut/grep |
--env | env.get, env.all, env.home_dir |
--time | time.now, time.now_ms, time.now_iso, time.elapsed, time.sleep, async.sleep |
--net | net.http_get, net.http_post, net.http_put, net.http_delete, net.http_request (HTTP only) |
--tcp | raw TCP client sockets: tcp.connect, tcp.tls_wrap, and tcp.send, tcp.recv, tcp.close, tcp.ping on the connections you hold; see Raw sockets |
--tcp-listen | raw TCP server sockets: tcp.listen, tcp.accept, and the same send/recv/close/ping; does not allow tcp.connect |
--ui | ui.*, only with crush gui run; see Windows |
--process | process.exec |
--crypto | crypto.sha256, crypto.random |
--db PATH | db.query, db.execute on that SQLite file |
--graphics | graphics.canvas/rect/circle/text/to_svg |
--bus | message_bus.publish/subscribe/recv |
--task | task.start/stop/list |
--akg | akg.write/read/search |
--polyglot | @python { }, @javascript { }, @bash { } blocks — see Polyglot |
crush-run caps prints the list for your build. Some groups (--db, --graphics,
--gpu) are Cargo features of crush-lang-sdk that a default build leaves out;
the standard library, the HTTP client (net.*, since 0.9.0) and the raw sockets
(tcp.*) are default features, which only compiles them in: a program that uses
them is still refused until you pass the flag.
The old HTTP names http.get, http.post, http.put, http.delete and
http.request are refused by name, with the replacement. This run is refused
before anything executes, with or without --net:
let r = http.get("http://example.com/")
print(r)
[capabilities] block.crush needs capabilities this run does not grant; nothing was run:
http.get was renamed to net.http_get (grant it with --net)
Without the flag, nothing runs, not even the first line:
print("first line")
print(fs.read("data.txt"))
[capabilities] block.crush needs capabilities this run does not grant; nothing was run:
--fs: fs.read
crush-run caps FILE answers the same question without running: what the
program can use, and which flag grants each.
With it, and with the filesystem confined to a directory:
print(fs.read("../outside.txt"))
Filesystem paths must be relative and resolve inside --fs-root (default .):
absolute paths and .. escapes are rejected. This is the one place the permission
has a scope.
Filesystem
print(fs.exists("missing.txt"))
0
| Capability | Arguments | Returns |
|---|---|---|
fs.read | path | file contents (string) |
fs.exists | path | 1 / 0 |
fs.list | dir | array of names |
fs.write | path, data | nothing |
fs.mkdir | path | nothing |
fs.write("out.txt", "hello")
print(fs.read("out.txt"))
fs.mkdir("sub")
fs.write("sub/a.txt", "a")
print(fs.list("sub"))
hello
[a.txt]
Environment, time, processes, network
print(env.get("CRUSH_GUIDE_DEMO_UNSET"))
print(time.now() > 0)
let r = process.exec("echo", "hi")
print(r.exit_code)
print(str.trim(r.stdout))
null
true
0
hi
env.get(name)→ string, ornullif unset.time.now()Unix seconds;time.now_ms();time.now_iso();time.sleep(ms)(bounded by the wall-clock budget,--max-wall-ms).process.exec(cmd, args)— exactly two arguments (the command and one argument string) — returns a map{exit_code, stdout, stderr}(crush-ast CRUSH-242; before 0.11 it was a JSON string). A command that cannot start is not an error:exit_codeis-1andstderrsays why.net.http_get(url)/net.http_post(url, body)— response body as a string; size capped by--net-max-response-bytes(default 1 MiB). Eachnet.*verb takes an optional last argument{timeout_ms: N}; a request that takes longer fails with a catchable error (… timed out after N ms).net.http_request(method, url, body, headers)returns{status, reason, headers, body}, with the response header names lower-cased (crush-ast #509).
let r = net.http_request("GET", "http://127.0.0.1:47125/hi.txt", "", {})
print(r.status)
print(r.headers["content-type"])
try {
print(net.http_get("http://127.0.0.1:47126/", {timeout_ms: 300}))
} catch e {
print(e)
}
200
text/plain
error(net.http_get: net.http_get http://127.0.0.1:47126/: timed out after 300 ms)
(Run by hand at the pinned commit, with python3 -m http.server 47125 serving a
hi.txt and a listener on port 47126 that accepts and never answers.)
crypto.sha256(data),crypto.random(n)(base64,n ≤ 4096).
Raw sockets (tcp.*)
Since 0.9.0 a program can open TCP connections directly. --net is HTTP only and
does not grant these; the socket flags are separate, and the server flag is a
stronger grant than the client flag because it makes the program reachable from
other hosts:
| Flag | Lets the program |
|---|---|
--tcp | tcp.connect(uri) outbound; tcp.tls_wrap(conn) upgrades a connection to TLS |
--tcp-listen | tcp.listen(uri) and tcp.accept(listener); it does not allow tcp.connect |
| either | tcp.send(conn, text), tcp.recv(conn), tcp.close(conn), tcp.ping(conn) on a connection id it already holds |
A URI is tcp://IP:PORT with a literal IP address (no host names). tcp.listen
and tcp.connect return an integer id; tcp.accept blocks until a client
connects. tcp.send takes text (or bytes) and returns the byte count. tcp.recv
returns what one read delivered, at most 16 KiB, as text; an incomplete UTF-8
character at the end is held back and returned by the next call, so a message can
arrive over several calls: loop until you have all of it (a delimiter, a length, or
"", which tcp.recv returns only at end of stream). tcp.recv and tcp.accept
take an optional {timeout_ms: N}; a timeout is a catchable error, and a timed-out
tcp.recv loses nothing (crush-ast #512). This program is both ends of a conversation, so it needs both
flags (the connect is queued by the kernel before accept takes it):
let srv = tcp.listen("tcp://127.0.0.1:47123")
let c = tcp.connect("tcp://127.0.0.1:47123")
let s = tcp.accept(srv)
tcp.send(c, "ping")
print(tcp.recv(s))
tcp.send(s, "pong")
print(tcp.recv(c))
tcp.close(c)
tcp.close(s)
ping
pong
A tcp.recv that times out can be caught, and the data that arrives later is read
by the next call:
let srv = tcp.listen("tcp://127.0.0.1:47124")
let c = tcp.connect("tcp://127.0.0.1:47124")
let s = tcp.accept(srv)
try {
print(tcp.recv(s, {timeout_ms: 100}))
} catch e {
print("caught: " + e)
}
tcp.send(c, "late")
print(tcp.recv(s))
tcp.close(c)
print(tcp.recv(s) == "")
tcp.close(s)
caught: error(tcp.recv: timed out after 100 ms)
late
true
(The capability name appears twice in that message; it is crush-ast’s text as it stands.)
Granting only --tcp is refused, naming what is missing:
[capabilities] tcp.crush needs capabilities this run does not grant; nothing was run:
--tcp-listen: tcp.accept, tcp.listen
A host capability that fails (missing file, refused connection, path escape)
raises [runtime] <name>: <reason>, for example [runtime] fs.read: fs.read missing.txt: No such file or directory (os error 2). Inside
try/catch it is caught like any other
fault; outside one it ends the program.
Declaring what a program uses: @capabilities
A program can say up front which capabilities it may use beyond the ambient,
effect-free built-ins (io.print, str.*, arrays, the standard library):
@capabilities [time.now_ms]
let t = time.now_ms()
print(t > 0)
true
Entries can be exact names (fs.cat), families (fs, fs.*) or scoped names
(fs.read:/var/log). Using anything else is a compile error, so a reviewer only
has to read that one line to know what the program can touch:
@capabilities [time.now_ms]
print(env.get("HOME"))
[compile] the program uses a capability not declared in @capabilities: env.get
add it to @capabilities, or stop using it
The declaration limits what the program may use; the run’s flags still decide
what it gets. crush-run caps prog.crush prints both:
prog.crush
declares: time.now_ms
needs these grants to run:
--time: time.now_ms
also uses (ambient): io.print
A program without @capabilities compiles as before.
Known bug (crush-ast #258). The check runs when
crush-run run/crush runcompiles a.crushfile.crushcandcrush builddon’t apply it yet, and the.cvm1they write drops the declaration, so review the source, not just the bytecode. (The awesome-crushagents/log-triageentry walks through this with an agent-written tool.)
Resource limits
Separately from capabilities, the VM enforces quotas; exceeding one ends the
program with a [runtime] error:
| Quota | Default | CLI flag |
|---|---|---|
| instructions | 1,000,000 | --max-steps N, or --max-steps unlimited |
| stack slots | 4,096 | --max-stack |
| output bytes | 1 MiB | --max-output |
| call depth | 256 | --max-call-depth |
| wall-clock time for the whole run | 30,000 ms | --max-wall-ms N, or --max-wall-ms unlimited for a long-lived program such as a server (crush-ast #510) |
The wall-clock budget covers the whole run, computation included, so lifting the step limit does not make a runaway loop run forever:
let i = 0
while true { i = i + 1 }
A blocking capability such as time.sleep gets what is left of the budget.
--max-wall-ms 0 is a zero budget, not “no limit”: the run stops at the first
clock check (the VM looks at the clock every 1,024 instructions) or the first
blocking call, so only a very short program still finishes.
Output printed before a run-time failure is kept: the program’s earlier lines
appear, then the [runtime] error on standard error.
Embedding: declaring permissions
When you embed the VM from Rust you choose the capability set yourself
(crush_lang_sdk::HostCaps, Runtime, ProgramBuilder), and a CASM program
names the capabilities it is allowed to call in its manifest — a list of names:
{
"version": "1.0",
"manifest": { "permissions": ["io.print"] },
"functions": { "main": { "params": [], "locals": [], "body": [] } }
}
A capability call whose name is not both registered by the host and listed
in the program’s permissions is refused. See Getting Started
and CASM structure. For assembly text (.cvms) run with crush-run,
--cap NAME adds names to that list.
There is no path or URL scoping in the manifest ("fs.read": ["./data"] is not a
thing): scoping today is the host’s job — e.g. --fs-root.
What is not enforced
Be honest with yourself about the isolation you actually get:
- Polyglot blocks run outside this capability model. With
--polyglot,@python { }/@javascript { }/@bash { }blocks run as ordinary subprocesses with the host process’s authority: a Python block can read any file the user can. Thefs/net/processflags above do not constrain it. An optional build-time sandbox (bubblewrap, viabuckets) exists but is off by default — see Polyglot. - Quotas bound instructions and (for polyglot) wall-clock time, not memory.
process.execruns any command the user can run; only enable it for programs you trust.
Not implemented
The following capabilities appeared in earlier revisions of this guide but do not
exist in the runtime: io.eprint, fs.delete, sys.exec, sys.env,
net.get, net.post, net.http, type.of, console.print,
array.length, map.keys, map.has_key, and module.load (what import
lowers to — crush-ast CRUSH-110). Use the replacements above
(fs.rm, env.get, net.http_get, conv.type_of, len, …). sys.args() and
sys.exit(code) do exist now (ambient).
Next Steps
Polyglot Programming
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03), with Python 3.14, Node 26 and bash 5.3 on the host.
A Crush program can embed code from other languages with @language { ... }
blocks. This chapter describes what actually happens when you run one today —
which languages work, how values cross the boundary, how errors and timeouts
behave, and, importantly, how much isolation you do and don’t get.
Status: alpha, and the security story is the part to read carefully. By default a polyglot block is an ordinary subprocess running with your user’s authority. An optional bubblewrap sandbox exists but is off by default and not enabled by any command-line flag. See Sandbox and authority.
The model in one paragraph
A block’s source text is handed to a real interpreter — python3 -c, node -e,
or bash -c — as a child process. Crush marshals some variables in, runs the
interpreter, captures its standard output, and (for Python and JavaScript)
marshals back the variables the block declares with -> names. There is no embedded WebAssembly runtime, no
WASI capability bridge, and no in-process interpreter.
Languages
| Block | Runs | Aliases |
|---|---|---|
@python { } | python3 -c | @python3, @py |
@javascript { } | node -e | @js, @node, @es6, @ecmascript |
@bash { } | bash -c | @sh |
The interpreter must be on PATH; crush doctor checks which ones it finds. Any
other tag (@rust, @go, @c, …) parses, but the program is refused before it
runs (not available in this host: polyglot.rust).
@rust {
fn main() {}
}
(crush-ast also ships walkers for Rust, Go, C, Zig, Wasm and others. A walker
translates a source file into CAST for compilation — it is a separate
mechanism, driven by the crush-walker tool, and is not what an @lang { }
block does.)
Enabling polyglot execution
Polyglot is off by default, because running another interpreter is full ambient authority. Turn it on per run:
crush run --polyglot program.crush # same flag on crush-run
Without it the program is refused before anything runs (--polyglot: polyglot.python):
@python {
print("hi")
}
An embedding host enables it explicitly with
HostCapsBuilder::polyglot(&["python", "javascript", "bash"]); each language is
gated by its own capability name (polyglot.python, polyglot.javascript,
polyglot.bash).
Output
Whatever the block writes to standard output appears in the program’s output, in order. Two details to know: the block’s output is trimmed (so it carries no trailing newline), and anything written to standard error is discarded when the block succeeds.
print("one")
@python {
print("two")
}
print("three")
one
twothree
If you want the following output on a new line, end the block’s output with an
explicit blank line (print()), or print from Crush.
Passing values in and out
Python and JavaScript
For @python and @javascript blocks:
- In (automatic): every name the block reads that is a Crush variable
already in scope (a
let, a parameter, a loop variable, or an earlier block’s output) is injected as a variable of that name, with its type preserved. - Out (declared): the names after
->in the block header are marshaled back and become (or assign) Crush variables at that line. Nothing else leaves the block. Use-> namefor one and-> (a, b)for several.
let count = 10
let base = 5
@python -> total {
tmp = base * 3
total = tmp * 2
}
print(total)
print(count)
30
10
Here base goes in, total comes out, and tmp stays inside the block (using it
afterwards is a compile error, Undefined variable). JavaScript works the same
way; values travel as JSON:
let n = 5
let tags = ["a", "b"]
@javascript -> out {
const out = [n * 2, tags.length, tags.join("+")]
}
print(out)
[10, 2, a+b]
Several outputs:
let xs = [2, 4, 4, 4, 5, 5, 7, 9]
@python -> (mean, spread) {
mean = sum(xs) / len(xs)
spread = max(xs) - min(xs)
}
print(mean)
print(spread)
5.0
7
Listing a name the block never binds is a compile error; a name bound only on
some paths is a run-time error naming it (output variable 'r' was not bound by the block), never a silent null:
@python -> missing {
x = 1
}
print(missing)
[compile] @python block declares output `missing` but never binds it; add `missing = …` at the block's top level, or drop it from `->`
Everything after the opening { is the guest’s source, including the rest of
the header line, so a Crush // comment there is Python code. With an output list
that syntax error is currently reported as [compile] Undefined variable: m
(crush-ast #266). Put comments
above the block, or use the guest’s own comment syntax inside it.
Blocks without -> (being phased out). A block with no output list still
exports its last top-level assignment, as in earlier releases, but the compiler
now warns on standard error, and warns again if that overwrites an existing Crush
variable. The next release drops the implicit export, so declare your outputs:
warning: @python block exports `count` implicitly; add `-> count` to declare it
warning: @python block overwrites the existing Crush variable `count`; declare `-> count` to make the overwrite explicit
Values travel as JSON, so the shareable types are exactly these:
| Crush | Python | JavaScript |
|---|---|---|
| Int, Float | int, float | number |
| String | str | string |
| Bool | bool | boolean |
| Null | None | null |
| Array | list | Array |
| Object | dict | Object |
let n = 5
let tags = ["a", "b"]
let cfg = {"k": 1}
@python -> out {
out = [n * 2, len(tags), cfg["k"], None, True]
}
print(out)
[10, 2, 1, null, true]
An output variable that can’t be serialised to JSON (a class instance, an open file, a function) fails the block with a clear error rather than being dropped:
@python -> obj {
class C:
pass
obj = C()
}
print(1)
Blocks compose through Crush variables, across languages:
let x = 1
@python -> y {
y = x + 1
}
@javascript -> z {
const z = y * 10
}
@python -> w {
w = z + 1
}
print(w)
21
Blocks inside functions and loops see the enclosing scope:
let total = 0
for i in 0..3 {
@python -> sq {
sq = i * i
}
total = total + sq
}
print(total)
5
Python and JavaScript state does not persist between blocks: each block is a fresh interpreter, and only the declared outputs carry over. You cannot define a function in one block and call it from Crush or from another block.
@python -> a {
a = 1
hidden = 2
}
@python -> r {
r = "hidden" in globals()
}
print(a)
print(r)
1
false
Imports for blocks: use @lang
use @lang python "module" (optionally as alias) writes the import into every
later @python block, so each block doesn’t have to repeat it. Each block is
still its own process:
use @lang python "math"
use @lang python "json" as j
@python -> (val, text) {
val = math.factorial(5)
text = j.dumps({"a": 1})
}
print(val)
print(text)
120
{"a": 1}
Bash
@bash blocks have no value marshaling: only their printed output comes back,
and -> on a @bash block is a compile error (`->` output lists are not supported for @bash: it has no value marshaling).
A @bash block does read Crush variables, by name: every $name or ${name} in the
block that matches a Crush variable in scope is passed to bash as an environment
variable of that name (since 0.9.0; crush-ast
#255). Numbers arrive as their
text. A variable the block does not mention is not passed, and a $name that is not
a Crush variable expands to the empty string, as in any shell:
let name = "crush"
let n = 42
@bash {
echo "hello [$name] n=${n} [$nothing_here]"
}
print("")
hello [crush] n=42 []
Nothing comes back except what the block prints, so to get a value out compute it in
a @python or @javascript block with ->. Bash inherits the host environment
($HOME, $PATH, …) in the default, unsandboxed lane.
Errors
If the interpreter exits non-zero, the program stops with a
LangRuntimeError. The message is the guest’s own stderr, prefixed with the
Crush source line of the block, so a Python traceback is attributed to the
right place in your .crush file:
print("a")
print("b")
@python {
raise ValueError("x")
}
[runtime] @python block raised a runtime error: (at .crush line 3) Traceback (most recent call last):
File "<string>", line 2, in <module>
raise ValueError("x")
ValueError: x
A guest failure is not catchable with Crush try/catch, unlike a VM fault
or a failing capability (Control Flow). Handle expected
failures inside the block (try: / except: in Python) and return a value that
says what happened. Failures to start a sandboxed block — package resolution,
missing bwrap — are reported separately as sandbox setup failed, so a
provisioning problem is never mistaken for a bug in your code.
Timeouts
A block runs under the run’s wall-clock budget: 30 seconds for the whole run by
default (--max-wall-ms, Quotas::max_wall_time_ms), and a block gets what is
left of it. At the deadline the interpreter’s whole process group is killed and the
program ends with:
[runtime] 'polyglot.python' exceeded its 30000ms wall-clock quota and was killed
(crush-ast CRUSH-19; with --max-wall-ms 500 the message says 499ms, the time
that was left when the block started.) crush-run --max-wall-ms N|unlimited sets
the budget (crush-ast #510). In the sandboxed
lane the limit also covers package provisioning. The instruction quota
(--max-steps) does not apply to time spent inside a guest.
Sandbox and authority
Default (no sandbox). A polyglot block is a plain child process of the Crush
runtime and inherits its environment, working directory, user and network. It is
not subject to the capability flags in Capability System:
--fs-root does not confine it, and withholding --net or --process does not
stop a block from opening sockets or running commands. This was verified: with
only --polyglot, a @python block reads /etc/hostname, and a @bash block
runs id and cat.
@python {
host = open("/etc/hostname").read().strip()
}
print(len(host) > 0)
true
Only use --polyglot on programs you trust, in an environment you are prepared
to lose.
Sandboxed lane (opt-in at build time). crush-ast can instead provision the
language runtime with buckets and run the
block under bwrap (bubblewrap) — CRUSH-20, with registry dependencies added in
CRUSH-66. It is gated behind the sandboxed-polyglot Cargo feature of crush-vm,
which is off by default and not re-exported as a crush-lang-sdk feature
(so there is no --features shortcut and no CLI flag). You enable it by building
the workspace with --features crush-vm/sandboxed-polyglot. It needs bwrap
installed and, on first use, network access to download the runtime.
What that lane does (verified against crush-ast 4e9c388):
| Default | Sandboxed | |
|---|---|---|
| interpreter | host’s python3 / node / bash | pinned python@3.11, node@20, bash@5 from buckets |
host files (/etc/hostname) | readable | not visible (FileNotFoundError) |
| network | inherited | blocked (allow_network: false) |
| working directory | inherited | bound read-write |
@lang[deps] | ignored | resolved and bound read-only |
Dependencies go in square brackets after the language tag. Registry specs are
prefixed pypi: or npm:; bare names are buckets package aliases. A bare
numpy is not assumed to mean PyPI.
@python[pypi:six] -> v {
import six
v = six.__version__
}
print(v)
1.17.0
The first run prints buckets’ progress lines (resolved python.org@^3.11 → …) to
standard error while it downloads. In a default build the [...] part still
parses, but the dependencies are silently ignored: import six then works
only if the host’s own Python happens to have six, and an unresolvable
[pypi:nothing_here_xyz] is not reported at all. An unknown package fails with
@python block sandbox setup failed: Failed to resolve version for 'pypi:…'.
Even the sandboxed lane is a first cut: the working directory is writable, memory
is not limited, and only python, javascript and bash are wired up.
Limitations summary
- Languages: Python, JavaScript (Node), Bash. Nothing else executes.
- Value passing is JSON-only, Python/JS only, and outputs are declared with
->. - No shared interpreter state or cross-block function calls.
- Guest errors and timeouts abort the program; they can’t be caught from Crush.
- Default execution is unsandboxed; the sandbox is a build-time opt-in.
Next Steps
- Capability System: what the flags do and don’t confine
- Standard Library
- CAST Specification
Standard Library
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush’s “standard library” is a set of capabilities — dotted functions such
as str.split and math.sqrt — that the host registers. It is not a module
system: there is no import std.io, and import does not load anything yet
(crush-ast CRUSH-110). You call these functions by their full dotted name.
Turning it on
It is on by default (crush-ast CRUSH-113): the stdlib Cargo feature of
crush-lang-sdk is a default feature, and crush-run/crush run register the
library without a flag, because these capabilities confer no authority. They are
pure computation and do no I/O; for files, network, time and processes see
Capability System.
--stdlibis still accepted, for compatibility, and changes nothing.--no-stdlibleaves the library out. A program that uses it is then refused before it runs, withstdlib (default; --no-stdlib): str.to_upper.- A build with
default-features = false(an embedder can choose that) has no library;--stdlibis then an error.
Arguments are positional and the arity is checked ([runtime] str.replace takes 3 arg(s), got 2). Note that some predicates return 1/0 rather than
true/false (for example regex.test and collections.includes), while the
str.contains, str.starts_with and str.ends_with predicates return a Bool
(starts_with / ends_with returned 1/0 before v0.12.0). Test a predicate’s
result as a condition rather than comparing it with == 1 or == true.
Strings — str.*
| Function | Result |
|---|---|
str.split(s, delim) | array of parts |
str.join(array, delim) | string |
str.trim(s), str.trim_start(s), str.trim_end(s) | string |
str.replace(s, old, new) | string |
str.contains(s, sub), str.starts_with(s, p), str.ends_with(s, p) | Bool |
str.to_upper(s), str.to_lower(s) | string |
str.pad_left(s, width, fill), str.pad_right(s, width, fill) | string |
str.repeat(s, n) | string |
str.substring(s, start, end) | string (end exclusive) |
str.char_at(s, i), str.index_of(s, sub) | one-char string / index |
str.format(template, value) | the first {} replaced by value (exactly two arguments) |
str.format(template, args) | {} placeholders filled from args |
str.concat(...) and str.len(s) are always available, even with --no-stdlib.
print(str.split("a,b,c", ","))
print(str.join(["a", "b"], "-"))
print("[" + str.trim(" x ") + "]")
print(str.replace("hello world", "world", "crush"))
print(str.to_upper("abc"))
print(str.pad_left("7", 3, "0"))
print(str.repeat("ab", 3))
print(str.substring("hello", 1, 3))
print(str.index_of("hello", "l"))
[a, b, c]
a-b
[x]
hello crush
ABC
007
ababab
el
2
(Arrays print as [a, b, c] — strings inside an array are shown unquoted.)
Math — math.*
math.sqrt, math.abs, math.floor, math.ceil, math.round, math.sin,
math.cos, math.tan, math.pow(base, exp), math.min(a, b), math.max(a, b),
math.pi(). Results are Float. math.random(), math.random_int(lo, hi)
(requires lo < hi) and math.seed(n) use a deterministic built-in generator
(crush-ast CRUSH-116), so seeded runs are reproducible.
print(math.sqrt(16))
print(math.pow(2, 10))
print(math.floor(-1.5))
print(math.round(3.6))
print(math.max(2.5, 1))
4.0
1024.0
-2.0
4.0
2.5
Conversion — conv.*
conv.to_int, conv.to_float, conv.to_str, conv.to_bool,
conv.parse_int(text, radix), conv.parse_float, conv.type_of, plus the
always-on conv.chr / conv.ord.
print(conv.to_int("42") + 1)
print(conv.to_int(3.9))
print(conv.parse_int("ff", 16))
print(conv.parse_int("101", 2))
print(conv.to_float("2"))
print(conv.type_of(3.5))
43
3
255
5
2.0
float
Collections — collections.*
collections.len, reverse, includes, flatten, chunk(array, n), zip,
unique, all, any, find, sort_by(array, key), pluck(array, key),
and for objects: keys, values, entries, merge.
let scores = {"ada": 3, "grace": 5}
print(collections.keys(scores))
print(collections.values(scores))
print(collections.keys(collections.merge(scores, {"linus": 1})))
print(collections.reverse([1, 2, 3]))
print(collections.chunk([1, 2, 3, 4], 2))
print(collections.unique([1, 1, 2, 2, 3]))
[ada, grace]
[3, 5]
[ada, grace, linus]
[3, 2, 1]
[[1, 2], [3, 4]]
[1, 2, 3]
Objects keep their keys in insertion order: collections.keys(obj),
collections.values(obj), collections.entries(obj), for k in obj and printing
all walk the keys in the order they were first set (not sorted):
let m = {"b": 2, "a": 1}
for k in collections.keys(m) {
print(k)
}
print(collections.entries(m))
b
a
[[b, 2], [a, 1]]
JSON — json.*
json.parse(text) → object/array/scalar; json.stringify(value);
json.stringify_pretty(value).
let o = json.parse("{\"name\": \"Ada\", \"n\": 3}")
print(o.name)
print(o.n + 1)
print(json.stringify({"x": 1}))
Ada
4
{"x":1}
Paths — path.*
path.join(a, b), dirname, basename, extension, stem, is_absolute,
normalize — pure string manipulation, no filesystem access.
print(path.join("a", "b.txt"))
print(path.dirname("/x/y/z.txt"))
print(path.basename("/x/y/z.txt"))
print(path.stem("z.tar.gz"))
print(path.normalize("a/./b/../c"))
a/b.txt
/x/y
z.txt
z.tar
a/c
Regular expressions — regex.*
The pattern comes first, then the text: regex.test(pattern, text),
regex.find_all(pattern, text), regex.replace(pattern, text, replacement),
regex.split(pattern, text).
print(regex.find_all("[0-9]+", "a1b22"))
print(regex.replace("[0-9]", "a1b2", "#"))
print(regex.split("[,;] *", "a, b;c"))
[1, 22]
a#b#
[a, b, c]
regex.match(pattern, s) returns the whole match followed by the groups. (It used
to be a parse error, because match is a keyword; since crush-ast CRUSH-394 a
keyword is accepted as a name after a dot.)
print(regex.match("([a-z]+)([0-9]+)", "abc123"))
[abc123, abc, 123]
Other families
Also in the standard library: bytes.* (from_string, to_string, len,
slice), buffer.* (alloc, read, write, freeze), binary.read_* /
binary.write_* (u16/u32/u64, big/little endian), result.* (ok, err,
is_ok, unwrap — results are plain {ok, value} objects), text.sort,
text.uniq, time.format, time.parse, env.os, env.arch, and the system.*
helpers implemented in Crush itself (crates/crush-lang-sdk/sbl/).
print(result.unwrap(result.ok(5)))
print(result.ok(5))
print(result.is_ok(result.err("no")))
print(str.format("Hello {}!", "World"))
5
{ok: true, value: 5}
false
Hello World!
env.os() and env.arch() return the host’s OS and CPU names (linux,
x86_64), so their output depends on the machine.
Not in the library
There is no std.* module tree, io.eprint, array.length or map.*. For
output use print/io.print; for the process environment use env.get
(--env). Program arguments are sys.args(), an array of what follows the file
name on the command line (crush run prog.crush a b → [a, b]), and
sys.exit(code) stops the program with that exit status.
Next Steps
Annotations
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
An annotation is an @name form written before a declaration (or at the top of
a file). Three kinds exist:
| Annotation | Effect |
|---|---|
@capabilities [ ... ] | enforced: the program may use only these capabilities (plus the ambient ones). See Capability System. |
@kind( ... ) | semantics: chooses the object model of the struct that follows. See Structs, Methods and Kinds. |
@module, @decision, @invariant, @wip, @temporary, @errors | metadata: recorded in the program’s CAST for tools and agents; they do not change what the program does. |
(@python { ... } and the other @lang blocks look similar but are code, not
annotations: see Polyglot Programming.)
Manifest annotations
These describe a module and its decisions in a form an agent can query instead
of parsing comments. Each takes a { key: value } body; @decision and
@invariant also take a name string.
@module {
purpose: "Show the manifest annotations"
exports: [area]
}
@decision "ints-not-floats" {
chose: "integer sides"
over: ["float sides"]
because: "exact output in the docs"
revisit-if: ["we need fractional sizes"]
}
@invariant "area-non-negative" {
description: "area never returns a negative number"
applies_to: [area]
}
@errors {
Overflow: rare
}
fn area(w, h) {
return w * h
}
@temporary {
reason: "demo"
expires-when: "never"
added: "2026-10-16"
}
fn helper() { return 1 }
print(area(3, 4))
print(helper())
12
1
| Annotation | Fields |
|---|---|
@module | purpose, exports, invariants, related |
@decision "name" | chose, over, because, revisit-if |
@invariant "name" | description, applies_to, check |
@wip | intent, done, todo, unresolved |
@temporary | reason, expires-when, added |
@errors | Variant: likely / possible / rare |
@wip marks unfinished work on the next declaration:
@wip {
intent: "parse the config"
done: ["read the file"]
todo: ["validate keys"]
unresolved: []
}
fn parse() { return "partial" }
print(parse())
partial
Hyphenated keys such as revisit-if and expires-when parse (an old crushc
hang on revisit-if, crush-ast #38, is fixed). An @invariant’s check is
stored, not executed. (crushc --invariant-runtime emits calls to an
invariant.evaluate capability at the top of each targeted function, but
crush-run does not provide one, so such a program is refused: not available in this host: invariant.evaluate.)
The AI-native statements
CAST has AI nodes (queries, tool chains, agent delegation, goals, …) for programs
that agents emit as JSON; they are described in AI-Native CAST.
Two of them also have Crush built-ins, ai_semantic_match(text, target, threshold) and ai_synthesize(prompt), which compile to the same
capability-gated call as the CAST SemanticMatch / Synthesize nodes. crush-run
has no AI backend, so such a program is refused before it runs; a host that
provides ai_native.semantic_match can run it:
let m = ai_semantic_match("refund", "billing", 0.8)
print(m)
[capabilities] … needs capabilities this run does not grant; nothing was run:
not available in this host: ai_native.semantic_match
The one AI statement with Crush syntax, semantic_switch, parses but is refused
at compile time, because it would have compiled to a silent no-op (crush-ast
CRUSH-265):
fn route(text) {
semantic_switch text {
case "billing question":
return "billing"
fallback:
return "human"
}
}
print(route("refund please"))
[compile] `semantic_switch` isn't supported yet (CRUSH-265): it would compile to a no-op
Next Steps
Errors and Diagnostics
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
This page is about how the tools report a problem; the language’s own
try/catch/throw is in Control Flow.
Since 0.9.0 crush, crushc and crush-run report problems with one JSON schema,
and a semantic error points at the line and column it is on.
Text (the default)
A mistake the compiler can see is reported before anything runs:
let x = 1
print(y)
[compile] Undefined variable: y
Syntax errors say where the parser gave up:
[compile] Parse errors: Unexpected token at line 1, column 12: unexpected token in expression: newline
JSON: --message-format json
Add --message-format json to crush run, crush-run run, crushc or crush build
and every error is one
JSON object on its own line, for an editor, a language-server bridge or an agent
that should not have to parse prose. Running the program above:
crush-run run e.crush --message-format json
{"code":"E-TP01","level":"error","file":"e.crush","line":2,"col":7,"message":"Undefined variable: y","hint":null}
crushc -C e.crush --message-format json prints the identical record: there is one
schema, with seven fields in this order:
| Field | Meaning |
|---|---|
code | a stable code: E-TP01 (a semantic / type error), E-PP01 (a parse error), E-RT05 (a run-time error: here division by zero), E-CAPS (a capability the run does not grant) |
level | error, or note for a non-fatal remark |
file | the file as you named it |
line, col | 1-based position, or null when the problem has none (a run-time error, a refused capability) |
message | the same text the default output shows |
hint | a suggestion, or null |
A syntax error carries its position the same way:
{"code":"E-PP01","level":"error","file":"s.crush","line":1,"col":12,"message":"unexpected token in expression: newline","hint":null}
and a refused run says what it lacks:
{"code":"E-CAPS","level":"error","file":"h.crush","line":null,"col":null,"message":"needs capabilities this run does not grant; nothing was run: http.get","hint":"no grant in this build provides them"}
Wrong arity is caught at compile time, with the call’s position:
{"code":"E-TP01","level":"error","file":"ar.crush","line":2,"col":1,"message":"Function 'f' expects 1 arguments, found 2","hint":null}
The stream has one record per error and nothing else on standard output, so
... --message-format json | jq is safe. The program’s own print output is
separate, and the [steps=…] summary is on standard error as ever.
Where to go next
- Debugging: stop at a line and look at the variables.
- Capability System: what
E-CAPSrefusals mean and which flag fixes each.
Debugging
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
crush debug FILE (the same program as crush-debug FILE) runs a program under a
debugger: breakpoints by source line, single-stepping, watchpoints on a variable, and
printing values. It reads commands from standard input, so it works at a terminal and
in a pipe. It is in the prebuilt tarball and in cargo install crush-lang-sdk.
Debugging is a grant
Like every other authority in Crush, looking inside a running program is switched on by a flag, and nothing is granted by default:
| Flag | Lets the debugger |
|---|---|
--step | run the program and break, step, next, finish, continue, watch |
--inspect | (needs --step) show variable values in full |
--inspect=redacted | (needs --step) show a value’s type and a per-session hash instead, so you can tell whether two values are equal without seeing them |
--break FILE:LINE | set a breakpoint before the first command (repeatable; LINE alone works) |
The program’s own capabilities are granted with the same flags as crush run
(--fs, --net, --polyglot, …). Without --step, every command that would run the
program is refused, and without --inspect values show as <hidden>:
$ printf 'break 3\ncontinue\nquit\n' | crush debug d.crush
cru-s-debugger> refused: `break` needs the `debug.step` grant (pass --step)
cru-s-debugger> refused: `continue` needs the `debug.step` grant (pass --step)
A session
Take this program, saved as d.crush:
let total = 0
for i in 0..3 {
total = total + i
}
print(total)
3
Stop on line 3 and look at the variables. The commands are typed after the prompt (shown here as a script piped in):
$ printf 'break 3\ncontinue\nprint total\nlocals\nquit\n' | crush debug d.crush --step --inspect
cru-s-debugger> breakpoint #0 set at d.crush:3
cru-s-debugger> hit breakpoint #0 at d.crush:3 in main
3 | total = total + i
cru-s-debugger> total = 0
cru-s-debugger> total (slot 0) = 0
i (slot 1) = 0
__end_0 (slot 2) = 3
cru-s-debugger> bye.
The __end_0 slot is the compiler’s copy of the loop bound; it shows that the debugger
reports the real locals of the compiled function.
With --inspect=redacted the same print total gives a type and a hash:
cru-s-debugger> total = <int #95e76d5b42ff8213>
Commands
| Command | Does |
|---|---|
break FILE:LINE or break LINE | set a breakpoint (delete ID removes it, list shows them) |
step / s | one instruction, or one source line; enters calls |
next / n | step over: run a call to completion |
stepi / nexti | the same, always by instruction |
finish / fin | step out: run until this function returns |
continue / c | run until a breakpoint, a watchpoint, or the end |
watch NAME | stop when that local changes (unwatch ID removes it) |
print NAME or p NAME | print a local, or a field with NAME.field |
locals / vars | print every assigned local of the current frame |
status / info | show the VM state |
quit / q | leave |
For editors and agents: --message-format json
With --message-format json there is no prompt and prose: each event the debugger
reports is one JSON object per line on standard output. Stopping at the same
breakpoint produces:
{"event":"started","file":"d.crush","visibility":"Full"}
{"command":"break 3","event":"message","text":"breakpoint #0 set at d.crush:3"}
{"event":"stopped","file":"d.crush","frames":[{"depth":1,"file":"d.crush","function":"main","ip":48,"line":3,"locals":[{"name":"total","slot":0,"value":{"text":"0","type":"int"}},{"name":"i","slot":1,"value":{"text":"0","type":"int"}},{"name":"__end_0","slot":2,"value":{"text":"3","type":"int"}}]}],"function":"main","line":3,"reason":{"id":0,"kind":"breakpoint"},"source":" total = total + i"}
{"command":"print total","event":"message","text":"total = 0"}
so a tool can follow the program without parsing the text form.
Windows: the ui.* API
Verified against crush-ast
bad81048(v0.9.0, 2026-10-31) up to the window (the page’s checked blocks also pass atdc0d0278): the refusal, the error without a display and the API below were checked against the release binaries and crush-ast’s source. The guide’s checker has no desktop session, so it has not opened a window; crush-ast says the same of its own desktop backend (its tests drive the page headless, by element id).
Since 0.9.0 a Crush program can draw a window. This is a separate package:
crush-gui is in the prebuilt release tarball next to crush, but it is not part of
cargo install crush-lang-sdk (it brings a whole rendering stack, arniko),
and the browser build has no windows. crush-run refuses a ui.* program and
points you at crush gui.
crush gui run counter.crush --ui # the umbrella CLI runs the crush-gui next to it
crush-gui run counter.crush --ui # the same thing
The grant
--ui unlocks every ui.* capability and nothing else (the other grants such as
--fs or --net work as they do for crush-run). Without it nothing runs:
$ crush gui run counter.crush
[capabilities] counter.crush needs capabilities this run does not grant; nothing was run:
--ui: ui.button, ui.next_event, ui.render, ui.title
With --ui on a machine with no desktop session, the run stops before the program
starts: crush-gui: cannot open a window: no display (neither DISPLAY nor WAYLAND_DISPLAY is set); run this where a desktop session exists.
The model: render a page, pull events
There are no callbacks. The program draws a page of HTML with ui.render, then asks
for the next thing the user did with ui.next_event(), which blocks until there is
one. A counter:
fn page(count) {
let html = "<h1>Counter</h1>"
html = html + "<p id=\"count\">Count: " + count + "</p>"
html = html + ui.button("dec", "-1", "outline")
html = html + ui.button("inc", "+1", "accent")
return html
}
ui.title("Counter")
let count = 0
ui.render(page(count))
while true {
let ev = ui.next_event()
if ev.kind == "close" { break }
if ev.kind == "click" {
if ev.id == "inc" { count = count + 1 }
if ev.id == "dec" { count = count - 1 }
ui.render(page(count))
}
}
print("bye, count was " + count)
(This block is not run by the guide’s checker, which has no window to open; it is
the repository’s examples/gui/counter.crush, which crush-ast’s own tests drive
headless.)
| Call | Returns | Notes |
|---|---|---|
ui.render(markup) | replace the whole page with markup (HTML) | |
ui.next_event() | event map | blocks until the next event; after the window closes it returns close every time |
ui.title(s) | the window title, read once when the window opens, so call it before the first render | |
ui.escape(s) | string | HTML-escape s; use it on any text you put into markup |
ui.button(id, label[, variant]) | markup | variants: default destructive outline secondary ghost accent |
ui.input(id[, value[, placeholder]]) | markup | a text input |
ui.card(title, body_html) | markup | body_html is markup, not escaped |
ui.alert(message[, variant]) | markup | info success warning error |
ui.badge(text[, variant]) | markup | default success warning error info purple |
The markup helpers are conveniences: markup is plain HTML, and an element is
addressable if it has an id attribute.
Events
Every event is a map with the same four string fields, kind, id, value and
key; a field that does not apply is "", so ev.id never needs an existence check.
kind | When | id | value | key |
|---|---|---|---|---|
click | a click on, or inside, an element with an id | that id | ||
input | the text of an <input id=…> changed | the input | its new text | |
submit | Enter in an <input id=…> | the input | its text | |
key | a non-printing key (Escape, Tab, ArrowUp, …) | the key name | ||
close | the window was closed |
Three things to know
ui.renderreplaces the page, so an<input>loses focus and its caret every time. Do not re-render on everyinputevent: rememberev.value, and redraw onclickorsubmit.- On
closethe program shouldbreak; it is not killed, so it can save its state. - By crush-ast’s design note, a
crush-guirun has a larger default step quota (500 million) because a window is long-lived, and the time spent waiting inui.next_event()costs no steps.
Engines, AOT and Walkers
Verified against crush-ast
bad81048(v0.9.0, 2026-10-31), with rustc 1.96, gcc, Python 3.14 and Node 26 on the host. The page’s checked blocks also pass atdc0d0278; the AOT and walker transcripts were not re-run there.
One Crush program can run on several engines. crush-ast’s rule for them is “the VM is exact; every other engine is exact or loud”: an engine either produces the VM’s output or refuses the program by name. It never silently produces something else. (Where that rule is broken today, this guide links the crush-ast issue.)
| Engine | How you reach it | Status |
|---|---|---|
| CVM1 VM (scheduler) | crush run, crush-run run | the reference: everything in this guide |
| CVM1 portable VM | the browser build (crush-web, the guide’s Run buttons) | same programs, same output; parallel_map runs items one after another |
| AOT via Rust or C | crush-aotc (from cargo build -p crush-aot) | a subset; refuses the rest by name |
| FastVM, Cranelift JIT | crush-diff, embedding | a smaller subset; refuse what they lack |
Ahead-of-time compilation: crush-aotc
crush-aotc translates a program to Rust (compiled with rustc) or C (gcc /
clang) and builds a native shared library. crush-aotc run compiles and runs it
in one step; after the program’s output it prints the entry function’s return
value (null for a script):
$ cat fib.crush
fn fib(n) {
if n < 2 { return n }
return fib(n - 1) + fib(n - 2)
}
let m = {"b": 2, "a": 1}
m["c"] = 3
print(m)
print(fib(20))
let s = "hello"
print(s[1])
$ crush-aotc run fib.crush # via rustc
{b: 2, a: 1, c: 3}
6765
e
null
$ crush-aotc run --backend gcc fib.crush # via gcc
{b: 2, a: 1, c: 3}
6765
e
null
Other forms: crush-aotc compile prog.crush -o prog.so (a library),
--emit rust / --emit c-source (print the generated source), --emit c --cc clang.
Run-time errors are the VM’s errors (crush(aot): division by zero,
crush(aot): arithmetic overflow, crush(aotc): `P` is sealed: it has no field `z` (fields: x)), and both backends compare maps and arrays by value, like the
VM.
What AOT refuses
Anything the backends can’t compile exactly stops crush-aotc with the
instruction it can’t handle, before producing a binary. All of these were seen
with both backends:
| Program uses | Refusal |
|---|---|
| a lambda or closure | the Rust AOT backend cannot compile: `make_closure` (fn main, instruction 0) |
a method call on a struct (p.norm2()) | the C AOT backend cannot compile: `call_member` (fn main, instruction 5) |
spawn | `spawn` (green tasks) isn't supported on the Rust AOT backend yet (#161) |
a @python block | the Rust AOT backend cannot compile: `exec_lang` (fn main, instruction 5) |
| most standard-library capabilities | the C AOT backend cannot compile: cap_call 'str.to_upper' (fn main, instruction 26) |
Plain functions, recursion, arrays, maps, strings and sealed structs without methods do compile.
Comparing engines: crush-diff
crush-diff FILE... runs each program on the VM and the other engines and
reports where they disagree. A loud refusal counts as a disagreement in outcome
class, so you can see which engines a program is out of reach for:
$ crush-diff closures/counter.crush structs/impl-methods.crush
✗ closures/counter.crush DIVERGED
interpreter vs fastvm OUTCOME CLASS: A_ok=true C=Err("ExecutionError(\"Unknown opcode: load_cell\")")
✗ structs/impl-methods.crush DIVERGED
interpreter vs fastvm OUTCOME CLASS: A_ok=true C=Err("ExecutionError(\"Unknown opcode: call_member\")")
2 files · 0 agree (0 with notes) · 2 DIVERGED · 0 don't compile
Walkers: other languages as input
A walker translates a source file in another language into CAST, which then
compiles and runs like Crush. This is separate from @lang blocks (which run a
real interpreter): walked code runs on the Crush VM, under its capabilities.
crush-walk-run FILE walks, compiles and runs a file by its extension
(.py, .js/.ts, .rs, .c, .go, .zig, .sh, .dart, .wasm, …);
crush run itself takes .crush, CAST (.cast.json, .castb), .casm (CASM
JSON), .cvms (assembly) and .cvm1.
Walkers follow the same exact-or-loud rule. A Python program prints exactly what
python3 prints:
$ cat fact.py
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
xs = [fact(i) for i in range(6)]
print(xs)
print({"a": 1, "b": [1, 2]})
$ crush-walk-run fact.py
[1, 1, 2, 6, 24, 120]
{'a': 1, 'b': [1, 2]}
and so does JavaScript, against node:
$ cat fact.js
function fact(n) { return n <= 1 ? 1 : n * fact(n - 1); }
const xs = [];
for (let i = 1; i <= 3; i++) { xs.push(fact(i)); }
console.log(xs);
console.log(7 / 2, "done");
$ crush-walk-run fact.js
[ 1, 2, 6 ]
3.5 done
Constructs a walker can’t translate exactly are refused at walk time, with the source position:
$ crush-walk-run map.js # const xs = [1,2,3].map(x => fact(x));
Error: javascript@CAST: calling a method on anything but a plain name (`a.b.m()`, `"s".m()`, `f().m()`) is not supported by the JS walker yet
The Rust walker is the strictest: it only accepts what it can prove has Rust’s
exact semantics (integer widths, Debug formatting), so expect refusals such as
unsupported Rust Debug at 7:30: call argument needs a proven compatible Rust type (CRUSH-xps-9). Simple code works:
$ cat squares.rs
fn main() {
let mut total = 0;
for i in 1..=4 {
total += i * i;
}
println!("sum of squares: {}", total);
}
$ crush-walk-run squares.rs
sum of squares: 30
Next Steps
- Polyglot Programming: running real interpreters instead
- CAST: what walkers produce
Examples
Runnable Crush programs. Every program and every output block on these pages is
executed against crush-ast dc0d0278 by scripts/check-examples.py, so what you
read is what happens. Pages also record where a
language feature is not yet implemented, with the crush-ast ticket.
| Example | Pattern | Flags to run it |
|---|---|---|
| Fibonacci & Functions | Recursion, typed signatures | — |
| Arrays & Loops | Arrays, for, break/continue, FizzBuzz | — |
| Exception Handling | try/catch/throw | — |
| Structs (and Concurrency) | Structs with methods; spawn/await | — |
| Lambdas & Pipes | |> pipelines, lambdas, closures | — |
| Import Styles | Every import form, and why none loads yet | — |
| System Info Report | env.*, time.* capabilities | --env --time |
| Build Pipeline | process.exec, fail-fast steps | --process |
| Polyglot Pipeline | Python + JavaScript + Bash in one program | --polyglot |
| Showcase: awesome-crush | Games, interpreters and an agent tool written by LLMs | varies |
The verified corpus has 120+ more, one small program per behaviour, each with its exact output.
Run any of them with crush run [flags] file.crush (see
Getting Started).
Fibonacci & Functions
Open as a notebook (.crush-nb, how to run it)
The canonical recursion example, with typed function signatures. Run it with
crush run fib.crush.
fn fib(n: Int) -> Int {
if n <= 1 {
return n
}
return fib(n - 1) + fib(n - 2)
}
fn factorial(n: Int) -> Int {
if n <= 1 {
return 1
}
return n * factorial(n - 1)
}
fn main() {
for i in 0..10 {
print("fib(" + i + ") = " + fib(i))
}
print("10! = " + factorial(10))
}
fib(0) = 0
fib(1) = 1
fib(2) = 1
fib(3) = 2
fib(4) = 3
fib(5) = 5
fib(6) = 8
fib(7) = 13
fib(8) = 21
fib(9) = 34
10! = 3628800
What this shows:
fn name(param: Type) -> ReturnType— a typed signature (hints are checked at call sites)- Recursion needs no special annotation; the default call-depth limit is 256 frames, which is far more than this needs
returnis explicit — there is no implicit last-expression return"text" + numberconverts the number, soprintcan build a line- A program may have both top-level statements and
fn main(); the top-level statements run first, thenmain
Arrays & Loops
Open as a notebook (.crush-nb, how to run it)
Array creation, indexing, for iteration, break/continue, and a classic
loop exercise.
let arr = [10, 20, 30, 40, 50]
print("length: " + len(arr))
print("first: " + arr[0] + ", third: " + arr[2])
// iterate
let sum = 0
for x in arr {
sum = sum + x
}
print("sum: " + sum)
// break — stop at 30
for x in arr {
if x == 30 {
break
}
print("before 30: " + x)
}
// continue — skip 30
for x in arr {
if x == 30 {
continue
}
print("not 30: " + x)
}
// build an array, index by position
let squares = []
for i in 1..6 {
squares.push(i * i)
}
print(squares)
// strings index too
let s = "hello"
print(s[0] + s[4])
// fizzbuzz
for n in 1..16 {
if n % 15 == 0 {
print("FizzBuzz")
} else if n % 3 == 0 {
print("Fizz")
} else if n % 5 == 0 {
print("Buzz")
} else {
print(n)
}
}
length: 5
first: 10, third: 30
sum: 150
before 30: 10
before 30: 20
not 30: 10
not 30: 20
not 30: 40
not 30: 50
[1, 4, 9, 16, 25]
ho
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
What this shows:
[v1, v2, ...]literals,len(arr), zero-basedarr[i], andarr.push(v)for x in arrand half-open rangesfor i in 1..6(1 through 5)breakleaves the loop;continueskips to the next iteration- Strings index like arrays, yielding one-character strings
if / else if / elsechains and%
Exception Handling
Open as a notebook (.crush-nb, how to run it)
try / catch / throw work, including across function calls. Any value can
be thrown.
print("Starting")
try {
print("Inside try block")
throw "Oops"
print("This should not print")
} catch e {
print("Caught exception: " + e)
}
print("After catch block")
fn safe_divide(a: Int, b: Int) -> Int {
if b == 0 {
throw "division by zero"
}
return a / b
}
try {
print(safe_divide(10, 2))
print(safe_divide(10, 0))
} catch e {
print("Error: " + e)
}
// any value can be thrown
try {
throw {"code": 404, "msg": "not found"}
} catch err {
print(err.code)
print(err.msg)
}
Starting
Inside try block
Caught exception: Oops
After catch block
5
Error: division by zero
404
not found
What this shows:
try { ... } catch e { ... }— the thrown value binds toethrow expr— the rest of thetrybody is skipped- Output printed before the
throwis kept (5above) - Thrown values may be strings, numbers, or objects (
err.code) catchalso handles VM faults such as1 / 0and failed capability calls (the caught value prints aserror(<message>)); a crashing polyglot block or an exhausted quota still ends the program — see Control Flow
Structs (and Concurrency)
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
A struct is declared once (on one line), built with a literal, and given methods
in an impl block. Structs are passed by reference.
struct Point { x: Float, y: Float }
impl Point {
fn new(x, y) { return Point { x: x, y: y } }
fn dist2(self, other) {
let dx = self.x - other.x
let dy = self.y - other.y
return dx * dx + dy * dy
}
fn label(self) { return "(" + self.x + ", " + self.y + ")" }
}
let p = Point::new(1.0, 2.0)
let q = Point { x: 4.0, y: 6.0 }
print("p = " + p.label())
print("squared distance: " + p.dist2(q))
p = (1.0, 2.0)
squared distance: 25.0
What this shows:
struct Point { x: Float, y: Float }: declare it on one line; the parser does not yet accept a struct body that spans linesPoint { x: 4.0, y: 6.0 }names every field;Point::new(...)is a method withoutself, called through the typep.dist2(q)resolvesdist2onp’s struct;selfispFloatarithmetic:3.0 * 3.0 + 4.0 * 4.0is25.0
More in Structs, Methods and Kinds.
Concurrency
spawn starts a green task; tasks take turns at yield, and await collects a
task’s result. The workers below share one captured counter:
fn main() {
let done = 0
let worker = |name| {
print(name + " running")
yield
print(name + " finishing")
done = done + 1
return name
}
let a = spawn worker("a")
let b = spawn worker("b")
print("main")
print(await a)
print(await b)
print("finished: " + done)
}
main
a running
b running
a finishing
b finishing
a
b
finished: 2
More in Concurrency.
Lambdas & the Pipeline Operator
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
The pipeline operator
x |> f calls f(x); x |> f(y) calls f(x, y). Chains read left to right and
bind more loosely than any other operator. The right-hand side must be a function
name, or a variable holding a function value.
fn add(a, b) {
return a + b
}
fn mul(a, b) {
return a * b
}
fn square(x) {
return x * x
}
print(add(1, 2) |> mul(3))
print(2 |> square |> square)
let result = 3 |> add(4) |> mul(10)
print(result)
9
16
70
add(1, 2) |> mul(3) is mul(add(1, 2), 3), i.e. mul(3, 3) = 9.
Lambdas
A lambda is |params| expression or |params| { block }:
let add = |a, b| {
return a + b
}
let mul = |x, y| x * y
print(add(1, 2))
print(mul(4, 5))
print(6 |> |n| n)
That program fails to compile because of its last line: an inline lambda on the
right of |> is a parse error (Pipeline right side must be function). Bind it
first:
let add = |a, b| {
return a + b
}
let mul = |x, y| x * y
let ident = |n| n
print(add(1, 2))
print(mul(4, 5))
print(6 |> ident)
3
20
6
Functions as values, and closures
A function name is a value, and a lambda captures the variables around it:
fn compose(f, g) {
return |x| g(f(x))
}
fn make_scaler(k) {
return |x| x * k
}
let triple = make_scaler(3)
let inc = |x| x + 1
let triple_then_inc = compose(triple, inc)
print(triple_then_inc(5))
print(parallel_map([1, 2, 3], triple))
16
[3, 6, 9]
More in Closures and Function Values.
Import Styles
Open as a notebook (.crush-nb, how to run it)
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
Crush has one import that loads Crush code, import a.b, resolved at compile
time from .crush files (crush-ast CRUSH-110), and a few other forms. This page
lists each with what it does at the pinned commit. The rules for modules, packages
and pub are in Modules, Packages and Visibility.
| Form | What happens |
|---|---|
import util.strings, import util.strings as s, import util.strings { twice } | loads util/strings.crush at compile time; see Modules |
import io, import fs as files (no such file) | compile error: `import fs`: module not found — no fs.crush in any of: … |
import @http "url" as x, import @git "url" as x, import @file "path" as x | compile error: is not supported yet: no Crush host can load an external resource |
use @mcp "url" { tools } as alias | compile error: is not supported yet: no Crush host implements MCP client connections |
use @cap "cap.path" { "names" } as alias | compiles, refused before running: not available in this host: cap.acquire |
use @lang python "math" [as m] | runs; see below |
The capabilities are not modules: fs.read(...) is available to a program run with
--fs without any import, and import fs looks for a file named fs.crush.
import fs as files
print("loaded")
use @mcp "https://api.github.com" { "issues.list", "repos.get" } as github
print("loaded")
import @http "https://example.com/data.json" as data
print("loaded")
use @cap "fs.read" { "read" } as r
print("loaded")
use @lang
use @lang <language> "<module>" [as <alias>] writes the import into every later
block of that language, under the module’s own name and the alias:
use @lang python "math" as m
@python -> v {
v = m.factorial(5) + math.factorial(3)
}
print(v)
126
Sharing code between files
Put shared functions in a module and import it:
// util/strings.crush
fn shout(s) { return str.to_upper(s) + "!" }
fn twice(s) { return s + s }
import util.strings as s
print(s.shout("hi"))
HI!
Run it from the directory that holds both files (crush run main.crush), or point
-L / CRUSH_PATH at the directory that holds util/.
System Info Report
Open as a notebook (.crush-nb, how to run it)
Crush as a conductor: gather facts from the host through capability calls, then
assemble them. The program needs three capability groups, so it is run with
crush run --env --time sysinfo.crush; with either flag missing, the program is
refused before it runs, with the flag it needs (--env: env.get).
// Gather host facts through capabilities and render a small report.
let os = env.os()
let arch = env.arch()
let home = env.get("HOME")
let lines = ["System report", "-------------", "os: " + os, "arch: " + arch]
print(str.join(lines, "\n"))
if home != null {
print("home is set")
}
print("clock ok: " + (time.now() > 0))
System report
-------------
os: linux
arch: x86_64
home is set
clock ok: true
(The os and arch lines depend on the machine that runs the example.)
What this shows:
env.os()/env.arch()(standard library, no flag),env.get(name)(--env, returnsnullwhen the variable is unset),time.now()(--time) — each group is deny-by-defaultstr.join(array, delimiter)to assemble text"label" + (expression)concatenation with aBoolresult- Calls that don’t exist yet: this page used to show
sys.hostname(),sys.cpu_usage(),sys.memory_info()and acapability system readonlydeclaration. None of those exist in the runtime today; host metrics beyondenv.*andtime.*have to come fromprocess.exec(see Build Pipeline) or a polyglot block.
Build Pipeline
Open as a notebook (.crush-nb, how to run it)
Crush’s intended role is a small, auditable conductor for other tools: it
decides what runs and in what order, while capability calls do the work. Here each
step is a real process started through process.exec, and the pipeline stops at
the first failure.
Run it with crush run --process build.crush.
// A tiny build pipeline: run each step as a process, stop at the first failure.
fn run_tool(cmd: String, arg: String) -> Int {
let res = process.exec(cmd, arg)
return res.exit_code
}
fn step(name: String, cmd: String, arg: String) -> Int {
print("[start] " + name)
let code = run_tool(cmd, arg)
if code != 0 {
print("[failed] " + name + " (exit " + code + ")")
return code
}
print("[ok] " + name)
return 0
}
fn main() {
let steps = [["configure", "echo", "config"], ["compile", "echo", "cc"], ["test", "false", "x"], ["package", "echo", "tar"]]
for s in steps {
let code = step(s[0], s[1], s[2])
if code != 0 {
print("pipeline stopped")
break
}
}
}
[start] configure
[ok] configure
[start] compile
[ok] compile
[start] test
[failed] test (exit 1)
pipeline stopped
What this shows:
- Capability-gated side effects.
process.execonly exists because of the--processflag; without it the program is refused before it runs, naming--process: process.exec. - Structured results.
process.exec(cmd, arg)returns a map withexit_code,stdoutandstderr(a JSON string before crush-ast 0.11). - Fail-fast.
stepreturns the exit code,mainbreaks out of the loop on the first non-zero one. - Data-driven steps. The pipeline is an array of
[name, command, argument]triples, indexed withs[0],s[1],s[2].
process.exec takes exactly two arguments — the command and a single argument
string — so multi-argument commands need to be wrapped (process.exec("sh", "make -j8") or similar). It runs with the full authority of the user, so enable
--process only for programs you trust.
Polyglot Pipeline
Open as a notebook (.crush-nb, how to run it)
The same data, handled by the language best suited to each step, with Crush
variables as the glue. This replaces an earlier “Async LLM Dashboard” page whose
dom.*, seahorse and async/await calls do not run in the current
toolchain.
Run it with crush run --polyglot poly.crush (needs python3, node and bash
on PATH; crush doctor checks).
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
// Three languages, one program. Values flow through Crush variables.
let numbers = [3, 1, 4, 1, 5, 9, 2, 6]
@python -> mean {
import statistics
mean = statistics.mean(numbers)
}
@javascript -> spread {
const spread = Math.max(...numbers) - Math.min(...numbers)
}
@python -> line {
line = f"mean={mean} spread={spread}"
}
print(line)
@bash {
echo "bash: $(echo done)"
}
print("")
mean=3.875 spread=8
bash: done
What this shows:
@python -> mean: the block reads the Crush variablenumbers(inputs are automatic) and declaresmeanas its output, which becomes a Crush variable@javascript -> spread: the same protocol;spreadcomes back as a number- the second
@pythonblock reads both earlier outputs, because they are Crush variables now @bash: only its printed output comes back. It could read a Crush variable by naming it ($name), but it has no way to hand a value back, which is why the formatting is done in Python- block output is trimmed and has no trailing newline, which is why
print("")is used to finish the line - all three run as ordinary subprocesses with your user’s authority — see Polyglot Programming
Showcase: awesome-crush
nixpt/awesome-crush collects real Crush programs, each written by a different LLM that was given little more than “can you learn crush?” and a pointer to crush-ast. Its README tells the story of each one: which constraints the authors hit, and the compiler bugs they found along the way.
Every program below was run on crush-ast
bad81048(v0.9.0, 2026-10-31) withcrush-run run --max-steps 500000000 FILE < /dev/null. All of them ran to their documented conclusion. The outputs quoted are what that run printed.
The programs
| Program | Author (from the awesome-crush README) | What it is | Ends with | VM steps |
|---|---|---|---|---|
games/pong.crush | Ornith-1.5-35B-A3B | self-playing Pong, scalar state threaded through recursion | draw 0-0 | 2,303,450 |
games/tictactoe.crush | foreman-v2 (Qwen3.8-27B fine-tune) | board packed as one base-3 integer | game over: draw | 117,606 |
games/lights_out.crush | qwen38-base (Qwen3.8-27B) | 25-bit bitfield board, solves itself | board solved in 8 moves | 189,907 |
games/game_of_life.crush | Claude (hand-written) | Conway’s Life with @module/@decision/@invariant | a blinker oscillating | 286,738 |
games/blackjack.crush | OpenCode | six self-played rounds with a bankroll | final bankroll: 120 | 5,631 |
games/pong-deepseek.crush | cece / bro (DeepSeek-v4) | a second, independent Pong | time's up — final score: left 0 : 0 right | 1,245,978 |
games/fifteen_puzzle.crush | bro (DeepSeek-v4) | IDA* solver, tiles packed as nibbles in one integer | solved in 6 moves. | 77,324 |
games/breakout.crush | cece (DeepSeek-v4) | brick-breaker, 30 bricks as bits | out of ticks — final score: 140 | 5,593,804 |
games/rps_tournament.crush | bro (Muse) | rock-paper-scissors bot round-robin | champion: Cycler! and an ASCII trophy | 3,289 |
forth/forth.crush | Buffy (DeepSeek-v4) | a Forth interpreter | five Forth programs run | 63,281 |
brainfuck/brainfuck.crush | Buffy (DeepSeek-v4) | a Brainfuck interpreter | Hello World!, A–Z, 0–9 | 94,146 |
caison/caison-parsor.crush | bro (the commit author; the README names no model) | a CAISON parser written in Crush | the parsed document as JSON | 72,957 |
agents/log-triage/log_triage.crush | Claude (Opus 5.5) | an agent-written tool that declares @capabilities | see below | — |
The step counts matter: the VM’s default budget is 1,000,000 instructions, so the
larger games need --max-steps. Without it, crush-run run games/pong.crush stops
with [runtime] instruction quota exceeded (1000000).
games/blackjack_interactive.crush (also in crush-ast’s examples/crush/) reads
its moves with io.read(). Feed it input, or redirect from /dev/null so it sees
end-of-file and leaves the table instead of waiting:
$ printf '10\nh\ns\n0\n' | crush-run run games/blackjack_interactive.crush
...
Bankroll: $110
Bet (1-110) — 0 or q to leave:
You leave the table with $110.
A taste of the output
Game of Life’s blinker, from crush run games/game_of_life.crush:
Conway's Game of Life -- 5x5, blinker seed, dead border (no wrap)
gen 0:
.....
.....
.###.
.....
.....
gen 1:
.....
..#..
..#..
..#..
.....
The Forth interpreter running Forth programs on the Crush VM:
Forth-in-Crush: a Forth interpreter running on the Crush VM
--- stack arithmetic: (3+4)^2 ---
source: 3 4 + dup * .s .
stack(1): 49
49
(final stack depth: 0)
and the Brainfuck interpreter’s Hello World:
--- hello world ---
source: ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Hello World!
What the collection shows about the language
- Older programs avoid features that now exist. The games thread all state
through recursive calls and pack boards into integers, because when they were
written arrays couldn’t be mutated in place and there was no random-number
capability. Both work now (
a[i] = v,math.seed/math.random_int), as do closures and struct methods, and the programs still run unchanged. - Capabilities are visible. The
log-triageagent tool starts with@capabilities [fs.list, fs.cat, time.now_iso].crush-run capsreports what it needs before anything runs, a run without those grants is refused, and a variant that addsnet.http_postwithout declaring it is refused at compile time:
$ crush-run caps log_triage.crush
log_triage.crush
declares: fs.list, fs.cat, time.now_iso
needs these grants to run:
--fs: fs.cat, fs.list
--time: time.now_iso
also uses (ambient): arr_set, io.print, push, str.concat, str.contains, str.ends_with, str.pad_left, str.pad_right, str.split, str.trim
$ crush-run run --fs --fs-root sample-logs --time tampered/undeclared.crush
[compile] the program uses a capability not declared in @capabilities: net.http_post
add it to @capabilities, or stop using it
(crushc doesn’t apply that check yet: crush-ast
#258.)
Run them yourself
git clone https://github.com/nixpt/awesome-crush
cd awesome-crush
crush run --max-steps 50000000 games/breakout.crush
crush run games/fifteen_puzzle.crush
crush run forth/forth.crush
CAST — the Crush AST
CAST is the JSON abstract syntax tree that sits between source languages and
CASM. The Crush parser produces it, the polyglot walkers
produce it from other languages, and an AI agent can write it directly (see
AI-Native CAST). The compiler (crush_frontend) turns it into CASM.
Crush source ──parse──┐
Python/JS/… ──walker──┼──▶ CAST (JSON) ──compile──▶ CASM IR ──▶ CVM1 ──▶ VM
an agent's JSON ──────┘
This page is the schema reference. It is derived from crates/crush-cast/src/lib.rs
in crush-ast (verified against dc0d0278, 2026-11-16); the examples are accepted by crush_cast::validate_json,
compiled and run by this guide’s checker.
Document structure
{
"cast_version": "0.1.0",
"entry": "main",
"lang": null,
"functions": {
"main": { "params": [], "body": [ /* statements */ ], "meta": {} }
}
}
| Field | Type | Required | Description |
|---|---|---|---|
cast_version | string | yes | format version; see Serialization |
entry | string | yes | name of the function to run first |
lang | string or null | yes (may be null) | language that produced the tree ("crush", "python", …) |
functions | object | yes | function name → function |
ai_meta | object | no | program-level AI metadata — see AI-Native CAST |
manifest | object | no | the @module navigation manifest (purpose, exports, invariants) used by crush-index |
exhaustive_sites, wip, temporaries, decisions | no | compiler-populated tooling nodes (@wip, @temporary, @decision blocks) |
A function is:
| Field | Type | Required | Description |
|---|---|---|---|
params | array of [name, type] pairs | yes | [["n", "Int"]]; use "Any" for untyped |
body | array of statements | yes | |
meta | object | yes | free-form ({} is fine). Forgetting it is the most common validation error |
is_async | bool | no | tooling hint |
annotations | object | no | @errors/@reads/@writes/@covers annotations |
There is no top-level imports or structs table: imports and struct definitions
are statements (Import, StructDef).
A complete program
{
"cast_version": "0.1.0",
"entry": "main",
"lang": null,
"functions": {
"square": {
"params": [["n", "Int"]],
"body": [
{ "type": "Return",
"value": { "type": "BinaryOp", "operator": "*",
"left": { "type": "Var", "name": "n" },
"right": { "type": "Var", "name": "n" } } }
],
"meta": {}
},
"main": {
"params": [],
"body": [
{ "type": "VarDecl", "name": "total", "value": { "type": "IntLiteral", "value": 0 }, "type_hint": "Int" },
{ "type": "For", "variable": "i",
"iterable": { "type": "ArrayLiteral", "elements": [
{ "type": "IntLiteral", "value": 1 },
{ "type": "IntLiteral", "value": 2 },
{ "type": "IntLiteral", "value": 3 } ] },
"body": [
{ "type": "Assign", "target": "total",
"value": { "type": "BinaryOp", "operator": "+",
"left": { "type": "Var", "name": "total" },
"right": { "type": "Call", "function": "square",
"args": [ { "type": "Var", "name": "i" } ] } } }
] },
{ "type": "If",
"condition": { "type": "BinaryOp", "operator": ">",
"left": { "type": "Var", "name": "total" },
"right": { "type": "IntLiteral", "value": 10 } },
"then_body": [
{ "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print",
"args": [ { "type": "StringLiteral", "value": "sum of squares: " },
{ "type": "Var", "name": "total" } ], "meta": {} } }
],
"else_body": null }
],
"meta": {}
}
}
}
sum of squares: 14
Every node is an object with a "type" tag. meta is optional on almost every
node (it defaults to {}), with one exception: CapabilityCall requires its
meta. The Crush parser fills meta with line and col.
Statements
type | Fields | Notes |
|---|---|---|
VarDecl | name, value, type_hint | declare a variable (type_hint defaults to "Any") |
Assign | target (a name), value | |
SetField | target (expression), field, value | p.x = 3 |
Export | name, value | publish a variable to the host / polyglot caller |
ExprStmt | expr | expression evaluated for effect; its value is dropped |
If | condition, then_body, else_body | else_body is null or a statement list |
While | condition, body | |
For | variable, iterable, body | |
Return | value (nullable) | |
Break, Continue | — | |
TryCatch | body, error_var, handler | |
Throw | value | |
FunctionDef | name, params, body | nested function definition |
StructDef | name, fields, kind | fields is [[name, type], …]; kind is the @kind(…) annotation as written ({"args": [{"key", "value"}]}, values Name / Apply / List), or absent |
ImplBlock | type_name, trait_name (optional), methods | impl P { … } / impl T for P { … }; each method is {name, params, body}, self is an ordinary first parameter |
TraitDef | name, methods | a method without body is a required signature |
LangBlock | lang, code, variables, outputs, imports, deps | a polyglot @lang { } block; variables are marshalled in, outputs (the -> names, mirrored in meta.polyglot_outputs) are marshalled out. After prepare_polyglot_blocks, code carries the generated marshalling prologue/epilogue |
Import | import | an ImportStatement — parsed, but not executed: see below |
DomMutate, DomEventListener | DOM nodes; compile to NOP today | |
AI | ai_type, … | AI statements — see AI-Native CAST |
Import, in particular, is accepted by the schema in six flavours (CrushModule,
PolyglotModule, MCPImport, Capability, External, SecureEnv), but at run
time an import lowers to an unregistered module.load capability and fails — Crush
imports are not implemented yet (CRUSH-110).
Expressions
type | Fields |
|---|---|
IntLiteral, FloatLiteral, StringLiteral, BoolLiteral | value |
NullLiteral | — |
Var | name |
BinaryOp | operator, left, right — operators as the language spells them: + - * / % == != < > <= >= && || |
UnaryOp | operator (-, !), operand |
Call | function (a name), args — a call to a user function |
CapabilityCall | name ("io.print"), args, meta (required) |
ArrayLiteral, TupleLiteral, ListLiteral, VectorLiteral, SetLiteral | elements |
ObjectLiteral | properties: [[key, expression], …] |
Index | target, index |
GetField | target, field |
NewStruct | name |
Range | start, end |
Match | expression, arms ({pattern, body} pairs) |
Pipeline | segments — a |> b |> c |
Spawn, Await, Yield | green tasks: Spawn is {function, args} (see Concurrency) |
Lambda | params ([name, type] pairs), body — what |x| x + k parses to; captures are worked out by the compiler, not stored in CAST (see Closures) |
VectorMath | operator, args |
DomQuery | query_type, selector |
AI | ai_type, … — see AI-Native CAST |
Note the naming: it is GetField (not FieldAccess), ArrayLiteral (there is no
MapLiteral — use ObjectLiteral) and Var (not Identifier).
Patterns (for Match)
type | Fields |
|---|---|
Literal | value (an expression) |
Identifier | name (binds the value) |
Struct | name, fields: [[field, pattern], …] |
Wildcard | — |
{ "type": "Match",
"expression": { "type": "Var", "name": "n" },
"arms": [
{ "pattern": { "type": "Literal", "value": { "type": "IntLiteral", "value": 6 } },
"body": [ { "type": "ExprStmt", "expr": { "type": "StringLiteral", "value": "six" } } ] },
{ "pattern": { "type": "Wildcard" },
"body": [ { "type": "ExprStmt", "expr": { "type": "StringLiteral", "value": "other" } } ] }
] }
Types
Type positions (type_hint, parameter and field types) hold a CastType. It is
serialized the usual serde way: a bare string for the simple types,
{"Variant": payload} for the others.
| JSON | Meaning |
|---|---|
"Int", "Float", "F32", "BigInt", "Complex", "String", "Bool", "Null" | scalars |
"Any" | dynamic (the default) |
{"Array": "Int"}, {"List": …}, {"Vector": …}, {"Set": …}, {"Map": …}, {"Tensor": …} | homogeneous collections of the inner type |
{"Tuple": ["Int", "String"]} | fixed-length sequence |
{"Struct": "Point"}, {"TypeRef": "Point"} | named types |
{"Lambda": {"params": […], "returns": …}} | function types |
Types are hints: the compiler records them but the VM is dynamically typed.
{
"cast_version": "0.1.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "meta": {}, "body": [
{ "type": "VarDecl", "name": "xs", "type_hint": { "Array": "Int" },
"value": { "type": "ArrayLiteral", "elements": [ { "type": "IntLiteral", "value": 7 } ] } },
{ "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print", "meta": {},
"args": [ { "type": "Index", "target": { "type": "Var", "name": "xs" },
"index": { "type": "IntLiteral", "value": 0 } } ] } }
] } }
}
7
Metadata
meta on a node is an open JSON object. The Crush parser writes line and col
(1-based); walkers add their own keys. crush_frontend copies line/col onto the
CASM instructions it emits, which is how a runtime error gets pointed at a source
line. Nothing in meta changes what a program does, with one exception the
compiler reads: LangBlock.meta.polyglot_output (the variable to marshal back).
Validation
crush_cast::validate_json(&str) checks a document against the schema and returns
errors with a JSON path and a hint for the mistakes agents make most often. Only
the first error is reported, because serde stops at the first one.
{ "cast_version": "0.1.0", "entry": "main", "functions": { "main": {
"params": [], "meta": {},
"body": [ { "type": "Print", "value": { "type": "StringLiteral", "value": "hi" } } ] } } }
The error for that document is functions.main.body[0].type: unknown variant Print, expected one of VarDecl, Assign, …, with the hint “Statement type
‘Print’ doesn’t exist. Use ExprStmt with CapabilityCall("print") instead”. Other
built-in hints cover Identifier/Literal expressions, a missing Function.meta,
prompt instead of query in an AI query, and an object where a
DelegationStrategy string belongs.
Validation is structural. It does not check that a called function exists or that a capability name is real; the compiler and the VM do.
Serialization
crush_cast::Program can be written and read as JSON (the canonical form) or as
CBOR:
| Extension | Codec |
|---|---|
.cast.json, anything else | JSON (pretty-printed) |
.castb, .cbor | CBOR (cbor4ii), no header or magic |
Program::deserialize / load check cast_version and refuse a different major
than CAST_VERSION ("0.1.0"): version mismatch at cast boundary: expected 0.1.0, found …. Every producer, the Crush front end included, writes "0.1.0"
(from v0.3.9 through v0.9.0 the front end stamped "1.0.0" and the loader
rejected its own output). A tree with major version 1 is refused:
{ "cast_version": "1.0.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "body": [], "meta": {} } } }
From CAST to CASM
crush_frontend::compile_cast(&program) (or compile_cast_owned) walks the tree and
emits CASM IR. The control-flow statements lower to jumps:
If→ condition,jmp_if_notover the then-branch,jmpover the else-branch.While→ test at the top,jmp_if_notto the exit,jmpback.Forover an array → an index loop (len/index), as shown in CASM Examples.TryCatch→enter_try, the body,exit_try,jmppast the handler; the handler starts by storing the thrown value intoerror_var.CapabilityCall→ arguments in order, thencap_call name argc(apopfollows when the call is a statement and the capability returns a value).Call→ arguments last first, thencall function argc.
AI-Native CAST
Verified against crush-ast
v0.13.0(dc0d0278, 2026-12-03).
The doctrine
CAST is JSON. An agent that knows the schema can emit a complete program as one JSON document — no lexer, no parser, no walker — validate it, and hand it to the compiler:
agent output (JSON) ──▶ validate_json ──▶ compile_cast ──▶ CASM ──▶ crush-vm
▲
└─ no front-end: the agent *is* the front-end
fn main() -> anyhow::Result<()> {
let cast_json = r#"{
"cast_version": "0.1.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "meta": {}, "body": [
{ "type": "ExprStmt", "expr": { "type": "CapabilityCall",
"name": "io.print", "meta": {},
"args": [ { "type": "StringLiteral", "value": "from an agent" } ] } }
] } }
}"#;
// 1. Schema check: errors carry a JSON path and, for common mistakes, a hint.
if let Err(errors) = crush_cast::validate_json(cast_json) {
for e in errors {
eprintln!("{e}");
}
anyhow::bail!("invalid CAST");
}
// 2. CAST -> CASM IR -> CVM1, then run it.
let program: crush_cast::Program = serde_json::from_str(cast_json)?;
let casm = crush_frontend::compile_cast_owned(program)?;
let vm = crush_lang_sdk::compile::casm_to_vm(&casm)?;
let result = crush_lang_sdk::Runtime::new().run(&vm)?;
assert_eq!(result.output, "from an agent\n");
Ok(())
}
(For a standalone checkout, crush_cast::validate_json and
crush_frontend::compile_cast are the entry points; the version-gated
crush_cast::Program::deserialize currently rejects the front end’s own 1.0.0
stamp, so parse with serde_json as above or write "cast_version": "0.1.0". See
CAST serialization.)
Writing CAST rather than source buys an agent three things: no syntax errors (the
schema is the grammar), a validator that answers with a path and a hint, and
meta fields it can use to tag nodes with their own provenance.
Program skeleton
{
"cast_version": "0.1.0",
"entry": "main",
"lang": "agent",
"functions": { "main": { "params": [], "body": [ /* statements */ ], "meta": {} } },
"ai_meta": null
}
lang may be any string — set it to identify the emitting agent in source maps.
ai_meta carries program-level AI metadata (below).
AI nodes
An AI node is an object with "type": "AI" and an ai_type discriminator. There are
seven expressions (they yield a value and may appear wherever an expression can)
and six statements (coordination steps in a statement list).
Expressions
ai_type | Fields |
|---|---|
Query | query, result_type (string or null), context (object) |
ToolChain | tools (array of {tool_name, parameters, result_binding?, condition?, required_capability?}), strategy, error_handling |
AgentDelegation | task, agents (ids or patterns), delegation_strategy, expected_format? |
LearningLoop | learning_target, strategy, adaptations |
ContextAware | expression (any expression), requires_context, provides_context |
SemanticMatch | target (expression), concept, confidence_threshold |
Synthesize | output_type (a CastType), constraints, context_refs, examples? |
Statements
ai_type | Fields |
|---|---|
GoalDeclaration | goal_id, description, success_criteria, priority, deadline? |
ProgressUpdate | goal_id, progress (0.0–1.0), status_message, metrics (name → number) |
KnowledgeSharing | knowledge_type, content (any JSON), recipients, retention_policy |
CapabilityDiscovery | domain, requirements, discovery_strategy |
AdaptationRequest | adaptation_type, reason, parameters |
SemanticSwitch | target (expression), cases: [[label, statements], …], fallback? |
The enumerations
| Field | Values |
|---|---|
strategy (ToolChain) | objects: {"type": "Sequential"}, {"type": "Parallel"}, {"type": "Conditional", "conditions": [..]}, {"type": "Retry", "max_attempts": 3, "backoff_strategy": {"type": "Fixed", "delay_ms": 100}} (also Exponential, Linear) |
error_handling | objects: {"type": "FailFast"}, {"type": "ContinueOnError"}, {"type": "Retry", "max_retries": 2, "retry_condition": null}, {"type": "Fallback", "fallback_tools": [..]} |
delegation_strategy | strings "FirstAvailable" "CapabilityMatch" "ParallelSplit" "Hierarchical" "Broadcast" "Best" "RoundRobin", or {"Consensus": {"threshold": 0.66}} |
learning_target | "UserBehavior" "ExecutionPatterns" "ErrorPatterns" "PerformanceMetrics" "ToolUsage" |
LearningLoop strategy | "PatternRecognition" "StatisticalAnalysis" "MachineLearning" "RuleBased" |
adaptations items | "OptimizeToolChain" "ImproveErrorHandling" "UpdateAgentSelection" "ModifyExecutionStrategy" "LearnNewPatterns" |
priority | "Low" "Medium" "High" "Critical" |
knowledge_type | "Pattern" "Solution" "BestPractice" "Warning" "Insight" |
retention_policy | "Ephemeral" "Session" "Persistent" or {"Conditional": {"condition": ".."}} |
discovery_strategy | "Broadcast" "Targeted" "Hierarchical" "LearningBased" |
adaptation_type | "Performance" "Reliability" "Usability" "Compatibility" "Learning" |
Note the asymmetry: ToolChain.strategy and error_handling are internally
tagged objects ({"type": …}), while delegation_strategy and the others are
plain strings. Mixing them up is the commonest validation failure; the validator’s
hint for the delegation case says so.
Here is every node that compiles, in one program: the schema’s AI surface, checked
by validate_json, the compiler and the lowering. (CapabilityDiscovery,
AdaptationRequest and SemanticSwitch validate but are refused by the compiler;
see What actually runs.)
{
"cast_version": "0.1.0",
"entry": "main",
"lang": null,
"functions": {
"main": {
"params": [],
"meta": {},
"body": [
{ "type": "AI", "ai_type": "GoalDeclaration", "goal_id": "ship-it",
"description": "Ship the release", "success_criteria": ["tests pass"],
"priority": "High", "deadline": null },
{ "type": "AI", "ai_type": "ProgressUpdate", "goal_id": "ship-it",
"progress": 0.5, "status_message": "halfway", "metrics": { "coverage": 0.8 } },
{ "type": "AI", "ai_type": "KnowledgeSharing", "knowledge_type": "Insight",
"content": { "finding": "x" }, "recipients": ["agent://reviewers/*"],
"retention_policy": "Session" },
{ "type": "VarDecl", "name": "answer", "type_hint": "String",
"value": { "type": "AI", "ai_type": "Query", "query": "Capital of France?",
"result_type": "string", "context": {} } },
{ "type": "VarDecl", "name": "hits", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "ToolChain",
"tools": [ { "tool_name": "search", "parameters": { "q": "x" }, "result_binding": "hits" } ],
"strategy": { "type": "Sequential" }, "error_handling": { "type": "FailFast" } } },
{ "type": "VarDecl", "name": "verdict", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "AgentDelegation", "task": "Review the diff",
"agents": ["agent://reviewers/*"],
"delegation_strategy": { "Consensus": { "threshold": 0.66 } },
"expected_format": "markdown" } },
{ "type": "VarDecl", "name": "insight", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "LearningLoop", "learning_target": "ToolUsage",
"strategy": "RuleBased", "adaptations": ["OptimizeToolChain"] } },
{ "type": "VarDecl", "name": "scoped", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "ContextAware",
"expression": { "type": "IntLiteral", "value": 1 },
"requires_context": ["session.goal"], "provides_context": ["review.summary"] } },
{ "type": "VarDecl", "name": "match", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "SemanticMatch",
"target": { "type": "StringLiteral", "value": "hi" },
"concept": "greeting", "confidence_threshold": 0.8 } },
{ "type": "VarDecl", "name": "draft", "type_hint": "Any",
"value": { "type": "AI", "ai_type": "Synthesize", "output_type": "String",
"constraints": ["two sentences"], "context_refs": [], "examples": null } }
]
}
}
}
Program-level metadata
ai_meta describes the program as a whole. It does not change compilation:
{
"ai_meta": {
"description": "Review orchestration",
"ai_tags": ["orchestration", "delegation"],
"required_capabilities": ["ai.query", "ai.agent_delegation"],
"execution_context": { "environment": [], "resources": [], "permissions": [], "dependencies": [] },
"learning_objectives": ["optimize delegation latency"],
"collaboration_patterns": [
{ "pattern_type": "consensus", "participants": ["reviewers"],
"communication_style": "async", "decision_making": "vote" }
],
"inputs": [], "outputs": [], "complexity": 3
}
}
What actually runs
The AI nodes compile to real opcodes, but nothing behind them thinks yet. The
CAST compiler turns each AI node into its ai_* CASM instruction, and the lowering
to CVM1 (casm_to_vm) turns ten of them into the matching AI opcode
(AI_QUERY, …, crush-ast CRUSH-156). At run time each opcode calls a host
capability named ai_native.<kind>. What happens then depends on the host:
crush run/crush-run: the CLI provides noai_native.*capability and has no flag for one, so a program containing an AI opcode is refused before it runs (not available in this host: ai_native.query).- An embedder can register stub gates with
HostCapsBuilder::new().ai_native(true). Each stub returns a map{kind: "<name>", echo: [...], ok: true}and does nothing else (no model call, no delegation, no learning). This is the wiring a real backend will replace, so the gate names are the stable part:
.func main
AI_QUERY "{\"q\": \"capital of France\"}"
CAP_CALL "io.print" 1
HALT
{kind: query, echo: [{q: capital of France}], ok: true}
- An embedder that registers nothing (
Runtime::new()) gets a run-time error from every AI opcode, naming the gate (crush-ast CRUSH-234; beforev0.11.0the opcode returnednullsilently, #261). So a statement such asGoalDeclarationstops the program:
{
"cast_version": "0.1.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "meta": {}, "body": [
{ "type": "AI", "ai_type": "GoalDeclaration", "goal_id": "g", "description": "d",
"success_criteria": [], "priority": "Low", "deadline": null },
{ "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print", "meta": {},
"args": [ { "type": "StringLiteral", "value": "after the goal" } ] } }
] } }
}
capability denied by host: ai_native.goal_declaration: AI op 'goal_declaration' not granted / no AI host registered (grant `ai_native` via HostCapsBuilder::ai_native(true) and register a provider)
and so does an expression such as Query:
{
"cast_version": "0.1.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "meta": {}, "body": [
{ "type": "VarDecl", "name": "answer", "type_hint": "String",
"value": { "type": "AI", "ai_type": "Query", "query": "Capital of France?",
"result_type": "string", "context": {} } },
{ "type": "ExprStmt", "expr": { "type": "CapabilityCall", "name": "io.print", "meta": {},
"args": [ { "type": "Var", "name": "answer" } ] } }
] } }
}
- Three statements are refused.
CapabilityDiscovery,AdaptationRequestandSemanticSwitchhave no CVM1 opcode. They used to compile to a silent no-op; now the compiler refuses them by name (crush-ast CRUSH-265), and hand-written CASM containing theirai_*instruction fails withUnsupported CVM1 opcode:
{
"cast_version": "0.1.0", "entry": "main", "lang": null,
"functions": { "main": { "params": [], "meta": {}, "body": [
{ "type": "AI", "ai_type": "CapabilityDiscovery", "domain": "code-review",
"requirements": ["rust"], "discovery_strategy": "Broadcast" }
] } }
}
The gates are ai_native.query, .synthesize, .agent_delegation,
.semantic_match, .learning_loop, .context_aware, .toolchain,
.goal_declaration, .progress_update and .knowledge_sharing. The DOM opcodes
follow the same pattern (dom_native.*), but the IR→CVM1 lowering still turns the
dom_* instructions into NOP.
So today the AI-native surface is best understood as a typed, validated schema for agent intent with a capability-gated runtime hook: a program an agent can emit, a tool can lint and an index can read, and a host can plug a backend into. Plan for the schema and gate names to be stable and the intelligence to arrive later.
Instruction mapping
| CAST node | CASM IR instruction | CVM1 opcode |
|---|---|---|
Query | ai_query | AI_QUERY |
ToolChain | ai_tool_chain | AI_TOOLCHAIN |
AgentDelegation | ai_agent_delegation | AI_AGENT_DELEGATION |
LearningLoop | ai_learning_loop | AI_LEARNING_LOOP |
ContextAware | ai_context_aware | AI_CONTEXT_AWARE |
SemanticMatch | ai_semantic_match | AI_SEMANTIC_MATCH |
Synthesize | ai_synthesize | AI_SYNTHESIZE |
GoalDeclaration | ai_goal_decl | AI_GOAL_DECLARATION |
ProgressUpdate | ai_progress_update | AI_PROGRESS_UPDATE |
KnowledgeSharing | ai_knowledge_share | AI_KNOWLEDGE_SHARING |
CapabilityDiscovery | refused by the compiler (CRUSH-265) | — |
AdaptationRequest | refused by the compiler (CRUSH-265) | — |
SemanticSwitch | refused by the compiler (CRUSH-265) | — |
(The IR column is what crush_frontend::compile_cast emits for each node, and
casm_to_vm lowers each of the first ten to the opcode in the last column.)
See also
examples/cast/in crush-ast — the example corpus (validates; most need host capabilities or hit the AI limits above to run)- CAST schema — the non-AI nodes
- CASM Instruction Reference
CASM Overview
Open as a notebook (.crush-nb, how to run it)
CASM (Crush Assembly) is the stack-machine instruction set that Crush programs compile to. The name covers three closely related things, and most confusion about it comes from mixing them up:
| Form | What it is | Extension | Defined in | Who produces / runs it |
|---|---|---|---|---|
| CASM IR (JSON) | The compiler’s structured output: functions of JSON instructions, {"op": "push_int", "value": 42} | .casm JSON, or .casmb (MessagePack) | the casm crate (casm::Program) | compile_crush_to_casm produces it; embedders load it with casm::Program::load |
| CASM text (CVM1 assembly) | A line-oriented assembly you can write by hand: .func main / PUSH 42 / CAP_CALL "io.print" 1 | .cvms | crush-vm’s assembler | crushc --emit cvms prints it; crush-run run x.cvms and crush-compile consume it |
| CVM1 (binary) | The bytecode the VM actually executes: magic CVM1, constant pool, flat code | .cvm1 | crush-vm (bytecode.rs) | crushc writes it; crush-run run x.cvm1 runs it |
(Up to crush-ast v0.9.0 the extension .casm was shared by the JSON IR and the
text assembly. Since v0.10.0 (#365) .casm means the JSON IR and the text is
.cvms; crush-run still runs text in a .casm file, with a note asking you to
rename it. This guide’s text examples are labelled casm but are CVM1 assembly.)
They fit together like this:
Crush source ──parse──▶ CAST (JSON AST) ──compile──▶ CASM IR (JSON) ──lower──▶ CASM text ──assemble──▶ CVM1 bytes ──▶ VM
(crush_lang_sdk::compile::casm_to_vm)
crushc runs the whole chain; crush-run run FILE.crush compiles in memory and
runs. The CASM IR is the interchange point: every front-end (the Crush parser,
the polyglot walkers, an agent writing CAST directly) ends up
there, and every back-end (the VM, the AOT compilers crush-aot / crush-aotc,
the FastVM lowering) starts there.
What is real and what is not
- The VM is stack-based, with a flat operand stack, per-frame local slots, a
call stack, and a
try/throwhandler stack. - Host access is capability-only. There is no syscall instruction. A program
talks to the outside world with
CAP_CALL "name" argc, and the VM refuses a capability that the host did not register or that the program’s manifest does not list. - The IR has more instructions than the VM bytecode. The
casmcrate’sOpCodeenum is a superset;casm_to_vmlowers only part of it (see the Instruction Reference). A few IR instructions lower to aNOP; a few are rejected withUnsupported CVM1 opcode. - The
ai_*anddom_*instructions are hooks, not features. AnAI_QUERY(and the other AI opcodes) calls anai_native.querycapability that no CLI provides; an embedder’s stub returns{kind: query, echo: [...], ok: true}and does nothing else. Thedom_*IR instructions lower toNOP. See AI-Native CAST. (spawn/yield/awaitare real: Concurrency.) - Source mapping is carried in each IR instruction’s
meta(line,col); the CVM1 binary does not store it (the text assembler keeps a line→offset map for debuggers only).
Seeing it for yourself
Compile a small program to text assembly:
fn add(a, b) {
return a + b
}
let x = add(2, 3)
io.print("x = ", x)
x = 5
crushc add.crush --emit casm
.func main
PUSH 3
PUSH 2
CALL add
STORE 0
PUSH_STR "x = "
LOAD 0
CAP_CALL "io.print" 2
PUSH_NULL
RET
.func add
STORE 0
STORE 1
LOAD 0
LOAD 1
ADD
RET
Two things to notice, both explained in Program Structure: arguments
are pushed in reverse order (3 then 2), so the callee’s first STORE pops the
first argument into slot 0, the second STORE the next one, and so on; and all top-level statements live in a
function called main.
Next steps
- Program Structure — the JSON IR, the text assembly and the CVM1 binary layout.
- Instruction Reference — every opcode, with stack effects.
- Examples — hand-written programs, all run by the guide’s checker.
- Serialization —
.casm,.casmb,.cvm1and the version gates. - Crush Language Guide — the source language that compiles to it.
Instruction Set Reference
Open as a notebook (.crush-nb, how to run it)
Every instruction has two spellings: the JSON name used in the CASM IR
("op": "push_int") and the CVM1 mnemonic used in the text assembly and the
binary (PUSH). The tables below give both, the operand, and the stack effect.
Behaviour was checked against crush-ast v0.13.0 (dc0d0278, 2026-12-03); the examples at the
end of each section are run by this guide’s checker.
Reading stack effects
a b → c means: pop b (the top), pop a, push c. The rightmost value is
always the top of the stack. … is “whatever was below”.
Operands in the text assembly follow the mnemonic: PUSH 42, LOAD 3,
CAP_CALL "io.print" 1. In the IR they are named fields next to op.
Two instruction sets. The IR (
casm::OpCode) is wider than the VM: it has names the VM bytecode does not (break,continue,awaitwith a handle,call_host,import_var) and the VM bytecode has mnemonics the IR lowering never emits (ROT,PICK,CAST, theMATH_*family). The last section lists exactly which IR ops reach the VM.
Stack
JSON op | CVM1 | Operand | Stack effect | Notes |
|---|---|---|---|---|
push_int | PUSH | value (i64) | → int | |
push_float | PUSH_F64 | value (f64) | → float | |
push_str | PUSH_STR | value (string) | → str | text form: quoted string |
push_bool | PUSH_BOOL | value (bool; 1/0 in text) | → bool | |
push_null | PUSH_NULL | — | → null | |
pop | POP | — | a → | |
dup | DUP | — | a → a a | |
swap | SWAP | — | a b → b a | |
rot | ROT | — | a b c → b a c | as observed on dc0d0278; not Forth’s ROT |
pick | PICK n | n | … → … v | copy the item n below the top (PICK 2 copies the third) |
roll | ROLL n | n | … → … v | move the item n below the top to the top |
| — | NOP | — | — | text/binary only |
.func main
PUSH 1
PUSH 2
PUSH 3
ROLL 2 ; stack is now 2 3 1
CAP_CALL "io.print" 1
CAP_CALL "io.print" 1
CAP_CALL "io.print" 1
HALT
1
3
2
Variables
JSON op | CVM1 | Operand | Stack effect | Notes |
|---|---|---|---|---|
load | LOAD slot | name | → v | push the variable |
store | STORE slot | name | v → | pop into the variable |
export_var | — | name | — | IR only; lowers to NOP (the value stays on the stack) |
import_var | — | name | — | IR only; not lowered |
In the IR a variable is a name; in CVM1 it is a numeric slot (0–65535) local to the current call frame. Frames do not share slots: a callee cannot see its caller’s variables.
Arithmetic and comparison
All binary operators pop b then a and push a OP b.
JSON op | CVM1 | Effect | Notes |
|---|---|---|---|
add sub mul | ADD SUB MUL | a b → a∘b | ADD also concatenates strings |
div | DIV | a b → a/b | integer division on two ints (7/2 = 3), float otherwise |
mod | MOD | a b → a%b | |
neg | NEG | a → -a | |
eq ne | EQ NE | a b → bool | |
lt gt le ge | LT GT LE GE | a b → bool | |
and or | AND OR | a b → bool | eager — both operands are already evaluated. The && / || operators of Crush compile to jumps, not to these |
not | NOT | a → bool | logical not |
bit_and bit_or bit_xor | BITAND BITOR BITXOR | a b → a∘b | |
bit_not | BITNOT | a → ~a | |
shl shr | SHL SHR | a b → a<<b / a>>b |
.func main
PUSH 10
PUSH 3
SUB ; 10 - 3
CAP_CALL "io.print" 1
PUSH 7
PUSH 2
DIV ; integer division
CAP_CALL "io.print" 1
PUSH 12
PUSH 10
BITAND
CAP_CALL "io.print" 1
PUSH 1
PUSH 4
SHL
CAP_CALL "io.print" 1
HALT
7
3
8
16
Control flow
JSON op | CVM1 | Operand | Stack effect | Notes |
|---|---|---|---|---|
jmp | JMP label | target | — | unconditional |
jmp_if_not | JZ label | target | cond → | jump if cond is falsy |
jmp_if | JNZ label | target | cond → | jump if cond is truthy |
call | CALL name | function, argc | args… → [result] | see below |
ret | RET | — | [v] → | return to the caller |
halt | HALT | — | — | stop the whole program |
enter_try | ENTER_TRY label | target | — | push an exception handler |
exit_try | EXIT_TRY | — | — | pop it again (normal exit of the try body) |
throw | THROW | — | v → | unwind to the nearest handler, which receives v on its stack |
break continue | — | — | — | in the IR enum only; the compiler lowers loops to jmps and never emits these |
Jump operands are instruction indices in the IR and byte offsets in the
binary; the text assembler takes label names. A value is falsy if it is false,
null, 0, 0.0, the empty string or an empty array; everything else (including
the string "0") is truthy.
Calling convention. The caller pushes the arguments last first, then
CALLs. The callee’s body begins with one STORE per parameter, in declaration
order, which pops the first argument first. RET returns to the caller; a function
that produces a value leaves it on the stack for RET. Crush functions always end
with PUSH_NULL / RET if they have no explicit return.
.func main
PUSH 5 ; counter
STORE 0
loop:
LOAD 0
JZ done ; stop when the counter reaches 0
LOAD 0
CAP_CALL "io.print" 1
LOAD 0
PUSH 1
SUB
STORE 0
JMP loop
done:
PUSH 4
CALL double
CAP_CALL "io.print" 1
HALT
.func double
STORE 0
LOAD 0
PUSH 2
MUL
RET
5
4
3
2
1
8
Exceptions. ENTER_TRY handler records where to resume; THROW pops a value,
unwinds, and jumps to handler with that value on top of the stack.
.func main
ENTER_TRY handler
PUSH_STR "boom"
THROW
EXIT_TRY ; not reached
JMP end
handler:
CAP_CALL "io.print" 1 ; prints the thrown value
end:
HALT
boom
Collections and objects
JSON op | CVM1 | Operand | Stack effect | Notes |
|---|---|---|---|---|
new_array | NEW_ARRAY n | size | v₁…vₙ → array | pops n values. IR quirk: lowering ignores size and emits NEW_ARRAY 0 — build arrays with new_array + array_push, as the compiler does |
array_push / arr_push | ARR_PUSH | — | array v → array | |
array_pop / arr_pop | ARR_POP | — | array → array v | |
index / arr_get | ARR_GET | — | array i → v | also indexes objects/strings |
arr_set | ARR_SET | — | array i v → array | |
len / arr_len | ARR_LEN | — | array → n | works on strings too |
make_range | MAKE_RANGE | — | start end → range | 1..4 yields 1, 2, 3 |
new_tuple new_list new_vector new_set | NEW_TUPLE n etc. | size | v₁…vₙ → coll | plus TUPLE_PUSH LIST_PUSH VECTOR_PUSH SET_PUSH |
new_obj | NEW_OBJ | — | → obj | empty object |
new_struct | NEW_OBJ | name | → obj | the struct name is dropped on lowering |
set_field | SET_FIELD "f" | name or field | obj v → obj | |
get_field | GET_FIELD "f" | name or field | obj → v |
.func main
PUSH 10
PUSH 20
PUSH 30
NEW_ARRAY 3
DUP
ARR_LEN
CAP_CALL "io.print" 1 ; 3
PUSH 1
ARR_GET
CAP_CALL "io.print" 1 ; 20
NEW_OBJ
PUSH 5
SET_FIELD "x"
GET_FIELD "x"
CAP_CALL "io.print" 1 ; 5
HALT
3
20
5
Strings, math, types
String operations pop their operands in the order shown and push the result.
JSON op | CVM1 | Stack effect |
|---|---|---|
str_contains | STR_CONTAINS | s pattern → bool |
str_split | STR_SPLIT | s delim → array |
str_replace | STR_REPLACE | s old new → s |
str_join | STR_JOIN | array delim → s |
str_starts_with str_ends_with | STR_STARTS_WITH STR_ENDS_WITH | s prefix → bool |
str_to_upper str_to_lower str_trim | STR_TO_UPPER STR_TO_LOWER STR_TRIM | s → s |
math_pow | MATH_POW | base exp → float |
math_sqrt math_abs math_round math_floor math_ceil | MATH_SQRT … | x → float |
type_of | TYPEOF | v → str — "int", "float", "str", "bool", "null", "array", "map" (an object), "tuple", … |
cast | CAST "t" | v → v' — "int", "float", "string" |
| — | VEC_ADD VEC_DOT MAT_MUL | vector/matrix helpers, CVM1 only |
.func main
PUSH_STR "aXb"
PUSH_STR "X"
PUSH_STR "-"
STR_REPLACE
CAP_CALL "io.print" 1 ; a-b
PUSH 2
PUSH 10
MATH_POW
CAP_CALL "io.print" 1 ; 1024.0
PUSH_STR "12"
CAST "int"
PUSH 1
ADD
CAP_CALL "io.print" 1 ; 13
HALT
a-b
1024.0
13
(The Crush-level equivalents of these live in the standard-library capabilities —
str.*, math.*, conv.* — and compile to CAP_CALLs, not to these opcodes. See
the standard library.)
Capabilities
JSON op | CVM1 | Operand | Stack effect |
|---|---|---|---|
cap_call | CAP_CALL "name" argc | name, argc | a₁…aₙ → [result] |
call_host | — | capsule, ic_id, method, argc | IR only, not lowered |
call_interface | — | handle, method, argc | IR only, not lowered |
CAP_CALL pops argc arguments (the first argument was pushed first) and invokes
the named host capability. Whether it then pushes a result depends on the
capability: io.print returns nothing, str.len returns a number. The compiler
knows this and drops the pop it would otherwise emit after a statement-position
call. If the capability is not registered by the host the VM stops with unknown capability: NAME; if it is registered but missing from the manifest, with
capability not declared in manifest: NAME. See the
capability chapter.
Records and Kinds (COSM)
Structs compile to Records of a Kind (crush-ast CRUSH-zorro-43). The
program carries a kind table, written in text assembly as one .cosm line of
JSON (crushc --emit casm prints a readable summary above it as ; comments),
and functions that need their arity for bound methods are written .func name N.
For this source:
struct P { x: Int }
impl P { fn get(self) { return self.x } }
let p = P { x: 7 }
print(p.get())
print(p.x)
7
7
crushc --emit casm writes:
; kind table (COSM): 1 Kind, 0 interfaces
; kind P (crush): fields [x], members [get]
.cosm {"kinds":[{"name":"P","home_lang":"crush","span":{"line":1,"col":1},"storage":{"sealed":{"fields":[{"name":"x","type":"Int"}]}},"semantics":"reference","resolution":"none","receiver":"explicit_ref","construct":"literal","members":[{"name":"get","span":{"line":2,"col":10},"kind":"method","fn":"P::get"}],"equality":"structural"}],"interfaces":[]}
.func main 0
NEW_RECORD "P"
PUSH 7
SET_FIELD "x"
STORE 0
LOAD 0
CALL_MEMBER "get" 0
CAP_CALL "io.print" 1
LOAD 0
GET_FIELD "x"
CAP_CALL "io.print" 1
PUSH_NULL
RET
.func P::get 1
STORE 0
LOAD 0
GET_FIELD "x"
RET
7
7
The member opcodes are GET_MEMBER, SET_MEMBER, HAS_MEMBER, DEL_MEMBER,
CALL_MEMBER name argc, CONSTRUCT kind argc, GET_SLOT, SET_SLOT, IS_KIND
(what a struct pattern tests), COPY (value semantics) and NEW_RECORD.
GET_FIELD/SET_FIELD on a Record are member accesses. Only the CVM1 VMs run
them; FastVM, the JIT and the AOT backends refuse a program that needs them (see
Engines, AOT and Walkers).
Polyglot, concurrency, AI and DOM
JSON op | CVM1 | Notes |
|---|---|---|
exec_lang | EXEC_LANG "json" | run a @python { } / @javascript { } / @bash { } block; the operand is a JSON string with lang, code, var_count and the marshalling lists. Needs the matching polyglot.<lang> capability — see Polyglot |
spawn yield await | SPAWN n YIELD AWAIT | real green tasks on the CVM1 VMs, see Concurrency |
ai_query … (10 names) | AI_QUERY … (10 opcodes) | gated through ai_native.<kind> capabilities; ai_capability_discovery, ai_adaptation_request, ai_semantic_switch are refused. See AI-Native CAST |
dom_query dom_mutate dom_event_listener | DOM_QUERY … | stubs: lowered to NOP; the dom_native.* gates exist only for hand-written CVM1 |
What lowers to CVM1
crush_lang_sdk::compile::casm_to_vm is the bridge from the JSON IR to a runnable
program. It handles exactly these IR operations:
| Lowered | every IR operation except the rows below: the stack, arithmetic, comparison, logic, bit (bit_*, shl, shr), math_*, type_of, cast, string, array/collection, object and COSM member ops, calls, jumps, try/throw, exec_lang, spawn/yield/await, and ten ai_* ops |
| Lowered with a loss | new_array (size ignored: always empty), new_struct (→ NEW_OBJ, name dropped), export_var and the dom_* ops (→ NOP) |
| Rejected | break, continue (no loop target in the instruction), import_var, call_host, call_interface, and the declined ai_capability_discovery, ai_adaptation_request, ai_semantic_switch: they fail with Unsupported CVM1 opcode: NAME at FUNCTION:INDEX |
(crush-ast keeps this classification exhaustive in its
crush-lang-sdk/tests/casm_lowering_completeness.rs; the spot checks below were
run against dc0d0278.) A bit shift lowers and runs:
{
"version": "1.0",
"functions": { "main": { "body": [
{"op": "push_int", "value": 1},
{"op": "push_int", "value": 3},
{"op": "shl"},
{"op": "cap_call", "name": "io.print", "argc": 1},
{"op": "halt"}
] } },
"manifest": { "permissions": ["io.print"] }
}
8
while break is refused:
{
"version": "1.0",
"functions": { "main": { "body": [
{"op": "push_int", "value": 1},
{"op": "break"},
{"op": "halt"}
] } },
"manifest": { "permissions": ["io.print"] }
}
Program Structure
This chapter describes the three forms of CASM from the top down: the JSON IR
(casm::Program), the text assembly, and the CVM1 binary. Field names and layouts
are taken from crates/casm/src/lib.rs, crates/crush-vm/src/assembler.rs and
crates/crush-vm/src/bytecode.rs in crush-ast.
The JSON IR
{
"version": "1.0",
"functions": { "main": { "params": [], "locals": [], "body": [ /* instructions */ ] } },
"manifest": { "permissions": ["io.print"] },
"lang": "crush"
}
| Field | Type | Required | Description |
|---|---|---|---|
version | string | yes | CASM format version. The loader accepts any version whose major is 1 (CASM_VERSION = "1.0"); the Crush compiler writes "1.0". Anything else is rejected at load time. |
functions | object | yes | function name → function definition |
manifest | object | no | {"permissions": [capability names…]}. Defaults to no permissions. |
lang | string | no | source-language hint ("crush", "python", …); informational |
There is no entry field. When the program is lowered to CVM1, execution
starts at the function named main (the assembler picks main if one exists,
otherwise the first function it sees — and functions is an unordered map, so
always name your entry function main). The Crush compiler puts all top-level
statements into main.
Functions
| Field | Type | Required | Description |
|---|---|---|---|
params | array of strings | no (default []) | parameter names |
locals | array of strings | no (default []) | declared local names |
type_hints | object | no | name → type string, tooling only |
body | array of instructions | yes | the code |
params and locals are documentation for tools: the VM does not bind
parameters for you. A call pushes its arguments (last argument first) and jumps; the
callee’s body must begin by store-ing them. This is what the compiler emits for
fn add(a, b):
{ "params": ["a", "b"], "locals": [],
"body": [ {"op":"store","name":"a"}, {"op":"store","name":"b"},
{"op":"load","name":"a"}, {"op":"load","name":"b"},
{"op":"add"}, {"op":"ret"} ] }
Variables are referred to by name in the IR; lowering assigns each distinct name in a function a numeric slot (in order of first use), and slots are local to the call frame.
Instructions
{ "op": "push_int", "value": 42, "instr_lang": "crush", "meta": { "line": 4, "col": 15 } }
| Field | Type | Required | Description |
|---|---|---|---|
op | string | yes | the operation, lower-case snake case ("push_int", "cap_call", …) |
instr_lang | string or null | no | source language of this instruction (the Rust field is lang, the JSON key is instr_lang) |
meta | any JSON | no | free-form metadata; the compiler writes line and col |
| (others) | varies | per op | operation arguments, flattened into the same object |
Operation arguments sit next to op, not in a nested object:
{"op": "push_int", "value": 42}
{"op": "store", "name": "x"}
{"op": "cap_call", "name": "io.print", "argc": 1}
{"op": "call", "function": "add", "argc": 2}
{"op": "jmp", "target": 10}
Jump targets are instruction indices within the same function’s body
("target": 10 means “the eleventh instruction”). A target equal to
body.len() jumps past the end.
A complete program, written by hand and checked by this guide:
{
"version": "1.0",
"functions": {
"main": {
"params": [],
"locals": [],
"body": [
{"op": "push_int", "value": 3},
{"op": "push_int", "value": 2},
{"op": "call", "function": "add", "argc": 2},
{"op": "push_str", "value": "2 + 3 = "},
{"op": "swap"},
{"op": "cap_call", "name": "io.print", "argc": 2},
{"op": "halt"}
]
},
"add": {
"params": ["a", "b"],
"locals": [],
"body": [
{"op": "store", "name": "a"},
{"op": "store", "name": "b"},
{"op": "load", "name": "a"},
{"op": "load", "name": "b"},
{"op": "add"},
{"op": "ret"}
]
}
},
"manifest": { "permissions": ["io.print"] }
}
2 + 3 = 5
(push_str then swap puts the label under the sum, so io.print sees the
label first.)
The manifest
manifest.permissions lists the capability names the program may call. The check
happens at run time, on every cap_call: a capability that is not in the list is
refused with capability not declared in manifest: NAME, even if the host has it
registered. When the Crush compiler lowers a program it adds every capability the
code actually calls, so a manifest only matters when you write or edit IR by hand
(or want to restrict a program).
The text assembly
This is what crushc --emit cvms prints and crush-run run FILE.cvms /
crush-compile read (.cvms, CVM1 assembly; up to v0.9.0 it was .casm, which
crush-run still accepts with a note). One instruction per line:
; a comment (# also works)
.func main ; start of function "main"
PUSH 40
PUSH 2
ADD
CAP_CALL "io.print" 1
JMP done ; jump to a label
done: ; a label is "name:" on its own line (or before an instruction)
HALT
.func NAMEbegins a function. Functions share one flat code section; aCALLmust name a function defined somewhere in the file (forward references are fine — the assembler runs two passes).LABEL:marks a jump target;JMP/JZ/JNZ/ENTER_TRYtake a label name.- Mnemonics are case-insensitive. Operands:
PUSHtakes a signed 64-bit integer,PUSH_F64a float,PUSH_STRa double-quoted string (Rust{:?}escapes), andLOAD/STOREa slot number0–65535. CAP_CALL "name" argctakes the capability name and the argument count (0–255).- The assembler records
main(or, failing that, the first.func) as the entry point and builds a function table. A file with no.funcat all is a single anonymous routine starting at offset 0.
.func main
PUSH 40
PUSH 2
ADD
CAP_CALL "io.print" 1
HALT
42
crush-run does not infer permissions from assembly text: list them with .cap NAME
lines (as crushc --emit cvms writes them), or pass the capabilities the program
uses with --cap (e.g. crush-run run prog.cvms --cap io.print).
The CVM1 binary
crushc x.crush -o x.cvm1 writes this layout (all multi-byte integers
big-endian):
offset size field
0 4 magic "CVM1"
4 1 version 2, or 3 when a kind table follows (1 to 3 are accepted)
5 2 manifest_len
7 n manifest JSON: {"runtime", "permissions", "name"?, "functions"?, "entry"?}
2 n_consts
… consts n_consts × ( 2-byte length + UTF-8 bytes )
4 code_len
… code flat bytecode
(version 3 only)
1 kt_format 1, or 2 for a module that needs a newer COSM
4 kt_len
… kind table the program's kinds (structs, traits) as canonical COSM JSON
A program with no struct or trait is written as version 2, as before; one with
kinds gets version 3 and the trailing kind table.
The constant pool holds every string the code names: PUSH_STR literals, capability
names and function names. A capability name or a string is limited to 65 535 bytes
and the pool to 65 536 entries because indices are 16-bit. The functions table in
the manifest maps each function name to its byte offset in code; entry names the
function the VM starts in.
Each instruction is one opcode byte followed by a fixed-size operand:
| Operand | Size | Used by |
|---|---|---|
| none | 0 | most opcodes |
i64 | 8 | PUSH, PUSH_BOOL |
f64 | 8 | PUSH_F64 |
| const index | 2 | PUSH_STR, CALL, GET_FIELD, SET_FIELD, CAST, EXEC_LANG, the AI_*/DOM_* opcodes |
| slot | 2 | LOAD, STORE |
| count | 2 | NEW_ARRAY, NEW_TUPLE, NEW_LIST, NEW_VECTOR, NEW_SET, PICK, ROLL, SPAWN |
| code offset | 4 | JMP, JZ, JNZ, ENTER_TRY (byte offset into code) |
| capability | 3 | CAP_CALL: 2-byte const index of the name + 1-byte argc |
Jumps in the binary are byte offsets, unlike the IR’s instruction indices; the assembler converts labels for you.
You can turn a binary back into text with crush_lang_sdk::disassemble; it prints
.func lines and synthesises L<offset>: labels for jump targets.
Metadata and source maps
The IR keeps meta.line/meta.col on each instruction, and casm::debug_info
defines DebugInfo/SourceLocation for mapping a runtime failure back to the
source (format_runtime_error_with_location). The CVM1 binary carries none of it:
Program::source_map (line → code offset) exists only on a freshly assembled
program, for debuggers, and is not serialized.
See also
- Instruction Reference
- Serialization — file extensions and version checks
- CAST — the layer above
Serialization Formats
A Crush program exists in several on-disk forms, one per layer of the pipeline. This chapter lists them, says which tool reads and writes each, and describes the version checks that gate loading. For the layouts themselves see Program Structure.
| Layer | Form | Extension | Written by | Read by |
|---|---|---|---|---|
| source | Crush text | .crush | you | crushc, crush-run, crush run |
| CAST | JSON | .cast.json (any non-.castb/.cbor name) | walkers, agents, casm-side tools | crush_cast::Program::{deserialize,load}, crush_frontend::compile_cast |
| CAST | CBOR | .castb, .cbor | crush_cast::Program::save | same |
| CASM IR | JSON | .casm | casm::Program::{serialize,save}, crushc --emit casm | casm::Program::{deserialize,load}, crush-run run, crush-compile |
| CASM IR | MessagePack | .casmb | casm::Program::{serialize,save} | casm::Program::{deserialize,load} |
| CASM text | assembly | .cvms (.casm before v0.10.0) | crushc --emit cvms, you | crush-run run, crush-compile |
| CVM1 | binary | .cvm1 | crushc -o, crush build, crush-compile | crush-run run, crush run, Runtime::run_blob |
CASM IR: JSON (.casm)
This is the readable form of a compiled program and the one you diff, commit and
generate from tools. casm::Program::load / save choose the codec from the file
extension: .casmb means binary, anything else is JSON.
{
"version": "1.0",
"functions": {
"main": {
"params": [],
"locals": [],
"body": [
{"op": "push_int", "value": 42},
{"op": "cap_call", "name": "io.print", "argc": 1},
{"op": "halt"}
]
}
},
"manifest": { "permissions": ["io.print"] }
}
42
The compiler writes pretty-printed JSON with meta on every instruction, so a
compiled program is verbose: the five-line add program in the
overview is about 3 KB as IR JSON and 199 bytes as .cvm1.
CASM IR: MessagePack (.casmb)
Program::serialize(Format::Binary) writes the line #!/usr/bin/env crush run
followed by the program as MessagePack (via rmp_serde), and save marks the file
executable on Unix. The reader skips a leading #! line.
A .casmb file can be read back (from crush-ast v0.3.9 through v0.11.2 every
load failed with invalid type: sequence, expected a map; CRUSH-392 fixed it on
main). This program is written as .casmb and loaded again:
{
"version": "1.0",
"functions": { "main": { "body": [ {"op": "halt"} ] } }
}
round-tripped 1 functions
crush run and crush-run run take .crush, CAST (.cast.json, .castb), CASM
IR JSON (.casm), assembly text (.cvms) and .cvm1, one extension per format
(crush-ast #365, v0.10.0). Assembly text in a .casm file still runs, with a note
asking you to rename it to .cvms.
CVM1 (.cvm1)
The executable form: CVM1 magic, a version byte, a JSON manifest, a constant
pool and a flat code section, described byte by byte in
Program Structure.
crushc add.crush -o add.cvm1 # or: crush build add.crush
crush-run run add.cvm1
crush-compile prog.cvms -o prog.cvm1 --cap io.print --name prog # text assembly -> CVM1
Version gates
Every loader fails closed on an incompatible version, comparing the major component only (minor bumps stay compatible):
| Format | Constant | Accepts | Error |
|---|---|---|---|
| CASM IR | casm::CASM_VERSION = "1.0" | version with major 1 ("1.0", "1.0.0", "1.4") | version mismatch at casm boundary: expected 1.0, found 2.0 |
| CVM1 | bytecode::VERSION = 3 | version byte 1 to 3 | UnsupportedVersion(n) |
| CAST | crush_cast::CAST_VERSION = "0.1.0" | cast_version with major 0 | version mismatch at cast boundary: expected 0.1.0, found … |
The old docs said "version": "0.1" for CASM; that is now rejected (major 0).
{ "version": "0.1", "functions": { "main": { "body": [ {"op": "halt"} ] } } }
Every producer now writes cast_version: "0.1.0", the front end included, so a
CAST dump from the compiler loads again with the versioned loader (from v0.3.9
through v0.9.0 the front end stamped "1.0.0", which that loader rejected). See
CAST.
Rust API
use casm::{Format, Program};
fn main() -> anyhow::Result<()> {
let program = crush_lang_sdk::compile::compile_crush_to_casm(
"io.print(6 * 7)",
)?;
// JSON IR, round trip through bytes.
let bytes = program.serialize(Format::Json)?;
let back = Program::deserialize(&bytes, Format::Json)?;
assert_eq!(back.functions.len(), program.functions.len());
// Lower to a runnable CVM1 program and execute it.
let vm_program = crush_lang_sdk::compile::casm_to_vm(&back)?;
let result = crush_lang_sdk::Runtime::new().run(&vm_program)?;
print!("{}", result.output);
assert_eq!(result.output, "42\n");
// CVM1 blob round trip.
let blob = vm_program.to_blob();
let result = crush_lang_sdk::Runtime::new().run_blob(&blob)?;
assert_eq!(result.output, "42\n");
Ok(())
}
Format::from_path picks Json or Binary from a path. Program::save(path) and
Program::load(path) combine that with file I/O.
Practical advice
- Distribute
.cvm1; it is the format with a working load path in every tool, a magic number and a version byte. - Commit
.crushsource, not generated IR; regenerate IR when you need to inspect it (crushc --emit casmfor text,compile_crush_to_casmfor JSON). - When an agent produces programs, have it emit CAST JSON and let the compiler produce CASM — see the doctrine there.
CASM Examples
Open as a notebook (.crush-nb, how to run it)
Every program here is CASM text assembly — the form you can write by hand and run
with crush-run run FILE.cvms --cap io.print (.cvms since crush-ast v0.10.0; a
.casm file of text still runs, with a note to rename it) — and every one is executed by this
guide’s checker against crush-ast dc0d0278, with the output shown. The JSON IR is
covered in Program Structure and
Serialization. Opcode details are in the
Instruction Reference.
All programs print with CAP_CALL "io.print" N, so run them with --cap io.print
(an assembly file carries no permissions unless it has .cap NAME lines).
1. Hello, world
.func main
PUSH_STR "Hello, CASM!"
CAP_CALL "io.print" 1
HALT
Hello, CASM!
io.print takes any number of arguments (here 1), prints them back to back and
adds a newline.
2. Variables and arithmetic
STORE n pops into slot n; LOAD n pushes it back.
.func main
PUSH 6
STORE 0 ; a = 6
PUSH 7
STORE 1 ; b = 7
LOAD 0
LOAD 1
MUL
STORE 2 ; product = a * b
PUSH_STR "6 * 7 = "
LOAD 2
CAP_CALL "io.print" 2
HALT
6 * 7 = 42
3. Conditionals
JZ jumps when the popped value is falsy, so an if compiles to a JZ over the
“then” branch plus a JMP over the “else” branch.
.func main
PUSH 3
STORE 0 ; n = 3
LOAD 0
PUSH 2
GT ; n > 2
JZ else
PUSH_STR "big"
CAP_CALL "io.print" 1
JMP end
else:
PUSH_STR "small"
CAP_CALL "io.print" 1
end:
HALT
big
4. Loops
.func main
PUSH 1
STORE 0 ; i = 1
PUSH 0
STORE 1 ; sum = 0
loop:
LOAD 0
PUSH 5
GT ; i > 5 ?
JNZ done
LOAD 1
LOAD 0
ADD
STORE 1 ; sum = sum + i
LOAD 0
PUSH 1
ADD
STORE 0 ; i = i + 1
JMP loop
done:
PUSH_STR "sum 1..5 = "
LOAD 1
CAP_CALL "io.print" 2
HALT
sum 1..5 = 15
5. Functions
Arguments are pushed last first; the callee’s first instructions STORE its
parameters in order, so the first STORE receives the first argument. RET
returns whatever the callee left on top of the stack.
.func main
PUSH 3 ; second argument (b)
PUSH 10 ; first argument (a)
CALL sub
CAP_CALL "io.print" 1
HALT
.func sub
STORE 0 ; a
STORE 1 ; b
LOAD 0
LOAD 1
SUB ; a - b
RET
7
Recursion works the same way (each call gets fresh slots). The default call-depth quota is 256:
.func main
PUSH 10
CALL fact
CAP_CALL "io.print" 1
HALT
.func fact
STORE 0 ; n
LOAD 0
PUSH 1
LE
JNZ base
LOAD 0
LOAD 0
PUSH 1
SUB
CALL fact ; fact(n - 1)
MUL ; n * fact(n - 1)
RET
base:
PUSH 1
RET
3628800
6. Arrays and objects
.func main
PUSH 10
PUSH 20
PUSH 30
NEW_ARRAY 3 ; [10, 20, 30]
STORE 0
LOAD 0
PUSH 40
ARR_PUSH ; array v -> array
STORE 0
PUSH_STR "length: "
LOAD 0
ARR_LEN
CAP_CALL "io.print" 2
PUSH_STR "second: "
LOAD 0
PUSH 1
ARR_GET
CAP_CALL "io.print" 2
NEW_OBJ
PUSH_STR "Ada"
SET_FIELD "name" ; obj v -> obj
STORE 1
LOAD 1
GET_FIELD "name"
CAP_CALL "io.print" 1
HALT
length: 4
second: 20
Ada
7. Errors
ENTER_TRY handler … THROW jumps to the handler with the thrown value on the
stack; EXIT_TRY retires the handler when the body finishes normally.
.func main
ENTER_TRY handler
PUSH_STR "disk full"
THROW
EXIT_TRY
JMP end
handler:
STORE 0
PUSH_STR "recovered from: "
LOAD 0
CAP_CALL "io.print" 2
end:
HALT
recovered from: disk full
A capability that is not registered, or a type error, is not catchable this way:
it ends the program with a [runtime] error.
8. Host capabilities
File access needs the --fs flag and the capability in the manifest, so run
this one as crush-run run prog.cvms --cap io.print --cap fs.exists --fs:
.func main
PUSH_STR "no-such-file.txt"
CAP_CALL "fs.exists" 1
CAP_CALL "io.print" 1
HALT
0
Two separate checks apply. The host’s grants come first: leave out --fs and
nothing runs (needs capabilities this run does not grant; nothing was run: --fs: fs.exists). With --fs but without --cap fs.exists, the program starts, and
the VM stops at the call with capability not declared in manifest: fs.exists
(the host registered it, but the program’s manifest doesn’t list it):
.func main
PUSH_STR "no-such-file.txt"
CAP_CALL "fs.exists" 1
CAP_CALL "io.print" 1
HALT
9. What the compiler writes
The text assembly is also what crushc --emit casm prints, so you can read how
Crush constructs lower. Labels there are byte offsets (L42).
if / else:
let n = 3
if n > 2 {
io.print("big")
} else {
io.print("small")
}
big
.func main
PUSH 3
STORE 0
LOAD 0
PUSH 2
GT
JZ L42
PUSH_STR "big"
CAP_CALL "io.print" 1
JMP L49
L42:
PUSH_STR "small"
CAP_CALL "io.print" 1
L49:
PUSH_NULL
RET
try / catch:
try {
throw "bad"
} catch e {
io.print("caught ", e)
}
caught bad
.func main
ENTER_TRY L15
PUSH_STR "bad"
THROW
EXIT_TRY
JMP L28
L15:
STORE 0
PUSH_STR "caught "
LOAD 0
CAP_CALL "io.print" 2
L28:
PUSH_NULL
RET
for x in array expands into an index loop: the array in slot 1, the index in
slot 2, and ARR_LEN … GT … JZ as the loop test:
let t = 0
for x in [1, 2, 3] { t = t + x }
io.print(t)
6
.func main
PUSH 0
STORE 0
NEW_ARRAY 0
PUSH 1
ARR_PUSH
PUSH 2
ARR_PUSH
PUSH 3
ARR_PUSH
STORE 1
PUSH 0
STORE 2
L60:
LOAD 1
ARR_LEN
LOAD 2
GT
JZ L114
LOAD 1
LOAD 2
ARR_GET
STORE 3
LOAD 0
LOAD 3
ADD
STORE 0
LOAD 2
PUSH 1
ADD
STORE 2
JMP L60
L114:
LOAD 0
CAP_CALL "io.print" 1
PUSH_NULL
RET
Notice the array literal: NEW_ARRAY 0 followed by one ARR_PUSH per element —
which is why the IR’s new_array never
needs its size.
Tips
- Comment freely.
;and#start a comment in the text assembly (JSON has no comments). - Name your labels. The assembler resolves them; you never count bytes.
- Keep the entry function called
mainand put it first. - Mind the stack. Each
CAP_CALLto a value-returning capability leaves a value; a stray one atHALTshows up asstack=1in the[steps=…, stack=…]line thatcrush-runprints. Compare it to0when debugging. - To see what a Crush construct costs, compile it:
crushc FILE.crush --emit casm.
Glossary
AOT (ahead-of-time) backends
crush-aot and crush-aotc translate CASM to Rust or C source for native
compilation. They live in the crush-ast repository and are not published to
crates.io. They refuse, by name, programs that use instructions they do not support
(closures, method calls, spawn, @lang blocks, most standard-library calls). See
Engines, AOT and Walkers.
Capability
A named host function that a Crush program may call, written as a dotted call
(fs.read(path), io.print(x)). A capability exists only if the host registered it
(on the CLI, with a flag such as --fs) and the program’s manifest lists it. There
is no ambient authority. See Capabilities.
CAST (Crush AST)
The JSON abstract syntax tree between front ends and the compiler: produced by the Crush parser and the language walkers, or written directly by an agent. See CAST.
CASM (Crush Assembly)
The stack-machine instruction set programs compile to. The name covers the IR
(JSON, casm::Program, .casm files), the text assembly (.func/PUSH/CAP_CALL,
.cvms files) and, one step down, the CVM1 binary. See
CASM.
CVM1
The binary bytecode format the VM executes (.cvm1): magic CVM1, a version byte, a
JSON manifest, a constant pool and flat code. Also the name of the default
interpreter. See Program Structure.
Embedder / host
The program that runs Crush code and decides which capabilities and quotas it gets —
the crush-run CLI, or your own Rust program using crush-lang-sdk.
FastVM
A second interpreter in crush-vm, lowered from the IR with pre-resolved symbols,
aimed at loops with many iterations. Slower than CVM1 on tiny programs.
Gate
A check that refuses an operation unless it was enabled. Examples: the --polyglot
flag for @lang blocks; the manifest check on CAP_CALL; the ai_native.*
capability names that guard the AI opcodes.
Lowering
Turning one representation into the next: CAST → CASM IR (the compiler), and
CASM IR → CVM1 (casm_to_vm). Lowering can lose information; the
instruction reference lists what.
Manifest
The list of capability names a program may call ({"permissions": [...]}), carried
in the CASM IR and in the CVM1 header. Checked on every CAP_CALL.
Polyglot block
A @python { }, @javascript { } or @bash { } block inside a Crush program. It
runs in a host subprocess, with free variables marshalled in and assigned variables
marshalled out. Needs --polyglot. See Polyglot.
Quota
A resource limit the VM enforces: instruction count, stack slots, output bytes, call depth, and wall-clock time per polyglot subprocess.
Sandboxed polyglot
An optional, off-by-default, Linux-only build feature (crush-vm’s
sandboxed-polyglot) that runs polyglot blocks under bubblewrap, provisioning
interpreters and dependencies with buckets. Without it, polyglot blocks have the
host process’s full authority.
SDK (crush-lang-sdk)
The Rust crate to embed Crush: Runtime, HostCapsBuilder, ProgramBuilder, and the
compile module. It also provides the crush, crushc, crush-run, crush-compile,
crush-repl and crush-diff binaries.
Kind (COSM)
The run-time type of a struct instance (a Record): its fields, methods and the
object semantics @kind(...) chose (reference or value, receiver, lookup, …). COSM,
the Crush Object Semantic Model, is how crush-ast describes every language’s objects.
See Structs, Methods and Kinds.
Slot
A numbered local variable in a CVM1 call frame (LOAD 3, STORE 3). The IR names
variables; lowering assigns slots.
Stub
An implemented interface with placeholder behaviour. The ai_* and dom_*
instructions are stubs today. See
AI-Native CAST.
Walker
A front end that translates source in some language into CAST (Python, JavaScript,
Rust, Bash and others, in crush-lang-* crates); crush-walk-run FILE runs the
result. Coverage varies by language and untranslatable constructs are refused. Walkers
are not the same thing as @lang execution, which runs a real interpreter (only
Python, JavaScript and Bash blocks). See Engines, AOT and Walkers.
Quick Reference
Open as a notebook (.crush-nb, how to run it)
Cheat sheets for the toolchain, the Crush language and CASM. Every code block that
can run is run by the guide’s checker against crush-ast dc0d0278. Details live in
the chapters linked from each heading.
Command line (Getting Started)
| Command | Does |
|---|---|
crush run FILE [flags] | run a .crush, .cast.json, .casm (CASM JSON), .cvms (assembly) or .cvm1 file |
crush build FILE.crush | compile to .cvm1 |
crush-run run FILE [flags] | same as crush run; all the capability flags live here |
crush-run caps [FILE] | list the capabilities of your build, or what FILE needs (runs nothing) |
crushc FILE.crush -o OUT.cvm1 | compile; --emit casm|ast|types prints a layer; -C only checks |
crush-compile FILE.cvms -o OUT.cvm1 --cap NAME | assemble CVM1 assembly text (or CASM JSON .casm) |
crush repl / crush-repl | interactive REPL (.help, .quit) |
crush doctor | which polyglot interpreters are on PATH |
crush debug FILE --step --inspect | breakpoints, step, watch, print (Debugging) |
crush gui run FILE --ui | a program that draws a window; needs the separate crush-gui (Windows) |
crush-aotc run FILE.crush | ahead-of-time compile via rustc (--backend gcc) and run |
crush-walk-run FILE.py | walk a Python/JS/Rust/… file to CAST and run it |
Capability flags (everything is off unless you pass it, except the standard
library, which --no-stdlib removes): --fs --fs-root DIR --env --time
--net (HTTP) --tcp --tcp-listen (raw sockets) --process --crypto --db PATH --graphics --bus --task --akg
--polyglot --cap NAME. A program that needs an ungranted capability is refused
before it runs; --message-format json makes errors one JSON object per line (Diagnostics). Quotas:
--max-steps (default 1,000,000, or unlimited), --max-wall-ms (30,000 for the
whole run, or unlimited), --max-stack (4,096), --max-output (1 MiB),
--max-call-depth (256).
Language (Syntax)
Variables and functions
let x = 42
let name: String = "Alice"
fn add(a: Int, b: Int) -> Int {
return a + b
}
fn greet(who) {
print("Hello, " + who)
}
greet(name)
print(add(x, 1))
Hello, Alice
43
- Semicolons are optional. Comments are
//and#. Strings use"…"or'…'. - A function returns a value only with
return; falling off the end yieldsnull. print(x)takes exactly one argument;io.print(a, b, …)takes any number.- No
let mut, noT?types, no workingimport(CRUSH-110).
Closures (Closures)
fn make_counter() {
let c = 0
return || {
c = c + 1
return c
}
}
let next = make_counter()
next()
print(next())
let sq = |x| x * x
print(5 |> sq)
2
25
Control flow (Control Flow)
let n = 3
if n > 5 {
print("big")
} else if n > 1 {
print("medium")
} else {
print("small")
}
let i = 0
while i < 2 {
i = i + 1
}
for k in 0..3 {
print(k)
}
for item in ["a", "b"] {
print(item)
}
medium
0
1
2
a
b
0..3 excludes the end, 0..=3 includes it. for also walks a string’s
characters and a map’s keys. break and continue work in while and for.
match v { 1 => "one", P { x: a } => a, _ => "other" } matches literals,
bindings and struct patterns; return match … returns its value.
Operators (Operators)
+ - * / % · == != < > <= >= · && || ! or and or not (short-circuit) · unary
- · pipeline |> · ranges a..b, a..=b. There is no **, //, +=, bitwise
operator or ternary. Int overflow and division by zero are run-time errors.
Errors
try {
throw "disk full"
} catch e {
print("caught: " + e)
}
caught: disk full
Structs and objects (Types)
struct Point { x: Int, y: Int }
impl Point {
fn sum(self) { return self.x + self.y }
}
let p = Point { x: 3, y: 4 }
let o = {"name": "crush"}
o["lang"] = "en"
print(p.sum())
print(o.name + "/" + o["lang"])
7
crush/en
Structs are sealed (no undeclared fields), references by default
(@kind(semantics: value(copy)) for values), and == compares fields. See
Structs, Methods and Kinds.
Capabilities (Capabilities)
Capability calls are dotted and have no @. They exist only if you enabled
them:
if fs.exists("notes.txt") {
print(fs.read("notes.txt"))
} else {
print("no notes")
}
no notes
io.print("a", "b", 3)
print(str.len("héllo"))
ab3
6
Polyglot blocks (Polyglot)
@python -> out { }, @javascript -> out { } and @bash { } run as host
subprocesses, only with --polyglot, and with the host’s full authority (no sandbox
by default). Names a block reads are passed in; the names after -> come back.
Without the flag the program is refused:
@python {
print("hello from python")
}
Types (Types)
| Type | Example | Notes |
|---|---|---|
Int | 42, 0x2A, 0b101 | 64-bit, checked overflow |
Float | 3.14, 1.5e3 | exponent form since 0.11 |
String | "hello", 'hello' | UTF-8; len counts bytes |
Bool | true | |
Null | null | |
| array | [1, 2, 3] | |
| object | {"key": "value"} | insertion-ordered |
| struct | struct P { x, y } | one line; P { x: 1, y: 2 } |
| function | |x| x + 1, fn names | values; closures capture by reference |
Annotations (: Int, -> Int) are checked at compile time and are optional.
Capabilities at a glance
| Always on | io.print io.read str.concat str.len conv.chr conv.ord |
|---|---|
| Standard library (default) | str.* math.* conv.* collections.* json.* path.* regex.* sys.args … |
--fs | fs.read fs.write fs.exists fs.list fs.mkdir … |
--env | env.get env.all env.home_dir |
--time | time.now time.now_ms time.now_iso time.elapsed time.sleep |
--net | net.http_get net.http_post |
--process | process.exec |
--crypto | crypto.sha256 crypto.random |
--db PATH | db.query db.execute |
--polyglot | @python @javascript @bash |
CASM text assembly (CASM)
.func main
PUSH 40
PUSH 2
ADD
CAP_CALL "io.print" 1
HALT
42
| Group | Mnemonics |
|---|---|
| Stack | PUSH n PUSH_F64 x PUSH_STR "s" PUSH_BOOL 0|1 PUSH_NULL POP DUP SWAP ROT PICK n ROLL n |
| Variables | LOAD slot STORE slot |
| Arithmetic | ADD SUB MUL DIV MOD NEG |
| Compare / logic | EQ NE LT GT LE GE AND OR NOT |
| Bits | BITAND BITOR BITXOR BITNOT SHL SHR |
| Control | JMP label JZ label JNZ label CALL name RET HALT ENTER_TRY label EXIT_TRY THROW |
| Capabilities | CAP_CALL "name" argc |
| Collections | NEW_ARRAY n ARR_GET ARR_SET ARR_LEN ARR_PUSH ARR_POP NEW_OBJ GET_FIELD "f" SET_FIELD "f" |
| Strings / math | STR_CONTAINS STR_SPLIT STR_REPLACE STR_JOIN STR_TRIM STR_TO_UPPER MATH_POW MATH_SQRT … |
Stack effects and the JSON-IR names are in the
Instruction Reference. Remember: arguments are pushed
first argument first (PUSH_STR "a", PUSH_STR "b", CAP_CALL "io.print" 2
prints ab), and an assembly file (.cvms) needs --cap (or a .cap line) for
every capability it calls.
Language Comparisons
Open as a notebook (.crush-nb, how to run it)
How Crush relates to the languages people usually compare it with. Crush is alpha:
the language is small, the standard library is a set of host capabilities, and several
features in its design (remote imports, an executing AI layer) are not implemented yet.
The comparisons below are about what is real today (verified against crush-ast
dc0d0278).
What Crush is for
- Running untrusted or semi-trusted scripts with explicit authority. A program can
only do what the host switched on (
--fs,--net,--process, …); everything else is simply not registered. See Capabilities. - Embedding. The VM is a Rust library (
crush-lang-sdk) with quotas for steps, stack, output and call depth, so a host can bound what a script costs. - One front door for several languages.
@python,@javascriptand@bashblocks run inside a Crush program, with values marshalled in and out. They are host subprocesses, so they are gated by--polyglotand carry the host’s full authority unless you use the opt-in sandbox lane. See Polyglot.
It is not a general-purpose replacement for Python or JavaScript: there is no
package ecosystem to speak of, only warning-level visibility between packages (pub, see Modules), and a small
standard library.
Crush vs Python
| Crush | Python | |
|---|---|---|
| Typing | dynamic; annotations (x: Int) are optional and checked at compile time | dynamic; hints are not enforced |
| Ambient authority | none — files, network, processes need a capability flag | everything the OS user can do |
| Execution | compiled to CVM1 bytecode, run by a Rust VM with quotas | compiled to bytecode, run by CPython |
| Functions | fn and |x| … lambdas; values and closures | def, lambda |
| Classes | struct + impl + trait; @kind(resolution: c3, …) gives Python’s MRO | class |
| Ecosystem | tiny; reach Python through @python { } | huge |
fn greet(name) {
print("Hello, " + name + "!")
}
greet("Alice")
Hello, Alice!
In Python that is def greet(name): print(f"Hello, {name}!") — no string
interpolation in Crush, so concatenate with +.
Crush vs JavaScript
| Crush | JavaScript | |
|---|---|---|
| Authority | capability-gated | Node has full OS access; browsers are sandboxed by the platform |
| Functions | first-class, closures (capture by reference) | first-class, closures |
| Async | green tasks: spawn/yield/await, async fn; parallel_map for threads | native promises and an event loop |
| Syntax | braces, optional semicolons, let, "…" or '…' strings | similar |
Crush vs Rust
Crush’s VM is written in Rust and Crush embeds into Rust programs, but the languages are opposites in philosophy: Rust is statically typed with ownership; Crush is a dynamic scripting language whose safety comes from the host (capabilities and quotas) rather than the type system.
Crush vs Bash
| Crush | Bash | |
|---|---|---|
| Values | typed (ints, floats, strings, arrays, objects) | strings |
| Running programs | process.exec with --process, or an @bash { } block | native |
| Errors | try / catch, throw | exit codes |
| Authority | capability-gated | everything the user can do |
Performance
Crush has an interpreter (CVM1), a second interpreter (FastVM, aimed at hot loops),
and — in the repository, not on crates.io — ahead-of-time backends (crush-aot,
crush-aotc) that translate CASM to Rust or C. The repository’s own benchmark
(docs/benchmarks/BENCHMARKS.md, one process per iteration) gives these figures
relative to the CVM1 interpreter:
| Tier | simple (return 42) | compute (14-op arithmetic chain) |
|---|---|---|
| CVM1 interpreter | 1.0× | 1.0× |
| FastVM | 0.09× | 0.5× |
| AOT via rustc | 42× | 130× |
| AOT via gcc | 54× | 317× |
| AOT via clang | 55× | 378× |
Read these with care. The programs are tiny, the AOT compilers constant-fold the
whole compute chain into a single value, FastVM loses on tiny programs and is meant
for loops with thousands of iterations, and the scripting-language rows in that
document measure interpreter start-up, not throughput. They show that the AOT path
can remove the stack machine’s overhead; they are not a claim about how fast real
Crush programs run. The AOT backends also reject programs that use instructions they
do not support.
When to use Crush
✅ A good fit:
- You embed a scripting layer in a Rust application and need to bound and gate what scripts can do.
- You want agents or tools to emit programs as validated data (CAST) rather than as source text.
- You are experimenting with a capability-first language.
❌ Look elsewhere when:
- You need a mature ecosystem, libraries or tooling — use Python or JavaScript.
- You need enforced module boundaries today (
pubis per package and, until 1.0, a violation is only a warning; see Modules). - You need hardened isolation of foreign-language code: polyglot blocks run as host processes unless you build the optional bubblewrap sandbox lane, which is Linux-only.
Migrating to Crush
From Python
def→fn; indentation → braces.print(a, b)→print(x)takes one argument; useio.print(a, b)for several (they are joined with no separator).f"…{x}"→"…" + x.and/or/not→&&/||/!;range(n)→0..n.- Anything that touches files, the network or processes needs the matching capability flag.
- Keep code you cannot port in an
@python { }block while you migrate.
From JavaScript
function→fn;const/let→let(there is noconst).- Strings use double quotes only.
console.log(x)→print(x).- No arrow functions yet — name the function.
- Keep code you cannot port in an
@javascript { }block.
From Bash
- Wrap shell commands in
@bash { }(needs--polyglot) or callprocess.exec("cmd", "arg")(needs--process). - Use Crush for the control flow and data handling around them.