Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

rut

rut is a small, statically typed, embeddable scripting language with Rust-flavored syntax, implemented in Rust. It is designed to be the scripting layer of host applications — typically UI apps — replacing JavaScript engines with a language whose type system is not erased: types exist at runtime, drive bytecode specialization, and make the host boundary fully checked.

Syntax feels like TypeScript (simple enum, the class shape, anonymous functions), with Go-flavored structural interfaces (interface + satisfaction by having the members) and Kotlin-style structured concurrency (async/await over poll-based futures). The runtime is a bytecode VM with no JIT — deterministic, fuel-metered, and small enough to embed everywhere a wasm binary fits.

use ink::{ Logger };
use pouch::{ Vec };

fn sieve(limit: i32) -> Vec<i32> {
    let mut marks = Vec<u8>::filled(0, limit + 1);
    let primes: Vec<i32> = Vec::new();
    for (let mut i = 2; i <= limit; i += 1) {
        if (marks[i] == 0) {
            primes.push(i);
            let mut m = i * i;
            while (m <= limit) {
                marks[m] = 1;
                m += i;
            }
        }
    }
    return primes;
}

entry fn main() {
    let log = Logger("sieve");
    let primes = sieve(100);
    log.info(f"{primes.len()} primes up to 100, last={primes[primes.len() - 1]}");
}

Where to go next

If you want to…Read
Use rut in your Rust project (and the temporary-run CLI)Quick Start
Learn the language hands-onthe Tutorial
Understand why the language is shaped this wayCore Concepts
Study complete programsExamples
Look up exact rulesthe Reference

The book is also served live at https://rut.hpp2334.com, and the wasm playground — where every snippet on this site runs in the browser — lives at https://playground.rut.hpp2334.com.

The repo

crates/     the implementation: lexer, parser, compiler, VM, std, CLI, wasm
rut/        the in-tree rut packages (core, pouch, ink, json, http, …)
examples/   seven runnable end-to-end projects
demo/       the wasm playground
docs/       this book (built with mdbook)

Build the CLI binary from a checkout:

cargo build --release -p rut-cli   # the `rut` binary: run / fmt / pack / dump

No checkout? cargo +nightly-2026-07-15 install --git https://github.com/hpp2334/rut.git --locked rut-cli puts the same binary on your PATH (Quick Start).

That binary is the temporary-run lane — running module directories and bundles, fmt, dump, pack. To use rut in your own project, depend on the engine crates as a git dependency — the crates are not on crates.io (Quick Start).

License

MIT OR Apache-2.0.

Installation

rut reaches your project in two ways, ranked by intent:

  1. Depend on the engine crates from your own Rust project through a Cargo git dependency. This is the intended path — your Cargo.toml names this repository and a commit, and the engine (lexer, parser, compiler, typed bytecode, VM) builds as part of your build, ready to embed.
  2. Build the rut CLI from a checkout of this repository — the temporary-run lane: running module directories and bundles, fmt, dump, pack. The fastest way to poke at the language; not the way anyone ships.

Both lanes build the same engine, and the crates are not published to crates.io — the git dependency is the only consumption path.

Use rut in your project

Prerequisites

  • Rust (nightly) — the repo pins an exact nightly in rust-toolchain.toml (because rut-vm-threaded uses incomplete features); rustup installs it on the first build. Any recent rustup works.

  • git — to fetch the dependency.

  • Node.js 20+ — only if you want to build or drive the wasm playground (the rest of the book does not need it).

No checkout of this repository is needed — your Cargo.toml does everything.

Depend on the crates

Name the engine crates as git dependencies:

[dependencies]
rut-driver = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-core   = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-parser = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-vm     = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }

Grab the current commit and drop it into every rev:

git ls-remote https://github.com/hpp2334/rut.git HEAD

Pin all the rut crates to the same rev — cargo then resolves them to a single checkout, one consistent engine. These four are the minimal embedder set: the run chain, binary decode, the parser’s Mode, and verify + the VM itself. Add rut-native the same way when the program walks in from a directory — it is the filesystem/wire half (embedding and native modules).

Pin the nightly

rut-vm depends on rut-vm-threaded, which uses the incomplete #![feature(explicit_tail_calls)] and #![feature(rust_preserve_none_cc)] — a stable toolchain refuses to build it. Give your project the same pin the repo uses (check this repo’s rust-toolchain.toml for the current value):

# your project's rust-toolchain.toml
[toolchain]
channel = "nightly-2026-07-15"

Smoke-test the embed

One rut module — compiled, verified, booted, called from Rust — the embedding loop at minimum size:

use std::rc::Rc;

use rut_parser::Mode;
use rut_vm::interp::{HostHooks, HostRegistry, Limits, Vm};

const SRC: &str = "entry fn answer() -> i32 { return 6 * 7; }";

fn main() -> Result<(), String> {
    // 1. compile the module — the core prelude auto-rides
    let out = rut_driver::compile_module(SRC, Mode::Impl, "app");
    if !out.diags.is_empty() {
        for d in &out.diags {
            eprintln!("error: {}", d.msg);
        }
        std::process::exit(1);
    }

    // 2. decode and verify the binary
    let prog = rut_core::binary::decode(&out.binary.unwrap())?;
    rut_vm::verify::verify(&prog)?;

    // 3. boot the VM — `Limits::default()` is uncapped
    let limits = Limits::default();
    let mut vm = Vm::builder()
        .program(Rc::new(prog))
        .limits(limits)
        .hooks(HostHooks::default())
        .hosts(HostRegistry::new())
        .build()
        .map_err(|e| e.msg)?;

    // 4. call an export, get a Rust value back
    let answer: i32 = vm.call::<_, i32>("answer", ()).map_err(|t| t.msg)?;
    println!("answer = {answer}"); // 42
    Ok(())
}

entry fn is the host-callable surface — what vm.call can name. cargo run prints answer = 42: a rut value crossed into Rust unchanged, no std bindings involved.

When the program uses the std packages (ink, pouch, json, …), add rut-std as a dependency the same way and bind its pkg() builders — the embedding and native modules page is the full contract.

The rut CLI — temporary runs

For temporary runs the repo builds a standalone binary — three ways to get it on PATH, pick one.

cargo install from git — no checkout

rustup toolchain install nightly-2026-07-15
cargo +nightly-2026-07-15 install --git https://github.com/hpp2334/rut.git --locked rut-cli

The pinned nightly is not optional — the engine builds on incomplete features (see Pin the nightly above) and a stable toolchain refuses to; the pin is nightly-2026-07-15 (check this repo’s rust-toolchain.toml for the current value). --locked builds against the repo’s committed Cargo.lock. The binary lands at ~/.cargo/bin/rut, normally already on PATH.

cargo install from a checkout

git clone https://github.com/hpp2334/rut.git
cd rut
cargo install --path crates/rut-cli --locked

Standing inside the clone, rustup resolves the repo’s rust-toolchain.toml pin for you — same binary, same destination.

Plain build

git clone https://github.com/hpp2334/rut.git
cd rut
cargo build --release -p rut-cli
export PATH="$PWD/target/release:$PATH"

All three lanes end in the same rut binary — call it by path or put it on your PATH (the pages here use the bare name). rut --help prints the surface (and rut <command> --help each command’s flags):

rut --help
the rut toolchain's temporary-run lane: run, scaffold, install, format, pack, fetch, inspect

Usage: rut <COMMAND>

Commands:
  run      compile and run a module directory or a packed `.rutbundle`
  new      scaffold a hello-world module directory (the std set as deps)
  install  resolve the url deps and pin them in rut.lock
  fmt      the source formatter — canonical house layout, rewrite in place
  pack     pack a module directory into a deterministic `.rutbundle`
  fetch    pre-warm the bundle cache for offline runs
  dump     the AST + IR readbacks for one file
  help     Print this message or the help of the given subcommand(s)

Options:
  -h, --help     Print help
  -V, --version  Print version

The binary embeds the whole engine: lexer, parser, compiler, typed bytecode, and the VM. The toolchain’s standard packages (core, pouch, ink, json, …) ship as compiled .rutbundles on jsDelivr — a program says use ink::{ Logger }; and its manifest’s deps row mounts the package from the CDN, pinned by the project’s rut.lock (dependency kinds), since every rut program is a module directory (your first rut program).

Try it:

mkdir hello
cat > hello/rut.jsonc <<'EOF'
// hello/rut.jsonc — the manifest IS the program's door
{
  "name": "hello",
  "deps": {
    // ink — the toolchain's logger package, served by jsDelivr at the
    // std-v11 tag; the pin lives in rut.lock, one install below
    "ink": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" }
  }
}
EOF
cat > hello/mod.rut <<'EOF'
use ink::{ Logger };

entry fn main() {
    let log = Logger("hello");
    log.info(f"hello, rut!");
}
EOF
rut install hello   # fetch ink, pin it, write hello/rut.lock
rut run hello
install: ink — downloading https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle
install: ink — downloaded (4193 bytes)
install: 1 url deps resolved — 1 downloaded, 0 cache hits (4193 bytes total)
rut.lock written: 1 rows (1 added, 0 changed, 0 dropped)
hello, rut!

rut install fetched ink from jsDelivr into hello/.rut/cache and pinned its sha256 in hello/rut.lock — the lock every later load verifies against, committed alongside the manifest (same manifest + same rut.lock ⇒ identical resolved world). rut install --locked re-verifies the pair without writing (the CI lane); rut fetch hello re-warms the cache without running anything.

The hand-typed walkthrough is the lesson — the manifest is what you are learning. When it is routine, rut new hello is the one-step equivalent: it scaffolds the directory in three files (rut.jsonc plus the matching rut.lock plus the hello mod.rut), with the whole swappable std set as url deps and the std pins already in the lock (the rut CLI).

If that printed, the CLI is ready. Continue to your first rut program — and keep the lane’s role in mind: the CLI is for temporary runs (run, fmt, dump, pack), not a shipping path. Real projects depend on the crates and embed the engine; the rut CLI is the binary’s reference.

Optional: the wasm playground

The playground runs the same engine compiled to WebAssembly. Building it needs one extra target:

rustup target add wasm32-unknown-unknown
cargo build -p rut-wasm --target wasm32-unknown-unknown --release

or, from demo/, the one-command lane that also copies the artifact into place:

cd demo && npm install && npm run build:wasm

Optional: build this book

The documentation is an mdbook site:

cargo install mdbook --locked
mdbook serve docs     # live-reload preview at http://localhost:3000
mdbook build docs     # static site in docs/book/

Your first rut program

rut feels like TypeScript on the surface and Rust underneath the hood. This page walks one program through the whole toolchain — running, formatting, inspecting, and budgeting — so every later page can assume the workflow.

Write and run

This chapter drives everything through the temporary-run rut CLI — the fastest lane for learning the language (installation). A real project embeds the engine instead and calls it from Rust (embedding and native modules); the language, the types, and the workflow below are the same either way.

use ink::{ Logger };

entry fn main() {
    let log = Logger("hello");
    let name = "rut";
    log.info(f"hello, {name}!");
}

Every rut program is a module directory: a rut.jsonc naming the package and its dependencies, plus the root module — mod.rut, the file the loader mounts. Create it, install the deps, run the directory:

mkdir hello
cat > hello/rut.jsonc <<'EOF'
// hello/rut.jsonc — the manifest IS the program's door
{
  "name": "hello",
  "deps": {
    // ink — the toolchain's logger package, served by jsDelivr at the
    // std-v11 tag; the pin lives in rut.lock, one install below
    "ink": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" }
  }
}
EOF
cat > hello/mod.rut <<'EOF'
use ink::{ Logger };

entry fn main() {
    let log = Logger("hello");
    log.info(f"hello, rut!");
}
EOF
rut install hello   # fetch ink, pin it, write hello/rut.lock
rut run hello
install: ink — downloading https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle
install: ink — downloaded (4193 bytes)
install: 1 url deps resolved — 1 downloaded, 0 cache hits (4193 bytes total)
rut.lock written: 1 rows (1 added, 0 changed, 0 dropped)
hello, rut!

The run works from ANY directory — nothing about it assumes a clone of the toolchain’s repo. The url row names the package on jsDelivr; rut install fetched it once into the project’s cache (.rut/cache) and pinned its sha256 in hello/rut.lock — the lock rides beside the manifest, committed, and every load verifies the fetched bytes against it (an unpinned url refuses at the door: run rut install``). Every later run is a pure cache hit, rut install hello --locked re-verifies the lock without writing (the CI lane), and rut fetch hello re-warms the cache without running anything.

Three things to notice:

  • One directory with a rut.jsonc is one program. The manifest is the runnable unit — rut run <dir> (or a packed .rutbundle) is the only run lane. Inside the package, one file is one module; cross-module code is reached through use paths (see the modules tutorial).
  • use ink::{ Logger }; pulls Logger out of the ink package — and the manifest’s deps row is what mounts it: a use line says which names the program wants, the manifest says where the package lives (project structure).
  • Logger("hello") constructs the logger through the class’s [constructor] member — the call form spells the construction (classes).
  • f"hello, {name}!" is a format literal: {expr} interpolates any expression, rendered through the value’s display contract.

entry fn main() is the entry the CLI calls.

Typing the directory by hand is the lesson — the manifest IS the program’s door, and now you have written one. For the next directory, the CLI scaffolds it in one step: rut new <dir> writes exactly those three files — the manifest with the derived name (and, unlike the walkthrough above, the whole swappable std set as url deps), the matching rut.lock (the std set’s pins), and the same mod.rut — and rut run <dir> runs it (the rut CLI):

rut new hello    # hello/rut.jsonc (the std set) + hello/rut.lock + hello/mod.rut
rut run hello

Values, briefly

Extend the file — rut infers, and every type is known at compile time:

use ink::{ Logger };

entry fn main() {
    let log = Logger("hello");
    let n = 10;            // i32 — the integer default
    let scale = 1.5;       // f32 — the float default
    let big: u64 = 10;     // u64 via annotation — fits the default
    let flags = [1, 2, 3]; // [i32] — a fixed heap cell
    let mut sum = 0;       // `mut` — this one is written to
    for (let x of flags) {
        sum += x * n;
    }
    log.info(f"sum={sum} scale={scale}");
}
sum=60 scale=1.5

The full tour — suffixes, casts, strings, bytes, structs — is the values and variables tutorial, and the exact rules live in literals and inference.

Format

The formatter is the style — there is no configuration:

rut fmt hello/mod.rut         # rewrite in place
rut fmt hello/mod.rut --check # verify only (note: --check goes AFTER the path)
rut fmt .                     # walk a directory tree, every *.rut file

--check prints unformatted: <file> and exits 1 when a file needs changes, which makes it a clean CI gate. A file that does not parse is refused loudly rather than half-formatted.

Inspect

dump compiles a single module and prints its structures — useful when a snippet behaves differently than you expect:

rut dump hello/mod.rut

dump runs the lone module through the frontend without mounting the packages, so it is the tool for surface questions (“what does this lower to?”) rather than whole-program runs. The playground’s AST and IR panes show the same two views live — see the playground.

Budget it

Every rut run is uncapped by default — fuel is opt-in via --fuel N:

rut run hello --fuel 1000

A program that exhausts its fuel halts with a diagnostic naming the budget — the same contract the VM enforces for embedded hosts, along with heap ceilings and depth limits (resource limits).

Where next

  • The tutorial teaches the language hands-on, one concept per chapter.
  • The examples are seven complete projects you can run today.
  • Core concepts explains why the language is shaped the way it is.

The playground

The playground is the zero-install way to run rut: the whole engine — lexer, parser, compiler, VM — compiled to WebAssembly and served as a static page. It is deployed at https://playground.rut.hpp2334.com.

The layout

  • Case list — prepared programs, ordered the way the repo’s own gate runs them: algorithms first (sieve, quicksort, matrix multiply), then language-surface tours (classes, closures & generics, structs, literals, checked arithmetic, str views, bytes, opaque, when, maps & sets, type aliases), then memory shapes (node cycle, tree, weak cache).
  • Editor — the case’s source, live-editable. The cases are read from the same .rut files the repository’s native test gate compiles and runs, so what you edit is the real corpus, not a copy.
  • Output / AST / IR panes — every run shows the program’s real output plus the two compile views: the parsed AST and the typed IR the compiler lowers to. rut dump <file> prints the same structures from the CLI.
  • Budget control — fuel is off by default: an explicit ▶ Run is uncapped, and a non-terminating program freezes the tab — that is what uncapped means. The checkbox arms the fuel box (seeded at 10,000,000; heap defaults to 4 MiB): a run that exhausts its fuel parks on the out-of-fuel trap, and the Resume control adds fuel and continues the same frame — structured-concurrency-grade resumption, not a restart. Auto-runs (case selection, edits) keep an internal 1M watchdog slice so a stray loop parks instead of freezing the page.

No silent fallback

The page probes the wasm artifact at boot. If the engine or the syntax-highlighting module is missing or invalid, you get a full-page error naming the exact build command — the panes never mount in a degraded mode. On the deployed site this never happens; when you run a local build (below), the preflight exists so a stale artifact cannot masquerade as a working playground.

Running it locally

cd demo
npm install
npm run build:wasm   # builds rut.wasm + rut-lsp.wasm, copies to public/
npm run dev          # http://localhost:8080 with live reload

Other lanes:

npm run build        # static build into dist/
npm run smoke        # headless gate: every case really runs
npm run dev:channel  # dev server + a throwaway public https URL for demos

The corpus itself is documented in the playground corpus, with the bigger end-to-end projects under Examples.

Values and variables

Every value in rut has a type, and every type is known at compile time. This chapter covers the primitive types, how literals infer their types, how bindings work, and the one rule that organizes everything else: primitives copy, every other value is a shared cell.

For the full grammar of literals and inference rules, see the reference on literals and inference.

The primitive types

GroupTypesNotes
unsigned integersu8 u16 u32 u64fixed width
signed integersi8 i16 i32 i64two’s complement
floatsf32 f64IEEE 754
booleanbooltrue / false
textstrimmutable UTF-8, compared by content
binarybytesimmutable octet buffer, compared by content
erasedopaquea box holding any value — see errors and optionality

There is no character type. A str iterates as one-codepoint strs, and codepoints read as u32 (s.code(), s.code_at(i)) — see string slicing and views.

Variables: let and let mut

use ink::{ Logger };

entry fn main() {
    let log = Logger("vars");
    let a = 10;          // an immutable binding
    let mut b = 10;      // a mutable binding
    b = 20;              // OK — b may be reassigned
    // a = 30;           // ERROR: a is not `mut`
    log.info(f"a={a} b={b}");
}
a=10 b=20

mut is permission to write through that name: reassigning the binding, assigning to a field (p.x = 3), or assigning to an element (xs[0] = 7). Sharing is not gated by mut — two bindings can name the same value, and what mut controls is only who may write.

Every type has a zero value: 0 for numbers, false for bool, the empty string, nil for nullables. But nothing fills a struct literal’s fields for you: a literal must cover every field — spelled in the literal, or covered by the field’s declared initializer (see structs, enums, and classes).

Numbers

An unsuffixed integer literal defaults to i32; an unsuffixed float defaults to f32. The default is also a ceiling: a literal adapts to the expected type only while it fits the default.

use ink::{ Logger };

entry fn main() {
    let log = Logger("numbers");
    let a = 10;                        // i32
    let b = 10u8;                      // u8 via suffix
    let c: u64 = 10;                   // u64 via annotation — 10 fits
    let big = 18446744073709551615u64; // past the i32 default: suffix required
    let d = 1.5;                       // f32
    let d64: f64 = 1.5;                // f64 via annotation
    let hex = 0xFF_u32;                // 0x / 0b / 0o bases, _ separators
    log.info(f"a={a} d={d} d64={d64} hex={hex} big={big}");
}
a=10 d=1.5 d64=1.5 hex=255 big=18446744073709551615

Conversions are explicit casts: expr as T. Casts truncate like C — they never trap.

use ink::{ Logger };

entry fn main() {
    let log = Logger("casts");
    let cast = 300 as u8;   // 44 — keeps the low 8 bits
    log.info(f"cast={cast}");
}
cast=44

Arithmetic has two sharp edges:

  • Mixed widths do not mix. Both operands must have the same width — convert one side first. let mut total = 0.0; makes an f32, and adding an f64 to it is a type error; annotate let mut total: f64 = 0.0; when you mean double precision.
  • Overflow, division by zero, and out-of-bounds indexing trap. For the explicit non-trapping ladder (wrapping_add, saturating_mul, checked_add), see the standard library.

Text: plain, raw, and format strings

Three literal forms. A plain string is always inert — no interpolation ever happens implicitly.

use ink::{ Logger };

entry fn main() {
    let log = Logger("text");
    let name = "rut";
    let s = "hi\tname";              // plain: escapes processed
    let raw = r"C:\temp\log.txt";    // raw: every byte is literal
    let t = f"hi {name}!";           // format: placeholders evaluated
    log.info(f"{s} | {raw} | {t}");
}
hi	name | C:\temp\log.txt | hi rut!

Plain and format strings share the same escapes (\t \n \r \\ \" and \u{...}). In an f-string, { expr } splices any expression — identifiers, calls, arithmetic — except nested string literals (bind one to a variable first). {{ and }} are literal braces:

use ink::{ Logger };

entry fn main() {
    let log = Logger("text");
    log.info(f"open{{close}} braces");   // prints: open{close} braces
}
open{close} braces

What an f-string can render: integers (decimal), floats (shortest round-trip decimal: 3.5, 0.1), bool (true/false), str (contents), and enum members (their name: Color::Green renders Green). Composite values — structs, classes, arrays, vecs — are a compile error inside an f-string; write a to_string()-style method and call it, or use a debug dump for development.

Sequences and buffers

The fixed array [T] is built from a literal or a repeat:

use ink::{ Logger };

entry fn main() {
    let log = Logger("arrays");
    let arr = [1, 2, 3];         // [i32] — fixed length
    let zero: [u8] = [0u8; 34];  // 34 slots of 0
    log.info(f"len={arr.len()} first={arr[0]} zero.len={zero.len()}");
}
len=3 first=1 zero.len=34

The growable sequence is Vec<T> (from the pouch package — use pouch::{ Vec };): Vec::new(), Vec::from([..]), Vec<i32>::filled(0, 1024), push, pop, len. Indexing and for..of work the same on both. See the standard library for the full surface.

bytes is the binary primitive. s.encode() turns text into octets, b.decode() reads it back (lossy UTF-8), bytes::zeroed(n) and bytes::from(a) build buffers directly:

use ink::{ Logger };

entry fn main() {
    let log = Logger("bytes");
    let b = "rut runs".encode();
    let ok = b.decode() == "rut runs";   // true — content comparison
    log.info(f"len={b.len()} roundtrip={ok}");
}
len=8 roundtrip=true

Sharing: the one rule

Primitives and fn values copy on assignment, argument passing, and return. Every other value is a shared cell: let q = p is an O(1) handle move, and a write through any alias is visible through all of them.

use ink::{ Logger };

struct Point { x: i32; y: i32 }

entry fn main() {
    let log = Logger("sharing");
    let mut p = Point { x: 1, y: 2 };
    let q = p;          // q and p name ONE cell
    p.x = 4;            // q.x is 4 now
    log.info(f"q.x={q.x} same cell: {q == p}");
}
q.x=4 same cell: true

Equality follows the same split:

Operands== means
numbers, boolvalue comparison
str, bytescontent comparison
everything elsecell identity — two separately-built literals are never equal

The one copy escape hatch is bytes::clone() — a fresh buffer with the same octets. There is no generic copy for any other type; if you need a divergent value, build a new one.

Absence is nil on a nullable ?T — see errors and optionality.

Tuples

Records (A, B) are first-class values with numeric fields:

use ink::{ Logger };

fn divmod(a: i32, b: i32) -> (i32, i32) {
    return (a / b, a % b);
}

entry fn main() {
    let log = Logger("tuples");
    let (q, r) = divmod(17, 5);   // destructuring
    let t = (1, true);
    log.info(f"q={q} r={r} t.0={t.0}");
}
q=3 r=2 t.0=1

The pair is also rut’s standard error channel — the next chapters use it constantly.

Put it together

Put this in a module directory and run it: literals/rut.jsonc names the two packages the program uses, and the program is literals/mod.rut:

// literals/rut.jsonc
{
  "name": "literals",

  "deps": {
    // the pins live in literals/rut.lock — `rut install` writes it
    "pouch": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle" },
    "ink":   { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" }
  }
}

Save the program as literals/mod.rut, then rut install literals (fetches the two url deps and writes rut.lock) and rut run literals:

use pouch::{ Vec };
use ink::{ Logger };

struct Point { x: f32; y: f32 }

fn literals(name: str) {
    let log = Logger("literals");
    let a = 10;                      // i32 (default)
    let b = 10u8;                    // u8 via suffix
    let c: u64 = 10;                 // u64 via annotation — fits the default
    let big = 18446744073709551615u64; // past the `i32` default: suffix REQUIRED
    let cast = 300 as u8;            // 44 — `as` truncates
    let d = 1.5;                     // f32 (default)
    let e = 1.5f32;                  // f32 via suffix
    let d64: f64 = 1.5;              // f64 via annotation
    let s = "hi\tname";              // plain string: escapes processed
    let raw = r"C:\temp\log.txt";    // raw literal: NO escape processing
    let t = f"hi {name}!";           // format literal
    let ch = "h";                    // a 1-codepoint str
    let mut arr = [1, 2, 3];         // [i32] — fixed array
    let mut zero: Vec<f32> = Vec<f32>::filled(0.0, 1024);  // growable, flat
    let grow = Vec<i32>::from([1, 2, 3]);  // array -> growable
    arr[0] = 7;                      // element write needs `mut`
    zero[0] = 9.0f32;
    let bin = bytes(64);             // 64 zeroed octets
    let p = Point { x: 1, y: 2 };    // struct literal: no `new`

    log.info(f"a={a} e={e} d64={d64} ch={ch} p.x={p.x} zero[0]={zero[0]} len={grow.len()} bin={bin.len()}");
}

entry fn main() {
    literals("rut");
}
a=10 e=1.5 d64=1.5 ch=h p.x=1 zero[0]=9 len=3 bin=64

Next: control flow and when.

Control flow and when

rut has the classic structured statements — if/else, while, for — and exactly one match construct: when, an exhaustive pattern expression. The full rules live in the reference on control flow.

if and else

Braces are always required, whatever the body length:

use ink::{ Logger };

entry fn main() {
    let log = Logger("flow");
    for (let hits of [0, 5, 12]) {
        let mut first = false;
        let mut warm = false;
        let mut hot = false;
        if (hits == 0) {
            first = true;
        } else if (hits < 10) {
            warm = true;
        } else {
            hot = true;
        }
        log.info(f"hits={hits} first={first} warm={warm} hot={hot}");
    }
}
hits=0 first=true warm=false hot=false
hits=5 first=false warm=true hot=false
hits=12 first=false warm=false hot=true

The condition must be a bool — there is no truthiness coercion, and no parenthesized-assignment footgun.

if is an expression too

The same spelling produces a value wherever an expression goes: each arm is a block, and the arm’s tail — the expression before the arm’s }, with no ; — is what the arm yields. The arms must agree on one type, and that type is the if’s:

use ink::{ Logger };

fn grade(n: i32) -> str {
    let band = if (n > 90) { "hi" } else if (n > 50) { "mid" } else { "lo" };
    band
}

entry fn main() {
    let log = Logger("if-expr");
    for (let n of [95, 72, 10]) {
        let verdict = if (n > 50) { "pass" } else { "fail" };
        log.info(f"{n}: {grade(n)}, {verdict}");
    }
}
95: hi, pass
72: mid, pass
10: lo, fail

No else and the whole if produces nil — that is the statement form above, running its arm for effect. A trailing ; after the statement form discards quietly; without it, a trailing if statement with an else at the end of a block IS the block’s value. That is the block tail law — see return — and if in tail position is where it shines.

Loops

while repeats until its condition is false:

use ink::{ Logger };

entry fn main() {
    let log = Logger("sieve");
    let i = 2;
    let limit = 12;
    let mut marks = [0; 16];
    let mut m = i * i;
    while (m <= limit) {
        marks[m] = 1;
        m += i;
    }
    log.info(f"marks[4]={marks[4]} marks[5]={marks[5]} stopped at m={m}");
}
marks[4]=1 marks[5]=0 stopped at m=14

for..of iterates anything with elements: fixed arrays, Vecs, str (yielding one-codepoint strs), bytes (yielding u8s), and any type that marks an [iterable] member (a user class or an enum — the loop calls that ONE designated member; see interfaces):

use ink::{ Logger };

entry fn main() {
    let log = Logger("loops");
    let mut n = 0;
    for (let w of ["rut", "runs", "rut"]) {
        // w is a str
    }
    for (let c of "héllo") {
        n += 1;             // 5 iterations — codepoints, not the 6 bytes
    }
    log.info(f"n={n}");
}
n=5

The loop variable is a fresh binding each iteration — and a normal one: assigning it in the body takes mut in the header, like any let.

Indexed for is the C shape. The header is a normal binding too: the update clause assigns the counter every iteration, so a written-to counter is spelled for (let mut i = 0; ...) — plain let there is a compile error.

use ink::{ Logger };

entry fn main() {
    let log = Logger("loops");
    let xs = [3, 1, 4];
    let n = xs.len();
    let mut total = 0;
    for (let mut i = 0; i < n; i += 1) {
        total += xs[i];
    }
    log.info(f"total={total}");
}
total=8

break and continue work in every loop form; there are no labels and no do..while.

return

return expr; exits the function. If the function returns nothing, the arrow is omitted and return; (or simply falling off the end) returns:

use pouch::{ Vec };
use ink::{ Logger };

fn swap(mut xs: Vec<i32>, a: i32, b: i32) {
    let t = xs[a];
    xs[a] = xs[b];
    xs[b] = t;
    // no return — the function's type is nil
}

entry fn main() {
    let log = Logger("swap");
    let xs = Vec<i32>::from([1, 2, 3]);
    swap(xs, 0, 2);
    log.info(f"first={xs[0]} last={xs[2]}");
}
first=3 last=1

A function WITH an arrow must produce its value on every path: spell return, or end the body with a tail — the last expression, written without ;. The tail is the block’s value, and a fn body’s tail is the implicit return; a body that can still fall off the end without one diagnoses missing return. The two spellings mix freely:

use ink::{ Logger };

fn plus_one(n: i32) -> i32 {
    n + 1
}

fn fact(n: i32) -> i32 {
    if (n <= 1) {
        1
    } else {
        n * fact(n - 1)
    }
}

entry fn main() {
    let log = Logger("tail");
    log.info(f"{plus_one(41)} {fact(5)}");
}
42 120

The trailing if in fact is the statement form in tail position — its arms produce the body’s answer. Tails are not special to fn bodies: any block’s last expression without ; is that block’s value, which is exactly how the if-as-expression arms above yield theirs.

when — the one match

when (value) { pattern -> body, ... } is an expression: the first matching arm produces the value. No fallthrough — exactly one arm runs.

use ink::{ Logger };

fn classify(n: i32) -> str {
    return when (n) {
        0       -> "zero",
        1, 2, 3 -> "small",     // comma-separated alternatives
        else    -> "big",       // the wildcard
    };
}

entry fn main() {
    let log = Logger("when");
    for (let n of [0, 2, 9]) {
        log.info(f"{n}: {classify(n)}");
    }
}
0: zero
2: small
9: big

The arm body before the , is an expression; arms can also be blocks:

use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn go()    { Logger("light").info("go"); }
fn brake() { Logger("light").info("brake"); }
fn stop()  { Logger("light").info("stop"); }

entry fn main() {
    let l = Light::Yellow;
    when (l) {
        Light::Green  -> { go(); },
        Light::Yellow -> { brake(); },
        Light::Red    -> { stop(); },
    }
}
brake

Used as a statement, the when’s value is discarded — the block arms above run for effect. But block arms are value blocks: a block arm’s tail is the arm’s value, and expression and block arms mix freely under the same one-type law (see below):

let w =
    when (x) {
        0 -> 10,
        1 -> { let t = 11; t },
        else -> 12,
    };

Patterns

The patterns are: enum members (Light::Red), literals (integers, floats, bool, str), comma-separated alternatives, and else. There are no ranges, no destructuring, and no guards — an if inside the arm body does that job.

Exhaustiveness is enforced

  • Enum scrutinee: either cover every member or add else. A partial when over an enum is a compile error — when you add a member later, the compiler finds every when you must extend.
  • Any other scrutinee: else is mandatory (integers and strings cannot be enumerated).
use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn go()    { Logger("light").info("go"); }
fn brake() { Logger("light").info("brake"); }
fn stop()  { Logger("light").info("stop"); }

fn drive(l: Light) {
    when (l) {
        Light::Green  -> { go(); },
        Light::Yellow -> { brake(); },
        Light::Red    -> { stop(); },   // all members: no else needed
    }
}

fn describe(n: i32) -> str {
    return when (n) {
        0    -> "zero",
        else -> "not zero",            // non-enum scrutinee: else REQUIRED
    };
}

entry fn main() {
    drive(Light::Red);
    let log = Logger("light");
    log.info(describe(0));
    log.info(describe(7));
}
stop
zero
not zero

when over a bool reads nicely as a two-arm check:

use ink::{ Logger };

struct Point { x: i32; y: i32 }

entry fn main() {
    let log = Logger("nullable");
    let p: ?Point = Point { x: 1, y: 2 };
    when (p != nil) {
        true -> { log.info(f"point {p.x} {p.y}"); },
        else -> { log.info("point: nil"); },
    }
}
point 1 2

Duplicate patterns — and arms made unreachable by an earlier one — are compile errors.

One type across the arms

All arm expressions must agree: that shared type is the when’s type. A when that builds a value usually reads best wrapped in a function — the function’s return type then pins every arm:

use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn light_for(i: i32) -> Light {
    return when (i) {
        0    -> Light::Green,
        1    -> Light::Yellow,
        else -> Light::Red,
    };
}

entry fn main() {
    let log = Logger("light");
    log.info(f"{light_for(0)} {light_for(1)} {light_for(5)}");
}
Green Yellow Red

Put it together

use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn action(l: Light) -> str {
    return when (l) {
        Light::Green  -> "go",
        Light::Yellow -> "brake",
        Light::Red    -> "stop",
    };
}

fn light_for(i: i32) -> Light {
    return when (i) {
        0    -> Light::Green,
        1    -> Light::Yellow,
        else -> Light::Red,
    };
}

fn classify(n: i32) -> str {
    return when (n) {
        0       -> "zero",
        1, 2, 3 -> "small",
        else    -> "big",
    };
}

entry fn main() {
    let log = Logger("lights");

    for (let n of [0, 2, 9]) {
        log.info(f"{n}: {classify(n)}");
    }

    let mut i = 0;
    while (i < 3) {
        log.info(action(light_for(i)));
        i += 1;
    }
}
0: zero
2: small
9: big
go
brake
stop

Next: functions, closures, and generics.

Functions, closures, and generics

Functions are declared with fn, values can be functions, and generic functions monomorphize at compile time — each instantiation gets its own specialized code. The details live in the reference on functions, closures, and generics.

Declaring functions

Parameter and return types are always written. A function whose return type is omitted returns nothing:

use pouch::{ Vec };
use calc::{ Math };
use ink::{ Logger };

struct Point { x: f32; y: f32 }

fn swap(mut xs: Vec<i32>, a: i32, b: i32) {
    let t = xs[a];
    xs[a] = xs[b];
    xs[b] = t;
}

fn length(pt: Point) -> f64 {
    return Math::sqrt((pt.x * pt.x + pt.y * pt.y) as f64);
}

entry fn main() {
    let log = Logger("fns");
    let xs = Vec<i32>::from([1, 2, 3]);
    swap(xs, 0, 2);
    log.info(f"first={xs[0]} length={length(Point { x: 3, y: 4 })}");
}
first=3 length=5

A mut parameter (fn step(mut p: Point)) is the callee’s permission to write through p — and because non-primitive values share, that means the caller’s value. A plain parameter promises not to write through it.

Recursion works as expected — functions are visible in their own bodies, and mutual recursion within a module needs no forward declaration.

Anonymous functions

The closure spelling is an anonymous fn with a block body. There is no arrow shorthand — every closure states its parameter and return types, which is what lets it inhabit a first-class fn type:

use ink::{ Logger };

entry fn main() {
    let log = Logger("closures");
    let add = fn (a: i32, b: i32) -> i32 { return a + b; };

    let area_of = fn (r: f32) -> f32 {
        let sq = r * r;
        return sq * 3.14159265f32;
    };

    add(1, 2);          // call it like any function
    log.info(f"add={add(1, 2)} area={area_of(1)}");
}
add=3 area=3.1415927

Function types are written fn(P..) -> R and appear anywhere a type does:

use ink::{ Logger };

fn apply(f: fn(i32) -> i32, v: i32) -> i32 {
    return f(v);
}

entry fn main() {
    let log = Logger("fns");
    let double = fn (x: i32) -> i32 { return x * 2; };
    log.info(f"apply={apply(double, 21)}");
}
apply=42

Closures capture the enclosing bindings — a closure body sees and can use the locals around it, including after the enclosing function would have returned, because captured cells stay alive as long as the closure does. The capture law has two halves: primitives (and nil and fn values) copy — the closure gets its own slot, and a reassign inside the closure never moves the original — while everything ref-headed (a Vec, a struct, str, ?T, …) crosses as a handle to the same cell. That second half includes whole-value reassignment: a captured binding that is reassigned — either frame — shares its slot with the closure, so both sides always see the current value:

use pouch::{ Vec };
use ink::{ Logger };

entry fn main() -> nil {
    let log = Logger("cap");
    let mut xs: Vec<i32> = Vec::new();
    xs.push(1);
    let len = fn() -> i32 { return xs.len(); };
    let mut ys: Vec<i32> = Vec::new();
    ys.push(9); ys.push(9);
    xs = ys;                       // a rebind the closure sees
    log.info(f"len={len()}");      // 2 — the closure shares the slot
}

Generics

A generic function declares type parameters in angle brackets. Each concrete instantiation is compiled separately (monomorphized), so generics cost nothing at runtime:

use ink::{ Logger };

fn first<T>(xs: [T], fallback: T) -> T {
    if (xs.len() == 0) {
        return fallback;
    }
    return xs[0];
}

entry fn main() {
    let log = Logger("generics");
    let head = first([10, 20], -1);      // first<i32> — inferred
    let name = first(["a", "b"], "?");   // first<str> — a separate instance
    log.info(f"head={head} name={name}");
}
head=10 name=a

T is inferred from the arguments; you rarely spell first<i32>(..) explicitly. Two rules to know:

  • A bare T has no methods — you cannot call anything on a value whose type is just T. Pass concrete values in, spell an interface bound (T requires Labeled), or take an interface-typed parameter (next chapter).
  • A generic class in a parameter position does not unify — fn sum(xs: Vec<i32>) is fine, but a function generic over T taking Vec<T> is not yet the shape to reach for. Concrete instantiations cover most code.

requires bounds

An inline requires bound gates which instantiations compile:

use ink::{ Logger };

interface Labeled {
    fn label(self) -> str;
}

struct Tag { id: i32 }

impl Tag {
    fn label(self) -> str { return f"tag-{self.id}"; }
}

fn name<T requires Labeled>(x: T) -> str {
    let w: Labeled = x;     // the bound proves this widening
    return w.label();
}

entry fn main() {
    let log = Logger("bounds");
    log.info(name(Tag { id: 7 }));
}
tag-7

The bound is admission-only: it checks at each call site that the concrete type satisfies the named interface (or union of type names), and it proves a T-typed value may be used as that interface type — it does not put methods on T itself. Union bounds admit any member:

fn kind<T requires Ridge | Trench>(x: T) -> str { .. }

This is exactly how typed JSON entry points are spelled — decodeJson<T requires JsonDeserialize>(s: str) — see errors and optionality. Bounds and unions are covered fully in the reference on type aliases and union bounds.

Free functions are the default idiom

rut’s records carry no methods (bodies are fields only; methods live in impl blocks — see structs, enums, and classes), so the everyday shape is small data plus free functions over it:

use ink::{ Logger };

struct Point { x: f32; y: f32 }

fn nudged(pt: Point) -> Point {
    return Point { x: pt.x + 1, y: pt.y };
}

entry fn main() {
    let log = Logger("free-fns");
    let p = nudged(Point { x: 2, y: 5 });
    log.info(f"p.x={p.x} p.y={p.y}");
}
p.x=3 p.y=5

Reach for methods when something is genuinely the receiver’s behavior, and for the members other code observes through interfaces — everything else is a plain function.

Put it together

use pouch::{ Vec };
use ink::{ Logger };

fn first<T>(xs: [T], fallback: T) -> T {
    if (xs.len() == 0) {
        return fallback;
    }
    return xs[0];
}

fn sum(xs: Vec<i32>) -> i32 {
    let mut total = 0;
    for (let x of xs) {
        total += x;
    }
    return total;
}

entry fn main() {
    let log = Logger("closures");
    let add = fn (a: i32, b: i32) -> i32 { return a + b; };
    let area_of = fn (r: f32) -> f32 {
        let sq = r * r;
        return sq * 3.14159265f32;
    };
    log.info(f"add={add(1, 2)} area={area_of(1)} sum={sum(Vec<i32>::from([1, 2, 3]))}");

    let head = first([10, 20], -1);       // first<i32> — monomorphized
    let name = first(["a", "b"], "?");    // first<str> — separate instance
    log.info(f"head={head} name={name}");
}
add=3 area=3.1415927 sum=6
head=10 name=a

Next: structs, enums, and classes.

Structs, enums, and classes

rut has three user-defined type forms, each with one job:

  • enum — a small set of named constants.
  • struct — an open data record: every field public, literal construction everywhere.
  • class — a sealed record: private fields, construction through class methods only.

In all three, the type body is fields only — every method lives in an impl block. A fn written inside a type body is a parse error. The reference pages are structs, enums, and classes and constructors.

Enums

An enum is a distinct named type over plain symbols. No payloads and no computed members — where another language would use a union of literal strings, rut uses an enum:

use ink::{ Logger };

enum Light { Green, Yellow, Red }

enum Direction { Up, Down, Left, Right }

entry fn main() {
    let log = Logger("enums");
    log.info(f"{Light::Green} {Direction::Left} {Direction::Right}");
}
Green Left Right

Members are the enum’s values and are spelled qualified: Light::Green. A member is a symbol — there is no integer value under it to read or spell.

when over an enum must be exhaustive — every member, or an else arm (see control flow and when). Enums render as their member name in format strings. Enums take impl blocks — non-self methods on the name, self methods on a value (a marked [iterable] fn makes for (let v of l) walk) — see enums.

Structs — open records

Declare with struct, construct with a literal — anywhere in a function body, nested inside other literals. Construction is the literal; there is no constructor gate:

use ink::{ Logger };

struct Point {
    x: f32;
    y: f32;
}

struct Rect {
    min: Point;
    max: Point;
}

struct Style {
    color: u32 = 0xff00ff;      // field initializer: literals may omit it
    width: f32 = 1;
}

entry fn main() {
    let log = Logger("structs");
    let p = Point { x: 1, y: 2 };                    // every field, by name
    let s = Style {};                                // declared initializers fill the rest
    let r = Rect { min: Point { x: 0, y: 0 }, max: p };
    log.info(f"r.max.x={r.max.x} width={s.width}");
}
r.max.x=1 width=1

A literal must cover every field — spelled in the literal, or covered by the field’s declared initializer. Omitting a field with no initializer is a compile error, and so is spelling a field twice (see structs for the exact diagnostics).

All fields are public, always — member visibility in a struct is a compile error. Privacy is what classes are for. Methods live in impl blocks with real visibility — pub fn exports cross-module, plain fn stays module-private (see structs).

Structs share. A struct value is a handle to a heap cell: assignment, arguments, and returns all pass the handle, and a write through any alias is visible through all of them. Writing needs a mut binding or mut parameter:

use ink::{ Logger };

struct Point { x: f32; y: f32 }

entry fn main() {
    let log = Logger("sharing");
    let mut p = Point { x: 1, y: 2 };
    let q = p;              // q and p name ONE cell
    p.x = 4;                // q.x is 4 now
    log.info(f"q.x={q.x} same cell: {q == p}");
}
q.x=4 same cell: true

== on struct values is cell identity — q == p is true (one cell), p == Point { x: 4, y: 2 } is false (a different cell). To compare field by field, write a function.

Recursive shapes are legal — a record may name itself through a nullable field, because ?Node is one word:

use ink::{ Logger };

struct Node {
    value: i32;
    left: ?Node;
    right: ?Node;
}

fn count(n: ?Node) -> i32 {
    let mut c = 1;
    if (n.left != nil) { c += count(n.left); }
    if (n.right != nil) { c += count(n.right); }
    return c;
}

entry fn main() {
    let log = Logger("nodes");
    let n = Node {
        value: 1,
        left: Node { value: 2, left: nil, right: nil },
        right: nil,
    };
    log.info(f"count={count(n)}");
}
count=2

Classes — sealed records

A class adds two things to a struct: module-private fields and construction gated through class methods. There is no outside literal — the only way to build a class value from outside is to call a class method that chooses to. (Cleanup hooks are not a class privilege: mark a [disposal] member on either shape, and the engine calls it when the value’s cell refcount reaches zero — see Rc, dispose, and identity.)

use ink::{ Logger };

class Counter {
    n: i32 = 0;             // module-private — the class's business
}

impl Counter {
    pub fn new() -> Self {                 // the construction surface
        return Self { };                   // the class-private literal
    }

    pub fn press(mut self) {
        self.n = self.n.wrapping_add(1);
    }

    pub fn count(self) -> i32 { return self.n; }
}

entry fn main() {
    let log = Logger("counter");
    let c = Counter::new();
    c.press();
    c.press();
    log.info(f"count={c.count()}");      // 2
}
count=2

The pieces:

  • A class method is just a function without self. Rect::new(w, h), Version::parse(s), Rect::from_square(s) — any no-self method returning Self is a constructor. new is a convention, not syntax.
  • The Self { .. } literal is class-private — legal anywhere in the class’s own impl block, never outside. This is the seal.
  • Instance methods spell self explicitly as the first parameter; mut self marks methods that write. A computed property is a method (c.count()).
  • Construction is validation. A constructor is an ordinary function — it can check arguments and refuse:
use ink::{ Logger };

class Rect {
    w: f32;
    h: f32;
}

impl Rect {
    pub fn new(w: f32, h: f32) -> Self {
        if (w <= 0 || h <= 0) {
            panic("Rect: negative extents");
        }
        return Self { w: w, h: h };
    }

    pub fn from_square(s: f32) -> Self {
        return Rect::new(s, s);
    }

    pub fn area(self) -> f32 { return self.w * self.h; }
}

entry fn main() {
    let log = Logger("rect");
    let r = Rect::new(3, 4);
    let sq = Rect::from_square(2);
    log.info(f"area={r.area()} square={sq.area()}");
}
area=12 square=4

A try-constructor answers the nullable — nil is a failed validation, not a crash:

impl Version {
    pub fn parse(s: str) -> ?Version {
        // ... split "1.2" — on failure:
        return nil;
    }
}

No inheritance. There is no extends, no super, no overriding. Code sharing is composition (hold a helper in a field) or free functions; polymorphism is structural interfaces — the next chapter.

Visibility recap

  • Struct members: public, always.
  • Class members: unannotated is module-private; pub exposes to importers (also pub(mod), pub(super), pub(self)).
  • The types themselves follow the same rule: pub class Vec<T> is importable, a bare class Helper stays in its module. See modules and packages.

Struct or class?

Default to a struct: data in, data out, shared like every other value. Reach for a class when the type has rules that construction must enforce, holds private state that outsiders must not read, or owns a resource that needs explicit cleanup.

Put it together

use ink::{ Logger };

class Counter {
    n: i32 = 0;
}

impl Counter {
    pub fn new() -> Self {
        return Self { };
    }

    pub fn press(mut self) {
        self.n = self.n.wrapping_add(1);
    }

    pub fn count(self) -> i32 { return self.n; }
}

class Rect {
    w: f32;
    h: f32;
}

impl Rect {
    pub fn new(w: f32, h: f32) -> Self {
        if (w <= 0 || h <= 0) {
            panic("Rect: negative extents");
        }
        return Self { w: w, h: h };
    }

    pub fn from_square(s: f32) -> Self {
        return Rect::new(s, s);
    }

    pub fn area(self) -> f32 { return self.w * self.h; }
}

entry fn main() {
    let log = Logger("classes");
    let c = Counter::new();
    c.press();
    c.press();
    let r = Rect::new(3, 4);
    let sq = Rect::from_square(2.0f32);
    log.info(f"count={c.count()} area={r.area()} square={sq.area()}");
}
count=2 area=12 square=4

Next: interfaces and impl blocks.

Interfaces and impl blocks

An interface declares a set of method signatures; a type satisfies it by having the members. Satisfaction is structural — there is no admission step, no registration, no impl Interface for Type anywhere in the language: impl T { .. } (the type’s own inherent impl) is the only impl form, and the boundary check is the whole law. The one-mechanism-per-job philosophy behind this is in interfaces and dispatch; the full story is in the reference on interfaces.

Declaring an interface

Interfaces declare method signatures — no bodies, no default implementations, no fields:

pub interface Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}

Methods spell their receiver self explicitly, like every rut method. Anything that looks like a property is a method: declare fn count(self) -> i32;, not a field. Self and generics are legal in signatures; interface members carry no pub — they are as visible as the interface — and the interface itself takes no bounds and embeds nothing: a flat member set, compose by declaring the members.

Satisfying an interface

Satisfaction is membership. Give the type a pub member for every interface member, on the type’s own inherent impl, and it satisfies — nothing else to write:

use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}

class Circle { r: f64; }

impl Circle {
    pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; }
    pub fn name(self) -> str { return "circle"; }
}

entry fn main() {
    let log = Logger("interfaces");
    let c = Circle { r: 1.0 };
    log.info(f"{c.name()}={c.area()}");
}
circle=3.14159

Rules worth knowing:

  • Signatures must match — receiver form (self vs mut self vs none), parameter types, return type, and async spelling, exactly. A member that is almost right is not right: the diagnostic names the first mismatching member.
  • Members live on the type’s own inherent impl, in the type’s module. impl Circle { pub fn area(self) -> f64 { .. } } is where the member set comes from; there is no second impl form to reach for.
  • Only the type’s own public members count. A used package’s type satisfies through the members its own module spells; you cannot add members to a foreign type, and nothing you write can register a satisfaction for a type that lacks the members.
  • Shape-equal is satisfied — including by types whose author never thought of your interface. Two types with the same member shapes both satisfy, and there is no opt-out. The convention that keeps this honest: give near-miss members distinct names or shapes, so accidental satisfaction stays a non-event in practice.
  • An interface with no members is satisfied by everything — the empty member set is vacuously true. There is no marker idiom: if a declaration needs to mean something, it spells a member.

Inherent impls

impl Type { .. } is where a type’s own methods live: class methods like new, instance methods, helpers. It compiles only in the module that declares the type. A generic type’s inherent impl declares its binders up front: impl<T> Vec<T> { .. }.

use ink::{ Logger };

class Circle {
    r: f64;
}

impl Circle {
    pub fn new(r: f64) -> Self {
        return Self { r: r };
    }
}

entry fn main() {
    let log = Logger("interfaces");
    let c = Circle::new(1.0);
    log.info(f"r={c.r}");
}
r=1

Every member the satisfaction law reads comes from here — public members of the type’s inherent impl, and nothing else.

Using interface values

An interface name in type position is the bare name. Four forms, one law each — checking at the boundary, never a search:

Interface-typed parameters accept any satisfying type — write the function once, call it with each concrete type:

use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}

class Circle { r: f64; }
class Square { side: f64; }

impl Circle {
    pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; }
    pub fn name(self) -> str { return "circle"; }
}

impl Square {
    pub fn area(self) -> f64 { return self.side * self.side; }
    pub fn name(self) -> str { return "square"; }
}

fn describe(s: Shape) -> str {
    return f"{s.name()}={s.area()}";
}

entry fn main() {
    let log = Logger("interfaces");
    log.info(describe(Circle { r: 1.0 }));    // Circle satisfies: checked here
    log.info(describe(Square { side: 3.0 })); // and here
}
circle=3.14159
square=9

The check fires where the concrete value crosses into the interface — each call above verifies the argument’s member set once. A type without the members is refused at that same spot, and the diagnostic names the type, the interface, and the missing member:

pub interface Shape {
    fn area(self) -> f64;
}

class Point { x: i32; y: i32; }

fn admit(p: Shape) -> nil { }
fn call_it() { admit(Point { x: 1, y: 2 }); }
`Point` does not satisfy `Shape`: no member `area`

Typed lets are satisfaction assertions — the annotation is the question, the initializer’s member set is the answer:

use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
}

class Square { side: f64; }

impl Square {
    pub fn area(self) -> f64 { return self.side * self.side; }
}

entry fn main() {
    let log = Logger("interfaces");
    let s: Shape = Square { side: 2.0 };   // asserted and checked
    log.info(f"area={s.area()}");
}
area=4

Heterogeneous containers hold mixed satisfiers behind the interface name. Inside a single-typed context calls bind directly; iterating a collection of Shape consults each value’s itable — the compiler picks, and mis-guessing costs one hop, never wrong behavior:

use pouch::{ Vec };
use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
}

class Circle { r: f64; }
class Square { side: f64; }

impl Circle {
    pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; }
}

impl Square {
    pub fn area(self) -> f64 { return self.side * self.side; }
}

entry fn main() {
    let log = Logger("interfaces");
    let mut shapes: Vec<Shape> = Vec::new();   // each push checks
    shapes.push(Circle { r: 1.0 });
    shapes.push(Square { side: 3.0 });
    let mut total: f64 = 0.0;
    for (let s of shapes) {
        total += s.area();       // dispatches per element
    }
    log.info(f"total={total} n={shapes.len()}");
}
total=12.14159 n=2

Primitives ride in wrappers

Primitives, arrays, tuples, and ?T have no inherent members, so they can never satisfy — and no layer will invent a satisfaction for you. The route in is a newtype class: a one-field wrapper whose inherent impl carries the members, spelled at every call site:

use ink::{ Logger };

pub interface Show {
    fn show(self) -> str;
}

class NumI64(i64);

impl NumI64 {
    pub fn show(self) -> str { return str(self.inner); }
}

fn print_it(x: Show) -> str { return x.show(); }

entry fn main() {
    let log = Logger("interfaces");
    log.info(print_it(NumI64(64)));    // spelled manufacture
}
64

print_it(NumI64(64)) — ✓ spelled, sound, per-call. print_it(64) — ✗ forever: no auto-insertion exists. Wrappers compose — a generic wrapper class Box<T requires Show> { v: T; } checks its bound at instantiation, and its own members let Box satisfy in turn. The standard library’s json and flow packages are built exactly this way (see the standard library).

Type tests: is

expr is Type answers with a bool and never traps:

  • Concrete RHS — p is Circle: an exact-type test.
  • Interface RHS — p is Shape: a capability probe — true when the value’s concrete type was satisfaction-boxed somewhere (itable fills exist for Shape).
use pouch::{ Vec };
use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
}

class Circle { r: f64; }
class Square { side: f64; }

impl Circle {
    pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; }
}

impl Square {
    pub fn area(self) -> f64 { return self.side * self.side; }
}

entry fn main() {
    let log = Logger("interfaces");
    let mut shapes: Vec<Shape> = Vec::new();
    shapes.push(Circle { r: 1.0 });
    shapes.push(Square { side: 2.0 });
    let sq = Square { side: 2.0 };
    log.info(f"shape: {sq is Shape} circle: {sq is Circle}");
}
shape: true circle: false

is answers the question; it changes nothing — there is no narrowing and no downcast through an interface. An interface-typed value is used through its interface’s members; if you need the erased-storage version — a value whose type is forgotten until recovered — that is opaque, covered in errors and optionality and the reference on opaque.

Bounds connect interfaces to generics

fn name<T requires Labeled>(x: T) admits exactly the instantiations whose concrete type satisfies Labeled — the same member-set check, run where T is chosen — see functions, closures, and generics. The bound is what makes interface use legal inside the body: let w: Labeled = x;.

Making your type iterable

A type becomes a for..of target by marking an inherent member [iterable] — the bracket marker designates the member (the NAME is free; the element type falls out of the member’s own emit parameter). No import is needed — the marker word IS the designation; the builtin sequences never mark one:

use pouch::{ Vec };
use ink::{ Logger };

class CountUp { n: i32; }

impl CountUp {
    [iterable] pub fn iterate(self, emit: fn(i32) -> bool) {
        for (let mut i = 1; i <= self.n; i += 1) {
            if (!emit(i)) { return; }   // false = stop
        }
    }
}

entry fn main() {
    let log = Logger("iter");
    let ups = CountUp { n: 4 };
    let got: Vec<i32> = Vec::new();   // shared: survives the loop's captures
    for (let v of ups) {
        got.push(v);
    }
    log.info(f"n={got.len()} first={got[0]} last={got[got.len()-1]}");
}
n=4 first=1 last=4

for (let v of it) desugars to it.iterate(emit) with a synthetic closure, and the capture law covers it like every closure: scalars copy (a rebind inside the loop stays local), ref-headed bindings share their slot — reassigning one inside the loop moves the original, and the loop variable is ONE variable reassigned per iteration, exactly like a handwritten while (see functions, closures, and generics). Accumulating through a shared vec.push(v) works, and so does plain reassignment.

The builtin sequences ([T], Vec<T>, str, bytes) iterate without the marker — their loops are fused, never a per-element call.

Put it together

use pouch::{ Vec };
use ink::{ Logger };

pub interface Shape {
    fn area(self) -> f64;
    fn name(self) -> str;
}

class Circle { r: f64; }
class Square { side: f64; }

impl Circle {
    pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; }
    pub fn name(self) -> str { return "circle"; }
}

impl Square {
    pub fn area(self) -> f64 { return self.side * self.side; }
    pub fn name(self) -> str { return "square"; }
}

fn describe(s: Shape) -> str {
    return f"{s.name()}={s.area()}";
}

entry fn main() {
    let log = Logger("interfaces");

    let c: Shape = Circle { r: 1.0 };        // satisfaction assertion
    log.info(describe(c));                    // single origin: static call

    let sq = Square { side: 2.0 };
    log.info(f"is shape: {sq is Shape}");

    let mut shapes: Vec<Shape> = Vec::new();   // heterogeneous storage
    shapes.push(Circle { r: 1.0 });
    shapes.push(Square { side: 3.0 });
    let mut total: f64 = 0.0;
    for (let s of shapes) {
        total += s.area();                    // itable per element
    }
    log.info(f"total={total} n={shapes.len()}");
}
circle=3.14159
is shape: true
total=12.14159 n=2

Next: errors and optionality.

Errors and optionality

rut has no exceptions you catch. Two mechanisms cover everything:

  • Absence is nil on a nullable ?T.
  • Failure is a value in the second slot of a pair — the (T, err) answer channel.
  • Bugs — broken contracts — trap loudly and immediately (panic, a nil deref, an out-of-bounds index).

The design background lives in everything is a value.

?T and nil: absence

?T is a nil-able cell. A plain T always holds a value; ?T is that value or nil:

use ink::{ Logger };

struct Node {
    value: i32;
    left: ?Node;      // one word — recursive shapes are legal
    right: ?Node;
}

entry fn main() {
    let log = Logger("nodes");
    let n = Node { value: 1, left: nil, right: nil };
    log.info(f"left is nil: {n.left == nil}");
}
left is nil: true

Lookups answer ?T: a hit is the value, a miss is nil. Deref is automatic at every use — p.x, p[i], for (let x of p), arithmetic — and dereferencing a nil traps NilDeref, so guard first:

use nmapset::{ HashMap };
use ink::{ Logger };

entry fn main() {
    let log = Logger("optional");
    let mut scores: HashMap<str, i32> = HashMap();
    scores.put("rut", 41);
    let mut n = 0;
    let hit = scores.get("rut");      // ?i32
    if (hit != nil) {
        n = hit + 1;                  // a hit auto-unwraps for `+`
    }
    log.info(f"n={n}");
}
n=42

p == nil compares against the null. There is no flow-typing: after the guard, hand the value to a typed binding when you want a plain T:

let err = map_response(resp, "no such repo or ref", "data.jsdelivr.com");
if (err != nil) {
    let why: str = err;           // the plain str behind the nullable
    eprint(why);
    return 1;
}

nil in an expected-?T position just works: let p: ?Node = nil;, or a left: nil field in a literal.

The (T, err) answer channel

Functions that can fail return a pair. The convention is uniform:

  • empty err + a value — success;
  • empty err + nil — a legitimate “not found”;
  • non-empty err — failure.

The simplest err is a str message (empty string means success):

fn hex_dec(s: str) -> (bytes, str) {
    if (s.len() % 2 != 0) {
        return (bytes::zeroed(0), "hex: odd-length input");
    }
    // ... decode ...
    return (out.freeze(), "");
}

Nullable halves make both slots explicit — this is the standard library’s own shape, (?T, ?E):

// json's entry points
fn decodeJson<T requires JsonDeserialize>(s: str) -> (?T, ?DecodeJsonError);
fn encodeJson<T requires JsonSerialize>(v: T) -> (?str, ?EncodeJsonError);

The caller destructures and checks the err half first:

use json::{ decodeJson, JsonI64 };
use ink::{ Logger };

entry fn main() {
    let log = Logger("json");
    let (n, e) = decodeJson<JsonI64>("42");
    if (e == nil) {
        log.info(f"n={n.get()}");
    } else {
        let why = e;
        log.info(f"decode failed at {why.at}");
    }
}
n=42

Integer arithmetic’s checked ladder uses the same idea in miniature: x.checked_add(y) answers (T, bool) where .1 is false exactly when the result escaped the width — see values and variables.

Building an error type

For errors a caller might want to branch on, pair a payloadless enum (the kind) with a fixed-field struct (the details). That is the shape json uses:

pub enum DecodeErrorKind { Unexpected, Truncated, InvalidUtf8, WrongType, Depth, Trailing }

pub struct DecodeJsonError {
    kind: DecodeErrorKind;
    at: i64;        // codepoint offset in the input
    got: str;       // the offending text
    expected: str;  // what the schema asked for here
}

The caller picks: branch on kind, or just render the fields:

use json::{ decodeJson, JsonI64 };
use ink::{ Logger };

entry fn main() {
    let log = Logger("json");
    let (bad, be) = decodeJson<JsonI64>("[1,2,3]");
    if (be != nil) {
        let why = be;
        // rejected at 0: got '[', wanted an i64
        log.info(f"rejected at {why.at}: got '{why.got}', wanted {why.expected}");
    }
}
rejected at 0: got '[', wanted an i64

Enums have no payloads — the struct carries the data. This split keeps every error a plain value: copy it, store it in a log, put a location next to it, test it.

panic: for bugs, not for flow

panic("Rect: negative extents");        // abort with a message

Use it when continuing would be a lie: a broken invariant, an impossible state, a caller error that is a programming mistake. Data problems — a bad byte in a file, a missing key, a network error — are values and belong in the answer channel, so callers can recover.

There is no builtin assert: if a package wants one, it writes the two-line helper over panic and owns it:

fn assert(c: bool, m: str) { if (!c) { panic(m); } }

assert(total == expected, "checksum");  // abort when the condition is false

A trap’s message and a stack trace (opt-in via capture_stacktrace()) land in the host’s diagnostics — see diagnostics, traces, and symbolication.

Erasure when you truly need it

When a value must cross a boundary that cannot name its type — host handles, heterogeneous boxes — opaque(v) seals it and opaque::downcast<T>(o) -> ?T recovers it (nil on a wrong type, never a trap):

use ink::{ Logger };

struct Point { x: i32; y: i32 }

entry fn main() {
    let log = Logger("opaque");
    let box1 = opaque(Point { x: 1, y: 2 });
    let p = opaque::downcast<Point>(box1);   // ?Point
    when (p != nil) {
        true -> { log.info(f"point {p.x} {p.y}"); },
        else -> { log.info("point: nil"); },
    }
}
point 1 2

x is T probes the box without recovering it. This is rut’s only any-shaped value, and it can do nothing until recovered — see the reference on opaque.

Put it together

use json::{ decodeJson, encodeJson, JsonArr, JsonI64 };
use ink::{ Logger };

entry fn main() {
    let log = Logger("json");

    // a successful decode: (value, nil)
    let (n, e) = decodeJson<JsonI64>("42");
    if (e == nil) {
        log.info(f"n={n.get()}");
    } else {
        let why = e;
        log.info(f"decode failed at {why.at}: {why.expected}");
    }

    // encode answers the same shape: (?str, ?EncodeJsonError) —
    // through the spelled wrapper: a bare [i64] never satisfies
    let (s, ee) = encodeJson(JsonArr([JsonI64(1), JsonI64(2), JsonI64(3)]));
    if (ee == nil) {
        let text = s;
        log.info(f"s={text}");
    } else {
        log.info("encode failed");
    }

    // a bad decode: the (nil, err) half answers the failure
    let (bad, be) = decodeJson<JsonI64>("[1,2,3]");
    if (be == nil) {
        log.info("unexpected success");
    } else {
        let why = be;
        log.info(f"rejected at {why.at}: got '{why.got}', wanted {why.expected}");
    }
}
n=42
s=[1,2,3]
rejected at 0: got '[', wanted an i64

Next: modules and packages.

Modules and packages

A rut file is a module: one namespace, one visibility scope. A directory with a rut.jsonc is a package — the unit you depend on and share. This chapter walks up those two levels. The reference pages are modules and visibility, project structure and rut.jsonc, and dependency kinds.

What lives at module scope

Module scope contains declarations only: use, let, fn, struct, class, enum, interface, impl. Every statement lives inside a function — and loading a module executes nothing. There is no load-time side-effect ordering to reason about; the host loads your module and calls one of its entry fns (entry fn main for a plain program).

Module-level let initializers must be load-time literals — 42, "app", true. Arithmetic, record literals, and calls to user functions are not accepted in this build (there is no mutable module state; programs build their state in main).

use pouch::{ Vec };
use ink::{ Logger };

struct Point { x: f32; y: f32 }

let version = 1;                       // fine: a literal
let app_name = "app";                  // any literal works

fn main_body() { /* statements live here */ }

entry fn main() {
    let log = Logger("app");
    let origin = Point { x: 0, y: 0 }; // record literals live in function bodies
    log.info(f"{app_name} v{version} origin.x={origin.x}");
}
app v1 origin.x=0

Visibility

Every declaration has a visibility, and unannotated means module-private — the safe default. Nothing leaks unless it says pub:

FormMeaning
pub fn ..public — importable by any module, other packages included
pub(mod) fn ..visible everywhere in this package’s module tree
pub(super) fn ..visible to the parent module only
fn ..module-private (pub(self)) — the default

The same forms apply to types, module lets, and class members. Structs are the exception: a struct is an open record — all members public, always, and its impl methods take no visibility annotation (they are as public as the type).

use — naming other modules

use imports names with Rust-like paths:

use ink::{ Logger };
use pouch::{ Vec };
use json::{ decodeJsonBytes, JsonDeserialize };

Builtin names — the primitives, str/bytes members, panic, Vec-free array grammar, opaque — are ambient: no use needed. The exceptions are core’s import-gated names — the disposal context DisposalContext and the weak reference Weak — they resolve only through use core::{ .. }, like any package name. Package names from your manifest are imported the same way; an unused name in a use is a lint, not an error, while a name the target doesn’t export is rejected at the use line itself — `ink` has no `Nope` — unknown import.

Within one module, everything is visible — including declarations later in the file. Order never matters.

Packages: rut.jsonc

A package is a directory with a manifest. The small but complete case — one library package and one app:

greet/
├── pkg/
│   ├── rut.jsonc
│   └── mod.rut            # the package's root module
└── app/
    ├── rut.jsonc
    └── mod.rut            # the app's root module
// greet/pkg/rut.jsonc
{
  "name": "greet",

  "deps": {
    // the toolchain's pouch package, from jsDelivr — the pin lives in
    // the app's rut.lock (one lock per walk root)
    "pouch": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle" }
  }
}
// greet/pkg/mod.rut
use pouch::{ Vec };

pub struct Greeting {
    to: str;
    lines: Vec<str>;
}

impl Greeting {
    pub fn new(to: str) -> Self {
        return Self { to: to, lines: Vec::new() };
    }

    pub fn add(mut self, line: str) {
        self.lines.push(line);
    }

    pub fn render(self) -> str {
        let mut out = f"dear {self.to},";
        for (let line of self.lines) {
            out = f"{out} {line}";
        }
        return out;
    }
}

fn shout(msg: str) -> str {   // module-private: no `pub`, never importable
    return f"{msg}!";
}

The app names its dependencies in deps, by url or path. One table carries two laws: mounting is transitive — each package pulls its own dependencies along (ink brings the host surface ink_host; you never spell it) — while nameability is declaration-scoped: the app may use exactly the heads its own manifest names. ink_host mounts here, but only ink declared it, so only ink’s sources may name it; an app-level use ink_host:: is refused, naming the fix (add the row to your rut.jsonc deps):

// greet/app/rut.jsonc
{
  "name": "app",

  "deps": {
    // your own package: a sibling directory
    "greet": { "path": "../pkg" },
    // the toolchain's ink package, from jsDelivr — the pin lives in
    // this app's rut.lock
    "ink": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" }
  }
}
// greet/app/mod.rut
use greet::{ Greeting };
use ink::{ Logger };

entry fn main() {
    let log = Logger("app");
    let mut g = Greeting::new("rut");
    g.add("hello");
    g.add("from a package");
    log.info(g.render());
}

Run the app from its directory — rut install fetches the url deps and writes the app’s rut.lock (the pin ledger every load verifies against; it pins the whole closure, including the url row ../pkg declares), then rut run .:

rut install .
rut run .
install: 2 url deps resolved — 2 downloaded, 0 cache hits (10594 bytes total)
rut.lock written: 2 rows (2 added, 0 changed, 0 dropped)
dear rut, hello from a package

Resolution walks deps recursively (a dep’s own deps mount with it), with a cycle guard and first-mount-wins. The walk decides what is mounted; what a source may name is its own manifest’s business: deps ∪ core (plus dev-deps at the program root). A head that is mounted but undeclared — riding along on someone else’s row — refuses with a dedicated diagnostic naming the mount edge and the row to add (dependency kinds).

One package, several files

A package’s body can be split across files — file modules. The root module is mod.rut beside the manifest, and a mod NAME; declaration in it mounts the sibling NAME/mod.rut as a child module:

app/
├── rut.jsonc        # { "name": "app" } — no entry keys
├── mod.rut          # the root module: `mod domain; pub mod world;`
├── domain/mod.rut   # app's `domain` module
├── world/mod.rut    # app's `world` module
└── app/mod.rut      # the shell

Each file is its own module. Cross-file references are qualified (domain::Todo, world::boot(..)) — or imported: use is also the intra-package import, so a file may bind another module’s pub names as bare names, per file:

// app/mod.rut — beside `mod domain;` and `mod world;`
use domain::{ Todo };
use world::{ World };

The leaves gate exactly as every crossing does: a name the target doesn’t declare is refused at the use line, and a private one stays private — pub or pub(pkg) to widen (import is no visibility bypass). A module needs its own use line: bindings are per file. Visibility is per module — private to the declaring module, pub(pkg) to share inside the package, pub to cross packages. Cross-package references still go through use paths (use greet::{ Greeting };).

Dependency tables

deps is one of two dep tables a manifest carries:

  • deps — the transitively mounted dependencies, and the declaration table (the nameability law above).
  • dev-deps — mounted only when building/testing the package itself, never for a consumer; the rows are path-only.

There is no third table: the grammar is strict at the top level, so a retired key (peer-deps) or flag (inline) refuses as the unknown key it now is, naming the key. The standard library’s json package shows the modern shape — its Vec/map serialization wrappers are json’s OWN source, and the container packages are plain deps riding along transitively:

{
  "deps": {
    "strbuild": { "path": "../strbuild" },
    "pouch":    { "path": "../pouch" },
    "nmapset":  { "path": "../nmapset" }
  }
}

entry fn — the host-facing surface

pub publishes a name to other rut modules. entry publishes a function to the embedding host, with its signature checked against the boundary’s crossing rules at compile time:

entry fn hex_enc(data: bytes) -> str { .. }

An embedded application drives these entries; rut run executes the program’s entry designation — exactly one entry fn runs it, several take --entry <name>. See the host boundary.

Tooling

rut run <dir | mod.rutbundle> [--entry <fn>] [--fuel N]      # compile + run
rut fmt <file.rut | dir> [--check]                    # format in place
rut pack <dir> [-o out.rutbundle]                     # a self-contained bundle
rut dump <file.rut>                                   # dump module info

Put it together

The greet project above is complete as shown — two directories, two manifests, two sources. Copy the trees into files and rut run . from greet/app to see:

dear rut, hello from a package

Next: async: futures and await.

Async: futures and await

rut’s concurrency is pull-based. An async fn compiles into a future — a cold value that runs nothing until something drives it. There are no promises that start on creation, no microtask queue, no implicit scheduling: the host owns time, and code progresses only when a driving loop pumps it. The model is described in the async model, with the full surface in async and await and launched futures.

async fn, async { }, and await

Calling an async fn runs nothing: it returns a cold future — a Future<T>, the ONE async type every producer answers (an async fn call, an async { } block, sleep, the race/completer mints). await is the in-body suspension point, and it consumes the future:

async fn countdown(log: Logger, n: u32) {
    let mut i = n;
    while (i > 0) {
        log.info(f"t-{i}");
        await sleep(500);       // park here; the loop resumes the frame
        i -= 1;
    }
    log.info("lift-off");
}

The resume context is injected, never spelled: the weave binds cx inside every async body (probe it with cx.cancelled() — see async and await). And async fn is sugar over the async { } block — the block is the primitive, an expression that mints the frame where it stands and answers Future<T>:

let f: Future<nil> = async {          // mints cold; runs when driven
    log.info("later");
};
launch_future(f);

Two consume paths, and exactly one per future:

  • await fut — drive it from this async body. Legal only inside an async fn or async block, and only for Future<..> values (which is every producer).
  • launch_future(fut) — hand it to the driving loop and keep a receipt. Returns a LaunchedFutureHandle<T>, which is not a future: it cannot be awaited or re-launched. Its abort() flags cancellation; the frame notices at its next checkpoint and runs its cleanup.

sleep(ms) is the one built-in pender — a Future<nil> that parks its frame until the VM’s clock reaches the deadline.

Both launch_future and sleep come from the futures package:

use futures::{ launch_future, sleep };

Who drives?

You never write a driving loop — the embedder does. The rut run CLI is an embedder: after main returns it pumps the loop — drain ready frames, advance the virtual clock to the next timer deadline, repeat — until nothing is pending. So a program launches work from main and the output simply appears:

rut run countdown/   # a module dir (rut.jsonc + main.rut); main launches the countdown
t-3
t-2
t-1
lift-off

Calling an async function and awaiting it in the same body is the straight-line case; launching is for concurrency — independent work that overlaps through the loop’s interleaving.

Talking to the network: the http package

The standard http package is async-only where work actually waits. Everything else — the client, the verbs, the builder — is sync construction sugar:

use http::{ HttpClient };

let client = HttpClient();
let resp = await client.get(url).build().send();

The shape, step by step:

  • client.get(url) (or request(), post, put, patch, del) hands back a RequestBuilder; .method(..), .url(..), .header(k, v) (repeatable), .body(bytes) chain on it.
  • .build() freezes a re-sendable Request.
  • .send() is the async point. It resolves at headers — the wire body is still unread.
  • From the Response, take one of two readbacks:
    • await resp.body() — drain the remaining body in one future;
    • resp.byte_stream() then await stream::next() — one chunk per future, nil at end-of-stream, for bounded-memory downloads.

Errors come back as data, not traps: status 0 is reserved for transport failure (resp.transport_error() carries the reason), any real status — 4xx and 5xx included — is a normal response (resp.ok() is the 2xx test), and a mid-read wire death surfaces as nil from next() with the reason in stream::error().

A complete request handler from the repository’s GitHub-viewer example — send, then drain:

async fn do_list(client: HttpClient, owner: str, repo: str, rf: str) -> i32 {
    let url = f"https://data.jsdelivr.com/v1/packages/gh/{owner}/{repo}@{rf}";
    let resp = await client.get(url).build().send();
    if (resp.status() == 0) {
        let why: str = resp.transport_error();
        eprint(f"rgh: network error: {why}");
        return 1;
    }
    if (!resp.ok()) {
        eprint(f"rgh: CDN {resp.status()}");
        return 1;
    }
    let (tree, e) = decodeJsonBytes<Root>(await resp.body());
    if (e != nil) {
        let why: DecodeJsonError = e;
        eprint(f"rgh: bad tree JSON at {why.at}");
        return 1;
    }
    // ... print the tree ...
    return 0;
}

The stream lane walks chunks — send, then loop:

let resp = await client.get(url).build().send();
let stream = resp.byte_stream();
while (true) {
    let c = await stream.next();
    if (c == nil) {
        let rerr = stream.error();
        if (rerr != nil) { return 1; }   // failed mid-read
        break;                            // clean end of stream
    }
    let chunk: bytes = c;
    total += chunk.len();
}

Racing futures and the join tier

select2(a, b) races two futures and answers the first-ready side as an Either2 (is_a()/a_value() or is_b()/b_value()); the losers are cancelled, their drop paths running at their next checkpoint. select_all(futs) extends the race to a cohort, answering (i, v). Joining a launched future’s value (await handle) is still spelled in the grammar but not in this build — the compiler gates it. See launched futures for the race and completer surfaces.

Parallelism

The language has none: a VM is single-threaded by construction (!Send, one heap — the VM); async is the whole concurrency story. A host that wants parallelism runs separate VMs — rut defines no surface for sharing between them.

Put it together

use futures::{ launch_future, sleep };
use ink::{ Logger };

async fn countdown(log: Logger, n: u32) {
    let mut i = n;
    while (i > 0) {
        log.info(f"t-{i}");
        await sleep(500);
        i -= 1;
    }
    log.info("lift-off");
}

entry fn main() {
    let log = Logger("countdown");
    launch_future(countdown(log, 3));
}
t-3
t-2
t-1
lift-off

Next: the standard library.

The standard library

The standard library splits in two. core is the only true standard — a prelude of builtin names that are ambient: in scope in every compilation unit, no use needed. Everything else is a set of swappable packages shipped in the toolchain tree — a program that wants one says so: a use line in the source and the package’s deps row in its rut.jsonc (project structure). Any of them can be replaced wholesale; the engine knows none of their names.

The reference page is core and the swappable packages.

What’s always there (core)

Reporting and bugs

panic("Rect: negative extents");       // abort with a message

assert is not a builtin — a package that wants one writes the helper over panic (bugs, not flow):

fn assert(c: bool, m: str) { if (!c) { panic(m); } }
assert(total == expected, "checksum"); // abort when false

Integer safety ladder

Every integer width carries compiler-lowered methods. Plain +/-/* trap on overflow; these never do:

use ink::{ Logger };

entry fn main() {
    let log = Logger("ladder");
    let mut v: u8 = 250;
    v = v.wrapping_add(10);            // 4 — two's-complement wrap
    let over = 200u8.checked_add(100); // (44, false) — .1 false = escaped
    let sat = 200u8.saturating_add(100); // 255 — clamp at the bounds
    log.info(f"v={v} over=({over.0}, {over.1}) sat={sat}");
}
v=4 over=(44, false) sat=255

checked_* answers (T, bool); .0 holds the wrapped bits either way. Pick per call site: a checksum wraps, a length checks.

str members

use ink::{ Logger };

entry fn main() {
    let log = Logger("str");
    let s = "héllo rut";
    log.info(f"len={s.len()} first={s.code()}");
    log.info(f"at1={s.code_at(1)} octets={s.encode().len()}");
    log.info(f"view={s.slice(6, 9)}");
    let head: str = "héllo";
    log.info(f"starts={s.starts_with(0, head)}");
    let joined = string_join(["rut", "runs"]);
    log.info(f"joined={joined}");
    let h = str::from_code(72);
    log.info(f"from_code={h}");
}
len=9 first=104
at1=233 octets=10
view=rut
starts=true
joined=rutruns
from_code=H

s.slice deserves a second look: no octets move; the view records a window over the parent, prints, compares by content, iterates, and can re-slice. Codepoint access is spelled with integers — str::from_code(n) builds the 1-codepoint str for a u32. Tokenizing rides s.scan(from, set) over a caller-owned [u8] class table. See string slicing and views.

bytes members

use ink::{ Logger };

entry fn main() {
    let log = Logger("bytes");
    let b = "rut runs".encode();
    log.info(f"len={b.len()} decode={b.decode()}");
    let copy = b.clone();     // the ONLY copy escape hatch
    let z = bytes::zeroed(4);
    let from = bytes::from([1, 2, 3]);
    log.info(f"same={copy == b} zeroed={z.len()} from={from.len()}");
}
len=8 decode=rut runs
same=true zeroed=4 from=3

Erasure and cleanup

opaque(v) seals any value for recovery with opaque::downcast<T>(o) -> ?T — see errors and optionality. Marking a [disposal] member on a type gives it cleanup code that runs when its cell’s refcount reaches zero, and Weak::new(v) holds a non-keeping reference (upgrade() -> ?T, nil once the referent died) — the memory stories live in the Rc heap and destructors and weak references.

The builder is a package

Core has no string-building class: the growable builder lives in the strbuild package (the stdlib reference) — use strbuild::{ StringBuilder }. For the common accumulator shape you need no builder at all: out = f"{out}{t}" appends in place, linear in the total output.

One gated name

NAN is core’s single constant, deliberately name-explicit: use core::{ NAN };. The float constants live in calc.

pouch — the growable sequence

use pouch::{ Vec };
use ink::{ Logger };

entry fn main() {
    let log = Logger("pouch");
    let mut xs: Vec<i32> = Vec::new();         // or Vec::with_capacity(64)
    xs.push(10);                              // amortized O(1)
    let v = Vec<f32>::filled(0.0, 1024);       // n slots of one value
    let w = Vec<i32>::from([1, 2, 3]);         // from a fixed array (copies)
    let x = xs[0];                            // indexing
    xs[0] = 42;                               // needs a `mut` binding
    let last = xs.pop();                      // removes + returns; traps if empty
    let n = xs.len();
    let mut total = 0;
    for (let e of w) {                        // iteration
        total += e;
    }
    log.info(f"x={x} last={last} len-after-pop={n} filled={v.len()} total={total}");
}
x=10 last=42 len-after-pop=0 filled=1024 total=6

Vec<u8> is the mutable byte builder: push bytes, then freeze() into the immutable bytes. xs.as_array() copies the live elements into a fixed [T]. A slice(from, to) window is compiler-lowered — an O(1) view that writes through to the parent vector.

nmapset — keyed collections

use nmapset::{ HashMap, HashSet };
use ink::{ Logger };

entry fn main() {
    let log = Logger("nmapset");
    let mut counts: HashMap<str, i32> = HashMap();
    let fresh = counts.put("rut", 1);          // answers true when the key was NEWLY added
    let mut n = 0;
    let hit = counts.get("rut");   // ?i32 — nil means absent
    if (hit != nil) { n = hit + 1; }
    let there = counts.has("rut");             // membership
    let gone = counts.remove("runs");         // answers whether it was there
    let size = counts.len();

    let mut seen: HashSet<str> = HashSet();
    let first = seen.put("x");     // true — newly added
    let again = seen.put("x");     // false
    log.info(f"fresh={fresh} n={n} has={there} removed={gone} len={size}");
    log.info(f"first={first} again={again}");
}
fresh=true n=2 has=true removed=false len=1
first=true again=false

Keys come from a fixed set — integers, bool, str, bytes (no floats: they have no stable equality contract) — hashed by the host; a user-defined key escapes by encoding canonically to bytes. A hit returns the stored cell, not a copy. There is no iteration surface: maps and sets answer questions, they don’t walk. Construction spells the call form — HashMap() / HashSet() are the designated new; with_capacity(n) stays named.

flow — the push pipeline

Flow<E> chains the push contract. A type is iterable when it marks an [iterable] member — for (x of it) calls that ONE designated member — and a Flow wraps one drive in adapter stages: a closure per stage, never per element. Entry is into_flow() — a member your value carries directly (Flow itself) or gets through a spelled adapter wrapper (VecFlow(nums), ArrFlow(xs), StrFlow(s)) — and everything after is chaining:

use pouch::{ Vec };
use flow::{ Flow, IntoFlow, FromFlow, VecFlow };
use ink::{ Logger };

entry fn main() -> nil {
    let log = Logger("flow");
    let nums: Vec<i32> = Vec::new();
    nums.push(1); nums.push(2); nums.push(3); nums.push(4); nums.push(5);

    // entry through the spelled adapter → adapters → consumer
    let src: VecFlow<i32> = VecFlow(nums);      // the manufacture, spelled
    let picked: Flow<i32> = src.into_flow()
        .map(fn(x: i32) -> i32 { return x * 2; })
        .filter(fn(x: i32) -> bool { return x > 4; })
        .take(3);
    let total: i32 = picked.fold(0, fn(acc: i32, x: i32) -> i32 { return acc + x; });

    // a fresh chain re-drives the same source
    let mut joined: Vec<str> = Vec::new();
    src.into_flow().skip(1).for_each(fn(x: i32) -> nil {
        joined.push(f"{x}");                    // a shared cell survives the closure
    });
    log.info(f"total={total} n={joined.len()} first={joined[0]} last={joined[joined.len-1]}");
}
total=24 n=4 first=2 last=5

Three laws to know:

  • The entries and sinks are interfaces, satisfied structurally — IntoFlow<E> is fn into_flow(self) -> Flow<E>: Flow itself carries the identity member (a chain re-enters as a source), and the builtin sequences — which can never carry members — enter through the spelled wrappers (ArrFlow<T>, StrFlow, BytesFlow, VecFlow<T>). The sinks (FromFlow<E>, the no-self member fn from_flow(it: Flow<E>) -> Self) are carried by VecFlow<T> (collected() unwraps) and SetFlow<T> (items()). Wrappers are explicit manufacture at the call site, never auto-inserted.
  • map introduces a new type variable. Annotate the lambda, spell the type argument (.map<i32>(..)), or pass a fn path — a lambda that spells nothing diagnoses with the fix.
  • Stateful stages are single-shot. take/skip hold their counter in a record the drive mutates; a drained stage stays drained. take answers false at its stop, which stops the SOURCE — the elements after it are never driven. A fresh into_flow() chain re-drives the source from its start.

Pipelines are the clarity tier: each stage costs one indirect call per element, and the fused builtin loops stay the perf tier. The full member table lives in the standard library reference.

strbuild — the string builder

use strbuild::{ StringBuilder };
use ink::{ Logger };

entry fn main() {
    let log = Logger("strbuild");
    let n = 3;
    let mut b = StringBuilder();     // or StringBuilder::with_cap(1024)
    b.append("count: ");
    b.append_code(33);                   // one codepoint
    b.append(f" up to {n}");             // appends are amortized O(1)
    let s = b.build();                   // the ONE materialization; builder keeps its buffer
    log.info(s);
}
count: ! up to 3

StringBuilder() is the designated new; with_cap(n) pre-sizes and stays named.

Every out = f"{out}{chunk}" loop copies the whole prefix each time; the builder appends into one growable cell and copies once, at build().

calc — float math

use calc::{ Math };
use ink::{ Logger };

entry fn main() {
    let log = Logger("calc");
    let x: f64 = -2.0;
    let a: f64 = 3.0;
    let b: f64 = 7.0;
    let d = Math::sqrt(2.0);        // f64 host fns: sin, pow, atan2, fma, ...
    let f = Math::sqrt_f(2.0f32);   // f32 twins under a `_f` suffix
    let mx = Math::max(a, b);
    let sg = Math::signum(x);
    log.info(f"sqrt={d} sqrt_f={f} pi={Math::PI}");
    log.info(f"abs={Math::abs(x)} min={Math::min(a, b)} max={mx} signum={sg}");
}
sqrt=1.4142135623730951 sqrt_f=1.4142135 pi=3.141592653589793
abs=2 min=3 max=7 signum=-1

rut has no overloading, so the width lives in the name. The integer ladder is not here — those are core’s, always available.

json — encode and decode

use json::{ decodeJson, encodeJson, JsonArr, JsonI64 };
use ink::{ Logger };

entry fn main() {
    let log = Logger("json");
    let (n, e) = decodeJson<JsonI64>("42");           // (?JsonI64, ?E) — see errors
    let (s, ee) = encodeJson(JsonArr([JsonI64(1), JsonI64(2), JsonI64(3)]));
    if (e == nil && ee == nil) {
        log.info(f"n={n.get()} s={s}");
    }
}
n=42 s=[1,2,3]

A bare [i64] never satisfies anything — the wrapper is the manufacture, spelled at the call (JsonArr([JsonI64(1), ..])), and the decode direction names the wrapper as the type argument (decodeJson<JsonArr<JsonI64>>(doc) then .to_arr()); a user type skips all of it by spelling encode/decode on its own inherent impl.

Decode is direct and schema-driven: your type’s decode member reads exactly the fields it expects, no intermediate tree. Your types opt in with two small members (satisfaction is structural — nothing to declare); the wrapper families (JsonVec<T> for Vec<T>, the map/set family) mount automatically when those packages are in your program. Error values are a kind enum plus a struct with .at/.got/.expected — see errors and optionality.

ink — logging

All output goes through a logger:

use ink::{ Logger };

entry fn main() {
    let n = 3;
    let log = Logger("app");
    log.info(f"started with {n} items");
    log.debug("..."); log.warn("..."); log.error("...");
}
started with 3 items
...
...
...

Logger is a plain rut class over a host-provided handle; the embedder chooses the sink (the rut CLI prints to stdout). The same pattern — declare a host surface in a .d.rut, wrap it in a rut class — is how any embedder package reaches rut code; see embedding and native modules.

http

The async HTTP client lives with the concurrency chapter — builder construction, send(cx) resolving at headers, body drains and byte streams — in async: futures and await.

Put it together

use pouch::{ Vec };
use strbuild::{ StringBuilder };
use calc::{ Math };
use ink::{ Logger };

// assert is plain rut code now: the helper a package writes over panic
fn assert(c: bool, m: str) { if (!c) { panic(m); } }

entry fn main() {
    let log = Logger("std");

    // Vec: build, pop, read
    let mut v: Vec<i32> = Vec::new();
    v.push(10);
    v.push(20);
    v.push(30);
    let last = v.pop();
    log.info(f"len={v.len()} last={last} first={v[0]}");

    // fixed arrays + string_join from core
    let parts: Vec<str> = Vec::from(["rut", "runs"]);
    log.info(f"joined={string_join(parts.as_array())}");

    // StringBuilder: amortized appends, one materialization
    let mut b = StringBuilder();
    b.append("count: ");
    b.append_code(33);
    b.append(f" up to {v.len()}");
    let s = b.build();
    log.info(s);

    // calc's Math namespace (f64) and its f32 twins (_f)
    let d = Math::sqrt(2.0);
    let f = Math::sqrt_f(2.0);
    log.info(f"sqrt2 f64~{d} f32~{f} pi={Math::PI}");

    // assert: the bug-catcher this file wrote itself
    assert(v.len() == 2, "vec should hold two");
    log.info("asserted");
}
len=2 last=30 first=10
joined=rutruns
count: ! up to 2
sqrt2 f64~1.4142135623730951 f32~1.4142135 pi=3.141592653589793
asserted

That completes the tutorial. From here, the core concepts explain why the language is shaped the way it is, and the reference pins down every rule.

Design goals

rut is a small, statically typed, embeddable scripting language with Rust-flavored syntax, implemented in Rust. It is designed to be the scripting layer of host applications — UI apps in particular — in the role a JavaScript engine usually plays: a safe, hot-reloadable language that drives the host’s object graph.

The difference is structural, not cosmetic. In an embedded JS engine the host’s types are erased (Element, Store are empty interfaces; the real types exist only in .d.ts files and get “recovered” by convention), cancellation is emulated on top of promises, and every value crossing the bridge is re-parsed and re-coerced by hand. rut is built so those three problems cannot arise: types are kept at runtime, coroutines are natively poll-based, and host values have deterministic lifetimes.

The pillars

Fully static, reified types. There is no dynamic typing and no gradual typing. Every value’s exact type is known to the compiler and carried at runtime — type tests, checked erasure, and host-boundary checks all read the same runtime truth. See reified types and layouts.

Types make code faster. The bytecode is typed, generics monomorphize, and primitive buffers stay flat: a fixed array of f32 is a packed f32 buffer, not an array of boxed numbers. There is no JIT and none is needed — the code shape a JS JIT exists to speculate on (polymorphic property loads) does not exist in rut.

Everything is a value — with two honest regimes. Primitives move by value; every composite (str, bytes, records, arrays, interface objects, erasure boxes) is a reference-counted cell whose handle copies in O(1). Sharing is the default and visible; there is no hidden copying. See everything is a value.

Poll-based coroutines. async/await compiles to cold state machines with Rust-style poll semantics: a future that nobody drives costs nothing, and cancellation drops the state machine at its suspension point. No promises, no microtask queue. See the async model.

Reference counting; no collector. Objects die the moment their last reference goes away, so destructors are deterministic — host resources (threads, sockets, textures) release at a knowable point, not “sometime at GC”. Strong cycles leak by design; weak references are the first-class answer. See memory.

No JIT. All optimization happens ahead of time: fold, inline, monomorphize, emit typed bytecode. What you run is what you compiled — predictable startup, predictable per-op cost, no tiering.

Embeddable by contract. The host registers native functions whose Rust signatures are the declared surface; every crossing is type-checked against reified types, and the host owns the event loop, the fuel budget, and the clock. See the host boundary and the bytecode VM.

Why not JavaScript

The case against shipping a JS engine — not just this or that implementation — is fourfold, and each item has a structural answer:

  1. History debt compounds. Two nullish values, coercing ==, typeof null, implicit semicolons: each is a permanent liability the ecosystem re-implements forever. rut starts from a closed, small grammar — absence is nil on a nullable type, errors are values, and the handful of reserved words each name what to write instead. Nothing legacy can accrete.

  2. Conformance means implementing the world. A compliant engine needs BigInt, Intl, Date’s quirks, microtask ordering — thousands of person-hours before user code runs. rut’s built-in contract is deliberately tiny: primitives, sequences, channels, string building. Everything else is library — maps and sets, JSON, logging, and the host’s own domain are ordinary packages, several of them written in rut and swappable.

  3. Too slow without a JIT. Interpreter-only JS runs one to two orders of magnitude slower, because a JS engine’s speed is its JIT. rut’s no-JIT stance is viable only because the language is statically typed: calls bind statically whenever the call site names one concrete type, and dynamic dispatch is a checked vtable hop that happens only where the program actually erases types.

  4. Too much memory. JS values are boxes — per-object headers, tagged pointers, boxed array elements, collector overhead. rut’s answer is layout: untagged 8-byte slots, record payloads as slot arrays, flat primitive buffers, and reference counting with no collector pass on the hot path.

What “no dynamic typing” leaves you

Erasure is never silent — it is spelled and checked:

  • Interface-typed values (s: Drawable) for polymorphism. Dispatch is dynamic only where a value may be one of several concrete types, and an interface-typed value still carries its exact class at runtime.
  • The opaque box (opaque(v), opaque::downcast<T>(o)) for storage. Erasure mints a checked box; recovery checks the runtime type and yields nil on a mismatch — never a silent wrong-type read.

JSON-shaped data, heterogeneous collections, and any-shaped host APIs all route through these two doors, which is what keeps “every value has a runtime type” true without giving up dynamism where it earns its keep.

The execution model

source ──► lexer/parser ──► typecheck ──► IR ──► typed bytecode ──► VM
                                   (fold, inline, monomorphize)
  • One thread per VM. A Vm instance runs on one thread with one heap and no atomics.
  • The host owns time. The VM exposes stepping verbs — drain the ready queue, expire timers, poll with a deadline — plus op budgets and interrupt callbacks. A UI host drives script between frames and stays responsive; a test host virtualizes the clock and gets fully deterministic schedules.
  • Traps stop at the boundary. A panic in script (overflow, nil deref) unwinds as a Trap value to the host call — rut code never catches one. Bugs become host-visible errors with a script backtrace, not corrupted state.

What this buys you

If you are writing scripts: assignments never deep-copy; cleanup runs when the last reference dies; a miss is nil, a failure is a returned err string, and a crash is a loud trap with a real stack trace. If you are embedding: you declare your API once in a rut declaration file, bind it with typed Rust closures, and the compiler plus the load-time verifier reject every mismatched shape before any script runs — there is no bridge boilerplate to maintain.

The rest of this section walks each pillar in depth; the tutorial shows the day-to-day syntax, and the reference pins down exact rules.

Everything is a value

rut’s type system has one spine: every name binds a value, and there are exactly two ways a value can exist. Primitives and fn values are immediate — moved by copying their bits. Every other type is a cell — a heap object whose handle is what gets copied. That single split explains assignment, parameter passing, equality, and what bytes::clone() is for.

The two regimes

immediatecells
typesu8..u64, i8..i64, f32, f64, bool, fn valuesstr, bytes, struct and class records, [T] arrays, enums, interface objects, opaque boxes, ?T boxes, closures’ captured cells
assignmentcopies the bitscopies the handle (O(1))
mutationn/a — write the variablevisible through every alias
==by valuestr/bytes: by content; everything else: identity

There is no third regime. No type is “sometimes copied, sometimes shared”: a struct value never silently deep-copies, a str never silently aliases. The regime is a property of the type, known at compile time, and the compiler emits the right move for it.

Sharing is the law for cells

let b = a on any cell type is one handle move: the new binding retains the cell, the old binding releases it. Passing a million-element array to a function retains once. A loop binding iterates the stored elements, not copies of them.

use ink::{ Logger };

struct Point { x: f32; y: f32 }

entry fn main() {
    let log = Logger("values");
    let mut p = Point { x: 1, y: 2 };
    let q = p;          // q and p name ONE cell
    p.x = 4;            // q.x is 4 now — sharing is the law
    log.info(f"q.x = {q.x}");   // read through the other alias
}
q.x = 4

Mutation through an alias is visible through all of them, in both directions. What gates writing is the mut-binding rule — a binding must be declared mut to be written through — never the sharing itself. Sharing is always safe: a handle keeps its referent alive, so nothing dangles, and there is no borrow checker because there are no loans.

If you want a value that aliases nothing, you build one: a literal, a constructor, a copy of the fields you need. The language has exactly one copy escape hatch — bytes::clone(), a one-shot deep copy of a binary buffer, for interop hand-offs. There is no generic clone: a divergent value of any other type is unreachable by construction, which is what makes aliasing something you can reason about locally.

?T — the nullable

Absence is nil on a nullable type, spelled as a prefix on the type: ?T is “a T or nil”. ? applies to the type term that follows, so [?T] is an array of nullables while ?[T] is a nullable array, and ??T chains (and unwraps transitively at use).

The coercions are one line: T → ?T boxes; ?T → T derefs. The box is a fresh one-slot cell that aliases the value’s cell — boxing a record shares it, boxing a primitive copies its bits. The deref is implicit at every value position: field access, method calls, indexing, iteration, arithmetic all read through the box.

use ink::{ Logger };

struct User { id: i64; name: str }

fn lookup(id: i64) -> ?User {
    if (id == 7) { return User { id: 7, name: "ada" }; }
    return nil;             // a miss is nil, nothing else
}

entry fn main() {
    let log = Logger("values");
    let u = lookup(7);                // ?User
    log.info(f"u.name = {u.name}");   // auto-deref when non-nil
    let missing = lookup(8);
    log.info(f"miss is nil: {missing == nil}");   // guard where absence is expected
}
u.name = ada
miss is nil: true

A nil reaching a value use traps (NilDeref) — never a silent read. Guard with u == nil where absence is expected; the trap is the bug-catcher, not the semantics. A miss is nil and nothing else: a lookup that finds nothing returns ?V, and callers compare against nil.

== is honest about the regime

  • Primitives compare by value.
  • str compares by content (codepoints); bytes by octets.
  • Everything else compares by identity — two bindings are equal exactly when they name the same cell.

Identity is the only equality full sharing can defend: two separately built [1, 2] arrays are two cells, so [1,2] == [1,2] is false. Content comparison is a loop over fields, written where content is the contract. The one place identity quietly behaves like value equality: enum variants are immortal singletons, so Flavor::Sour == Flavor::Sour is true.

The answer channel: a pair

There is no exception type. Failures are data in the second element of a record — (value, err) — with one documented convention:

  • an empty err plus a value is success;
  • an empty err plus nil means “not found”;
  • a non-empty err means “failed”.
use ink::{ Logger };

fn parse_hex(s: str) -> (bytes, str) {
    if (s.len() % 2 != 0) {
        return (bytes::zeroed(0), "hex: odd-length input");
    }
    let n = s.len() / 2;
    let mut buf: [u8] = [0u8; n];
    for (let mut i = 0; i < n; i += 1) {
        let hi = hex_digit(s.code_at(i * 2));
        let lo = hex_digit(s.code_at(i * 2 + 1));
        if (hi < 0 || lo < 0) {
            return (bytes::zeroed(0), "hex: not a digit");
        }
        buf[i] = ((hi * 16) + lo) as u8;
    }
    return (bytes::from(buf), "");       // (data, "") on success
}

fn hex_digit(c: u32) -> i64 {
    if (c >= 48 && c <= 57) { return (c - 48) as i64; }   // '0'..'9'
    if (c >= 97 && c <= 102) { return (c - 87) as i64; }  // 'a'..'f'
    return -1;
}

entry fn main() {
    let log = Logger("values");
    let (raw, err) = parse_hex("4869");
    if (err != "") { log.info(f"err: {err}"); return; }   // propagate
    log.info(f"ok: {raw.decode()} ({raw.len()} bytes)");
    let (raw, err) = parse_hex("486");
    if (err != "") { log.info(f"err: {err}"); }           // the failure channel
}
ok: Hi (2 bytes)
err: hex: odd-length input

The pair destructure in return position is free — the compiler fuses the mint away — so this shape costs nothing on hot paths. At the host boundary the same pair crosses field by field, which makes entry fn -> (?T, err) the standard answer a Rust embedder reads.

Consequences you feel day to day

  • Reassignment is cheap. Moving containers around — returning them, storing them, restructuring them — is handle traffic, not payload traffic. Algorithms that churn records and arrays pay aliasing, not copying.
  • Loop variables share elements; the binding is one variable. A for (let x of xs) loop hands you the stored element: plain let is a read-only view, and write access follows the header’s mut like any binding — a let mut loop variable’s writes mutate the sequence. The loop variable is ONE binding reassigned per iteration — for..of is sugar for a while-shaped loop, and the capture law treats it like any other ref-headed binding.
  • Containers of primitives stay flat. A fixed [i32] is a packed i32 buffer; growable sequences of primitives store raw payloads with a one-byte nil tag — no per-element heap box.
  • Erasure is a box. opaque(v) mints an erasure box; recovery is opaque::downcast<T>(o), checked against the runtime type. See reified types and the reference on opaque.

The memory machinery under all of this — refcounts, deterministic destructors, weak references — is the next chapter’s subject: memory. The exact rules live in the reference on by-reference and nullable.

Reified types and layouts

Types in rut are not a compile-time fiction. Every value’s exact type is available at runtime — generics included: a Cache<i32> and a Cache<str> are different types to the VM, with distinct identities and distinct method sets. This chapter explains where that reified reality lives, what it is used for, and how values are actually laid out.

The mental model

Think of the VM as keeping a type table: one descriptor per instantiated type — its kind, its field list, its itable fills, and for composites the method tables its instances point at. Every heap cell’s header names an entry in that table. A value never “forgets” its type, because its type is one field read away.

Types themselves are not first-class script values — you cannot put a type in a variable or write a function over types. What you get is the language-facing surfaces of reification:

  • is type tests — x is Circle (exact) and x is Drawable (capability: does this value’s type have a registered impl?).
  • Checked erasure — opaque::downcast<T>(o) reads the box’s runtime type and recovers the payload, or nil on a mismatch.
  • Host-boundary checks — native functions declare parameter types once; every call is checked against them.
  • Debugging and traces — error messages, backtraces, and formatter output name real runtime types.

Why reification is load-bearing

The reason rut can check everything cheaply is that the runtime type is always reachable:

  1. The host boundary needs no coercion code. A native fn declares (Opaque, str, str) -> nil once; the VM checks each argument’s runtime type at the crossing. There is no bridge-side “re-parse-and-pray” layer, because a wrong-shaped call fails loudly at the boundary.
  2. Erasure is checked, not blind. opaque(v) stamps the box; opaque::downcast<T> consults the stamp. A box answers type tests by the box — o is T misses for every payload type — so the only way back to the payload is the checked recovery. Erasure without reification would be any; with reification it is a sealed box.
  3. Distinct instantiations. Vec<f32> and Vec<f64> are different types everywhere — in the type table, in method resolution, at the host boundary. Nothing about a generic’s type argument is erased.

Slots: the untagged hot path

Inside the VM, registers and record fields are untagged 8-byte slots. The bytecode is typed — every register’s static type is recorded in the function’s signature and re-verified at load — so hot paths carry no type tags at all:

#[derive(Clone, Copy)]
pub union Slot {
    pub i: i64,            // ints, bool: the canonical scalar width
    pub f: f64,            // floats: f32 widened
    pub r: *mut CellVal,   // every non-primitive: a cell handle
}

A primitive is its bits; a composite is a handle to a cell. The tagged world — a value that carries its type with it — exists only at the host boundary, where Rust code that cannot trust static types receives checked, typed values.

Record layout: one slot per field

Both struct and class values live in a cell: a header (refcount + type id), a pointer to the type’s vtable when the type has methods, and the payload — a slot array, one untagged slot per field, in declaration order.

  • Primitive fields are widened into their slot; composite fields are cell handles.
  • Visibility, generic parameters, and impl blocks elsewhere add nothing — the payload depends only on the field list.
  • Field access is by index; there are no hidden members and no inheritance, so there is no base-class prefix and nothing to walk.
  • Fixed arrays of primitives ([f32]) keep their elements flat and packed at machine width — the one place values live inline. Growable sequences are rut-library classes over such arrays.

Consequences:

  • size_of/align_of do not exist, deliberately. Layout is an implementation detail, not an API — rut has no C-ABI struct surface for hosts to mirror. Hosts see records only through the checked boundary (see the host boundary).
  • A record’s memory cost is its field count times 8 bytes plus the cell header, which is exactly what the heap budget charges.
  • Widening a value to an interface type allocates nothing: the interface-typed value is the same cell, reinterpreted through its vtable.

Vtables: one per type, attached at construction

A cell’s vtable is filled when the value is constructed and never changes. It names the exact type and holds one entry per interface member the type was satisfaction-boxed at, keyed by a global (interface instantiation, member) id — Slice<Point> and Slice<str> have separate slot sets, because they are separate interface instantiations.

A call through an interface object is two loads and an indirect jump:

d.draw(g)          ; d: Drawable, draw has global slot 3
  obj  <- d.cell
  code <- obj.vtable.slots[3]
  call code(d, g)

An inherent method call — c.area() on a concrete c — compiles to a direct call with no table involved. The dispatch rules that choose between the two are the subject of the next chapter, interfaces and dispatch.

Type tests, lowered

Every type test is a small, pure read:

  • Concrete test (d is Circle): load the value’s runtime type id, compare. When the receiver’s static type already answers, the compiler folds it to a constant.
  • Interface probe (x is Drawable): load the type id, scan the descriptor’s registered impl list. Pure in its inputs, so repeated probes deduplicate and invariant ones hoist.
  • Downcast (opaque::downcast<T>(o)): the same type-id compare, followed by the guarded payload extract.

There is no runtime layout introspection — the descriptors serve the VM, the checks, and tooling, not userland metaprogramming.

What this buys you

  • Type errors are runtime facts, not conventions: a host call, a downcast, or an interface probe is checked against the same table the VM dispatches through.
  • One runtime truth per value — the vtable that answers dispatch is the same one that answers is.
  • The tag-free hot path keeps the interpreter’s arithmetic and field traffic at raw slot speed while reification costs only what the program’s dynamic features actually use.

Interfaces and dispatch

An interface in rut is an observed capability: a list of method signatures that a type satisfies by having the members. Satisfaction is structural — checked once, at the boundary where a concrete value is used as the interface. There is no admission step: no registration, no impl block for an interface, nothing a type can join by saying so.

The philosophy

Every polymorphism mechanism in rut answers to one table of equations; they are worth internalizing before any syntax:

  • inherent = contract — a type’s inherent impl is its contract: the members it actually has, visible to whoever can name the type.
  • interface = observed capability — an interface never changes a type; it is a member set some code observes the type through.
  • newtype = manufacture — a wrapper class manufactures a member set for a type that cannot carry one (a primitive, a composite); the call site spells the manufacture, every time.
  • marker = designation — the bracket markers ([disposal], [iterable], [constructor]) are designated surfaces, not polymorphism ([disposal] and [iterable] are engine hooks; [constructor] binds the user’s Type(..) call form).
  • closed class = engine value — Future<T> and RunContext are engine-minted; no user spelling can become one.

And the corollaries that keep the model honest:

  • Scope changes spelling, never meaning. What a module imports changes which names resolve, never what a type can do.
  • One job per mechanism. The member-set check admits; the itable dispatches; the marker designates. No mechanism does two jobs.
  • No mechanism may make a type’s capability depend on imports. A type’s members are where the type is declared; no use anywhere can add or remove them.
  • Wrappers are explicit manufacture at the call site. A primitive crosses into polymorphism inside a spelled wrapper construction — never auto-inserted.
  • Satisfaction is boundary checking, never resolution search. The compiler checks the member set at param-passing, typed lets/assigns, returns, and boxing sites; it never scans the program for “who might implement this”.

The shape of an interface

use ink::{ Logger };

pub interface Area {
    fn area(self) -> f64;
}

class Point {
    x: f64;
    y: f64;
}

impl Point {
    pub fn area(self) -> f64 { return self.x * self.y; }
}

entry fn main() {
    let log = Logger("areas");
    let p = Point { x: 3, y: 4 };
    log.info(f"area = {p.area()}");     // a concrete receiver: static
}
area = 3
  • Signatures only, no bodies. An interface declares members — no fields, no properties, and no default implementations, ever. One member kind means one dispatch candidate per call; a default body would be a second candidate with a resolution law of its own.
  • Self and generics are legal in signatures; interface generic parameters take no bounds. Each type-argument list gives the interface its own member set.
  • No pub on members, no requires on the interface, no embedding. A flat member set; compose by declaring the members.
  • One impl form. impl T { .. } defines the type’s inherent members and may live only in the module that declares T. impl I for T does not parse — there is no second form.

Type bodies are fields only — a fn inside a struct or class body is a parse error. Every method a type has lives in an impl block.

Interface-typed values

An interface name in type position is the bare name — there is no object-type keyword:

use ink::{ Logger };
use pouch::{ Vec };

pub interface Area {
    fn area(self) -> f64;
}

class Circle {
    r: f64;
}

class UnitSquare {
    side: f64;
}

impl Circle {
    pub fn area(self) -> f64 { return 3.14159265358979 * self.r * self.r; }
}

impl UnitSquare {
    pub fn area(self) -> f64 { return self.side * self.side; }
}

class Canvas {
    log: Logger;
}

impl Canvas {
    pub fn render(self, a: f64) { self.log.info(f"blitted a shape of area {a}"); }
}

fn blit(g: Canvas, s: Area) { g.render(s.area()); }   // a parameter over any Area

entry fn main() {
    let log = Logger("shapes");
    let g = Canvas { log: log };
    let mut mixed: Vec<Area> = Vec::new();   // heterogeneous storage
    mixed.push(Circle { r: 1.0 });
    mixed.push(UnitSquare { side: 2.0 });
    for (let s of mixed) { blit(g, s); }
}
blitted a shape of area 3.14159265358979
blitted a shape of area 4

An interface-typed value is a reference to a real cell that still carries its exact class. Passing a concrete value at an interface-typed position is implicit on assignment, argument passing, and returns, allocates nothing, and is gated by exactly one question: does the value’s type have the members? There is no top interface to widen to, and intersection types (A & B) are ruled out by design — when you need both capabilities, declare an interface that spells both member sets.

Dispatch: the two-rule law

Every method call compiles under one of exactly two rules, fixed at compile time as a property of the call site:

  1. Static — the call site names exactly one concrete type. The call binds directly to that type’s member, no table involved:
    • a concrete receiver (c.area() on c: Circle);
    • an interface-typed local whose single concrete origin the compiler tracked (let s: Area = Point { .. }; s.area());
    • an interface-typed parameter — the function specializes per concrete argument at monomorphization, so an interface parameter is effectively an implicit generic bound;
    • inside monomorphized generics.
  2. Itable — the receiver is interface-typed with multiple possible concrete origins; the call consults the value’s itable — the per-(concrete type × interface) method table:
    • elements of a heterogeneous container (Vec<Area>);
    • interface-typed field and element loads (the cell may hold any satisfier);
    • branch-merged bindings (if arms carrying different concretes into one interface-typed variable).

The itable rows are synthesized at the boxing sites — the same boundary checks that proved satisfaction fill the rows. The origin analysis is conservative: any merge, indirection, or cross-function flow counts as multiple. Mis-analysis cannot produce wrong code — an uncertain origin costs one itable hop, never a wrong static bind. And the same descriptor that answers itable calls answers is probes: one runtime truth per value.

Type tests

expr is Type yields a bool and is total — it never traps. Two probes, one keyword:

  • Concrete RHS: is the value’s exact type T? (No inheritance — a single id compare.)
  • Interface RHS: does the value’s concrete type have itable fills for the interface — i.e. was it satisfaction-boxed somewhere? A capability probe, usable on any value (k is Encodable).

is has no flow-sensitive effects: a true probe does not narrow x. When the static type already answers — on an exact receiver the member set decides at compile time — the probe folds to a constant. Interface-typed values cannot be downcast to a concrete type at all — if you need Circle-specific behavior behind an Area, put that member on the interface. The one recovery path for erased values is the explicit opaque box (see the reference on opaque).

Visibility: the use-both gate

Calling an interface’s member requires both names in scope: the type (by declaration or use) and the interface (use). Inherent members need only the type. A call through an interface no use brings in is an error — “use I to call its methods on T” — so a foreign interface can never silently change what a call site means. The gate is diagnostic-level: it governs which calls a module may spell, never what a type can do (scope changes spelling, never meaning).

The iteration protocol

A type is iterable when an inherent impl marks a member [iterable] (the bracket marker — the contract’s shape is fn <free>(self, emit: fn(E) -> bool), the element falling out of the marked member’s own signature):

use ink::{ Logger };

class CountUp {
    n: i32;
}

impl CountUp {
    [iterable] pub fn iterate(self, emit: fn(i32) -> bool) {
        for (let mut i = 1; i <= self.n; i += 1) {
            if (!emit(i)) { return; }
        }
    }
}

entry fn main() {
    let log = Logger("iter");
    for (let v of CountUp { n: 3 }) {
        log.info(f"tick {v}");
    }
    log.info("done");
}
tick 1
tick 2
tick 3
done

for (let v of it) { body } desugars to it.<member>(emit) with a synthetic closure: the body runs, then emit returns true; break returns false. The loop variable is ONE variable reassigned per iteration — the same law the fused index loops follow (the capture law treats the two forms identically; see functions, closures, and generics). The builtin sequences ([T], str, bytes, and the standard growable Vec) keep fused index loops instead; they never pay a per-element call.

Engine contracts are not interfaces

The engine’s own contracts stand alone — no polymorphism machinery, no member-set checks: the bracket markers [disposal], [iterable], and [constructor] designate inherent impl members (one per contract per class, the signature checked against the contract — [disposal] and [iterable] dispatched through a designated slot, never an itable lookup; [constructor] bound at the call form Type(..), byte-identical to the member call), and the async protocol lives on two CLOSED builtin class rows, Future<T> and RunContext. The closure IS the wall: futures and cx records are engine-minted only, so a user type cannot BE one — the member-set law cannot see engine identity, and nominal closure is the only spelling of “engine-minted only”. See the async model, interfaces, and the Rc heap.

Equality is not an interface

== is builtin and cannot be opted into or out of: primitives compare by value, str/bytes by content, everything else by cell identity. Field-wise comparison is a loop you write, or the map packages’ own key rules. See everything is a value.

What this buys you

  • Structural satisfaction keeps the surface small: one mechanism (the member set), one checking moment (the boundary), no registry to reason about — a type’s capability is readable off its own impl.
  • The two-rule law makes dispatch predictable: you can tell, per call site, whether you are paying a hop.
  • The boundary check keeps costs local: satisfaction is proved where the value crosses, the itable row is filled right there, and nothing anywhere else in the program can change either.

The async model

rut’s concurrency is pull-based, built on one noun: Future<T> — a closed builtin class, engine-minted only. Calling an async fn (or evaluating an async { } block) runs nothing — it produces a cold future. The future runs when something drives it: an await inside another async body, or a launch into the VM’s queue. There are no promises, no microtask queue, and no implicit scheduling: the host owns time, and nothing runs unless the driving loop runs it.

Pull, not push

push (promises)pull (rut futures)
createdstarts on the next microtaskcold — nothing runs until awaited or launched
idle costreactions and queues exist whether or not anyone waitsnobody drives ⇒ nobody pays
per-await allocationpromise + callback listsone hidden frame record per call
cancellationabort flags layered on topnative: the frame is dropped at a checkpoint
host integrationthe host must drain a job queuethe host polls: drain ready frames, ask for the next deadline

The surface

use futures::{ launch_future, sleep };
use ink::{ Logger };

async fn countdown(log: Logger, n: u32) -> nil {
    for (let mut i = n; i > 0; i -= 1) {
        log.info(f"{i}");
        await sleep(1000);             // the only suspension spelling
    }
}

entry fn main() -> nil {
    let log = Logger("countdown");
    launch_future(countdown(log, 3));  // the other consume: launch
}
3
2
1

The rules:

  • The context is injected, never spelled. The weave binds cx (a RunContext) in every async body; an async fn’s parameters are ordinary values. It carries the frame edge: checkpoint() reads the resume state, cancelled() reads the frame’s abort flag. The RunContext class is core’s, import-gated (use core::{ RunContext }) — the weave itself never needs the import, only source that names the class does.
  • Calling does not run. async fn f(..) -> T answers a Future<T>; it runs when awaited or launched. async fn is sugar — fn f(..) -> Future<T> { return async { .. }; } is the same program, because the async { } block is the primitive: one expression form that mints the frame where it stands (legal in sync code — the mint is pure), its return answering the future, its reads capturing the enclosing locals by value.
  • One consume law. A future is consumed by await or by launch_future — exactly one. The launch returns its own receipt type, which is not a future and cannot be launched or awaited again.
  • Every producer has one type. An async fn call, an async block, sleep, the race/completer mints — all Future<..>, so await never asks “which kind”. The walls hold by nominal closure: no constructor, no impl lane — a user type cannot BE a future (which is how the standard sleep itself is minted: engine-side, sealed under the class spelling).

What the compiler emits

An async producer compiles to one hidden frame — an ordinary heap cell — with a woven yield that the driving loop calls once per resumption (the Future<T> class’s designated slot — the engine ABI, unspelled):

frame:  [0]=state      the checkpoint enum's member — the pc
        [1]=cancelled  the frame's abort flag
        [2]=awaiter    the frame awaiting THIS one
        [3]=pending    the future THIS one parks on
        [4..]=locals   every binding, mirrored into the frame

entry:      dispatch on state
per await:  probe the parked future's state
              done    -> resume with its value
              pending -> link awaiter/pending edges, park, return
resume arm: cancelled-probe -> drop path | restore locals -> continue

The state field is the program counter: resume dispatch is a jump table over the checkpoint enum. Because locals are mirrored into the frame cell, parking releases only staging registers and no liveness analysis decides which locals survive a suspension. The whole weave rides existing bytecode — no new opcodes, no new runtime machinery.

Cancellation is drop

handle.abort() flags the frame’s cancellation and re-enqueues it. The probe at its next checkpoint branches to the drop path: locals release in reverse binding order, [disposal] members run at refcount zero, and any pending sleep dies with the frame. Cancellation never interrupts mid-expression — the checkpoint probe is the only place a cancellation becomes observable, so a cancelled function dies at a known-clean boundary. This is the same machinery that frees any heap object (see memory); coroutine frames get no special case.

The driving loop

The VM owns the queues; the embedder owns the loop:

vm.call::<_, ()>("main", ())?;              // script boots, launches futures
loop {
    vm.run_ready()?;                        // one drive per ready frame
    if let Some(d) = vm.next_deadline() {   // expire due timers into ready
        sleep_until(d);                     // the wall-clock stand-in
    }
    if vm.pending_tasks() == 0 { break; }   // idle
}
  • sleep(ms) arms a deadline on the VM’s virtual clock (vm.now_ms() / vm.set_now()). A test host advances the clock by hand and gets fully deterministic schedules — a UI host just maps it to wall time.
  • Each queue entry owns one reference; a completed drive re-enqueues the awaiting frame through a one-directional edge pair, so wake wiring never forms a cycle.
  • Fuel accounting rides the ordinary per-op budget: a drive that runs out parks the frame at its checkpoint and resumes there later.

Host futures: pub host async fn

Native code joins the same model. A declaration file spells the row:

pub host async fn http_send(c: opaque, method: str, url: str,
                            headers: str, body: bytes) -> opaque;
pub host async fn http_stream_next(s: opaque) -> ?bytes;

and the embedder binds it with one closure that starts the work and returns the future’s state cell:

rut_vm::register_async!(hosts, "http_host::stream::http_stream_next",
    (Opaque<HttpStream>,) -> Option<Vec<u8>>,
    move |s: Opaque<HttpStream>| -> Completer<Option<Vec<u8>>> {
        let c = Completer::new();
        let w = c.clone();
        std::thread::spawn(move || {
            w.complete(read_chunk(s));     // settle from any thread
        });
        c
    });

Completer<T> is a small shared cell: complete(v)/fail(msg) are callable from any thread (atomics plus a mutex — the VM stays single-threaded), fail’s message becomes the trap at the await, and an optional abort closure runs when the script cancels a pending future (late results are then simply discarded). The macro registers the whole row family the weave drives — start, probe, take, cancel — and the load-time check verifies the expansion against the declaration, so a decl and its bodies cannot drift apart. IO written with plain async/await Rust maps onto this naturally: the work leaves the VM, and completion is one enqueue back into the ready queue.

Structured concurrency, honestly

The language today keeps the core vocabulary deliberately small: launch, abort, and await. Racing (select2 / select_all) and the manually resolvable future (completer<T>()) are stdlib surface over the same engine rows — the losers of a race are cancelled through the ordinary abort path. Joining a launched future (await handle) parses but is compile-gated, and structured scopes (a block that cancels its children on exit) are the same story. What exists now is already enough to structure real programs — the launch/abort receipt gives you explicit ownership of background work, and drop-based cancellation gives it a clean off switch — but nothing in the model silently cancels siblings on your behalf. See the reference on async and await, launched futures, and the host futures bridge; the GitHub viewer CLI example shows a full program living inside this loop.

Memory: the Rc heap, weak refs, and cycles

rut’s memory management is reference counting with deterministic destructors and no collector. An object is destroyed the moment its last strong reference goes away — at a knowable statement, not “at some future GC”. The cost is honesty about cycles: a strong cycle never reaches zero, so it lives until the VM is torn down. rut makes that a stated rule and ships Weak<T> as the first-class answer, instead of hiding it behind a collector.

Everything is a cell

Every non-primitive value — strings, byte buffers, arrays, records, enums, interface objects, erasure boxes, nullable boxes, coroutine frames — is a heap cell. Each cell starts with a header: a refcount, a type id, and a few flags. The counts are plain integers: a VM runs on one thread with one heap and nothing is ever shared, so there are no atomics anywhere in the heap.

Because assignments and passes copy handles, not payloads, the refcount traffic is exactly the aliasing the program performs:

use ink::{ Logger };

struct Node { next: ?Node }

entry fn main() {
    let log = Logger("cells");
    let a: ?Node = Node { next: nil };
    let b = a;              // one retain
    log.info(f"a == b: {a == b}");   // one cell — it dies when the LAST of a, b goes away
}
a == b: true

The compiler knows every register’s static type, so it emits ref-aware moves only where references flow; scalar code pays nothing. Function boundaries do the paired inc/dec; a flat primitive buffer’s element traffic is plain slot moves.

Deterministic destruction

When a count reaches zero, destruction runs in a fixed order:

  1. Weak boxes null first, then the [disposal] member. A type carrying a [disposal]-marked member gets it called — (mut self, cx: DisposalContext), the engine minting the cx — the engine pins the dying cell, queues the call, and the interpreter drains the queue at call boundaries. One marked member per class; use core::{ DisposalContext } brings the cx type in. Fields release after the body returns.
  2. Fields release in declaration order, recursively — a dying record’s strings, arrays, and boxes release their own references, so nothing is pinned until VM shutdown just because its owner died.
  3. Host opaques run their Rust Drop at the same point. A host handle registered by the embedder releases its socket, texture, or thread when the last script reference disappears — never “someday at GC” (see the host boundary).
use core::{ DisposalContext };
use ink::{ Logger };

class Connection {
    url: str;
    log: Logger;
}

impl Connection {
    fn open(url: str, log: Logger) -> Connection {
        return Connection { url: url, log: log };
    }
}

impl Connection {
    [disposal] fn close(mut self, cx: DisposalContext) {
        self.log.info(f"closed {self.url}");
    }
}

entry fn main() {
    let log = Logger("rc");
    let conn = Connection::open("tcp://edge", log);
    log.info("main is done — the count hits zero at the boundary");
}
main is done — the count hits zero at the boundary
closed tcp://edge

Compare this with finalizer-based designs: there is no finalizer that “may run later or never”, no flush phase, and no resource whose release time you cannot point at in your own code.

Two edge rules worth knowing:

  • Refcount overflow pins. If a counter would exceed its maximum, the object is deliberately immortalized (and logged) rather than wrapping — the same rule Swift uses.
  • Weak boxes null first. When a cell with weak watchers dies, every Weak box to it is nulled before any user code runs — a dispose body that calls upgrade() sees nil, deterministically.

Weak references

Weak::new(v) mints a Weak<T> over v’s cell that never keeps anything alive; w.upgrade() answers ?T — the retained referent, or nil once it died. Construction is the class-method form, admission is checked (reference types only — Weak<i32> diagnoses), and Weak::new(nil) traps. The name is import-gated — spell use core::{ Weak };, or the bare Weak diagnoses `Weak` is not in scope — `use core::{ Weak }`.

use core::{ Weak };
use ink::{ Logger };

class Model {
    name: str;
}

class View {
    model: ?Model;
    observer: ?Weak<Model>;      // a back-pointer that closes no cycle
}

entry fn main() {
    let log = Logger("rc");
    let mut m = Model { name: "doc" };
    let v = View { model: nil, observer: Weak::new(m) };   // observe without owning
    log.info(f"holding {m.name}; the view holds only a weak edge");
    m = Model { name: "next" };   // the old cell's last strong reference dies here
    log.info(f"upgrade() answers nil: {v.observer.upgrade() == nil}");
}
holding doc; the view holds only a weak edge
upgrade() answers nil: true

The two shapes that cause accidental cycles — back-pointers (child → parent) and caches (a table that should not extend lifetimes) — are exactly what Weak is for. A path through a Weak does not close a strong cycle.

The cycle policy

A strong cycle is a leak — deterministically. Its members live until the VM is dropped; no collector ever runs, no pass interrupts execution, and destructor ordering never surprises you. Guidance is lint-level, not runtime:

  • resource-holding types (types with [disposal] members or host handles) must not participate in strong cycles;
  • parent/child and observer shapes take Weak back-pointers;
  • pure-data cycles are harmless — they cost only memory.

You are not left alone with the rule: debug builds assert refcount discipline (retain/release pairing, no underflow, no double free), and at teardown the VM emits a leak report — surviving objects grouped by type with allocation sites — which is the primary tool for hunting accidental cycles. Behavior is fully deterministic, so a leak reproduces exactly.

The self-managed heap

Host code may use std freely, but every byte backing a rut value is allocated through the VM’s own heap manager. The discipline is the point, not the allocator:

  • Cells come from fixed-size arena chunks with freelists; a dead slot is reused by the next mint.
  • Variable-size payloads (string octets, array element runs) live in size-classed blocks that never move; in-place geometric growth keeps append loops linear, and freelists recycle the common sizes.
  • Immortal singletons — interned string literals, enum variants — live in a slab freed only at VM drop, carrying the “no refcount” sentinel.
  • Nothing compacts. The heap never moves cells, which is precisely what lets the boundary hand Rust zero-copy views into buffers (see the host boundary).

Why self-manage instead of using the host’s allocator?

  1. Budgets. An embedder can say “this script gets N bytes” and get a clean, resumable out-of-memory trap instead of an OS abort. vm.heap_usage() is exact because every allocation is accounted.
  2. Teardown. Vm::drop frees the whole heap in slab units after the leak report; nothing per-object leaks past the VM — important for wasm pages and plugin hosts that spawn and kill scripts.
  3. Leak reporting walks the VM’s own headers, which requires the VM’s own headers everywhere.

The budget check runs before any write — a failed allocation leaves the heap byte-identical — and traps resumably: raise the limit and continue, or drop references and retry. See the reference on resource limits for the full knob set, and the bytecode VM for how budgets interleave with execution.

What this buys you

  • Deterministic resource release — the property the whole design is organized around. If your script opened something, the closing statement is knowable.
  • No pauses. There is no collection pass; destruction happens inline at release-to-zero, so nothing ever interrupts a frame.
  • A small, honest mental model. Sharing is by reference, copies are built explicitly (see everything is a value), lifetimes are refcounts, and the one thing refcounts cannot do — cycles — is a documented rule with a first-class tool.

The host boundary

rut exists to be embedded. The host — a Rust program — owns a VM, declares its API once in rut source, binds the implementations with typed Rust closures, and drives everything. The design rule for the whole boundary: the type system does the checking, not your bridge code. There is no argument re-parsing, no as number, no “trust-me” coercion — a value crossing either direction is checked against a reified runtime type, and a mismatch is a loud error naming both sides.

The embedding model

// the surface offers as a pkg — a .d.rut lowered to host rows
let gfx = rut_driver::Pkg::decl("app:gfx", GFX_DECL);

// the raw lane: bind the bodies on a bare registry, full `scope::name`
// strings (the HostPkg/pkg_fn! builder lane is [host fns](../reference/host-fns.md))
let mut hosts = HostRegistry::new();
hosts.register::<_, (i32, i32), Opaque<Canvas>, _>(
    "app:gfx::newCanvas",
    |_vm, w: i32, h: i32| Ok(Canvas::new(w, h)),
);

// one chain composes and compiles; the boot join (at .build()) proves
// every declared row the world mounts has a binding — BEFORE any
// script runs. `verify_against` checks both directions, now.
hosts.verify_against(&rut_driver::declared_host_fns(&[gfx.clone()]))?;

let compiled = rut_driver::RutRun::new()
    .pkg(gfx)
    .entrypoint("app")
    .compile()?;

let mut vm = Vm::builder().compiled(compiled).limits(limits).hosts(hosts).build()?;
vm.call::<_, ()>("main", ())?;      // an entry point
vm.run_ready()?;                    // drive async work to idle

The declaration file (a host package) spells the surface in rut:

pub host fn newCanvas(w: i32, h: i32) -> opaque;
pub host fn circle(h: opaque, x: f32, y: f32, r: f32) -> nil;

and the load-time join rejects three wiring bugs as panics — an embedder mistake, never a script diagnostic: a declared row with no binding, a binding with no declaration, and signature drift. “Offer what you bind”: an embedder that offers a package declares its rows and must bind them.

The crossing set

What may cross is a compile-time property of the surface, not a runtime negotiation:

  • Parameters: the primitives, str, bytes, and opaque.
  • Returns: the same set plus the answer optionals ?str, ?bytes, ?opaque — Option<String>, Option<Vec<u8>>, and the opaque handles mint the nullable box, with None as the flat nil.
  • Tuples cross field by field, which makes the error convention — (value, err) — a first-class entry answer. The two channels stay distinct by law: a returned err is data the host reads and acts on; a panic is drift and arrives on the trap channel, never filling an err field.

Everything else — user structs and classes, Vecs, interface-typed values, closures — stays inside the VM. A declaration that violates the set is a compile error at the declaration, not a failed call at 2 a.m. A polymorphic crossing seals its value in an erasure box (opaque(v) at the call, opaque::downcast<T> after), checked, never silent — see reified types.

The currency is typed Rust

On the Rust side the boundary speaks ordinary Rust types. Each type declares the rut type it binds against and converts checked:

  • Borrow, don’t copy. &str and &[u8] parameters read the VM’s buffers zero-copy. The borrow is call-scoped — the type system makes smuggling it past the return a compile error.
  • Copy on purpose. Owned String/Vec<u8> parameters are the explicit “I keep this data” choice.
  • Opaque<T> is the typed view of a host handle: an 8-byte store handle the host holds and passes back; the payload stays host-owned (Box<dyn Any> plus an optional finalize hook).

Borrow guards make the zero-copy views safe while script runs: a borrowed object is flagged, and script-side mutation through a re-entrant call traps with borrowed by host instead of racing. Guards clear on return. This is sound forever because the heap never moves objects (see memory).

Wrapping host state: the class-in-rut pattern

There is no “host class”. Native state crosses as an opaque handle and a rut class wraps it — ordinary source the compiler can see and optimize around:

class Canvas {
    h: opaque;
    fn circle(mut self, x: f32, y: f32, r: f32) -> nil {
        canvas_circle(self.h, x, y, r);
    }
    fn hits(self) -> i32 { return canvas_hits(self.h); }
}

Every method is exactly one host call — the same crossing a magic host class would have paid — but the wrapper can also carry impl blocks, validation, and convenience the native side never needed to know about. The payoff for keeping the boundary this small: host resources die deterministically. When the wrapper’s last reference goes, the handle’s refcount hits zero and the payload’s Rust Drop runs at that point — sockets and textures close on script schedule, not at some future collection.

Host functions are rows, dispatched by slot

Each declared row gets a stable slot id at compile time; calls compile to slot dispatch, so names are binding-time labels only — renaming a Rust-side binding target fails the join instead of silently rebinding. The surface grammar is small:

host fn name(params) -> T;        // concrete signature; no generics —
                                  // a generic has no shape to check
host struct Name { fields };      // flat record of crossing fields

builtin declarations (the engine’s own fns and classes — str methods, Weak, Future) are engine surface: the embedder cannot spell them, and the engine’s contracts are the bracket markers and the closed classes — no interface machinery behind them. Async rows (pub host async fn) are declared like any row and expand into a small row family the driving loop uses — the embedder binds them with one closure per future; see the async model.

Re-entrancy, traps, budgets

  • A native fn receives a context that may call back into rut (vm.call) — nested calls run under the same budget on a fresh frame stack.
  • Native code runs outside the op budget: the host is trusted to be fast, or to hand back a future instead of blocking. A trap raised inside a native fn propagates to the host as an Err(Trap) with the native frame visible in the backtrace.
  • Traps are catchable only at the boundary — script never catches one. That is what keeps panics loud and state uncorrupted.

What was deliberately left out

No C ABI. There is no register_struct, no size_of, no pointer mirroring of record layouts: records are slot arrays internal to the VM, and a host sees them only through the checked crossing. The few bytes you give up to the checked boundary buy the property that makes embedding pleasant — every mismatch is a named, typed, load-time diagnostic instead of a runtime mystery.

The full details live in the reference: embedding and native modules, the value boundary and borrows, and host fns and declaration files.

The bytecode VM

Everything a rut program becomes is a typed bytecode executed by a register VM. There is no JIT, no interpreter tiering, no runtime speculation: the compiler does all optimization ahead of time, and what runs is exactly what was compiled. This chapter is the tour of that artifact — the instruction set, the module binary, the load-time verification, and the interpreter’s execution and budgeting model.

One struct, one thread, one heap

pub struct Vm {
    types:  TypeTable,     // runtime type descriptors + vtables
    heap:   Heap,          // the refcounted, self-managed heap
    mods:   Vec<Module>,   // linked binaries
    frames: Vec<Frame>,    // the call stack
    ready:  Deque<Slot>,   // woken async frames
    timers: BTreeMap<u64, Vec<Slot>>,  // the virtual clock's wheel
    lim:    Limits,        // fuel, heap budget, interrupt interval
    host:   HostHooks,     // registered native bodies, clock, loader
}

A VM is single-threaded by construction (!Send). The host holds one and drives it with methods: call an entry point, run_ready to drain woken frames, next_deadline for the timer wheel, drive for a single resumption. See the host boundary for the embed loop and the async model for the queues’ role in scheduling.

Typed bytecode

The instruction set is register-based: operands are u16 indices into a per-frame slot file, and every register has a static type recorded in the function’s signature. That single decision is what lets the hot path stay tag-free (see reified types) and what makes refcounting precise: the compiler emits plain moves for scalars and retain/release moves for references, with no runtime tag checks.

Ops are small and fixed-size, with variadic operand lists (call arguments, branch tables) living in per-function pools. A representative sample:

mov / movref   rD, rS        ; move; the ref form retains new, releases old
i32add, f64mul, ...          ; typed arithmetic — the opcode selects the
                             ; kind, the width rides the op
icmp, fcmp     rD, a, b      ; compares -> bool
call / callm   f, args       ; direct call / direct method call
calli          slot, recv    ; interface itable call (dynamic dispatch)
callnat        nat, args     ; internal natives (string concat, ...)
newcell / getf / setf        ; mint a record, read/write a field
arrget / arrset              ; indexing — bounds checked, trap on miss
tidof          rD, rO        ; read a value's runtime type id
brtable        rIdx, arms    ; enum matching, resume dispatch

The type system also decides what is not an op:

  • Nothing static. What the type table can answer at compile time becomes a constant — no “get type id” instruction, no length load for a fixed-size array.
  • Nothing polymorphic and nothing named. An interface-typed receiver has exactly one op (the itable call); string concatenation is a native call, not an opcode.
  • Concrete memory, control flow, and two readbacks. Ops touch memory only through compile-time-known layouts, plus the two reads reification needs: “what is it” (tidof) and the guarded payload extract behind a downcast.

The module binary

Compilation produces a versioned, self-contained binary per module: types, constants, functions (with their typed register signatures), imports, and a symbol table for backtraces. Its properties matter more than its layout:

  • Deterministic. The same sources plus the same dependency versions produce byte-identical binaries, so artifacts are cacheable by content hash and shippable instead of sources.
  • Self-describing but strippable. Names and source spans are retained for traces by default; a release build can strip them, and a sidecar map file (keyed by content hash) can restore symbolication later. See the reference on diagnostics.
  • Link-time identity. Type ids are module-local at rest and rebased into the VM’s global table at link, where the interface tables merge by name. Cross-module interface-typed calls specialize per concrete argument here too — the static-dispatch rule of interfaces and dispatch holds across module boundaries.
  • Little-endian everywhere, by law — every serialized word, so artifacts are platform-independent by construction rather than by luck.

Verification at load

Loading re-checks each function before anything executes: register operands against the signature, operand pools and jump targets in range, type operands present in the type table, native slots declared, and async state tables closed. A failed verification is a load error naming the module and function — corrupted binaries never execute. This is also where crossing rules are enforced for host-facing signatures, so a non-crossing shape is rejected before any script runs.

Module-level initialization is folded at compile time: literals, enum members, constant expressions, and interned string literals become constants in the binary. A user function call in a module initializer is a compile error — there is no load-time execution at all. Loading a module runs nothing.

The interpreter loop and traps

Execution is a decode-dispatch loop over frames. A frame is the function’s code, a program counter, its typed register file, and (for async frames) the resume state. Calls push frames; returns pop them; direct calls are an index plus jump, and interface calls are two loads plus an indirect jump through the itable.

Failure is a trap, not an exception and not a Rust panic: integer overflow on the plain operators, a nil deref, an out-of-bounds index, a panic(..), or an exhausted budget. A trap captures the raw frame chain (rendered lazily — symbolication happens only if someone prints it), runs destructors on the way out, and unwinds as an Err(Trap) to the host call. Rut code cannot catch one; the boundary is the catch point (see the host boundary).

Budgets and interrupts

Two knobs make it safe to run third-party code, both set at construction and mutable while running:

Limits { fuel: Option<u64>,            // one unit per op, counts down
         heap_limit_bytes: Option<u64>,// checked at every allocation
         interrupt_every: u32 }        // default: check every 1024 ops
  • Exhaustion is resumable: the trap parks the frame exactly where it was — the frame is the loop state — so the host can add fuel, raise the heap limit, or flip the interrupt flag and resume. A UI host yields mid-frame; a wasm page grants finite fuel; a test sets finite fuel plus a virtual clock and gets a deterministic hang proof.
  • The heap check runs before any write, so an out-of-memory failure leaves the heap byte-identical (see memory).
  • Native functions run outside the fuel budget — a hanging native is a host bug by contract — and the interrupt hook is the host’s lever at native return points.

Why no JIT is viable

A JS engine’s speed is its JIT, and the JIT exists to speculate about polymorphic property loads. rut has no polymorphic loads: field access is by known index, calls bind statically whenever the site names one concrete type, generics are monomorphized, and the remaining dynamic dispatch is an honest checked vtable hop. The optimizer’s currency is type stability — what the checker proves is everything the optimizer gets — and its passes (constant folding, inlining, monomorphization, register-level cleanup) all run ahead of time. The result is a runtime with no warmup curve, no deoptimization asymmetries, and per-op costs you can reason about from the bytecode alone.

The full tables and laws live in the reference: typed bytecode, the module binary and verification, VM core, and resource limits and fuel.

Examples index

The repo ships two kinds of example material. The examples/ directory holds six runnable Cargo projects (five console programs and one browser page) plus one parse-only corpus example. Alongside them, demo/src/examples/ holds the playground classics — short, self-contained programs the web playground runs in the browser, the same programs the repo’s gates compile and run in CI. Each project has its own page in this chapter; the classics share The playground corpus.

ProjectRunWhat it demonstrates
00 — Todolistcargo run -p todolistan entry fn surface over a rut class — the host drives CRUD through opaque handles
01 — Sortcargo run -p sortfive sorting algorithms behind one dispatcher entry; when on strings, the mut-binding law, fuel budgets
02 — Digestcargo run -p digestsbyte-level codecs and hashes (MD5/SHA/base64/CRC/FNV); the host as an independent test oracle
03 — Plugincargo run -p plugina module directory + .rutbundle chat-moderator plugin; re-entrant vm.call, both opaque directions
04 — Custom asyncparse-only — no runnable harnessa user launcher re-spelled over the closed Future surface (no user type can BE a future) with per-checkpoint stats and cancellation audits
05 — Todolist webcargo test -p todolist-web + node tests/e2e-browser.mjsa full page app whose brain is a two-package rut project — ten DOM/timer crossings over web_sys on wasm32
06 — GitHub viewer CLIcargo run -p rgh -- --repo=… --ref=… listrgh — an async rut brain over the std http lane; headers-then-stream downloads, fixture-lane tests
The playground corpuscd demo && npm run smokethe classics: runnable programs, compiled and run by two gates

All Cargo commands run from the repository root. The runnable crates share one run pattern — compile the module, verify the binary, bind host fns, then drive it through typed vm.call sites — so the pages cross-link often: 00 — Todolist establishes the pattern and 06 — GitHub viewer CLI stretches it the farthest.

The two dependency tables

Every package carries a rut.jsonc manifest (see Project structure and rut.jsonc), and a manifest relates a package to other packages through two tables, all visible in the examples:

  • deps — the transitively mounted dependencies, and the declaration table: a pkg may use exactly the heads its own manifest names. The common case: 03-plugin’s plugin/rut.jsonc declares server = { path = "../server" }, and 05 — Todolist web’s biz package declares ui (which itself pulls the collection packages). The std json package shows the wrapper shape — its Vec/map serialization wrappers are json’s OWN source, and the container packages are plain deps riding along transitively.
  • dev-deps — mounted only while building the package itself, never in a consumer’s world; the rows are path-only.

There is no third table: the grammar is strict at the top level, so a retired key (peer-deps) or flag (inline) refuses as the unknown key it now is, naming the key.

The full rules — the declaration-scoped nameability law, the closed bundle closure, and what bundle format the packer emits — are on Dependency kinds.

Reading order

New to the language: read 00 — Todolist and 01 — Sort for the embedding shape, then The playground corpus for the language surface in small doses. For the web story, 05 — Todolist web is the centerpiece and 06 — GitHub viewer CLI is the networking counterpart. 03 — Plugin is the one to study for packaging and module loading, and 04 — Custom async for what the future protocol looks like from user code.

00 — Todolist

The first runnable host example, and the template for the rest of the chapter: a Rust program embeds rut, compiles a rut library (there is no main in it), and drives the library through its entry fn surface. The split is two sides — mod.rut (the rut module) owns the data and the logic as a TodoList class with full CRUD; src/main.rs owns the run: compile, verify, then a scripted conversation of vm.calls. The one-sentence design rule: the host owns the run, rut owns the data.

Run it

cargo run -p todolist        # from the repo root
cargo test -p todolist       # the same run asserted as a test

The run prints an abridged transcript like this:

added: #1, #2, #3
set_done(#2, true)
title_of(#2) = Opt(Some(Str("implement the VM")))
title_of(42) = Opt(None)
remove(#1) = Res(Ok(Bool(true)))
remove(#1) again = Res(Err(Str("no todo #1")))
TodoList[2]
  #2 [x] implement the VM
  #3 [ ] ship the demo
second list #1: 0 todos
fuel used: 680 of Some(1000000)

Code tour

The data: a class with a fields-only body

examples/00-todolist/mod.rut — the type body is fields only; methods live in an inherent impl block (Structs, Classes and constructors). Unannotated members are module-private. The block below is the class verbatim — new, add, and remove — closed with a main so it runs on its own; the example file itself has no main — it is a library the host drives through its entry fn surface:

use ink::{ Logger };
use pouch::{ Vec };

struct Todo {
    id: i32;
    title: str;
    done: bool = false;      // field initializer — `done` may be omitted
}

pub class TodoList {
    items: Vec<Todo>;         // unannotated members = module-private
    next_id: i32;
}

impl TodoList {
    pub fn new() -> Self {
        return Self { items: Vec::new(), next_id: 1 };
    }

    // ---- CREATE ----

    pub fn add(mut self, title: str) -> i32 {
        let id = self.next_id;
        self.items.push(Todo { id: id, title: title });
        self.next_id += 1;
        return id;
    }

    // ---- DELETE ----

    pub fn remove(mut self, id: i32) -> bool {
        let kept: Vec<Todo> = Vec::new();
        let mut removed = false;
        for (let t of self.items) {
            when (t.id == id) {
                true -> { removed = true; },   // drop the row
                else -> { kept.push(t); },     // keep everything else
            }
        }
        if (removed) {
            self.items = kept;
        }
        return removed;
    }
}

entry fn main() {
    let log = Logger("todos");
    let mut list = TodoList::new();
    list.add("implement the VM");
    list.add("ship the demo");
    let first = list.remove(1);
    let second = list.remove(1);
    log.info(f"remove(#1) = {first}, again = {second}, left: {list.items.len()}");
}
remove(#1) = true, again = false, left: 1

Note mut self: writing through a class handle requires a mut binding head, the same law 01 — Sort exercises on plain vecs — add and remove both declare it. remove filters through a when: the matching row is dropped, everything else is kept, and the list is rewritten only if something was actually removed. The read side (not shown) is ordinary code — len, title_of (which returns "" for a miss; the example pairs it with has_title because there is no ?. sugar), and a render built from f-strings.

The handle: one opaque box around the world

Instances of TodoList can never cross into Rust — the crossing set admits primitives, str, bytes, and opaque only, and entry fn signatures are checked against that rule at compile time (see the host boundary). So the library boxes its whole container once and the host holds the handle:

struct Lists {
    lists: Vec<TodoList>;    // handle = index; handles stay stable while held
}

fn at(c: opaque, h: u32) -> TodoList {
    let lists = opaque::downcast<?Lists>(c);
    return lists.lists[h as i32];
}

entry fn createContainer() -> opaque {
    let ls: ?Lists = Lists { lists: Vec::new() };
    return opaque(ls);
}

entry fn create(c: opaque) -> u32 {
    let k = opaque::downcast<?Lists>(c);
    k.lists.push(TodoList::new());
    return (k.lists.len() - 1) as u32;
}

Two things to take away. First, entry fn marks the host-callable surface — distinct from pub, which is use-visibility for other rut modules and carries no crossing limits (Modules and visibility). Second, erasure is the opaque(v) type-call and recovery is opaque::downcast<T>(o) -> ?T — a wrong box answers nil, never a trap (opaque — erasure and downcast). The internal helper at is an ordinary fn and may speak in full types.

The embedder: typed calls, budgets, and honest errors

examples/00-todolist/src/main.rs mounts core and the pouch package (for Vec), compiles in one call, verifies the binary, and then talks to the module through typed closures:

let c: rut_vm::OpaqueRef = vm.call("createContainer", ()).unwrap();
let list: u32 = vm.call("create", (c.clone(),)).unwrap();

let mut add = |title: &str| -> i32 {
    vm.call::<_, i32>("add", (c.clone(), list, title)).unwrap()
};
let vmf = add("implement the VM");
let demo = add("ship the demo");

The run executes under explicit budgets — fuel and a heap limit — so a runaway module fails loudly instead of hanging the host (Resource limits and fuel):

let limits = rut_vm::interp::Limits {
    fuel: Some(1_000_000),
    heap_limit_bytes: Some(4 * 1024 * 1024),
    interrupt_every: 1024,
};

And the transcript’s remove(#1) again = Res(Err(...)) line is the VM’s typed view of a bool answer — the second remove returns false, and the debug print shows the value shape the crossing produces (Value boundary and borrows).

Takeaways

  • entry fn is the host-callable surface; its signatures are checked against the crossing rule at compile time, so a bad plan is a diagnostic, never a call-time surprise.
  • State lives rut-side in one opaque container the host holds and re-passes; plain values cross, instances never do.
  • Erasure is opaque(v); recovery is opaque::downcast<T> -> ?T.
  • Budgets (fuel + heap) are the embedder’s call, and every embedder mistake comes back as a named trap.
  • The same file works as a library: entries are compilation roots, so a module with no main still emits every entry.

Next: 01 — Sort scales the pattern to five algorithms and shows what recursion costs in fuel. The crossing rules behind this page are in the host boundary.

01 — Sort

The second runnable host example, in the shape of 00 — Todolist: five sorting algorithms in rut — insertion, bubble, and selection (loop-shaped), plus quicksort and merge sort (recursion, in-place vs. out-of-place) — driven from Rust through one entry fn dispatcher. Where 00 is about the boundary, this one is about the language: recursion, when on strings, the mut-binding law, wrapping arithmetic, and visible fuel budgets.

Run it

cargo run -p sort          # from the repo root
cargo test -p sort         # every algorithm, edge cases, cross-agreement

The run sorts a hand-picked input, then fills the bank with a deterministic pseudo-random vector and runs the full sweep, printing fuel per algorithm:

pushed: [5, 2, 9, 2]
after insertion: [2, 2, 5, 9]
fill(16, seed=42), each algorithm:
  insertion true  fuel   2335  [208, 320, 353, ..., 854, 893]
  bubble    true  fuel   3895  [208, 320, 353, ..., 854, 893]
  selection true  fuel   3353  [208, 320, 353, ..., 854, 893]
  quick     true  fuel   2241  [208, 320, 353, ..., 854, 893]
  merge     true  fuel   4358  [208, 320, 353, ..., 854, 893]
sort(bogus) = Res(Err(Str("unknown algorithm: bogus")))
fuel used: 21142 of Some(5000000)

The fuel column is the demo’s quiet joke: quick < insertion < selection < bubble, exactly as the textbooks promise — and the VM counts it for you.

Code tour

One opaque bank; the data never leaves rut

Vec<i32> cannot cross the host boundary, so create() boxes a Bank in an opaque and the host holds the handle — the 00 — Todolist pattern again. Results come back three ways, all crossing-shaped. serialize below is verbatim, plus a main that boxes a small bank the way create() does, so the block runs on its own:

use ink::{ Logger };
use pouch::{ Vec };

struct Bank {
    data: ?Vec<i32>;
}

entry fn serialize(c: opaque) -> str {
    let b = opaque::downcast<?Bank>(c);
    let xs = b.data;
    let mut out = "[";
    for (let mut i = 0; i < xs.len(); i += 1) {
        if (i > 0) {
            out = f"{out}, ";
        }
        out = f"{out}{xs[i]}";
    }
    return f"{out}]";
}

entry fn main() {
    let log = Logger("sort");
    let bank: ?Bank = Bank { data: Vec<i32>::from([5, 2, 9, 2]) };
    let c = opaque(bank);
    log.info(f"serialized: {serialize(c)}");
}
serialized: [5, 2, 9, 2]

serialize is the workhorse: a whole result crosses as one JSON array string, so the host asserts an entire sort in one compare. get(c, i) / has(c, i) read element-by-element, and is_sorted(c) returns the verdict.

The dispatcher: when on strings, errors as values

Every algorithm sits behind a single string-keyed entry. Unknown names are an ordinary value, not a trap — the empty string means success:

entry fn sort(c: opaque, algo: str) -> str {
    let b = opaque::downcast<?Bank>(c);
    let mut unknown = false;
    when (algo) {
        "insertion" -> { insertion_sort(b.data); },
        "bubble"    -> { bubble_sort(b.data); },
        "selection" -> { selection_sort(b.data); },
        "quick"     -> { quicksort(b.data, 0, b.data.len() - 1); },
        "merge"     -> { merge_sort(b.data); },
        else        -> { unknown = true; },
    }
    if (unknown) {
        return f"unknown algorithm: {algo}";
    }
    return "";
}

when with string-literal arms is the general dispatch idiom — see Control flow and when.

Deterministic input in one call

fill replaces the bank with n pseudo-random values from a linear-congruential generator, so sizing a benchmark input is one host round-trip, not one per element. The u32 math must wrap, and rut makes that explicit — plain * traps on overflow. The entry is verbatim (the Bank inlined so the block compiles alone), with a main that fills and prints what one call produces:

use ink::{ Logger };
use pouch::{ Vec };

struct Bank { data: ?Vec<i32>; }   // inlined from above — the block runs alone

entry fn fill(c: opaque, n: u32, seed: u32) {
    let mut b = opaque::downcast<?Bank>(c);
    let fresh: Vec<i32> = Vec::new();
    let mut x = seed | 1;         // the LCG needs an odd state
    for (let mut i = 0; i < n as i32; i += 1) {
        x = (x.wrapping_mul(1664525)).wrapping_add(1013904223);
        fresh.push((x % 1000) as i32);
    }
    b.data = fresh;
}

entry fn main() {
    let log = Logger("sort");
    let bank: ?Bank = Bank { data: nil };
    let c = opaque(bank);
    fill(c, 8, 42);
    let b = opaque::downcast<?Bank>(c);
    let xs = b.data;
    let mut out = "";
    for (let x of xs) {
        out = f"{out} {x}";
    }
    log.info(f"fill(8, seed=42):{out}");
}
fill(8, seed=42): 798 893 208 375 746 353 452 555

The wrapping family (wrapping_mul, wrapping_add, wrapping_shl) is the honest spelling of two’s-complement arithmetic — the playground corpus has a whole checked-arith case on the contrast.

Recursion under fuel

Quicksort partitions in place; merge sort builds out-of-place halves and merges back through the shared handle. Both are plain recursive fns — the call-frame stack is the VM’s, counted by the same fuel budget (the bytecode VM):

fn quicksort(mut xs: ?Vec<i32>, lo: i32, hi: i32) {
    if (lo >= hi) {
        return;
    }
    let p = partition(xs, lo, hi);
    quicksort(xs, lo, p - 1);
    quicksort(xs, p + 1, hi);
}

Note the mut xs parameter heads: vecs are handles, so an in-place swap inside a call is shared with the bank — but writing through the handle requires the mut binding head, while mere reads (and push) do not. That asymmetry is the mut-binding law, and every algorithm in this file declares it (Modules and visibility).

The embedder’s sweep

src/main.rs drives the sweep and prints the fuel deltas, which is how the table above gets its numbers:

println!("fill(16, seed=42), each algorithm:");
for algo in ["insertion", "bubble", "selection", "quick", "merge"] {
    vm.call::<_, ()>("fill", (c.clone(), 16u32, 42u32)).unwrap();
    let before = vm.fuel_used;
    vm.call::<_, String>("sort", (c.clone(), algo)).unwrap();
    let sorted: bool = vm.call("is_sorted", (c.clone(),)).unwrap();
    println!("  {algo:<9} {sorted}  fuel {:>6}  {}", vm.fuel_used - before, ser(&mut vm));
}

Takeaways

  • Same host pattern as 00 — Todolist, one entry richer: a single string-keyed dispatcher keeps the entry fn surface small.
  • Vec<T> never crosses; a serialized JSON array makes a whole result one host-side compare.
  • Errors are values: an unknown algorithm comes back as a string, not a trap.
  • mut on a binding is a capability law, not a suggestion — and the wrapping arithmetic family is explicit about overflow.
  • Fuel budgets make algorithmic differences visible from the host, for free.

Deep-dives: the bytecode VM explains what a unit of fuel counts; 02 — Digest takes the same run shape to the byte level.

02 — Digest

The byte-level example, in the shape of 00 — Todolist and 01 — Sort — with a twist: this time the embedder is also the oracle. mod.rut is a byte-level library written in pure rut:

  • encodings — hex (encode/decode, case-insensitive) and base64 (standard + URL-safe alphabets, padding, invalid-input rejection)
  • crypto digests — MD5, SHA-1, SHA-256, SHA-512 behind one when-on-string dispatcher
  • hashmap hash keys — CRC-32, FNV-1a 32/64, djb2, sdbm
  • JSON — decode to an opaque tree, encode back, round-trip, with numbers stored as verbatim lexemes so round-trips are exact

Nothing in the rut file trusts itself: the Rust host cross-checks every algorithm against independent crates (the RustCrypto hash family, base64, crc32fast, serde_json) on canonical test vectors and on deterministic pseudo-random inputs at every padding-edge length, plus a 64 KiB stress blob. mod.rut knows nothing about the crates; only the host compares.

Run it

cargo run -p digests       # from the repo root
cargo test -p digests      # the oracle, asserted

The run prints one verified row per check — abridged:

hex([114, 117, 116, 33]) = 72757421
b64([102, 111, 111, 98, 97, 114], url=false) = Zm9vYmFy  OK
digests, rut vs crates:
  md5     empty         fuel    8419  d41d8cd98f00b204e9800998ecf8427e  OK
  sha256  "abc"         fuel   18866  ba7816bf...f20015ad  OK
  md5     1 KiB lcg(42) fuel  113117  d6c1961991b0106647e36ca4ba12d345  OK
sample_doc -> {"name":"rut","version":0.2,"tags":["tiny","fast","verified"],...}
serde_json parses it: OK
hash keys over that JSON text:
  crc32   eccc5960  OK
  fnv1a64 8ba697141da02e83  OK
hex_dec("zz")   = "hex: invalid character at index 0"
json_dec("{,}") = "json: expected a key string at index 1"
digest("md4")   = "unknown algorithm: md4"
every row agrees: OK
fuel used: 1014105 of Some(50000000)

Code tour

The integer surface is enough for real algorithms

mod.rut runs on hex literals, u32/u64, the wrapping family, and signedness-correct shifts. CRC-32 is the compact showcase — table-free, bitwise, and exactly the textbook loop. The entry is pure rut — no host, no manifest — so it runs on its own, here checked against the algorithm’s canonical test value:

use ink::{ Logger };

entry fn crc32(data: bytes) -> u32 {
    let mut crc: u32 = 0xFFFFFFFFu32;
    for (let b of data) {
        crc = crc ^ b as u32;
        for (let mut k = 0; k < 8; k += 1) {
            if ((crc & 1) == 1) {
                crc = (crc >> 1) ^ 0xEDB88320u32;
            } else {
                crc = crc >> 1;
            }
        }
    }
    return crc ^ 0xFFFFFFFFu32;
}

entry fn main() {
    let log = Logger("crc");
    let vector = "123456789".encode();   // the canonical CRC-32 test vector
    log.info(f"crc32(vector) = {crc32(vector)} — check value 0xCBF43926: {crc32(vector) == 0xCBF43926u32}");
}
crc32(vector) = 3421780262 — check value 0xCBF43926: true

SHA-512 is the demanding one: its 64-bit rotations need >> to be a logical shift on u64 and wrapping_shl to truncate to the operand width. The FNV/djb2/sdbm trio, by contrast, deliberately never shifts a 64-bit word — wrapping_mul, wrapping_add, and ^ carry them, showing how far the primitive surface alone goes.

bytes crosses directly; opaque appears exactly once

Byte payloads need no wrapper — bytes is in the crossing set, so entry fn hex_enc(data: bytes) -> str takes a host byte slice head-on (primitive types). The one erasure in the file is the recursive JSON tree: rut has no recursive struct, so the tree is a tagged union by hand with children boxed in opaque to break the recursion (opaque — erasure and downcast):

enum JTag { Null, False, True, Num, Str, Arr, Obj }

struct Json {
    tag:  JTag;
    num: str;          // verbatim lexeme — exact round-trips, no
    str: str;          // float formatting anywhere in this file
    arr:  Vec<opaque>;
    keys: Vec<str>;
    vals: Vec<opaque>;
}

Storing numbers as their verbatim lexemes is what makes round-trips exact: -3e2 decodes and re-encodes as -3e2, with no float formatting anywhere in the file.

The encode half rides the std json package

The encode side is not private code: it is a member on Json’s own inherent impl matching the std json package’s serialization interface — satisfaction is structural, so spelling the member is the whole admission; the package’s writer does the byte work (Interfaces and dispatch):

impl Json {
    pub fn encode(self, mut w: JsonWriter) -> ?EncodeJsonError {
        when (self.tag) {
            JTag::Null -> { w.write_raw("null"); },
            JTag::False -> { w.write_raw("false"); },
            JTag::True -> { w.write_raw("true"); },
            JTag::Num -> { w.write_raw(self.num); },
            JTag::Str -> { w.write_str(self.str); },
            JTag::Arr -> {
                w.begin_array();
                for (let mut i = 0; i < self.arr.len(); i += 1) {
                    let ae: Json = opaque::downcast<Json>(self.arr[i]);
                    let e = ae.encode(w);
                    if (e != nil) { return e; }
                }
                w.end_array();
            },
            JTag::Obj -> {
                w.begin_object();
                for (let mut i = 0; i < self.keys.len(); i += 1) {
                    w.key(self.keys[i]);
                    let ve: Json = opaque::downcast<Json>(self.vals[i]);
                    let e = ve.encode(w);
                    if (e != nil) { return e; }
                }
                w.end_object();
            },
        }
        return nil;
    }
}

The entry surface then hands the tree to encodeJson and flattens the (str, err) pair it answers. The decode half stays a private cursor parser (strings iterate as codepoints, so the source is split once into single-char strings and walked by index) — and every decode error is an honest string value, never a trap:

hex_dec("zz")   = "hex: invalid character at index 0"
b64_dec("!*")   = "base64: invalid character `!`"
json_dec("{,}") = "json: expected a key string at index 1"

The host oracle, in miniature

The host keeps three-line reference implementations for the hash keys with no canonical crate, and crates for everything else — then compares:

// the hash-key trio with no canonical crate: three-line references
fn fnv1a32(b: &[u8]) -> u32 {
    let mut h = 0x811c9dc5u32;
    for &x in b {
        h ^= x as u32;
        h = h.wrapping_mul(16777619);
    }
    h
}

The same run executes under 50 M fuel for the demos and raises to 500 M for the 64 KiB stress blob — budgets are the host’s call, per call.

Takeaways

  • The integer surface (hex literals, u32/u64, wrapping ops, logical shifts) is enough for MD5-through-SHA-512 — verified, not asserted, against independent Rust.
  • bytes crosses the boundary directly; opaque is for the one place recursion needs breaking.
  • The std json package is usable from day one: spell its serialize interface’s member on your own type and its writer does the byte work (core and the swappable packages).
  • Errors are values, and the host-as-oracle pattern is the strongest test shape in this chapter.

The oracle pattern returns in 06 — GitHub viewer CLI, where the fixture is a recorded HTTP lane instead of hash crates.

03 — Plugin

A Rust chat-room server with a rut moderator plugin — the first example built on two things at once: re-entrant vm.call (the host calls rut, and a host fn called by rut calls back into rut while the first call is still parked) and both opaque directions (rut hands the host a handle to its own state; the host hands rut a handle to the server’s event bus). It is also the packaging example: the plugin loads from a module directory and from a .rutbundle packed from that directory at runtime — the two forms of one contract (Module bundles).

Run it

cargo run -p plugin         # from the repo root
cargo test -p plugin        # transcript asserted + bundle round-trip gates

The demo drives one scripted run twice — once against the directory, once against the packed bundle — and prints both transcripts plus the round-trip proof. Abridged:

== transcript (module directory) ==
[system] *** ada joined (1 online)
[broadcast] <ada> hello world
...
[system] shutdown: 0 online, 3 msgs, 1 mutes
-- 3 messages moderated --

== packed form (examples/03-plugin/plugin -> NNNN bytes, written to /tmp/...) ==
transcript identical to the directory form: true

The test suite asserts the transcript exactly, proves every line crossed the nested render (emits == renders), and gates the bundle form: round-trip equality, byte-determinism, and refusal on an unknown format version or CRC corruption.

Code tour

The layering: callbacks at the edges, classes in the middle

Four layers, and neither business layer ever touches the crossing protocol:

RUST biz (main / tests)      ->  typed Plugin methods, no vm.call
RUST adapter (src/lib.rs)    ->  the ONLY vm.call sites
RUT adapter (plugin/mod.rut) ->  the ONLY entry fns; one-line forwards
RUT biz (Moderator)          ->  pure logic + emit, no entry fn

The moderator rules themselves are plain rut — flood control (three consecutive messages from one sender mutes them), muted users rejected on rejoin, a !stats command, tick heartbeats:

pub fn on_msg(mut self, user: str, text: str) {
    if (self.is_muted(user)) {
        self.say("muted", user);
    } else if (text == "!stats") {
        self.say("direct", f"{user}: {self.stats()}");
    } else {
        if (user == self.last_sender) {
            self.streak += 1;
        } else {
            self.last_sender = user;
            self.streak = 1;
        }
        if (self.streak == 3) {
            self.muted.push(user);
            self.mutes += 1;
            self.say("system", f"{user} muted for flooding");
        } else {
            self.msgs += 1;
            self.say("broadcast", f"<{user}> {text}");
        }
    }
}

Every bus write funnels through one private say(topic, payload) — the business logic never spells a crossing.

The handshake: both opaque directions meet

Closures cannot cross the boundary in either direction, so callbacks register by name: the plugin hands the host the export names it wants wired to each topic, and returns the handle to its own state (init is the entire handshake — bus box in, state handle out):

entry fn init(bus: opaque) -> opaque {
    subscribe(bus, "join", "on_join");
    subscribe(bus, "msg", "on_msg");
    subscribe(bus, "leave", "on_leave");
    subscribe(bus, "tick", "on_tick");
    let mod_: ?Moderator = Moderator::new(bus);
    return opaque(mod_);
}
  • rut’s moderator state comes back as a rut-constructed opaque — the host holds the handle and passes it back on every event.
  • the host’s EventBus goes in as a host-constructed Opaque<EventBus> — subscribe and emit are that box’s callbacks, reached only through the borrow guards (Value boundary and borrows, Embedding and native modules).

The re-entrant call: emit re-enters rut mid-op

The host binds the two server rows over its bus. The emit body is the interesting one — while the emitting handler is still parked mid-op, it makes a nested vm.call("render_line") to format the wire line:

let mut pkg = rut_vm::HostPkg::new("server");
rut_vm::pkg_fn!(pkg, "emit", (Opaque<EventBus>, &str, &str) -> (),
    |vm: &mut Vm, bus: Opaque<EventBus>, topic: &str, handler: &str| -> Result<(), Trap> {
        bus.with_mut(vm, |vm, b| -> Result<(), Trap> {
            let line: String =
                vm.call("render_line", (topic.to_string(), handler.to_string()))?;
            b.lines.push(line);
            b.emits += 1;
            b.renders += 1;
            Ok(())
        })?
    },
);
// the built pkg rides the run chain:
// loaded.pkgs.iter().fold(RutRun::new(), |r, p| r.pkg(p.clone()))
//   .pkg(pkg.build())...compile()

(The comment above this code in the source is worth reading too.) The bus stays mutably borrowed across the nested call — the value boundary’s borrow guard is what makes that sound: a second emit fired from inside render_line would trap on the guard instead of racing. On the rut side, render_line is the one-line entry the host re-enters — pure string work, so it runs on its own (the line it prints below is the transcript’s broadcast row):

use ink::{ Logger };

entry fn render_line(topic: str, payload: str) -> str {
    return f"[{topic}] {payload}";
}

entry fn main() {
    let log = Logger("bus");
    log.info(render_line("broadcast", "<ada> hello world"));
}
[broadcast] <ada> hello world

The packaging: one directory, two load forms

The plugin is a module directory — a manifest naming the entry plus its deps, loadable as-is and packable unchanged (Project structure and rut.jsonc):

// plugin/rut.jsonc
{
  "format": "rutbundle",
  "format_version": 11,
  "name": "plugin",

  "deps": {
    "server": { "path": "../server" }
  }
}

server/ is the interesting dependency: a pure declaration surface — a host package whose manifest points at a .d.rut decl file, with the Rust embedder binding the bodies (Host fns and declaration files):

pub host fn subscribe(bus: opaque, topic: str, handler: str);

pub host fn emit(bus: opaque, topic: str, payload: str);

main.rs packs the same directory with rut_native::pack_dir_opts_with — a compiled bundle: the plugin rides as a .rutc binary, its host pkg server as a source group — writes plugin.rutbundle to temp, and loads it back through the identical Plugin::load. The transcript equality print is the proof. The CLI drives the same loader for any self-contained module:

rut run path/to/mod            # a module directory (rut.jsonc)
rut pack path/to/mod           # -> mod.rutbundle
rut run path/to/mod.rutbundle  # the packed form

The Rust side mirrors the rut layering: business code calls typed methods (p.join("ada"), p.msg(...)), and vm.call happens in exactly one dispatcher that looks up the subscribed export name per topic — unknown topics are dropped, not trapped, so a server keeps running when a plugin didn’t subscribe.

Takeaways

  • One directory is one module; the manifest names the entry and the deps, and the same directory packs to a .rutbundle unchanged.
  • Registration by name, not by closure — callbacks never cross the boundary as values, in either direction.
  • Re-entrancy is sound by construction: a host fn can call back into rut mid-op, and the borrow guard turns a would-be data race into a loud trap.
  • Both opaque directions compose: rut-state-out, host-state-in, and neither side can inspect what the other erased.
  • The layering discipline — adapters own the crossing protocol, business logic stays pure — is what keeps a plugin auditable.

The crossing rules this example lives on are in the host boundary; the load forms are specified in Module bundles.

04 — Custom async

A parse-only example: examples/04-custom-async/mod.rut is a single rut file with no Cargo harness — you cannot run it today, and that is a deliberate disclosure, not an oversight. What it shows is the async vocabulary from the user side: async { } blocks and async fns as the producers (the engine mints their frames; a user type cannot BE a future — Future<T> is a closed class), the injected cx read as data inside the async bodies, and a user-written launcher with per-checkpoint stats and cancellation audits. The runnable harness that would drive it end to end is the follow-up work; the file is kept in the repo now because the parser’s conformance suite compiles every example, so this vocabulary is checked to stay parseable (Async and await).

“Run” it

There is no harness. The file is exercised by the parser conformance test, which walks every .rut file in examples/:

cargo test -p rut-parser --test corpus    # parses every example, incl. this one

To read the same machinery running, see 06 — GitHub viewer CLI: its brain is an async fn driven by the standard launcher this file re-spells by hand.

Code tour

The audit log — the example’s reason to exist

The point of the file is the accounting around the futures: every launch, resumption, cancellation, and completion lands in one module-owned record the embedder can read after the run:

struct AuditLog {
    launches: u32;      // futures this log saw started
    yields: u32;        // resumptions driven — one per checkpoint
    cancels: u32;       // cancellation probes that answered true
    checkpoints: u32;   // high-water mark of the context ledger
    finished: u32;      // runs that walked every step they booked
}

The launcher takes a shared ?AuditLog, so the embedder holds one cell and reads the whole run’s story out of it afterwards — summary renders the one-line audit.

The producers — async { } blocks and the injected cx

Every async producer answers the ONE closed class: an async fn call, an async { } block, sleep — all Future<..>, so the whole await/select/launch vocabulary never asks “which kind”. The async { } block is the primitive: one expression form that mints the frame where it stands (the mint is pure — legal in sync code); its return answers the FUTURE, and its reads capture the enclosing locals by value. async fn is genuine sugar over it — both sides of that law are writable programs.

Inside an async body the weave injects the resume context as cx (an async fn’s parameters are ordinary values — a spelled cx diagnoses). The frozen cx protocol reads as data: checkpoint() answers this frame’s resume state, cancelled() answers the frame’s abort flag — cancellation is a value the frame inspects, not an exception it catches:

fn cancellable(log: ?AuditLog) -> Future<nil> {
    return async {
        while (true) {
            if (cx.cancelled()) {      // the probe, as data
                if (log != nil) {
                    log.note_cancel();
                }
                return;                // answers the FUTURE
            }
            await sleep(20);
        }
    };
}

The user launcher

The engine’s standard launcher set (launch_future, LaunchedFutureHandle, sleep) is ordinary code any module may re-spell — that is the point of launch_custom. It supplies the driving and the audit over the same Future surface, so the producer never knows which launcher started it:

use async_host::{ __abort, __launch };

fn launch_custom(f: Future<nil>, log: ?AuditLog) -> CustomLaunched {
    __launch(opaque(f));
    log.note_launch();
    return CustomLaunched { fut: f, log: log, alive: true };
}

The returned CustomLaunched receipt is deliberately not a future — it cannot be awaited, and it is not re-launchable (that is a type error, never a runtime check). Its one real member is the cancel edge, which flags the frame and lets the loop’s re-drive run the probe.

The crossings cross as opaque — the engine rows’ fixed ABI (opaque) — and the driving loop owns every launched frame from there.

Scope, honestly

Two boundaries to keep straight when you read this file:

  • Futures are engine-minted only. Future<T> is a CLOSED builtin class: no constructor, no impl lane. The walls are the point — structural satisfaction cannot see engine identity, so nominal closure is the only spelling of “engine-minted only”.
  • The file is parse-only — nothing launches or drives it here. The runnable version of the same story is 06 — GitHub viewer CLI, and the model behind it is the async model.

Takeaways

  • Every async producer has ONE type — Future<T>, the closed class; the hidden frame is representation, the handle is the surface.
  • async { } is the primitive and async fn its sugar; a block mints where it stands, its return answering the future.
  • The cx is injected, never spelled: cx.cancelled() and cx.checkpoint() are data reads inside any async body.
  • A launcher is just code: driving + audit over the public Future surface, re-spellable by any module.
  • The file is parse-only by disclosure; the runnable harness is follow-up work.

05 — Todolist web

One page app — a todolist with a simulated server — where every DOM move and every timer goes through ten declared host crossings, and the page’s brain is a rut project of two packages. ui is the framework: an atom store (the jotai shape, in rut), a widget type, a keyed diff, and a component vocabulary. biz is the domain: the todolist machine expressed as store mutations, plus the app shell. The host — web-sys on wasm32 in the browser, a fake-DOM twin on native in the tests — owns the loop; rut owns the state. Pure rut: no event loop, no async keywords on the rut side; every asynchronous fact enters through a door named for its event.

Run it

cargo test -p todolist-web       # the twin + the law (95 tests), from the repo root
cd examples/05-todolist-web
node tests/e2e-browser.mjs       # the through-the-artifact gate (node tier + browser tier)

cargo test runs the whole story on the fake-DOM twin — a HashMap element tree with real DOM semantics and a virtual timer clock — over the same rut sources the browser runs. The e2e script builds nothing silently and skips nothing silently: tier 1 (plain node) drives the real wasm artifact through the loader’s own ABI on a fake DOM; tier 2 (when geckodriver + Firefox exist) types and clicks the live page.

To open the page yourself:

cd examples/05-todolist-web
cargo build -p todolist-web --target wasm32-unknown-unknown --release
wasm-bindgen --target web --out-dir gen --out-name web_host \
  ../../target/wasm32-unknown-unknown/release/todolist_web.wasm
python3 -m http::server        # then open http://localhost:8000/

What you’ll see: type a title — the status line echoes the typing and the counts never move (the draft is not a counts dependency). Press Add — an italic pending line paints immediately, the counts line flips to 1 in flight, and ~400 ms later the committed row replaces it. Toggle a row — the title goes italic for ~250 ms, then the check fills and the title strikes through. The row animates because the keyed diff kept the node alive — nothing is cleared and rebuilt, ever.

Code tour

The ABI is the page: main plus the doors

rut/biz/app/mod.rut — the boot turn builds the app container and returns it as an opaque (rut has no mutable module state, so the host holds the state and re-passes it every turn — the 00 — Todolist pattern at page scale):

entry fn main() -> opaque {
    let boot: World = world_boot("booted — type a title, press Add");
    let root = AppRoot {
        world: boot,
        t1: t1_mount("app"),
    };
    paint(root);
    return opaque(root);
}

Every asynchronous fact enters through a door named for its event — on_click/on_input for DOM events, on_timer for the clock. Each door re-passes the container and answers the entry-err pair: (opaque(c), "") on a clean turn, (nil, why) on a soft failure the pump reports while keeping the page alive.

fn dom_event(mut r: AppRoot, id: str, detail: str) -> (?opaque, str) {
    let booked = t1_event(r.t1, id, detail);
    let req = opaque::downcast<Req>(booked);
    if (req != nil) {
        tim_after(req.latency, req.tag);
    }
    paint(r);
    return (opaque(r), "");
}

The “server” is a request table, not a scheduler: adding never touches the list — the machine books a request and the app books one tim_after(latency, tag); the list changes only when the timer’s turn runs the answer mutation (per-kind latency, so deadline-ordered commits are visible across kinds).

The ten crossings

web.d.rut (flat at the example root, registered by hand in both lanes) declares the whole host surface. Elements cross as opaque handles; everything else is strings, ints, and bools — no app names, no data shipping, no callbacks (the host boundary):

pub host fn ui_get(id: str) -> opaque;
pub host fn ui_create(tag: str) -> opaque;
pub host fn ui_set_text(el: opaque, text: str);
pub host fn ui_attr(el: opaque, name: str, value: str);
pub host fn ui_append(parent: opaque, child: opaque);
pub host fn ui_remove(parent: opaque, child: opaque) -> bool;
pub host fn ui_clear(el: opaque);
pub host fn ui_set_input_value(el: opaque, v: str);
pub host fn ui_listen(el: opaque, event: str) -> i64;
pub host fn tim_after(ms: i64, tag: str);

A wiring bug is loud: a missing id traps (web::ui_get: no element '#x'), a kind mismatch names both sides. The host never grew an app-specific crossing — the entire widget system fits over these ten rows, unchanged.

The store: jotai’s shape over private interfaces

rut/ui/store/mod.rut is the kernel. Handles are keys, not objects — Source<T>, Derived<T>, Mutation<A, R> carry ids and have no logic of their own beyond routing through their store. The machinery interfaces are module-private — the domain package cannot name them even to import them — and satisfaction is structural: each handle carries the members on its own inherent impl, and the member-set match at the store’s boundary is the whole admission (Interfaces and dispatch):

interface Readable {
    fn atom_id(self) -> u32;
    fn materialize(self, st: Store) -> nil; // first touch: the seed lands
}

interface Writable {
    fn atom_id(self) -> u32;
}

“Non-writability” rides the shape, not a seal: a derived cell is not writable because the write verb does not exist where a derive could reach it — the derive ctx exposes get only, and the one write lane takes a Mutation handle (the store re-checks, loud). Under structural satisfaction no interface can fence a member set, so the guarantee is the API’s shape; the private interfaces are the store’s uniform plumbing over handles.

Freshness is pull-on-read: a write bumps a generation, and a get recomputes a stale derived at most once per write-set. There is no flush step anywhere. Dependencies are discovered, never declared — the ctx.get calls inside a derive closure ARE the dependency list, re-recorded on every recompute. The domain’s counts line is the worked example (rut/biz/world/mod.rut):

let counts$ = store::derive(fn (ctx) -> str {
    let items = ctx.get(items$);
    let reqs = ctx.get(reqs$);
    let mut open = 0;
    for (let t of items) {
        if (t.done == false) {
            open += 1;
        }
    }
    let done_n = items.len() - open;
    return f"{open} open | {done_n} done | {reqs.len()} in flight";
});

Writes go through mutation fns — add_m, toggle_m, remove_m, answer_m — multi-step write programs that run in the one write lane; the machine’s counters are sources too, because with no domain container there is nowhere else for state to live.

Widgets are data; the diff does the DOM

view(r) is a pure function from app state to a Widget tree — it runs no crossing and reads nothing (reads are reactive props, resolved at the render door). t1_render diffs the new tree against the previous one held in T1Root and fires only deltas: match children by key, patch in place, re-append on reorder, retire gone keys’ listeners. Nothing changed = nothing fires (HashMaps and sets carry the path-keyed tables):

pub struct T1Root {
    parent: opaque; // the mounted root element
    prev: ?Widget = nil; // the previous tree — the diff's left side
    els: HashMap<str, opaque>; // path -> live handle (ops application)
    regs: HashMap<str, Ev>; // listener id (as crossed) -> the
    // widget's event wiring (a data-shaped binding)
    lids: HashMap<str, i64>; // path -> listener id (retirement)
}

Event wiring rides the widgets as data, not closures — a row’s toggle mutation carries its argument bound (.on_row(w.toggle_row, t.id)), and the framework resolves a firing listener id to that wiring. Styling is a token contract: the stylesheet keys only the lowered t1-* tokens, and the app spells no class.

Two packages, two manifests

A real project is not one file — but the package boundary is also the privacy boundary, which is why there are exactly two (Project structure and rut.jsonc):

// rut/biz/rut.jsonc — the project root
{
  "name": "app",

  "deps": {
    // the sibling package — the consumer's own local package
    "ui":      { "path": "../ui" },
    // the toolchain's packages, from jsDelivr at the std-v11 tag —
    // the pins live in this walk root's rut.lock
    "pouch":   { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle" },
    "nmapset": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/nmapset.rutbundle" }
  }
}

Each package’s body is a file module tree: the root module is mod.rut beside the manifest, mod NAME; declarations mount the children (biz/ is mod.rut + domain/ + world/ + app/; ui/ is mod.rut + five framework modules). The privacy tiers are honest now: the store’s plumbing stays private to store/mod.rut (not even ui’s own components can spell it), pub(pkg) shares inside the package, pub crosses to biz — and the grep gate pins that biz’s import set stays exactly the two-package vocabulary. The native lane mounts the directory — the manifest, not a Rust fn, is the module list. The path row is for the project’s own sibling package; the toolchain’s packages ride in as url deps from the std tree’s jsDelivr CDN, pinned by each walk root’s committed rut.lock (dependency kinds). The wasm lane mounts the same packages by hand as a mirror (the app’s own tree crossing the ABI as the module-rows wire), and a test pins both lanes to byte-identical binaries.

Takeaways

  • The page ABI is main plus doors named for their events; state lives in the container the host re-passes every turn.
  • Ten thin crossings carried an entire reactive framework — the host stayed generic and never learned the word “todo”.
  • The store is jotai’s shape in rut: discovered deps, pull-on-read freshness, mutations as the write lane, and non-writability by shape — the derive ctx has no write verb to reach.
  • Widgets are values; the keyed diff is the only thing that speaks DOM, and patch-in-place is what makes the UI animatable.
  • Soft failures are data ((nil, why) and the pump keeps draining); a panic alone kills the page, loud.

The async shape this page simulates (the request table + timers) is the real thing in 06 — GitHub viewer CLI; the store’s building blocks are in the swappable packages.

06 — GitHub viewer CLI

rgh lists and downloads files from public GitHub repositories over the jsDelivr CDN — no GitHub API, no tokens. Its brain is a rut async free fn: argv carving, the URL building, the tree JSON decode, the human-size formatter, every message and exit code run in the VM. The Rust half is a pure embedder: mount packages, bind host bodies, launch the brain, pump the driving loop to idle, exit with the brain’s i32 (0 ok, 1 runtime error, 2 usage). This is the worked example for the std http lane’s redesigned face — HttpClient, builder-style construction, and async-only send with true streaming.

Run it

cargo run -p rgh -- --repo=jquery/jquery --ref=3.7.1 list
cargo run -p rgh -- --repo=jquery/jquery --ref=3.7.1 download test/data/1x1.jpg
cargo test -p rgh                  # the offline suite — zero network
RGH_LIVE=1 cargo test -p rgh live_smoke   # opt-in live CDN check

list prints one line per file, depth-first in the API’s own order (directories are walked, never printed):

<repo path>\t<human size>\t<hash8>

The size ladder is N B under 1024, then KiB/MiB/GiB with one decimal only when the remainder is nonzero (1536 → 1.5 KiB, 1048577 → 1.0 MiB); the last column is the first 8 characters of the entry’s base64 integrity hash, or - when absent. The offline suite rides a fixture lane keyed on method + URL with a virtual clock — the fixture map’s keys ARE the assertions — and covers every usage error, the boundary tree’s exact output, streamed binary downloads verified byte-verbatim, wire deaths, and status mappings.

Code tour

The brain is async; the host launches and pumps

mod.rut — the entry point is one boot fn: the host crosses argv in as a single \n-joined string (no arg lists in the crossing set), and boot launches the brain with the standard launcher (launched futures):

entry fn boot(args: str) -> nil {
    launch_future(rgh_main(args));
}

The embedder then pumps the driving loop to idle — real reqwest workers settle the completers from their threads, and the process’s one-way exit row fires mid-pump:

loop {
    match vm.run_ready() {
        Ok(_) => {}
        Err(t) => {
            eprintln!("rgh: trap: {} — {}", t.name(), t.msg);
            std::process::exit(1);
        }
    }
    if vm.pending_tasks() == 0 {
        // the brain retired WITHOUT exiting — a brain bug: loud
        eprintln!("rgh: the brain retired without exit (a brain bug)");
        std::process::exit(1);
    }
    std::thread::sleep(std::time::Duration::from_millis(2));
}

The awaits live at the fetch sites and only there — everything else (argv carving with the scan/slice tokenizer primitives, flags, JSON, formatting) is the same sync code it always was.

The http face: build a request, await the send

The std http package is async-only and unsuffixed: only the operations that really wait are async points, everything else is sync construction sugar. The five verbs are build sugars (get/post/ put/patch/del — the DELETE verb spells del; the wire still sees canonical DELETE), and send() is THE async point, resolving at headers — the wire body stays unread (the async model):

async fn do_list(client: HttpClient, owner: str, repo: str, rf: str) -> i32 {
    let url = f"https://data.jsdelivr.com/v1/packages/gh/{owner}/{repo}@{rf}";
    let resp = await client.get(url).build().send();
    let err = map_response(resp, "no such repo or ref", "data.jsdelivr.com");
    if (err != nil) {
        let why: str = err;
        eprint(why);
        return 1;
    }
    let (tree, e) = decodeJsonBytes<Root>(await resp.body());

list is the drain lane: one body() await pulls the whole tree, and the JSON decode goes through the std json package’s reader with decode spelled on Entry’s own inherent impl in this file. Status mapping is one function: status() == 0 is the reserved transport verdict, 404 names the host that was checked, 403 is the rate-limit note, anything else non-2xx is the bare status.

The download: true streaming, chunk by chunk

download walks a ByteStream — next() answers one chunk per await (nil = EOF-or-failed; the sticky error() names which), and each chunk lands through the sync append_file host row. The destination is truncated once first, so a stale file never leaks its tail into a fresh download:

    let stream = resp.byte_stream();
    let mut total: i32 = 0;
    while (true) {
        let c = await stream.next();
        if (c == nil) {
            // EOF — or a mid-read failure? the sticky error names it
            let rerr = stream.error();
            if (rerr != nil) {
                let why: str = rerr;
                eprint(f"rgh: {dest}: {why}");
                return 1;
            }
            break;
        }
        let chunk: bytes = c;
        let werr: ?str = append_file(dest, chunk);
        if (werr != nil) {
            let why: str = werr;
            eprint(f"rgh: {dest}: {why}");
            return 1;
        }
        total += chunk.len();
    }

Bounded memory end to end, and every failure on the data path is a message plus an exit code — never a panic, never a trap. The lane’s one-shot law is worth knowing: per response it is body() xor byte_stream(), and a late/second taker degrades (an empty drain, a dead reader) rather than trapping.

The readbacks, on the response handle

The Response class wraps the host’s opaque handle with sync readbacks — status, the 2xx test, the transport text, and the sticky mid-read failure (the std packages):

impl Response {
    /// the HTTP status word — 0 means the transport failed (0 is never
    /// a real status; any real status, 4xx/5xx included, is not one)
    pub fn status(self) -> i32 { return http_status(self.r); }

    /// the 2xx test
    pub fn ok(self) -> bool {
        let s = self.status();
        return s >= 200 && s < 300;
    }

    /// the transport-failure text — nil unless status is 0
    pub fn transport_error(self) -> ?str { return http_err(self.r); }

    /// the sticky mid-read failure — nil until one fails, then
    /// non-nil forever; meaningful after awaiting `body()`/`next()`
    pub fn read_error(self) -> ?str { return http_read_err(self.r); }

The embedder’s offer list

src/main.rs shows the whole program closure in one chain — the walk feeds the run, the async pair and calc offer beside it, and the host bodies ride pkg(Offer::Host(..)) — pkg(hp) coerces:

let loaded = block_on(rut_native::load_path_session_with(base, &remote))?;
let rgh_host = rut_native::dir_pkgs(&base::join("rgh_host"))?;   // example-local rows

let mut chain = loaded.pkgs.iter().fold(rut_driver::RutRun::new(), |r, p| r.pkg(p.clone()));
chain = chain
    .pkg(rut_native::tree_pkg("calc")?)
    .pkg(rut_std::math::pkg())
    .pkg(rut_std::nmap::pkg())
    .pkg(rut_std::async_host::pkg())
    .pkg(rut_std::http::pkg());
let compiled = chain.entrypoint(&root).compile()?;

The walk pulls json’s own deps along — strbuild, pouch, nmapset — so the whole serde surface, wrapper families included, is in the closure (Dependency kinds). The HTTP bodies install through http::pkg() (the reqwest lane); the example’s own rows are CLI I/O only — out (stdout), eprint, the file pair, and exit — declared in the example-local rgh_host decl package and verified against the bindings at boot (Host fns and declaration files). One consequence: rut run cannot host rgh itself — its rows are example-local — but ordinary HTTP programs do run under rut run, which offers the std http pair by presence.

Takeaways

  • An async rut program in production shape: the brain awaits at the fetch sites only; the embedder launches, pumps to idle, and exits with the brain’s code.
  • Headers-first send + one-shot body/stream is the whole mental model of the std http lane — drain JSON in one await, stream files chunk by chunk.
  • Failures are values end to end: transport errors, 404s, wire deaths, and io errors all become messages plus exit codes.
  • The fixture lane is the test gate: recorded replies keyed on method + URL, deterministic chunks on a virtual clock, zero network.
  • The closure is load-bearing here: json’s Vec<T> serde wrappers are json’s own source, compiled where json compiles — the container packages ride along as json’s plain deps.

The lane’s declarations live in the std tree; for the runner behind rut run, see the rut CLI.

The playground corpus

The classics: eighteen short, self-contained rut programs in demo/src/examples/ that the web playground offers in its picker and runs in your browser. They are not copies — the playground imports the .rut files raw, so what you edit there is what this repo ships. The classics are the fastest way to see the language surface in working code: algorithms first, then the language-surface tours, then the memory shapes. The same order is the playground’s.

Run it

The playground itself:

cd demo && npm run dev      # serve the playground locally
# or use the deployed instance: https://playground.rut.hpp2334.com

Pick a case and press run — and the classics shown in the tour below run in the book too, on their ▶ buttons. The gates that keep the corpus honest:

cargo test -p rut-cli --test playground   # from the repo root — the native gate
cd demo && npm run smoke                  # the wasm gate, headless

Concretely:

  • cargo test -p rut-cli --test playground compiles and runs every classic through the full pipeline natively — a compile failure or a trap fails the gate.
  • cd demo && npm run smoke builds the demo bundle (wasm included) and drives every case through it, headless — the same run through the wasm engine.

Both gates drive the same sources through the same engine — native and wasm — so a classic that stops running cleanly fails in CI, not in front of a reader.

The eighteen cases

CaseDemonstratesFirst line it prints
sieveSieve of Eratosthenes — flat Vec<u8>/Vec<i32> primitive buffers25 primes up to 100, last=97
quicksortin-place Vec<i32> mutation (handles, shared with the caller), recursionsorted: 1 2 2 3 5 7 8 9
matrix-mulflat Vec<f32> hot loops — unboxed buffers, no per-element refcountsout[0]=21 out[last]=107
classesclass-method construction (new/from), Self {}, member pub + sealingcount=2 area=12
closures-genericsanonymous fns (block bodies), monomorphized generics, fn types, captureadd=3 area=3.1415927 sum=6
structsreference semantics (sharing by default), identity ==len=6.324555320336759 color=16711935 area=6
literalsnumeric suffixes, plain/raw/format strings, fixed [T], bytes buffersa=10 e=1.5 d64=1.5 ch=h p.x=1 zero[0]=9 len=3 bin=64
checked-arithwrapping_* wraps two’s-complement, checked_* answers the (T, bool) tuplewrap=4 under=255
str-viewsO(1) slice views (a slice IS a str), codepoints — s.code / str::from_codeword=world len=5 eq=true
bytesthe binary primitive — encode/decode, clone as the ONE copyround=true octets=8 chars=8
opaqueopaque / opaque::downcast<T> -> ?T / is — erasure and checked recoverypoint 1 2
whenwhen pattern expressions over enums, exhaustivenesssmall
if-exprthe if ATOM — if (cond) { x } else { y } as an expression — and block tails (implicit return)95: hi grade=20
mapsthe keyed-collection lane — HashMap/HashSet, keys admitted by the compile-time union boundrut=3 runs=1
node-cyclestrong cycles keep cells alive — the program’s responsibilityhead.next alive: true
treerecursive structs (?Node nullable fields), composite fields as handle slotsnodes=15
weak-cachethe cache/observer shape, shown with today’s strong refsheld: true id=1
type-aliasestransparent aliases, bound-only unions, inline requires at the call sitetrip=1500 plain=1500 ridge/trench kind=trench

Output goes through ink’s Logger (the log.info lines above) — the same logging surface the std packages use (core and the swappable packages).

Code tour

A classic, whole

demo/src/examples/quicksort/mod.rut is the archetype — imports, one algorithm, one log line — and the shared-handle mutation law in action (the sort writes through the caller’s vec). Verbatim, so what runs here is exactly what the playground edits:

use pouch::{ Vec };
// Quicksort — in-place Vec<i32> mutation (vecs are handles: the
// mutation is shared with the caller), recursion, explicit conversions.

use ink::{ Logger };

fn swap(mut xs: Vec<i32>, a: i32, b: i32) {
    let t = xs[a];
    xs[a] = xs[b];
    xs[b] = t;
}

fn partition(xs: Vec<i32>, lo: i32, hi: i32) -> i32 {
    let pivot = xs[hi];
    let mut i = lo - 1;
    for (let mut j = lo; j < hi; j += 1) {
        if (xs[j] <= pivot) {
            i += 1;
            swap(xs, i, j);
        }
    }
    swap(xs, i + 1, hi);
    return i + 1;
}

fn quicksort(xs: Vec<i32>, lo: i32, hi: i32) {
    if (lo >= hi) { return; }
    let p = partition(xs, lo, hi);
    quicksort(xs, lo, p - 1);
    quicksort(xs, p + 1, hi);
}

entry fn main() {
    let log = Logger("sort");
    let xs = Vec<i32>::from([5, 2, 9, 1, 7, 3, 8, 2]);   // fixed -> growable
    quicksort(xs, 0, xs.len() - 1);

    let mut out = "";
    for (let mut i = 0; i < xs.len(); i += 1) {
        out = f"{out}{xs[i]} ";      // `mut`: rebinding; the f-string form builds in place
    }
    log.info(f"sorted: {out}");
}
sorted: 1 2 2 3 5 7 8 9 

(The line above ends with the trailing space the program builds — one after every element — kept byte-for-byte.)

Compare with 01 — Sort: same algorithm, no host — run it here and compare with the fuel-counted host sweep.

Erasure and checked recovery, in one screen

The opaque case is the reference for the erasure primitive — opaque(v) forgets the static type, opaque::downcast<T> answers the nullable, and is names the box, never the payload (opaque — erasure and downcast). The case’s erase_and_recover verbatim, with its two payload types and a main so it runs in place:

use ink::{ Logger };

struct Point { x: f32; y: f32 }
enum Flavor { Sweet, Sour }

fn erase_and_recover() {
    let log = Logger("opaque");
    let box1 = opaque(Point { x: 1, y: 2 });    // erasure = type-call;
    let box2 = opaque(Flavor::Sour);             // zero-copy (shares the cell)
    let box3 = opaque("hello");

    let p = opaque::downcast<Point>(box1);       // ?Point — the nullable
    when (p != nil) {
        true -> { log.info(f"point {p.x} {p.y}"); },
        else  -> { log.info("point: nil"); },
    }
    let wrong = opaque::downcast<i32>(box2);     // wrong type: nil, no trap
    log.info(f"sour? {opaque::downcast<Flavor>(box2) != nil} wrong? {wrong == nil}");
    log.info(f"is str: {box3 is str}");   // `is` names the box — misses every payload type; downcast recovers
}

entry fn main() {
    erase_and_recover();
}
point 1 2
sour? true wrong? true
is str: false

How a case is wired

Each classic is registered in demo/src/examples/index.ts — an id, a blurb, and the raw source, in the playground’s order. The table above quotes each case’s first log line, and the tour’s blocks run right here — quicksort exactly as shipped. Two details worth noticing when you browse: the corpus is walked by the parser conformance test too (alongside examples/ and the std tree — every .rut file in the repo must parse clean), and one quicksort log line ends with a trailing space the program builds on purpose — run it above and look closely.

Takeaways

  • The classics are live sources, not string copies: the playground edits what the repo ships.
  • Every case is exercised by two gates — native and wasm — over the same engine.
  • Eighteen files cover the language surface in run-sized doses: algorithms, types and interfaces, strings and bytes, erasure, patterns, maps, and the memory shapes.
  • When you change the language, these files are the first smoke test — and often the clearest place to demonstrate the change.

For the bigger, host-driven versions of the same ideas, start at 00 — Todolist and work up to 06 — GitHub viewer CLI.

Lexical structure

The character-level rules of rut source: files, comments, identifiers, the keyword set, and the enforced naming conventions.

Source model

  • Files are UTF-8, extension .rut. Both LF and CRLF line endings are accepted (CRLF is normalized); a leading BOM is skipped.
  • Comments:
    • // line comment
    • /* block comment */ — block comments do not nest
    • /// doc comment (also /** ... */) — attaches to the following declaration and is kept for tooling; it is not semantic
  • There is no off-side rule: statements end with ; (required), blocks are braced.

Identifiers and $

ident := (letter | "_" | "$") (letter | digit | "_" | "$")*

$ is an ordinary identifier character, valid anywhere in a name: on_mount$, viewport_size$, $temp, $x1, even $ alone. There is no $ punctuation token and no $-interpolation (f-string holes use { } — see Literals and inference).

The trailing $ is a naming convention, not a lexical category: it marks dispatch-inverted members — anything a runtime fires or owns rather than you calling it. Event props (on_click$), lifecycle hooks (on_mount$, before_destroy$), subscription updates (on_update$), watch controls (start$, stop$), engine atoms (viewport_size$), and mutation handles generally. Never on functions you call, widget builders, or types.

Keywords

The keyword set is exactly:

fnletmutifelse
whileforofreturnwhen
enumstructclassinterfaceimpl
requiresusepubstaticasync
awaitexternishost
truefalsenil

Contextual words — ordinary identifiers elsewhere:

WordSpecial meaning
typethe alias introducer (type Km = Meters; — see Type aliases and union bounds)
entryentry fn at module scope publishes the function to the embedder
selfthe explicit receiver, first parameter of an instance method
Selfnames the enclosing class inside its body; the class-private literal Self { .. }
newnot special — the conventional construction-method name (Rect::new(..))
asthe numeric cast (x as u32)
superonly inside pub(super)
builtindeclaration modes of the engine’s own surface — spelled prelude builtin (ambient) or pub builtin (import-gated); see Host fns and declaration files
disposal / iterable / constructorthe bracket markers — [disposal] fn / [iterable] fn / [constructor] fn designate an inherent impl member as a designated surface (before visibility: [disposal] pub fn ..); the set is closed and engine-owned (interfaces)

panic(msg) is a prelude function, not a keyword.

Reserved words

Each reserved word is a hard error whose message names the rut replacement:

ReservedError replacement
voidthe empty type spells nil
initeration is for (let x of ..)
privatemembers are private by default; add pub

The list is short and closed. Words that are keywords in JavaScript or Rust — switch, match, null, var, const, delete, new, … — are ordinary identifiers here: let null = 5; and fn match() are legal rut — and so is trait: an ordinary identifier (name your pet snake trait if you like; it carries no meaning).

Punctuation: :: and .

Two separators, one law:

tokenrolespells
::the path separator — segments of any name-resolution pathuse paths, module positions, enum members, statics/associated fns, extern namespaces: use pkg::a::b::{ C }, Light::Green, Rect::new(..), Vec<T>::from(..)
.value access on an expressionfields, instance methods, tuple indices: p.x, v.push(..), t.0

A path never spells .; a value access never spells ::. Qualified positions resolve names inside one package, use paths cross packages (see Modules and visibility); Self spells the enclosing type inside an impl body (its class-private literal, its members through the ordinary value-access postfix).

The async block

async { .. } — keyword before a block — is the async primitive: one expression form whose evaluation mints the frame (pure; legal in sync code) and whose type is Future<T> (async and await). async before fn is the declaration sugar over it.

Naming conventions (enforced)

  • Types are PascalCase — user types and parameterized builtins: Vec<T>, [T], Weak<T>, opaque, LaunchedFutureHandle<T>, Point, Drawable. Scalars and simple buffers stay lowercase: i32, u8, f32, bool, str, bytes.
  • Functions and methods are lower_snake_case — unwrap_or(d), push(v), checked_add(y), string_len(s).
  • Construction is a method call; the call form binds by designation. User classes construct through their own class methods: Rect::new(3, 4), Rect::from(other), Version::parse(s) — see Classes and constructors. A class that designates a [constructor] member additionally takes the call form: Point(1.0, 2.0) is sugar for the designated member call, byte-identical lowering. The newtype decl’s own constructor needs no marker: class JsonI64(i64); constructs as the call JsonI64(64) — the compiler-provided positional mint (see Newtypes). Only builtin surfaces keep the other call forms: bytes::zeroed(n), opaque(v), the repeat [v; n], and Vec<T>::from(..) (see Builtin generic types).
  • The trailing-$ marker is kept meaningful by this style rule alone; the compiler attaches no semantics to it.

Modules and visibility

Module scope contains declarations only — every statement lives inside a function, and loading a module executes nothing. Visibility is private by default, with package-scoped forms for libraries.

Module structure

Allowed at module scope:

DeclarationSpelling
importuse pkg::{ A, B }; / use pkg::A; / use pkg::a::b::{ C }; (see below)
child modulemod name; / pub mod name; — declares a file module
bindinglet name: T = expr; (also under pub)
enum / struct / class / interfaceenum E { .. }, struct S { .. }, class C { .. }, interface I { .. }
impl blockimpl T { .. } — inherent, the type’s module only
functionfn f(..) { .. }, async fn f(..) { .. }
entry pointentry fn f(..) { .. }
aliastype X = A; (see Type aliases and union bounds)

Anything else — calls, any statement — is a compile error: statements are not allowed at module scope — modules contain declarations only.

host fn / host struct and builtin declarations are signature-only native surfaces: host rows live in declaration files (.d.rut) and builtin rows in the engine’s own core surface, never as executable bodies in .rut.

File modules (mod)

A mod NAME; declaration mounts a file module. The child has two spellings, probed beside the declaring file in order:

  1. the directory form — NAME/mod.rut (or NAME/mod.d.rut on a host surface tree);
  2. the single-file form — NAME.rut in the same directory.

Both spellings present is a loud ambiguity error naming both — the mount is undecidable until you delete one. In an implementation file there are no inline mod X { .. } blocks — files are the one mechanism. The package’s root module is mod.rut beside its manifest (Project structure); a child’s own declarations may declare grandchildren (layout/mod.rut declaring pub mod grid; mounts layout/grid/mod.rut), recursively. Mounting follows declarations in source order, cycle-guarded by file identity; a repeated name mounts once. A missing child (under both spellings) or a directory without its mod.rut is a loud error naming the spellings. Logical mod paths are unchanged by the spelling — a single-file imp.rut mounts at module path imp exactly as the imp/mod.rut directory would, so qualified positions, uses, and visibility read identically over either shape. mod versus pub mod feeds the same visibility law every declaration follows (below): a pub mod child’s pub members cross packages; a plain mod child is the package’s own.

The inline form lives in declaration files (.d.rut, wire 12): pub? mod NAME { <declarations> } nests declarations in the grammar — host-fn signatures, nested mod blocks, type declarations — no bodies, recursively. This is how a published group’s consolidated declaration entry spells its whole mod tree in ONE file (Module bundles): structure lives in the grammar, never in paths. A directory tree and its consolidated entry are two spellings of one truth — they lower to the same path-qualified rows.

Uses

use pouch::{ Vec };
use ink::Logger;

entry fn main() {
    let log = Logger("uses");
    let v = Vec<i32>::new();
    log.info(f"{v.len()}");
}
0

The use path is pkg:: followed by module segments: the head is the mounted package’s bare [a-zA-Z0-9_]+ name — or the consumer’s own package (its name, or one of its mod edges; see the intra-package import below) — then zero or more module segments walking the package’s file modules, then the leaf — a brace list of one or more names, or a single name:

use tur_kit::layout::grid::Cell;       // one name from a nested module
use tur_kit::layout::{ Column, Span }  // several names from a module
use ink::Logger;                       // the degenerate root path

Importing a module itself (use tur_kit::layout;) is an error — modules are namespaces, not values; the diagnostic names the fix (spell a name at the leaf). rut is fully statically typed: the compiler resolves every used name and knows from usage whether it lands in type position (Column in an annotation) or value position (Logger(..)), so there is nothing for the user to annotate. A use line may spell only what the target exports: a name the target doesn’t declare is rejected at the use line itself — `ink` has no `Nope` — unknown import — not later, at a call site that might never be written. An unreferenced use name is a lint, not an error.

Every leaf must bind — at the use line. Validation is total and it happens where the use was written, before any body compiles: a leaf that binds nothing in its own file is a hard error there. A name the target declares but does not export — a private row — names the fix on the exporter’s side:

`helper` is not exported by `pkga` — mark it `pub` there

(a qualified leaf names the walked module: not exported by `pkga::layout::grid`; the intra-package lane keeps its own visibility spelling, naming both files). A compiled dependency — a packed .rutbundle — carries its declarations as a binary surface with no source text, so a leaf its surface never carried states the bare law: `leaf` is not part of `pkga`'s exported surface — nothing binds in this file.

A use binds its own file. The binding a use creates is visible in the file that wrote it and nowhere else: every file of a multi-file package spells its own imports, the root’s use never feeds a child module’s file, and a sibling’s never feeds its sibling’s. There is no ambient fallback beyond the engine’s own names (the builtins below); beyond them, a bare dep name resolves in a file iff that file’s own use bound it, and a miss at the call site says exactly which fix applies — the name rides another file’s use:

`fetch` is bound by a `use` in the root module — write the `use` in this file

(intra-package bindings add where that file imported it from), or the name is a mounted export no use spells at all:

`dup` is not bound — no `use` statement names it

One name, one leaf, per file. The duplicate-name law is NAME-level, not package-level: a leaf name spelled by more than one use leaf in the same file — whatever the heads, including twice within one list — errors at the second spelling, citing the first:

use pkga::{ x };
use pkgb::{ x };
// duplicate name `x` — `use pkga::{ x }` (mod.rut) already binds it in this file

use pkga::{ x }; use pkga::{ y } is fine — the name is the rule, never the package or the list.

pub async fn crosses package surfaces. A plain pub async fn exports like any pub fn. The exporter materializes the sugar law’s export shape beside the woven body — a hidden start wrapper spelling fn f(p) -> Future<T> that mints the frame — and the surface row carries the declared answer type. The consumer’s use binds the name, a call answers the closed Future<answer>, and await drives it like any future: the wrapper mints the frame in the one unit that knows its full layout, and the drive reaches the exporter’s woven body through the frame’s yield slot exactly as a local call would. The one gap is the generic async fn — the weave refuses generics, no row materializes, and a use leaf naming one refuses at the use line: `grab` is a generic `pub async fn` — generic async fns do not cross package surfaces yet.

The head may also name the consumer’s own package — the intra-package import. The package’s own name resolves to its root module, and a mod edge of its own tree resolves by walking from the file the use is written in (the current module first, then the ancestors — the same walk qualified positions take):

use imp::{ TodoList, Task };   // beside `mod imp;` — imp's pub names

mod imp;

The leaves obey the same laws every crossing does. Each must be a declaration of the walked module, visible from the importing file: a bare, private member of imp is not importable — pub or pub(pkg) is (import is no visibility bypass). A module itself is not an import — walk it (use imp::grid::{ Cell }, not use imp::{ grid }). And the binding is per file, exactly like a dep use: a module needs its own use line. One head must never answer as two things: a name that is both a declared dep and an own module edge is a loud ambiguity — rename one of the two.

The head itself is declaration-scoped: a package may use exactly the heads its own manifest names — deps ∪ (dev-deps when the package is the program root) ∪ core. Mounting stays transitive (a dep’s own deps still join the program’s closure), but a head that is mounted without being declared by this package is the resolver’s dedicated diagnostic, naming who pulled it in and the row to add (dependency kinds).

The engine’s builtin names — the primitives, opaque, panic, type_id<T>(), str(x) — are ambient: no use is needed for them. The gated names resolve only through use core::{ .. }: the const NAN, the disposal context DisposalContext, the weak reference Weak<T>, and the closed async pair (Future<T>, RunContext) — the engine’s weave never needs the import, only source that spells one of the names does. The bracket markers ([disposal]/[iterable]/[constructor]) need no import — the marker word is the designation, not a name (Host fns and declaration files). Package code (pouch, ink, nmapset, …) mounts only through use.

Qualified positions

Inside one package, a declaration of another module is nameable where a path is legal — a type annotation, a call, a field read — by qualified position: layout::Column, store::Source<str>, widget::mk(3). The head resolves against the current module’s scope, then the module’s ancestors up to the package root; positions never take a dep package head — use statements are the only cross-package door. use is also the intra-package import — a use head may be this package’s own name, or one of its mod edges (see Uses) — so a cross-file name binds bare once imported; positions stay spelling-free: imp::grid::Cell never needed an import, and still spells. :: is THE path separator — every name-resolution path (use paths, qualified positions, enum members, statics/associated fns, extern namespaces) spells its segments with it; . is value access only (fields, instance methods, tuple indices — see Lexical structure). One separator, two doors:

formspellingdoor
use pathuse pkg::a::b::{ C }:: — cross-package and own-package module, the import
qualified positiona::b::C / a::b::f(..):: — intra-package, at the use site

Module-level let

Initializers must be load-time expressions: literals, enum members, builtin operators over load-time expressions, struct literals whose fields are load-time expressions, fixed-array literals whose elements are, type_id<T>(), and builtin zero allocations ([nil; n] with a const n). Calls to user functions are not load-time expressions.

let KIND_ADD: i64 = 1;
let ORIGIN = Point { x: 0, y: 0 };

There is no mutable module state: program state is constructed in main, or held by the embedder and passed across the boundary. No user code runs at load.

Entry points

The embedder loads a module and then explicitly calls an entry function — entry fn main for a script, sync or async. entry fn publishes a function to the embedder; entry is orthogonal to visibility and does not combine with pub. Consequences of declarations-only loading: no use side-effect ordering, no load-order bugs, deterministic and cheap loads.

Bindings: let vs let mut

  • let x = e; binds immutably — no reassignment, no field assignment through x, and no mut self method calls on it. It is a read-only view of the shared object.
  • let mut x = e; may be reassigned and grants write access to the object it holds. Every non-primitive is a shared cell (see By-reference and nullable), so that write is visible through every other handle: mut is permission, never a copy. Every assignment path must run through a mut binding.
  • Parameters may declare mut name — the callee’s permission to mutate the caller’s object: fn step(mut p: Point) moves the caller’s point; fn area(p: Point) promises not to.

Visibility

Modules form a tree per package (the package root is the root module mod.rut; each declared child is a module file). Every declaration — and every class member — carries a visibility:

FormMeaning
pub fn ..public — nameable by any rut module (other packages included)
pub(pkg) fn ..visible everywhere inside this package (its whole module tree)
pub(super) fn ..visible to the parent module’s subtree only
(unannotated)module-private — visible in this module and its descendants; the default
  • Unannotated = private to the declaring module and its descendants (a child module sees its ancestors’ privates, never a sibling’s).
  • The paren forms pub(mod) / pub(self) are repealed — they parsed but gated nothing; the parser refuses them with the fix (bare private, or pub(super)/pub(pkg)/pub).
  • Applies uniformly: let, enum, struct, class, interface, impl (an impl exports with its target type), fn, type aliases, and the mod edge itself (pub mod opens the child’s pub members to other packages; a plain mod keeps the child package-internal). On a class declaration it means the type name is visible.
  • Class members take the same forms: an unannotated field or method is module-private; pub (optionally scoped) exposes it. See Classes and constructors.
  • Struct fields are always public — the field law has no dial (see Structs). Impl-block methods take the pub dial — pub fn exports cross-module, plain fn is module-private — the same law a class’s methods follow, enums included (see Structs and Enums). Interface members take no pub at all — they are as visible as their interface; satisfaction reads a type’s public inherent members (see Interfaces and dispatch).
  • Visibility is checked at compile time; it has no runtime representation. Only pub names enter a module’s export table; a non-exported declaration is known inside its module but nameable nowhere else — which is how libraries hide implementation surfaces behind exported ones. Hiding stops at the checker’s door: every non-generic, non-async fn/method body is type-checked even when nothing calls it.

Primitive types

The primitive types, the one sharing regime, and integer semantics.

The type table

GroupTypesNotes
unsigned intu8 u16 u32 u64fixed width
signed inti8 i16 i32 i64two’s complement
floatf32 f64IEEE 754
miscbool
textstrimmutable UTF-8, length-prefixed; compared by content; s.slice(a, b) is an O(1) view (see String slicing and views)
binarybytesimmutable, content-compared octet buffer; the engine-level u8 array
seqVec<T>mutable, growable buffer — shared; a library class over [T] (see Builtin generic types)
seq[T]fixed array — shared; runtime length, non-growable
nullable?Tnil-able cell; nil is the null (see By-reference and nullable)
erasureopaquethe erasure box (see opaque — erasure and downcast)
userstruct / class recordsshared cell handles (see Structs, Classes and constructors)

There is no character type: 'x' does not parse, and str iteration yields one-codepoint strs. Codepoints are spelled with integers:

MemberMeaning
s.code() -> u32the FIRST codepoint of s (traps on empty)
s.code_at(i: i32) -> u32the codepoint at codepoint index i (traps out of bounds — the index is a bug, not data)
str::from_code(n: u32) -> strthe 1-codepoint str for n

Absence is nil on a nullable ?T.

Size and members

.len() is the sequence member shared by every sequence: [T], Vec<T>, str (codepoints), bytes (octets).

str members: len(), code(), code_at(i), encode() -> bytes, slice(from, to) -> str, starts_with(from, head) -> bool, scan(from, set) -> i64. bytes members: len(), decode() -> str (UTF-8, lossy), clone() -> bytes; type-methods bytes::zeroed(n) -> bytes and bytes::from(a: [u8]) -> bytes. str::encode() and bytes::decode() convert between text and octets.

One regime: primitives by value, everything else shared

Primitives (u8..u64, i8..i64, f32/f64, bool) and fn values copy on assignment, passing, and return — plain slot moves. Every other type is a refcounted heap cell handle: assignment shares, and mutation through any alias is visible through all of them — struct and class instances, str, bytes, Vec, [T], enums, opaque boxes, interface-typed values, ?T boxes alike. Writing is gated by the mut-binding law (see Modules and visibility), never by the sharing.

There is no eager copy: bytes::clone() is the one copy escape hatch. There is no &/* syntax anywhere. == on cells is identity (the raw slot compare); str/bytes compare by content — the full table is in Rc, dispose, and identity.

No box<T>, no loans: a loan needs an exclusivity proof, and rut has no borrow checker. The construct is rejected, not deferred. The only borrows anywhere are host-side, call-scoped ones at the embedding boundary.

Tuples and the answer channel

Tuples are first-class values: type (A, B), value (a, b), numeric field access .0, .1, .., destructuring:

let (lo, hi) = bounds;
fn checked_add(self, y: u8) -> (u8, bool);

(?T, err) — concretely (value, ok) / (T, str) — is the answer channel for results and errors. The convention is law:

  • empty err + a value = success
  • empty err + nil = “not found” (a legitimately absent value)
  • non-empty err = failed

checked_add/checked_sub/checked_mul return (value, ok) — false exactly on overflow, value the wrapped bits either way.

Integer semantics

  • Overflow in + - * << traps in debug and release. Wrapping escapes are compiler-lowered methods, ambient on every integer primitive (no use):

    FamilyMembers
    wrapping (two’s complement)wrapping_add wrapping_sub wrapping_mul wrapping_shl
    saturatingsaturating_add saturating_sub saturating_mul
    checked ((T, bool))checked_add checked_sub checked_mul
  • Division by zero traps; int / int is integer division.

  • Mixed-width arithmetic is an error — both operands must have equal width; convert first with as.

  • Conversions are the numeric cast expr as T, truncating like C/Rust — see Literals and inference. There are no implicit numeric conversions at all.

Builtin generic types

The built-in sequence and wrapper surfaces: the heap array [T], the nullable ?T, the growable Vec<T>, Weak<T>, and the keyed collections.

[T] — the heap array

[T] is the spelling of the fixed array: runtime length, non-growable. The type is grammar, resolved directly — no use names it.

use ink::{ Logger };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let xs: [i32] = [1, 2, 3];   // the literal allocates the cell
    let ys: [?Point] = [nil; 4]; // the repeat: a VALUE and a count
    log.info(f"{xs.len()} {ys.len()}");
}
3 4
  • Construction is the repeat expression [v; n] — a value and a count. A scalar/nil fill is the memset-class op; a ref fill retains the cell handle n times — every slot aliases the one cell (the sharing law: the repeat never copies).
  • [T] is a cell handle — shared like every non-primitive: assignment aliases, mutation is visible through every handle.
  • a[i], a[i] = x, .len(), and for (x of a) are compiler-lowered to the fused array ops — never a per-element call. Out-of-bounds traps.
  • Fixed-length windows: v.slice(from, to) — see String slicing and views.

?T — the nullable

?T is a nil-able cell: a one-slot box whose payload is a T or the null slot. nil is its null literal — and the empty type’s one value: a context-free nil has type nil, while nullable positions (let p: ?T = nil, p == nil, left: nil in a literal) type it as ?T. Dereferencing nil is the NilDeref trap — never a silent read.

The spelling is prefix-only and binds tightest — ? applies to the type term that follows:

SpellingTypeReading
?TT | nilthe nullable
[?T][T | nil]array of nullables
?[T][T] | nilnullable array
??Tchainedthe same runtime box, unwrapped transitively at use sites
  • Coercions: T → ?T boxes (the box aliases the payload’s cell — a share; primitives copy bits), ?T → T derefs (a field-0 read plus nil check). Both are implicit at the expected-type position; the funnel is transitive through ??T.
  • Auto-deref covers every value position: p.x, p.m(..), p[i], for (x of p), arithmetic on p’s payload.
  • p == nil / p != nil compare against the null slot; ?T == ?T is slot identity (see Rc, dispose, and identity).
  • A ?T binding IS the cell reference — writes through it hit the shared cell (gated by mut, see Modules and visibility).
  • When the cell’s refcount reaches zero, the engine runs the type’s [disposal] member (<free>(mut self, cx)) — the cell-death hook, not a per-value attach (the Rc heap).
  • Across the host boundary ?T crosses nil-flattened when its element crosses.

Vec<T> — the growable sequence

Vec<T> is a library class (package pouch) over the non-growable [T]: a buf: [?T] backing plus a live len. Loads yield the ?T (uses auto-deref), stores take the coerced handle — reads and writes alias the stored cells, and binding an element copies nothing.

ConstructionMeaning
Vec::new()empty
Vec::with_capacity(n)reserve n slots
Vec::filled(v, n)n slots of v
Vec::from(arr)copy a [T]

Explicit type arguments may be spelled at the call: Vec<i32>::from([1, 2, 3]). Construction is always a method call (see Classes and constructors).

MemberMeaning
push(v)append; amortized O(1) growth
pop() -> Tremove and return the last element; traps on empty — guard with len() > 0
v[i], v[i] = xelement access; out-of-bounds traps
len() -> i32live length
for (x of v)iteration; x is the shared element
slice(from, to) -> ?Vec<T>fixed-length window (compiler-lowered) — writes through it hit the parent
as_array() -> [T]copy the live elements into a fresh, exactly-sized array
freeze() -> bytesVec<u8> only: copy the live octets into the immutable bytes

Vec<u8> is the mutable binary builder; bytes is the binary type that crosses the host boundary (see Primitive types).

Weak<T> — the weak reference

Weak<T> is a builtin class whose box holds an unretained word to a referent — a weak never keeps anything alive. The name is import-gated: spell use core::{ Weak }; or the bare Weak diagnoses `Weak` is not in scope — `use core::{ Weak }`.

use core::{ Weak };
use ink::{ Logger };

struct Tile { v: i32; }

entry fn main() {
    let log = Logger("t");
    let tile = Tile { v: 7 };
    let w = Weak::new(tile);        // the class-method construction
    let got: ?Tile = w.upgrade();  // the live referent, or nil once dead
    log.info(f"{got.v}");
}
7
  • Weak::new(v) traps on a nil v; T must be a reference type (Weak<i32> diagnoses — primitives move by value). Weak<?U> is legal and upgrade() answers ??U.
  • The referent’s death nulls every weak box before any user code runs; upgrade() answers nil deterministically from then on.
  • A weak edge closes no cycle: strong cycles still leak — see Rc, dispose, and identity.

Keyed collections

HashMap<K, V> and HashSet<T> (package nmapset) wrap a native key table. Admission is the compile-time union bound K requires i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | bool | str | bytes — a key type outside the set fails at the instantiation (escape hatch: encode it canonically to bytes). Float keys are absent by design: floats have no stable equality contract. The API is new/with_capacity/put/get/has/remove/len; get answers ?V — nil is absent, and a hit returns the stored cell, not a copy (the aliasing law).

Absence and errors

  • Absence is nil on a nullable: a lookup returns ?V, and nil means “not found”.
  • Errors are the answer channel: (?T, err) — see Primitive types.
  • Type-erased recovery is opaque::downcast<T>(o) -> ?T — the checked lane, nil on a miss; unopaque<T>(o) -> T is the inverse, the bad-cast lane — see opaque — erasure and downcast.

A nullable/enum value is not compared structurally with == — test it with when, a nil/!= nil guard, or the payload.

Enums

enum — simple named symbol sets. This is the entire feature: rut has no data-carrying enums. Heterogeneous data goes through interfaces (see Interfaces and dispatch); absence goes through ?T (see Builtin generic types).

Syntax

enum := 'pub'? 'enum' Ident '{' member (',' member)* ','? '}'
member := Ident
use ink::{ Logger };

enum Color { Red, Green, Blue }
enum Direction { Up, Down, Left, Right }

entry fn main() {
    let log = Logger("t");
    log.info(f"{Color::Blue} {Direction::Right}");
}
Blue Right
  • An enum is a distinct named type; its members are its values — plain symbols, nothing more. There is no integer under a member to read, set, or spell.
  • No data payloads and no computed members — ever. Methods are an impl block away (see Impl blocks).

Using members

Members are named through the enum and compare as equal singletons:

use ink::{ Logger };

enum Light { Red, Yellow, Green }

entry fn main() {
    let log = Logger("t");
    let l = Light::Yellow;
    log.info(f"{l == Light::Yellow}");   // true — members are immortal singleton cells
}
true
  • An enum value renders as its member name in format strings: f"{Color::Red}" is "Red".
  • Enums are ordinary shared values: binding shares the singleton.

Exhaustive when

when over an enum must be exhaustive: cover every member (then else is optional) or add an explicit else arm — a partial when is a compile error. See Control flow and when.

use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn go() { let log = Logger("t"); log.info("go"); }
fn brake() { let log = Logger("t"); log.info("brake"); }
fn stop() { let log = Logger("t"); log.info("stop"); }

entry fn main() {
    let l = Light::Yellow;
    when (l) {
        Light::Green  -> { go(); },
        Light::Yellow -> { brake(); },
        Light::Red    -> { stop(); },   // all members: no else needed
    }
}
brake

Impl blocks

Enums take impl blocks — the same two forms a struct or class takes: non-self methods (called on the enum’s name) and self methods (called on a value). A marked [iterable] member makes the enum a for..of target.

use ink::{ Logger };

enum Dial { Low, High }

impl Dial {
    fn default() -> Self { return Dial::Low; }
    fn flipped(self) -> Dial {
        return when (self) {
            Dial::Low  -> Dial::High,
            Dial::High -> Dial::Low,
        };
    }
}

entry fn main() {
    let log = Logger("t");
    let d = Dial::default().flipped();
    log.info(when (d) {
        Dial::Low  -> "low",
        Dial::High -> "high",
    });
}
high
  • A non-self method is a namespaced function: Dial::default(). Self spells the enum, so -> Self is the return type and Dial::Low mints the member.
  • A self method dispatches on the value: d.flipped() — the receiver crosses as the singleton cell it already is.
  • Method visibility is real: pub fn exports cross-module, plain fn is module-private (see Modules and visibility).

A marked member makes enum values iterable — for (let v of c) rides the same desugar as a class’s (see The iteration protocol):

use ink::{ Logger };

enum Light { Green, Yellow, Red }

impl Light {
    [iterable] fn iterate(self, emit: fn(Light) -> bool) {
        let mut cur = self;
        for (let mut i = 0; i < 3; i += 1) {
            if (!emit(cur)) { return; }
            cur = when (cur) {
                Light::Green  -> Light::Yellow,
                Light::Yellow -> Light::Red,
                Light::Red    -> Light::Green,
            };
        }
    }
}

entry fn main() {
    let log = Logger("t");
    for (let l of Light::Red) {
        log.info(f"{l}");
    }
}
Red
Green
Yellow

One limit stays: [disposal] is for structs and classes only — the engine disposes a record’s cell, and an enum member is immortal.

Boundaries

  • Where another language would use a union of literals ("left" | "right"), rut uses an enum; where it would use a union of shapes, rut uses an interface-typed value (see Interfaces and dispatch).
  • The | spelling exists only for bound-only union aliases and requires bounds (see Type aliases and union bounds) — a compile-time admission gate, never a runtime union value.
  • There is no enum↔int cast: as is the numeric cast only. Enum values cross the host boundary as their runtime identity plus the integer value.

Literals and inference

Numeric suffixes, the default-width rule, casts, tuple literals, string literal forms, and the format-string desugaring.

Inference and conversions

Inference is bidirectional (literal ↔ expected type). A literal without context defaults to i32 (integers) / f32 (floats) — and the default is also a ceiling: an unsuffixed literal adapts to the expected type only while it fits that default.

use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let a = 10;                // i32 (default)
    let b = 10u8;              // u8 via suffix
    let c: u64 = 10;           // u64 via annotation — fits the default
    let big = 18446744073709551615u64;  // past the i32 default: suffix REQUIRED
    // let bad = 13503953896175478587;  // ERROR — exceeds i32, add `u64`
    log.info(f"{a} {b} {c} {big}");
}
10 10 10 18446744073709551615

Past the ceiling the literal must declare itself with a suffix, so a dropped or doubled digit cannot silently re-base a constant. Floats: magnitude is the trigger, precision is not — 0.1 is fine anywhere; 1.0e300 needs f64 even in an f64 position.

Numeric literals: decimal and 0x / 0b / 0o, _ separators, suffixes u8..u64 i8..i64 f32 f64 (3.14159f32, 0xFF_u32).

The cast — expr as T

Conversions are casts, truncating like C/Rust:

  • int→int keeps the target’s low bits (signed targets sign-extend);
  • float→int truncates toward zero and saturates at the target bounds (NaN → 0);
  • a conversion never traps (arithmetic still does).
use calc::{ Math };
use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let cast = 300 as u8;      // 44
    let x = 3;
    let y = 4;
    log.info(f"{cast} {Math::sqrt((x * x + y * y) as f64)}");
}
44 5

as binds tighter than *, is left-associative (x as u32 as u64 chains), and its right-hand side is a naming position restricted to the numeric primitives. There are no implicit numeric conversions at all.

Fixed arrays and repeats

  • [e1, .., en] has type [T] — pure data whose literal allocates the array cell; binding the value shares the cell. It infers T bidirectionally like any literal; at module scope it is a load-time expression when every element is (see Modules and visibility).
  • [v; n] is the repeat: n slots of the value v — see Builtin generic types.

Tuples

Tuples are first-class values: type (T0, T1, ..), value (a, b, ..), numeric fields .0 / .1 / .., and destructuring:

use ink::{ Logger };

fn divmod(a: i32, b: i32) -> (i32, i32) {
    return (a / b, a % b);
}

entry fn main() {
    let log = Logger("t");
    let pair = (1, "two");         // (i32, str)
    let (n, s) = pair;
    log.info(f"{n} {s} {divmod(7, 2).0}");
}
1 two 3

The (value, ok) / (T, err) pair is the language’s answer channel — see Primitive types.

String literals

Three forms — a plain "..." string is always inert (no interpolation ever happens implicitly):

FormExampleMeaning
plain"hi\tname"escapes processed: \t \n \r \b \f \\ \" \u{...}
rawr"C:\temp\log.txt"no escape processing; every byte is literal
formatf"hi {name}, n={n}"Rust-style placeholders, evaluated at runtime

Raw and format do not combine (rf"..." does not parse).

Format literals — f"..."

  • { expr } splices an expression’s value: identifiers, paths, calls, arithmetic — any expression except nested string literals (bind one to a name first). The lexer balances braces to find the closing }.
  • {{ and }} are literal braces. Escapes work exactly like plain strings.
  • The literal desugars at compile time to a concatenation of the literal chunks and one str(x) conversion per placeholder — a builtin per-type formatting call, no runtime parsing:
f"a={a} b={f(b())}"   ->   concat("a=", str(a), " b=", str(f(b())))

Formattable types and their rendering:

TypeRendering
intsdecimal, - for negatives
f32/f64shortest round-trip decimal (3.5, 0.1, 1e300)
booltrue / false
strcontents, verbatim
enummember name (Color::Red → "Red")

Everything else — struct/class values, vecs and fixed arrays, ?T boxes, opaque, tuples — is a compile error inside f"..." (preventing accidental implementation-detail printing). Write a to_string() -> str method on your type and call it explicitly, and route developer output through your host logger (for example the ink package’s Logger::debug(f"...")).

The accumulator idiom out = f"{out}{chunk}" is recognized by the compiler and appends in place — amortized O(1) instead of copying the whole prefix per step, linear in the total output. Core ships no string-builder class: when a reusable builder reads better (a tokenizer or encoder threading text through many calls), reach for the strbuild package’s StringBuilder (stdlib); when an accumulator binding reads better, the f-string shape IS the optimized path.

Control flow and when

The structured statements, the indexed and iterating for forms, and when — the one match construct, an exhaustive pattern expression. Branching on a value is when: arms are pattern -> body, and the construct is exhaustive.

Statements

  • if (cond) { .. } else if (..) { .. } else { .. } — braces required; the same spelling is also an expression (see below).
  • while (cond) { .. }.
  • return expr?; — expr is required unless the function returns nil (or the body ends in a tail; see below).
  • break / continue exist for loops; there are no labels and no do..while.

if — statement and expression

The statement form runs its effect. The same spelling is also an expression: wherever an expression goes — a let initializer, a call argument, an operand, an f-string hole, a when scrutinee — the construct branches and produces the taken arm’s value:

use ink::{ Logger };

entry fn main() {
    let log = Logger("if");
    let n = 7;
    let label = if (n > 5) { "big" } else { "small" };
    let odd = if (n % 2 == 0) { "no" } else { "yes" };
    log.info(f"{n}: {label}, odd={odd}");
}
7: big, odd=yes

The laws:

  • Parens are required — if (cond), never if cond. Braces are required too, and else if chains link arm by arm.
  • Arms are blocks, and a block’s tail is the arm’s value — the expression before the arm’s }, written without ;. A block with no tail produces nil.
  • Producing arms agree on one type — that shared type is the if’s; a disagreement is a compile error naming both types. An arm that diverges (return, break, continue) contributes no type: the completing arm’s value is the if’s.
  • No else types the whole if nil — the implicit else arm is the nil value, so a value-producing then-arm without an else is an agreement error. The no-else form is the statement shape: it runs the arm for effect.
  • The ; decides. A trailing ; after the statement form is the discard form — whatever the arms produced is nobody’s (the assignments are the effect). Without the ;, a trailing if statement with an else reads as the enclosing block’s tail — the value the block produces.

Block tails

Every block has a value, and one rule decides it: an expression closed by ; is a statement (its value is discarded); an expression followed immediately by the block’s } is the block’s tail — the value the block produces. (let always demands its ;.) The tail reads the block’s own bindings, and its value moves out before the scope pops. A fn body’s tail is an implicit return: the definite-return law counts it, so a function with a result arrow can answer without spelling return — the same law covers lambda block bodies:

use ink::{ Logger };

fn classify(n: i32) -> str {
    let band = if (n > 90) { "hi" } else if (n > 50) { "mid" } else { "lo" };
    band
}

fn fact(n: i32) -> i32 {
    if (n <= 1) {
        1
    } else {
        n * fact(n - 1)
    }
}

entry fn main() {
    let log = Logger("tails");
    log.info(f"{classify(72)} {fact(5)}");
}
mid 120

The trailing if in fact is the statement form in tail position: its producing arms agree on i32 and the merged value is the body’s tail. Loop bodies produce values the same way, discarded; when arm blocks are value blocks too (see the laws).

for — two forms

Iterating form — vecs, fixed arrays, slices, strings (one-codepoint strs per step), bytes (u8 per step), and any type carrying an [iterable]-marked member — an enum value included (see Interfaces and dispatch and Enums). Both spellings of this form are one loop: the loop variable is a single binding reassigned per iteration, and over a marked type the loop calls that ONE designated member with an emit closure that follows the capture law exactly like the fused form:

for (let x of expr) { .. }         // plain `let`: a read-only view
for (let mut x of expr) { .. }     // `mut`: the body may assign x

Indexed form — the C shape:

for (let mut i = 0; i < n; i += 1) { .. }

Both headers declare a normal binding, and the mut-binding law gates them like any let: assigning the loop variable — in the body, or in the indexed form’s update clause — requires mut in the header:

use ink::{ Logger };

entry fn main() {
    let log = Logger("for");
    let mut total = 0;
    for (let mut i = 0; i < 5; i += 1) {   // the update clause assigns i
        total += i;
    }
    // for (let i = 0; i < 5; i += 1) { }  // ERROR: assignment to `i` requires `mut`
    let rows = [[1, 2], [3, 4]];
    for (let mut row of rows) {            // the body assigns the element
        row[0] = 99;                       // the write reaches the sequence
    }
    log.info(f"total={total} rows[1][0]={rows[1][0]}");
}
total=10 rows[1][0]=99

when

when (x) { pattern -> body, ... } is an expression: the first matching arm’s body produces its value. No fallthrough; exactly one arm runs.

use ink::{ Logger };

fn describe(n: i32) -> str {
    return when (n) {
        0         -> "zero",
        1, 2, 3   -> "small",   // comma-separated alternatives
        else      -> "big",     // non-enum scrutinee: else REQUIRED
    };
}

entry fn main() {
    let log = Logger("t");
    log.info(f"{describe(0)} {describe(2)} {describe(10)}");
}
zero small big

Patterns

PatternExample
enum member (path)Light::Green
literal0, 3.5, true, "text"
negative literal-1
alternatives (comma list)1, 2, 3
wildcard else / _else -> ..

Ranges, destructuring, binding patterns, and guards (x if cond) do not exist; patterns are enum members, literals, alternatives, and the wildcards only.

The laws

  • Exhaustiveness is always enforced. An enum-typed scrutinee must cover every member (then else is optional) or add else — a partial when is a compile error. Any other scrutinee type (integers can’t be enumerated): else is mandatory.
  • All arms must agree on one type — that is the when’s type. Block arms are value blocks: a block arm’s tail is the arm’s value, and expression and block arms mix freely under the same law. Used as a statement, the when’s value is discarded — the arms still agree (the check is the same one), and block arms written for effect stay tail-less.
  • Duplicate patterns, and arms made unreachable by earlier ones, are compile errors.
  • Arms use ->. Expression arms are comma-separated; block arms may omit the trailing comma (the corpus writes it).
  • when literal patterns match compile-time values, never runtime ==.
use ink::{ Logger };

enum Light { Green, Yellow, Red }

fn go() { let log = Logger("t"); log.info("go"); }
fn brake() { let log = Logger("t"); log.info("brake"); }
fn stop() { let log = Logger("t"); log.info("stop"); }

entry fn main() {
    let l = Light::Yellow;
    when (l) {
        Light::Green  -> { go(); },
        Light::Yellow -> { brake(); },
        Light::Red    -> { stop(); },   // every member: else optional
    }
}
brake

A when is also the idiomatic nullable guard, together with != nil:

use ink::{ Logger };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let p: ?Point = Point { x: 7, y: 0 };
    when (p != nil) {
        true -> { log.info(f"{p.x}"); },
        else -> { /* absent */ },
    }
}
7

Structs

struct — the open data record: all fields public, constructed only by literal, sharing its cell like every non-primitive.

Declaration

use ink::{ Logger };

struct Point {
    x: f32;
    y: f32;
}

struct Style {
    color: u32 = 0xff00ff;   // field initializer: literals may omit it
    width: f32 = 1;
}

entry fn main() {
    let log = Logger("t");
    let s = Style {};
    log.info(f"{s.color} {s.width}");
}
16711935 1

Reference semantics

A struct value is a heap cell handle (see By-reference and nullable): assignment, argument passing, and returning share the cell, and a mutation through any alias is visible through all of them.

use ink::{ Logger };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let mut p = Point { x: 1, y: 2 };
    let q = p;                       // SHARE: q and p name one cell (O(1))
    p.x = 4;                         // q.x is 4 now — sharing is the law
    log.info(f"{q.x}");
}
4

Writing is gated by the mut-binding law (see Modules and visibility): field stores and mut self methods need a let mut binding (or a mut parameter). Parameters declare their intent: fn nudge(mut pt: Point) may write the caller’s point; fn length(pt: Point) -> f64 promises not to, and returns a fresh record instead:

use ink::{ Logger };

struct Point { x: i32; y: i32; }

fn nudged(pt: Point) -> Point {     // builds a NEW record
    return Point { x: pt.x + 1, y: pt.y };
}

entry fn main() {
    let log = Logger("t");
    let p2 = nudged(Point { x: 1, y: 2 });
    log.info(f"{p2.x} {p2.y}");
}
2 2

== on two struct values is a cell-identity test — q == p is true exactly when they name one cell; two separately built literals are never equal. Field-wise comparison is an interface-shaped contract of your own (spell a member that compares — see Interfaces and dispatch).

Construction — the literal, everywhere

Name { field: expr, .. } is the only construction. There is no new, no class methods, no type-call. The literal is available everywhere — function bodies and module-level let initializers alike — and it allocates the cell.

  • Fields may be given in any order, by name.
  • The every-field-covered law: a literal must cover every field — spelled in the literal, or covered by the field’s declared initializer (tag: str = "..."). Omitting a field that has no initializer is a compile error — missing field `b` in the `P` literal (the every-field-covered law) — the silent zero-fill default is gone.
  • A field spelled twice is a compile error — duplicate field `a` in the `P` literal — there is no last-wins.
  • An omitted field with an initializer takes it; {} with all-initialized fields is legal.
  • Field-init shorthand: a bare field name takes its value from the like-named binding in scope — Name { x, y } is exactly Name { x: x, y: y }.
use ink::{ Logger };

struct Point { x: i32; y: i32; }
struct Style { color: u32 = 0xff00ff; width: f32 = 1; }
struct Rect { min: Point; max: Point; }

entry fn main() {
    let log = Logger("t");
    let q = Point { x: 9, y: 9 };
    let s = Style {};                     // the declared initializers fill the fields
    let r = Rect { min: Point { x: 0, y: 0 }, max: q };  // max shares q's cell
    log.info(f"{s.color} {r.max.x}");
}
16711935 9
use ink::{ Logger };

struct Task { id: i32; title: str; done: bool }

entry fn main() {
    let log = Logger("sh");
    let id = 7;
    let t = Task { id, title: "Eat an apple", done: false };  // `id` is `id: id`
    log.info(f"{t.id} {t.title} {t.done}");
}
7 Eat an apple false

All fields public, always

A struct is an open data record: member visibility in a struct body is a compile error (privacy needs construction control, which is the class’s job — see Classes and constructors). Structs also have no static members.

Methods live in impl blocks

A struct body is fields only — a fn member in the body is a hard parse error. Methods live in the inherent impl S { .. }, in the type’s module only — the one impl form (see Interfaces and dispatch):

impl Point {
    fn dist(self, other: Point) -> f32 { .. }   // inherent — the type's module
}

impl Point {
    fn hash(self) -> u64 { .. }                 // a member set, if you want one:
    fn eq(self, other: Point) -> bool { .. }    // satisfaction reads these
}

Methods carry real visibility — the class rule: pub fn exports cross-module, plain fn is module-private. Self spells the struct, in signatures (-> Self) and the literal (Self { x: 1, y: 2 }) alike:

use ink::{ Logger };

struct Counter { n: i32 }

impl Counter {
    pub fn new() -> Self { return Counter { n: 0 }; }
    fn bump(mut self) -> Self { self.n += 1; return self; }
    fn value(self) -> i32 { return self.n; }
}

entry fn main() {
    let log = Logger("t");
    let c = Counter::new().bump().bump();
    log.info(f"{c.value()}");
}
2

Free functions over data remain the default idiom; methods are for tight helpers, impl blocks for the members other code observes.

Limits, exhaustively:

  • fields are always public — no field-visibility dial (privacy needs construction control, which is the class’s job — see Classes and constructors);
  • construction is the literal — Point { x: 1, y: 2 } everywhere (open literal vs class-method-gated is the struct/class distinction).

Everything else class-shaped is allowed — impl blocks, Self, [disposal]. And the old “no destructor” limit is gone: a shared value dies exactly when its cell’s refcount reaches zero, so cleanup is one impl away — mark a [disposal] member on the type and the engine calls dispose at that moment (see Rc, dispose, and identity).

Interfaces and representation

  • Widening a struct to an interface I attaches the itable to the same handle — no allocation, no copy: the interface-typed value aliases the record, and mutations through it are visible to every other handle.
  • Representation: one slot per field inside the cell, in declaration order — primitive fields widened into their slot, composite fields as cell-handle slots (see Reified types and layout). Recursive shapes (next: ?Node) are legal because composite fields are pointer-sized.
  • Structs are for small data (points, rects, colors, configs), but any size is allowed.

Classes and constructors

class — the sealed record: module-private fields by default, construction gated behind class methods, no inheritance.

Declaration and construction

use ink::{ Logger };

class Rect {
    w: f32;
    h: f32;
}

impl Rect {
    pub fn new(w: f32, h: f32) -> Self {   // construction VALIDATES — it is
        if (w <= 0 || h <= 0) {            // just a function
            panic("Rect: negative extents");
        }
        return Self { w: w, h: h };
    }

    pub fn from_square(s: f32) -> Self {   // named constructors are siblings
        return Rect::new(s, s);
    }

    pub fn area(self) -> f32 { return self.w * self.h; }
}

entry fn main() {
    let log = Logger("t");
    let r = Rect::from_square(3);
    log.info(f"area={r.area()}");
}
area=9
  • Classes construct through their own class methods — nothing else is constructible. No outside literal exists:

    let r = Rect::new(3, 4);            // the one construction surface
    let v = Version::parse("1.2");      // ?Version — nil on failure
    // Rect { w: 1, h: 1 };            // ERROR: classes have no outside literal
    

    new is not special syntax — just the conventional primary-constructor name (from, parse, open, default are its siblings); it is an ordinary identifier. Try-construction returns the nullable: a class method fn parse(s: str) -> ?Version answers nil on failure. A class may designate its primary constructor with [constructor] — then the call form spells the construction too: std’s Logger("t") constructs through the [constructor] member (the [constructor] section below).

  • The Self { field: expr, .. } literal is the class-private construction — legal anywhere inside the class body (class methods and instance methods alike); the class name spells it inside the body too (Rect { .. }). The literal must initialize every field without an initializer — the every-field-covered law, structs and classes alike — and a field spelled twice is an error; field initializers run for omitted fields. Private fields are settable in the literal — inside the class body only. That privacy is the seal: outside code can build a class value only by calling a class method that chooses to build one.

  • No implicit default construction. A class whose fields all have initializers still needs an explicit fn new() -> Self { return Self {}; } if outsiders should build it. A class with no accessible constructing class method is sealed — constructible only inside its own body.

  • No parameter properties: parameters are parameters — the Self { field: name } literal makes the param→field mapping explicit.

  • async class methods are allowed — same function, await in the body. No partially constructed instance ever exists across an await: the Self { .. } literal is an ordinary expression, and locals live in the coroutine frame.

[constructor] — the designated construction surface

A bracket marker designates THE member a surface binds to — the member’s name is free; the designation routes the call. Three designated surfaces, one law:

markersurfacecallersignature ownerbody compiled
[disposal]cell deaththe engine, at refcount zerothe engine — (mut self, cx: DisposalContext)eagerly queued at death (the Rc heap)
[iterable]for (x of it)the for-of desugarthe member — its emit parameter fixes Efused into the loop (interfaces)
[constructor]the call form Type(..)user codethe member — its parameters fix the call’s shapebyte-identical to Point::from_xy(..)

[constructor] designates the class’s construction surface — the call form Type(..) binds to the one marked member:

use ink::{ Logger };

class Point {
    x: f32;
    y: f32;
}

impl Point {
    [constructor] pub fn from_xy(x: f32, y: f32) -> Self {
        return Self { x: x, y: y };
    }
}

entry fn main() {
    let log = Logger("t");
    let p = Point(1.0, 2.0);      // sugar for Point::from_xy(1.0, 2.0)
    log.info(f"p=({p.x}, {p.y})");
}
p=(1, 2)
  • Sugar, not a new mechanism. Point(1.0, 2.0) lowers byte-identically to Point::from_xy(1.0, 2.0) — the marker changes what the call form binds to, never what the call compiles to. Point as a bare (non-call) expression stays an error: the construction surface is the call form Type(..), never the bare name.
  • One designated constructor per class, on the inherent impl only. Class bodies stay fields-only; a second [constructor] member is refused — “Point already carries a [constructor] member — origin and from_xy both designate the construction surface; at most one per class (Point(..) must lower to one member)”. The member takes no receiver — “a [constructor] member takes no receiver — fn <free>(..) -> Self (the call Type(..) spells the class, not a value)” — and returns Self (or ?Self): “a [constructor] member returns Self (or ?Self — the try-construction: Type(..) then yields ?Type)”. An unknown bracket word was always refused, and the closed set now names three: “[fragile] is not a designated surface — the closed marker set is [disposal], [iterable], and [constructor]”.
  • ?Self is try-construction. A constructor spelled fn parse(s: str) -> ?Self makes Type(..) answer ?Type — the call yields the nullable, nil on a refused construction, exactly like the method call it is.
  • Newtypes never carry it — JsonI64(64) is already the newtype’s construction surface, the compiler-provided positional mint; there is nothing for the marker to designate. Structs and enums are refused too — structs construct by literal, and an enum’s members are its own immortal singletons.
  • The seal holds. Visibility rides the method’s pub — an unannotated (module-private) constructor answers Type(..) only inside its own module. Outside, the used-class hint says so: “Point constructs through its class methods (Point::new(..)) — mark one [constructor] to call the class itself”. Arity is the member call’s — the refusal names the member (Point::from_xy).
  • Resolution order for Name(args): a local fn value, then free fns, then the prelude, then the newtype mint, then the designated constructor, then the error — a free fn named Point wins.
  • Generics ride the method-call path. Box(3) infers exactly like Box::of(3) — the sugar IS the member call after resolution.
  • Named constructors stay live. new, from_square, parse, open, default — every existing class method keeps its place; the marker designates one of them as the call form’s target, it does not remove the siblings.

Newtypes: the one-field wrapper

class Name(Wrapped); — the positional one-field decl. It IS an ordinary class: exactly one field, inner, of the wrapped type. The positional spelling additionally provides the constructor — the call form Name(value):

class JsonI64(i64);              // the wrapper family — one per wrapped
class JsonI32(i32);              // type, each with its own body
class JsonF64(f64);
impl JsonI64 {
    pub fn encode(mut self, w: JsonWriter) -> nil { w.int(self.inner); }
}

dump(JsonI64(64));               // manufacture at the boundary
  • The wrapped type is unrestricted — primitives, composites, tuples, fn types, another module’s class: class Opt(?i64);, class Pair((i32, str));, class Cb(fn(i32) -> str); are all legal. The wrapped position is a FIELD type, never an impl target — that is the point. A wrapper is how a primitive or a third-party type gains a capability satisfaction can’t reach: declare the wrapper, implement on it, hand the wrapper across the boundary.
  • No auto-insertion, ever. dump(64) is an error forever; the capability exists exactly where the constructor is spelled. And no implicit forwarding: the wrapper exposes exactly its own members — inner (the ordinary field, ordinary visibility) and its impl methods.
  • The naming law: wrappers are named for what they wrap (JsonI64, never JsonExt). Per-type wrappers with type-specific bodies when the bodies differ; a generic wrapper covers the uniform cases: class DebugWrap<T>(T);.
  • The generic instantiation law: a binder is determined by the wrapped argument when it appears there (class Tail<T>([T]); → Tail([1, 2]) is a Tail<i32>), or by explicit type arguments at the constructor (Converter<i32>("64") — class Converter<T>(str); cannot infer, the binder is not in str). If any binder is undetermined, the call spells ALL binders — all-or-nothing: class Pair<A, B>(i32); accepts Pair<i32, str>(7), never Pair<i32>(7).
  • The third-party adapter (the orphan case, dissolved): class TheirJson(TheirType); plus an inherent encode hands THEIR type the capability — consumers manufacture TheirJson(x) from their own modules; the newtype flag rides the class’s surface row like the class itself does.
  • A braced class — even one with a single inner field — has no call construction of its own: the positional spelling is what provides the newtype’s constructor, and a braced class gains the call form only by designating a [constructor] member (above). A newtype itself never carries the marker — its mint already IS Name(v); everything else stays sealed.

At runtime the construction mints a real cell: the wrapper is a value like every class.

Methods: explicit self

  • The receiver is explicit. An instance method spells its receiver as the first parameter — fn add(self, x: i32, y: i32) — and the body reads fields through self. A method that mutates declares mut self and requires a let mut receiver (see Modules and visibility).
  • A method without a self parameter is a class method — invoked on the class itself (Rect::new(..), Self.new(..) inside the body). Presence or absence of self is the whole distinction. Class methods are ordinary functions: they validate, default, cache, register, or hand out singletons.
  • A computed property is a method (c.count()), and a settable one takes an argument (c.set_count(n)). One member kind, one call convention.
  • Static fields are declared static name: T = init; in the class body, with the same visibility forms as fields.

Member visibility

Members follow the same visibility forms as declarations (see Modules and visibility): an unannotated field or method is module-private; pub, pub(mod), pub(super), pub(self) expose it to the form’s audience. The construction surface is therefore explicit: pub fn new(..) builds; unannotated members stay the class’s own business within its module.

Reference semantics and equality

A class value is a heap cell handle like every non-primitive (see By-reference and nullable): assignment shares, mutation is visible through aliases. == is cell identity; field-wise comparison is an interface you write for it.

No inheritance

  • No extends for classes — no base-class constructors (super(..)), no method overriding, no super.m(), no protected.
  • Code sharing is composition (hold a helper object or struct in a field) or free functions; polymorphism is only the structural kind — a type used through an interface whose members it has (see Interfaces and dispatch).
  • Layout stays trivial: fields at fixed offsets — identical inside every cell payload (see Reified types and layout) — no prefix layout, no fat pointers, and every object has exactly one concrete class forever. That keeps is a single descriptor check.

Rc, dispose, and identity

One memory regime: every non-primitive value is a shared, refcounted heap cell; destruction is deterministic; == is identity for cells.

Reference semantics

Every non-primitive value — struct and class records, str, bytes, Vec, [T], enums, opaque boxes, interface-typed values, ?T boxes, closures’ captured cells — is a heap cell handle:

  • assignment, argument passing, and returning copy the handle (retain/release), an O(1) move;
  • mutation is visible through every alias;
  • writing is gated by the mut-binding law (see Modules and visibility), never by the sharing.

There is no eager copy of any composite — bindings share by reference. bytes::clone() is the one copy escape hatch: a one-shot deep copy of a buffer’s octets. Every other type shares on binding; a divergent value of any other type is unreachable — build a new one instead.

Recursive shapes (next: ?Node, trees, lists) are legal: composite fields and elements are pointer-sized handle slots, and the refcount walk sees every handle field via the compile-time field table (see Reified types and layout).

Disposal — the cell-death contract (the [disposal] marker)

Destructors are implemented, not attached. A type opts in with one [disposal]-marked member on its inherent impl (the name is free — the bracket designates):

use core::{ DisposalContext };
use ink::{ Logger };

struct Conn { log: Logger; url: str; }

impl Conn {
    [disposal] fn close(mut self, cx: DisposalContext) {
        self.log.info(f"closed {self.url}");
    }
}

entry fn main() {
    let log = Logger("t");
    let c = Conn { log: log, url: "tcp://edge" };
    log.info("main is done");
}   // c's refcount reaches zero here; dispose runs at the call boundary
main is done
closed tcp://edge
  • A [disposal] member runs when the cell’s refcount reaches zero — deterministic destruction, not a collector callback. The dying value arrives as mut self; the fields release after the body returns. The member’s NAME IS FREE — the bracket designates, the spelling never does (one [disposal] member per class).
  • cx: DisposalContext is engine-minted, one per call. It is empty today — the parameter exists so the context can grow additively without ever touching the marker’s signature.
  • DisposalContext is the import-gated builtin class: use core::{ DisposalContext }; brings it in (core and the swappable packages). Using it without the use line diagnoses `DisposalContext` is not in scope — `use core::{ DisposalContext }`. The marker stands alone — there is no Disposal interface behind it and no import for the bracket word itself.
  • One marked member per class, by the marker’s own law — there is no per-value attach and nothing to attach twice.
  • The body runs at a call boundary, not re-entrantly inside the release; the full sequence — weak boxes nulled first, then dispose, then the recursive field walk — is the Rc heap’s destruction order.
  • The host side of the same law: a host payload’s finalizer runs at cell death, before the payload’s own Rust Drop.

Because every shared value now has a single knowable death — its refcount reaching zero — a struct can carry its own destructor: no wrapper class and no mint-site bookkeeping, just the impl.

Weak references

Weak<T> (see Builtin generic types) demotes any handle to a non-keeping reference:

use core::{ Weak };
use ink::{ Logger };

struct Tile { v: i32; }

entry fn main() {
    let log = Logger("t");
    let tile = Tile { v: 7 };
    let w = Weak::new(tile);        // does NOT keep the cell alive
    let got: ?Tile = w.upgrade();  // the live referent, or nil once dead
    log.info(f"{got.v}");
}
7

The referent’s death nulls every weak box before any user code runs. A weak edge closes no cycle: strong cycles (two records holding each other, a container that holds its own observer) still leak to engine shutdown — the memory law is the program’s; break cycles with Weak.

Identity — ==

a == b is a builtin operator: no dispatch, no opting in, no element-wise story. a != b is its negation.

Operand type== meansLowering
numeric / bool primitivesvaluecompare, IEEE 754 for floats (NaN != NaN, -0.0 == 0.0)
strcontent (codepoints)content compare
bytescontent (octets)content compare
everything else — records, arrays, Vec, enums, closures, interface objects, opaque, ?Tcell identitythe raw slot compare
  • Identity is the only == sharing can defend: with aliasing everywhere, structural equality of two independently built cells is ambiguous, and identity is O(1) with no deep walk. [1, 2] == [1, 2] is false — two cells.
  • Enum members are immortal singletons, so Flavor::Sour == Flavor::Sour is true — the one place identity quietly behaves as value.
  • ?T == ?T is slot identity: two nils are equal, a null and a box are not; p == nil derefs the nullable side and compares against the null slot.
  • An identity-compare lint flags == between two obviously fresh composites (Vec::from([..]) == Vec::from([..])): “always false — compare fields”. Asserting distinctness is legitimate and suppressible.
  • Field-wise comparison is a library interface contract (hash + eq spelled per type) — the mechanism value-keyed maps ride. It is not connected to ==.
  • when literal patterns are unaffected: arms match compile-time values, never runtime ==.

Interfaces and dispatch

An interface is a member set: signatures only, no bodies. A type satisfies an interface by having the members — satisfaction is structural, checked once at the positions that need it. There is nothing to register, nothing to declare, and no impl lane for an interface: impl I for T does not parse. Dispatch follows two positive rules, fixed at compile time per call site.

Interfaces

pub interface Shape {
    fn area(self) -> f64;         // bodiless signatures; async legal
}

pub interface Decoder<E> {
    fn decode(mut r: JsonReader) -> (Self, ?E);   // Self + generics legal
}
  • Signatures only, no bodies. No fields, no properties, and no default implementations, ever — one member kind, one dispatch candidate per call. Anything that reads like a property is a method.
  • Self and generics are legal. Self in a member’s signatures accepts the satisfying concrete type (-> Self returns, (?Self, ?E) decodes into it); a generic interface gives each type-argument list its own member set (Decoder<E> ≠ Decoder<F>). Interface generic parameters take no bounds — an interface is a flat requirement, not a constraint stack.
  • Members carry no pub — they are as visible as the interface.
  • No requires list on the interface. Bound-taking code spells T requires Shape at the use site; the interface itself stays a bare member set.
  • No embedding. Interfaces are flat member sets — an interface cannot embed another. Compose by declaring the members: an interface that needs two capabilities spells both member sets.
  • No object-type keyword anywhere: an interface name in type position is the bare name — s: Shape, Vec<Shape>, generic arguments included.
  • No top interface. The erased-storage type is the concrete primitive opaque (see opaque — erasure and downcast), reached by an explicit call, never by widening.
  • Intersection types (A & B) are never supported — not deferred: heterogeneous needs compose an interface that declares both member sets.
  • Interfaces may be declared in .d.rut declaration files — signatures-only fits the declaration surface; the engine’s own prelude carries none (the engine’s contracts are the bracket markers and the closed classes below).

Satisfaction — the member-set law

Satisfaction is structural: a type satisfies I exactly when its public inherent members cover I’s member set. Any pub form counts — a class method, a struct’s method on its inherent impl, a newtype wrapper’s member. Checking, never searching: there is no registry, no registration, no impl block for an interface anywhere in the language.

  • The check runs at the boundary — exactly the positions where a value of some type T is used as the interface:
    • interface-typed parameters — dump(p) against fn dump(x: Serializable) checks Point’s member set once;
    • typed lets and assignments — let s: Shape = Point { .. }; is a satisfaction assertion;
    • returns — a function whose return type is the interface checks each returned concrete;
    • boxing sites — pushing into a Vec<Shape> checks before the box is built. Everywhere else the compiler never asks the question.
  • Members must be the type’s own. The member set is the public inherent surface — the type’s module’s impl block. A third party’s inherent block is refused; a used type’s members live where the type was declared.
  • Signatures must match: receiver form (self vs mut self vs none), parameter types, return type, and async spelling — exactly, wherever both sides are locally visible. Self in the interface’s signatures accepts the satisfying concrete type.
  • Failure names all three: passing a Point without area to a Shape parameter diagnoses “Point does not satisfy Shape: no member area”.
  • Who can never satisfy: primitives, the composites ([T], tuples), ?T, and foreign closed classes have no inherent members, so no member set — they satisfy nothing. The route in is the wrapper (below).
  • The empty member set is vacuously true: an interface with no members is satisfied by every type — there is no marker idiom. If a declaration needs to mean something, it spells a member.
  • Shape-equal is satisfied. Two types whose public members have the same shapes both satisfy — including types whose author never thought of the interface. Accidental satisfaction is real and accepted: the mitigation is convention (distinct member shapes, spelled receivers), not machinery. No registration exists that could gate it.

impl T { .. } — the one impl form

Type bodies are fields only; methods live in impl blocks. The inherent impl is the only impl form:

impl T { .. } (inherent)
Lives in.rut, T’s module only
Valid targetslocal struct/class, or a builtin class this module declares
pub(..)classes only (structs are all-public)
asynclegal
no-self methodslegal (constructors)
fields / empty bodynever / legal
pub interface Serializable {
    fn encode(mut self, w: JsonWriter) -> nil;
}

class Point {
    x: i32;
    y: i32;
}

impl Point {
    pub fn encode(mut self, w: JsonWriter) -> nil {
        w.key("x"); w.write_i64(self.x);
        w.key("y"); w.write_i64(self.y);
    }
}
  • The orphan rule and the one-impl-per-pair link law are gone — there is nothing to register, so there is nothing to duplicate and no placement rule beyond the inherent one (the type’s own module).
  • Generic binders are declared after impl — impl<T> Vec<T> { .. }, not impl Vec<T> { .. }. The declared list is the definition site: a bare parameter name in the head is a use that must resolve against it (“undeclared type parameter T — declare it: impl<T> ..”).
  • Self in impl signatures names the impl’s target under the impl’s substitution: -> Self returns, Self { .. } constructs.
  • An inherent impl may not carry an interface’s name anywhere — there is no for clause to spell.

The wrapper route — manufacturing a member set

Primitives and composites can never satisfy (no inherent members, no way to add one — impl i32 { .. } diagnoses). The route in is a newtype class: a one-field wrapper whose inherent impl carries the members, manufactured explicitly at every call site:

pub interface Encodable {
    fn encode(self) -> str;
}

class JsonI64(i64);

impl JsonI64 {
    pub fn encode(self) -> str { return str(self.inner); }
}

fn dump(x: Encodable) -> str { return x.encode(); }

entry fn main() {
    let s: str = dump(JsonI64(64));   // spelled manufacture
}
  • dump(JsonI64(64)) — ✓ spelled, sound, per-call. The standard library’s json package spells exactly this shape for real (encodeJson(JsonI64(64)) — see core and the swappable packages).
  • dump(64) — ✗ forever. No auto-insertion exists at any layer: the constructor call IS the manufacture, and its spelling is the audit trail.
  • Wrappers compose: a generic wrapper’s bound checks at instantiation — class SWrap<T requires Encodable> { v: Vec<T>; } admits only instantiations whose argument satisfies, and the wrapper’s own members let SWrap satisfy in turn (recursive wrappers are legal).
  • The standard library’s wrapper families (JsonI64/JsonF64/…, ArrFlow/VecFlow/…) are exactly this shape — see core and the swappable packages.

Using an interface — the four forms

use pouch::{ Vec };
use ink::{ Logger };

pub interface Shape { fn area(self) -> f64; }

class Circle { r: f64; }
class Square { side: f64; }

impl Circle { pub fn area(self) -> f64 { return 3.14159 * self.r * self.r; } }
impl Square { pub fn area(self) -> f64 { return self.side * self.side; } }

fn dump(x: Shape) -> f64 {            // 1. interface-typed parameter
    return x.area();
}

entry fn main() {
    let log = Logger("shapes");

    dump(Circle { r: 1.0 });          // 2. the boundary checks the member set

    let s: Shape = Square { side: 2.0 };   // 3. satisfaction assertion

    let mut shapes: Vec<Shape> = Vec::new();  // 4. heterogeneous: itable boxes
    shapes.push(Circle { r: 1.0 });
    shapes.push(Square { side: 3.0 });
    let mut total: f64 = 0.0;
    for (let sh of shapes) { total += sh.area(); }
    log.info(f"total={total}");
}
total=12.14159

An interface-typed value is a reference to a real cell that still carries its exact class. Passing a concrete value at an interface-typed position is implicit and allocates nothing; the compiler checks the member set at that boundary and moves on — there is no widening relation to maintain and no registry row to consult. An interface-typed value cannot be downcast: use it through the interface, or erase explicitly through opaque.

Dispatch — the two-rule law

Every method call compiles under exactly one of two rules; the rule is a property of the call site, fixed at compile time.

  • Static — the call site names exactly one concrete type; the call binds directly to the member, no table hop:
    • a concrete receiver — c.area() on c: Circle;
    • an interface-typed local of single concrete origin — let s: Shape = Point { .. }; s.area() binds straight to Point’s member;
    • an interface-typed parameter — the callee specializes per concrete argument type (one clone per argument type — finite, terminating), so an interface parameter is an implicit generic bound;
    • a monomorphized generic — inside fn first<T>(..), T’s members are static per instantiation.
  • Itable — the receiver is interface-typed with multiple possible concrete origins; the call consults the value’s itable — the per-(concrete type × interface) method table:
    • heterogeneous container elements — for (s of shapes) over a Vec<Shape>;
    • interface-typed field/element loads;
    • branch-merged origins — let s = if (c) { a } else { b }; where the arms carry different concretes into one interface-typed binding.

The itable rows are synthesized at the boxing sites where satisfaction was proved — the same boundary check that admitted the value fills the row. Origin counting is conservative: any merge, indirection load, or cross-function flow counts as multiple. Mis-analysis cannot produce wrong code — an uncertain origin costs an itable hop, never a wrong static bind.

The use-both gate: x.iface_member() requires both names at the call site’s module — the type (by declaration or use) and the interface (use). A call through an interface no use names is an error — “use I to call its methods on T” — so a foreign interface can never silently change what a call site means.

Type tests — is

expr is Type → bool, at relational precedence, non-associative. The right-hand side is a naming position: a concrete type or a bare interface name/instantiation.

  • Concrete RHS — exact-type test: true when the value’s exact class or struct is T. With no inheritance this is a single descriptor lookup.
  • Interface RHS — capability probe: true when the value’s concrete type has itable fills for that interface — which is exactly when the value was satisfaction-boxed somewhere (k is Serializable).
  • No flow sensitivity: if (x is Shape) { .. } grants nothing — no narrowing, no widening. The keyword answers; it does not admit.
  • Static folds: when the receiver’s static type already answers, the result is a compile-time constant, with an always-true/false lint. On an exact receiver the member set decides at compile time.
  • is is total: never traps, yields only bool. The same descriptor that answers the itable answers the probe — one runtime truth per value.

The iteration protocol — the [iterable] marker

A type is iterable when an inherent impl marks a member [iterable]:

use ink::{ Logger };

class CountUp {
    n: i32;
}

impl CountUp {
    pub fn new(n: i32) -> Self { return Self { n: n }; }

    [iterable] pub fn iterate(self, emit: fn(i32) -> bool) {
        for (let mut i = 1; i <= self.n; i += 1) {
            if (!emit(i)) { return; }
        }
    }
}

entry fn main() {
    let log = Logger("t");
    for (let v of CountUp::new(3)) {
        log.info(f"tick {v}");
    }
}
tick 1
tick 2
tick 3

The contract’s shape: fn <free>(self, emit: fn(E) -> bool) — the member’s NAME IS FREE (the bracket designates, never the spelling), and the element type E falls out of the marked member’s own emit parameter. for (v of it) { body } calls that ONE designated member — it.<member>(emit) — with a synthetic closure: the body runs, then emit returns true; break returns false (stopping the iteration); continue returns true immediately; a return inside the body stops the iteration (not the enclosing function). The loop variable is the closure’s parameter — a fresh binding per iteration; captured enclosing locals are copied by value at the desugar, so accumulate through a shared cell or a method. The builtin sequences ([T], Vec<T>, str, bytes) keep their fused index loops and never reach the marker. An enum value iterates the same way — a marked member on the enum’s impl makes for (let v of c) walk whatever it emits (see Enums).

Engine contracts — markers and closed classes

The engine’s own contracts stand alone — they are neither interfaces nor user-visible polymorphism, and they share no machinery with the member-set law. Two mechanisms, one job each:

The bracket markers — [disposal], [iterable], and [constructor] designate an inherent impl member. The parser accepts any contextual word in the brackets; the checker validates the engine’s CLOSED set, at most one member per contract per class, inherent-members-only, and each contract’s signature. The descriptor ABI is a designated slot per class — the engine’s release path and the for-of weave read their slot directly, never an itable lookup; [constructor]’s slot is bound at the call site — the call form Type(..) resolves to the designated member:

impl Db {
    [disposal] fn dispose_db(mut self, cx: DisposalContext) {  // name FREE —
        self.file.close();                                      // the bracket
    }                                                           // designates
}

impl Rows {
    [iterable] fn iterate(self, emit: fn(Row) -> bool) { .. }   // for-of reads
}                                                               // this slot

impl Point {
    [constructor] fn from_xy(x: f32, y: f32) -> Self { .. }     // Point(..)
}                                                               // binds this slot

[disposal]’s contract: fn <free>(mut self, cx: DisposalContext) — the engine calls it when a value of the type reaches refcount zero (the Rc heap); the target must be a CONCRETE struct or class (the row keys the cell’s type id). [iterable]’s contract is the iteration protocol above. [constructor]’s contract: fn <free>(..) -> Self (or ?Self) on a class’s inherent impl — the one user-invoked surface: Type(..) lowers byte-identically to the designated member call, the seal rides the method’s pub, and newtypes are refused (their positional mint already IS Name(v)) — see Classes and constructors.

The closed builtin classes — Future<T> and RunContext carry the async protocol. Both are pub builtin (the import-gated spelling) and closed: no constructor, no impl lane, no user-callable members beyond RunContext’s two reads — a user type cannot BE a future or a cx. The walls hold by nominal closure: the member-set law cannot see engine identity, so closure is the only spelling of “engine-minted only”. The ENGINE weaves without them — async frames, the minted cx, and the fused for..of loops never consult user scope; source that SPELLS a name resolves it only through use core::{ .. } (a launcher’s f: Future<T>, downcast<Future<..>>, a cx probe in an async body — see Async and await, host fns and declaration files, and the Rc heap).

Accepted debts

The model trades two guarantees for its one mechanism, on purpose:

  • Shape-equal satisfaction. Two types with public members of the same shapes both satisfy an interface, whether or not either author intended it. There is no opt-in to fence this — the mitigation is convention (distinct member shapes, spelled receivers), documented here as accepted debt.
  • Wrappers at every primitive boundary. Because primitives never satisfy, every polymorphic hand-off of a primitive spells a wrapper construction — dump(JsonI64(64)), per call site. The spelling is the price of having no auto-insertion; the payback is that a wrapper’s presence is greppable and its cost is visible.
  • Bare containers never derive. A [T], a tuple, or a ?T will never grow members; container polymorphism always goes through an explicit wrapper family (JsonArr<T>, ArrFlow<T>, …), never a compiler-derived instance.

Equality

== is a builtin operator with no dynamic dispatch: primitives by value, str/bytes by content, everything else by cell identity — see Rc, dispose, and identity. Field-wise comparison is an interface-shaped contract implemented per type; it is not connected to ==.

Functions, closures, and generics

Function declarations, anonymous closures, and monomorphized generics with admission-only bounds.

Functions

use ink::{ Logger };

fn add(a: i32, b: i32) -> i32 {
    return a + b;
}

entry fn main() {
    let log = Logger("t");
    log.info(f"{add(2, 3)}");
}
5
  • Parameters are name: Type; a mutable parameter declares mut name — the callee’s permission to mutate the caller’s object (see Modules and visibility).
  • A function without a result arrow returns nil; return; (or falling off the end) is its return.
  • A function WITH a result arrow must return on every path: a body that can fall off the end diagnoses — missing return: 'f' is '-> str' but a path reaches the end of the body, naming the function and its arrow — instead of handing the caller a never-written value. Ending the body in a tail — the last expression, no ; (the block value law) — is the implicit return and counts: the analysis sees return, a value-producing body tail, break/continue, an if/else whose arms both return or produce the tail, an exhaustive when whose arms all return, and a while (true) with no break bound to it (the scan-loop shape); dead statements after a return are still just dead code. The same law covers the closure block form.
  • Methods are functions in impl blocks: the first parameter spelled self (or mut self) makes it an instance method; absence of self makes it a class method (see Classes and constructors).
  • entry fn publishes a function to the embedder (see Modules and visibility); async fn declares a suspending function (see Async and await).
  • Function types are first-class: fn apply(f: fn(i32) -> i32, v: i32) -> i32.

Closures

The closure spelling is an anonymous fn — block bodies, no arrow form:

use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let add = fn (a: i32, b: i32) -> i32 { return a + b; };
    let area_of = fn (r: f32) -> f32 {
        let sq = r * r;
        return sq * 3.14159265f32;
    };
    log.info(f"add={add(1, 2)} area={area_of(1)}");
}
add=3 area=3.1415927
  • An anonymous fn inhabits fn(P..) -> R directly — it is a value of the function type, copyable like a primitive.
  • The capture law: primitives, nil, and fn values copy — a captured scalar is the closure’s own slot, and reassigning it inside the closure never moves the original. Ref-headed values (records, Vec, arrays, str/bytes, ?T, enums) cross as handles: writes through the captured handle reach the shared cell, and so does a whole-value REASSIGNMENT — a captured-and-reassigned binding is promoted to a hidden shared-slot cell, so both frames stay linked for the binding’s whole scope (a stash-then-reassign, a reassign inside the closure, and the for..of loop variable — one binding reassigned per iteration, its write access gated by the header’s mut — all follow this one law). Refcounting keeps captures alive; a closure is itself a shared cell value.

Generics

use ink::{ Logger };

fn first<T>(xs: [T], fallback: T) -> T {
    if (xs.len() == 0) { return fallback; }
    return xs[0];
}

entry fn main() {
    let log = Logger("t");
    let head = first([10, 20], -1);      // first<i32>   — monomorphized
    let name = first(["a", "b"], "?");   // first<str>   — separate instance
    log.info(f"{head} {name}");
}
10 a
  • Generics monomorphize at compile time: each instantiation emits its own typed code. T infers from the arguments; explicit type arguments may be spelled at call sites, including method calls: self.st.get<T>(self).
  • Interface-typed arguments are ordinary arguments: a T instantiated at an interface type becomes a handle slot, satisfying no bound.
  • Generic parameters are unconstrained by default — you cannot call methods on a bare T. Pass values in, take an I-typed parameter, or spell the bound (T requires I).
  • There are no const-generic user parameters. The builtin surfaces fix their shapes ([T] is one type; lengths are runtime values).

Inline bounds — requires

gparam := Ident ('requires' bound)?
bound := Type ('|' Type)*

fn f<T requires A | B>(x: T) — an admission-only bound on fn, method, and class generic parameters (struct and interface generic parameters reject requires):

  • The bound gates which instantiations compile: enforcement is at every substitution-completing site (free-fn calls, method instantiation, impl-method enqueue). A failing instantiation diagnoses with the bound spelled out — “bool does not satisfy T requires i32 | str”.
  • Members may be concrete type names (satisfied by exact type identity), aliases (expanded first — see Type aliases and union bounds), a single interface (satisfied structurally — the member set checks where T is chosen), or a type union of concrete names/aliases. An interface member inside a union spelling is invalid — an interface bound stands alone.
  • Interface-typed values satisfy nothing: a T instantiated at an interface type fails any bound — only a concrete type with the members admits.
  • A non-union bound proves the widening: the body may widen a T-typed value into a bound-interface-typed slot (let w: Labeled = x;), but gains no method calls on bare T.
  • A union bound carries the whole-bound contract: a method call on a union-bounded value requires every member to provide the method — even a member that is never actually instantiated. Dispatch is untouched: each instantiation still binds the concrete member’s own method.
  • Bounds may reference the item’s other generics: fn hold<T, U requires [T]>(x: U).
  • Generic classes take bounds on their parameters — the bound records on the class descriptor and admits every instantiation: pub class HashMap<K requires i8 | .. | bytes, V> (see Builtin generic types).

opaque — erasure and downcast

opaque is the erasure-box engine primitive: a concrete type whose values box any value — forgetting the static type and keeping the runtime type for downcast only. Erasure is a call you write; the static type system never loosens, and rut has no cast syntax for it (as is the numeric cast only).

The surface

opaque is a declared engine primitive, ambient — no use gates it. Its entire API:

MemberMeaning
opaque(v)erasure: box any value; answers the opaque box
opaque::downcast<T>(o) -> ?Tchecked recovery: the box’s inner cell on a match, nil on a mismatch
unopaque<T>(o) -> Tthe erasure inverse: the typed value on a match, the bad-cast trap on a mismatch
x is opaquethe ordinary concrete test for the box type itself
use ink::{ Logger };

struct Point { x: i32; y: i32; }
enum Flavor { Sour, Sweet }

entry fn main() {
    let log = Logger("t");
    let box1 = opaque(Point { x: 1, y: 2 });   // erasure = call of the type name
    let p = opaque::downcast<Point>(box1);      // ?Point — the nullable
    when (p != nil) {
        true -> { log.info(f"point {p.x} {p.y}"); },
        else  -> { log.info("point: nil"); },
    }
    let wrong = opaque::downcast<i32>(opaque(Flavor::Sour));  // nil, no trap
    log.info(f"wrong == nil: {wrong == nil}");
}
point 1 2
wrong == nil: true

The laws

  • Construction is erasure. Every value can become opaque. Under the all-cells regime, boxing is zero-copy: the box stores the payload’s cell handle, so mutations through the original name are visible through the box (the alias law, see By-reference and nullable). A primitive payload copies the bits — value semantics where aliasing is unobservable:

    use ink::{ Logger };
    
    entry fn main() {
        let log = Logger("t");
        let mut n = 5;
        let b = opaque(n);    // a prim payload COPIES the bits
        n = 9;                // ...so the source moving stays out
        log.info(f"{opaque::downcast<i32>(b)} vs {n}");
    }
    
    5 vs 9
    
  • A match is the box’s own inner cell. The recovered ?T shares the box: writes through the recovery are the source’s, in both directions, through every holder. A primitive payload reads the copied value.

  • A mismatch is nil. There is no flag and no zero value — the miss is the nullable’s null; an unguarded dereference traps NilDeref, never a silent zero.

  • unopaque<T> is the inverse — the bad-cast lane. Where downcast<T> reports a miss as nil, unopaque<T>(b) -> T demands the sealed type: a match moves the payload out (the same inner-cell alias law — a record’s recovery writes through to the source), a mismatch is the BadUnbox trap naming both types:

    use ink::{ Logger };
    
    entry fn main() {
        let log = Logger("t");
        let b = opaque(7);
        let n: i32 = unopaque<i32>(b);
        log.info(f"{n}");
    }
    
    7
    

    The split is the language’s cast discipline: a mismatch the compiler can know is a compile error — interface objects are never boxed, so unopaque<Drawable> diagnoses without a run (the ONE sealed Future<T> exception rides the async lane); every other mismatch is a runtime fact of the erased content and traps, never a silent zero. Reach for downcast<T> when nil is a meaningful miss; reach for unopaque<T> when only the exact type will do.

  • The type argument must be concrete. An interface-typed type argument (opaque::downcast<Drawable>) is a compile error — interface-typed values have no recovery path by design.

  • The opaque-is law: is names the box, never the payload. o is T and o is I answer by the box — false for every payload type, concrete and interface alike. The one check that names what it is — o is opaque — is true. Recovery is downcast<T> only. On a non-box receiver, x is opaque is the ordinary concrete test for the box type.

    use ink::{ Logger };
    
    entry fn main() {
        let log = Logger("t");
        let b = opaque("hello");
        log.info(f"{b is str} {opaque::downcast<str>(b) != nil}");
    }
    
    false true
    
  • Boxes are never equal unless identical: opaque(v) == opaque(v) is false — two boxes, two cells. Box once, compare boxes.

  • Interface-typed values cannot be boxed: erasure takes a concrete value. Fixed arrays box fine; their identity covers the element type.

Composition and costs

opaque is a concrete primitive, not a lattice node: it composes in every type position trivially — Vec<opaque>, [opaque], fields, returns, parameters.

use ink::{ Logger };
use pouch::{ Vec };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let boxes: [opaque] = [opaque(Point { x: 3, y: 4 }), opaque("two")];
    let vec: Vec<opaque> = Vec::from([opaque(5)]);
    log.info(f"{boxes.len()} {vec.len()}");
}
2 1
  • The rut-side box is one small cell: the erased value rides inline in the box, and cell churn is recycled by the heap arena. Heap accounting charges the box’s cell, as always (see Reified types and layout).
  • The host side of the same surface: an embedder can mint the box over host data with no static rut shape. rut sees only the box — o is opaque is true, o is T misses for every rut T, and opaque::downcast<T> answers nil for every T (the miss is checked, never a trap). The host borrows the payload back typed, call-scoped and borrow-guarded.
  • An opaque box can do nothing until it is recovered — no methods, no fields, no format-string rendering. That is the difference from gradual typing: the erased-storage type for a hot loop is a smell; lints flag downcasts inside loop bodies and opaque parameters/returns on non-storage functions.

Reified types and layout

Every value’s type is available at runtime as a type descriptor. Slots are untagged 8-byte values; bytecode is typed, so hot paths carry no tags. This page is the language-facing contract; the descriptor itself is VM data, not a script value.

Where reification is language-facing

SurfaceMechanism
is type tests — concrete and interface RHSthe value cell’s descriptor (see Interfaces and dispatch)
opaque::downcast<T> recoverythe box’s recorded runtime type (see opaque — erasure and downcast)
type_id<T>()the compile-time type-identity constant
host boundary checksevery crossing is checked against the declared parameter type
diagnosticsstack traces and host tooling read the same descriptors

type_id<T>()

use ink::{ Logger };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let TID_POINT: u32 = type_id<Point>();
    log.info(f"{TID_POINT} eq={type_id<Point>() == TID_POINT}");
}
23 eq=true
  • type_id<T>() -> u32 — the identity of the instantiated type: unique per VM run, stable across modules, comparable only. Vec<f32> ≠ Vec<f64>; Point = Point wherever declared.
  • It is a compile-time constant — a load-time expression (legal in module-level let initializers, see Modules and visibility), folded from the type table, never executed.
  • Value size and alignment are implementation details, not a language surface.
  • Constructing a value from raw bytes is deliberately not provided: it could forge private fields and class invariants.

Value representation — slot arrays

Every struct and class value lives in a heap cell: header + (vtable, when the type has impls) + the payload.

  • The payload is a slot array: one untagged 8-byte slot per field, in declaration order. Primitive fields are widened into their slot (sign/zero-extended; a float is stored at the canonical 64-bit width); composite fields are cell-handle slots.
  • Visibility, generic parameters, and impl blocks add nothing — the payload depends only on the field list. Field access is by index; heap accounting charges fields × 8 bytes.
  • Buffers of primitive elements (Vec<f32>, [i32]) stay flat, packed to the element’s machine width; composite elements are one handle slot each — Vec<Point> stores one handle per element.
  • Enums are tagged cells (a tag slot plus a payload slot); dataless enum variants are immortal singleton cells.
  • Nullable ?prim element storage inside sequence backings is the raw payload plus a one-byte nil tag — no per-element cell.
  • bytes at the engine level is a u8 array cell; a str is an immutable, COW-shared UTF-8 block, and a slice of it is a small view cell (see String slicing and views).

Cells and vtables

RutCell := Header { rc, type id } VTable* Payload
VTable := { exact type id, dispose trampoline, interface member slots }
  • The exact runtime type lives in the cell (via the vtable when present, the header otherwise). Every cell is minted at construction with its vtable already attached.
  • Interface member ids are assigned globally per interface instantiation at compile time (Slice<Point> ≠ Slice<str>); a type’s vtable fills every slot of every interface instantiation it was satisfaction-boxed at — the fill is synthesized by the boxing site’s boundary check, and a type that never crosses an interface-typed boundary fills nothing.
  • Widening a composite to an interface I reuses the same cell and vtable: the interface-typed value is the handle plus the vtable pointer — no allocation, no copy. The vtable reserves no base-prefix room: there is no inheritance.
  • A call through an interface object is two loads and an indirect jump (the receiver’s vtable, the member slot). Interface members never devirtualize; inherent calls bind directly:
Op::CallI { recv, slot: 3, args }   // s.area() — itable slot 3
Op::Call     { func: "Circle$area", recv, args }   // c.area() — inherent

The type test

is with a concrete right-hand side lowers to: load the object’s exact type id, compare — a compile-time constant comparison when the static type already answers. The interface-RHS capability probe is: exact-type compare, then a flat scan of the descriptor’s filled itable slots — no inheritance chain to walk (see Interfaces and dispatch).

opaque interacts with exactly one of these reads: is reads the box’s own type, so every payload probe misses; only opaque::downcast<T>’s match test keeps reading the payload — the one legitimate see-through.

Boxing

Storing a value into an erasure box widens by the slot discipline: an integer box stores the 64-bit sign/zero-extended value, a float the 64-bit width. A kind check plus opaque::downcast<i64>() / downcast<f64>() / downcast<bool>() / downcast<str>() is therefore total in-branch: within the successful branch the value’s type is the exact concrete type, and everything downstream optimizes as if the value had never been erased.

String slicing and views

s.slice(from, to) — the O(1) string window. A slice is a view: no octets move or copy; the new str cell retains the original and records a byte window. Slicing is safe because str is immutable — a view can never observe mutation, so no pointer spelling is needed.

Surface

use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let s = "hello world";
    let w = s.slice(6, 11);        // "world" — no copy
    log.info(w);
}
world
  • from/to are codepoint indices, from <= to <= s.len(); bounds violations trap (same as an out-of-range index).
  • The window is recorded internally in byte offsets — codepoint bounds are resolved once at slice time (a UTF-8 walk only when the string is non-ASCII).
  • The result is an ordinary str: it prints, compares by content (==), iterates (for (c of w)), renders in f-strings, and len() counts its own codepoints. There is no separate view type on the surface — a slice of a str is a str.
  • Binding the slice shares it like every cell (see By-reference and nullable); str has no clone — a materializing copy happens only where an operation needs one (the append fast path, the host crossing).
use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let accented = "héllo!";
    log.info(f"{accented.len()} {accented.encode().len()} {accented.slice(1, 2)}");
}
6 7 é

The view cell

A slice mints a small view cell: { parent, off, len, ascii } — a retained handle to the owned parent string plus byte offsets into its block.

  • The view charges only its own header (~32 bytes) against the heap budget; the parent’s octets stay alive as long as any view does (deterministic destruction: view rc-0 → parent release).
  • View-of-view flattens: slicing a view combines offsets onto the root, so the parent is always an owned string and reads never chain.
  • The ascii flag is inherited from the root at slice time (a window of an ASCII string is ASCII).

Reads go through, writes never do

Every string operation reads through views transparently: content equality, codepoint count, indexing, iteration, f-string rendering, encode, and the host boundary (which copies the window’s bytes out).

The in-place append fast path (the out = f"{out}.." accumulator) is gated to owned, uniquely-referenced cells. Concatenating a view copies its bytes out — f"{view}!" yields a fresh owned string, and the view (and its parent) are unchanged. No operation can ever mutate through a string view. The accumulator is linear in the total output — core ships no string-builder class; a long-lived builder is the strbuild package’s StringBuilder (stdlib).

Cost model

OperationCost
s.slice(a, b)O(1) — one small cell + one retain (UTF-8 walk only for non-ASCII bounds)
read/compare/render a viewO(window) — same as any str
concat out / the host crossingO(window) — the materializing copy
parsing a 1 KiB line out of a 1 MiB bufferone 32-byte cell, zero copies

Digest-style workloads (splitting, tokenizing, windowing) stop copying entirely; peak heap reports the buffer once instead of per-piece.

[T] windows

v.slice(from, to) on a Vec<T> (and on [T]) mints a fixed-length window over the backing array, boxed as ?Vec<T> (the T → ?T coercion — see Builtin generic types). The window is the shared cell:

  • reads: w[i], w.len(), for (x of w) — auto-deref the nullable and go through the window (element i is parent[off + i], bounds are the window’s);
  • writes: w[i] = x (and compound assignment) hit the parent;
  • fixed-length: push/pop through a view trap — copy the elements out to grow (a for-push loop does it);
  • reslicing flattens onto the root backing (w.slice(a, b));
  • parent growth detaches: push re-backs the Vec with a fresh array; the window keeps pinning the old backing — the same aliasing rule Go slices have;
  • iteration yields the stored elements as-is under the sharing law: a cell element shares its cell, so a write through the loop variable hits the parent; primitive elements copy out as slots always do.

The asymmetry is deliberate: str/bytes are immutable, so their views carry no mutability law — purely an optimization plus a nicer parsing surface. Array windows change what writes mean, which is why they surface as an explicit ?Vec<T> value while the string view is invisible.

Type aliases and union bounds

type X = A; — the transparent alias. type X = A | B; — the bound-only union. fn f<T requires A | B>(..) — the inline admission-only bound. All three are compile-time gates: no IR, no runtime representation.

Type aliases

typealias := 'pub'? ('(' vis ')')? 'type' Ident '=' Type ';'
use ink::{ Logger };

type Meters = i64;
type Km = Meters;             // chains expand: Km is Meters is i64
type Row = [i32];

let trip: Km = 1500;          // Km is Meters is i64 — all one type

entry fn main() {
    let log = Logger("t");
    let plain: Meters = trip;     // no conversion: the alias IS the target
    log.info(f"{trip} {plain}");
}
1500 1500
  • Transparency by construction: X resolves to the target’s type identity everywhere — params, fields, returns, lets, bounds. A value of the alias and a value of the target are the same type; there is no conversion and no wrapper.
  • Chains expand through resolution; type A = B; type B = A; is a “recursive type alias” error. Forward references are legal.
  • The alias target validates at declaration: type Foo = NotAType; is an error whether or not Foo is used.
  • Non-generic: the head admits no members. type Vec2<T> = Vec<T>; is not expressible — a generic alias would be a type constructor, not a transparent name.
  • One name = one type: an alias may not share its name with an alias, enum, struct, class, or interface in the same module — the duplicate-name check is symmetric and fires in both orders.
  • Visibility: pub, pub(mod), pub(super), pub(self) all parse on type (see Modules and visibility). Like every name, the alias is usable in a consumer only when the consumer’s use names it.

Union aliases — bound-only

unionalias := typealias   // with Type spelled `A | B`
bound      := Type ('|' Type)*
type Num = i32 | str;    // legal — here and in requires bounds ONLY
  • The union exists only in the type grammar; the compiler never interns a union runtime kind. There is no runtime union value, no subtyping, and no is/when support over unions (heterogeneous data goes through interfaces — see Interfaces and dispatch — or enums, see Enums).
  • Value positions reject unions: a union (or a union-alias name) in a param/field/return/let/is position is diagnosed as bound-only.
  • | continues a completed type as a union only where unions are legal — the alias target and requires bounds — so x as u32 | y keeps spelling the binary operator.
  • Union aliases are module-local: never exported; a cross-module use fails as an unknown type.

Inline requires — the admission-only bound

gparam := Ident ('requires' bound)?
use ink::{ Logger };

interface Labeled { fn label(self) -> str; }
struct Ridge { depth: i32; }
struct Trench { depth: i32; }

impl Ridge { fn label(self) -> str { return "ridge"; } }
impl Trench { fn label(self) -> str { return "trench"; } }

fn name<T requires Labeled>(x: T) -> str {
    let w: Labeled = x;      // the widening compiles BECAUSE the bound holds
    return w.label();
}

fn kind<T requires Ridge | Trench>(x: T) -> str { return "geo"; }

entry fn main() {
    let log = Logger("t");
    log.info(f"{name(Ridge { depth: 3 })} {kind(Trench { depth: 1 })}");
}
ridge geo
  • Members may be concrete type names (satisfied by exact type identity at instantiation), aliases (expanded before detection), or a type union of those. Type names only in a union: an interface member inside a union spelling parses but diagnoses at admission — an interface bound must stand alone.

  • Enforcement at every substitution-completing site: free-fn calls, direct and instance method instantiation, and impl-method enqueue. A failing instantiation diagnoses with the bound spelled out: “bool does not satisfy T requires i32 | str — no matching type in the bound”. An interface bound fails with the member set: “T’s instantiation does not satisfy Labeled: no member label”.

  • Interface-typed values satisfy nothing: instantiating T at an interface type fails any bound — only a concrete type with the members admits.

  • Bounds may reference the item’s other generics: fn hold<T, U requires [T]>(x: U) — members resolve under the call-site substitution.

  • Admission-only — except the union’s whole-bound contract. A non-union bound grants NO method calls on bare T; what it proves is the widening into a bound-member-typed slot. A union bound carries the whole-bound method contract: a method call on a union-bounded value is checked against the WHOLE bound — every member must provide the method through its own impls — even when the offending member is never instantiated. Dispatch is untouched: each instantiation still binds the concrete member’s own impl.

  • Provenance — a value is known to carry a union-bounded type when it is: a generic parameter, a let whose annotation spells the generic, a copy of either, or a direct self.f field whose declared type spells the generic. Provenance rides inlining and is cleared when the name rebinds. Documented holes (the gate under-fires, never over-fires): closure bodies compile with fresh provenance; destructuring carries none; a shadowing rebind resets it.

  • Class generics take bounds; struct/interface/surface generics do not:

    pub class HashMap<K requires i8 | .. | str | bytes, V> { .. }
    

    The bound records on the class descriptor and admits every instantiation: a key type outside the set fails at the instantiation site (see Builtin generic types). Inside the class’s method bodies the union contract applies through the class’s own requires.

See also Functions, closures, and generics for the bound grammar in context.

By-reference and nullable

The sharing regime, the nullable ?T, identity ==, and the one copy escape hatch. These laws landed together and they are not optional: every other page assumes them.

The sharing regime

  • Primitives and fn values copy (immediate slots): u8..u64, i8..i64, f32/f64, bool, and closures’ function values.
  • Every cell type shares its cell: str, bytes, struct/class records, [T] arrays, enums, interface objects, opaque boxes, closures’ captured cells, and ?T boxes.
  • let b = a — any cell type — is an O(1) handle move (retain new, release old). Mutation through any alias is visible through all of them.
use ink::{ Logger };

struct Point { x: i32; y: i32; }

entry fn main() {
    let log = Logger("t");
    let mut p = Point { x: 1, y: 2 };
    let q = p;              // SHARE: one cell, two names — no copy
    p.x = 4;                // q.x is 4 now
    log.info(f"{q.x}");
}
4
  • Writing is gated by the mut-binding law, never by the sharing: a let binding is a read-only view; let mut grants write access to the object it holds (see Modules and visibility). Parameters declare the same intent: fn step(mut p: Point) writes the caller’s point; fn area(p: Point) promises not to.
  • A T stored into a ?T slot boxes once — the box aliases the payload’s cell (a share); primitives and nil copy the bits. There is no deref-on-load/box-on-store special case anywhere.
  • Primitive elements in a [T] stay flat slots; composite elements are handle slots. for (let x of xs) yields the shared element, not a per-element copy — a cell element writes through to the sequence, and writes through it are gated by the header’s mut, like any binding.
  • The repeat [v; n] retains the handle n times: every slot aliases the one cell. The repeat never copies.

Copy-by-value is unobservable except through the two legal effects: aliasing (writes visible through every binding) and == (below).

?T — the nullable type

?T is a nil-able cell — a one-slot box. nil is the null literal; dereferencing it traps NilDeref — never a silent read.

Grammar — prefix only, binds tightest

SpellingTypeReading
?TT | nilthe nullable
[?T][T | nil]array of nullables
?[T][T] | nilnullable array
??Tchainedthe same runtime box, unwrapped transitively

There is no postfix T? and no *T — each is a diagnosed error naming ?T. In expression position, *x/&x diagnose: “bindings share by reference now — pass x directly” (binary */& operators are untouched).

Coercions and uses

T → ?T boxes; ?T → T derefs — both implicit at the expected-type position, transitive through ??T:

  • Auto-deref covers every value position: p.x, p.m(..), p[i], for (x of p), arithmetic on p’s payload.
  • p == nil / p != nil compare against the null slot; guard before use. The trap is the bug-catcher, not the semantics.
  • A ?T binding IS the cell reference: writes through it hit the shared cell (a nudge(mut pt: ?Point) moves the caller’s point).
  • nil typing: a context-free nil has type nil; in an expected-?T position it types as that ?T — so let p: ?Node = nil and a left: nil field in a literal just work. Absence reads plainly: a lookup returns ?V, and nil means “not found”.
  • When the cell’s refcount reaches zero, the engine runs the type’s [disposal] member — the cell-death hook (see Rc, dispose, and identity).
  • Across the host boundary ?T crosses nil-flattened when its element crosses — an entry fn -> (?T, err) is a first-class host answer.

== — identity for cells, content for text

Operand type== meansLowering
numeric / bool primitivesvalueIEEE 754 for floats (NaN != NaN, -0.0 == 0.0)
strcontent (codepoints)content compare
bytescontent (octets)content compare
everything else — records, arrays, enums, closures, interface objects, opaque, ?Tcell identitythe raw slot compare

[1, 2] == [1, 2] is false — two cells. Identity is O(1) with no deep walk; compare content where content is the contract (a loop, or a hash/eq interface contract for keys). ?T == ?T is slot identity: two nils are equal, a null and a box are not. See Rc, dispose, and identity for the full law and the lint on obviously-fresh composites.

bytes::clone() — the one copy escape hatch

b.clone() -> bytes mints a fresh buffer with b’s octets — a one-shot deep copy, the only copy syntax in the language. bytes::from(a) also deep-copies. Every other type shares on binding, and a divergent value of any other type is unreachable — build a new one instead.

use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let header = bytes::from([1, 2, 3]);
    let alias = header;              // shares: one buffer, two names
    let diverged = header.clone();   // a fresh buffer, same octets
    log.info(f"{alias == header} {diverged == header}");
}
true true

Containers under sharing

  • Vec<T> backs on buf: [?T] — [nil; cap] is the generic zero (nil is the slot’s zero); push takes the T → ?T-boxed handle; loads yield the ?T (uses auto-deref). See Builtin generic types.
  • Keyed collections: get(k) -> ?V — nil = absent, a hit answers the stored cell (the aliasing law: two gets of one key name one cell until a replace re-stores).
  • Array windows (v.slice(a, b) -> ?Vec<T>) are the shared cell: writes through the window hit the parent (see String slicing and views).
  • Erasure rides the same laws: opaque(v) aliases the payload’s cell, and opaque::downcast<T>(o)’s match is the box’s own inner cell (see opaque — erasure and downcast).

The answer channel

(?T, err) — concretely (value, ok) / (T, str) — is THE answer channel. The convention is law: empty err + a value = success; empty err + nil = “not found”; non-empty err = “failed”. The err channel disambiguates a legitimately-absent value from a failure. The exactly-one-non-nil invariant is the caller’s convention — the engine types the components and decodes them; it does not police the combination. A return-position destructure (let (v, ok) = f();) is optimized so the pair mints no cell where it is used as a pair.

The Rc heap and destructors

rut’s heap is reference-counted. When an object’s strong count reaches zero it is destroyed immediately, at a deterministic point in the program. There is no collector: strong cycles leak by design — weak references are the answer. Every VM owns one heap on one thread, so the counters are plain cells with no atomics and no locks.

The cell model

Everything except primitives and fn values is a heap cell:

Inline (moved by plain copy)Heap cells (refcounted handles)
u8..u64, i8..i64, u/isize, f32, f64, bool, nilstr, bytes, Vec<T>, [T], enums, structs, classes, interface objects, opaque boxes, host boxes, ?T boxes, coroutine frames

Assignment, argument passing, and returning copy the handle (retain), never the bytes. Mutation through one alias is visible through every alias — reference semantics is the one default regime; there is no eager copy anywhere. bytes::clone() is the only copy escape hatch.

There is no borrow syntax and no lifetimes: a handle simply keeps its referent alive, so nothing dangles.

Refcounting rules

The compiler knows the static type of every register, so ref-aware ops are emitted only where a reference can flow:

  • Primitives and fn values move with a plain move — no counting.
  • References move with a ref move — retain the new, release the old; both steps are exact.
  • Function boundaries pass references in registers; call/return sequences emit the paired inc/dec. A loop over a Vec<f64> does no per-element counting.
  • Overflow: an increment past u32::MAX immortalizes the object — the count is pinned to the 0 sentinel (the same value interned literals use) — a deliberate, logged leak instead of unsoundness.
  • Debug builds assert the full counter discipline: retain/release pairing, no underflow, no double destruction.

Destruction — the [disposal] marker

A type opts into destructor code by marking an inherent member [disposal] (see Rc, dispose, and identity for the marker’s surface — the name is free, the bracket designates):

use core::{ DisposalContext };
use ink::{ Logger };

struct Audit { log: Logger; n: i32; }

impl Audit {
    [disposal] fn release(mut self, cx: DisposalContext) {
        self.log.info(f"released {self.n} octets");
    }
}

fn work() {
    let log = Logger("work");
    let buf = Audit { log: log, n: 4 };
    log.info("working — 4 octets in flight");
}   // buf's count reaches zero here

entry fn main() {
    work();   // the boundary drains: dispose runs after main's body
}
working — 4 octets in flight
released 4 octets

Laws:

  • The engine calls dispose(mut self, cx: DisposalContext) exactly once per cell death — when the strong count reaches zero. Types without a [disposal] member release straight to the field walk.
  • The call runs at a call boundary, not re-entrantly inside the release: death pins the cell and queues it, and the interpreter drains the queue at its call boundaries — the root call’s end for sync code, each drive for the async weave — passing the pinned cell as self with a freshly minted cx.
  • A dispose body may itself release references (a field walk that kills a child whose own dispose is next): the drain loops until the queue stays empty.
  • The context cx is engine-minted and empty today; it grows additively, never by touching the marker’s signature.
  • Cancellation drops locals at the suspension point through the same machinery (launched futures) — no special case.

Note the difference from finalizer-based runtimes: dispose always runs, exactly once, at a knowable point. There is no “later or never”.

Destruction order

When a cell’s strong count reaches zero:

  1. Every Weak box watching the cell is nulled before any user code runs — a dispose body that calls upgrade() sees nil, deterministically (weak references).
  2. The type’s queued dispose body runs for cells whose type carries a [disposal] member (pinned cell, then released).
  3. Ref-typed children are released recursively: record fields in declaration order, sum payloads, array elements, opaque box inners, closure captures. The walk is driven by a per-type release plan built once from the type table.
  4. Host box payloads run their Rust Drop at the same point — sockets, files, and textures die with the last handle, not “sometime later”. An opt-in finalize hook (no-op default) runs before the payload’s Drop; a rut value the payload held releases through the same walk.
  5. The block store frees the cell’s variable-size payload; the slot returns to the arena free list and is reused by the next mint (the VM heap).

Buffers, strings, and views

  • Primitive-element [T] buffers stay flat: a [T] over numeric or bool element types stores raw values inline behind the header. Element copies in and out are plain moves — no counting. This is the one place the everything-is-a-cell law does not reach.
  • Vec<T> is not flat: its backing is buf: [?T], so element traffic crosses nullable handles. push/pop/set emit the paired retain/release.
  • Composite-element buffers store handles: [Point] and Vec<Point> hold one cell pointer per element; the buffer itself is the counted unit.
  • [T] is a fixed-length cell; N is a compile-time constant and part of the type’s identity. Fixed-array literals that fold at compile time become immortal constant-pool cells.
  • Slice<T> view cells hold a handle to their owner plus off/len — never a pointer into the data block. Views dispatch through the owner, so growth keeps existing views valid; indexing bounds-checks against len ∩ owner len and traps out of range instead of reading garbage. Slices are born only from implicit widening at an argument site; they are not nameable or constructible in script.
  • str is immutable: interned literals live in the module’s constant pool (immortal); runtime-built strings are ordinary cells whose buffers are internally copy-on-write — an implementation detail no program can observe, because str has no mutation API.
  • No interior pointers exist anywhere, which is what keeps every heap walk a simple typed walk.

Internals

Header:  rc: u32        // strong count; u32::MAX = immortal sentinel
         ty: u32        // index into the type table
         bytes: u32     // accounted bytes, refunded on release

The weak lists (referent slot word → its WeakBox cells) and the disposal-armed markers (cells whose dispose is queued or has run) are arena side tables, not header words.

Cell kinds: string, vec (growable), array (fixed), slice view, record (every user struct/class — vtable + payload slots), enum (tag + payload slots; dataless variants are immortal singletons), opaque box, weak box, and the coroutine frames the async weave mints. Reified layouts are covered in reified types and layout.

The engine’s two counting ops are exact and total:

fn retain(&self, p: Slot) { /* rc += 1 */ }

fn release(&self, p: Slot) {
    let n = rc(p) - 1;                 // underflow is a bug: assert
    set_rc(p, n);
    if n == 0 { destroy(p); }          // order above; no suspect list
}

Destruction is fully deterministic under the virtual clock, so a drop order reproduces exactly in tests. Identity and equality semantics for cell values are covered in Rc, dispose, and identity.

Weak references and the cycle collector

Reference counting frees an object when its strong count reaches zero (the Rc heap). A strong cycle never reaches zero — so strong cycles leak until the Vm is dropped. rut states this as a rule instead of hiding it behind a collector: the heap stays trivially simple, destructors stay exactly deterministic, and Weak<T> gives the two shapes that cause accidental cycles — back-pointers and caches — a first-class answer.

Cycle policy

RuleContent
No collectorNo mark bits, no colors, no pauses beyond destructor chains. What leaks leaks wholly and predictably.
Resource holdersClasses holding resources ([disposal] members, host boxes) must not participate in strong cycles.
Back-pointersParent/child and observer shapes take a Weak back-pointer.
Pure-data cyclesHarmless — memory only, freed wholesale at teardown.
LintsThe compiler may warn on obvious self-reference (a value stored into its own field through a handle path); general cycle detection stays out of scope.

Cycles are possible through ordinary struct fields (next: ?Node back-pointers) as well as through collections.

Weak<T>

Weak is a builtin generic class with one member. A weak box is a side cell holding the referent’s slot word, unretained — a weak never keeps anything alive, and a path through a Weak does not close a strong cycle.

Weak is one of core’s import-gated builtin names: spell use core::{ Weak }; to bring the class in (core and the swappable packages). A bare Weak does not compile — the diagnostic is `Weak` is not in scope — `use core::{ Weak }`.

use core::{ Weak };
use ink::{ Logger };

class Node {
    value: u32;
    next: ?Node;          // strong — keeps the tail alive
}

impl Node {
    pub fn new(value: u32) -> Self { return Self { value: value, next: nil }; }
}

fn use_node(n: Node) {
    let log = Logger("t");
    log.info(f"node {n.value}");
}

entry fn main() {
    let n = Node::new(1);
    let w = Weak::new(n);        // Weak<Node>; T infers from n
    let b = w.upgrade();        // ?Node — a live handle
    if (b != nil) {
        use_node(b);
    }
}
node 1

Construction — Weak::new(v)

  • Construction is a class method with admission at the instantiation: T must be a reference type. Weak<i32> and Weak::new(some_fn) diagnose; primitives and fn values refuse.

  • Works over any cell: a class, struct, Vec, [T], enum, str, bytes, a user opaque box, or a host box.

  • Weak::new(nil) traps (“weak on nil”).

  • Weak::new(v) consumes the argument’s temporary and nulls its register (the engine’s one consuming op): the weak observes the binding’s lifetime, never a temporary’s. Weak::new(make()) watches a referent that dies as soon as the temporary is released — upgrade() answers nil. Bind the value first:

    use core::{ Weak };
    use ink::{ Logger };
    
    struct Payload { n: i32; }
    
    fn make() -> Payload { return Payload { n: 1 }; }
    
    entry fn main() {
        let log = Logger("t");
        let v = make();
        let w = Weak::new(v);  // watches the binding v — lives as long as v does
        log.info(f"{w.upgrade() != nil}");
    }
    
    true
    
  • Two Weak::new(v) of one v are distinct boxes; == on weak boxes is identity, and two weaks of the same referent are not equal to each other.

Upgrade — w.upgrade() -> ?T

  • A dead-check plus retain: a live referent is retained into a fresh ?T handle; a dead one answers the null slot — true nil, never a box containing nil.
  • On Weak<?U> (legal) the answer is ??U — the sticky-? law (by-reference and nullable).
  • upgrade() on nil traps (“upgrade on nil”); on a non-weak value it traps (“upgrade on non-weak”).

Deterministic ordering

The referent’s death nulls every weak box before anything that runs user code — before the dispose pin, before payload teardown. A dispose body that calls upgrade() sees nil, with no window:

use core::{ DisposalContext, Weak };

class Node  { child: ?Node; }
class Child { back: ?Weak<Node>; }   // the observer's weak back-pointer

impl Child {
    [disposal] fn release(mut self, cx: DisposalContext) {
        // the parent's death released self through the field walk,
        // and the parent's weak list was nulled before any of that
        // user code ran — the back-pointer reads nil from in here:
        if (self.back.upgrade() == nil) { /* always taken here */ }
    }
}

Weak references are not destructors — they observe; they never run code. They exist for caches, observers, and back-pointers.

Leak reporting

  • rc discipline is asserted in debug builds: retain/release pairing, no underflow, no double destruction.
  • Shutdown leak report: at Vm::drop, surviving non-immortal objects are reported grouped by type, with allocation sites in debug builds — the primary tool for finding leaked cycles. Deterministic execution means a leak reproduces exactly.
  • The host can read live usage at any time (vm.heap_usage(), resource limits).
  • Fuzz targets assert no crash and that destructor counts match allocations minus reported survivors.

Status: the Weak<T> surface above is shipped; the shutdown report and per-type live counts are the specified diagnostics tier.

If real code ever demands more, a collector could return only as a separate, opt-in module — the heap assumes nothing of it today.

The VM heap

Host Rust code may use std freely. The VM’s heap is the exception: every byte that backs a rut value comes from the VM’s own heap manager — accounted, budgeted, pooled, and freed wholesale at Vm drop. No rut allocation is an untracked Box/Vec somewhere in Rust land. The point of the discipline:

  1. Caps — an embedder says “this script gets N bytes” and gets a resumable OutOfMemory trap, not an OS abort (resource limits).
  2. Answers — vm.heap_usage() is exact only if every allocation is accounted.
  3. Teardown — Vm::drop frees the heap in slab units; nothing per-object leaks past the VM.
  4. Leak reporting — the shutdown leak report (weak references) walks the heap’s own headers, which requires that every value have one.

What the VM manages

Managed by the VM heapThe host’s business
every cell — structs, classes, enums, opaque boxes, weak boxes (the Rc heap)module binaries and maps (read zero-copy, never copied into the heap)
variable-size payload blocks — Vec/[T] data, string buffersthe shared type table
coroutine frames and register blocks (async and await)native-module state
the ready ring, the frame pool, the timer wheelhost-side handles, caches, futures, channel buffers at the boundary

Host-side Rust state is the host’s memory, charged to the host.

The manager surface

impl Heap {
    /// The one allocation path for rut values.
    /// Over budget -> Err(Trap::OutOfMemory); never aborts.
    fn alloc(&mut self, size: u32, align: u8, ty: TypeId)
        -> Result<NonNull<Header>, Trap>;

    fn usage_bytes(&self) -> u64;     // feeds vm.heap_usage()
    fn peak_bytes(&self) -> u64;      // high-water mark: vm.heap_peak()
    fn set_limit(&self, limit: Option<u64>);  // live budget change
}

Every route that materializes a rut value goes through it: cell mint, Vec growth, string concatenation, frame-pool growth, opaque store inserts. The contributor rule: an allocation path that materializes a rut value and does not flow through alloc is a bug — the budget would not bind, heap_usage would lie, and the leak report would miss it.

Accounting checks run before any write: a failed allocation leaves the heap byte-identical to its state before the op, and the trap is resumable (resource limits).

Allocation strategy

  • Fixed-size cell slots in the arena. Cells are one fixed-size record carved from 1024-slot chunks with a free list; a dead slot is reused by the next mint. Reuse is invisible except in heap_usage.
  • The block store. Every variable-size payload — string octets, array element runs — lives in a block carved from size-classed pages the VM owns:
    • Size classes 16 B … 2 KiB (multiples of 8); small blocks come from 32 KiB pages via per-class free lists plus a single-slot LIFO cache for the churn pattern (a temp dies, the same size is minted again).
    • In-place growth within a class keeps append-accumulation loops linear; the block header carries the class-rounded capacity, so free re-derives the class with no side table.
    • Large blocks (> 2 KiB) get dedicated allocations, freed wholesale.
    • Blocks are 1:1 with their cell (the cell is the counted unit) and never move, so a raw &[u8] into the store stays valid for the cell’s life.
  • Immortal singletons. Interned string literals and dataless enum variants live in a slab freed only at Vm drop; they carry the rc == 0 sentinel.
  • The opaque store. Every rut opaque value lives in a slab of two-kind entries (rut value / host payload) with its own borrow guards; entries charge their bytes on insert and refund on death, so the budget and the receipts stay honest.
  • No compaction. Non-moving keeps host borrows into Vec buffers sound and freelists trivial.
  • Cells are addressed by raw pointer in the slot word. A 32-bit handle design was prototyped and reverted on measurement: ref-heavy workloads paid +8–15% for the decode chain per slot read.

Deterministic teardown

Teardown mirrors the destruction rules: the host drops its references, releases run inline (the Rc heap), and Vm::drop frees the survivors wholesale — leaked cycles included — after emitting the leak report. The heap never outlives the Vm, and no rut cell can outlive the heap.

let mut vm = Vm::builder().compiled(compiled).build()?;
vm.call::<_, ()>("main", ())?;
println!("used {} bytes (peak {})", vm.heap_usage(), vm.heap_peak());
// dropping `vm` frees every remaining slab

Resource limits and fuel

Two knobs make rut safe for third-party code: a heap budget and fuel. Both are enforced as resumable traps, both are set at construction, and both bind on the VM’s own accounting (the VM heap) — not on the OS.

pub struct Limits {
    pub fuel: Option<u64>,             // None = unbounded ops
    pub heap_limit_bytes: Option<u64>, // None = host-enforced only
    pub interrupt_every: u32,          // check period; default 1024
}

The heap budget

What countseverything the VM heap tracks: cell headers + payloads, buffer blocks, string blocks, frames and register blocks, opaque store entries
What does notmodule binaries, the shared type table, host-side Rust state
Check pointsevery Heap::alloc route: cell mint, Vec growth (push reallocation), string concat, frame-pool growth, host crossing mints
On failureTrap::OutOfMemory — the check runs before any write, so the heap is byte-identical to its pre-op state; nothing is half-initialized
Resumptionthe frame is parked: raise the limit (Heap::set_limit), drop references and retry, or drop the VM
Observabilityvm.heap_usage() (live), vm.heap_peak() (high-water)

Vec growth charges the budget before the write; shrinking is never refunded (the accounting overcounts rather than undercounts).

Fuel

  • One unit per executed op; fuel counts down. The counter is decremented and checked on every op — interrupt_every meters the separate interrupt lane, not fuel.
  • Trap::OutOfFuel parks the frame exactly like any resumable stop: nothing is unwound. Resumption is vm.add_fuel(n) then vm.resume() — the frame is the loop state. Fuel is chosen at construction: add_fuel is a no-op on an unbounded machine, and the runtime budget is read-only — by design.
  • Fuel is the deterministic budget: the same program with the same fuel dies at the same op, every run — reproducible reports and hang proofs in tests.
  • Native fns run outside fuel. A hanging native is a host bug: keep native bodies non-blocking, or push blocking work to a thread through the host-futures lane (the host futures bridge).

The trap contract

TrapRaised byFrame stateResumption
OutOfMemoryheap budget exceeded at an allocation checkparked before the writeraise limit / free refs → resume()
OutOfFuelfuel reached 0 at a check pointparked at the exact pcadd_fuel(n) → resume()
let limits = Limits { fuel: Some(1_000_000),
                      heap_limit_bytes: Some(64 * 1024 * 1024),
                      interrupt_every: 1024 };
let mut vm = Vm::builder().compiled(compiled).limits(limits).build()?;

match vm.call::<_, ()>("main", ()) {
    Err(t) if t.name() == "OutOfFuel" => {
        vm.add_fuel(1_000_000);
        vm.resume::<()>()?;           // re-enters at the parked pc
    }
    r => { r?; }
}

The async layer’s resume granularity is the checkpoint, not the op: a drive that runs out of fuel parks the future’s frame, and a re-drive re-enters at the frame’s checkpoint state (async and await).

Hang detection

The host owns time; the recipes differ by embedder:

HostRecipe
UI / gamedrain the ready queue inside the frame loop; grant fuel per frame so a runaway script starves at the next check
wasm pagegrant finite fuel; a watchdog stops refueling — the parked frame dies at its next check
desktop servicea watchdog thread flips a flag the host honors between resume() calls; no joins, no signals
testsfinite fuel + the virtual clock (vm.set_now) → fully deterministic hang proofs

Anything blocking that cannot be bounded by fuel (IO, locks) belongs on a worker thread answering a Completer — the VM thread never blocks on it (the host futures bridge).

Fairness

Within one VM, the ready ring is round-robin: one greedy launched future cannot starve the rest of a queue drain indefinitely — each frame runs to its next park or completion, and fuel bounds each of those runs.

Async and await

rut’s concurrency is pull-based. An async fn compiles into the driven half of a hidden frame type — a cold future that only progresses when driven. There are no promises, no microtask queue, and no implicit scheduling: the host owns time. One noun (Future<T>, a closed builtin class), one consume law (await or launch — exactly one), one pender (sleep; an embedder may mount its own).

Push (promises)rut (poll)
createdstarts executing on the next microtaskcold — nothing runs until awaited or launched
completionpushes callbacks through a job queuenobody drives ⇒ nobody pays
allocationpromise + reactions per thenone hidden frame record per mint; locals are cell-backed
cancellationabort flag / never settlesabort() flags the frame; the probe at its checkpoint runs the drop path
host integrationthe host must drain a job queuethe host polls the VM: run_ready(), next_deadline()

Future<T> — the one async type

Every async producer answers the same type: an async fn call, an async { } block, sleep, select2, completer — all Future<..>, so await/select2/launch_future never ask “which kind”. Future<T> is a closed builtin class: no constructor, no impl lane, no user-callable members — a user type cannot BE a future (structural satisfaction cannot see engine identity, so nominal closure is the only spelling of “engine-minted only”). The hidden frame is representation; the handle is the surface.

async fn, async { }, and await

use ink::{ Logger };
use futures::{ launch_future, sleep };

async fn countdown(n: u32) -> u32 {
    let log = Logger("count");
    let mut i = n;
    while (i > 0) {
        await sleep(1000);            // the ONLY suspension point
        i -= 1;
        log.info(f"tick {i}");
    }
    return i;
}

entry fn main() {
    launch_future(countdown(3));      // trigger; receipt ignored
}
tick 2
tick 1
tick 0

async fn is genuine sugar — both sides of the law are writable programs:

async fn work() -> nil { BODY }
// ≡
fn work() -> Future<nil> {
    return async { BODY };
}

The async { } block is the primitive: one expression form (keyword before a block). Evaluating it mints the frame — the mint is pure, so an async block is legal in sync code (launch_future(async { .. }), a select2 arm); the frame runs when driven. Its type is Future<T> with T inferred from the block’s return statements (fn-body rules); an annotated position pins it (let f: Future<str> = async { .. }). The block’s reads capture the enclosing locals by value at the mint (the capture law: scalars copy, ref-headed handles share their cell), and a return inside the block answers the future — not any enclosing fn.

Rules:

  • The cx is injected, never spelled. The weave binds cx (a RunContext) in every async body; an async fn’s parameters are ordinary values — a spelled cx: RunContext diagnoses.
  • async fn f(..) -> T describes a value of type Future<T>. Calling it runs nothing (cold). It runs when the future is awaited or launched.
  • await is legal only inside an async body (an async fn or an async { } block), and its operand must be a Future<..> — plain type identity, since every producer mints the closed class.
  • A future is awaited or launched by exactly one driver; each path consumes it. Driving one frame from two paths is a disclosed misuse, not a soundness hole.
  • launch_future(launch_future(f)) is a type error: the receipt is not a Future (launched futures).
  • Async methods are not woven in this build — async points are free fns or async { } blocks inside sync methods (the standard HTTP face mints inside its methods).
  • Cancellation-by-drop: the probe at the resumed checkpoint branches to a drop path that releases the frame’s cell-backed locals (their [disposal] members run, the Rc heap), retires the state, and returns.

The cx protocol

RunContext — a closed builtin class, injected by the weave — carries two reads, usable as plain data inside any async body:

ReadAnswers
cx.checkpoint()this frame’s current resume state (a u32)
cx.cancelled()the frame’s abort flag

Cancellation is data the frame reads — never an exception it catches. (The weave’s own next_checkpoint edge is unspelled: the weave records each await’s resume state.)

The standard launcher set

Launchers are host surface — ordinary rut code over the closed Future class, provided by the rut/futures package (users may write their own the same way):

pub fn launch_future<T>(f: Future<T>) -> LaunchedFutureHandle<T>;
pub fn sleep(ms: u32) -> Future<nil>;
// LaunchedFutureHandle<T>: the receipt — one member, abort() -> bool

Each embedder offers rut/async_host (the rows __launch, __abort, __sleep, __sleep_yield) plus rut/futures, and installs the row bodies. A world that offers neither simply has no launcher; await still works inline.

The crossings cross as opaque: opaque(f) seals a frame on the way out, opaque::downcast<Future<nil>>(b) -> ?Future<nil> recovers it on the way in (opaque — erasure and downcast). sleep(ms) is literally that downcast over the engine’s minted sleep frame.

Host async fns declared in a declaration file — pub host async fn fetch(url: str) -> bytes; — mint the same cold frames; the embedder backs them with a Completer (the host futures bridge).

What the compiler emits

One async producer compiles into one code body over existing ops only — no new vocabulary:

  • a hidden frame record is the future:

    fieldcontent
    statethe checkpoint enum’s member singleton; null = completed or dropped
    cancelledthe abort flag
    awaiterthe frame awaiting this one
    pendingthe future this one parks on
    [4..]locals — every binding, cell-backed (an async block’s captures included)
  • a per-producer checkpoint enum whose member index is the resume state, dispatched with a branch table — the state field is the pc;

  • each await site: read the callee’s state; not done → drive one step (a call through the Future<T> class’s designated yield slot — the engine ABI, unspelled); still pending → store the awaiter/pending edges, set the state, and ret — suspension is a plain return whose caller reads the state field for the answer (Done | Parked);

  • the drop path: clear the pending edges, release ref locals in binding order, retire.

Locals are mirrored into the frame cell uniformly, so no liveness analysis decides which locals survive a park. A completed frame re-drive answers at the dispatch default (a silent retire). The awaiter/pending pair is one-directional — a driven frame re-enqueues its awaiter, and no cycle forms.

The driving loop

The VM owns the queues; the embedder owns the loop:

Engine APIMeaning
vm.launch(fut)enqueue a future (the queue owns one reference)
vm.cancel(fut) -> boolflag cancellation + re-enqueue; false when already retired
vm.drive(fut) -> Driveone drive step through the future’s designated yield slot; reads the state field
vm.arm_timer(deadline_ms, fut)arm a sleep deadline on the virtual clock
vm.now_ms() / vm.set_now(t)read / advance the deterministic virtual clock
vm.next_deadline() -> Option<u64>expire due timers into the ready queue; answer the earliest remaining deadline
vm.run_ready() -> usizedrain the ready queue, then poll parked host futures, until a spin produces no completion
vm.pending_tasks() -> usizeready + armed timers + host futures parked on Completers — the idle test

Two embedder pumps:

// wall-clock (a CLI or service): settle from real threads
vm.call::<_, ()>("boot", (args,))?;
while vm.pending_tasks() > 0 {
    vm.run_ready()?;
    std::thread::sleep(Duration::from_millis(2));
}

// virtual clock (tests): fully deterministic
while vm.pending_tasks() > 0 {
    vm.run_ready()?;
    if let Some(d) = vm.next_deadline() { vm.set_now(d + 1); }
}

Fuel rides the existing per-op budget (resource limits): a drive that runs out parks the frame and propagates OutOfFuel; a re-drive re-enters at the frame’s checkpoint.

See launched futures for receipts, cancellation, and the race/completer tier (select2 / select_all / completer); the host futures bridge for backing a host async fn with Rust.

Launched futures

A launched future’s receipt — LaunchedFutureHandle<T> — is its own type, and it is the entire management surface. Everything in this chapter is spelled in that vocabulary (async and await).

Surface status

FeatureSpellingStatus
launchlaunch_future(f)live
cancelh.abort()live
joinawait h on a receiptcompile-gated — “not in this build”
raceselect2(a, b) (stdlib)live
first-ofselect_all(futs) (stdlib)live
manual futurescompleter<T>() (stdlib)live
structured scopesscope { .. }specified, not built

The receipt — LaunchedFutureHandle<T>

pub class LaunchedFutureHandle<T> {
    pub fn abort(mut self) -> bool;
}

Laws:

  • The receipt is not a Future: await h diagnoses — the type system rejects it, never a runtime check.
  • It is not re-launchable: launch_future(h) is a type error for the same reason. A future is consumed exactly once — by await or by launch_future, never both, never twice.
  • One member: abort() — true if the frame was flagged and re-enqueued, false when it had already finished (a repeat abort is stable and harmless).

Cancellation

abort() flags the frame’s cancellation and re-enqueues it. The probe at its next checkpoint is the only place cancellation becomes observable — it never interrupts mid-expression.

At the probe, the frame runs its drop path:

  1. the pending edge is cleared — a pending sleep dies with the frame;
  2. every local releases deterministically, in reverse declaration order ([disposal] members run, the Rc heap);
  3. the state retires (null) — later abort() calls answer false.

Inside an async body, the injected cx.cancelled() reads the same flag as data, so a frame can honor cancellation at its own pace. Cancellation is synchronous at the engine level (flag + re-enqueue); a frame parked on a host future only observes the flag when the loop drives it again.

use core::{ DisposalContext };

class Drops {
    n: u32;
}

impl Drops {
    [disposal] fn release(mut self, cx: DisposalContext) { self.n += 1; }
}

async fn job() -> nil {
    let buf = Drops { n: 0 };
    await sleep(5000);
    // if `job` is aborted while parked here, the probe at the sleep
    // checkpoint runs the drop path: buf's `[disposal]` member fires,
    // then the locals release in reverse declaration order
}

Join (specified)

The receipt is the join surface: await h joins the launched future and produces its completion value. Until the join tier lands, await h diagnoses with the join law and the receipt stays non-awaitable.

Planned laws: joining an already-cancelled receipt yields the cancelled case, never a trap; join re-enqueues the awaiter the same way an in-body await parks, so the value surfaces on the driving loop, not through a callback.

Racing — select2 / select_all (stdlib)

use ink::{ Logger };
use futures::{ launch_future, sleep, select2, Either2 };

async fn slow_fetch() -> str {            // the stand-in for any slow producer
    await sleep(200);
    return "data";
}

async fn fetch_or_timeout() -> str {
    let winner = await select2(slow_fetch(), sleep(50));
    if (winner.is_a()) {
        return winner.a_value();
    }
    return "timeout";
}

async fn run_race(log: Logger) -> nil {
    log.info(await fetch_or_timeout());   // "timeout" — sleep(50) wins the race
}

entry fn main() {
    let log = Logger("race");
    launch_future(run_race(log));
}
  • select2(a, b) races two futures; the call mints the race — nothing runs until await (or launch_future) drives it. The answer is Either2<T, U>: is_a()/a_value() read the first future’s side, is_b()/b_value() the second’s. The winner’s type is the fn signature’s Either2<T, U> — computed at the call site, never a cast.
  • The losers are cancelled the moment a winner is settled: their drop paths run (pending sleeps die with them, [disposal] members fire). A cancelled race (h.abort() on the race future) cascades through its children.
  • select_all<T>(futs) races a whole [Future<T>] cohort and resolves with (i, v) — the winner’s index and value — cancelling every other still-live member. Ties (two members already retired) break by index order.

Either2 is an ordinary generic class (left: ?A; right: ?B) — rut’s enums are the C-style member set, so the two-sided answer is private fields plus accessors, not pattern arms.

Manual futures — completer<T>()

completer<T>() mints a cold Future<T> and the resolution right beside it — the primitive that turns a plain callback into a future the whole await/select2 vocabulary drives:

use core::{ Future };
use ink::{ Logger };
use futures::{ completer, Completer, launch_future, sleep };

// a PLAIN fn returning a Future; no async block needed:
fn fetch_like(tag: str) -> Future<str> {
    let (f, done) = completer<str>();
    launch_future(settle_later(done, tag));   // the "callback" side
    return f;
}

async fn settle_later(done: Completer<str>, tag: str) -> nil {
    await sleep(10);
    done.resolve(tag);
}

async fn consume(log: Logger) -> nil {
    let v = await fetch_like("tag!");         // parks until the resolve
    log.info(v);
}

entry fn main() {
    let log = Logger("completer");
    launch_future(consume(log));
}
  • done.resolve(v) settles the future and wakes its awaiter; it answers false when the future already retired — resolved, cancelled, or abandoned (the same stability abort() has). The right consumes itself: one resolve.
  • Completer<T> is only the right, not the future — a LaunchedFutureHandle sibling. await diagnoses on it; the engine minted future it settles is the awaitable.

Structure and fairness

  • Launched futures are unstructured: aborting a frame does not abort frames it awaits. Structured scopes — scope { .. } cancelling children on exit — are the specified remedy.
  • The ready ring is round-robin: each drive runs a frame to its next park or completion, so one greedy future cannot starve the queue. Priorities are not in the model.
  • vm.pending_tasks() counts ready frames, armed timers, and host futures parked on Completers — the embedder’s idle test (async and await).
  • A trap inside a launched future propagates out of run_ready() / drive(); the frame is retired either way, and its locals ran their drop path.

The host futures bridge

Native Rust code can back a rut async fn. The contract is one closure per operation: spawn the work, hand out a Completer<T>, and settle it from anywhere. The engine weaves the future; the embedder never touches a frame.

Declaring a host async fn

In a declaration package (host fns and declaration files):

/// fetch `url`; the answer is the response body
pub host async fn fetch(url: str) -> bytes;

Rules:

  • Concrete crossing signatures only — no generic host async fns; parameter and answer types come from the crossing set (the host boundary).
  • Arity 0–8.
  • Calling one runs nothing: the call site mints a cold engine-woven Future<T> frame whose state field holds the host cell. The body is driven by await or launch_future exactly like any other future.
  • The declared name itself is never dispatched — calling through it traps with a teaching message (“the weave mints the future at the call site”).

Completer<T>

The completion cell — the one helper a host async fn’s body needs:

MemberThreadMeaning
Completer::new() -> Completer<T>anya fresh cell: atomic state + a mutex slot, one Arc
.clone()anyanother handle on the same cell — never a copy of the state
.complete(v: T)any threadsettle with the answer
.fail(msg: String)any threadsettle with a failure — msg becomes the trap at the await
.poll() -> i32anythe driving loop’s probe: PENDING (0) / READY (1) / FAILED (2)
.take_result() -> Result<T, Trap>VM threaddrain the answer — one take; a second take traps; taking while pending traps

T must be a crossing type (Ret). The completer itself crosses boxed under opaque — it is what the woven frame holds in its state field (opaque — erasure and downcast).

Thread law: the VM stays single-threaded. Worker threads touch only the completer’s atomics + mutex; every rut cell is minted on the VM thread when the answer is marshaled.

Late answers are disclosed best-effort: after a cancellation the thread runs to its blocking completion and the result is simply never taken.

Registering — pkg_async_fn!

One closure (plus an optional abort hook) expands into the five rows the weave drives. On the installer lane the row names are bare and the pkg’s scope prefixes at the install; the raw register_async! twin (full scope::name strings on the bare registry) is the escape hatch — same emitter, same family:

use rut_vm::{ HostPkg, Completer, Vm };

let mut pkg = HostPkg::new("mypkg");
rut_vm::pkg_async_fn!(pkg, "fetch", (String,) -> Vec<u8>,
    |url: String| -> Completer<Vec<u8>> {
        let c = Completer::new();
        let w = c.clone();
        std::thread::spawn(move || {
            match std::fs::read(url) {
                Ok(data) => w.complete(data),
                Err(e) => w.fail(e.to_string()),
            }
        });
        c                       // returned immediately: the future parks
    });
// the built pkg rides the run chain: .pkg(pkg.build())
Emitted rowSignatureRole
mypkg::fetch(args) -> Tthe decl row — a teaching trap, never dispatched
mypkg::fetch__start(args) -> opaquecalls the closure, boxes the Completer — the state cell
mypkg::fetch__yield(state, cx) -> i32the resumption probe: 0 pending / 1 ready / 2 failed
mypkg::fetch__take(state) -> Tmarshals the answer onto the heap on the VM thread; a failure traps here
mypkg::fetch__cancel(state)the abort closure when one is given; otherwise the disclosed no-op

The abort-closure form receives a Completer<T> clone (safe to move anywhere); without it, cancellation is the documented best-effort law — the thread finishes, the late result is discarded.

Rut side, the closure’s own surface is invisible — callers see a normal async fn (the cx is injected, never spelled):

use futures::{ launch_future, sleep };

// `fetch` is the host's async fn (the mypkg::fetch row family above);
// a stand-in body keeps the block runnable end to end:
async fn fetch(path: str) -> bytes {
    await sleep(5);
    return "hostname".encode();
}

async fn grab(path: str) -> bytes {
    let body = await fetch(path);
    return body;
}

entry fn main() {
    launch_future(grab("/etc/hostname"));
}

The embedder’s loop

The engine polls every future parked on a completer:

vm.call::<_, ()>("main", ())?;
while vm.pending_tasks() > 0 {
    vm.run_ready()?;                       // drain + poll + drain
    std::thread::sleep(Duration::from_millis(2));
}

run_ready() drains the ready queue, polls the parked host futures (each poll runs the __yield probe; a ready one is driven through __take and its awaiter re-enqueued), then drains again — one pass settles a completed host future end to end. vm.pending_tasks() counts ready frames, armed timers, and the host-pending set, so a worker that never completes keeps the loop alive — the flip side of best-effort cancellation.

The virtual clock works here too: drive with finite fuel and vm.set_now for deterministic tests (resource limits).

In-tree users

The standard HTTP lane is a register_async! client: http_send (living in the surface tree’s net/ mod), http_body, and http_stream_next (in stream/) are pub host async fn rows whose bodies park Completers answered from reqwest worker threads (or the fixture lane’s virtual clock); the registrations spell the paths ("net::http_send__start" et al). Mount it with rut/http_host + rut/http; the full walk-through is the GitHub viewer example.

Plain host fn rows (synchronous, run to completion inside the crossing) are the other half of the boundary — see embedding and native modules.

Embedding and native modules

The host is a Rust program. It walks the program’s packages off disk (or offers them by hand), composes one run fluently, binds native function bodies to declared surfaces, and drives rut entry points. One value flows end to end: Pkg → RutRun → Compiled → Vm. Compiling and type-checking rut code never requires any Rust: surfaces are declared in rut source (host fns and declaration files), and the boot join proves every referenced native member has a bound, signature-equal implementation before the first instruction runs.

There is no load-time execution: composing and compiling verify and link; the host runs entry points explicitly.

Getting the crates

The engine ships as git dependencies — the crates are not on crates.io. Name the repository once per crate, every crate on the same rev (cargo then resolves them to one checkout):

[dependencies]
rut-driver = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-native = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-core   = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-parser = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }
rut-vm     = { git = "https://github.com/hpp2334/rut.git", rev = "<commit-hash>" }

rut-native is the walk and the world — everything with a filesystem or a wire (the walk vs the offer). A host that offers every Pkg by hand (a wasm page, an in-memory test) depends on the driver alone and skips it. The build needs the nightly this repo pins (rut-vm-threaded uses incomplete features) — your project’s rust-toolchain.toml carries the pin. Add rut-std the same way when the program uses std packages; the full walk-through (hash lookup, nightly pin, a runnable smoke test) is installation.

The embed loop

// 1. The walk (rut-native): a directory's whole closure as walked
//    pkgs — `[deps]` recursion, the rut.lock pins, the root-only
//    dev pass.
let loaded = block_on(rut_native::load_dir_with(
    std::path::Path::new("plugins/server"),
    &rut_native::HttpRemote::project_local(project_dir),
))?;

// 2. The chain (rut-driver): offer the walk's yield, hand over the
//    host bodies, name the root — and ONE terminal step compiles.
//    `pkg(..)` is the ONE offering verb over the Offer classification;
//    `&Bundle` and `HostPkg` coerce in (`impl Into`).
let compiled = loaded
    .pkgs
    .iter()
    .fold(rut_driver::RutRun::new(), |r, p| r.pkg(p.clone())) // first-pkg-wins
    .pkg(rut_std::math::pkg())                         // calc's bodies (Offer::Host)
    .pkg(rut_std::logger::pkg(|s| println!("{s}")))
    .entrypoint(&loaded.root)
    .compile()?;
if !compiled.graph.diags.is_empty() { /* render and exit */ }
rut_vm::verify::verify(compiled.graph.program.as_ref().unwrap())?;

// 3. Boot and drive — `Vm::builder()` is the only construction door.
let limits = rut_vm::interp::Limits {
    fuel: Some(1_000_000),
    heap_limit_bytes: Some(64 * 1024 * 1024),
    interrupt_every: 1024,
};
let mut vm = rut_vm::interp::Vm::builder()
    .compiled(compiled)          // the run's product; also .limits/.hooks/.hosts
    .build()?;
let answer: i64 = vm.call("compute", (41,))?;

A hand-rolled pkg for your own host rows rides the same chain step (the raw register! escape hatch on the bare registry — same machinery, flat names — stays for hosts that bind outside the chain):

let mut server = rut_vm::HostPkg::new("server");
rut_vm::pkg_fn!(server, "emit", (OpaqueRef, &str, &str) -> (),
    |vm: &mut rut_vm::interp::Vm, bus, topic, payload| -> Result<(), rut_vm::Trap> {
        // re-entrant rut calls are legal here (see "Native fn rules")
        Ok(())
    });

let compiled = rut_driver::RutRun::new()
    /* ..offers.. */
    .pkg(server.build())
    .entrypoint("app")
    .compile()?;

Rows under a surface’s mod tree register scope-relatively. A type = "host" pkg may organize its surface as a module tree (pub mod net; in the .d.rut, the rows in net/mod.d.rut — project structure); a row under net/ declares as pkg::net::name and its body registers under the path spelling without the pkg scope — the scope prefixes once, at the install:

let mut http = rut_vm::HostPkg::new("http_host");
rut_vm::pkg_fn!(http, "net::http_status", (OpaqueRef,) -> i32,
    |vm, r| Ok(status_of(r)));                    // → http_host::net::http_status
rut_vm::pkg_async_fn!(http, "stream::http_body", (OpaqueRef,) -> Vec<u8>,
    |r| drain(r));                                // → http_host::stream::http_body (+ family)
// a bare spelling stays the ROOT row's shape ("map_new", not "net::map_new")

A path spelling for a row the surface declares flat (or vice versa) fails the install’s contract check by name — the declared rows are the graph, the registration strings must spell the same tree.

The .compile() law

RutRun::compile() is the single terminal step. In order:

  1. auto-offer the core prelude — unless a pkg named core was offered (first-pkg-wins override);
  2. close the world — every offered pkg mounts into the run’s internal table; the walk’s yield already carried its groups, and every module links — nothing appends after the walk;
  3. the host registry — every Offer::Host installs against the mounted rows snapshot. A mounted scope whose declared rows the installer does not bind is the loud panic (the .d.rut ↔ host-impl contract); an unmounted scope’s rows merge inert — an embedder wiring bug is never a rut diagnostic;
  4. the closure check — every use name in every offered source resolves against the offered world AND its consumer’s own manifest (nameability is declaration-scoped: deps ∪ root dev-deps ∪ core; a mounted-but-undeclared head is the dedicated D5 diagnostic, its host clause naming the builder doors for a hand offer); a miss is Err(RunError), carrying the resolver’s own diagnostic;
  5. parse → check → LIR → link.

Shape/closure failures (a bad package name, a missing entrypoint, an unresolved use) are Err(RunError). Compile diagnostics are NOT errors: they ride inside Compiled::graph exactly as they always did — check compiled.graph.diags before trusting compiled.graph.program.

The registry is consumed by .build(): every host thunk the program declares is resolved against it once, at boot. A declared-but-unbound fn is a construction error, never a mid-run trap.

The walk vs the offer

Two doors produce Pkgs; both feed the same chain.

The walk (rut-native) reads a module directory — or a packed .rutbundle — and yields the closure:

lanewhat it does
load_dir(dir)the walk: [deps] recursion (cycle guard, first-mount-wins, name-mismatch is an error), the root’s rut.lock read fresh (an unpinned url refuses, naming rut install), the lock pins verified at the mount door, then the root-only [dev-deps] pass. Url deps are the loud no-fetcher error.
load_dir_with(dir, &remote)the same walk; url deps rows are collected, gated against the root’s rut.lock, fetched over the host’s DepRemote, and pinned at the mount door
load_dir_fetched(dir, &map)the walk over PRE-fetched url bytes — the sync core; tests and offline hosts hand a url → bytes map
load_path_session(path) / load_path_session_with(path, &remote)dispatch on the shape: a directory walks (above); a .rutbundle loads closed (below)

The yield is rut_driver::Walk { pkgs, root } — pure pkgs plus the root’s name. Offer each pkg through pkg(..) (first-pkg-wins — fold the walk into the chain) or pick pieces with walked.pkg(name).

The offer is ONE verb, RutRun::pkg(..), over the Offer classification — the same lib/host pair the manifest type field spells:

offerwhat it is
pkg(&bundle) — Offer::Lib(&Bundle)a decoded .rutbundle archive: Bundle::parse(&bytes) decodes + verifies ONCE (CRC, version, group decode), the handle is reusable across runs, and each offer only relocates + mounts
pkg(rut_std::math::pkg()) — Offer::Host(hp)host bodies — the embedding Rust’s own rows
pkg(pack_inline_pkg(name, text))ephemeral source as a one-member source bundle — a pack method that assembles, never compiles; the run compiles the member when it is offered
pkg(mounted)the walked pkg data (deprecated bridge — offer bundles instead)

An archive handle carries its strip restore too: bundle.restore_symbols(&map) — applied once, before any offer; every subsequent offer carries the restored names (symbol stripping).

The mounted pkg data behind the walk (the constructors tests and hosts spell by hand) is Mounted:

constructorbuilds
Mounted::source(name, text)the ordinary .rut body
Mounted::decl(name, text)a .d.rut surface (declaration mode)
Mounted::host(name, rows)the native rows — exported constants, bodyless host fns
Mounted::compiled(name, program)a decoded .rutc binary pushed as-is
Mounted::from_bundle(bytes)the pure parse — the bundle’s pkgs as a Walk (below)
lower_decl_module(text, children, file)a .d.rut lowered to host rows — the wasm hosts’ surface lane; children is the mounted mod tree (NAME/mod.d.rut files, mount with mount_mod_children in Decl mode) and each row carries the path it lives under

Mounted is pure data: the walker-found metadata (the [deps] table and the declaration rows the nameability law reads) is pub data on it — the graph only reads.

Two offer lanes walk a directory for someone else’s program:

lanewhat it does
rut_native::dir_pkgs(dir) / dir_pkgs_with(dir, &remote)offer one package directory — and, recursively, its [deps] — as walked pkgs. No dev-deps pass: the closure is the program’s own .compile() law.
rut_native::tree_pkg(name)one toolchain-tree package (rut/calc, rut/futures, …). A pkg whose [deps] pull a closure is refused — offer the whole walk (load_dir) instead, never a silently-truncated world.

core is never offered — .compile() auto-rides it. calc and the async pair are ordinary tree packages: the host offers rut_native::tree_pkg("calc") when the program’s surface needs it and binds rut_std::math::pkg() for the bodies (core and the swappable packages).

Hand mounts carry a manifest

A hand-offered world is lawed by the same declaration table as a walked one — nameability is declaration-scoped, so a consumer may use exactly the heads ITS manifest names — the manifest just travels structurally instead of as a file. Two builder doors:

  • Real manifests — parse the embedded jsonc and stamp it: Mounted::manifest(parse_manifest(include_str!("../pkg/rut.jsonc"))). The tree’s own rut.jsonc stays the single source of truth; the wasm host mounts every std pkg this way.
  • Ad-hoc surfaces — Manifest::lib(name, &[heads]) stamps the structural form directly, no json text anywhere. 05’s web package is the worked example: embedder-registered, no artifact, no path/url — a structural-only declaration of the heads its sources name.

A hand offer has no walk edge, so D5’s mount edge renders the structural clause — “offered by the host” — and the fix names the two builder doors, never a file (dependency kinds). Declared-unused rows stay legal: the law bounds uses by declarations, never declarations by uses.

The wasm playground rides the same law with a host-side default: the page’s compile lane accepts an optional consumer manifest (jsonc) beside the source — rut_compile_manifest in the raw ABI (a manifest that does not parse returns as a span-0 diagnostic) — while plain rut_compile defaults the program’s declaration to the offered lib names (ink_host, nmap_host, ink, pouch, nmapset, flow, async_host, futures, strbuild_host, strbuild, json, calc — core stays row-free; the prelude is free by law), computed from the world the host actually mounts. A use outside the declared set is D5.

Url deps — the remote policy (DepRemote + HttpRemote)

The embedder owns exactly three things: the fs policy ([Source]), the remote policy ([DepRemote]), and its own runtime. The _with lanes take &dyn DepRemote and nothing else: the remote matters only when the dep walk actually reaches a url row. Url-free projects and .rutbundles are closed — they load with no remote named at all.

The standard remote is rut_native::HttpRemote — cache-first: a hit NEVER touches the network, a miss GETs (redirects on, loud status errors, a size cap) on the remote’s own private worker thread and writes the cache back atomically. Cache layout law: <root>/<sha256(url)>.rutbundle. The futures come back READY, so any executor works — including the std-only noop-waker block_on poll loop the examples spell.

constructorbehavior
HttpRemote::project_local(project)<project>/.rut/cache — hermetic, project-local; networks on a miss (the http feature, default on)
HttpRemote::at(root)an explicit cache root, wire on
HttpRemote::offline(root)cache-only — a miss never networks; the guaranteed-offline lane (CI gates, wasm-adjacent hosts)
path_for(url) / evict(url)the concrete entry path / delete a poisoned entry

Guaranteed-offline loads (tests, CI, wasm-adjacent hosts): prime an offline remote, then load over it. The committed std artifacts play the wire — DepRemote::write is the stand-in for the GET:

let remote = rut_native::HttpRemote::offline(&cache_root);
for (url, bytes) in vendored_rows {                  // parsed from rut.jsonc
    rut_native::DepRemote::write(&remote, &url, &bytes)?;  // prime the cache
}
let loaded = block_on(rut_native::load_dir_with(project_dir, &remote))?;

Memory hosts (wasm, in-process tests) hand-roll the trait — one required method, sync impls are first-class via std::future::ready:

struct Mem(Vec<(String, Vec<u8>)>);

impl rut_native::DepRemote for Mem {
    fn fetch(&self, url: &str)
        -> Pin<Box<dyn Future<Output = Result<Vec<u8>, rut_native::RemoteError>> + '_>> {
        Box::pin(std::future::ready(
            self.lookup(url).ok_or_else(|| rut_native::RemoteError::new(
                format!("no bytes for {url}")))))
    }
    fn lookup(&self, url: &str) -> Option<Vec<u8>> {
        self.0.iter().find(|(u, _)| u == url).map(|(_, b)| b.clone())
    }
    fn write(&self, url: &str, bytes: &[u8]) -> Result<(), rut_native::RemoteError> {
        self.0.retain(|(u, _)| u != url);
        Ok(self.0.push((url.to_string(), bytes::to_vec())))
    }
}

The walk still owns WHAT the bytes are: the pin is lock law — the root’s rut.lock (url → sha256), gated before any fetch and verified at the mount door on every load — fresh fetch, cache hit, vendored map, test fixture.

The filesystem policy is rut_native::Source — string keys, all key math in the impl. FsSource::at(dir) is the real filesystem with the root baked in; a Path lives only inside its impls. A test or a memory host answers read/resolve with lookups instead of files. The load_dir* lanes bake FsSource in; a custom Source hosts the walk through dir_pkgs-shaped collectors of your own.

Module bundles

A packed .rutbundle is the same contract zipped — loading it never fetches (bundles are closed; their closure rode inside at pack time):

// from a file: the walk adds only the file read
let loaded = rut_native::load_bundle_session(Path::new("vendor/plugin.rutbundle"))?;

// from bytes (embedders, tests, wasm): decode + verify ONCE —
// the handle is reusable across runs (offer it with pkg(&bundle))
let bundle = rut_driver::Bundle::parse(&bytes)?;

Both root kinds load (a compiled root with its groups and its pack-time scope ledger, rebased at the close of the world; a decl root as the pkg’s host rows), first-mount-wins, and the bundle root’s package name is loaded.root. Wasm hosts include_bytes! the committed artifact and parse through Bundle::parse. For the url-dep walk (pins, closure checks, the archive’s identity-keyed groups) stay on the load_dir* lanes — a bundle mount is the offer, not the walk. The container, the manifest grammar, and the reader are module bundles.

What to take from a url is the engine’s instantiation law, read from the embedding side: a compiled bundle serves host surfaces, concrete-class libs, and — by instantiation independence — the generic owners: a request the pack-time ledger lacks monomorphizes from the template the binary carries and compiles the body under the declaring pkg’s spec, at the link, nothing persisted (Vec<MyTodo>, decodeJson<T> — module bundles — the std-CDN section). A bundle that owns an open generic surface but whose binary carries no template bodies refuses at the mount (corrupt or doctored — re-pack the directory), and a bundle-mounted json names its pack-time dev closure in its ledger, so the consumer’s closure must contain those names.

The walk API (rut-native)

APIMeaning
Sourcethe one filesystem door, STRING keys: read(key), resolve(from, spec), root() — the key math is the impl’s; a Path crosses nothing
FsSource::at(dir)the real filesystem with the root baked in
DepRemotethe url-dep contract: fetch(&self, url) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, RemoteError>> + '_>> (required), lookup, write — the call site owns HOW bytes arrive (transport, cache, offline policy). Dyn-compatible (hand-rolled boxing, no async-trait), deliberately not + Send: a browser fetch bridge is !Send, and sync impls (cache hits, fixtures) are first-class
HttpRemotethe standard remote: cache-first (<root>/<sha256(url)>.rutbundle), a miss GETs on a private worker thread and writes back atomically; project_local / at wire on, offline is cache-only, path_for/evict are concrete
load_dir(dir) / load_dir_with(dir, &remote) / load_dir_fetched(dir, &map)the walk and its fetched lanes — the yield is rut_driver::Walk (the walk vs the offer)
load_path_session(path) / load_path_session_with(path, &remote)dispatch on the shape: directory walk or closed .rutbundle
load_bundle_session(path)load a packed .rutbundle from disk — the pure container lane plus the file read
dir_pkgs(dir) / dir_pkgs_with(dir, &remote)the OFFER lane: a package directory walked for someone else’s program (no dev pass, no gate)
tree_pkg(name)one toolchain-tree package (rut/<name>); a [deps] closure is refused
load_module_source(path)one .rut file’s text — a loose file is a single module, no manifest
prefetch_urls(&src, &dir, &remote)collect a manifest’s url rows and fetch them — the _with lanes’ input step
pack_dir(dir) / pack_dir_with(dir, &remote) / pack_dir_opts(..) familypack a module directory into a deterministic .rutbundle — a compiled root for a lib pkg, a decl root for a host pkg (type routes; format_version is 12); returns the bytes (module bundles)
default_out_path(dir)the conventional pack output path

The run chain API (rut-driver)

APIMeaning
.pkg(offer)the ONE offering verb over the Offer classification — pkg(&bundle) (Offer::Lib), pkg(host_pkg) (Offer::Host), pkg(pack_inline_pkg(name, text)) for ephemeral source. FIRST OFFER WINS: a pkg whose name is already offered is ignored
.entrypoint(name)the root pkg — the graph compiles it and its transitive uses
.compile() -> Result<Compiled, RunError>the terminal step (the law)
Compiled { graph, hosts }the linked graph (diags inside — check graph.diags before trusting graph.program) and the host registry every Offer::Host installed
Bundle::parse(&bytes)decode + verify an archive ONCE (CRC, version, group decode) — the handle is reusable across runs; bundle.restore_symbols(&map) restores a stripped artifact’s names on the handle (symbol stripping); bundle.walk() is the raw mount assembly
Walk { pkgs, root }a walk’s yield; walked.pkg(name) picks one pkg
Mounted::source / decl / host / compiled / from_bundlethe walked pkg data’s constructors (the offer)
RunErrorwhy a run refused to compose or compile — shape (bad name, missing entrypoint) or closure (a use nothing offered resolves); the message IS the diagnostic
declared_host_fns(pkgs)the declared rows, async-expanded, flattened — the raw lane’s verify_against input
host_pkg_ctx(pkgs)the declared rows, partitioned by scope — for hosts that build registries OUTSIDE the chain (a bench probe’s fresh Vm per iteration, a raw-row host’s verify_against)
compile_module(src, mode, name)the single-source lane: the core prelude auto-rides, the source offers as the root pkg, one .compile() — returns diags, AST/IR dumps, and the binary. The walked packages (calc’s Math, the async pair) are NOT here: a host that wants them offers rut_native::tree_pkg(..)
compile_program(src, mode, name) / compile_program_resolved(..) / ir_dump_of(..)the raw pipeline pieces (tooling)
lower_decl_module(text, children, file)lower a .d.rut surface to host rows (children = the mounted mod tree — a declared child with no mounted NAME/mod.d.rut is a loud error; registration is path-qualified, pkg::net::connect)
bundle::{parse_manifest, Bundle, Layout, ..}the container codec, the rut.jsonc grammar, the reader (both root kinds) — pure, in-memory
pack::{pack, pack_inline_pkg, PackOpts, ..}the pure emit half of packing (rut-native owns the walk + dev tables + the gate); pack_inline_pkg(name, text) assembles a one-member source bundle — never compiles
sha256_hex(bytes)pin arithmetic (pure)

mode is Mode::Impl for .rut and Mode::Decl for .d.rut (host fns and declaration files).

The driver is provably pure: no fs, no net, no walk, no std::path anywhere in rut-driver — everything with a filesystem or a wire lives in rut-native.

VM API (rut_vm::interp)

APIMeaning
Vm::builder()the construction door: .compiled(x) (anything IntoVmParts — the driver’s Compiled) or .program(rc) for embedders holding a decoded binary, each plus .limits(l) / .hooks(h) / .hosts(registry), ending at .build() -> Result<Vm, VmError>. Unset limits ⇒ Limits::default() — uncapped, the mechanism law; explicit setters win over the compiled parts
HostRegistry::new()an empty binding table (the raw lane)
HostPkg::new(scope)a pkg builder; rows register under bare names or scope-relative paths ("net::connect" — a row under the pkg’s mod net tree; the scope itself is never part of the row name) and the scope prefixes once, at the install
pkg_fn! / pkg_async_fn!the builder’s sugar: one spelling → one row / the five-row async family (the spelling may carry the mod path: "net::send" → net::send__start et al)
hosts.register::<_, (P…), R, _>(name, f)the raw lane: bind one body under a full scope::name string
hosts.verify_against(&expected)the raw lane’s net: panic on declared-unbound / bound-undeclared / signature drift
vm.call::<A, R>(export, args)call an export with Rust values, get a Rust value back (value boundary)
vm.resume::<R>()resume a budget-parked call after refueling
vm.run_ready()drain the async ready queue once; returns frames run
vm.next_deadline() -> Option<u64>the earliest timer deadline, if any
vm.set_now(t_ms)advance the virtual clock
vm.pending_tasks() -> usizeunfinished async work
vm.fuel_used / vm.heap_usage()budget meters
vm.alloc_opaque_str(s)mint an opaque box over host-built text (the logger’s named logger)
vm.call_host_row(row, &[Value])dispatch a registered row by name (test/tooling reads)

The canonical async driving loop (single-threaded; the host owns it):

loop {
    vm.run_ready()?;
    match vm.next_deadline() {
        Some(d) => vm.set_now(d),          // advance to the next timer
        None if vm.pending_tasks() == 0 => break,
        None => std::thread::sleep(std::time::Duration::from_millis(2)),
    }
}

Cap the loop in embedders that cannot prove termination, so a program that never idles fails loudly instead of hanging.

Limits

pub struct Limits {
    pub fuel: Option<u64>,          // ops per turn; None = unlimited
    pub heap_limit_bytes: Option<u64>,
    pub interrupt_every: u32,       // ops between interrupt checks
}

Exhaustion and interrupts surface as traps (resource limits). A trap inside re-entrant work propagates to the embedder parked at the host op; vm.resume::<R>() re-runs the turn.

Native fn rules

  • A body is FnMut(&mut Vm, P…) -> R or -> Result<R, Trap>; the Rust parameter types are the declared row (compile error at the register site for a type that does not cross — value boundary).
  • Native fns run outside the op budget. The host is trusted to be fast — or to hand the work to a future (async host fns).
  • Re-entrancy: a body may call vm.call on rut exports. Nested calls draw the same fuel pool; borrows held by the outer body are guarded (value boundary).
  • Failures are values: return Err(Trap) — Trap { kind, msg }. The fn traps cleanly and the error propagates as an Err to the embedder with the rut backtrace intact. Traps never unwind Rust.
TrapKindraised by
OutOfFuelbudget exhaustion
OutOfMemoryheap limit
Interruptedinterrupt flag
Overflow / DivByZeroarithmetic
IndexOutOfBoundssequence access
Panicpanic
BadUnboxa failed unbox
NilDerefnil where a reference is required
Invalideverything else, including boundary mismatches

The engine’s own natives

The VM boots with internal native calls in the same dispatch family — the str/bytes members, the f"..." concatenation lowering, array length/slice, and stack-trace capture. They are call slots fixed at boot, never IR-level special forms; hosts see them exactly like their own registered modules.

Host-side helpers (rut-std)

One pkg() builder per module; each rides the chain — .pkg(rut_std::math::pkg()) — and installs at .compile() against the rows snapshot (see host fns for the asymmetric contract — an unmounted scope merges inert, so hosts blanket-install their subset):

builderbinds
math::pkg()calc’s float functions, both widths
logger::pkg(sink)ink_host’s two rows, routed to a FnMut(&str) sink
nmap::pkg()the native key table behind nmapset (stdlib)
strbuild::pkg()the string builder’s rows behind strbuild (stdlib) — growth is charged against the embedder’s heap budget
async_host::pkg()the launcher rows (__launch/__abort/__sleep/__sleep_yield)
http::pkg()the std HTTP lanes (reqwest; native builds only); http::pkg_with(f) is the fixture twin, returning (HostPkg, HttpFixture). The http_host surface is a mod tree — the rows register scope-relatively (net::http_send + the readbacks, stream::http_body/http_stream_next)
bench_cross::pkg()the crossing-tax benchmark rows

In-tree examples

  • 03 — Plugin: a Rust chat server driving a rut moderator plugin, loaded from a module directory and from a packed .rutbundle; re-entrant emit crossings.
  • 06 — GitHub viewer CLI: walks the std packages, binds example-local I/O rows, launches an async entry fn, and pumps the driving loop to idle.

Value boundary and borrows

The one place tagged values exist: the host boundary. Inside the VM, registers are untagged slots (the VM heap); crossing into Rust materializes a checked, borrow-guarded value. The currency of the boundary is typed Rust: the registered closure’s parameter types and the vm.call return type are the whole contract. The internal marshaling formats stay out of it: Slot never appears, and the raw Value enum surfaces only as the one untyped read in the map below.

The crossing set

What may cross is a compile-time property of the surface. A violation is a compile error on the declaration or binding — never a call-time failure.

  • Parameters cross over: the primitives (i8–i64, u8–u64, f32, f64, bool), str, bytes, and opaque.
  • Returns cross over the same set plus the answer optionals ?str, ?bytes, ?opaque.
  • Tuples cross field-by-field; each field must itself cross.
  • Entry fns follow the same rule in both directions: ?T crosses iff T crosses, decoded nil-flattened.
  • Everything else — structs, classes, Vec<T>, [T], interface-typed values, closures — stays inside the VM. Seal polymorphic values in the erasure box: opaque(v) at the call, opaque::downcast<T>(v) after (opaque — erasure and downcast).

Rust ↔ rut type map

Rust typerut typedirectioncost
i8 i16 i32 i64sameboththe raw slot bits
u8 u16 u32 u64samebothraw bits (u64 is never narrowed through i64)
f32 f64 boolsamebothraw slot bits
()nilboththe zero word
&strstrparam onlyzero-copy borrow of the block store, scoped to the call
Stringstrbothowned copy
&[u8]bytesparam onlyzero-copy borrow
Vec<u8>bytesbothowned copy
OpaqueRefopaqueboththe handle; the rc transfers across
Opaque<T>opaquebothtyped payload view; a wrong T traps naming both sides
Option<String>?strreturn (answer lane)Some mints the opt box; None is the flat nil
Option<Vec<u8>>?bytesreturn (answer lane)as above
Option<OpaqueRef> / Option<Opaque<T>>?opaquereturn (answer lane)as above
Option<T> (other T)——no lane: traps naming ?str/?bytes/?opaque
(A, B, …) up to 8tuplebothfield-by-field under the record’s own field types
Valuewhatever’s declaredreturn onlypositional decode for generic tooling

The optional read is nil-flattening: the null slot is None, a some-slot decodes its payload as T. There is no separate optional currency — nil is absence.

Borrows and copies

&str/&[u8] params read the block store directly. The handler bound is higher-ranked over the borrow’s lifetime, so a borrowed param cannot outlive its call — smuggling one out is a type error, not a runtime check. Owned String/Vec<u8> params are the explicit “I keep this data” copy.

Borrow guards, the whole rule:

  • A borrow is call-scoped. The Rust lifetime prevents storing it past return; the object’s guard flag additionally excludes conflicting access.
  • While an exclusive borrow is held, a re-entrant vm.call that touches the same box traps borrowed by an outer host call instead of aliasing.
  • Shared borrows stack; an active exclusive borrow excludes them.
  • Guards clear on return. To keep data, the host copies.

The two-channel law

A rut entry typed -> (?T, err) decodes positionally as (Option<T>, String) — or generically as Value::Tuple([Nil|payload, Str(err)]):

  • A returned err is data: it crosses as the pair’s second component; the host reads it and acts. The pair’s convention belongs to the caller: empty err + a value = success; empty err + nil = “not found”; non-empty err = “failed”.
  • A panic is drift: it stays on the loud channel (Result<_, Trap> — Err means a trapped turn, a bug) and never fills an err field. The two channels are never merged.

opaque — the one cell the host holds

A host payload and a host-held rut value share the one erasure box. The store entry is one of two kinds:

entryholdsidentity
HostBox<dyn Any> + a type name + an optional finalize hookTypeId guards the payload view
Ruta rut cell slotidentity is the cell; rut-side downcast reads the cell’s runtime kind

The rut-side value addresses the entry directly (a tagged slot word); the Rust-side typed view is:

APIMeaning
Opaque::alloc(vm, val)mint a box; size_of::<T>() charged to the heap budget
Opaque::alloc_hosted(vm, val)mint a box whose payload opted into the release hook (T: HostPayload); finalize runs at entry death, before Drop
Opaque::from_handle(&h)the checked view; a wrong payload T traps naming both sides, a rut-value box names the rut-side recovery
o.with(|v| …)shared borrow of the payload; nested withs stack
o.with_mut(vm, |vm, v| …)exclusive borrow; flows &mut Vm for in-crossing rc work
o.handle()the erased OpaqueRef, for passing the box back across

Death is deterministic: at rc-0 inside the release walk, finalize(heap) runs first, then the payload’s own Drop (the Rc heap). Instances are per-map/per-logger, never per-op.

Calling in

// entry fn half(x: f64) -> f64
let y: f64 = vm.call("half", (2.0,))?;

// entry fn find(id: i64) -> (?str, err) — the two-channel shape
let (name, err): (Option<String>, String) = vm.call("find", (7i64,))?;
if !err.is_empty() { /* "failed" */ }

// an opaque round trip
let b = rut_vm::Opaque::alloc(&mut vm, MyHandle::new())?;
let back: rut_vm::OpaqueRef = vm.call("stash", (b,))?;
  • vm.call::<A, R>(export, args) converts the args under the export’s declared parameter types, runs, and decodes the answer under the declared return. A shape mismatch traps naming both sides.
  • vm.resume::<R>() continues a budget-parked call.
  • Argument bundles are tuples up to arity 8 (CallArgs); each element must be a CallArg (Copy prims, String, &str, Vec<u8>, &[u8], OpaqueRef, Opaque<T>).

Host fns and declaration files

One linkage keyword, one implementer:

keywordimplementation lives inbound at link against
host fn / host structthe embedding Rust — a typed registrationthe load-time contract (below)
prelude builtin / pub builtin rowsthe engine itself — compiler-lowerednothing; the decl is a pure signature contract

rut→rut names resolve through use paths (modules and visibility); host→rut entry points are entry fn (loading and the embed loop).

Surfaces live in declaration files — .d.rut — so compiling rut code never requires any Rust, and a published package can ship its compiled bodies plus a hand-written surface.

Host pkgs

A package directory whose manifest declares type = "host" is a host pkg — pure surface, no rut source:

// server/rut.jsonc
{
  "name": "server",
  "type": "host",
  "entry": { "type": "./server.d.rut" }
}
// server/server.d.rut
pub host fn subscribe(bus: opaque, topic: str, handler: str) -> nil;
pub host fn emit(bus: opaque, topic: str, payload: str) -> nil;

Consumers reach a host pkg two ways:

The loader lowers the declared signatures into the mounted surface at load time; the compiler type-checks calls against them. A host pkg packs into a .rutbundle like any dep (module bundles).

The surface grammar

host fn name(params) -> T;            // concrete signature; generics are a
                                      // compile error — a generic parameter
                                      // has no shape the boundary checks
host struct Name { fields }           // flat record; every field a crossing
                                      // type; no methods, no field
                                      // initializers — the shape IS the
                                      // whole surface
prelude builtin fn name<T>(params) -> T;   // engine fn, compiler-lowered
prelude builtin class Name<T> { .. }       // engine type member contract
                                           // (the closed async pair among
                                           // them — `Future<T>`, `RunContext`)
prelude builtin impl i32 { .. }            // engine methods on a primitive
pub builtin class Name<T> { .. }           // the import-gated twin (below)

Rules:

  • The crossing set — host fn signatures are concrete over: nil, the primitives, str, bytes, and opaque. Returns may additionally use the answer optionals ?str / ?bytes / ?opaque. Named records never cross — a host struct decl is surface, not a signature type — and the anonymous-tuple lane belongs to the entry fn surface (value boundary). Everything else (user classes, Vec<T>, [T], interface-typed values, closures) is a compile error on the declaration.
  • any is not in the language. An any spelling fails at resolution as an unknown type — there is no any type to write. Seal polymorphic values with opaque(v) / opaque::downcast<T>(v) (opaque).
  • builtin is the engine’s reservation — spelled only in the toolchain’s own decl files (core, calc). A builtin in an embedder decl is a compile error. The engine’s contracts are spellings on types: the bracket markers on inherent impl members and the closed builtin class pair; library polymorphism stays plain interface (interfaces).
  • builtin is a contextual keyword: .d.rut-only; elsewhere it is a legal identifier.

The two builtin spellings

A builtin decl spells one of two strict forms — a bare builtin diagnoses “builtin must be spelled prelude builtin (ambient) or pub builtin (import-gated)”:

  • prelude builtin — the ambient engine surface: the name binds in every compilation unit, no use needed. The primitives and their builtin impl methods, opaque, StackTrace, and panic/string_join/capture_stacktrace are all ambient.
  • pub builtin — the import-gated engine surface: the name resolves only through use core::{ .. }, the way a package’s names do. Today’s rows are the closed async pair — Future<T>, RunContext — the disposal context, DisposalContext, and the weak reference, Weak<T> (interfaces, async and await, the Rc heap, weak references). The engine’s weave never consults the gate — it keys on the engine symbols — so a module with no imports still iterates, awaits, and launches; only spelling a name in source gates.

Using a pub builtin name without the use line is a resolution miss that names the fix, never a bare “unknown name”:

`Future` is not in scope — `use core::{ Future }`

The split is per name: a unit that imports one gated name still sees every ambient name for free, and an unused name in a use core line stays a lint, not an error.

  • opaque wraps native state; there is no host class. rut wraps the handle in a class of its own — the wrapper-class pattern (native containers API surface). Destructors still run deterministically: when a box’s rc hits 0, the payload’s finalize hook runs, then Rust Drop (the Rc heap).

Declaration mode

A .d.rut is parsed in declaration mode: declarations only, each complete as a surface.

allowednotes
use / pubvisibility exactly as in a module; non-exported decls are known inside the file, nameable nowhere else
letwith load-time constant initializers
enumthe member list is the whole definition
interfacemember signatures are the whole definition — signatures-only fits the surface model
structfields only, with load-time initializers
host fn / host structsignatures only, concrete over the crossing set
prelude builtin / pub builtin rowstoolchain decl files only — the two spellings above

Forbidden — the parser errors “implementation in a declaration file”: any fn/class body, statements. Symmetrically, a .rut file that spells host errors “belongs in a .d.rut”.

Signatures are derived, not hand-written

The registered callable’s Rust shape is the .d.rut row. The installer lane is a HostPkg builder per pkg — rows under bare names, the scope (the pkg’s name) spelled once — handed to the chain with pkg(Offer::Host(..)) — pkg(hp) coerces:

// one builder per host pkg; the scope string appears exactly once
let mut logger = rut_vm::HostPkg::new("server");
rut_vm::pkg_fn!(logger, "make", (&str,) -> OpaqueRef,
    |vm: &mut Vm, name: &str| vm.alloc_opaque_str(name::to_string()));
rut_vm::pkg_fn!(logger, "emit", (OpaqueRef, &str, &str) -> (),
    |_vm, _bus, _topic, _payload| Ok(()));

// the built pkg rides the run chain; .compile() installs it against
// the offered rows snapshot
let compiled = rut_driver::RutRun::new()
    /* ..offers.. */
    .pkg(logger.build())
    .entrypoint("app")
    .compile()?;

pkg_async_fn! is the async twin: one row spelling emits the five-row family (__start/__yield/__take/__cancel + the decl-row trap), the same expansion the ctx declares. The raw macros — register! / register_async! on the bare registry (see embedding and native modules) — remain the escape hatch (hand-spelled <scope>::<name> strings, the flat table’s own responsibility); everything above them is the same derived-signature machinery:

let mut hosts = rut_vm::interp::HostRegistry::new();
hosts.register::<_, (&str,), OpaqueRef, _>(
    "server::make", |vm: &mut Vm, name: &str| vm.alloc_opaque_str(name::to_string()),
);
  • The signature is a fixed array of type ids derived from the closure’s parameter and return types; a param type with no crossing impl is a compile error at the register site.
  • Both body shapes fit: -> R (infallible) and -> Result<R, Trap> (fallible). Errors travel an explicit trap channel — a trapped body propagates as Err(Trap) with a rut backtrace (embedding and native modules).
  • &str / &[u8] params are zero-copy borrows scoped to exactly the call (value boundary).
  • One installer per pkg: a duplicate row name inside a builder panics, a second Offer::Host for the same scope panics (at the .compile() install), and a pkg cannot spell another pkg’s rows — the scope comes solely from HostPkg::new.

The load-time contract — asymmetric, by design

Offering a host pkg declares; the embedding Rust binds. The .compile() install checks the two sides against each other, per pkg, against the offered rows snapshot (rut_driver::host_pkg_ctx(pkgs) — the same snapshot exposed for hosts that bind outside the chain):

  • scope offered, a declared row never bound — a panic naming the pkg (the installer left it out), and .build() refuses a boot naming it again when the installer never ran at all;
  • signature drift on a declared row — a panic; this is the only drift gate on the boot path;
  • scope NOT offered — the whole pkg merges inert: no panic, no gate. Blanket installs are legal (the CLI installs all of them; a program that offers a subset carries the rest as dead bindings), and rows the decl does not name ride as inert extras.

The raw lane’s verify_against(&rut_driver::declared_host_fns(&pkgs)) re-checks the whole flat table and panics on all three mismatch classes:

  1. declared but unbound — a rut call would trap mid-run;
  2. bound but undeclared — no surface declares what the host installed;
  3. signature drift — the decl says (opaque, str, str) -> nil, the binding took (opaque, i64, str).

The law follows the offer: offer what you bind — with the asymmetry the offer law needs: rut-declares-but-host-never-binds is loud; host-binds-but-rut-never-declares rides inert.

Slots, not strings

Compiling a declaration file assigns every host fn a stable slot id in declaration order; the module binary carries the slot table. Calls compile to callnat { slot } — names are binding-time labels, resolved once at boot, never dispatch keys, never in IR. A typo’d binding is a startup error, never a runtime one. IR cannot inline into native bodies; if a body should be optimizable, it is rut source — the wrapper class is exactly that place.

Async host fns

// http_host/net/mod.d.rut — an async row expands into a five-row
// family on the path-qualified name
pub host async fn http_send(c: opaque, method: str, url: str,
                            headers: str, body: bytes) -> opaque;

The embedder binds the family with one spelling; the closure spawns the work, hands out a completer clone, and returns. On the installer lane the row name is the scope-relative spelling — bare for a root row, the mod path for a row under a surface tree (net::http_send; the scope itself prefixes once, at the install):

let mut http = rut_vm::HostPkg::new("http_host");
rut_vm::pkg_async_fn!(http, "net::http_send",
    (OpaqueRef, &str, &str, &str, &[u8]) -> OpaqueRef,
    |c: OpaqueRef, method: &str, url: &str, headers: &str, body: &[u8]|
        -> rut_vm::Completer<OpaqueRef> {
        let done = rut_vm::Completer::new();
        let w = done.clone();
        std::thread::spawn(move || {
            match do_request(c, method, url, headers, body) {
                Ok(r)  => w.complete(r),
                Err(e) => w.fail(e.to_string()),
            }
        });
        done
    },
    /* optional abort hook: */ move |_c| { /* best-effort cancel */ },
);
// the built pkg rides the chain: RutRun::new()...pkg(http.build())

// the raw lane (bare registry, full `scope::path::name` strings) — the
// escape hatch, same emitter:
// rut_vm::register_async!(hosts, "http_host::net::http_send", ...);

pkg_async_fn!(pkg, name, (P…) -> R, start [, abort]) (and its raw twin register_async!(hosts, …)) emits the family the compiler’s weave joins:

emitted rowmeaning
<name>the decl row itself; calling it directly traps — the weave mints the future at the call site
<name>__start(P…) -> opaqueruns the closure, boxes the Completer as the future’s state cell
<name>__yield(state, cx) -> i32resumption probe: 0 pending, 1 ready, 2 failed
<name>__take(state) -> Rmarshals the answer onto the VM thread; a failed completer traps here
<name>__cancel(state)the abort hook when given; otherwise the disclosed no-op
Completer<T> APIMeaning
Completer::new()a fresh cell; clone() shares it (one Arc)
complete(v) / fail(msg)settle from any thread (atomics + mutex only)
poll() -> i32the driving loop’s probe
take_result() -> Result<T, Trap>VM thread only; a fail message becomes the trap at the await

Thread law: the VM stays single-threaded; workers touch only the completer. Cancellation is best-effort — a worker runs to its blocking completion and the late answer is discarded. See the host futures bridge and async and await.

Declaration files as artifacts

A published package ships:

artifactrole
mod.rutcthe compiled module binary: bodies + the surface, the linking truth (module binary and verification)
mod.d.rutthe surface text — hand-written, editable, publishable (humans, LSP); documentation only, never the loader’s source of truth
  • The surface rides the binary: a consumer binds p’s exports from mod.rutc alone. Nothing is rebuilt from .d.rut text — impl-to-fn ids, interface-table indices, and namespace/host rows are not derivable from text without guesswork.
  • Link compares the consumer’s bound surface against the binary’s export table — a pure data compare. Drift is a load error naming both modules, never a runtime surprise.
  • Publishing is not encryption: bodies are compiled and local names are stripped (--release drops member-name strings), but code is recoverable with effort. What publishing guarantees is API discipline.

Surface resolution during compilation

When module M uses package p, the compiler resolves p’s surface, first hit wins:

  1. source — p’s rut source on the source path: compile it normally;
  2. bundle — a mounted .rutbundle: its compiled .rutc (bodies + surface on the wire) — or its bundled source for a splice-needed group; explicit mounts outrank stray sources, never dev source;
  3. host registry — for host pkgs, the .d.rut the embedder ships beside the registered implementation.

Bodies resolve only at link/run. Compiling M against a package whose implementation is absent is legal and complete — checking passes; only running requires the bodies.

End-to-end shape

The chat-bus plugin is the canonical walkthrough: a Rust server binds server::subscribe/server::emit over its own EventBus box, the plugin subscribes rut export names per topic, and every emit re-enters rut to format the wire line — see 03 — Plugin. For a full application host with mounted std packages and an async entry, see 06 — GitHub viewer CLI.

Native containers API surface

A “native container” is host state rut can hold: a Rust value boxed as an opaque handle, with a set of host fns as its API and a wrapper class on the rut side. No second class system, no per-instantiation machinery: the declaration is host fns with concrete signatures over opaque (host fns and declaration files), and the wrapper is ordinary rut source the compiler can optimize around.

The pattern

Declaration — rut source, ships with the plugin:

// my_map.d.rut
pub host fn my_map_new(cap: i32) -> opaque;
pub host fn my_map_set(m: opaque, k: str, v: opaque) -> nil;
pub host fn my_map_get(m: opaque, k: str) -> ?opaque;
pub host fn my_map_size(m: opaque) -> i32;

Implementation — Rust bodies only; values stay sealed boxes:

use rut_vm::interp::{HostRegistry, Vm};
use rut_vm::{Opaque, OpaqueRef, Trap};
use std::collections::HashMap;

struct MyMap { inner: HashMap<String, OpaqueRef> }

pub fn my_map_module() -> HostRegistry {
    let mut hosts = HostRegistry::new();
    rut_vm::register!(hosts, "my_map::my_map_new", (i32,) -> OpaqueRef,
        |vm: &mut Vm, cap: i32| {
            Ok(Opaque::alloc(vm, MyMap::with_capacity(cap.max(0) as usize))?
                .handle().clone())
        });
    rut_vm::register!(hosts, "my_map::my_map_set", (OpaqueRef, &str, OpaqueRef) -> (),
        |vm: &mut Vm, m: OpaqueRef, k: &str, v: OpaqueRef| {
            let map = Opaque::<MyMap>::from_handle(&m)?;
            map.with_mut(vm, |_vm, map| {         // exclusive, call-scoped
                if let Some(old) = map.inner.insert(k.to_string(), v) {
                    drop(old);                    // releases the displaced box
                }
                Ok(())
            })
        });
    rut_vm::register!(hosts, "my_map::my_map_get", (OpaqueRef, &str) -> Option<OpaqueRef>,
        |vm: &mut Vm, m: OpaqueRef, k: &str| {
            let map = Opaque::<MyMap>::from_handle(&m)?;
            Ok(map.with(|map| map.inner.get(k).cloned())?) // Option<OpaqueRef>
        });
    rut_vm::register!(hosts, "my_map::my_map_size", (OpaqueRef,) -> i32,
        |_vm, m: OpaqueRef| {
            let map = Opaque::<MyMap>::from_handle(&m)?;
            Ok(map.with(|map| map.inner.len() as i32)?)
        });
    hosts
}

Consumer side — an ordinary rut class; every method is exactly one host call:

use my_map::{ my_map_new, my_map_set, my_map_get, my_map_size };

pub class MyMap {
    h: opaque;
}

impl MyMap {
    pub fn new(cap: i32) -> Self { return Self { h: my_map_new(cap) }; }
    pub fn set(mut self, k: str, v: opaque) -> nil { my_map_set(self.h, k, v); }
    pub fn get(self, k: str) -> ?opaque { return my_map_get(self.h, k); }
    pub fn size(self) -> i32 { return my_map_size(self.h); }
}

Consumers recover values with opaque::downcast<V>(box) — nil on mismatch, checked, never a trap (opaque).

The connection contract — two checkpoints

checkpointwhencheckserrors to
compile/verifycompile / verifyevery call vs the declared host rows: concrete types over the crossing set. Checking needs no Rust.rut author
linkbootevery host fn referenced by rut code has a bound, signature-equal impl — a pure data compare (host fns).loader / embedder

A name bound that no decl declares is an embedder startup error (typo guard). Drift between the halves never reaches a rut runtime.

What crosses

The crossing rule is the whole story (value boundary): primitives, str (hashed host-side by content), bytes, tuples and ?T over those, and opaque. Map values cross as opaque — set stores the box unopened, get hands it back. Nothing native re-enters the VM through a vtable, and no native signature has a type parameter.

The typed box view

APIMeaning
Opaque::alloc(vm, val)mint a box; shallow size_of::<T>() charged to the heap budget
Opaque::alloc_hosted(vm, val)opt the payload into a finalize(heap) release hook
Opaque::from_handle(&h)the checked view; a wrong payload T traps naming both sides
o.with(|v| …)shared borrow; nested withs stack
o.with_mut(vm, |vm, v| …)exclusive borrow; a re-entrant call touching the same box traps borrowed by an outer host call
o.handle()the erased OpaqueRef to hand back to rut

Guards live on the store entry and clear on return; to keep data, copy (value boundary).

Notes

  • Hashing: str keys hash by content — a registered builtin impl. Structured keys are the rut wrapper’s business (stringify, or a wrapper defined strategy); no user hashing contract crosses.
  • Containers do not cross: Vec/[T] stay inside the VM. Iterate via per-element fns, keep the index rut-side, or pack into bytes.
  • Builtin answers flow back natively: a fn may return an optional built host-side (?str/?bytes/?opaque answer lanes); rut cannot tell it was not written in rut.
  • Memory: the instance lives in the box; at rc-0 the payload’s finalize hook runs first, then Rust Drop — dropping the container releases every stored handle deterministically, with no collector involvement (the Rc heap). An OpaqueRef’s own Drop releases its reference; dropping a stored handle is the release.

In-tree consumers

Templates — f“…“ across the boundary

Status: this page specifies the template surface; it is not yet wired into the engine. The format-literal behavior it extends is live (literals and inference).

A format literal normally renders to a str at the call site — it desugars to a string concatenation, and the structure of the interpolated values is gone. Hosts that need the structure — localization, structured logging, analytics — must not re-parse strings.

Template is the answer: a builtin value type built only by format literals, chosen by expected type.

One literal, two behaviors

expected typebehavior
strthe ordinary desugaring to concatenation — zero new cost on the hot path, output identical to the plain formatting path
Templatethe literal compiles to a template construction: literal chunks and boxed values, not pre-rendered text
pub host fn label(t: Template) -> nil;      // a host fn taking structure

fn work(name: str, n: i32) -> nil {
    let s = f"hi {name}, n={n}";            // str position: rendered text
    let t: Template = f"hi {name}, n={n}";  // Template position: structure
    label(t);
}

The value

A Template is { parts: [str], args: [opaque] } — the literal chunks, and the interpolated values boxed with their runtime types through the erasure box (opaque — erasure and downcast). Construction is an internal native call — the only way to mint one.

APIMeaning
t.str() -> strrender with rut’s own formatting rules — byte-identical to the str path
t.parts() -> [str]the literal chunks
t.args() -> [opaque]the boxed arguments, in order
t.type_id(i) -> u32argument i’s runtime type id

Nothing else. Like opaque, a template cannot do anything until someone renders it: recover an argument with opaque::downcast<T>(a) — i64 stays i64, so locale decimal separators and number formats are the renderer’s choice, never baked into a pre-rendered string.

At the boundary

A Template parameter arrives as { parts, args } — the chunks and the typed args:

rut_vm::register!(hosts, "app::label", (rut_vm::Template,) -> (),
    |vm: &mut rut_vm::interp::Vm, t: rut_vm::Template| {
        // per-locale formatting: reorder placeholders, re-render numbers
        let _ = (t.parts(), t.args());
        Ok(())
    });

Example: locale-aware rendering

// app.d.rut
pub host fn label(t: Template) -> nil;

pub fn checkout(item: str, price: f64, n: i32) -> nil {
    label(f"{item}: {n} x {price}");
}

The literal in label’s argument position compiles to the template — parts ["", ": ", " x ", ""], args boxed in order. The host renders per locale: reorder the placeholders, format price with the locale’s decimal separator, pluralize around the n arg — i64/f64 arrive as typed values, so none of that is baked into a pre-rendered string:

rut_vm::register!(hosts, "app::label", (rut_vm::Template,) -> (),
    |vm: &mut rut_vm::interp::Vm, t: rut_vm::Template| {
        for (chunk, arg) in t.parts().iter().zip(t.args().iter()) {
            // emit chunk; if the locale grammar needs arg i, recover it:
            // let n: i64 = opaque::downcast-like read on the host side
        }
        Ok(())
    });

Laws

  • The expected type chooses the behavior; a literal never renders “twice”. The str path and Template.str() are byte-identical by construction.
  • Arguments are retained by the template’s boxes; a template keeps its args alive as any cell does (the Rc heap).
  • A Template crosses the host boundary like any builtin — a host fn may return one where the VM expects Template.

core and the swappable packages

The standard library splits in two:

  • core — the only standard. The prelude surface, uniformly engine-implemented: it registers no host bodies and needs no offer — every run’s .compile() auto-rides it.
  • the swappable packages — in-tree rut/host packages that a module declares in its manifest deps (project structure). The community may replace any of them wholesale; nothing in the engine knows their names.

Anything else — gfx, imaging, your own my_map — is an embedder package: a declaration file plus Rust bodies registered the same way (embedding and native modules).

core — the prelude surface

The builtin fns, primitives, and containers are in scope in every compilation unit; no use is needed. A use core::{ … }; statement stays legal but is redundant for them. The exceptions — the import-gated spellings, resolving only through use core::{ .. }: the const NAN, the disposal context DisposalContext, the weak reference Weak<T>, and the closed async pair (Future<T>, RunContext) — the engine’s weave itself never needs the import, only source that spells the names (a cx: T parameter, a launcher’s f: Future<T>, a downcast<Future<..>>). The bracket markers ([disposal]/[iterable]/[constructor]) need NO import — the marker word is the designation, not a name. The two builtin spellings (ambient vs import-gated) are documented in Host fns and declaration files.

Functions

signaturemeaning
panic(msg: str) -> nilabort with the message
string_join(parts: [str]) -> strjoin in one pass
capture_stacktrace() -> StackTraceopt-in stack snapshot: raw frames only, symbols resolved lazily per access
str::from_code(n: u32) -> strthe 1-codepoint string

Primitives and their members

builtin primitive str {
    fn len(self) -> i32;                     // codepoints
    fn code(self) -> u32;                    // the FIRST codepoint (traps on empty)
    fn code_at(self, i: i32) -> u32;         // traps out of bounds
    fn encode(self) -> bytes;                // the UTF-8 octets
    fn slice(self, from: i32, to: i32) -> str; // O(1) view, codepoint bounds
    fn scan(self, from: i32, set: [u8]) -> i64;  // fused classify; (stop << 8) | class
    fn starts_with(self, from: i32, head: str) -> bool;
}

builtin primitive bytes {
    fn len(self) -> i32;                     // octets
    fn decode(self) -> str;                  // UTF-8, lossy
    fn clone(self) -> bytes;                 // the one copy escape hatch
}
// type-methods: bytes::zeroed(n) -> bytes, bytes::from(a: [u8]) -> bytes

builtin primitive opaque {
    fn downcast<T>(o: Self) -> ?T;           // nil on mismatch; `x is T` probes
}

Construction keeps its builtin forms: opaque(v) seals, Weak::new(v) wraps (the class-method construction; the Weak name itself is import-gated — use core::{ Weak }) (opaque, weak references).

Builtin classes

classmembers
StackTracelen() -> i32, name(i) -> str, line(i) -> i32, col(i) -> i32, render() -> str
Weak<T>Weak::new(v) (traps on nil; reference types only), upgrade() -> ?T — nil once the referent died. import-gated — use core::{ Weak }
DisposalContextno members — the engine-minted parameter of a [disposal] member; it exists so the context can grow without touching the marker’s signature

Engine contracts — markers and the closed async pair

The engine’s contracts are spellings on types, standing alone — no interface machinery behind them:

contractspellingnotes
[iterable]fn <free>(self, emit: fn(E) -> bool) on an inherent implfor (x of it) calls that ONE designated member; emit returning false stops; the element type falls out of the marked member’s signature. No import — the marker IS the designation; the builtin sequences’ fused loops never mark one
[disposal]fn <free>(mut self, cx: DisposalContext) on an inherent implthe cell-death contract: the engine calls it at refcount zero (the Rc heap); DisposalContext is import-gated — use core::{ DisposalContext }
[constructor]fn <free>(..) -> Self (or ?Self) on a class’s inherent implthe construction surface: the call form Type(..) binds to the ONE designated member — user-invoked, the lowering byte-identical to Type.<name>(..); one per class, no receiver; newtypes are refused — their positional mint already IS Name(v) (classes)
Future<T>pub builtin class — closedevery async producer’s answer (async and await); import-gated — use core::{ Future } (a launcher’s f: Future<T>, downcast<Future<..>>). No constructor, no impl lane — engine-minted only
RunContextpub builtin class — closed; checkpoint() -> u32, cancelled() -> boolthe cx the weave INJECTS into every async body; import-gated — use core::{ RunContext } (a cx probe’s type). No constructor — engine-minted per async call

The ENGINE weaves without any of them — async frames, the minted cx, and the fused for..of loops never consult user scope: a module that imports nothing still iterates builtins, awaits, and launches.

Numeric methods (per integer width i8–u64)

wrapping_add/sub/mul/shl   — modular, no trap
saturating_add/sub/mul     — clamped at the width's ends
checked_add/sub/mul        — the tuple (value, ok); ok is false exactly
                             when the mathematical result escaped the width

Ambient like the primitives themselves: x.wrapping_add(y) needs no use. The trap-on-overflow +/-/*/<< stay the default operators.

Constants

NAN (f64) — core’s one const, behind use core::{NAN}. All other float constants are calc’s.

The swappable set

A rut pkg below is an ordinary source package — every module links, and the published bundle form is compiled (there is no inline lane; see the compiler pipeline). A host pkg is the declaration surface whose bodies the embedder binds.

packagekindsurface
ink_hosthost pkgcreate_logger(name: str) -> opaque, logger_log(log: opaque, level: i32, msg: str)
inkrut pkg (over ink_host)the Logger class
pouchrut pkgthe growable sequence Vec<T>
flowrut pkg (pouch + nmapset as deps)the push pipeline (Flow<E>, the wrappers)
nmap_host / nmapsethost pkg + rut pkgthe native key table; HashMap/HashSet
jsonrut pkg (strbuild + pouch + nmapset as deps)encodeJson / decodeJson / decodeJsonBytes + the serde interfaces and the wrapper families
strbuild_host / strbuildhost pkg + rut pkgthe builder rows; the StringBuilder class
calchost pkgthe Math namespace
async_host / futureshost pkg + rut pkgthe launcher rows; launch_future / sleep
http_host / httphost pkg (a mod-tree surface: net/ + stream/) + rut pkgthe std HTTP lanes
bench-crosshost pkgthe crossing-tax benchmark rows

ink_host and ink — logging

There is no global output builtin. All logging goes through a used logger; the host owns the sink, and an uninstalled sink is a silent no-op — a script cannot accidentally spam an embedded host’s stdout.

use ink::{ Logger };

entry fn main() {
    let log = Logger("app");
    log.info(f"started");
}
started

Logger("app") constructs through the class’s [constructor] member — the call form spells the construction.

methodlevel passed to ink_host
debug(msg)0
info(msg) / log(msg)1
warn(msg)2
error(msg)3

Embedder side: .pkg(rut_std::logger::pkg(|s| println!("{s}"))) on the run chain (embedding). Offering ink pulls ink_host along (deps).

pouch — Vec<T>

The growable sequence, written in rut over the fixed [T] array:

membermeaning
new() / with_capacity(cap) / filled(v, n)construction ([v; n] under the hood)
push(v) / pop() -> Tpop returns the removed element; traps on empty — guard with len() > 0
get/set via v[i], for (x of v)compiler-lowered; element access aliases the stored cell
from([T]) / as_array() -> [T]bridges to the fixed array
freeze() -> bytesthe Vec<u8> → immutable bytes copy (exactly the live length)
slice(from, to) -> ?Vec<T>compiler-lowered O(1) fixed-length window; detaches on grow

flow — the push pipeline

Flow<E> chains the push contract: a type is iterable when it marks an [iterable] member, and a Flow wraps one drive in adapter stages — a closure per STAGE, never per element. Pipelines are the clarity tier; the fused builtin loops stay the perf tier.

Entry and sink are interfaces, satisfied structurally: IntoFlow<E> is fn into_flow(self) -> Flow<E> — Flow itself carries the identity member (a chain re-enters as a source), and the builtin structural targets (which can never carry members) enter through the spelled adapter wrappers ArrFlow<T>, StrFlow, BytesFlow, and VecFlow<T>. FromFlow<E> is the no-self sink member fn from_flow(it: Flow<E>) -> Self — carried by the wrappers VecFlow<T> (with collected() unwrapping) and SetFlow<T> (with items()). Nothing is auto-inserted: the call site spells the wrapper, every time.

use pouch::{ Vec };
use flow::{ Flow, IntoFlow, FromFlow, VecFlow };
use ink::{ Logger };

entry fn main() -> nil {
    let log = Logger("flow");
    let nums: Vec<i32> = Vec::new();
    nums.push(1); nums.push(2); nums.push(3); nums.push(4);
    let src: VecFlow<i32> = VecFlow(nums);       // the spelled manufacture
    // entry → adapters → consumers: one drive, stage by stage
    let picked: Flow<i32> = src.into_flow()
        .map(fn(x: i32) -> i32 { return x * 10; })
        .filter(fn(x: i32) -> bool { return x > 15; });
    log.info(f"picked={picked.count()}");
}
picked=3
surfacemeaning
x.into_flow() -> Flow<E>the entry — IntoFlow<E>’s member; Flow carries the identity row, the wrappers ArrFlow<T> / StrFlow / BytesFlow / VecFlow<T> carry the rest
VecFlow<T>(vec) / ArrFlow<T>(arr) / StrFlow(s) / BytesFlow(b)the adapters — newtype wrappers manufactured at the call site; a primitive or bare container cannot carry members, the wrapper does
map<R>(f: fn(E) -> R) -> Flow<R>transform — introduces a new type variable, so annotate the lambda or spell the type argument; a fn path infers
filter(p: fn(E) -> bool) -> Selfkeep the elements the predicate admits
take(n) / skip(n)the first n / everything after the first n — the counter is a record the drive mutates, so a drained stage stays drained
count() -> i32 / for_each(f) / fold<R>(init, f) -> R / enumerate() -> Flow<(i32, E)>the one-drive consumers
W<T>::from_flow(it: Flow<E>) -> W<T>the sink — FromFlow<E>’s no-self member, carried by VecFlow<T> and SetFlow<T>; collected() / items() unwrap the materialized container
for (x of chain)chains are iterable — the [iterable] member on Flow<E> feeds the ordinary desugar

Import the interfaces you spell and the pipeline type: use flow::{ Flow, IntoFlow, FromFlow } — the use-both law names each one.

Deferred, documented: IntoFlow for the mapset (nmapset ships no host-table walk — json’s map encode grows with it) and a map sink (nmapset’s HashMap has no wrapper family in flow yet — json’s decode-only JMap* wrappers are the precedent such a family would follow).

nmapset — HashMap/HashSet

Thin wrappers over the native key table (nmap_host rows): the whole state is one opaque handle, every method one host call.

pub class HashMap<K requires i8 | i16 | i32 | i64 | u8 | u16 | u32 | u64 | bool | str | bytes, V> {
    [constructor] pub fn new() -> Self;
    pub fn with_capacity(n: i32) -> Self;
    pub fn put(mut self, k: K, v: V) -> bool;      // true = newly inserted
    pub fn get(self, k: K) -> ?V;                  // the STORED cell, not a copy
    pub fn has(self, k: K) -> bool;
    pub fn remove(mut self, k: K) -> bool;
    pub fn len(self) -> i32;
}
pub class HashSet<T requires ..same key set..> { new, with_capacity, put, has, remove, len }

Both classes designate new — HashMap() / HashSet() spell the construction; with_capacity stays a named constructor.

Laws: the key set is closed (no floats — no stable equality; encode a custom key canonically to bytes); get answers the stored cell, so two gets of one key name one value until a replace; values release host-side. str keys hash by content; str keys also carry *_range(parent, off, len) members keyed by a byte range of the parent string — a range key is the same key as its content, with no key cell minted on a probe (string views).

calc — the Math namespace

use calc::{ Math };
use ink::{ Logger };

entry fn main() {
    let log = Logger("t");
    let x = 3.0f64;
    let y = 4.0f64;
    let d = Math::sqrt(x * x + y * y);
    let a = Math::abs(x);
    let hf = Math::sqrt_f(2.0);            // f32 twin — the width is in the name
    log.info(f"{d} {a} {hf}");
}
5 3 1.4142135

Functions (each with an _f f32 twin): sqrt, floor, ceil, round, trunc, exp, ln, log2, log10, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, pow, atan2, hypot, copysign, fma, plus the float helpers abs, min, max, signum. Constants: Math::PI, TAU, E, SQRT_2, LN_2, LN_10, LOG2_E, LOG10_E, INFINITY, NEG_INFINITY, EPSILON, MAX, MIN, MIN_POSITIVE. Integer numeric methods are core’s, not calc’s.

json — the serde package

Pure rut, zero host fns — offering json adds no host bindings. Its container wrapper families are json’s OWN source, and strbuild, pouch, and nmapset are plain deps that ride along transitively (dependency kinds).

fn encodeJson<T requires JsonSerialize>(v: T) -> (?str, ?EncodeJsonError);
fn decodeJson<T requires JsonDeserialize>(s: str) -> (?T, ?DecodeJsonError);
fn decodeJsonBytes<T requires JsonDeserialize>(b: bytes) -> (?T, ?DecodeJsonError);

pub interface JsonSerialize   { fn encode(self, mut w: JsonWriter) -> ?EncodeJsonError; }
pub interface JsonDeserialize { fn decode(mut r: JsonReader) -> (?Self, ?DecodeJsonError); }
  • The pair law: (?T, ?E) with exactly one nil — success = (value, nil), failure = (nil, err). Encode returns ?EncodeJsonError because a cyclic structure is expected, recoverable data, not a trap.

  • Direct decode: no intermediate document; a type’s decode reads its expectations straight off the cursor. A Vec<Row> decode mints exactly the program’s values, once.

  • Satisfaction is structural: your type satisfies JsonSerialize/JsonDeserialize by spelling the members on its own inherent impl — impl Row { pub fn encode(self, mut w: JsonWriter) -> ?EncodeJsonError { .. } }. json owns the interfaces; user types satisfy them without asking.

  • The wrapper law: primitives and bare containers never satisfy — no inherent members to have. The wrapper families are the spelled, per-call manufacture: encodeJson(JsonI64(64)), never encodeJson(64) — nothing is auto-inserted, forever.

    wrapperwrapsmembers
    JsonI64 / JsonF64 / JsonBool / JsonStri64 / f64 / bool / strboth directions; get() unwraps
    JsonU64u64decode-only — satisfaction is per-interface, so it satisfies JsonDeserialize alone (an out-of-i64-range producer has no encode row); get() unwraps
    SOpt<T requires JsonSerialize>?Tboth; nil → null, null → nil; get() unwraps (the encode-direction bound means a decode-only T cannot ride it)
    JsonArr<T requires JsonSerialize>[T]both; to_arr() unwraps
    JsonVec<T requires JsonSerialize>Vec<T>both (over pouch’s Vec<T>); to_vec() unwraps
    JMapStr<V> / JMapI64<V> / JMapBool<V> / JMapU64<V> / JMapBytes<V>HashMap<K, V> per key shapedecode-only (over nmapset’s HashMap); to_map() unwraps — JMapBytes answers the bytes-keys disclosure
    JSet<T requires JsonDeserialize>HashSet<T>decode-only (over nmapset’s HashSet); to_set() unwraps
  • Numbers: i64 accepts integer lexemes only (overflow/decimal lexeme = WrongType, never a silent wrap); f64 parses IEEE-exact in the common range, ±1 ulp beyond (disclosed); encode renders the shortest round-trip decimal.

  • Depth: capped at 128 both directions, recoverable (DecodeErrorKind::Depth / EncodeErrorKind::Depth).

  • Errors: payloadless kind enums + fixed-field structs — DecodeErrorKind { Unexpected, Truncated, InvalidUtf8, WrongType, Depth, Trailing }, EncodeErrorKind { Depth, NotFinite, KeyUnsupported }; decode details carry at/got/expected, encode details carry at and the lazily built $.rows[3].name path.

  • decodeJsonBytes is strict UTF-8 (InvalidUtf8), never lossy.

  • Ownership: json owns everything — the interfaces AND the container wrapper families (json’s own source); pouch and nmapset are plain deps, so the wrappers’ use heads resolve in every consumer’s closure (dependency kinds).

  • The writer accumulates through strbuild’s StringBuilder; the reader rides the core str::scan/starts_with primitives and O(1) string views.

strbuild — the builder

The builder is a host package now (the ink/Logger pattern): the strbuild_host decl pkg declares the five rows (sb_new / sb_push / sb_push_code / sb_len / sb_finish, registered under the pkg-name scope), and the strbuild package wraps them in the StringBuilder class. Core ships no string-building machinery; offering strbuild pairs with the bodies:

use ink::{ Logger };
use strbuild::{ StringBuilder };

entry fn main() {
    let log = Logger("t");
    let k = "name";
    let mut b = StringBuilder::with_cap(1024);   // octet hint
    b.append(f"{k}=");
    b.append_code(0x21);
    let s = b.build();                          // the ONE materialization
    log.info(s);
}
name=!
membermeaning
new()grow from small — the designated [constructor]: StringBuilder() spells it
with_cap(cap: i32)pre-size to an octet hint (negative traps; the hint is advisory — identical behavior for every cap)
append(mut self, value: str)amortized O(|s|), in place
append_code(mut self, cp: u32)one codepoint; invalid scalars mint U+FFFD
len() -> i32codepoints so far, O(1)
build() -> strfresh immutable str; the builder keeps its buffer

Sharing is the default: appends through an alias (or a mut parameter) land in the caller’s document; copies happen at exactly two engineered points — build’s materialization and growth’s prefix move. Growth consults the embedder’s heap budget BEFORE growing (the geometric next-capacity is charged), so the wasm 4 MiB cap governs builder growth exactly as it governs engine allocations.

Embedder side: .pkg(rut_std::strbuild::pkg()) on the run chain. Offering strbuild pulls strbuild_host along (deps); offering json pulls both (its writer rides the builder).

For the common accumulator shape no builder is needed at all: out = f"{out}{t}" appends in place, linear in the total output (f-strings).

calc’s company: async and http

  • async_host declares the engine rows (__launch, __abort, __sleep, __sleep_yield); futures restores the typed surface: launch_future(f: Future<T>) -> LaunchedFutureHandle<T>, LaunchedFutureHandle::abort() -> bool, sleep(ms: u32) -> Future<nil>. Each embedder offers rut/futures (a rut_native::tree_pkg walk) and installs rut_std::async_host::pkg() on the chain; a world that offers neither has no launcher (launched futures, host futures).

  • http_host declares the transport rows (three async, five sync readbacks) as a surface tree — net/ carries the send + the response readbacks, stream/ the body lanes (project structure); http wraps them in HttpClient / RequestBuilder / Request / Response / ByteStream — async only at the points that really wait, and HttpClient() constructs through the designated new:

    use http::{ HttpClient, ClientQueryMethod };
    
    let resp = await HttpClient().request()
        .method(ClientQueryMethod::Post)
        .url("https://example.com/api")
        .header("Accept", "application/json")
        .body(payload)
        .build()
        .send(cx);
    

    send resolves at headers; body(cx) drains the wire; byte_stream()/next(cx) walk it in chunks. Status 0 is reserved for transport failure. The reqwest lane is native-only.

Offering

  • core auto-rides — every run’s .compile() offers the core prelude unless a pkg named core was offered. calc and the async pair are ordinary tree packages: the host offers them (rut_native::tree_pkg(..)) when the program’s surface names them, and binds the bodies (rut_std::math::pkg(), rut_std::async_host::pkg()) on the chain (embedding). The rut CLI offers the tree packages a loose file names by use (the rut CLI).
  • The rut packages over host rows (ink, strbuild, nmapset, futures, http) pull their decl pkg along (deps) — the embedder pairs the mount with the bodies (rut_std::logger::pkg() et al), exactly ink + logger::pkg. json and flow pull their own wrapper-deps the same way; there is no special compilation lane — every module links (the compiler pipeline).
  • Generic exports link on their own: instantiation happens where the body lives, consumers request it, and Vec<i64> is one type program-wide (the compiler pipeline).

The compilation model

rut compiles deterministically: a declared closure is a pure input, and whole-program compilation is the deterministic reference — the same closure in ⇒ the byte-identical program out, on any machine, any day. A package compiles to an object (code + surface + templates); objects and their symbol tables form an archive — the .rutbundle, the sole publication unit. A consumer compiles its own source against the archive’s surface; the instantiate stage materializes the generics the consumer spelled; the linker resolves and relocates — arithmetic only. A staged build is correct exactly when it equals the reference build.

The pipeline

publish:  compile (pkg → object + surface + templates)
          → emit declaration entry (generated mod.d.rut)
          → archive (shade the closure)

consume:  compile (app; validates `use` against the archive surface)
          → instantiate (ledger hit | template substitution + repr refold)
          → link (resolve + relocate — arithmetic only)
          → load (mount, install host rows, rebase, verify, run)
stagesidewhat happensmore
compilebothsource → object: lex/parse, resolve, typecheck, monomorphize, optimize, encodeThe compiler pipeline
declaration entrypublishthe group’s surface text, generated at pack — never hand-maintainedModule bundles
archivepublishthe object set + symbol tables, shaded to the closure, one fileModule bundles
instantiateconsumethe only consumer-side codegen: template substitution, ledger lookups, repr refolds — one row program-wide per shapeThe compiler pipeline
linkconsumescope resolution + relocation + merge — arithmetic only, never type-aware, never code-generatingLoading and the embed loop
loadconsumemount, install host rows, rebase the ids onto the loader’s numbering, verify, runLoading and the embed loop

The stages are the model’s wiring, not the API’s surface: embedders compose intent-level verbs — publish is rut pack (The rut CLI); consume is the run chain, RutRun::new().pkg(..).entrypoint(..).compile() (Embedding and native modules).

The reference, and the equivalence contract

Two statements are the mode’s contract:

  • The reference is deterministic. Whole-program compilation is a pure function of the declared closure: byte-identical everywhere, independent of caches, mounts, or how a consumer happens to spell its generics. Same source + same dependency versions + same compiler version ⇒ byte-identical output — this is what makes bundles diffable and content-addressable (The compiler pipeline).
  • Staged equals reference. A staged build — the archive-mounted lane — is correct exactly when it produces what the reference build would have for the same closure. The equivalence is pinned, not assumed: goldens compile one closure through both lanes and compare the results — the same run behavior, and identical bytes where the lanes make bytes comparable.

The reference is also the widest dialect: it serves any source closure. A staged build derives from the reference and is licensed by the equivalence — it never produces more than the reference would.

Instantiation is lazy

Only consumer-spelled shapes materialize. A compiled owner carries two things relevant here:

  • its ledger — the (owner, decl, arguments) rows its own pack closure spelled (the pre-instantiated bodies), and
  • its templates — every exported generic decl compiled once against #<param> placeholder rows, riding inside the binary (Module bundles).

At the consumer’s instantiate stage, a request the ledger satisfies is a lookup; a shape the ledger misses monomorphizes from the template — one row program-wide, owner-anchored, indistinguishable from a pack-time one, nothing persisted. A shape nobody spells compiles nowhere: that laziness is what keeps a consumer’s one-off Vec<Todo> out of every other consumer’s program.

Two truths: linking and editing

Every published group carries both truths, and neither contaminates the other:

  • The object (mod.rutc) is the linking truth: bodies plus the surface on the wire. A consumer binds a compiled group’s exports from the binary alone (Module binary and verification).
  • The declaration entry (mod.d.rut) is the editing truth: the group’s surface text, generated at pack time from the validated surface — never hand-maintained, so it cannot drift from what links. This is universal (wire 12): every group carries exactly one. A host group’s entry IS its source (its tree consolidated into the inline form); a compiled group’s entry is rendered, round-trip gated, and omitted under --strip.

This is the TypeScript .d.ts pattern: ship the declaration beside the compiled code, generate it from the thing that links, and let the runtime ignore it. The loader never reads declaration entries of compiled groups; they ride for humans and tooling.

The editor’s ladder

Editor-facing data degrades gracefully — and nothing editor-facing is ever load-required:

  1. Declaration entry (full) — names, types, structure: the editor’s primary view of a dependency. Go-to-def on a dependency’s member lands on the declaration — the declaration is where the name is published; the body is the owner’s private code. The entry is one Decl parse per group; a consolidated entry’s inline mod nesting stamps each row with its mod path.
  2. Object surface (names + types) — the binary’s own surface section, always present, is the floor: tooling can read names and signatures from the decoded object alone. It answers when the entry is absent (old bundles, stripped packs).

Stripping removes names for runtime privacy and carries a private sidecar to restore them (Symbol stripping and .rutsym sidecars); the surface rows the linker and the instantiation machinery consult survive by construction, so the ladder’s floor holds on stripped bundles too.

Where to read more

The frontend

The frontend turns source text into a checked-syntax tree: source (UTF-8) → lexer → tokens → parser → AST, with one diagnostics model flowing out of every stage. It has no type knowledge — resolution and checking begin in the compiler pipeline.

The implementation is three crates: rut-lexer (span, token, lexer, diag), rut-ast (the arena tree and its dumper), and rut-parser (the frame machine and its expression engine). Everything is no_std-clean and wasm-compatible, so the same code runs in the CLI, the LSP, the formatter, and the browser playground.

The contract

Four invariants hold for any input, hostile included:

invariantmechanism
C1Flat AST — nodes are records in one arena; children are NodeIds, never boxed pointers, built bottom-up. Drop/clone are flat Vec ops.AST
C2No native recursion — an explicit frame stack handles structure; expressions use an iterative operator/operand engine. Host stack use is constant regardless of input.parser
C3Depth budget, not stack exhaustion — nesting over the budget is a normal diagnostic, never a host crash.budgets
C4Lookahead discipline — local decisions peek at most 4 tokens; the two decisions that need more use read-only balancing scans. The cursor is monotone non-decreasing for the whole parse, recovery included — there is no checkpoint/rollback.lookahead

The lexer and parser are pure functions — lex(src) -> (Vec<Token>, Vec<Diag>) and parse(src, mode) -> (Ast, Vec<Diag>) — so they are fuzzable and reusable in an LSP or formatter with no VM present.

The lexer

  • One flat Tok enum for literals, punctuation, and operators. Keywords are ordinary Idents; the parser matches them by interner name. Reserved words are rejected by the lexer with a message naming the rut replacement (interface, private, void, in); ?. and ?? are punctuation-level rejections, a separate mechanism.
  • Maximal munch with an explicit longest-match table; / vs // vs /* resolves with one lookahead. Compound assignment operators are one token each (+=, <<=, &&=, …), so there is no munch ambiguity.
  • Numeric literals: 0x/0b/0o, _ separators, and per-width suffixes (u8..u64, i8..i64, f32/f64). Unsuffixed integers default to i32, unsuffixed floats to f32.
  • Comments are dropped (doc comments are re-attached by the formatter’s gap-scan, below).

Format strings

f"..." is the one construct the lexer must understand structurally, because placeholders hold expressions, not strings:

struct FStrTok { parts: Vec<FPart> }
enum FPart {
    Lit(String),      // decoded like a plain string; {{ }} -> { }
    Hole(Vec<Token>), // a FULLY LEXED token stream, `}`-terminated
}

The lexer enters hole mode after { (not {{), balances braces, and lexes normally until depth 0. Holes are re-lexed, not stored as text, so placeholder expressions carry real spans inside the literal’s span. A hole may contain any expression except a string literal — a quote inside a hole is a lex error with a bind it to a name first note. See Templates for the surface semantics.

Raw strings r"..." carry everything up to the closing " literally; \" inside a raw string does not close it.

Nesting budgets

Two budgets make C3 a law:

  • NEST_MAX = 1024 — the lexer’s bracket depth budget (rut-lexer/span.rs). Exceeding it is one clean diagnostic at the offending opener.
  • EXPR_MAX = 64 — the parser’s expression-nesting budget. The frame machine itself has no host-stack cost, but downstream recursive walks (AST dump, typecheck) do; the cap keeps the trees they visit shallow.

Both produce the same diagnostic — nesting too deep — and neither can overflow the host stack.

The parser

One loop over the token slice drives two mechanisms:

  • A frame stack handles structure — one frame kind per grammar rule (Module, Item, Block, TypeArgList, Pattern, Arm, Impl, …). A rule that needs a child pushes a frame; a completed frame pops and hands its NodeId to the parent.
  • An embedded Pratt engine handles expressions — an operator stack plus an operand stack of NodeIds. Binary and assignment steps push an operator; reductions pop operands and push one node, bottom-up.

There is no grammar generator and no left-recursion handling. Binding powers, loosest to tightest:

precassocoperators
1right= += -= *= /= %= &= |= ^= <<= >>= &&= ||= (target must be a path or index)
2–=> lambda bodies — decided by the scan below, not by binding powers
3left||
4left&&
5left== !=
6left< > <= >=
7left| ^
8left&
9left<< >>
10left+ -
11left* / %
12leftas — numeric cast; the RHS is a type-naming position
13rightunary - ! ~
14leftpostfix: .name, .name<..>(..), (..), [..], ?

Postfixes chain in one loop, so p.value.x and arr[i].push(x) compose without special cases. is (type test) is a keyword; as is the only cast.

Lookahead

rut’s grammar makes shallow peeking enough: statements are keyword-led, { never starts an expression, imports are flat, and paths are ::-separated (one Colon2 token between segments, looped in the atom stage — no lookahead).

decisionmechanism
item dispatchpeek 1 (use let enum struct class interface impl fn)
statement vs expression-statementpeek 1 (leading keyword)
for-of vs C-style forpeek 4: for ( let Ident <of or =>
instance vs class methodpeek 4: fn Ident ( <mut? self? …>
struct literal vs path expressionpeek 2: Ident { ⇒ literal (classes have no instance literal)
when-arm body formpeek 1 after -> ({ ⇒ block arm, else expression arm)
if atom vs statementpeek 2: if ( in expression position ⇒ the if ATOM (statement-leading if is claimed by the statement grammar first)
postfix loop steppeek 1 (. ( [ ?)
assignment targetno lookahead — parse, then validate

Two decisions need more than 4 tokens and use scans — read-only, commit-once, never a guess:

  • Lambda vs parenthesized expression. Scan to the matching ); it is a lambda iff the tokens form a valid parameter list and => follows (an optional -> Type may sit between). Otherwise a comma inside the parens errors at the comma — rut has no tuples-as-expressions spelling — with a note: if you meant a lambda, add =>.
  • Generic call vs < comparison (Vec<f32>(n) vs a < b > (c)). Scan from the < tracking angle depth; a >>/<< consumed where a closer/opener is expected counts as two, so Vec<Vec<i32>> needs no re-lexing. Generic arguments commit iff depth returns to 0 on a > and the very next token is (. a < b > (c) is not expressible unparenthesized — write (a < b) > (c).

Scans never mutate parser state. Peeking at arbitrary distance is allowed; checkpoint/rollback is not — the API does not exist, so the monotone-cursor invariant (debug-asserted) cannot be violated, even during error recovery.

Recovery

Within a file the parser resynchronizes at ;, }, or the token after a balanced block and keeps parsing — a file yields many diagnostics, not one. Resync only ever skips forward.

Declaration mode

The mode is chosen by file extension: Mode::Impl for .rut, Mode::Decl for .d.rut. Both share one grammar; declaration mode adds the surface declarations — host fn, host struct, and the builtin rows (prelude builtin / pub builtin, see Host fns and declaration files) — and forbids bodies: any block, impl blocks included, is rejected with implementation in a declaration file. Implementation mode rejects host/builtin with the mirror message. The full surface and how bodies bind at load time live in Host fns and declaration files.

Declarations-only module scope is enforced by the parser itself: a statement at module top level is a syntax error, not a semantic one. The grammar itself is specified in Lexical structure and Modules and visibility.

The AST

Nodes are plain records in one arena; children are NodeIds into it. Spans sit on every node; there are no String keys — names are IdentIds into an interner that lives in rut-core, shared by the AST, the type table, and the module binary’s name table. The interner pre-interns a fixed well-known table (rut_core::sym: self, Self, nil, main, iterate, the builtin members, the primitives, …), so ids below well_known_len mean the same name in every interner instance and special names compare as IdentId equality, never by text.

struct Ast { nodes: Vec<Node>, root: NodeId }
struct Node { span: Span, kind: NodeKind }

enum NodeKind {
    // items
    Use { pkg: IdentId, names: Vec<IdentId> },
    Let { vis, name: IdentId, ty: Option<NodeId>, init: NodeId },
    Enum { vis, name, members: Vec<IdentId> },
    Struct { vis, name, generics, fields: Vec<NodeId> },  // fields only
    Class  { vis, name, generics, fields: Vec<NodeId> },  // fields only —
                                                           // methods live in impls
    Interface { vis, name, generics, methods },           // signatures only
    Impl      { generics, bounds, target: NodeId },       // inherent only —
              // no trait_ref: `impl I for T` does not parse
    Fn     { vis, name, generics, params, ret, body },
    SurfaceFn / SurfaceClass,                             // .d.rut only
    // statements
    LetStmt, If, While, ForOf, ForC, Return, When, ExprStmt,
    // expressions
    Lit(Lit), Path(Vec<IdentId>),
    Call { callee, generics, args },
    Method { recv, name, generics, args },
    Field { recv, name }, Index { recv, idx },
    Unary, Binary { op, lhs, rhs }, Assign,
    Block { stmts, tail },               // the block value; tail: Option
    Lambda { params, ret, body }, When { scrut, arms },
    If { cond, then, els },              // the if ATOM (statement-if above)
    Try { expr },                 // postfix ?
    FStr { parts },               // holes are NodeIds
    StructLit { ty, fields }, Array { elems }, Conv { ty, expr },
}

Stable NodeIds are the rest of the pipeline’s currency: the checker keys side tables by node id, diagnostics reach spans through them, and the LSP, formatter, and dumper hold copyable references with no reparenting.

What the AST does not contain: no new, no switch/case, no ?. or ?? — the lexer rejects those words before parsing. There are no paren nodes either: the parse’s grouping is the tree.

Diagnostics

struct Diag { span: Span, msg: String, file: Option<String>,
              labels: Vec<(Span, String)>, notes: Vec<String> }

One renderer serves every frontend stage: a primary error: line, the rustc-style --> file:line:col arrow (1-based line and char column; the label is the module name — a pkg spec, a spec/path child, a real path from rut fmt), the caret line under the span, secondary labels, and notes, all over byte offsets (rut_lexer::diag::render_diags). Rendering sorts by (file, span start) and groups by file, so multi-file output is stable; a diag with no file of its own spells the fallback --> line L, column C. Suggestions are part of the message set: did you mean when? for switch/match; bind it to a name first for string literals in format-string holes; classes have no instance literal — use Circle(..) for Circle { .. } on a class.

The compile stops before IR if any diagnostic exists — a module with diagnostics never produces bytecode. See Diagnostics, traces, and symbolication for the runtime half of the story.

The formatter

rut fmt (crate rut-fmt, CLI subcommand) reprints a parsed-clean module from the AST:

  • Comment gap-scan — comments live in the byte gaps between token spans, so the formatter recovers every // and block comment with zero lexer/parser changes: trailing runs go on their element’s line, own-line runs at the enclosing indent.
  • Parens and literals re-derived — the printer re-parens only where flat precedence would invert the tree, re-spells floats shortest round-trip from their bits, and re-quotes strings by the exact inverse of the lexer’s escape set (0xff legitimately becomes 255).
  • Tested invariants — every corpus file formats, reparses clean, and is idempotent (fmt(fmt(x)) == fmt(x)); probe programs run through the full pipeline before and after formatting and log identical output.
  • Refusal law — a source with diagnostics is refused: rendered diagnostics, exit 1, nothing rewritten. The formatter never guesses.
  • Style is the package’s — the nearest ancestor rut.jsonc’s style block sets indent_width (1–8, default 4) and max_width (≥ 20, default 100); no manifest means defaults. See Project structure and rut.jsonc.

Testing

The corpus is the conformance suite: every examples/**/*.rut, examples/**/*.d.rut, and playground classic must parse with zero diagnostics. Parser invariant tests include 100k-deep ((((, [[[[, {{{{, unary chains, and nested generic arguments — each yields exactly one nesting too deep diagnostic — and fuzz targets assert no host stack overflow and no cursor rollback. Formatter tests pin the round-trip and idempotence laws above.

The compiler pipeline

Compilation is AOT, in-process, and deterministic. There is no JIT and no deoptimization: whatever the checker proves is final, and the emitted bytecode is the whole story. The model around this stage — the deterministic reference, the archive, instantiate + link — is The compilation model.

source ─► lex/parse (rut-lexer, rut-parser)      [The frontend](frontend.md)
      ─► resolve + typecheck (rut-lir/check)
      ─► monomorphize + compile bodies (rut-lir/lir)
      ─► optimize (fold, inline, CSE/LICM, peephole, SROA)
      ─► FuncCode — typed register bytecode       [Typed bytecode](typed-bytecode.md)
      ─► link + flatten (rut-core/link)           [Loading](loading.md)
      ─► encode (rut-core/binary)                 [Module binary](module-binary.md)

The unit of compilation is the module. A .d.rut declaration surface runs through resolve/typecheck and stops there — it has no bodies, so it publishes a signature surface, never code.

Stages

stagecratein → outnotes
lex + parserut-lexer, rut-parsersource → AST + diagsflat arena, no recursion
collectrut-lir/check/collectAST → types, interfacesper-module symbol tables
resolverut-lir/check/resolvepaths → symbolsimports, Self, visibility, use-path routing
typecheckrut-lir/check (Ctx)expressions → TyIdsbidirectional inference, fused with body compilation
monomorphizerut-lir/check/instgeneric calls → instantiationsa work queue; HIR contains no generic code
compile bodiesrut-lir/lir (FnCompiler)instantiations → FuncCodeone function at a time
optimizerut-lir/lir (peephole, sroa, …)FuncCode → FuncCodefixed pipeline, no flags
link + flattenrut-core/linkmodules → one Programtype-id rebase, interface-table merge
encoderut-core/binaryProgram → bytesversioned, little-endian, hash-stable

The middle stages are deliberately one crate: the checker’s monomorphization queue drives the body compiler and the body compiler reports new instantiations back through the checking context. The fusion keeps instantiation admission exact — every substitution-completing call site is checked against its inline requires bounds as it is compiled.

Resolve

Name resolution walks the AST and binds every path to a symbol:

  • use imports resolve against the run’s offered pkgs — exact, single-step: a use path resolves only if a pkg with that name was offered. Missing pkgs diagnose against the consumer manifest (see Loading and Dependency kinds).
  • Self binds inside impls; pub visibility is checked per Modules and visibility.
  • Struct-vs-class is decided here: literals are legal only for structs; classes construct through their class methods.
  • is expressions resolve their right-hand side to a concrete type or an interface instantiation id; is on an erasure-typed receiver answers by the box (see opaque — erasure and downcast).
  • host/extern surface references resolve against the declaration surfaces of the packages the module imports, with slot ids attached to every member reference.

Typecheck

Bidirectional inference: expected types flow down, literal types flow up. Every expression node is decorated with a type id (an index into the module’s type table). Generic calls get their instantiation inferred or take it explicitly (downcast<Point>(o)).

Laws enforced here:

  • The == law — primitives and str compare by value; every other cell type compares by identity; nullable ?T operands and tuple operands are a compile error (pattern-match instead — destructure the pair). A lint flags == between two obviously fresh composites.
  • is folding — when the receiver’s static type already answers the question (a concrete receiver, d: I is I), the expression folds to a constant and an always-true/false lint fires.
  • Union bounds — a generic parameter’s requires T1 | T2 bound is checked at every site that completes the substitution (Type aliases and union bounds).
  • Interface bounds — a T requires I bound checks the interface’s member set once, where T is chosen: at a generic call’s instantiation and at a satisfying value’s crossing. A type without the members is refused there, naming the first missing member (Interfaces and dispatch).
  • The crossing rule — an entry fn’s published signature may only use types that cross the host boundary: primitives, str, bytes, opaque, ?T over a crossing type (nil-flattened), and tuples of crossing types. A violation is a compile error, so a bad surface never reaches the embedder at load time (The host boundary).

There is no orphan rule to enforce — nothing registers. Satisfaction is checked at boundaries only, so the checker’s interface work is a per-call-site member-set match, never a program-wide search.

Monomorphization

Generic functions never reach a binary. The checker’s instantiation queue compiles one concrete copy per substitution; the queue closes because instantiating a body can enqueue more. Instantiation names ([i32], Vec<f32>) are synthesized into the shared interner, and type_id<T>() folds to a constant from the type table at this point — it never executes at runtime.

The same law fixes WHERE an instantiation compiles: where the body lives. Vec<i64> is one type program-wide — the declaring package owns every instantiation of its generics, and consumers request them: a consumer’s spelling lays out the concrete shape and routes the bodies to the declaring package’s compile, so a linked library’s make() -> Vec<i64> and the consumer’s own Vec<i64> are one row, and the binary ships one copy of each instantiation’s code.

There is no splice lane and no inline flag left: every module links. A class’s methods cross on the surface’s inherent rows (the ordinary call boundary — the ink-pattern packages over host rows compile like any other), and a generic export links owner-anchored, the way the section above describes. The swappable std packages (ink, pouch, flow, nmapset, json, strbuild, futures, http) are ordinary linked packages. See Project structure and rut.jsonc.

The type lattice

In a no-JIT VM, compile-time type knowledge is the only knowledge. The IR tracks a per-value lattice:

exact concrete  >  I (interface-typed, satisfies I)
  • Exact types compile to direct calls and known layouts.
  • Interface-typed values (s: Drawable) are unsized: the payload lives in a heap cell and the slot stores the cell handle. One indirect itable call per multi-origin use; fields are inaccessible; no inlining without evidence. The cost is per-call, never per-field — and when a call’s receiver is statically concrete (a single tracked origin, a monomorphic body), the call devirtualizes at body-compile time and the dispatch overhead is zero.
  • Erasure sits off the lattice. The opaque primitive is reached only through the type-call opaque(v), and opaque::downcast<T>(o) is the refinement: the successful branch re-enters the exact lattice position, so downstream code optimizes as if nothing was erased. Downcast checks are pure dataflow — repeated checks CSE, invariant ones hoist, and a chain over one cell folds to a type-id switch. What the compiler must not assume is the type inside a box at a given program point; speculative devirtualization through opaque is JIT behavior and does not exist.
  • The slice tier parallels interface widening: Array<T, N> | Vec<T> (concrete) > Slice<T> view (unsized). N is part of the type’s identity; slices are never boxed or erased.

The intended program shape: exact types on the hot path, interface-typed values where polymorphism is real, opaque only inside heterogeneous storage. Lints flag downcast in loop bodies and erasure crossing non-storage function boundaries.

Optimization

A fixed pipeline with no flags:

  1. Folding — constant arithmetic, type_id<T>(), Array<T, N>.len() → the constant N (with const-index bounds checks folded against it), statically-decided is probes, dead branches.
  2. Inlining — single-callee calls and small bodies (a callee op-count budget). Cross-module inlining after linking is future work; binaries carry no cross-function inlined code.
  3. CSE / LICM over pure operations — type-id loads, downcast checks, field loads on immutable records.
  4. Peephole + SROA — the rewriters re-intern operand pools on register remap, so pool sharing stays consistent (see Typed bytecode). SROA declines a record whose class carries a [disposal] member: the cell’s death is observable (it runs runs at refcount zero), so its mint is never deleted.
  5. Pattern lowering — downcast chains become one type-id load plus a jump table; when on enums lowers to brtable over the member slot.

The pipeline is honest by construction: there is no tier-2 to fall back on, so the emitted code must be right the first time. Every gate measures against the example programs and the benchmark corpus.

Async lowering

async fn compiles to a state machine: each await is a checkpoint state in the hidden frame, resume dispatch is the existing jump-table op, locals become frame fields, and suspension is a plain return. The op set grows zero rows for this — the driven half is an ordinary itable call through the future’s designated yield slot (the closed Future class’s engine ABI). The full protocol lives in Async and await and launched futures.

Determinism

Same source + same dependency versions + same compiler version ⇒ byte-identical output. Serialization is ordered and little-endian everywhere, and the graph compiles dependencies in a fixed post-order before flattening. This is what makes compile caches content-addressable, bundles diffable, and trace restoration by recompilation possible (Diagnostics, traces, and symbolication).

Typed bytecode

The compiler’s output — and the VM’s input — is LIR: a flat op stream per function over typed registers. Every register has a static type recorded in the function’s signature, and the load-time verifier re-checks all of it (Module binary and verification). The op definitions live in rut-core/src/ops.rs; the VM that executes them in VM core.

Registers and functions

Registers are u16 indices into a per-frame Vec<Slot>; a register file can never reach u16::MAX, which is reserved as the NOREG sentinel for optional single-register operands (a call destination, a native receiver). One function:

pub struct FuncCode {
    pub name: IdentId,
    pub params: Vec<TypeId>,   // methods: params[0] is the receiver
    pub ret: TypeId,
    pub is_method: bool,
    pub n_captures: u32,       // closure environment size
    pub regs: Vec<TypeId>,     // the register file's static types
    pub argv: Vec<Reg>,        // operand pool (below)
    pub labels: Vec<Label>,    // branch-table pool (below)
    pub code: Vec<Op>,         // the stream
    pub spans: Vec<(u32, u32)>,// pc -> source byte offset
    pub pos: Vec<(u32, u32)>,  // pc -> (line, col), parallel to spans
    pub host_id: Option<IdentId>, // Some = bodyless host fn (thunk)
}

host_id is the one name kind carried as an interner id: a host function is a bodyless FuncCode whose call dispatches to the embedder’s registered body instead of interpreting (Embedding).

Operand pools

No op owns a heap allocation. The variadic operand lists — call arguments, record/array/capture element registers, branch-table arms — live in per-function pools (FuncCode::argv for register lists, FuncCode::labels for branch targets); each op carries an (off, argc) span into its own function’s pool. Consequences:

  • Op is a fixed 24 bytes — pinned by a compile-time assert, with a never-constructed Op::Pad variant holding the reasoning. The natural 16-byte stride measured +13% on the interpreter gate (op-stream loads aliasing register-file stores at power-of-two strides); 24 measures clean and stays far narrower than the pointer-carrying layout it replaced.
  • Pools are append-only and deduplicated at emission — repeated argument shapes share one entry. The empty list is the span (0, 0) and is never stored. Optimizer rewrites re-intern on register remap; deleted ops orphan their entries, which is dead weight, not corruption.
  • argc is u16: a list can name at most as many registers as the register file holds. The emitter rejects literals beyond that bound.
  • Method calls fold the receiver into the pool as argv[0], so the span is the callee’s parameter list and one uniform copy loop transfers a frame — no special-cased slot zero.
  • The binary format serializes the pools ahead of the code; the verifier bounds-checks every span before execution.

Scalar ops are one opcode per operation — the kind (int vs float) is in the opcode and the width in a prim operand, resolved by the compiler. The VM never consults the type table for arithmetic and there is no runtime op selector.

The op families

Representative ops (exact Rust names; the table below is the whole machine):

familyopsnotes
movesMov, MovRefref move retains new, releases old
constantsConst (pool), ConstRaw (folded scalar bits)
int arithmeticAddI SubI MulI DivI ModI (+prim)+ - * / % trap on overflow / divide-by-zero
wrap arithmeticWAddI WSubI WMulI, WrapShlIthe wrapping_*/wrapping_shl builtin methods, lowered inline
float arithmeticAddF SubF MulF DivF ModF NegF
int bitwiseAndI OrI XorI ShlI ShrIshifts mask the count; overflow traps
comparesEqI…GeI (+prim), EqF…GeFbools and codepoints ride the int slots
equality on refsStrCmp (content), ArrayCmp (content), RefEq (cell identity)the == law’s three arms
controlJmp, Br, BrTableBrTable arms in the labels pool
callsCall, CallM, CallI, CallFn, CallNat, Retsee below
recordsNewCell, MakeRecord, GetF, SetFMakeRecord allocates + initializes every field in one op; field operands bake the field’s Repr
ownershipOwn (payload copy; bytes::clone()’s lowering)opcode 90 (OnDrop) is retired — cell-death code is the [disposal] marker, dispatched by the release path, not an op (the Rc heap)
nullablesMakeOptT -> ?T: box into a one-slot cell (shares, never copies)
weak refsWeakNew, WeakUpgradeWeak references
arraysArrNew (zeroed), ArrLit (fixed), ArrGet/ArrSet, ArrGetF/ArrSetF (fused field+index)bounds trap; element repr baked in
enumsEnumNewimmortal singleton cell per member
type machineTidOf, IsType, IsIface, Unbox, Boxthe two readbacks + their guards
closuresMakeClosure{ func, captures }, captures in the pool
panicsPanic, Assert
conversionConvi32(x) etc.; narrowing traps when the value does not fit
stringsStrCodeAtone codepoint read as u32, bounds trap
budgetsLoopHeadfuel-check back-edge marker at loop heads

Call ops:

opmeaning
Call { func, argv, dst }direct call — free functions, class construction, closure entries, and host thunks
CallM { func, argv, dst }direct method call; receiver is argv[0]
CallI { slot, argv, dst }interface itable call — the only path for interface-typed receivers: always dynamic, even when the receiver’s exact class is statically known
CallFn { fval, argv, dst }call through an fn-typed value (closures: two consecutive registers, { fn_ptr, env })
CallNat { nat, recv, argv, dst }internal native, recv == NOREG for free functions

Internal natives (CallNat)

Things rut spells with a name are natives, never ops. The fixed, compiled-in table:

nativespelling
Strper-type formatting — the f"..." desugaring
Concats.concat(parts...)
StrLen / ArrLens.len() (codepoints) / array and bytes length
StrJoinjoin an array of strings in one pass
StrSlice / ArrSliceslice(from, to) — O(1) views (String slicing and views)
BytesClonebytes::clone() — the one copy escape hatch
CaptureTrace, TraceLen/Name/Line/Col/Renderthe stack-trace surface (Diagnostics)
StrScan, StrStartsWithfused host-side scan/classify and prefix test
StrFromCodestr::from_code(n) — one codepoint to str

Everything else rut spells with a name is ordinary rut code (Vec’s methods) or a bodyless host function. There is no strcat op and no template op.

What is not an op

An op exists for exactly one of three reasons:

  1. Nothing static. What the type table answers is a constant, never an op: type_id<T>() folds at compile time; Array<T, N>.len() is the constant N (N is part of the type’s identity). Hence no typeid and no arrlen op.
  2. Nothing polymorphic, nothing named. An interface-typed receiver gets exactly one op (CallI) through its itable. Slice-view indexing and len are ordinary calls through the view’s builtin impl. The erasure primitive’s names lower to primitives — the type-call opaque(v) to the Box op, opaque::downcast<T>(o) to prelude code (below) — and both are ambient: no use gates them (opaque — erasure and downcast).
  3. Concrete memory + control + the type machine’s two readbacks. Ops touch memory only through compile-time-known layouts (inline blocks, cells with known headers), plus control flow and calls — and the two readbacks reification needs: TidOf (what is it?) and Unbox (the payload, guarded).

is and downcast lowering

  • x is T with concrete T: one TidOf + an integer compare. On an erasure box, is answers by the box — it misses for every payload type; downcast is the only see-through.
  • x is I with interface I: one IsIface descriptor scan — pure in (recv, want), so repeated probes CSE and invariant ones hoist.
  • opaque::downcast<T>(o) (yielding ?T): TidOf; branch on the compare against T’s id; Unbox on the hit arm, a nil box on the miss. The check is visible dataflow — the compiler CSEs repeated checks, hoists invariant ones, and folds a downcast chain over one cell into a single TidOf + BrTable. The compiler always guards Unbox with the branch; an unguarded one still verifies but traps on mismatch — the safety net, like a bounds check.

Statically-answered is expressions never emit an op — the checker folded them (The compiler pipeline).

Async lowering

async fn compiles to a state machine with zero extra opcodes:

  • Each await is a checkpoint state — one enum-member-style singleton per suspension point, stored in the hidden frame’s state field.
  • Resume dispatch is the existing BrTable over that state.
  • Locals live across suspension as cell-backed frame fields (GetF/SetF).
  • The driven half is an ordinary CallI through the Future<T> class’s designated yield slot (the engine ABI — the vtable row is keyed by the hidden frame type, never spelled in source); suspension is a plain Ret.

The async plan rides the version gate like every surface change (v20 carried the closed Future class) — bundles and binaries from different compiler versions are refused at the version byte. The driving loop that wakes these frames is VM core’s scheduler; the surface semantics are Async and await.

Budget hooks in the stream

The only budget artifacts in the op stream are LoopHead markers: loop back-edges are natural checkpoints where fuel is accounted (Resource limits and fuel). Everything else — fuel countdown, heap checks at allocation, interrupt slices — lives in the interpreter loop, not in the code.

Module binary and verification

The compiled module artifact — a .rutc file — is a versioned, deterministic, hash-stable serialization of a linked program. Encoder and decoder live in rut-core/src/binary.rs; this page is the layout, the verification contract, and the constant-pool rules. The loader that runs verification is Loading and the embed loop.

Program shape

Everything the VM runs is one Program:

pub struct Program {
    pub name: String,               // module / program name
    pub scope: ScopeId,             // stable module scope (0 if unset)
    pub interner: Interner,         // every IdentId in the program
    pub surface: Surface,           // exports, for using modules
    pub inst_types: Vec<InstTy>,    // the instantiation ledger
    pub inst_fns: Vec<InstFn>,      //   — link unifies rows by key
    pub types: TypeTable,           // type descriptors, dense ids
    pub ifaces: Vec<IfaceDesc>,     // interface tables
    pub iface_slots: Vec<(u32, u32)>,   // global interface-member slots
    pub vtables: Vec<Vec<Option<u32>>>, // per type: slot -> func id
    pub disposal_impls: Vec<Option<u32>>, // per type: dispose fn id
    pub consts: Vec<ConstVal>,      // the constant pool
    pub funcs: Vec<FuncCode>,       // the code ([Typed bytecode](typed-bytecode.md))
    pub exports: Vec<(IdentId, u32)>,   // host-callable names
    pub templates: Vec<TemplateRow>,    // instantiation-independent bodies
    pub template_stubs: Vec<TemplateStub>, // bound-member stubs of the window
    pub template_first_fid: u32,    // the window's first func
    pub template_end_fid: u32,      // one past its last
}

The Surface is the export record — functions, constants, types, interface declarations, inherent method surfaces, and the builtin names core publishes. It is how a using module binds a used module’s members at compile time, and it is part of the wire format too — the surface section rides after exports, and decode validates every row against the tables above it.

Wire layout

The format is little-endian, everywhere — encoded words, hash inputs, checksums. The first byte of a byte range is the least significant byte of word 0; this is a law pinned by unit tests, not an accident of the host.

offset  field
0       magic "RUTC"                      # 4 bytes
4       version: u32                      # VERSION = 22; refuses any other value
8       name: str
        name table: u32 count, then count × str
        types: u32 count, then per type { name: IdentId, kind }
        ifaces: u32 count, then per iface { name, methods[] }
        iface slots: u32 count, then (iface: u32, member: u32) pairs
        vtables: u32 entries, then per entry { ty, [(slot, func)] }  # sparse
        disposal rows: u32 entries, then (ty, func) pairs            # sparse
        consts: u32 count, then tag + payload (below)
        funcs: u32 count, then per func (below)
        exports: u32 count, then (name: IdentId, func: u32) pairs
        instantiation ledger: type rows, then fn identities   # below
        surface: namespace, funcs, consts, types + scope blocks + type
                 exports, interface decls, inherent method surfaces,
                 the native rows   # below
        templates: window first fid, window end (exclusive), then
                 u32 count, then per row (below)   # template bodies ride the binary
  • Templates (instantiation-independent bodies): after the surface, the wire carries the template window — template_first_fid and template_end_fid (every func in [first, end) is template-derived; the end is WIRE, not implicit, because a pack walk that materializes consumer-served instantiations into a decoded dep appends them AFTER the window — real ledger instantiations, not window entries), then one index row per exported generic decl: the kind tag (0 free / 1 method), the bound name(s), the #<param> placeholder rows in declaration order, the bound interface names, and the fid of the placeholder-compiled body (the body itself rides funcs). The window’s bound-member stubs ride beside the rows as (fid, param placeholder, member name) triples. Decode validates the window against the func table and every type id against the carried blocks; a consumer-spelled shape the pack-time ledger misses monomorphizes from these rows at link (see Bundles — instantiation independence).

  • Name table. Names are interner ids everywhere — type names, field names, enum members, interface/method names, function names, exports. The binary carries only the interner’s non-well-known tail; the fixed well-known prefix (self, nil, the builtin members, the primitives, …) is implied by the format. Decoding rebuilds the interner, so a decoded program is self-contained; at link, each module’s tail merges into the linked program’s table with the same rebase the type ids get.

  • Type kinds encode as a one-byte tag: nil, primitives, str, bytes, arrays, enums (member + value pairs), records (field table), interface objects, opaque, fn types, ?T, trace, Weak<T>.

  • Const tags: 0 i64, 1 f64, 2 bool, 4 str, 5 type id. Retired tags fail decode loudly rather than being reinterpreted.

  • Funcs serialize in full: name, param/ret types, is_method, capture count, the typed register table, both operand pools, the op stream, the span table, the parallel (line, col) position table, and the host-fn binding id when the function is a bodyless thunk.

  • Instantiation ledger: the owner-anchored identity of every instantiation the program compiled — type rows (owner, decl, arguments, type id) first, then fn identities (the kind, the substitution values, and the local fn id). Instantiation is owned by the declaring package, and link unifies rows sharing a key into ONE program-wide row; a consumer resolves its requests against a packaged binary’s ledger. Type exports carry their generic parameter lists beside this (see the surface below).

  • Surface: the exported surface rides after exports — the namespace head, funcs (with their async/host rows), consts, the carried type descriptors + scope blocks + type exports (generic exports carry their parameter names in order), interface declarations (SurfaceIface — every module publishes the interfaces it declares; a consumer links them into one merged table), the inherent method surfaces (the linkable-classes phase’s one row per class with methods), and the native rows with their ambient bits. There are no impl-registration rows on the wire — satisfaction is structural, so nothing registers. Names are ids into the name table above; decode rejects any id its tables cannot resolve.

  • Versioning policy: the version u32 must equal the toolchain’s exactly — there is no migration or best-effort decode. A byte that changes observable behavior bumps the version; artifacts from older compilers are refused with the standard version error.

Determinism

Same AST + same dependency versions + same compiler version ⇒ byte-identical bytes. Serialization order is fixed (mount order, manifest order, pool order), so binaries are cacheable by content hash, two builds diff to nothing, and a trace captured against one binary can be restored against a locally rebuilt one (Diagnostics, traces, and symbolication).

Strip levels

The symbolication data rides in every function: the spans table (pc → byte offset) and the parallel pos table (pc → line/col). A build that skips filling pos produces a binary whose traces still capture and render, degrading to pc-only text. Names ride the interner; dropping name strings is a publishing choice, and stripped traces restore through recompilation-by-determinism (see Diagnostics, traces, and symbolication).

Both strippable halves are format-legal encodings, not special cases: tail strings are opaque to the format (rewriting them to mangled %N names touches no id, opcode, or table), and 0/empty pos is the documented stripped encoding — a stripped binary decodes and verifies identically, no version bump required. The toolchain lane that produces and restores them — the mangle/keep-set law, the private .rutsym sidecar, and run --symbols — is Symbol stripping and .rutsym sidecars.

Type ids are program-global in a linked binary only because link already rebased them. At rest (per module, pre-link) ids are module-local; the boot table — the fixed primitive and builtin prefix — is shared by every module, and each module’s remaining types append after it. Every type id reachable from a type descriptor, interface signature, constant, function signature, or op operand is remapped at link, and type_id<T>() constants rebase with everything else.

type_id<T>() values are u32, comparable, and unique per instantiated type within a VM run: Vec<f32> ≠ Vec<f64>, [i32; 3] ≠ [i32; 4] (the constant length is part of the identity), and Point = Point across modules — identity is assigned at link (Reified types and layout).

Interface and vtable tables

  • Interfaces serialize with their member signatures; interface ids merge by name at link — an interface imported in one module and declared in another is one interface, and every capability probe and itable slot lands on the same global table.
  • Interface-member slots are a global table of (iface, member) pairs; vtables are per-type sparse maps slot → function id, merged at link. The slots a type fills are decided at its boxing sites — the boundaries where satisfaction was proved — and reach every call site from there. Nothing registers: a type that never crosses an interface-typed boundary fills nothing.

Verification (load time)

Before any code executes, the verifier re-checks every function in the binary:

checkrule
register rangeevery register operand < the function’s register-file size; NOREG legal only where an optional operand is defined
pool spansevery (off, argc) span lands inside its function’s argv / labels pool
type operandsevery type id names a row of the type table
jump targetsevery jmp/br/brtable target is in range
call aritycall argument counts match the callee’s declared signature
enum membersEnumNew member indices in range, target actually an enum
interface slotsCallI slot ids name a row of the global iface-slot table
host thunksbodyless functions are skipped (nothing to verify)

A failed verification is a load error naming the module and function — function name (#i): op @pc: message. Corrupted binaries never execute. Verification is structural: it re-establishes what the compiler enforced at emit time, so a hand-corrupted or stale artifact fails here instead of misbehaving at runtime.

The constant pool and load-time expressions

Module-level let and static initializers are folded at compile time. The surviving forms are: literals, enum members, operators over constants, record literals (immortal constant-pool cells), fixed-array literals, Vec<T>(n) / Vec::from([...]) blobs, the layout builtins, and Array<T, N>.len() with const-index bounds checks. A call to a user function in an initializer is a compile error — there is no deferred evaluation.

type_id<T>() never executes: it folds to a constant from the type table. debug position folding and trace symbolication are covered in Diagnostics, traces, and symbolication.

What is not here

A .d.rut declaration surface does not produce a binary — it has no bodies, so it compiles to a signature surface only (Host fns and declaration files). And a .rutbundle is binaries plus their container: the compiled packages ride as .rutc binaries (this format), splice-needed packages and host pkgs as source groups (Module bundles).

Symbol stripping and .rutsym sidecars

A publisher can ship a compiled artifact whose function, type, field, interface, and method names — and source positions — are unreadable, while keeping a private symbol table that, when supplied at load time, restores the real names and line/col for stack-trace symbolication. Users holding only the binary see mangled names and pc-only traces; users holding the sidecar see the real thing.

The VM changes nothing: symbolication is lazy, per-index, against the loaded program’s interner and position tables — restoring is a matter of what the loaded program carries (Diagnostics, traces, and symbolication).

The model

rut pack plugins/server --strip -o server.rutbundle
# packed plugins/server -> server.rutbundle (...) + symbol table
# server.rutsym (... bytes, keep PRIVATE)

Two files leave the build:

filerole
server.rutbundlethe public artifact — every renameable name mangled, every function’s symbolication tables gone
server.rutsymthe private half — mangled → original name rows, and the span/position tables per module

The sidecar is never an entry inside the bundle. It rides beside it, and whoever holds it may restore; whoever holds only the bundle cannot. It is also not encrypted or obfuscated — see the limitations below.

What is renamed

Everything name-shaped a binary carries: function names, type names, field names, interface and method names, enum members, and the exported surface rows. Renaming is purely a tail rewrite: every name in a .rutc is an interned-id index, and the binary serializes only the name table’s instance-local tail (Module binary and verification) — rewriting those tail strings touches nothing else. Ids, opcodes, vtables, fn tables, and type layouts are untouched, so no format-version bump rides this: a stripped binary decodes and verifies identically, and 0/empty position tables are the documented stripped encoding.

Mangled names are %0, %1, … — sequential over the sorted union of renameable names across the whole packed closure (deterministic and collision-free). % can never appear in an identifier or a package name, so a mangled string cannot collide with any source-derived name by construction.

Mangling is one closure-wide string→string map applied to every compiled group in the bundle — never per-group random names. Bundles link across .rutc groups by name text at load (interface merge-by-name, the instantiation-ledger keys), and a consistent map preserves all cross-group identity for free.

The keep-set

Some names are load-bearing and never rename:

keptwhy
well-known names (main, the builtin members, the primitives)never in the serialized tail
host-fn registration names (FuncCode::host_id, SurfaceFn.host, host thunks)the embedder’s registry keys — ink_host::log, rt:log, …
export nameshosts call by string (vm.call("main", …))
package specs in instantiation rowsload-time unification keys

Program::name (the module’s display name in traces) is a plain string field, not an interned name — it stays as-is. Local variable names never exist at runtime (registers only), so there is nothing to strip there.

Positions

The pc → byte-offset span table and the parallel pc → (line, col) position table leave together, per function, and restore together. Without them, StackTrace.line(i)/col(i) read 0 and render() degrades to the pc-only form — the behavior is unchanged, only the diagnostics lose fidelity (Diagnostics).

The mixed-closure refusal

--strip needs a fully-compiled closure. A package riding as a declaration file set (a host pkg, or a source dep whose unit did not link) would bind its compiled dependencies’ surfaces at load — and those names are mangled. The packer refuses rather than guesses:

pack: --strip needs a fully-compiled closure: the source group `boxy`
binds compiled `util`'s surface at load, whose names would be mangled —
restructure the closure, or pack without `--strip`

Host and declaration leaf groups have no compiled dependencies and pass trivially. A refused world packs fine without --strip.

CLI

rut pack <dir> [--strip] [-o out.rutbundle]   # + out.rutsym beside it
rut run <mod.rutbundle> [--symbols <file.rutsym>]
  • --strip writes the bundle as today plus the sibling sidecar (mod.rutbundle → mod.rutsym) and prints both paths.
  • --symbols is legal only against a compiled .rutbundle — the source and directory lanes compile fresh and need no map (a mismatched input is a usage error). The table restores before the graph compiles, so linking and every trace see real names. A section naming a module the bundle does not carry draws a warning; a table from a different build simply matches nothing and errors nothing.

Embedders get the same lane as library calls: the packer’s pack_dir_opts returns the sidecar bytes beside the bundle, and bundle.restore_symbols(&map) on the decoded archive handle restores into pkgs.

Determinism and limitations

Same input directory ⇒ byte-identical bundle ⇒ byte-identical sidecar (the mangled numbering is sorted-union based, like everything else in the pack). That determinism is also the honest limitation:

  • String values are data, not names — string constants in the binary stay exactly as the source wrote them. Stripping hides identifiers; it does not scrub string literals.
  • The sidecar is the private half, not a secret. Anyone holding the original source can rebuild the same closure deterministically and regenerate an identical map. Treat .rutsym like a .pdb: distribute it only to parties who may see names and positions.
  • Stripping and generics compose. A successful pack’s templates cover its generic surface by construction, so --strip on a generic-owning closure is legal unconditionally: the consumer-spelled shapes monomorphize from the in-binary templates at link, never from source. The keep-set therefore preserves every name instantiation independence (the separate-compilation contract) consults — the exported surface’s names (funcs, types, consts, interface and inherent methods), the generic parameter names (the consumer’s substitution env spells #{param} against them), the template rows’ bound names and bounds, the bound-member stubs’ member texts, the instantiation ledger’s owner specs, and the carried type block’s row names (a mirror construction reads the target row’s spelling). The mangle stays real where nothing consults: internal helpers, lambdas, and pre-surface temporaries rename to %N beside the sidecar. A consumer binding a stripped compiled group’s surface later is still a loud unification miss, never a mislink.

What is not here

rut dump on a .rutc with --symbols, and auto-keeping the shared surfaces of a mixed closure (so it could strip anyway), are natural follow-ups; neither ships today.

VM core

One struct, one thread, one heap. The VM (rut-vm) interprets typed bytecode over an RC heap with inline destruction — no JIT, no garbage-collection pass, no background threads.

The machine

pub struct Vm {
    pub prog: Rc<Program>,        // the linked program
    heap: Heap,                   // the RC heap — [The VM heap](vm-heap.md)
    frames: Vec<SavedFrame>,      // saved frames (the call stack)
    cur_func: u32, cur_pc: u32,   // the ACTIVE frame
    cur_regs: Vec<Slot>, cur_ret_dst: Option<Reg>,
    fuel: Option<u64>,            // per-op budget
    interrupt_every: u32,         // budget check cadence (default 1024)
    hooks: HostHooks,             // embedder surface
    ready: VecDeque<Slot>,        // launched/parked frames to (re)drive
    timers: BTreeMap<u64, Vec<Slot>>,  // sleep deadlines -> wake lists
    now_ms: u64,                  // the VM's virtual clock
    ...
}

A Vm is single-threaded by construction. Saved frames are plain records { func, pc, regs, ret_dst }; calls push, returns pop. Register files are recycled through a pool, and per-function side tables (reference-typed register indices, per-type field layouts, baked type representations) keep the hot loop free of type-table lookups.

The interpreter loop

The loop is a match over decoded ops — decode is a table index, not a byte scan. On native targets the default engine is a threaded dispatcher (rut-vm-threaded): every op ends by tail-calling the next op’s handler, so dispatch is a jump and hot state stays in registers. A portable loop over the same handler methods backs wasm and other targets; behavior is identical, only the dispatch shape differs. Ops the threaded engine does not absorb bail to the match interpreter with the pc pinned at the op.

  • Direct calls are an index + jump; interface (itable) calls are two loads (itable row) + an indirect jump.
  • Refcount retain/release are inline in the loop; a release to zero nulls the weak list, queues the type’s dispose body (the [disposal] contract), and frees (The Rc heap and destructors).
  • Fuel is accounted per op, with the fuller budget check amortized every interrupt_every ops.

The host boundary

The embedder’s host-fn binding table (HostRegistry) is built before the Vm exists and is consumed at construction: every host thunk the program declares is resolved against the registry immediately, so a declared-but-unbound host fn is a construction error, never a mid-run trap. The join produces one dense dispatch row per function — an adapter code pointer, the body’s state word, the declared return type, and its is-reference verdict — so calling a host fn costs one table copy, no name work, no allocation.

  • Host bodies are plain Rust functions over &mut Vm and slots; arity is capped at 8 (the boundary’s tuple law), and signatures are derived from the body’s Rust shape, not written by hand.
  • A host body records a trap in a VM-side channel rather than returning Result; the trap fires before any destination register is written.
  • Re-entrant calls (a host fn calling back into rut) run the callee on a fresh frame stack under the same budget. The outer cursor is stash/restore: on return or trap the outer frame is exactly as it was, so a propagated nested trap parks the outer frame at the host op and resume() re-runs the host fn. A host fn that prefers to handle the situation itself can catch the trap, add fuel, and retry its nested call.
  • The async host-fn lane (register_async!) binds a Rust async body to the minted {scope}::{name}__start/__yield/__take/__cancel rows the compiler weaves for host async fn declarations (The host futures bridge).

Traps

Bugs are traps, errors are values. Arithmetic overflow, division by zero, indexing out of bounds, nil dereference, panic(...), a failed downcast guard, and budget exhaustion all unwind as Err(Trap) — never a Rust panic:

pub struct Trap { pub kind: TrapKind, pub msg: String }

pub enum TrapKind {
    OutOfFuel, OutOfMemory, Interrupted,
    Overflow, DivByZero, IndexOutOfBounds,
    Panic, BadUnbox, Invalid, NilDeref,
}

Traps are catchable only at the host boundary. vm.call(...) returns Result; rut code never catches one — errors in rut are (T, err) tuples (Errors and optionality). On the way out, frames are dropped and destructors run: dispose bodies fire, borrow guards release. The Vm itself survives a trap — the next call starts clean.

Budgets and interrupts

pub struct Limits {
    pub fuel: Option<u64>,          // per-op countdown
    pub heap_limit_bytes: Option<u64>,
    pub interrupt_every: u32,       // default 1024
}
  • Fuel counts ops down. Exhaustion parks the frame at its pc — the loop state is the frame — so add_fuel(n) + resume() continues it; nothing is lost or restarted. Loop back-edges carry LoopHead markers so tight loops still park.
  • Heap budget is checked at every allocation; over-limit allocation traps OutOfMemory the same parkable way.
  • Heap accounting is live: heap_usage() reports current bytes, fuel_used accumulates across resumes.
  • Interrupts are cooperative: the budget check cadence bounds how long any host-requested stop can take. Native (host) bodies run outside the fuel budget and are expected to be fast.
  • Vm::builder().compiled(c).limits(l).build() takes the limits (.limits(..) on the builder, or the parts a Compiled hands over); unset limits mean unbounded fuel and heap — embedders that need budgets pass them explicitly (Resource limits and fuel).

Coroutines and the driving loop

Every async entry runs as a root frame, parked when await returns pending. There is no microtask queue and no job executor — two queues and a virtual clock:

  • ready: VecDeque<Slot> — launched or woken frames; each entry owns one reference (retained on enqueue, released on pop).
  • timers: BTreeMap<u64, Vec<Slot>> — sleep deadlines against the VM’s virtual clock (now_ms / set_now — deterministic; the host advances it explicitly, or maps it to wall time).
  • drive(fut) — one drive step through the future’s designated yield slot (the Future<T> class’s engine ABI): a fresh engine context over the frame edge, answering Done or Parked off the frame’s state field. Fuel accounting rides the per-op budget unchanged: an exhausted drive parks the frame at its pc, and a re-drive re-enters at the checkpoint state.
  • run_ready() drains the ready queue one drive per entry; next_deadline() expires due timers into ready and answers the earliest remaining deadline; pending_tasks() is the idle test.
  • The wake pair (awaiter edge on the awaited frame, pending edge on the awaiter) is one-directional and cleared on resume — no cycle forms.
  • A completed drive re-enqueues the frame’s awaiter edge. A parked async frame is simply not in ready until its wake edge or timer fires.

The engine never owns a wall clock: sleeps are virtual-clock deadlines, and tests virtualize time by advancing the clock — full determinism (Async and await, Launched futures).

Heap integration

Allocation, retain, and release are inline loop work. There is no collection pass at all: destruction happens at release-to-zero, so nothing ever interrupts a frame. Strong reference cycles leak by design; the weak-reference machinery and the shutdown leak report are the diagnostic surface (Weak references and the cycle collector, The Rc heap and destructors). Heap layout, cell formats, and the bump allocator are The VM heap.

Loading and the embed loop

Loading verifies, links, and mounts a program — it executes nothing. The host owns time, I/O, and lifetime: the VM never reads the filesystem or a clock on its own, and the host decides when (and whether) any rut code runs.

From path to machine

rut run app/            # a directory with rut.jsonc
rut run plugin/plugin.rutbundle

Turning a path into a booted Vm is the walk (rut-native) feeding the run chain (rut-driver) feeding the builder door (rut-vm) — five steps:

stepwhat happens
1. the walkA directory is one module: its rut.jsonc names the package (name) and its surface (entry.type — optional on a host pkg, where mod.d.rut beside the manifest is the default root and a spelled entry wins), its body is the mod.rut module tree, and its deps/dev-deps ride the manifest (Project structure and rut.jsonc). A type = "host" package has no body: its .d.rut surface is itself a module tree — mod NAME; edges mount NAME/mod.d.rut children beside the declaring file (or the single-file NAME.rut), recursively — and each row registers path-qualified (myhost::net::connect; a flat pkg’s rows keep today’s bare shape). rut_native::load_dir walks deps recursively — cycle guard, first-mount-wins, name-mismatch is an error — gates every url dep against the root’s rut.lock (an unpinned url refuses, naming rut install) and verifies the fetched bytes against the lock’s pin at the mount door, then runs the root-only [dev-deps] pass (Dependency kinds). A .rutbundle loads closed from the zip — groups mounting under their content identities (Module bundles). The yield is rut_driver::Walk { pkgs, root }.
2. the offerpkg(..) — the ONE offering verb — offers every walked pkg (first-pkg-wins; fold the walk into the chain) and Offer::Host hands over the host bodies. core auto-rides unless a pkg named core was offered; the closure check refuses a use name nothing offered resolves — and a head that IS mounted but undeclared by its consumer (nameability is declaration-scoped: deps ∪ root dev-deps ∪ core; Dependency kinds).
3. compile the graph.compile() mounts the offers into the run’s internal table, then compiles each module (sources, in dependency post-order) — every module links; there is no splice lane and nothing appends after the walk. Every use path resolves through the run’s one resolver door, so a mounted-but-undeclared head is the dedicated D5 diagnostic naming the mount edge and the fix; host packages synthesize bodyless thunks from their declared surfaces; a bundle’s compiled packages push their decoded binaries at fresh, rebased scopes (The compiler pipeline).
4. link + flattenModule-local type/function/const ids rebase into the global tables; the shared boot prefix passes through; name tables merge; interface declarations merge by name and duplicate module names are link errors. Cyclic use is a compile-graph error, never a runtime event.
5. verify + bootThe load verifier re-checks every function (Module binary and verification); Vm::builder().compiled(compiled).build() joins the program’s host thunks against the Compiled’s HostRegistry — a declared-but-unbound host fn is a boot error.

Loading a .rutc binary (vm.load_binary-style paths, and the wasm runner) skips steps 2–3 and lands directly in verify + boot.

What the host can call

Callable names are exactly the program’s entry fns. Their signatures were checked against the host-crossing rule at compile time — primitives, str, bytes, opaque, ?T over a crossing type, and crossing tuples — so a bad surface can never surprise the embedder at call time. An entry fn -> (?T, err) decodes positionally at vm.call as a (value, err) pair (below).

Use paths never execute anything: importing a package mounts its surface; only the host’s calls run code.

The embedder surface

Everything the host needs is the chain plus a handful of Vm methods (the registries build before the Vm boots):

callpurpose
rut_native::load_dir(dir) / load_dir_with(dir, &remote)the walk: a directory’s whole closure as rut_driver::Walk
rut_native::load_bundle_session(path) / Bundle::parse(&bytes)load a packed .rutbundle from a file / decode its bytes into a reusable handle
rut_native::dir_pkgs(dir) / tree_pkg(name)the offer lanes: a dep-style directory walk / one toolchain-tree package
HostRegistry::register(name, f)bind a host-fn body on the raw lane; signatures derived from the Rust shape
pkg_fn! / pkg_async_fn!the HostPkg builder’s sugar — one spelling → one row / the five-row async family (embedding and native modules)
RutRun::new().pkg(..).entrypoint(..).compile()the run chain: offers (Offer::Lib(&bundle) / Offer::Host(hp)), the root — one terminal step compiles (Result<Compiled, RunError>)
bundle.restore_symbols(&map)restore a stripped artifact’s private symbol table on the decoded archive handle — once, before any offer
Vm::builder().compiled(c).limits(l).hooks(h).build()boot; joins every declared host fn to its binding (a declared-but-unbound fn is a construction error)
vm.call(export, args) -> Result<Value, Trap>sync entry — typed arg/ret adapters over the boundary
vm.resume()continue a parked frame after add_fuel
vm.run_ready(), vm.next_deadline(), vm.pending_tasks(), vm.drive(fut)the async driving verbs
vm.set_now(ms), vm.arm_timer(deadline, fut)the virtual clock
vm.add_fuel(n), vm.fuel_used, vm.heap_usage()budgets and telemetry (Resource limits and fuel)
vm.call_host_row(row, args)invoke a registered host row directly (tests, tooling)

Errors are values (Result), bugs are traps, and the host is always in charge of time, I/O, and lifetime.

The frame loop

An embedder that owns an event loop (a GUI, a game frame, a web page) runs one engine frame per tick:

fn on_vsync(&mut self) {
    self.process_host_events();                 // input, network, ...
    self.rut.run_ready()?;                      // drive ready frames to completion
    if let Some(d) = self.rut.next_deadline() { // earliest armed sleep
        self.schedule_wake(d);                  // host parks until then,
    }                                           // then advances the clock
    self.render_frame();
}

pending_tasks() is the idle test — zero means the program has nothing runnable. There is no job executor inside the VM: parking, waking, and timing are these three verbs plus set_now (Async and await). A program whose world offers no async packages simply has no launcher; await stays cold-poll inline (The async model).

The soft-fail law (the err channel)

An entry fn -> (?T, err) never produces Err. The pair decodes at vm.call as Ok — with data in the pair: a non-empty err string means the turn failed softly; an empty err means success (nil value = “not found”). Err remains exclusively the trapped turn: a bug, wiring drift, exhausted fuel — the loud channel.

The law for host event loops (the pump pattern): per queued event, call the turn entry, then —

  • Ok: decode the pair. A non-empty err is reported (surfaced to the user/log, retained) and the loop keeps draining: the container survives, the queue proceeds, the page stays alive. A returned err must never poison the container or kill the drain — it is data the host acts on.
  • Err: the pump aborts loud — a trapped turn is a bug, not data. The Vm itself survives for the next good turn.

On a raw JSON boundary (the wasm host), the envelope carries "err" beside "trap": a soft-fail run reads {"trap": null, "err": "…"}, a success reads "err": null, and a panic sets trap with "err": null. trap never fills err. Fuel and heap reporting are unchanged by this.

Parse-time robustness

The same embeddability pillar holds at the other end of the pipeline: the frontend is stack-bounded with explicit nesting budgets — malformed or hostile module source yields diagnostics, never a host stack overflow, and a module with diagnostics never reaches the VM.

Diagnostics, traces, and symbolication

Errors are values and bugs are traps — either way, the first question is where. The story has two halves: compile-time diagnostics (one model from the first illegal byte to the last type error) and runtime traces (raw captures, lazy symbolication).

Compile-time diagnostics

One model serves every frontend and checking stage (The frontend):

struct Diag { span: Span, msg: String, file: Option<String>,
              labels: Vec<(Span, String)>, notes: Vec<String> }

Byte-offset spans; file is the module the span indexes, as the producer’s module name — a pkg spec (hello), a mounted child under it (hello/layout), or a formatter’s real path — never a filesystem path, since loaded pkgs deliberately carry none. None means there is no position to show (a graph-level structural refusal) or the producer did not label.

One renderer (render_diags) produces the caret form: a primary error: line, the --> arrow with the file and the 1-based line and char column, the offending source line with carets under the span, secondary labels, notes. With a file and its source text:

error: expected an expression, found `@`
  --> hello:2:13
   2 |     let x = @@;
     |             ^

The fallbacks degrade honestly: a diag with no file spells the position alone (--> line L, column C), a file whose text is not loaded renders the bare arrow (--> hello), and a diag with neither is just the error: line. rut run renders the whole graph grouped by file — diags sort by (file, span start), the root labeled with its spec, each child with spec/path, each dep with its own spec — so output is stable across files and phases. The parser recovers at statement boundaries and keeps going, so a file yields many diagnostics, not one. Compilation stops before IR if any diagnostic exists; there is no warnings-only lane.

A compile trap worth knowing: name-level misses are not all one shape. A name nothing offers is the bare unresolved name; a head that IS mounted but undeclared by its consumer gets the dedicated diagnostic naming the mount edge and the fix (Dependency kinds).

Runtime traces

Capture — raw pcs, nothing else

capture_stacktrace() -> StackTrace (a builtin: the engine itself implements it, compiler-lowered) walks the frame stack and stores raw frames:

  • the active frame innermost, then every saved frame outward, as (func, call-site pc) pairs — about 8 bytes per frame;
  • no name lookup, no source access, no symbolication at capture — capture is cheap enough for any error path;
  • saved-frame pcs are resume points, so symbolication backs one op to the call site;
  • target-independent by construction — the same walk runs on wasm.

The result lives in a dedicated immutable trace cell: a snapshot, shared by handle, safe to store in error tuples. It takes no user impls and never crosses the host boundary — a trace is a rut-side diagnostic object (The host boundary).

builtin class StackTrace {
    fn len(self) -> i32;          // frame count (innermost first)
    fn name(self, i: i32) -> str; // frame i's function name
    fn line(self, i: i32) -> i32; // call-site line (0 when stripped)
    fn col(self, i: i32) -> i32;  // call-site column (0 when stripped)
    fn render(self) -> str;       // the symbolication string
}

Out-of-range i traps IndexOutOfBounds — the index is a bug, not data.

The tiers

tiercostwhen it exists
StackTrace captureexplicit; a depth-proportional frame walk (~30 ns base + ~0.2 ns/frame)opt-in at raise sites — a rich err carries trace: ?StackTrace only where the producer decides the cost is worth it
Trapautomatic at trap unwindbugs, overflow, panic — the loud channel carries kind + message
? / err propagationzero cost — no auto-capture on propagationalways

Opt-in is the design: the cheap error path stays cheap, and capture is pay-per-capture.

Symbolication — lazy, per index

Members symbolicate on access, against the loaded program:

  • name(i) — one interner lookup for frame i’s function name.
  • line(i) / col(i) — one direct read of the function’s position table (pc → (line, col), parallel to the pc → byte-offset span table; Module binary and verification).
  • render() — the only whole-trace pass, innermost first:
at c_big (core:27:13)          # names + positions available
at c_big (core #3 @ pc 25)     # stripped: pc-only degradation

There is no eager symbolication and no frames array — a frame array would mint rut-side data per access and fix the representation into the surface.

Restoration paths

A trace is captured against whatever is loaded — possibly a stripped, published artifact. Four ways back to names:

  1. In-VM (the default). The loaded program carries its interner and position tables; every member call symbolicates from them.
  2. Recompile by determinism. Serialization is deterministic — same source + same compiler version ⇒ byte-identical binary ⇒ identical pcs — so tooling can symbolicate a captured trace against a locally rebuilt binary (The compiler pipeline).
  3. Stripped, no artifact. Traces still work: they degrade to the pc-only render form above, and stay restorable via path 2 later.
  4. The stripped artifact’s private symbol table. Name resolution and position lookup follow the loaded program — so supplying a .rutsym sidecar at load time (run --symbols, or bundle.restore_symbols(&map) on the decoded archive handle) restores real names and line/col before any trace is taken. The sidecar’s law — what mangles, what stays, the mixed-closure refusal — is Symbol stripping and .rutsym sidecars.

Trap messages

A trap renders as its kind plus message, e.g. IndexOutOfBounds: index 9, len 3, OutOfFuel: fuel exhausted — the frame is parked; add fuel and resume(). Traps do not carry captures — the trace surface is the opt-in rut-side snapshot — but the host that receives Err(Trap) gets the kind, the message, and (via vm.fuel_used, heap_usage()) the budget context (VM core).

Where the surfaces live

Module bundles

rut pack mod/ reads a module directory and emits one file — mod.rutbundle — a zip archive carrying the module in one of two root kinds, routed by the manifest’s type key: a lib pkg packs compiled (the root’s mod.rutc binary, its scope ledger, and each dependency as a group under deps/<name>@<fp16>/), and a type = "host" pkg packs as a decl root (its .d.rut surface rides as source; single-package). A bundle is the same contract as the directory it was packed from, in one file: the loader mounts it exactly like the directory, and the two compile to identical programs.

Layout rules

  • The archive root carries only the root’s own files — rut.jsonc, rut.scopes, mod.rutc, the root’s declaration entry (and its rows when the pkg has mod children). Every dep group rides one level down, at deps/<name>@<fp16>/… keyed by the group’s content identity. No metadata entries; nothing else at the root. Unknown extra entries are ignored by loaders (forward compatibility) — except in a decl bundle, where a group entry, a root .rutc, or a ledger is a contradiction and refuses (see the decl root).
  • Entry names are canonical — mod.rutc, mod.d.rut, mod.rut, rut.mods at both levels. The archive is name-free: whatever a directory grammar spelled (<pkg>.rutc, a custom entry.type surface), the wire spelling is the canonical one.
  • The manifest’s name is the package name the bundle answers to — a bare [a-zA-Z0-9_]+ name, the same law as directory manifests. A group’s manifest name must equal its dirname’s name half (the identity’s name@).
  • No entry reaches outside the archive: there is no outside — a bundle’s sources compile from the archive’s own bytes alone.

The compiled root (lib)

rut.jsonc                byte-for-byte; "format": "rutbundle", "format_version": 12
rut.scopes               the pack-time scope ledger — one `<scope> = "<identity>"`
                           row per linked module, ascending by scope; every row
                           spells name@<16 hex> (the group identities; the loader
                           maps the self-row and engine rows to their bare mounts)
mod.rutc                 the root's compiled binary — bodies + surface
mod.d.rut                the root's DECLARATION ENTRY — GENERATED from the
                           validated surface at pack (the .d.ts pattern);
                           omitted under --strip
rut.mods                 the root's module rows, when it has mod children
deps/<name>@<fp16>/      one directory per dep group, keyed by the group's
                           CONTENT IDENTITY — fp16 is the first 16 hex chars of
                           the sha256 over the group's own rode source set
                           (rut.jsonc + mod.rut + mod.d.rut + rut.mods, fixed
                           order, absent files skipped); same source ⇒ same
                           dirname, two identities of one name coexist side by
                           side
deps/<name>@<fp16>/rut.jsonc   the group's manifest, byte-for-byte
deps/<name>@<fp16>/mod.rutc    a compiled group (the ordinary case: a source
                           body the graph linked) — bodies + surface, the
                           linking truth; the binary carries the closure's
                           instantiations in its ledger AND its generic
                           bodies as templates (instantiation-independent
                           bodies)
deps/<name>@<fp16>/mod.d.rut   the group's ONE declaration entry — GENERATED
                           for a compiled group (rendered from the validated
                           surface); a v11 archive group copies whatever its
                           own archive carried
deps/<name>@<fp16>/rut.mods    its module rows, when it has mod children
deps/<name>@<fp16>/…           a host pkg (or a declared dep whose unit did
                           not link) → its ONE consolidated declaration
                           entry: no binary, the source is the interface
  • The declaration entry is universal (wire 12): every published group carries exactly ONE mod.d.rut. For a compiled group it is GENERATED — rendered from the validated surface, canonically ordered, and round-trip gated at pack (the emitted text must parse back clean and re-state the same surface — the generation invariant). Never hand-maintained, so it cannot drift from what links. This is the TypeScript .d.ts pattern: ship the declaration beside the compiled code, generate it from the thing that links, and let the runtime ignore it — the loader never reads a compiled group’s entry. --strip OMITS the entry: its plaintext would leak the very names the binary mangles (the sidecar restores them privately).
  • The .rutc binaries are the linking truth: bodies plus the surface on the wire (module binary and verification). A consumer binds a compiled group’s exports from the binary alone — nothing is rebuilt from .d.rut text. The .d.rut files ride for humans and tooling.
  • The scope ledger names the pack-time scope of every linked module in the closure (engine mounts included), and every row spells the owner’s content identity. A decoded program’s ids spell its pack-time scopes; the loader resolves each through the ledger to the module to ensure and rebases the ids onto its own numbering — pack-time and load-time numbering never have to agree. A reference with no ledger row is refused.
  • The module rows are a lib body tree’s wire form (rut.mods — deps/<ident>/rut.mods for a group): one JSON object, mod path → source text, "" = the root module, one row per mounted child. A package with no mod children writes no rows entry. (A HOST pkg’s tree no longer rides the rows envelope — wire 12 consolidates it into the inline form inside the group’s declaration entry; the rows lane remains the READER’s law for v11 bundles.) The section is additive: the reader accepts both envelopes, so a bundle packed before file modules keeps loading — that is a loading law, not a transition; a NEW directory whose manifest spells the repealed entry.lib/entry.libs keys refuses loudly at the manifest walk.
  • Group kinds are the packer’s one decision: a source body rides compiled iff the graph linked it; a host body (or a declared dep whose unit did not link) rides its ONE consolidated declaration entry. Refuse, never guess: the packer calls the graph’s own classifier, there is no second implementation.
  • Generics ride compiled — instantiation independence (the separate-compilation contract): instantiation is owned by the declaring package, and the pack walk seeds each generic dep with the instantiations its consumers spell — the binary’s instantiation ledger names every (owner, decl, arguments) row the closure compiled. A compiled pkg whose surface exports an OPEN generic surface (generic fns, generic type exports, generic methods) ALSO carries the generic BODIES as templates inside the binary (the wire’s templates section): every exported generic decl compiles once against #<param> placeholder rows at pack time, and a consumer-spelled shape the ledger misses monomorphizes from the template at link — one row program-wide, owner-anchored, indistinguishable from a pack-time one, nothing persisted. A published bundle never carries source: the ledger is the fast path, the templates the only other lane, and a request missing both is a torn or doctored bundle — the mount refuses loudly (pouch owns an open generic surface but its binary carries no template bodies — corrupt or doctored, re-pack the directory), never mislinks. --strip is legal with a generic surface unconditionally: a successful pack’s templates cover by construction.
  • The root must compile — a root that produces no compiled program is refused: pack: <pkg> produced no compiled program — a host pkg (a .d.rut surface with no body) cannot be a bundle root; pack a source pkg instead.

The decl root (host)

A type = "host" pkg’s root IS its declaration surface, so a host bundle is the manifest plus that ONE entry — single-package, no ledger, no groups, nothing to decode:

rut.jsonc                byte-for-byte; "format": "rutbundle", "format_version": 12
mod.d.rut                the ONE consolidated declaration entry — the tree
                           normalized into the inline form, whatever the
                           directory grammar spelled

The entry rides at the canonical mod.d.rut name. The mod tree lives IN THE GRAMMAR now (wire 12): a pub mod net; edge in the root surface rides as pub mod net { .. } — the child’s own text spliced inline at its declaration edge, recursively, verbatim (comments and authored signatures survive byte-for-byte). Structure lives in the grammar, never in paths. The generation invariant gates the pack: the consolidated entry must lower to the same path-qualified rows the file-tree form did. (The v11 shape — the tree as a rut.mods rows envelope — still READS forever; it just is not written anymore.)

rut pack <host-dir> works (the surface verifies by parsing and lowering once — the exact lane a mount runs — then consolidates), --strip refuses on a host root (no symbols to strip — no programs, no sidecar), and rut run <host.rutbundle> refuses with intent: a host bundle carries a declaration surface — nothing to run; bind its rows from the embedder (host fns). The mount is the same lane a host group rides inside a compiled bundle: the entry lowers into the pkg’s host rows.

The manifest — rut.jsonc

First entry in the zip; JSONC (the directory grammar: // and /* */ comments and trailing commas are legal); the same manifest grammar the directory form uses, byte-for-byte the directory’s manifest — which is what makes a bundle-shaped directory pack unchanged:

{
  // the bundle wire — 12, always; the manifest's `type` routes the
  // root kind (the module-binary version is a different constant)
  "format": "rutbundle",
  "format_version": 12,
  // the package this bundle answers to
  "name": "plugin",

  // the whole dep closure rides the archive, as groups under
  // deps/<name>@<fp16>/ — this manifest is the closure's map
  "deps": {
    "server": { "path": "../server" }
  }
}

Directory loading ignores format/format_version — a directory is not a bundle — which is why the keys are safe to write into every module manifest today: examples/03-plugin/plugin is a working directory that also packs unchanged.

The rest of the manifest grammar — the dep tables, dev-deps, style, and the strict-keys law — is defined in Project structure and rut.jsonc; the dependency semantics are Dependency kinds.

Url deps — bundles by reference

A consumer may mount a bundle by url instead of vendoring it:

{
  "deps": {
    "server": { "url": "https://example.com/server.rutbundle" }
  }
}

The pin lives beside the manifest, in the walk root’s rut.lock (rut install writes it — the rut CLI): the manifest row names the url, the lock pins its bytes.

The mount is the bundle mount, one gate earlier: the embedder’s remote produces the bytes (DepRemote — the standard rut_native::HttpRemote is cache-first), then the loader runs the same container/layout/name checks and — before all of them — the pin law: the url must have a lock row (an unpinned url refuses, naming rut install), and the bytes must hash to the lock row’s sha256, on every load, or the load refuses naming the dep, the url, and both hashes. The url dep mounts as a leaf: its bundle brings the whole closure (every declared dep satisfied by an in-archive group — the closure law is unchanged, and a url row inside a packed bundle is inert metadata; loading a bundle never fetches).

Because the manifest rides byte-for-byte, url rows carry into a consumer’s own rut pack output, satisfied by the groups the archive carries: the archive’s groups re-encode from the consumer run’s units (one .rutc path) or copy their file sets under the new identity prefixes, and the same manifest + lock still pack byte-identically. The pack refuses, loudly and named, the cases that would emit a bundle the loader must reject: an archive source group still declaring dev-deps directories (vendor the dep), a compiled group the consumer’s closure never uses (it cannot ride unpackaged), and a declared dep that did not ride.

The wire version

format_version is 12 — the one bundle wire, both root kinds; the manifest’s type routes lib-compiled vs host-decl. The 11 lane — the pre-declaration-entry wire — READS FOREVER (a published bundle is forever old, and a rut.lock pin to v11 bytes keeps working; migration is a re-pin, not a break). Anything else refuses before reading anything else — refuse, never guess: this toolchain reads bundle format_version 12 (and the old 11 lane) only (found {v}) — re-pack the directory.

Every file in the two layouts is part of the package: a bundle that dropped a declared child module would load partial — semantically wrong, so the closure law is checked at the mount. Compilation is the contract, no exceptions — the generic bodies ride INSIDE the binary as templates (instantiation independence, above), so consumer-spelled shapes stay servable and a published bundle never carries source. Source sharing as the general contract stays a directory (rut run <dir>), as it always was outside bundles.

The groups mirror the manifest. The archive root is the root’s own files; every dep rides at deps/<name>@<fp16>/ — the dirname IS the content identity, fingerprinted over the group’s own rode source set, and the reader recomputes the fingerprint and refuses a mismatch (a doctored or stale dirname). Same source ⇒ same dirname, so a repack of an unchanged group lands at the same directory and the two identities of one name coexist side by side (the packer exact-dedups one identity’s file set — two groups stage to one identity only when their bytes are equal).

The ledger namespaces per archive. Each archive’s scope rows shift into a fresh numeric range of the consuming run’s world (boot passes through), and its binaries rebase with that same map before mounting — so two independently packed bundles can share one world without their pack-time numberings ever arguing. First-mount-wins still decides which body a shared group name keeps, and a group’s ledger row must still be the scope its own binary carries (refuse, never guess — that check is per archive). The CDN lane below is the reason this exists: per-package bundles are packed independently, each numbering its own closure.

The bundle module

The container codec, the rut.jsonc grammar, the source file-set collector, and the reader (both root kinds) live in the driver’s rut_driver::bundle module — pure and in-memory: the walk adds every filesystem read. That half lives in rut-native, whose one-method Source trait is the one filesystem door: rut_native::FsSource::at(dir) is the real filesystem (the CLI, native hosts); an in-memory path→bytes map serves tests and wasm hosts. The packer needs the walk and lives beside it (rut_native::pack_dir) — it returns the bundle bytes; writing the output file stays with the caller. Loading a bundle into a run goes through rut_native::load_bundle_session(path) (the file read) or rut_driver::Bundle::parse(&bytes) (the decode-once handle) over the parsed rut_driver::bundle::Bundle and its rut_driver::bundle::Layout — the compiled root and its ledger + groups, or the decl root and its surface.

Deterministic packing

Same directory + same toolchain ⇒ byte-identical .rutbundle:

  • fixed entry order — rut.jsonc first, then the scope ledger, the root’s binary, then the root’s generated declaration entry (plus its module rows when it has mod children), then dep groups in identity order (one group per distinct identity);
  • fixed (zeroed) timestamps;
  • STORE (no compression) — determinism over size.

This is the module binary’s determinism law extended one level up (Module binary and verification): bundles are content-cacheable, and two builds of the same module diff to nothing.

Stripping — the private sidecar

rut pack <dir> --strip emits the bundle as above plus a private symbol table at the sibling path <out-without-ext>.rutsym. Every renameable name in the .rutc binaries mangles to %N and every function’s span/position tables leave — the sidecar carries exactly what left, so supplying it at load restores real names and line/col for stack-trace symbolication. The sidecar is never an entry inside the archive. It needs a fully-compiled closure (a source group that could bind a compiled group’s surface is a pointed refusal); without --strip, packing is unchanged. The whole law lives in Symbol stripping and .rutsym sidecars. run accepts --symbols <file.rutsym> against a compiled bundle (The rut CLI).

The declaration entry is the strip policy’s other half (v1): a stripped pack OMITS every compiled group’s generated entry. The entry’s plaintext would state the real names the binary just mangled — shipping it would undo the strip. The editor degrades to the ladder’s floor (the object surface’s own names-less rows); the sidecar restores everything privately. Host groups are unchanged: their entry IS their source, there is no binary to mangle, and a host root refuses --strip outright.

Checks on load

Every check runs at load time, before compilation and linking — a bad bundle never executes. The order is the law: container, then manifest and version, then every group’s decode, then the mount.

checkrule on mismatch
zip entry CRC-32refuse — corrupt bundle (names the entry)
rut.jsonc present, "format": "rutbundle"refuse — not a rut bundle
format_version exactly 12 (or 11 — the old lane, read forever)anything else refuses — this toolchain reads bundle format_version 12 (and the old 11 lane) only (found {v}) — re-pack the directory
a host root carrying a root mod.rutcrefuse — a host bundle’s root is its surface, not a compiled unit
a host root carrying a rut.scopes ledger or any group entryrefuse — a host bundle is its surface, single-package
a compiled root without its rut.scopes ledger, or a ledger row that is not a content identity (name@<16 hex>)refuse — a corrupt compiled bundle
an entry under a top-level prefix other than deps/refuse — the archive root carries only the root’s own files; dep groups ride at deps/<name>@<fp16>/
a deps/ group directory whose name is not a content identityrefuse — expected <name>@<16 hex>
a group’s manifest name disagreeing with its dirname’s name halfrefuse — names both
a group dirname’s fingerprint disagreeing with the hash of its rode source setrefuse — the dirname and the content disagree
mod.rutc decode (root and groups): version, tables, surface idsrefuse — names the entry and the cause
a compiled group’s ledger row agrees with its binary’s own scoperefuse — corrupt or doctored
a riding source entry that fails to read or decode (UTF-8)refuse — names the entry; a bad archive never reaches the run
every declared dep satisfied by a group (compiled roots)refuse — names the missing group

The std tree on a CDN — the per-package delivery

The std tree (rut/) ships as committed per-package bundles at dist/std/<pkg>.rutbundle — one bundle per package a deps row can spell (16 today). jsDelivr’s gh lane serves repo files at a ref, so the artifacts ARE the delivery and the publish act is a git tag:

{
  "deps": {
    "http": {
      "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@<tag>/dist/std/http.rutbundle"
    }
  }
}

<tag> is a placeholder — real urls live in the worked manifests, and the real pins live in each project’s committed rut.lock (the in-repo examples’ locks are the reference; anti-rot: docs never rot pins). The laws:

  • Committed artifacts, immutable tags. scripts/pack-std::cjs packs all 16 (deterministic — same input ⇒ byte-identical, so freshness is a pure equality gate: --check repacks and byte-compiles, no network; the retired --pins flag is gone — the pins live in rut.lock now, written by rut install, and no manifest tool rewrites them anymore). Tags advance (std-vNN) and are never re-pointed — jsDelivr caches aggressively.
  • What a compiled bundle serves. Instantiation is owner-anchored: a compiled owner carries the generic instantiations its own pack closure spelled in its ledger — and its generic BODIES as templates inside the binary (instantiation independence): at the consumer’s link a request the ledger lacks monomorphizes from the template under the declaring pkg’s spec (one row program-wide, nothing persisted). So the CDN lane delivers host surfaces (decl bundles), concrete-class libs (http, ink, strbuild — methods cross on the surface’s inherent rows), and the generic owners (pouch, flow, nmapset, json, futures — Vec<Todo>, Flow<i32>, decodeJson<T> compile at the link from the templates). The law binds this lane too: a pkg that owns an open generic surface but whose binary carries no template bodies refuses at the mount (corrupt or doctored — re-pack the directory). And every bundle is closed — a bundle-mounted json carries its strbuild + pouch + nmapset groups inside, so its wrappers’ use heads resolve wherever it travels (the ordinary closure law).
  • Duplicate mounts are safe. Two archives may carry the same group (json’s and http’s closures both carry strbuild): the same identity mounts once (exact dedup), two identities of one name coexist side by side, and the per-archive ledger namespacing keeps every binary’s ids resolving through its own archive’s rows. A bare use head under several identities of one name is the loud ambiguity (Dependency kinds) — pin one of them with your own deps row.

Loading

A bundle is one more resolution source alongside the directory form — same name resolution, same compile, same identity-keyed groups:

// from a file
let loaded = rut_native::load_bundle_session(Path::new("vendor/plugin.rutbundle"))?;
// from bytes (embedders, tests, wasm) — the pure container parse
let bundle = rut_driver::Bundle::parse(&bytes)?;

After the offer, the package name resolves exactly as the directory form does — with one difference: a compiled group’s body is the decoded program itself. The run assigns it a fresh scope, rebases its packed ids through the ledger, and pushes it; source groups offer as sources and compile exactly as a directory world. Then the normal pipeline takes over (Loading and the embed loop). Loose directories and loose .rut files stay valid share layouts; the bundle packages them, nothing requires it.

CLI

rut pack <dir> [-o <dir>.rutbundle] [--strip]   # default output: a sibling of the dir
rut run <dir | mod.rutbundle> [--symbols <file.rutsym>]

The packed form and its directory compile to identical programs — pinned by tests (the linked binaries are equal).

Project structure and rut.jsonc

One directory is one module; its rut.jsonc names the exact package it answers to and how to reach its surface. The body is a file module tree: the root module is mod.rut beside the manifest, and mod NAME; declarations in it mount child modules (NAME/mod.rut beside the declaring file, or the single-file NAME.rut). The manifest is what makes the directory the runnable unit: rut run <dir> (or its packed .rutbundle) is the only run lane — a loose .rut file is not a program (the rut CLI). This page is the manifest grammar, the resolution laws, and where everything lives in the toolchain tree.

The manifest

// rut/pouch/rut.jsonc — a body package (the body is mod.rut beside it)
{
  "name": "pouch"
}

// rut/calc/rut.jsonc — a pure declaration surface (a host pkg)
{
  "name": "calc",
  "type": "host",
  "entry": { "type": "./calc.d.rut" }
}

// the same surface, the default-root spelling: mod.d.rut beside the
// manifest IS the root — entry.type is optional on a host pkg
{
  "name": "calc",
  "type": "host"
}

// a consumer (an app directory): a `path` row for a sibling package
// of your own, url rows for the toolchain's packages — the pins live
// in the app's rut.lock (`rut install` writes it)
{
  "name": "app",

  "deps": {
    "greet": { "path": "../greet" },
    "pouch": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle" },
    "ink":   { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" }
  }
}

The keys, all of them:

keymeaning
namethe package’s use-path name: bare [a-zA-Z0-9_]+ only. A scoped or quoted spelling is a manifest error.
entry.typethe declaration surface: one .d.rut file — the ONLY entry key left. OPTIONAL on a host pkg: when absent, mod.d.rut beside the manifest is the root surface (lib parity with a body’s mod.rut), and when spelled it wins. Neither present is the loud no-entry error naming both spellings. On a lib pkg it is documentation surface (a surface-only dev state mounts as a declaration unit; host fn text there is refused)
typethe declared kind: type = "host" for a host pkg — a pure declaration surface whose host fns the embedder binds at load (Host fns and declaration files); the surface organizes as a module tree of mod.d.rut files rooted at the default root or the spelled entry.type (below); type = "lib" (or absent) is the ordinary source package. The kind is never inferred — an entry.type-only manifest with no kind and no mod.rut is an error naming both fixes
depsthe transitively mounted dependencies — and the declaration table: a pkg may use exactly the heads its manifest names (deps ∪ core, plus dev-deps at the program root), so a head riding someone else’s deps is mounted but not nameable (Nameability). One source per descriptor: pkg = { path = "..." } (relative to this manifest) or pkg = { url = "https://…" } (a remote .rutbundle) — never both, never neither. Url rows carry no pin: the sha256 key is retired from the grammar, and the pins live in the walk root’s rut.lock beside this manifest — rut install writes it and every load verifies against it (Dependency kinds, The rut CLI). optional is rejected here.
dev-depsmounted only while building/testing this pkg itself — never in a consumer’s world. Descriptors are path-only: a dev row is directory-time metadata for the declarer’s own build, nothing to fetch (Dependency kinds)
format, format_versionbundle keys — ignored by directory loading, required by rut pack (Module bundles)
styleformatter knobs: indent_width (1–8, default 4), max_width (≥ 20, default 100). Schema-free at the manifest layer — unknown keys ride; malformed values are formatter errors, never compile errors. Resolution: the nearest ancestor manifest of the formatted file; no manifest → defaults.

The grammar is strict at the top level: the keys above are all of them, and any other top-level key refuses naming the key — manifest: unknown key 'whatever'. There is no forward-compat lane: a typo is a manifest error, never a silent ignore, and the retired keys refuse the same way (peer-deps and inline are unknown keys now); host_scope keeps its dedicated retirement refusal — the registration scope is the package name.

The body keys are repealed: entry.lib and entry.libs refuse loudly, each error naming the fix — the root module is mod.rut beside the manifest, structure lives in mod directories. (Inside a published bundle the old keys still load — the reader’s compat lane; see Module bundles.)

The manifest text is JSONC — // line comments, /* */ block comments, and trailing commas are all legal — parsed by serde_json behind a syntax-stripping front stage: the comment and comma bytes become spaces before the parser sees them, so a syntax error keeps the parser’s own wording under a line N: prefix that names the ORIGINAL file’s line. The value laws are unchanged. Value errors are path-targeted (deps::pouch: unknown key 'feats'). Descriptors are key/value objects; unknown descriptor keys are path-targeted manifest errors. Duplicate keys are last-wins. An _-key refuses loudly naming the fix — comments are the prose now.

Resolution laws

  • Exact, single-step. A use path resolves only if a module with that name is mounted and the consuming manifest declares it — nameability is declaration-scoped, so a mounted-but-undeclared head is the D5 diagnostic naming the mount edge and the fix row (Dependency kinds). Nothing is derived from directories or file layouts beyond the mod declarations the source itself spells.
  • The walk is recursive, with a cycle guard; first mount wins. An already-mounted name (the embedder’s, the root’s, or an earlier dep’s) is never overwritten — the consumer’s own path for a package always beats a dep’s transitive row.
  • Name mismatch is an error. A dep whose manifest name disagrees with its key fails, naming both.
  • The cross-table law. A name in deps beside dev-deps is an error naming both rows — a package is either pulled transitively or held for development, never both.
  • core needs no deps — .compile() auto-offers it unconditionally (core and the swappable packages); every name still requires use core::{ .. }; per core and the swappable packages.

Module trees

A package’s body is authored as a file module tree — the tur_kit-style layout:

tur_kit/
├── rut.jsonc        # no entry keys — mod.rut IS the lib
├── mod.rut          # the root module
├── layout/
│   └── mod.rut      # tur_kit::layout
└── widget/
    └── mod.rut      # tur_kit::widget

The root module declares its children:

// tur_kit/mod.rut
pub mod layout;
pub mod widget;

Mounting is declared, not discovered: mod NAME; (or pub mod NAME;) in a file resolves against the sibling NAME/mod.rut directory — or, when there is no such directory, the single-file spelling NAME.rut in the same directory (both present is a loud ambiguity naming both spellings; a single-file child mounts at the logical mod path NAME exactly as the directory would). The loader never reads a directory listing — an undeclared directory is invisible, a declared child that is missing under both spellings (or whose directory carries no mod.rut) is a loud error naming the spellings. Mounting is recursive and cycle-guarded by file identity; a repeated declaration mounts once.

Visibility is per module file (Modules and visibility): plain declarations are visible in their own module and its descendants, pub(pkg) shares inside the package, pub crosses packages. Cross-file references inside one package are qualified positions (layout::Column, widget::mk(3) — the :: spelling); use statements stay the only cross-package door (use tur_kit::layout::{ Column }).

Host surface trees

A type = "host" package has no body — but its .d.rut surface organizes as the same kind of tree. The root surface follows the same discovery law a body’s mod.rut does: mod.d.rut beside the manifest is the default root (lib parity), and a spelled entry.type still wins — calc.d.rut, engine.d.rut and every other flat host pkg keep their custom root names. Neither present is the loud no-entry error naming both spellings. mod NAME; in the surface file mounts NAME/mod.d.rut beside the declaring file — or the single-file NAME.rut when there is no such directory — recursively and cycle-guarded, exactly like a body tree with mod.d.rut as the module file (both spellings present is the loud ambiguity):

http_host/
├── rut.jsonc           # type = "host" — no entry keys: mod.d.rut IS the root
├── mod.d.rut           # the root surface: pub mod net;  pub mod stream;
├── net/
│   └── mod.d.rut       # http_host::net — the request lane + readbacks
└── stream/
    └── mod.d.rut       # http_host::stream — the body lanes

The tree is declaration-lawed like everything else: a declared child with no NAME/mod.d.rut beside it is a loud error naming the declaring file, a mod.rut beside a host manifest still refuses (the pkg is a pure surface — the message points at mod.d.rut), and the pub on both the mod edge and the host fn row is what a consumer’s use crosses.

What the tree changes is the registration naming: a row under net/ registers as pkg::net::name (async families ride the qualified name too — pkg::net::send__start et al), while the root’s own rows keep the flat pkg::name shape. Consumers spell the tree in their uses (use http_host::net::{ send }), and the embedding Rust registers the bodies scope-relatively ("net::send" under HostPkg::new("http_host") — embedding and native modules). Packing rides the same additive envelope a body tree uses: the tree travels as rut.mods source rows inside the bundle, and a FLAT host pkg packs byte-identically (no rows entry) — module bundles.

The toolchain tree

rut/
├── crates/
│   ├── rut-lexer/        # spans, tokens, the lexer, diagnostics
│   ├── rut-ast/          # the flat arena AST + dumper
│   ├── rut-parser/       # the frame machine, Mode::Impl | Mode::Decl
│   ├── rut-semantic/     # the semantic classifier (spans + token classes)
│   ├── rut-lir/          # the fused middle end: check/ (resolve,
│   │                     #   typecheck, monomorphize) + lir/ (bodies,
│   │                     #   peephole, SROA, async lowering)
│   ├── rut-core/         # types, ops, binary encode/decode, link, sym
│   ├── rut-vm/           # heap, interpreter, verifier, driving loop
│   ├── rut-vm-threaded/  # tail-call threaded dispatch (nightly `become`)
│   ├── rut-driver/       # the run chain: Pkg, RutRun, Compiled; bundles, dep graph, decl
│   ├── rut-native/       # the walk and the world: Source/FsSource, DepRemote/HttpRemote, pack
│   ├── rut-fmt/          # the formatter
│   ├── rut-std/          # host bodies: log, math, nmap, http, async
│   ├── rut-wasm/         # the wasm ABI (compile/run envelope)
│   ├── rut-lsp/          # the language server (stdio)
│   ├── rut-lsp-wasm/     # the same queries as an in-process wasm module
│   └── rut-cli/          # the `rut` binary ([The rut CLI](cli.md))
├── rut/                  # the in-tree packages (below)
├── examples/             # 00-todolist … 06-github-viewer-cli
├── demo/                 # the wasm playground (React + rspack)
├── benches/              # cross-runtime benchmarks
└── integrations/         # editor configs; the vscode extension

Dependency line: rut-lexer ← rut-ast ← rut-parser ← rut-driver → rut-lir → rut-core ← rut-vm (with rut-vm-threaded behind it; the driver sits on the vm’s HostPkgContext/HostRegistry for the install law), rut-native beside the driver (it depends on the driver, never the reverse — the driver is provably pure: no fs, no net, no std::path), hosts (rut-std, rut-wasm) on top, and rut-cli/demo above those. rut-lsp sits on the frontend crates — tokens, diagnostics, and symbols need no VM — plus the driver’s pure core for manifest and bundle parsing (the dep tables behind the editor’s dep walk). Its classifier is rut-semantic (re-exported as rut_lsp::semantic), which sits on the frontend crates for the same reason — embedders take it without the server.

The in-tree packages

rut/ carries the standard and swappable packages the CLI offers on demand:

packageshape
corethe only standard package — the builtin surface, auto-offered by every run’s .compile()
calchost pkg: the math surface — offer rut_native::tree_pkg("calc"), bind rut_std::math::pkg() (stdlib)
ink_host, nmap_host, async_host, bench_crosshost pkgs — flat .d.rut surfaces; bodies live in rut-std
http_hosthost pkg, the surface-tree pilot — the default mod.d.rut root over the std HTTP rows, net/ + stream/ mods (project structure); bodies in rut-std
ink, http, strbuild, futuresrut classes over host rows (published compiled — methods cross on the surface’s inherent rows)
pouchthe growable sequence Vec<T> (plain linked package)
flowthe push pipeline (Flow<E>; its VecFlow/SetFlow wrappers over pouch/nmapset)
jsonthe serde pkg — owns the wrapper families over pouch/nmapset, plain deps (Dependency kinds)
nmapsetnative-key maps/sets over nmap_host

Nothing in the engine knows the swappable packages’ names — deps are resolved by name from manifests; a host may replace the non-core set wholesale (Embedding and native modules).

The playground

demo/ is a React + rspack + TypeScript page over the wasm build. The wasm ABI is two calls — compile(src) returning diagnostics, an AST dump, an IR dump, and an optional binary; run(binary, budget) returning output lines, an optional trap, and used fuel/heap. Fuel is off by default (fuel 0 is the ABI’s uncapped encoding) and opts in through the page’s fuel box; the heap defaults to 4 MiB, and auto-runs keep an internal 1M fuel watchdog so unbounded loops park and resume instead of hanging the page. The served artifact is deployed at https://playground.rut.hpp2334.com.

Dependency kinds

Every package’s rut.jsonc names the packages it relates to, and the kind of each relation decides how — and whether — it mounts, and whether the declarer may name it. Two tables, one grammar, strict keys:

  • deps — the transitively mounted dependencies — and the declaration table: a pkg may use exactly the heads its manifest names.
  • dev-deps — mounted only when building/testing the package itself (the program root), never in a consumer’s world.

A package is either pulled transitively (deps) or held for development (dev-deps) — never both. There is no third relation: the strict-keys law refuses any other top-level key naming the key, so a retired table (peer-deps) or flag (inline) refuses as the unknown key it now is — manifest: unknown key 'peer-deps'.

The grammar

// rut/json/rut.jsonc — the reference shape
{
  "name": "json",

  "deps": {
    "strbuild": { "path": "../strbuild" },
    "pouch":    { "path": "../pouch" },
    "nmapset":  { "path": "../nmapset" }
  }
}
  • Keys are bare package names — the same [a-zA-Z0-9_]+ law as name; a dep-table key outside it is a path-targeted manifest error.
  • A deps descriptor accepts exactly one source: path (a directory, relative to this manifest) or url (a remote .rutbundle, http(s)) — both set, or neither, is the one-descriptor-one-source manifest error. Any other key is the strict-manifest error naming the path (deps.pouch: unknown key 'feats').
  • A dev-deps descriptor is path-only — dev rows mount only for the declarer’s own build walk (directories, never fetches); url, optional, and lib refuse as the unknown keys they are.
  • The zero-dep spelling { path = ".." } is valid in both tables.
  • The cross-table law: a name riding deps beside dev-deps is a manifest error naming both rows — pouch appears in both deps and dev-deps — a package is either pulled transitively or held for development, never both.

Url dependencies — the second source kind

A deps descriptor may name a remote .rutbundle instead of a directory:

{
  "deps": {
    "pouch": { "url": "https://example.com/pouch.rutbundle" }
  }
}
  • One descriptor, one source: path or url, never both, never neither — a path-targeted manifest error either way. The url itself must be http(s). dev-deps stays path-only — a dev row is directory-time metadata for the declarer’s own build, nothing to fetch.
  • The manifest row carries no pin. The old optional sha256 key is retired from the descriptor grammar — the strict (directory) lane refuses it, naming the fix: deps.pouch: 'sha256' retired — pins live in rut.lock (run rut install). Pins live in the walk root’s rut.lock (rut install writes it), read fresh on every load. (Inside a published bundle the reader’s compat lane still parses the old key — inert metadata, never enforced — module bundles.)
  • The layer split. The call site owns HOW bytes arrive — transport, caching, offline policy — by implementing the DepRemote contract (fetch(url) — one required method returning a boxed future of bytes — plus optional lookup/write; the standard rut_native::HttpRemote is cache-first). The walk owns WHAT the bytes are declared to be: the pin is lock law — the closure’s url rows are collected at the root, gated against rut.lock before any fetch (an unpinned url is refused before the wire), and the fetched bytes are verified against the lock’s pin at the mount door on every load — fresh fetch, cache hit, vendored map, test fixture. A check the call site performs would be a check the call site could skip; only the mount point holds both the pin and the bytes, so only the mount point can enforce it.
  • Url deps are leaves. The deps walk never follows them: one fetch brings the whole closure, because bundles stay closed — every dep a bundle’s manifest declares must be satisfied by an in-archive group, and a bundle that does not satisfy one is refused at the mount door. A url row inside an already-packed bundle is inert metadata; loading a bundle never fetches.
  • The lock is the pin lane. A url the lock has no row for refuses at the mount door, naming the fix: dep `pouch` (https://…) is not pinned — rut.lock has no row for it: run `rut install` ; fetched bytes that break the lock’s pin refuse too — dep `pouch` — sha256 pin mismatch for <url>: rut.lock pins <sha>, the fetched bytes hash to <sha>. Reproducibility is the pair’s law: same manifest + same rut.lock ⇒ identical resolved world — the lock pins are what make packs reproducible, and --locked verifies the pair before anything runs.
  • The CLI lane: rut run/rut pack fetch through the cache-first standard remote (<project>/.rut/cache, $RUT_CACHE_DIR overrides; a hit never touches the network), and a pin refusal evicts the poisoned cache entry so the next run heals. rut install <dir> resolves + fetches + writes the lock (--locked verifies without writing — the CI lane), and rut fetch <dir> re-warms the cache without running anything (The rut CLI).

The std tree on jsDelivr

Which kind, when. The toolchain’s standard packages (core, ink, pouch, json, …) are consumed as url rows pinned by the project’s rut.lock from this CDN — that is the recommended import for everything the toolchain ships. A path row is for your own local packages: a sibling directory in the same project (the modules tutorial’s greet app mounting ../pkg is the shape). The tag advances with format changes (std-v11 today) and is never re-pointed, so a lock pin at a tag stays honest forever.

The std tree ships as committed per-package bundles — https://cdn.jsdelivr.net/gh/hpp2334/rut@<tag>/dist/std/<pkg>.rutbundle. The manifests here keep placeholder tags; the worked manifests in the quick-start, the tutorial, and the examples carry the real urls, and their committed rut.locks carry the real pins (a pin at an immutable tag cannot rot). Tags advance (std-vNN) and are never re-pointed — jsDelivr caches aggressively; the artifacts are committed at dist/std/, packed by scripts/pack-std::cjs (whose --check gate is a pure byte-equality repack — CI never touches the network).

What a url row can deliver is the engine’s instantiation law, read from the CDN side: a compiled bundle carries the generic instantiations its own pack closure spelled in its ledger, and — by instantiation independence — its exported generic decls ride as templates inside the binary:

  • host surfaces and concrete-class libs deliver — a type = "host" bundle is a declaration surface (no generics), and a lib of concrete classes (http, ink, strbuild) crosses on its surface’s inherent rows with its whole closure riding inside;
  • generic owners deliver too — pouch, flow, nmapset, json, futures carry their generic bodies as templates in the binaries, so a consumer’s Vec<Todo> or decodeJson<Vec<Todo>> compiles at the consumer’s link: a shape the ledger lacks monomorphizes from the template, the body registers under the declaring pkg’s spec (one row program-wide, identity by owner), and nothing persists (.rutc caches stay pack-time). The law binds both sides: a pkg that owns an open generic surface but whose binary carries no template bodies refuses at the mount (corrupt or doctored — re-pack the directory). And a bundle is closed: every dep its manifest declares rides as an in-archive group, so a bundle-mounted json carries strbuild, pouch, and nmapset inside — the ordinary closure law, nothing to supply at the consumer’s side.

Semantics

tablewho supplies ittransitive?missing behavior
depsthe declarer’s own graphyes — walked recursivelymount error
dev-depsthe pkg’s own self-buildroot only — never walked for a depn/a (they exist to be there)

The tables decide mounting; what a mounted head lets its consumer name is the declaration-scoped law of Nameability below.

The mount law — three passes

All loader-owned; the run stays I/O-free.

  1. The deps walk. Recursive, name order, first-mount-wins, cycle guard, name-mismatch error. A dep mounted from a url bundle brings its whole closure with it: the archive’s groups mount under their content identities (name@<16 hex>) — first-mount-wins becomes per-identity exact dedup (Module bundles, Coexistence).
  2. The dev pass — root only. The program root’s dev-deps mount exactly like deps. A dep’s dev table is never walked — a consumer’s world never contains another package’s dev table. Offering a package to someone else’s program (rut_native::dir_pkgs, or .pkg(..) by hand) is the same law: it walks no dev-deps.
  3. Compile. Every mounted module links — sources compile in dependency post-order, and the walk’s yield is the whole program. There is no presence-gated append and no splice lane: nothing changes shape after the walk.

Nameability

The passes above decide what mounts; a separate, declaration-scoped law decides what a source may name. Mounting stays transitive — A’s deps still pull B into the closure, and A still compiles against B’s mounted rows — but nameability belongs to the consumer’s own manifest: a package may use exactly the heads it declares itself,

deps ∪ (dev-deps, only when the package is the program root) ∪ core

— and there is no ambient tier. core rides unconditionally (the graph threads the prelude into every unit, and the resolver passes the core head without a row); every other head must be the consumer’s own declaration. Over-declaring stays legal — the law bounds uses by declarations, never declarations by uses — so a row naming a head the source never spells is inert.

The dedicated diagnostic is D5, and it fires only when a head is MOUNTED but UNDECLARED by the consumer — an unmounted head keeps its existing shape (NoModule for a name nothing offers). D5 names the mount edge — who pulled the head in — and the fix, in two renderings:

  • The walked edge (the consumer mounts through the dep walk, an archive group, or a dev row — there is a first-mount mounted_by edge to name): the puller and the jsonc row to add:

    cannot resolve `b` — `b` is mounted in this program (pulled by `a`) but `app` does not declare it; add "b": { "path": ".." } to `app`'s `rut.jsonc` `deps`
    
  • The host edge (a hand offer — no walk edge exists): the “offered by the host” clause, and a fix that names the manifest-builder doors, never a file:

    cannot resolve `b` — `b` is mounted in this program (offered by the host) but `c` does not declare it; declare it in the pkg's manifest — `Manifest::lib("c", &["b"])` or a `"deps"` row through `parse_manifest(..)`
    

The closure check reads every mounted source’s uses at every depth, so the law is per-package, not root-only: a dep naming a head it never declared is the same D5 with that dep as the consumer. dev-deps follow the same root-only law as their mount pass — the program root may name its dev-deps; a dep naming the root’s dev-dep is D5.

Heads are one axis of nameability; the file is the other. A head must be declared by the package’s manifest, and a leaf must be bound by the file that spells it: a use binds its own file — every file of a multi-file package writes its own imports, and no ambient tier backfills a leaf a file never spelled (the engine’s builtin names are the only ambient set). Validation is total and lands at the use line: a leaf that binds nothing there is a hard error — a private row of the target says `helper` is not exported by `pkga` — mark it `pub` there, a surface a compiled bundle never carried states the bare law — and a leaf name spelled twice in one file errors at the second spelling (the name is the rule, never the package). pub async fn crosses like any pub fn — the consumer’s call answers the closed Future<answer> — except the generic shape, which refuses at the use line. The full leaf law, with every diagnostic, is Uses.

This is a breaking law change. Mounting was always transitive, and nameability used to ride along with it: a program could use any head the closure happened to contain. Previously-compiling programs that rode a transitive head now refuse with D5 and the fix row — add the head to the consumer’s own manifest.

Embedders and hand-mounted worlds are lawed by the same declaration table, carried structurally on the Pkg — parse_manifest for an embedded jsonc, Manifest::lib(name, &[heads]) for an ad-hoc surface (embedding). The wasm playground stamps the same shape, defaulting the program’s declaration host-side to the offered lib names.

Coexistence

A dep group mounted from a bundle carries its content identity — name@<16 hex>, the first 16 hex chars of the sha256 over the group’s own rode source set (rut.jsonc, mod.rut, mod.d.rut, rut.mods; fixed order, absent files skipped). Same source ⇒ same identity, and the same identity mounts once (exact dedup); two identities of one name mount side by side — two builds of util in one program without colliding. @ sits outside the [a-zA-Z0-9_]+ name alphabet, so an identity can never collide with a bare package name.

A bare use head stays exact while one identity spells the name; under several, it refuses naming them all:

cannot resolve `util` — 2 identities of that name are mounted (`util@0123…`, `util@4567…`); a bare use head is ambiguous under coexistence — mount one of them under its bare name or bind through the bundle's scope ledger

— mount one of them under its bare name (your own deps row) or bind through the bundle’s scope ledger (Module bundles).

Interplay

  • Dev-deps are invisible to bundles-as-consumers. A packed package carries its closure; a consumer packing their app never pulls the package’s dev table (pass 2 is root-only), so dev-only convenience packages cannot leak into consumer worlds (Module bundles).
  • Structural satisfaction is unaffected: a consumer’s own types satisfy json’s interfaces by having the members, whether the interface came from a path row or a packed bundle.
  • The LSP is advisory. The language server embeds the toolchain packages’ sources, never parses manifests, indexes every dep it can reach (any depth, the root’s dev-deps too), and completes heads the compiler’s D5 would refuse for an undeclaring consumer — it runs no declaration-scoped filter and raises no D5. Recorded as accepted: the LSP is advisory; the compiler is the law.

Consuming a compiled package

// an app that wants json's whole surface
{
  "deps": {
    "json": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/json.rutbundle" }
  }
}

One row is the whole story: the bundle is closed, and json’s own deps — strbuild, pouch, nmapset — ride inside it as groups, so every wrapper family resolves wherever json travels. The same shape works with path rows into your own tree; the walk pulls the declared table transitively either way.

The rut CLI

The rut binary is the toolchain’s command-line face. It is also a full host: running a program walks its directory, offers the tree packages its surface names, binds the standard native bodies, and drives the async loop — the same contract an embedded host implements (embedding and native modules).

It is the temporary-run lane: running module directories and bundles, fmt, dump, pack. The intended consumption path is depending on the engine crates from your own project through a Cargo git dependency (installation) and embedding the VM (embedding and native modules) — this page documents the binary itself. To get the binary: cargo install from git, cargo install --path from a checkout, or a plain cargo build --release (installation).

rut run [<dir | mod.rutbundle>] [--entry <fn>] [--fuel N] [--symbols <file.rutsym>] [--no-cache]
rut new <dir>
rut install [<dir>] [--locked]
rut fmt <file.rut | dir> [--check]
rut pack <dir> [-o out.rutbundle] [--strip]
rut fetch <dir>
rut dump <file.rut>

The arg surface is clap: rut --help prints the commands, rut <command> --help the flags. run and install take their <dir> optionally — omitted, both act on the working directory (.): inside a module directory, rut run runs it and rut install pins it. Running rut with no subcommand prints the help to stderr and exits 2; a parse error — an unknown flag, a dangling flag value, an unparsable --fuel — is the same exit 2 with clap’s message. The usage sketch above stays the quick map.

run

Compiles and executes. Two input forms — every rut program is a module directory (project structure), so there is no loose-file shape:

inputpipeline
dir (a module directory with rut.jsonc)cache-first: the run key is sha256 over the closure’s sources, manifests, rut.lock pins, and the toolchain version — a hit in .rut/cache/<key>.rutbundle mounts the cached archive; a miss is the whole-program compile (the deterministic reference — the compilation model), whose archive then emits into the cache. --no-cache (alias --repack) forces the miss path; the fresh archive still refreshes the entry. A host-rooted directory never reaches the cache (it refuses at the door — a host root is a declaration leaf, nothing to run)
mod.rutbundlethe packed form of the same contract — decoded directly, no cache lane (module bundles)

Anything else is refused at the door (exit 2): a loose .rut file is not a runnable unit — give the directory a rut.jsonc naming the package ({"name": "…"} — the root module is mod.rut beside it; JSONC: // comments and trailing commas are legal), or run a packed .rutbundle.

Flags and defaults:

itembehavior
--entry <fn>name the entry fn to run. Without the flag: exactly one entry fn runs the program; several refuse to guess (exit 1, naming the set); none reports no entry fn — nothing to run — a library shape compiles clean, the designation is where the run stops. A named fn that is not an entry is a loud error
--fuel Ncap the op budget per turn. Fuel is opt-in: without the flag the run is uncapped; a missing or unparsable value is a loud error (exit 2) — no silent default
--symbols <file.rutsym>restore a stripped artifact’s private symbol table — legal only against a compiled .rutbundle (the directory lane compiles fresh and needs no map; anything else is a usage error, exit 2). The table restores before the graph compiles, so linking and every trace see real names; sections naming modules the bundle does not carry warn
heap limitfixed at 64 MiB
interrupt checkevery 1024 ops

Bodies bound by run (each rides the chain as pkg(Offer::Host(..))):

chain steppurpose
math::pkg()calc’s float fns
logger::pkg (sink: stdout)the logger; silent no-op unless the program uses ink
nmap::pkg()the native key table behind nmapset
bench_cross::pkg()the crossing-benchmark rows
async_host::pkg()the async launchers
http::pkg()the std HTTP lanes

Execution: main is called with no arguments; then the async driving loop runs — drain the ready queue, advance the virtual clock to the next timer deadline, repeat until no frames and no pending work remain. The loop is capped, so a program that never idles fails loudly instead of hanging.

A .d.rut input is refused: a declaration file is a surface, not a runnable module (host fns and declaration files).

new

rut new hello            # scaffold a hello-world module directory

Scaffolds a hello-world module directory in three files: the manifest with the full swappable std set as unpinned url deps, the matching rut.lock (the std set’s pins), and the root module — the same bytes as your first rut program. The directory is runnable as-is: rut run hello prints hello, rut!.

Behavior:

itembehavior
package namederived from the target’s basename — bare [a-zA-Z0-9_]+, non-empty (the manifest’s law). An illegal name is refused, never sanitized (exit 2)
clobber refusala target already holding a rut.jsonc, a mod.rut, or a rut.lock is refused (exit 2, naming the file) — other pre-existing files are fine
parentscreated as needed — rut new a/b/hello works
files writtenrut.jsonc — the derived name plus the whole swappable std set (nine packages) as unpinned url deps at the @std-v11 tag; rut.lock — the set’s pins, rendered through the lock grammar (install is its re-writer); mod.rut — the ink hello
first runfetches the std set (9 bundles) into <dir>/.rut/cache; rut install <dir> or rut fetch <dir> pre-warms without running

The three created files, for rut new hello — all verbatim:

{
  // hello — scaffolded by `rut new`: a runnable hello-world module
  // dir — the manifest carries the deps, and `mod.rut` is the root
  // module the loader mounts.
  //
  // THE STD SET: all nine swappable std libs, each a COMMITTED
  // compiled bundle (dist/std, jsDelivr-served at the std-v11 tag).
  // The pins live in `rut.lock` beside this file (machine-generated:
  // the scaffold wrote them; `rut install` re-pins after a dep edit —
  // the sha256 key is retired from manifest rows). Unused deps are
  // legal: host pkgs merge inert unless the program mounts their pkg,
  // and every source pkg compiles only as part of the closure — this
  // hello (ink only) runs clean with the full set declared.
  "name": "hello",
  "deps": {
    "ink": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle" },
    "pouch": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle" },
    "flow": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/flow.rutbundle" },
    "nmapset": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/nmapset.rutbundle" },
    "json": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/json.rutbundle" },
    "strbuild": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/strbuild.rutbundle" },
    "calc": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/calc.rutbundle" },
    "futures": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/futures.rutbundle" },
    "http": { "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/http.rutbundle" }
  }
}

// hello/rut.lock
// rut.lock — generated by `rut install`; commit it. Rows sorted by url;
// the sha256 is law at the mount door on every load.
{
  "format": "rutlock",
  "format_version": 1,
  "deps": [
    { "pkg": "calc",     "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/calc.rutbundle",     "sha256": "0ded688375f71dc4241096faf4ac07bd5154f765705145908589d911fef918d0" },
    { "pkg": "flow",     "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/flow.rutbundle",     "sha256": "48493535461a15bbe7bcdea881e221cce62354ee92651c527533241853a3c730" },
    { "pkg": "futures",  "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/futures.rutbundle",  "sha256": "a3b44897107b3a04aa605ad94f674dedd254755f0310448feb8d1c5102cfa89b" },
    { "pkg": "http",     "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/http.rutbundle",     "sha256": "3494e2554e369119fa460213c00b3384ab6318892d09cc236cdea359c5388677" },
    { "pkg": "ink",      "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle",      "sha256": "7e9e7f58582ae0a3cd5b4ae76a16b7051c0c79f9479edc34a3ab8261ee250205" },
    { "pkg": "json",     "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/json.rutbundle",     "sha256": "811e6f5b98ebb2816ea21782e42441183a1c5d262850567164540cc3d7801467" },
    { "pkg": "nmapset",  "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/nmapset.rutbundle",  "sha256": "8b9b62ef68994115db7a8e75bf410fd4ab3a6c0213733b71df1001b4db83a7b1" },
    { "pkg": "pouch",    "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/pouch.rutbundle",    "sha256": "249aba803d8a70f05952041f667b5897f4733257f00d5d7b73c6032f4ba70373" },
    { "pkg": "strbuild", "url": "https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/strbuild.rutbundle", "sha256": "1c152f28ff2d55b9dbd9868c2abe15c7116840d6a4cc8bcd4f2cdf520f848dfd" }
  ]
}

// hello/mod.rut
use ink::{ Logger };

entry fn main() {
    let log = Logger("hello");
    let name = "rut";
    log.info(f"hello, {name}!");
}

install

rut install                    # resolve the url deps of the working directory, write rut.lock
rut install app/               # resolve the url deps, write rut.lock
rut install app/ --locked      # CI: verify against rut.lock, write nothing

Resolves the closure’s url deps and pins them in rut.lock — the pin ledger beside the walk root’s rut.jsonc, one per root, committed (like Cargo.lock): it is what makes everyone’s build resolve the same bytes. The lane: collect every url row the closure declares (the walk’s own collection — a path dep’s url rows are collected with it, so the root’s lock pins the whole closure), fetch each cache-first and sequentially, mount-validate the whole graph against the computed pins (install never writes a lock over bytes that do not load), then write <dir>/rut.lock atomically. A .rutbundle argument is refused (exit 2): bundles are closed — there is nothing to install.

The lock is machine-generated and byte-deterministic — rows sorted by url, fixed field order (pkg/url/sha256), a header comment, a trailing newline — so the same closure renders the same bytes and the file diffs cleanly. The url is the identity (the fetch key; one url, one row); pkg is display-only (the first dep name that spelled the url). Parsing is JSONC-lenient like the manifest’s (comments and trailing commas legal — hand-edits load), and the value refusals are path-targeted (deps[1].sha256: must be 64 hex digits…). An empty closure still writes the empty-deps lock: the record that the closure resolved to nothing.

The streams: progress on stderr, summaries on stdout —

install: ink — downloading https://cdn.jsdelivr.net/gh/hpp2334/rut@std-v11/dist/std/ink.rutbundle
install: ink — downloaded (4193 bytes)
install: 1 url deps resolved — 1 downloaded, 0 cache hits (4193 bytes total)
rut.lock written: 1 rows (1 added, 0 changed, 0 dropped)

(a warm cache swaps the miss pair for one install: ink — cache hit (4193 bytes) line — no fake re-download flash; a re-run over an identical lock prints rut.lock unchanged (1 rows, no drift) and writes nothing).

--locked never writes and never evicts: it fetches the same closure and verifies every row against the existing lock — the CI gate.

--locked casebehavior
lock freshinstall: 1 url deps verified against rut.lock — 0 downloaded, 1 cache hits, 0 drift, exit 0
no lock, non-empty closurethe install recipe, exit 2: install: no rut.lock in <dir> — run `rut install` first
no lock, empty closurepasses lockless — a no-dep project needs no lock
a dep’s url has no lock rowthe + diff row, exit 2: + <url> (dep `X` has no rut.lock row)
fetched bytes break the lock’s pinthe ~ row, exit 2 — it names the url and BOTH hashes: ~ <url> (dep `X` pins <lock sha>, the fetched bytes hash to <served sha>)
a lock row no dep names anymorethe - row, exit 2: - <url> (no dep names this url anymore)

Any drift prints install: --locked found drift, rut.lock untouched: and the diff block; the lock file on disk is byte-for-byte what it was.

fmt

rut fmt src/            # rewrite in place
rut fmt --check main.rut

The canonical formatter. Behavior:

  • a directory argument is walked recursively; every .rut file is collected (sorted) and formatted;
  • style comes from the nearest ancestor rut.jsonc’s style block; no manifest → defaults (project structure);
  • .d.rut files are formatted in declaration mode;
  • a file that does not parse clean is refused (diagnostics listed, nonzero exit) — fmt never reformats on a parse error;
  • default mode rewrites in place and prints formatted: <path> per changed file;
  • --check writes nothing: it prints unformatted: <path> for each would-change file and exits nonzero, or fmt: N file(s) formatted when everything is clean.

pack

rut pack plugins/server -o server.rutbundle
# packed plugins/server -> server.rutbundle (18304 bytes)
rut pack plugins/server --strip
# packed plugins/server -> plugins/server.rutbundle (...) + symbol table
# plugins/server.rutsym (... bytes, keep PRIVATE)

Packs a module directory into a deterministic .rutbundle — same input, same bytes. Without -o, the output is written beside the input as <dir-name>.rutbundle. A lib pkg packs compiled (format_version 11): the root and every source dep ride as mod.rutc binaries (bodies + surface — the linking truth) under deps/<name>@<fp16>/ identity directories, host pkgs (and declared deps whose unit did not link) ride as declaration file sets, and the scope ledger’s rows spell the identities so any loader can rebase the binaries onto its own numbering. A root that produces no compiled program — a type = "host" pkg — is refused: pack a source pkg instead. A type = "host" pkg packs as a decl root (its .d.rut surface riding as source at the canonical mod.d.rut name, single-package), --strip refuses there (no symbols to strip), and run accepts either bundle directly — though running a host bundle refuses with intent: bind its rows from the embedder (module bundles).

--strip mangles every renameable name and strips the symbolication tables from the emitted binaries, writing the private symbol table at the sibling path <out-without-ext>.rutsym — the sidecar is never an entry inside the bundle. It needs a fully-compiled closure: a source group that could bind a compiled group’s surface is a pointed refusal. See Symbol stripping and .rutsym sidecars.

dump

rut dump main.rut

Prints the compiler’s view of one file: the == AST == section followed by == IR == (per-function typed register tables and op listings). Compilation is the same offered-world pipeline run uses, minus execution and verification. .d.rut inputs dump in declaration mode — useful for inspecting a host surface’s slots.

fetch

rut fetch app/            # CI: warm the cache while the network is up

Walks a module directory with the url-dep remote and discards the result — every deps url is fetched (or found in the cache) and the graph is then loaded and thrown away, so a later offline run hits only the cache. The load is the same law every load obeys: the walk root’s rut.lock must pin every collected url row, so rut fetch is the re-warm lane — install is the lane that writes the lock a fetch (and every run) travels with. A .rutbundle argument is refused (exit 2): bundles are closed — there is nothing to fetch. The cache and the eviction law are the same lane run/pack use:

itembehavior
cache root<project>/.rut/cache — project-local, hermetic; $RUT_CACHE_DIR overrides the root (CLI-side only — the walk never reads env). Entries named <sha256(url)>.rutbundle
cache-firsta hit never touches the network — offline reloads are the point
missGET (redirects on), non-2xx is a loud error, a size cap refuses without buffering, the write is atomic (tmp + rename)
poisoned entrythe pin is the loader’s law at the mount door — the pin’s source is the root’s rut.lock; when the door refuses, the CLI maps the url back to its cache path, deletes the entry, and exits 2 — the next run re-fetches and heals

The wire is rut-native’s http feature (default on) — a build with default-features = false (the wasm graphs) has no transport at all: a cache miss errors loudly instead of networking.

Declaration mode

The file extension selects the parser mode:

filemoderunfmtdump
*.rutimplementationruns mainformats implsAST + IR of the module
*.d.rutdeclarationrefused (exit 2)formats the surfacethe surface’s AST + IR

Exit codes

codemeaning
0success
1compile diagnostics; no binary emitted; binary decode or verify failure; VM boot failure; a trap at run; fmt refuses a file that does not parse; fmt --check found drift; pack or output-write failure
2usage errors (missing arguments); unreadable input file; run on a .d.rut; run on an input that is neither a module directory nor a .rutbundle; fmt finds no .rut files under a directory; a url dep the root’s rut.lock does not pin, or whose fetched bytes break the lock’s pin (the poisoned cache entry is evicted); install/fetch on a .rutbundle; install --locked drift, including the missing-lock refusal; install on a directory whose graph fails to mount against the computed pins; new onto an existing rut.jsonc/mod.rut/rut.lock, or an illegal package name

Diagnostics go to stderr; the success summaries (pack’s packed line, install/fetch’s resolved/verified lines and lock reports) go to stdout.

Notes

  • The CLI offers and binds on behalf of the program, but it never injects names the program did not declare: a program that never spells use ink:: gets no logger; one that never offers the async packages has no launcher and await stays cold-poll inline (core and the swappable packages).
  • The HTTP lane is native-only: the CLI build carries it, wasm builds do not.
  • run on a module directory is the deployment path for development; pack + run <bundle> is the shipping path — both run the identical contract (loading and the embed loop).

Glossary

The book’s vocabulary for the compilation model. Where a standard toolchain word’s intuition is ~90% right, rut uses the community’s word and documents only the delta — there are exactly two.

The vocabulary

termmeaning
deterministic reference modewhole-program compilation over a declared closure — byte-identical everywhere; the contract every other lane is measured against, not a fallback (The compilation model)
object filea package’s compiled binary (mod.rutc): bodies + surface — the linking truth (Module binary and verification)
archivethe published .rutbundle — objects and their symbol tables, shaded to the closure; uber-jar / Go .a semantics; the sole publication unit (Module bundles)
declaration entrythe generated surface text (mod.d.rut) a compiled group carries for humans and tooling — the editing truth; generated at pack, never hand-maintained
symbol tablethe archive’s scope ledger (rut.scopes): one row per linked module, spelling the content identity the loader relocates through (Module bundles)
templatesinstantiation-independent bodies: exported generic decls compiled once against #<param> placeholder rows and carried in the binary, so any consumer-spelled shape can materialize at the consumer
instantiatethe consumer-side materialization of the generics the consumer spelled — template substitution, ledger lookups, repr refolds; the only consumer-side codegen
linkscope resolution + relocation + merge — arithmetic only, never type-aware, never code-generating
load + relocatemounting a decoded archive into a run: its ids rebase onto the loader’s own numbering (dynamic relocation, PIE-style)
pre-instantiated bodiesthe ledger rows the pack closure already compiled — ≈ COMDAT-folded duplicates
auto-linked core / preludecore — offered and linked automatically unless overridden, like Go’s runtime (core and the swappable packages)
host bindingshost packages and their rows — the FFI surface (Embedding and native modules)
compilation sessionthe run’s internal compile state (RutRun) — an implementation detail, never user-facing vocabulary

Already community-standard, unchanged: pkg, manifest, [deps], rut.lock, install, fetch, url + sha256 pins, pack (Dependency kinds, The rut CLI).

Delta 1 — instantiation independence

The contract in plain words: the same generic substitution, spelled by any consumer, in any run, against any mount of the owner, yields the same body — one row program-wide, identity by owner. Consumer spelling picks shapes; it never changes bodies.

This is separate compilation for generics: a package publishes without knowing the shapes its consumers will spell, and still every shape links to exactly one body — a ledger hit when the owner’s own closure already compiled it, otherwise a substitution into the template the binary carries (Module bundles). There is no standard toolchain word for the property — the groundings are C++ template instantiation and COMDAT folding — so rut describes it instead of branding it: instantiation independence, the separate-compilation contract.

Delta 2 — surface validation at compile

A consumer compiles against an archive without its source: the consumer’s compile stage reads the object’s surface — exported names, signatures, types — the way rustc reads a dependency’s metadata. use heads, member sets, and types validate at consumer compile time; a missing member is a compile diagnostic, never a link or load surprise (The compiler pipeline).

Internal vocabulary

Engine internals — seeds, reseeding, the graph walk, dev tables — may appear in source comments and trace output. They are not part of the model, and the book avoids them.