snail-scheme
snail-scheme is a statically-typed Scheme successor, for building
applications, compiling to WebAssembly with garbage collection. Its compiler
is written in the language and compiles itself; programs run on Node and in
the browser.
What is here
- The language: S-expressions, hygienic macros and explicit types; records as mutable heap objects any number of names may share; capabilities passed as values, so a function can do only what it was handed; and one-shot suspension, from which exceptions, generators and tasks are built (the language).
- Libraries, all written in
snail-scheme: a prelude, files, processes and sockets, pages, document interfaces and canvas applications, WebGPU as a capability with rasterizing, Gaussian splatting and path tracing on top of it, and GPU tensor graphs with gradients (library reference). - Tools: one command,
snail-scheme, that builds and runs scripts, a language server with editor support for Zed and VS Code, and a formatter (development toolchain). - Runtimes: tasks scheduled in
snail-scheme, with Node and the browser completing what they wait on (runtimes). - Applications, in
src/apps/: Siegework, a colony game; Hearsay’s two prototypes; a path-traced glTF viewer; a Gaussian splat viewer; and a trainer that fits splats to photographs (tensors and training).
Where to start
- To learn the language, read
snail-schemein ten minutes, then the tutorials. - To find a library, start at the library reference, which lists every one and links its source.
- To build something, read getting started, then workspaces and builds and the application model.
- To work on the compiler, read the compiler architecture and bootstrap.
Try it in a browser with WebGPU
- Play Siegework: explore a seeded map, wire an energy network across it, and destroy three nests.
- Open the viewer and drop a
.glbon it, or pick a sample, to see it path traced (the path tracer). - Open Splats and drop a trained scene’s
.plyon it. - Play Hearsay: the rumor mill and the favor ledger.
The book describes what is implemented and marks proposals explicitly. Source lives in the repository, and GitHub issues track open work.
snail-scheme
snail-scheme is a statically-typed Scheme successor. It has S-expressions, hygienic
macros, explicit types, and capabilities passed as values. Records are mutable heap objects
that any number of names may share; primitive values stay unboxed, and the
collector reclaims what nothing reaches. Functions use the Fn type former
with the Unicode → separator.
A top-level definition is a value: its initializer runs at most once, on the first read, changes nothing, and every read shares the result. A function definition is shorthand for defining a lambda. Arrays have a fixed length and mutable elements.
This is one language, with no R7RS compatibility layer, call/cc or
dynamic-wind. The compiler emits WasmGC and compiles itself; a small Chez
adapter runs its source for the first bootstrap.
These chapters describe the language:
- Terms: programs, libraries, language forms and toolchain names.
- Types: scalars, data, typeclasses, foreign functions, linked files and dynamic values.
- Capabilities: capabilities as values, how
mainasks its target for them, and what a signature does not say. - Suspension: prompts, exceptions, generators and a
one-shot
resume. - Values: sharing, mutable records, closures, resources and their representation.
- Macros and generated libraries: hygienic expansion and explicit build-time producers.
- Notable omissions: what was left out, and why.
- References: influences and further reading.
Building programs covers applications, workspaces, builds, the toolchain and the compiler; the library reference lists every library; and proposed typed state is an API for review, not implemented functionality.
Terms
Programs and libraries
A program is a file of import forms followed by declarations and definitions.
Its root main starts runtime work. A top-level value’s initializer runs
when the value is first read, so importing a library runs nothing. A library
uses define-library with import,
export and begin sections, stored at a path that matches its name:
(sample geometry) lives in sample/geometry.sld under a search directory.
Import sets may use only, except, prefix and rename.
(import
(snail core base)
(snail core io))
(define (fibonacci (n I64)) (→ I64)
(if (< n 2) n (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
(define (main (out OutputPort)) (→ Unit)
(write-line out (show (fibonacci 30))))
A script’s imports resolve under the src/ of its workspace, the nearest folder above it that holds one, then the standard libraries’.
A library file may instead hold a generate-library recipe: a program whose
value is the library’s define-library form, as a Syntax from
(snail shell syntax). The compiler builds and runs it first:
(generate-library (sample table)
(import
(snail core base)
(snail shell syntax))
(library-syntax (list "sample" "table")
(list "squares")
(list (list "snail" "core" "base"))
(list (form "define" (list (SymbolSyntax "squares")
(form "list" (map (lambda (i) (IntegerSyntax (* i i))) (iota 6))))))))
The program writes the syntax as bytes that the compiler decodes, so no text
is printed or parsed in between, and a BytesSyntax reaches the compiler
as the bytes it holds. Construct syntax explicitly with (snail shell syntax).
Every generated form is located at the recipe.
A recipe names the files it reads relative to itself, with the forms any
library uses: (link-file "data/table.txt") declares a packaged resource,
and read-resource reads its bytes when the producer runs. A producer can emit
those bytes as a byte literal in its generated library.
tests/programs/src/sample/blob.sld demonstrates this flow.
Forms
| Form | Meaning |
|---|---|
(define name [(→ Type)] value) | Value definition. At top level the initializer runs at most once, on the first read (top-level values). |
(define (name (param type) ...) (→ Result) [header ...] body ...) | Typed function definition, shorthand for (define name (lambda ((param type) ...) (→ Result) [header ...] body ...)). Optional generic and constraint clauses precede the body. |
(lambda (param ...) body ...), (lambda ((param type) ...) (→ Result) [header ...] body ...) | Function with a fixed number of parameters. It takes a definition’s whole header, or annotates nothing and has its type inferred. |
(if test then [else]) | test is Bool; without else the result is Unit. |
(begin form ...) | A body: definitions and expressions in order. |
(let ((name value) ...) body ...), (let loop ((name value) ...) body ...) | Local bindings and loops. |
(match value (pattern body ...) ...) | Pattern matching, checked for exhaustiveness and unreachable clauses. |
(declare (name (param type) ...) (→ Result) [header ...]) | Bodyless method declaration in a typeclass, with the same header as a function definition. |
(ann expression type) | Static type annotation. |
(cache function) | A closure with the same signature and a private, unbounded result cache. |
(lru-cache capacity function) | The same wrapper with a least-recently-used entry limit. |
(Any expression) | Boxes an unrestricted value with its concrete type. |
(downcast Type boxed) | Returns Some of the payload if its type matches, or None. |
(record (Name param ...) ((field type) ...)) | Mutable heap record type. |
(new Name (field expression) ...) | Construct a record; every field exactly once, evaluated in written order. |
(enum (Name param ...) (Case [((field type) ...)]) ...) | Tagged sum. |
(type (Name param ...) type) | Transparent alias. |
(typeclass (Class param ...) (declare (method ...) ...) ...) | Class of types with methods. |
(instance (Class type ...) [(⊨ constraint ...)] (define ...) ...) | Instance. |
(make-prompt), (with-prompt prompt body handler), (suspend prompt value) | Functions, not forms: a prompt, the call that catches its suspensions, and a suspension (suspension). |
(extern name "module" "symbol" type) | Wasm import, its type asserted. |
(primitive name type) | An operation the backend implements, bound to the global prim:name. Accepted only in (snail core primitive). |
(expose name "symbol") | Exports a monomorphic top-level function to the host; its arguments and result must be unrestricted. |
(define-syntax name (syntax-rules (literal ...) (pattern template) ...)) | Hygienic macro. |
(snail core base) adds let*, letrec, cond, case, when, unless, and,
or, do, list, string and a variadic string-append as macros.
Bodies and scope
Library and program top levels see all of their definitions, so top-level functions may be mutually recursive. A local body is sequential: a definition is visible to the forms after it, and a local function is also visible to itself. Write mutually recursive helpers at the top level.
Functions have fixed arity. Where Scheme uses variadic procedures, snail-scheme
uses macros (list, string-append) or lists.
Cached functions
cache and lru-cache wrap ordinary functions, including lambdas. They preserve
all argument types and the result type; they work at any fixed
arity. The callback expression is evaluated once.
Each wrapper owns a fresh local cache that remains alive between calls.
Aliases of that wrapper share its
cache, while two evaluations of (cache f) have separate caches.
(define (make-lookup) (→ (Fn I64 → I64))
(cache (lambda (key) (* key key))))
(define (use-lookup) (→ I64)
(let ((lookup (lru-cache 128 (lambda (key) (* key key)))))
(+ (lookup 12) (lookup 12))))
A wrapper defined as a top-level value is made once, so the whole program shares its cache:
(define square (cache (lambda ((n I64)) (→ I64) (* n n))))
A wrapper does what its function does, on a miss: a hit skips the function’s body and so what it does. A function that logs each call logs once for each key when cached, which is what caching it asks for. A capability among the arguments is part of the key like any other. A call that suspends out of the function is not remembered: resumed, it answers its caller, and the next call with that key runs the function again.
Both names are builtins sharing one runtime implementation, since the language has no parameter packs to express every arity in a library. A generic factory states a known function shape, for example:
(define (memoize (f (Fn A → B))) (→ (Fn A → B)) (∀ (A B))
(cache f))
An unbounded cache retains successful results until its wrapper becomes
unreachable. An LRU cache holds at most capacity entries; a hit moves its entry
to the front, and insertion evicts the least recently used entry if needed.
Capacity zero returns the original function without caching; a negative capacity
panics when constructing the wrapper. Zero-argument functions use a single
cached result slot.
Every positional argument participates in the key. Integers, booleans, characters and fieldless enum cases compare by value; strings compare by content. Floating point keys compare their bits, so signed zeros differ and identical NaN bit patterns match. Other heap objects compare by identity. Mutating an object key does not invalidate its entry. Results are shared objects, so callers see mutations to a cached result.
Scalar and string hashes distribute entries into growing hash buckets; collisions always check complete key equality. WasmGC has no portable identity hash, so object components contribute a constant hash. Object-only keys can therefore require a linear bucket search. Mixed keys still benefit from scalar and string components. There is no hidden identity field added to user objects.
Raw Funcref host handles cannot be keys. Any other value may be a key or a
result, including functions, Any values, mutable records and arrays.
Cache only functions for which skipping the body is intended. A function may read and write mutable objects and captured state, so no signature proves that its answers stay the same. A result is stored only after a successful return. Reentrant calls can populate the same cache: the last successful completion for a key wins, and each call returns its own computed result. There is no in-progress entry or recursive-cycle guard. Wrapping a function does not redirect its original recursive references through the wrapper.
A local wrapper has one monomorphic callable type. Generic factory functions can create fresh wrappers for different concrete types; one wrapper is never shared across unrelated type instantiations.
Cache performance
A focused V8 benchmark measures 50,000 calls over 128 scalar keys, including each wrapper’s creation and initial misses. On an Intel Core Ultra 7 270K Plus, two processes with 21 alternating-order samples each measured:
| Workload | Plain function | cache | lru-cache 128 |
|---|---|---|---|
| 64-step integer calculation, repeated keys | 9.04–9.50 ms | 0.297–0.301 ms | 0.384–0.386 ms |
| One multiplication, repeated keys | 0.142–0.143 ms | 0.274–0.276 ms | — |
| One multiplication, 20,000 distinct keys | 0.0571–0.0573 ms | 0.427–0.428 ms | — |
Caching helps when avoided work exceeds lookup and storage costs. Here the
repeated expensive calculation is about 30–32 times faster; trivial repeated
work costs about 1.9 times as much, and all-miss trivial work costs about 7.5 times
as much. These are scalar-key microbenchmarks, not compiler-wide or object-key
performance claims. The LRU capacity fits every key, so eviction pressure is not
measured. Forced GC runs outside timing, and eventual collection of discarded
tables is not measured. Raw samples and artifact hashes
include an independent-process confirmation. They were taken with one
linked module from snailc, since removed:
./snail-scheme run . snailc compile -o build/function-cache.wasm tests/benchmarks/function-cache.sld
taskset -c 2 node --no-warnings --expose-gc scripts/benchmark-cache.mjs build/function-cache.wasm
A release build makes such a module again, optimized as well:
./snail-scheme build --target node --release FILE writes build/PATH/NAME.wasm.
Proposed surface design
Design for review, not implemented. Everyday programs should be
comfortable to read and write without expertise in Lisp conventions.
Uniform S-expressions are useful for structured syntax and macros, but
they do not require every source operation to use the same punctuation.
Familiar projection syntax such as a.b.c should be considered on its
own merits, alongside bindings, calls, signatures and callback bodies.
The implemented function type is Fn, with →
separating the result. Named functions use typed parameter pairs and
inline result, generic and constraint clauses. Definitions continue to use
define.
Direct field selection is (● receiver label ...): each nominal record type
supplies its stored fields, and paths follow heap references.
(set! (● receiver label ...) value) writes the path’s final field; set!
is a form, so it takes a field path where it is written and is not a
value to pass.
Every field is mutable. Computed getters are ordinary functions.
Direct-style suspension remains available: the compiler
turns the remaining computation into a one-shot callable. No type marks a
call that may suspend, and ! retains its mutation convention. Dot
notation need not expose a runtime offset.
Evaluate candidates by rewriting complete examples: the tour’s counter,
a nested update in an application, a higher-order collection operation,
and a with-prompt. Show the existing and proposed code side by side.
A useful syntax makes the receiver, arguments, binding scope and mutation
visible, works with multiline formatting, and gives useful diagnostics
for incomplete edits. Reducing the number of parentheses alone is not
enough to establish those properties.
Additional surface syntax must produce located, hygienic structure that the existing expansion and checking pipeline understands. A projection can remain unresolved until its receiver’s type and writable-field evidence are known. Parsing it must preserve evaluation order and evaluate the receiver once. Before adopting dots, specify their interaction with existing identifiers, numeric literals, quoted data and Scheme dotted lists. Before adopting infix or brace syntax, specify precedence, scope and macro matching. These are options for review, not selected changes. The design should preserve one typed language and one compiler pipeline, with editor, formatter, bootstrap and macro support developed together.
Sweet-expression reader
Candidate for review, not implemented. Evaluate SRFI 110 sweet-expressions as the preferred source notation, selected by a language-reader directive at the start of every file. A traditional S-expression reader is also selectable. It combines indentation, call notation and SRFI 105 curly infix. It accepts conventionally formatted S-expressions, but is not a meaning-preserving superset of every traditional source file:
| Input at the start of a line | Traditional reader | Sweet reader |
|---|---|---|
f(x) | Two datums: f and (x) | One datum: (f x) |
(f) (g) | Two datums | One datum: ((f) (g)) |
These distinctions are documented in the SRFI’s compatibility section.
The directive selects parsing; parentheses can still be used within sweet
code. Backslash grouping/splitting is available, but explicit lists can
keep it out of routine examples. Curly infix does not supply conventional
operator precedence: write {a + {b * c}} to state the grouping.
With the existing definition form, the same callable could be written as:
#lang snail/sweet
define square(n(I64)) (→ I64)
{n * n}
Its expansion is the parenthesized definition in function signatures. Sweet syntax only changes how forms are written. Dot projection and typed locators also require their own rules; adopting this reader does not itself specify field access.
New-file templates should choose sweet syntax, while every source file
declares its language reader. The header spellings #lang snail/sweet and
#lang snail/sexp are candidates, not implemented syntax. Parse that header
before invoking either reader. The traditional choice preserves exact
S-expression interpretation for generated code and imported libraries.
Both readers produce the same located syntax and share expansion,
checking and lowering. Selection is local to the file and does not
propagate into imports. A stream without a source-file header must have
its reader supplied explicitly by its caller. Supporting arbitrary
user-provided readers is separate from providing these two built-in choices.
During migration, compare both readers’ output across the source tree and
add explicit headers or reformat files whose meaning changes. Do not guess
the reader from whether the first expression uses parentheses. Accepting
parenthesized expressions inside sweet source does not replace a true
traditional mode: generated (f) (g) must still be two forms when that
reader is selected. The source-file header selects one reader for that
file; support for SRFI parsing directives in data readers is a separate
conformance obligation, not an implicit replacement for the header.
Implement the source reader against the same located syntax consumed by expansion. Preserve source locations and macro hygiene, and keep generated binary syntax independent of textual notation. Reader equivalence tests should compare structures while accounting for their different locations, then execute equivalent programs. Include blank lines, indentation, comments, quote forms and advanced markers. The formatter and editor must agree with the compiler on mode and indentation; changing source syntax must not silently change a program’s data-reading protocol.
Chez reads the compiler’s source directly during stage 0. Adding sweet
syntax to snail-scheme’s reader alone does not let Chez load a converted compiler.
Bootstrap-loaded sources need an explicit, tested header/reader adapter
or preprocessing solution with source mapping before source migration.
Claim SRFI 110 conformance only when its required reader behavior and APIs
are covered; an initial source-reader implementation must state its scope.
Dot projection as a reader extension
Candidate syntax, not implemented. Reuse the neoteric reader’s
postfix-to-form approach for field selection. SRFI 105 specifies postfix
calls and a bracket hook, a[b] becoming ($bracket-apply$ a b). It does
not give a.b field-access semantics; its {a . b} example produces an
improper form headed by $nfx$. Dot projection therefore needs a distinct
snail-scheme extension, rather than treating a standalone dot as an ordinary
infix operator. SRFI 105
The proposed structural translation is schematically:
a.b.c => (project a b c)
project stands for a located projection form whose actual name is still
open. a is an evaluated expression; b and c are field labels, not
variable reads. The traditional reader must admit an explicit form with
the same semantics so generated code can express it without dot syntax.
The reader-created form must have a defined hygienic binding; a local
variable must not accidentally change what punctuation means.
The translation should preserve the existing nominal projection semantics:
read (● object field ...), or use that projection in set!.
Each step follows one object reference. Field lookup is resolved during
checking, and every stored field is mutable. Computed getters are ordinary
functions and do not become writable by punctuation.
Projection should compose left to right with calls, so make().b.c has
one receiver evaluation. Its lexical rules must distinguish decimal
literals, the standalone dotted-list marker, ellipses and escaped names
that contain dots. Under the traditional reader a dotted identifier keeps
its existing meaning. Compatibility tests must cover these boundaries;
the extension must not split arbitrary identifier strings after parsing.
Toolchain terms
These names distinguish source organization, compilation and execution.
Workspaces, script builds and snail-scheme lsp are implemented.
The application process and persistence workflow
remains proposed.
| Term | Meaning |
|---|---|
| Workspace | A folder that holds src/, where every library lives and every import resolves. |
| Script | A source file in a workspace, built for a platform named on the command line. Its build produces one output directory, which may contain multiple files. |
| Build attempt | One invocation of a script’s build, with diagnostics and a success/failure result. |
| Application process | An OS process running a program. A browser frontend is a client of a server process. |
| Runtime | The scheduler and host services executing a program’s tasks. It is distinct from compilation and the OS process. |
| Host | The platform environment, such as Node or a browser, providing APIs to the runtime. |
| Worker | A separate execution agent used for CPU work, such as a Node worker thread; it is not a browser Service Worker or a snail-scheme task. |
| Working state | In-memory values used by the running application, including changes not yet saved. |
| Persisted data | The application’s chosen representation committed to storage independently of the running code. It need not encode every transient resource or cache. |
Incremental compilation reuses compiler work. Restart starts a fresh application process; the application can reconstruct working state from persisted data. Hot reload (also called live reload) would replace running code while preserving application data under a stated contract; it is not implemented. The proposal uses durable typed tables and disposable cached views, recomputed on demand after ordinary startup. Recompiling does not by itself preserve application state, and moving execution into a worker does not supply a preservation contract.
Types
Types
Scalars are U8, I32, I64, F32, F64, Bool, Char and Unit.
Any explicitly packages an eligible value; downcast attempts to recover its
exact type (explicit Any).
String is a sequence of Unicode scalars. (Array T) has a fixed runtime
length and mutable elements. Besides it there is only (ConstantArray T), a
table of scalars nothing can write (below); there is no
MutArray, type-level lengths or dependent types.
Primitives occupy unboxed slots; records, enum cases and nested arrays occupy
reference slots. Bytes is an alias for (Array U8), stored packed.
(array) constructs an empty array; make-array, array-generate and
list->array construct fixed-length arrays. array-ref reads an element
and array-set! replaces it. Every alias observes writes. Indices and copy
ranges are checked at their full integer width before conversion to Wasm indices.
There are no push, pop, resize or capacity operations.
array-copy, subarray and array-append create fresh mutable arrays and
copy their elements shallowly. array-set is the copying replacement operation;
array-copy! overwrites a destination range and supports overlap. Iteration
visits the array’s fixed extent; callbacks may change its elements.
String/array conversions copy character storage in both directions, so changing
the array cannot change the string. Use lists to accumulate values of an
unknown count, then convert once when indexed access is needed.
A byte array literal, #u8(137 80 78 71), embeds exactly those bytes. Use
linked files for external assets. A library producer may read a
linked resource and emit a byte literal when embedding is appropriate; the
reader performs no file inclusion.
A closure has type (Fn Param ... → Result). This is a built-in type
former, with the same spelling in arguments, fields, collections and
results; there is no dyn, impl, FnMut or callable-class hierarchy,
and no annotation for what calling it does: that is in what the function
was made with (capabilities).
A typed function header carries its type where it is defined. Every parameter has a
mandatory (name Type) annotation, and the header must state its result
with (→ Result). Optional generic-variable and constraint clauses follow
the parameter list at the start of the definition, before its body:
(define (map-with (function (Fn A → B)) (values (List A)))
(→ (List B))
(∀ (A B))
(map function values))
(define (sum (zero T) (values (List T)))
(→ T)
(∀ (T))
(⊨ (Num T))
(fold-left + zero values))
A lambda takes the same header, and (define (name parameter ...) clause ... body ...) is shorthand for defining one:
;; A lambda takes a function definition's header, and a definition of a
;; typed lambda is that function definition.
(define double (lambda ((n I64)) (→ I64) (* n 2)))
(define identity (lambda ((value T)) (→ T) (∀ (T)) value))
(define report
(lambda ((out OutputPort) (label String) (n I64)) (→ Unit)
(write-line out (string-append label " " (show n)))))
(define (apply-twice (f (Fn I64 → I64)) (n I64)) (→ I64)
(f (f n)))
A lambda either writes the whole header, every parameter as (name Type)
and (→ Result), or annotates nothing and has its type inferred from its
use.
A value definition can carry a type in the same header position, for
example (define zero (→ I64) 0).
Class methods use declare with the same typed function header and no
body, for example (declare (describe (value T)) (→ String)). A colon
signature is not a language form. Type-level callable signatures use the Unicode →;
universal quantification and requirements use ∀ and ⊨. These are the only
spellings: ->, All and requires are not aliases.
Integer literals check against any integer or float type and are
range-checked; float literals check against F32 or F64. A literal whose
type nothing determines defaults to I64 or F64. Numeric values never
change numeric type implicitly: use i64->i32, i32->f64 and the other
conversions. Crossing an Any boundary checks the payload’s type; it
does not change that type. Integer arithmetic wraps.
Local bindings remain monomorphic. Put explicit quantifiers on reusable generic functions. A library is checked before its importers, so callers do not decide its exported definitions’ types.
Constant arrays
(constant-array TYPE (VALUE ...)) is a table of literals of a scalar type,
U8, I32, I64, Bool or Char, each checked against it
where it is written. Its type is (ConstantArray TYPE), which has no setter,
so the table is built once in its module, when a use first reaches it, and
every use shares it. constant-array-ref and constant-array-length read
it as array-ref and array-length read an array, and
constant-array->array copies it into an array of its own.
(define powers (→ (ConstantArray I32)) (constant-array I32 (1 10 100 1000)))
(constant-array-ref powers 2) ; 100
A table is shared as any top-level value is, and
reading it allocates nothing. A table is a data segment of its elements, so it may be as large as
its data. A float table is a table of the floats’ bits, an I64 table read
through bits->f64, since only the assembler knows a float literal’s bits. The program
tests/programs/constant-arrays.sld exercises each element type.
Top-level values
A top-level (define name value) is a cached thunk. Its initializer runs at
most once in a program, the first time something reads name, and every
read shares the result: a record or an array defined this way is one object,
and writes to it are seen by every reader. Types, macros, classes, imports
and exports remain declarations, and a program starts by calling its root
main; importing or linking a library runs nothing.
;; A value's initializer runs at most once, on the first read, and every
;; read shares the result.
(define counter (new Counter (value 0)))
(define (tick) (→ I64)
(set! (● counter value) (+ 1 (● counter value)))
(● counter value))
;; Values are read in expression order, whatever their source order.
(define total (→ I64) (+ later later))
(define later (tick))
(define unused (→ I64) (panic "an unused initializer ran"))
;; A value may be a function: this one keeps the results of its calls.
(define square (cache (lambda ((n I64)) (→ I64) (begin (tick) (* n n)))))
- No capability. An initializer takes nothing, so it holds no capability and reaches nothing of the host’s. It may read and write mutable objects it can name, so a value computed from one depends on when it is first read. An initializer that suspends keeps nothing, and runs again on the next read.
- Order. Values are read in the order expressions reach them, whatever
their order in the source, and one that nothing reads never runs. An
initializer that reads its own value, directly or through another, panics
with
initialization cycle. - One type. A value is not generic, since it is one object. What its
initializer leaves open, as the element type of
(define empty (Nil)), the uses in its library decide together; when they decide nothing, state it with(→ Type). Write a generic one as a function of no arguments,(define (empty) (→ (List A)) (∀ (A)) (Nil)), which makes a fresh value at each call. - Functions. A definition whose initializer is a lambda is a function:
it is code, with nothing to cache, and may be generic, recursive and
exposed to the host. Any other initializer makes a value, even when the
value is a function, as
squareabove is; calling it reads the value first.
To have a fresh object at each use, write a function that constructs one. Application state that must survive a restart still belongs in an explicit Save.
Data
(record (Vec3 T)
((x T)
(y T)
(z T)))
(enum Shape
(Circle ((radius F64)))
(Polygon ((points (List (Vec3 F64)))))
(Empty))
Every record and every enum case with fields is a heap object. Its fields
are mutable by default; there is no per-field mutation annotation. A record
Name defines its constructor and pure Name-field-set operations, which
produce shallow replacement records. It generates no field getters or mutable
setter functions.
Construct a record with new, naming every field exactly once:
(new Vec3 (z 3.0) (x 1.0) (y 2.0))
Fields may appear in any order. Initializers run once each, from left to right as written; their names select the destination slots. Unknown, repeated and missing fields are compile errors. Field types and the expected record type guide inference, including generic records and callback fields. There are no defaults or spreads. A visible type alias does not grant access to a hidden constructor.
Record constructors are used only through new. Use an ordinary function or
lambda for a factory, such as (lambda (x y) (new Point (x x) (y y))).
Record patterns remain positional: (match point ((Point x y) ...)).
Function arguments remain positional; new does not add keyword arguments
to Fn or change its calling convention.
Read record fields by path: (● segment from x). Each step follows an
ordinary object reference. Reads are pure. (set! (● segment from x) 3)
writes the resolved slot, evaluating the receiver and incoming value once.
There are no field typeclasses, computed property overloads,
or borrowed receiver types.
Enum cases are constructors, not types, and are always applied: (Empty).
Use match to select an enum case and bind its fields. There are no generated
case getters or mutable setters. A field path requires a nominal record receiver;
for mutable enum payloads, store a record in the case and access its fields after
matching.
A field read shares the value the field holds; see values.
(record Point
((x I64)
(y I64)))
(record Segment
((from Point)
(to Point)
(label String)))
(record Tag
((label String)
(weight I64)))
(define (describe (segment Segment)) (→ String)
(string-append (● segment label)
": "
(show (● segment from x))
" to "
(show (● segment to x))))
;; A generic nominal record still identifies the slot being read.
(define (labelled (record (Pair T String))) (→ String) (∀ (T))
(string-append "[" (● record second) "]"))
;; Computation uses an ordinary function; projection always means storage.
(record Circle
((radius I64)))
(define (diameter (circle Circle)) (→ I64)
(* 2 (● circle radius)))
(define (main (out OutputPort)) (→ Unit)
Patterns are _, variables, literals (numbers, characters, strings,
booleans) and constructor patterns, nested freely. (List T) is an ordinary
enum with cases Nil and Cons.
Typeclasses
A typeclass declares methods over its parameters; instances may be generic and may require other instances:
(typeclass (Describe T)
(declare (describe (value T)) (→ String)))
(instance (Describe (List T))
(⊨ (Describe T))
(define describe
(lambda (items) (string-join (map describe items) ", "))))
The checker chooses each instance when it checks a use and records that choice; monomorphization copies the chosen method for each type, so no dictionary exists at run time. Instance heads must not overlap. Classes have no superclasses: a signature lists every class it needs. Unbound names in an instance head are its type variables.
Every class parameter is a type, and all of them together choose the instance. A class has no associated types: a result type that depends on the instance is a further class parameter.
An instance’s requirements are solved where its head matches. A requirement
that leads back to its own goal, or a chain that keeps growing, is refused
as non-terminating; a requirement at a smaller type, as (Describe T) for
(Describe (List T)), is ordinary.
Arithmetic and comparison are the classes Num, Ord, Integral and
Fractional; Show converts values to text. Each takes one type, as in
(Num T).
Repr is a class with one type parameter: (Repr T) supplies
(repr value) → String. (snail core io)’s write prints that
representation to an OutputPort. Records and enums can generate instances
with (deriving Repr); see ports.
What a call may do
A function’s type does not say. A function reaches the host only through
a capability it holds, and suspends only to a prompt it can name:
capabilities covers the first, and what a signature
leaves out, and suspension prompts and their one-shot
resume.
Functions
A closure may capture any value, including mutable records, and may be called any number of times.
(define (twice (function (Fn I64 → I64)) (value I64)) (→ I64)
(function (function value)))
A with-prompt’s resume is an Fn too, which may be stored like any
other; the frames it holds run at most once
(resuming once).
Foreign functions
extern declares a foreign function; the declaration is the boundary’s
unsafe assumption.
A foreign call may take a final String or Bytes argument. The compiler
copies it into the runtime’s staging buffer just before the call. A String
arrives as its Unicode scalar count, with four bytes per scalar in staging.
Bytes arrive as an i32 address: a little-endian u32 length followed by
that many packed bytes. The host reads the current memory buffer and copies
any bytes it retains before returning or awaiting; later calls reuse staging.
Imports are leaves and must not call back into snail-scheme while reading staging.
An exposed function passes scalars directly and managed values as opaque engine
references. JavaScript can retain those references and pass them to synchronous
Wasm constructors/projectors, but cannot inspect their fields or substitute a
JavaScript object, string or typed array. Exposed String and Bytes are opaque
managed references; the staging convention above applies to calls into foreign imports.
Affine values, including records that contain them, cannot cross this unrestricted
boundary. Exposed signatures remain monomorphic; a parameter whose type the
target provides is a capability the build supplies, and the rest are the host’s.
A function export may infer its concrete signature, and then asks its
target for nothing; its type variables still generalize, so an unannotated
generic identity function cannot be exposed.
The host must respect the declared snail-scheme types: Wasm representation checks do not
prove nominal identity or permit treating a String as an Array Char.
An exposed (Option Any) crosses as null for None or the opaque Any
payload for Some. The wrapper converts at the boundary; internal Options
keep their normal enum representation. Plain Any remains non-nullable.
This exception applies only to exposed parameters/results; a host import
returning (Option Any) still expects its ordinary enum. A host builds no
managed value for a typed host operation: its imports take and answer
scalars, and the library builds the result from them, in the waiting task’s
own call (the native boundary).
A task’s capabilities are values its saved frames hold, so nothing about
them crosses the host. See
waiting on the host.
unsafe-cast is unchecked: it turns a Funcref, a
function another module exports, into a function of whatever type the
context expects ((snail shell wasm)). The engine verifies its WebAssembly
representation; the caller must establish its snail-scheme type contract.
Linked files
(snail shell resource) ties a file to a library as one of its dependencies
instead of embedding it, as Python’s importlib.resources addresses a
package’s data, and the library reads it when it needs it:
(import
(snail core base)
(only (snail shell task) tasks)
(snail shell resource))
(define (hero) (→ Resource) (link-file "art/hero.png"))
(define (hero-bytes (resources Resources)) (→ Bytes)
(read-resource resources (hero)))
- Found beside the library. The path is relative to the file the form is
written in, or the
generate-libraryrecipe’s directory for a producer’s own forms, and may not leave its directory:.and..are resolved, and an absolute path, an empty name or a path that climbs out is an error. A file that is missing fails the build with the library and the path. - Shipped by content. The build places the file as an object of the
program’s store, at
STORE/sha256/AB/DIGEST, where DIGEST is the SHA-256 of its bytes in hex and AB its first two digits, in every build that produces one. A program’s store isstore/beside its module. The name is never a path or a library’s: libraries that link the same bytes ship one object, an object is written once and never rewritten, and a file’s name changes exactly when its bytes do. The module itself records what it links:link-filebecomes a call to an import fromsnail.runtime.linknamed for the digest, which answers the file’s handle. Editing a linked file therefore compiles again the library that links it, and its importers, whose modules name the new digest. - A handle, not the bytes.
link-fileevaluates to aResource, which names a file and nothing more. The type is exported without its constructor, so a program cannot make one from a string: holding aResourceis evidence that its file ships.(read-resource resources r)returns the file’sBytes, and(read-resources resources (list a b))the bytes of each, read together: every read starts before the task waits for any. Both take aResources, which every target provides, on Node and in the browser. It is notFs: a page has no filesystem, and a program with none still reads its own files.
A file is read when the program asks for it. A host reads nothing a
module links when it instantiates the module. read-resource waits for the
host as a task does (through-host in (snail shell task)), so it runs
in a task. The first read of a file reads it, Node from
the payload’s directory and the browser by fetching beside the
page’s module, and later reads of it from the same module return the same
bytes. A file the program never reads is never fetched, so a library may link
far more than any one program uses. A file that cannot be read traps the task
that reads it. The bytes under a digest never change, so a host keeps what it
has read by digest: a module linked again reads a file it still links without
fetching it, and an edited file, under its new digest, is read anew. For the
same reason a server may let a browser cache the store for good, as the
development server does.
Explicit Any
(Any value) boxes a value with its concrete type identity. (downcast T boxed)
returns (Option T): Some holds the recovered value, and None reports a
mismatch. Both evaluate their input exactly once. Downcasting does not panic.
Ordinary checking never inserts a conversion:
arguments, results, branches and annotations must agree on their types.
(define (read-count (boxed Any)) (→ I64)
(match (downcast I64 boxed)
((Some count) count)
((None) 0)))
(define (example) (→ I64)
(read-count (Any 42)))
Boxing preserves the exact input type. (Any (Any 42)) holds an Any, whereas
(Any 42) holds an I64. Downcasting never converts numbers, container elements,
or function signatures. There are no type-convert, try-convert, type-test,
dyn-cast, dynamic instance dispatch, or (snail core dynamic) APIs.
A closure may be boxed like any other value: its type identity is its parameters’ and its result’s.
The type identity includes nominal names, arguments, fields, cases, and nested function signatures. Changed schemas receive changed identities across separately linked modules, even if their Wasm layouts match. Downcast also checks the Wasm representation before reading the payload. Type identities are currently 32-bit hashes; they are not collision-free structural proofs.
Capabilities
What a function may do to the world outside the program is in what it is handed. A function reaches nothing of the host’s unless one of its arguments lets it: an output port, the file system, a clock, a device. Such a value is a capability, and code that was handed none can reach none.
There are no effect declarations, no handlers and no effect rows: a function’s type says what it takes and what it returns, and nothing about what calling it does. What a program does to the world it does through ordinary values, passed as ordinary arguments, and a program that wants a different world, a port that keeps what is written or a clock that stands still, makes a different value. Suspension, the one way a computation stops short of its result, is had the same way: a function suspends to a prompt it can name.
Every example is part of a program under tests/programs/, which
make test runs, and the output shown is that program’s. Run one with
./snail-scheme run --target node tests/programs/ports.sld
What a signature does not say
Changing a value is not a capability. Every field of every record can be written, and every element of an array, by whoever holds it:
(set! (● record field) value)
(array-set! items index value)
So a signature says what of the host a function can reach, and not whether
it changes the values it is handed: that a function leaves its arguments
as they were is a convention, which a name ending in ! breaks out loud
(values). Two things follow.
- A capability that is a record is no exception. A function handed an
OutputPortcan write its field, and so change what the port does for everyone who holds it. Code that minds hands over a port it made for the purpose. - A top-level value that is a mutable record is state every importer can change. A top-level value’s initializer runs once, whenever the value is first read, so what it computes from such a record depends on when that is.
A type leaves out the rest of what a call may do as well: any function may
panic, loop forever, or stop at a suspend.
Capabilities
A capability is a value
(snail core io)’s output port is a record of the one function that
writes it, and write-line takes the port it writes to:
(record OutputPort
((write-string (Fn String → Unit))))
(define (write-line (out OutputPort) (text String)) (→ Unit)
((● out write-string) (string-append text "\n")))
(● out write-string) is the port’s field, so ((● out write-string) text) calls the port’s own function, and write-line is an ordinary
function built on it. Nothing stands between a caller and a capability’s
operations but the record: an operation is declared once, as a field.
A function that should print takes an OutputPort. One that takes none
cannot print, whatever it calls, unless something it is given can. A
capability is kept in a record, captured by a closure, handed to a task
and passed down like any other value.
The standard libraries’ capabilities:
| Capability | Library | What holding one allows |
|---|---|---|
Host | (snail core io) | making any of the host’s capabilities |
Arguments, ProcessEnvironment | (snail core io) | reading what the program was started with |
OutputPort, InputPort | (snail core io) | writing text; reading it |
Fs | (snail core io) | the host’s file system |
Clock | (snail core io) | the monotonic clock |
Resources | (snail shell resource) | reading the files a program links |
Wasm | (snail shell wasm) | compiling and linking modules |
Files | (snail shell async-files) | whole-file reads that wait as a task |
Processes, Signals | (snail shell process) | child processes; termination signals |
Tcp, Udp | (snail shell socket) | sockets |
Web | (snail shell web) | the files at URLs, a part at a time |
Events, PageStorage | (snail shell page) | a page’s input; its saved state |
Gpu | (snail shell gpu) | the WebGPU device |
Dom | (snail shell dom) | a document |
Fetch | (snail shell fetch) | requests to a server |
FilePicker | (snail shell files) | the files a user chooses |
Each library decides what its capability is. Most are records of their
operations, each a function, so that another implementation is another
record. Fs holds nothing: it is the host’s file system whole, and having
one is the permission.
Making one’s own
A program makes a capability as it makes any record. A port that keeps
what is written, and one that reads a text
(tests/programs/ports.sld):
;; A port that reads `text`, a character at a time.
(define (from-text (text String)) (→ InputPort)
(let ((position (new Cursor (index 0))))
(new InputPort
(read-char (lambda ()
(let ((index (● position index)))
(if (= index (string-length text))
(None)
(begin
(set! (● position index) (+ index 1))
(Some (string-ref text index))))))))))
;; What `action` writes to the port it is given.
(define (capture (action (Fn OutputPort → Unit))) (→ String)
(let ((chunks (new Output (reversed (Nil)))))
(action (new OutputPort
(write-string
(lambda (text) (set! (● chunks reversed) (Cons text (● chunks reversed)))))))
(string-concatenate (reverse (● chunks reversed)))))
So a test double is a value the test makes and passes: a Clock that
answers a fixed time, a Tcp whose connections are buffers
(tests/programs/tcp-handler.sld), the Gpu of
(snail shell gpu record), which records each command instead of running
it, or the Dom of (snail shell dom memory), a document in memory. Two
ports compose into one that writes both; a port over another adds a
prefix. None of this needs the language’s help.
main asks its target
A program’s entry is its main, and the parameters of main are what the
program asks for:
(define (main (out OutputPort) (fs Fs)) (→ Unit)
(write-line out (read-file fs "greeting.txt")))
Each build names a target, --target node or --target browser, and a
target is a library, (snail target node) for one. A target provides
a type by exporting a function of no parameters that answers it:
(define (provide-output-port) (→ OutputPort)
(standard-output root))
The build calls main with what the providers of its parameters’ types
answer, whatever the parameters’ names or order. A parameter whose type
the target does not provide is a build error naming it
(tests/programs/error-main-arguments.sld), so a program that asks for
Tcp fails to build for browser instead of trapping when it connects.
A program names each thing it needs, and gets nothing it did not name.
| Target | Provides |
|---|---|
| both | Host, Arguments, ProcessEnvironment, OutputPort, Clock, Resources, Wasm |
node | InputPort, Fs, Files, Processes, Signals, Tcp, Udp, Web |
browser | Events, PageStorage, Gpu, Dom, Fetch, FilePicker |
An exposed function of the program asks the same way: each parameter whose
type the target provides is supplied, and the rest are the host’s
arguments (tests/host-boundary/main.sld). Only a signature asks: an
exposed function whose types are inferred is called with the host’s
arguments alone. A generate-library recipe that needs capabilities is a
lambda over them, and its producer’s main asks for those
(macros).
Host
A Host is the ability to make the host’s capabilities. Every function
that makes one takes it:
(standard-output host) ; OutputPort
(host-fs host) ; Fs
(host-gpu host) ; Gpu
(page-dom host events) ; Dom
A target holds the one Host there is and makes what it provides from
it. Code that was handed neither a Host nor something made from one
reaches nothing of the host’s, so whether a function can acquire a
capability it was not given is also in its parameters.
A main may ask for the Host itself, to make a capability later or not
at all. A program on Node makes its Gpu this way, so one that draws
nothing links no device
(scripts):
(define (main (host Host) (out OutputPort)) (→ Unit)
(let ((gpu (host-gpu host)))
...))
What the host itself is trusted with
The host’s own capabilities answer by calling it through extern imports.
An extern’s type is its library author’s claim, trusted as written, and a
library keeps its externs behind its capability: the file externs of
(snail core io) are reached only through functions that take an Fs,
and an Fs is made only from a Host. One function makes that authority
from nothing, unsafe-host, and is named for it: a target calls it, and
nothing else should. Nothing stops a library from declaring an extern of
its own; that a library takes what it uses as a parameter is what a reader
checks, by reading its imports and searching for unsafe-host and
extern.
Suspension
A computation can stop short of its result: an error ends it, a generator
hands over a value and waits to be asked for the next, a task waits for a
timer. snail-scheme has one mechanism for all three, of three functions
in (snail core base):
(make-prompt) ; (Prompt S R)
(with-prompt prompt body handler) ; A
(suspend prompt value) ; R
(with-prompt prompt body handler) calls body, a function of no
arguments, and answers its value. If the body, or anything it calls,
however deep, calls (suspend prompt value), the body stops there, and the
call answers (handler value resume) instead. resume is the rest of the
body: (resume answer) goes on from the suspend, whose value is
answer, to the body’s end, and answers the body’s value.
A Prompt S R is what ties the two together: a suspension carries an S
out and is resumed with an R. Nothing between the suspend and its
with-prompt takes part: no function on the way says in its type that it
may be suspended, takes anything for it, or is written differently.
Every example is part of a program under tests/programs/, which
make test runs, and the output shown is that program’s.
Stopping
Exceptions
A handler need not call resume. One that never does is an exception
handler (tests/programs/prompts.sld):
;; A prompt whose answer is Never: a suspension to it never comes back.
(define failing (→ (Prompt String Never)) (make-prompt))
(define (fail (why String)) (→ A) (∀ (A))
(absurd (suspend failing why)))
(define (digit (c Char)) (→ I64)
(if (char-numeric? c)
(- (char->integer c) (char->integer #\0))
(fail (string-append "not a digit: " (make-string 1 c)))))
(define (number (text String)) (→ I64)
(fold-left (lambda (value c) (+ (* value 10) (digit c))) 0 (string->list text)))
;; `text` as a number, or `default`, after saying why not.
(define (parse-or (out OutputPort) (default I64) (text String)) (→ I64)
(with-prompt failing
(lambda () (number text))
(lambda (why resume)
(write-line out why)
default)))
(write-line out (show (parse-or out 0 "123")))
(write-line out (show (parse-or out 0 "12x")))
123
not a digit: x
0
The handler’s value is the value of the whole with-prompt, here
default. Nothing after the fail runs, in digit, in number’s fold,
or anywhere between them and the with-prompt. A procedure held across an
abandoned suspension is never called; there is no finally clause.
failing answers Never, the type with no values, so nothing could be
passed to its resume, and (absurd never), of type
(∀ (A) (Fn Never → A)), gives the suspension whatever type the code
around it needs. Since nothing resumes such a suspension, it costs less:
it saves nothing of the computation it leaves, and only unwinds
(tests/programs/prompt-exception.sld). The compiler reports every source
error this way (compile-error in (snail shell compiler read)).
The handler runs outside
A handler runs outside its with-prompt, so a suspension it makes goes to
the next with-prompt of that prompt, further out. A handler that fails
again is caught there:
;; A handler that fails again reaches the `with-prompt` outside its own.
(report out
(attempt (lambda ()
(match (attempt (lambda () (total out (list -7))))
((Ok value) value)
((Err why) (fail (string-append "again, " why)))))))
failed: again, negative: -7
Resuming
Generators
(resume answer) runs the rest of the body, with answer as the
suspension’s value, to the body’s end, and answers the body’s value, so
the handler may build on it:
(define yielding (→ (Prompt I64 Unit)) (make-prompt))
(define (yield (value I64)) (→ Unit)
(suspend yielding value))
;; Yields the numbers from `low` to `high`.
(define (range (low I64) (high I64)) (→ Unit)
(when (<= low high)
(yield low)
(range (+ low 1) high)))
;; Every value `body` yields, in order.
(define (collect (body (Fn → Unit))) (→ (List I64))
(with-prompt yielding
(lambda ()
(body)
(Nil))
(lambda (value resume) (Cons value (resume (unit))))))
(show-all out (collect (lambda () (range 1 5))))
1 2 3 4 5
Each yield stops range and hands its value to the handler, which
conses it onto whatever the rest of the body produces. The body ends with
(Nil), the answer when nothing more is yielded. A handler may also
choose, value by value, whether to resume:
;; The first value above `limit` that `body` yields, or -1.
(define (first-above (limit I64) (body (Fn → Unit))) (→ I64)
(with-prompt yielding
(lambda ()
(body)
-1)
(lambda (value resume) (if (> value limit) value (resume (unit))))))
4
-1
The with-prompt is around the rest again
Resumed, the body runs under its with-prompt again: its next suspension
reaches the same handler, with a new resume for what is left then.
collect above depends on it: each (resume (unit)) runs to the next
yield, whose handler conses again.
Keeping resume
resume is an ordinary function. A handler may return it inside a value,
and whoever holds that value may call it later, after the with-prompt
has returned:
;; A generator stopped at a value, holding the rest of its body.
(enum Step
(Done)
(Yielded
((value I64)
(next (Fn Unit → Step)))))
;; Runs `body` to its first yield, and hands back the rest rather than
;; resuming it.
(define (start (body (Fn → Unit))) (→ Step)
(with-prompt yielding
(lambda ()
(body)
(Done))
(lambda (value resume) (Yielded value resume))))
;; Takes turns between two generators until both are done.
(define (interleave (this Step) (other Step)) (→ (List I64))
(match this
((Done)
(match other
((Done) (Nil))
(rest (interleave rest (Done)))))
((Yielded value next) (Cons value (interleave other (next (unit)))))))
1 10 2 11 3 12 13 14
start runs a generator to its first yield, and the handler returns the
value with resume instead of calling it. interleave calls each next
long after start returned. Another task may call it just as well
(tests/programs/prompt-handoff.sld).
Resuming once
The frames resume holds run at most once. The checker does not track
this: to it, resume is an Fn like any other. Instead the continuation
records that it has run, and a second call panics
(tests/programs/prompt-resume-twice.sld):
(import
(snail core base)
(snail core io))
;; `resume` runs the rest of the body at most once. It is an ordinary
;; function to the checker, so a handler may call it twice, as this one
;; does, and the second call panics.
(define choosing (→ (Prompt Unit Bool)) (make-prompt))
(define (both (out OutputPort)) (→ (List Bool))
(with-prompt choosing
(lambda () (list (suspend choosing (unit))))
(lambda (value resume)
(let ((first (resume #t)))
(write-line out "resumed once")
(append first (resume #f))))))
(define (main (out OutputPort)) (→ Unit)
(both out)
(write-line out "not reached")
(unit))
resumed once
snail: resume called twice
A handler that never calls resume leaves its frames to the collector;
nothing in them runs. Multi-shot continuations are out of scope: they
would need every frame to be reachable twice, a cost paid by code that
never captures one.
Loops in constant stack
A handler that calls resume in tail position runs in constant stack
(tests/programs/prompt-tail-loop.sld):
(define ticking (→ (Prompt I64 I64)) (make-prompt))
(define (count-down (n I64) (total I64)) (→ I64)
(if (= n 0) total (count-down (- n 1) (+ total (suspend ticking n)))))
(define (main (out OutputPort)) (→ Unit)
(display out
(with-prompt ticking
(lambda () (count-down 100000 0))
(lambda (n resume) (resume (* n 2)))))
(newline out)
(unit))
10000100000
A hundred thousand suspensions grow neither the loop’s stack nor the handler’s.
Prompts
Which with-prompt catches
A suspension goes to the nearest with-prompt of its own prompt that is
running around it, past those of other prompts. A with-prompt it passes
is kept with the rest of the body and is around it again when the body
resumes, so the two nest as calls do
(tests/programs/prompt-nested.sld):
(define outer (→ (Prompt String Unit)) (make-prompt))
(define inner (→ (Prompt I64 I64)) (make-prompt))
;; Doubles what its body asks `inner` for, and tells `outer` about it
;; first: that suspension passes this `with-prompt` on its way out.
(define (doubling (body (Fn → I64))) (→ I64)
(with-prompt inner
body
(lambda (n resume)
(suspend outer (string-append "doubling " (show n)))
(resume (* n 2)))))
;; Every line the body tells `outer`, then its value.
(define (told (out OutputPort) (body (Fn → I64))) (→ I64)
(with-prompt outer
body
(lambda (line resume)
(write-line out line)
(resume (unit)))))
(display out
(told out
(lambda ()
(doubling (lambda ()
(suspend outer "asking")
(+ (suspend inner 1) (suspend inner 20)))))))
(newline out)
asking
doubling 1
doubling 20
42
Of two with-prompts of one prompt, the inner one catches.
A prompt is a value
A prompt made at the top level is one prompt for the whole program, which
any code that can name it may suspend to: failing and yielding above,
and the prompt every task waits on (tasks). A
prompt made inside a function is that call’s own
(tests/programs/prompt-local.sld):
;; Every value `body` hands the function it is given, in order.
(define (collect (body (Fn (Fn A → Unit) → Unit))) (→ (List A)) (∀ (A))
(let ((prompt (ann (make-prompt) (Prompt A Unit))))
(with-prompt prompt
(lambda ()
(body (lambda (value) (suspend prompt value)))
(Nil))
(lambda (value resume) (Cons value (resume (unit)))))))
;; The collection inside sees only its own values, and the one outside
;; the rest, though both prompts carry an I64.
(define (nested) (→ (List I64))
(collect (lambda (emit)
(emit 1)
(for-each emit (collect (lambda (inner) (inner 10) (emit 2) (inner 20))))
(emit 3))))
("a" "b" "c")
(1 2 10 20 3)
The collection inside sees only its own values, though both prompts carry
an I64: nothing but the function a prompt was handed to can suspend to
it. find-first in the same file makes a prompt of its own for an early
exit that no caller’s handler can intercept.
No with-prompt running
A suspension needs a with-prompt of its prompt running around it. With
none, nothing could catch it, so suspend panics where it is called
(tests/programs/prompt-unhandled.sld):
made
snail: suspend: no with-prompt of this prompt is running
What a suspension passes through
A suspension unwinds through the calls between it and its with-prompt,
and resuming runs what they had left. Anything written in snail-scheme
can be left and resumed. Three places are the backend’s own:
- A function an array or string is generated by (
array-generate,string-generate, and what is built on them, such asarray-map) is called by a loop that cannot go on from the middle. A suspension nothing resumes passes through it; one that may be resumed panics there (tests/programs/prompt-generate.sld). - A cache and a top-level value keep a result. A call that suspended
kept none: the next call with that key runs the function again, and the
next read of the value runs its initializer again
(
tests/programs/prompt-kept.sld). - The host. A suspension cannot leave through a function the host
called to reach a
with-promptrunning beneath it; that panics.
How the compiler knows
No type says which calls may suspend, so the compiler finds out. After
specialization, when every function is concrete, it computes what each
definition’s call may suspend to, and what a call of a function value of
each type may, and tests for a suspension only after the calls that may
have one (the compiler tour). A
prompt held by a top-level value is known by name, so a with-prompt of
it is known to catch its suspensions, and code that only stops, as the
compiler’s passes do, pays for no frames. Code that never suspends is
compiled as if suspension did not exist.
Suspension is this translation, ordinary calls and explicit frames, and
not stack switching, so any WasmGC engine runs it and both hosts agree.
call/cc, dynamic-wind and multi-shot continuations are not language
features (notable omissions).
Values
Every value may be shared. Records and enums are heap objects with identity; primitive numbers and booleans remain unboxed. Passing a record, binding it to another name, storing it in a field or capturing it in a closure refers to the same object, and the Wasm engine’s collector reclaims it once nothing reaches it. There are no linear types, reference counts, destructors or borrows, and the compiler inserts no ownership operations.
Mutable records
Record fields are mutable by default. A field declaration is (name Type);
there is no per-field mutability annotation and no separate Ref cell type. Local
bindings themselves are not reassigned. Aliases of a record observe writes to
that record, including writes through another enclosing record.
(record Counter
((value I64)))
(define (increment! (counter Counter)) (→ Unit)
(set! (● counter value) (+ (● counter value) 1)))
Whoever holds a record may select and update its fields: nothing in a
signature says which a function does, so one that writes is named with a
trailing !, and one that only reads is not
(capabilities). To exchange a field’s value, read it,
then set! the new one.
Name-field-set is a pure replacement operation: it returns another record
with that field replaced, sharing the values of the others. Use set! on a
● path for mutation. There are no generated mutable setters.
Sharing
Sharing a value preserves its identity. There is no general Clone class or
implicit deep copy. Construct a new record or copy an array when independent
mutable state is needed.
A function that constructs a value makes a fresh one at each call. A top-level value is constructed once and shared by every reader.
Closures
(Fn A → B) is the built-in callable type former. A closure may capture
any value, and may be called any number of times. A named top-level function
has no capture environment. The backend represents any closure without
captures as an immutable global. There is no separate code pointer type,
callable class, FnMut, dyn, or impl form.
A with-prompt’s resume is an Fn too, but the frames it holds run at
most once: calling it a second time panics with resume called twice. A
handler that never calls it leaves the suspended frames to the collector,
and nothing in them runs (suspension).
Resources
A value that stands for something outside the managed heap, such as a socket,
a child process or a file read in flight, carries a host handle. Its library
offers an explicit operation that releases the handle, such as
close-connection; nothing releases it when the value becomes unreachable,
since there are no finalizers.
A fatal panic, a terminal Wasm trap or divergence ends the computation. Hosts close the failed run or instance; they do not continue an interrupted source activation.
Representation
Every nominal aggregate is a WasmGC object. A field contains one scalar or one
managed reference; nested records are never flattened into their owners. An
enum case stores its tag before its fields. Arrays are WasmGC arrays with
fixed runtime lengths, of any element type. An Any pairs its type’s TypeId
with the value, boxed when it is a scalar. A closure is a struct of its code
followed by its captures. No object carries a header beyond these fields, and
the engine traces all of them.
Macros and generated libraries
Macros are hygienic syntax-rules transformers, defined with
define-syntax at the top level or in a local body. Surface forms such as
let*, cond, case and the variadic list are macros in (snail core base).
So is what a deriving clause expands to, a use of a macro in its class’s
library: a macro can expand into an instance, as into any declaration.
They expand before checking, so generated expressions obey the same type
rules as handwritten code.
A macro can generate a typed definition, including its (→ Result), ∀,
⊨ and documentation clauses. It cannot hand code a capability it was
not given: a template’s own names are resolved where the macro is defined.
Generated identifiers retain their lexical context; field labels select
stored slots of the receiver’s nominal type.
snail-scheme is a statically-typed Scheme successor. There is no R7RS
translator, (scheme base) compatibility library, dynamic Scheme runtime,
call/cc or dynamic-wind. S-expressions, hygienic macros and the
define-library envelope remain useful syntax in their own right. The
compiler’s Chez bootstrap is a host adapter for its source
closure, not a compatibility contract for arbitrary programs.
Generated libraries
A library file may hold a generate-library recipe instead of a
define-library. The build driver compiles and runs the producer, then the
compiler decodes the Syntax it returns. The wire representation carries
bytes directly, so a producer need not print and reparse a source string.
(generate-library (sample table)
(import
(snail core base)
(snail shell syntax))
(library-syntax (list "sample" "table")
(list "squares")
(list (list "snail" "core" "base"))
(list (form "define"
(list (SymbolSyntax "squares")
(form "list"
(map (lambda (i) (IntegerSyntax (* i i)))
(iota 6))))))))
The recipe is an explicit build-time program. Its expression is placed in a
producer entry function; it is not a runtime initializer in the generated
library. A recipe that needs capabilities is a lambda over them, and the
producer’s main asks its target for each
(src/lpc/skins.sld reads a linked file through a Resources):
(generate-library (lpc skins)
(import (snail core base) (lpc embed) (snail shell resource))
(lambda ((resources Resources))
(ramps-library (list "lpc" "skins")
(read-resource resources (link-file "palettes/skin.json")))))
The resulting library still contains only definitions and compile-time declarations. Recipe inputs, failures and cycles are tracked by the compiler input protocol.
A native producer can also run a build tool. The Ink recipe links its sources, asks for Processes to run inklecate, and returns ordinary dialogue definitions. Both browser and Node builds use that producer. Compiling Ink
link-file resolves relative to the recipe’s own file.
The first embeds a dependency as a literal; the second makes a linked resource
available to the producer’s task. Every emitted form is located at the recipe
for diagnostics. Use (snail shell syntax) to construct syntax explicitly;
there is no dynamic Scheme datum conversion layer.
What a build keeps
A build runs every producer it reaches, every time, and keeps none of
their output, so no build is handed a library made from inputs that have
since changed. Running one again is cheap: a build of Hearsay, its three
producers among its work, takes about four seconds. Nor could a build
tell when a kept output had gone stale: a recipe reads files through
Fs, runs processes and reaches the web, and nothing records what it
read. A cache keyed by the recipe’s text would serve the LPC art as it
was when the cache was filled.
What is costly is what a recipe fetches, and the recipe keeps that
itself, under a digest that pins what it must be. A fetch pinned so gives
the same bytes or fails, whatever its server does later, so its result
depends on the pin alone, and keeping it changes nothing a build can
observe: the machine’s cache holds it for every workspace, and a build
that finds it there needs no network. (snail shell web zip) reads a zip
archive’s members that way, pinned by the digest of the archive’s end, and
a dataset’s recipe is one call of it
(datasets):
(generate-library (datasets mipnerf360 bicycle)
(import
(snail core base)
(only (snail core io) Fs ProcessEnvironment)
(only (snail shell web) Web)
(datasets mipnerf360))
(lambda ((fs Fs) (web Web) (environment ProcessEnvironment))
(scene-library fs web environment
(list "datasets" "mipnerf360" "bicycle")
"bicycle"
"images_4")))
The network is one more capability the recipe asks for, Web, and the
cache’s place comes from the environment it is handed. The library it
returns links each file it fetched rather than embedding it, so the
program reads them as resources, and they ship in its store/.
Notable omissions
snail-scheme is deliberately smaller than its first plan. These parts were dropped
because they would cost more than they give the programs snail-scheme runs today;
each can return if a program needs it.
Cut from the plan
- The dependent elaborator. Generic code is served by Hindley–Milner checking with typeclasses and monomorphization. Normalization by evaluation and implicit arguments would add type-level computation no program uses.
- Linear types and counted ownership. Every value may be shared, and
the collector reclaims it (values). There is no
FnOnce,Rc,WeakRc,DroporCopy, and no finalizer: a resource has an explicit close operation. A second call ofresumepanics at run time instead of being rejected by the checker (#767). - Algebraic effects and effect rows. Effect declarations, handlers and rows are gone (#877). What they gave is had with less: a capability is a value a function is given, and suspension is three functions. What went with them: no type says whether a call writes, reaches the host or suspends. Reaching the host is in what a function is handed; writing is not tracked at all, so that a function leaves its arguments unchanged is a convention. Divergence was never tracked; a row is the one way it could be, since nothing can be handed to a function to let it loop.
- Incremental compiler state. Every build expands, checks and emits its complete dependency closure. There is no retained compiler Session, interface hashing or checked-code/Wasm reuse.
- Actor destinations. Tasks schedule one-shot closures and share
Mailboxqueues, which are values, not addresses of tasks. Request/reply protocols and network transports are application concerns.
Simplifications made on the way
- Local bodies are sequential: a local function may call itself but not a later local definition.
- Named functions require an annotation on every parameter. Generic variables and class obligations appear on the definition. A lambda either takes that whole header or annotates nothing and is inferred; values also use inference.
- Classes have no superclasses, no associated types, and no higher-kinded parameters.
- Wire TypeIds are 32 bits, and every record and enum value carries its case’s TypeId.
snail-scheme deliberately omits R7RS compatibility, call/cc, dynamic-wind,
a dynamic numeric tower, source borrows, callable classes, dyn, impl,
FnMut and inline records. These are design decisions, not compatibility
bugs waiting for implementation. A top level has no statements: a
program’s entry is its main. A top-level value’s initializer is handed
no capability. Instance
dispatch, named instance sets, plugins, code pointers, declaration metadata,
implicit Any conversions and resizable arrays have also been removed.
Mutually recursive local functions, class superclasses, literals at generic numeric types and overflow-checked arithmetic remain possible future work. The roadmap tracks the current priorities.
References
- R7RS, the Scheme standard whose syntax and
libraries
snail-schemefollows. - WebAssembly garbage collection, the target: structs, arrays and references managed by the engine.
- wasm-tools, whose
watcrate assembles the compiler’s output, and wasm-fuse, which links the scalar runtime. - Luc Maranget, Compiling Pattern Matching to Good Decision Trees and
Warnings for Pattern Matching: the checks behind
match. - Per Vognsen’s Bitwise and Resin’s discussion of it: representations that explain operations, and control flow that teaches the problem.
- Chez Scheme, the first stage of the compiler’s bootstrap.
Tutorials
Small complete programs, each run by the repository’s test suite with the output shown. Run one with
./snail-scheme run --target node examples/fibonacci.sld
snail-schemein ten minutes: the whole language at a glance, as one commented program. Start here.- Fibonacci: a typed recursive function and output.
- Colors: records, enums, typeclasses and pattern matching.
- Capabilities: a port as a value, and what a callback does.
- Values and mutation: shared objects, mutable fields and fresh explicit factory functions and shared state.
Siegework is the complete application.
snail-scheme in ten minutes
The whole language at a glance, as one program: values, control, data, typeclasses, mutation, capabilities, suspension and macros, each in a few lines. Read it top to bottom; the chapters on types, capabilities, suspension and values say what each form means, and the tutorials after this one are small programs that use them.
examples/tour.sld:
;; `snail-scheme` in ten minutes. Every line of this file runs:
;;
;; ./snail-scheme run --target node examples/tour.sld
;;
;; prints what `examples/tour.out` holds, and the test suite checks it.
(import
(snail core base)
(snail core io))
;; ---- Values and definitions ----
;; A top-level `define` names a value, and `:` declares its type. The
;; scalars are I32, I64, F32, F64, Bool, Char, String and Unit; an integer
;; literal is an I64 unless something says otherwise.
(define (answer) (→ I64) 42)
;; A function's type is an arrow from its arguments to its result.
(define (square (n I64)) (→ I64)
(* n n))
;; ---- Control ----
;; `if` always has both branches. `cond`, `case`, `when` and `unless` are
;; Scheme's.
(define (sign (n I64)) (→ String)
(cond ((< n 0) "negative")
((= n 0) "zero")
(else "positive")))
;; A named `let` is a loop. A call in tail position never grows the stack.
(define (sum-to (n I64)) (→ I64)
(let loop ((i 1)
(total 0))
(if (> i n) total (loop (+ i 1) (+ total i)))))
;; ---- Lists and functions ----
;; A list holds values of one type and never changes. Functions are values,
;; and `lambda` makes one.
(define (numbers) (→ (List I64)) (list 1 2 3 4 5))
;; ---- Data ----
;; A struct has named fields; an enum has cases, each with its own fields.
;; A type's name builds it, and `(● point x)` reads a stored field.
(record Point
((x I64)
(y I64)))
(enum Shape
(Circle
((center Point)
(radius I64)))
(Rectangle
((corner Point)
(width I64)
(height I64))))
;; `match` takes data apart. A match that misses a case does not compile.
(define (area (shape Shape)) (→ I64)
(match shape
((Circle _ radius) (* 3 (square radius)))
((Rectangle _ width height) (* width height))))
;; There is no null and no exception: absence is an Option, and failure a
;; Result, both ordinary enums.
(define (divide (n I64) (d I64)) (→ (Result I64 String))
(if (= d 0) (Err "division by zero") (Ok (quotient n d))))
;; ---- Generics and typeclasses ----
;; A typeclass names operations, and an instance gives them for one type.
(typeclass (Describe T)
(declare (describe (value T)) (→ String)))
(instance (Describe Point)
(define (describe (point Point)) (→ String)
(string-append "(" (i64->string (● point x)) ", " (i64->string (● point y)) ")")))
(instance (Describe Bool)
(define (describe (b Bool)) (→ String)
(if b "yes" "no")))
;; `All` makes a definition generic, and `requires` asks for instances.
;; Each use is compiled for its own types, so generic code costs what a
;; hand-written copy would.
(define (describe-all (items (List T))) (→ String) (∀ (T)) (⊨ (Describe T))
(string-join (map describe items) " "))
;; ---- Mutation ----
;; Records are heap objects with mutable fields. Aliases see the same
;; writes: whoever holds a record may change it.
(record Counter
((count I64)))
(define (bump! (counter Counter)) (→ Unit)
(set! (● counter count) (+ (● counter count) 1)))
;; ---- Capabilities ----
;; What a function may do to the world is in what it is given. `greet`
;; asks whoever it is handed, and its caller decides who that is: a
;; capability is a value, here a function.
(define (greet (ask (Fn → String))) (→ String)
(string-append "hello, " (ask)))
;; ---- Suspension ----
;; `suspend` stops the body of the `with-prompt` around it and hands its
;; value to that call's handler, with `resume`, the rest of the body, to
;; call at most once (a second call panics): here the handler collects
;; each value emitted and carries on.
(define emitting (→ (Prompt I64 Unit)) (make-prompt))
(define (count-down (n I64)) (→ Unit)
(when (> n 0)
(suspend emitting n)
(count-down (- n 1))))
;; ---- Macros ----
;; Macros are Scheme's `syntax-rules`, and hygienic: `swap!`'s own
;; `temporary` cannot capture the caller's.
(record Label
((text String)))
(define-syntax swap!
(syntax-rules ()
((_ a b) (let ((temporary (● a text)))
(set! (● a text) (● b text))
(set! (● b text) temporary)))))
(define (main (out OutputPort)) (→ Unit)
(write-line out (string-append "seven squared is " (i64->string (square 7))))
;; Nothing converts implicitly: an I64 becomes an F64 only when asked.
(write-line out (f64->string (/ (i64->f64 (answer)) 8.0)))
(write-line out (sign -3))
(display out (sum-to 100))
(newline out)
(write out (map square (filter (lambda (n) (= (remainder n 2) 1)) (numbers))))
(newline out)
(display out (fold-left + 0 (numbers)))
(newline out)
(write out
(map area
(list (Circle (new Point (x 0) (y 0)) 2) (Rectangle (new Point (x 1) (y 1)) 3 4))))
(newline out)
(for-each (lambda (d)
(match (divide 10 d)
((Ok quotient) (write-line out (i64->string quotient)))
((Err reason) (write-line out reason))))
(list 2 0))
(write-line out (describe-all (list (new Point (x 1) (y 2)) (new Point (x 3) (y 4)))))
(write-line out (describe-all (list #t #f)))
(let ((clicks (new Counter (count 0))))
(bump! clicks)
(bump! clicks)
(display out (● clicks count))
(newline out))
(write-line out (greet (lambda () "world")))
(write out
(with-prompt emitting
(lambda ()
(count-down 3)
(Nil))
(lambda (value resume) (Cons value (resume (unit))))))
(newline out)
(let ((left (new Label (text "left")))
(right (new Label (text "right"))))
(swap! left right)
(write-line out (string-append (● left text) " " (● right text))))
(unit))
It prints:
seven squared is 49
5.25
negative
5050
(1 9 25)
15
(12 12)
5
division by zero
(1, 2) (3, 4)
yes no
2
hello, world
(3 2 1)
right left
Fibonacci
examples/fibonacci.sld:
;; The smallest complete program: a typed recursive function and output.
(import
(snail core base)
(snail core io))
(define (fibonacci (n I64)) (→ I64)
(if (< n 2) n (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
(define (main (out OutputPort)) (→ Unit)
(display out (fibonacci 30))
(newline out)
(unit))
It prints:
832040
Colors
examples/colors.sld:
;; Structs, enums, typeclasses and pattern matching.
(import
(snail core base)
(snail core io))
(record (Vec3 T)
((x T)
(y T)
(z T)))
(enum PrimaryColor
(Red)
(Green)
(Blue))
(enum Color
(Primary ((value PrimaryColor)))
(Rgb ((value (Vec3 I64)))))
(typeclass (ToHex T)
(declare (to-hex (value T)) (→ String)))
(define (channel-hex (value I64)) (→ String)
(let ((digits "0123456789abcdef"))
(string (string-ref digits (quotient value 16)) (string-ref digits (remainder value 16)))))
(instance (ToHex PrimaryColor)
(define (to-hex (color PrimaryColor)) (→ String)
(match color
((Red) "#ff0000")
((Green) "#00ff00")
((Blue) "#0000ff"))))
(instance (ToHex (Vec3 I64))
(define (to-hex (v (Vec3 I64))) (→ String)
(string-append "#" (channel-hex (● v x)) (channel-hex (● v y)) (channel-hex (● v z)))))
(instance (ToHex Color)
(define (to-hex (color Color)) (→ String)
(match color
((Primary value) (to-hex value))
((Rgb value) (to-hex value)))))
(define (main (out OutputPort)) (→ Unit)
(for-each (lambda (color) (write-line out (to-hex color)))
(list (Primary (Red)) (Rgb (new Vec3 (x 255) (y 160) (z 0))) (Primary (Blue))))
(unit))
It prints:
#ff0000
#ffa000
#0000ff
Capabilities
examples/capabilities.sld:
;; Capabilities. A function writes only to the port it is given, so its
;; caller decides where the lines go.
(import
(snail core base)
(snail core io))
(define (total-cost (log OutputPort) (prices (List I64))) (→ I64)
(fold-left (lambda (total price)
(write-line log (string-append "adding " (show price)))
(+ total price))
0 prices))
;; A port is a record of the function that writes it, so a program makes
;; its own: this one keeps nothing.
(define (nowhere) (→ OutputPort)
(new OutputPort (write-string (lambda (text) (unit)))))
;; The same function, quiet or verbose, depending only on the port.
(define (main (out OutputPort)) (→ Unit)
(display out (total-cost (nowhere) (list 3 4 5)))
(newline out)
(display out (total-cost out (list 1 2)))
(newline out)
(unit))
It prints:
12
adding 1
adding 2
3
total-cost writes to the port it is given and to no other, so its caller
decides where the lines go: main hands it its own port, from the target,
or one of the program’s making that keeps nothing.
A callback does what it was made with. This function adds output around an action:
(define (announce (out OutputPort) (action (Fn → A))) (→ A) (∀ (A))
(write-line out "calling")
(action))
announce writes to the port it is given. What the call of action does
is not in announce’s signature or in action’s type: a closure that
captured a port writes to it, and one that captured none reaches nothing
of the host’s.
Capabilities covers this in full, and
suspension how a computation stops and resumes.
Values and mutation
A record is a heap object. Assigning it another name shares that object; all fields are mutable. The field-path example shows nominal selection through nested records.
Select an enum case with match. Put mutable payload in a record, then use
● and set! to read or change its fields:
(import
(snail core base)
(snail core io))
(record Radius
((value I64)))
(enum Shape (Circle ((radius Radius))) (Empty))
(record LinkData
((value I64)
(next (Option Chain))))
(enum Chain (Link ((data LinkData))) (End))
(define (cycle) (→ Chain)
(let* ((data (new LinkData (value 3) (next (None)))) (link (Link data)))
(set! (● data next) (Some link))
link))
(define (main (out OutputPort)) (→ Unit)
(let* ((circle (Circle (new Radius (value 4)))) (alias circle))
(match alias
((Circle radius) (set! (● radius value) 9))
((Empty) (panic "empty shape")))
(match circle
((Circle radius)
(write-line out (show (● radius value)))
(write-line out (show (● radius value)))
(set! (● radius value) 12))
((Empty) (panic "empty shape")))
(match alias
((Circle radius) (write-line out (show (● radius value))))
((Empty) (panic "empty shape"))))
(match (cycle)
((Link first)
(set! (● first value) 21)
(match (● first next)
((Some (Link same)) (write-line out (show (● same value))))
(_ (panic "missing cycle")))
(match (cycle)
((Link second) (write-line out (show (● second value))))
((End) (panic "empty chain"))))
((End) (panic "empty chain")))
(unit))
9
9
12
21
3
The first three lines show two names observing one object. The last two show a cyclic object’s internal alias and a separate call to its factory. Each call constructs a fresh graph; the second graph keeps its original value. Bind a factory result once and pass it to callers that should share state.
Any value can be shared this way, with no borrow syntax or explicit cloning; the collector reclaims it once nothing reaches it. See values for sharing, closures and resources.
Application model
An application is a script: its main asks the page for the
capabilities it uses and hands control to an engine’s loop. The engine is a
library, in the style of Rust’s
winit: the script builds a
handler, a record of the application’s functions, and calls the engine with
it.
Siegework’s script, src/apps/siegework/main.scm, is the whole of it:
;; Siegework: the page's scene, from its game, view and HUD.
(import
(snail core base)
(snail shell app)
(snail shell wire)
(apps siegework game)
(apps siegework view)
(apps siegework hud)
(only (snail shell gpu) Gpu)
(only (snail shell dom) Dom)
(only (snail shell page) Events)
(only (snail shell page) PageStorage)
(only (snail core io) Clock))
(define (main (gpu Gpu) (dom Dom) (events Events) (storage PageStorage)) (→ Unit)
(run-scene dom events storage (new SceneHandler
(initialize new-game)
(update update-game)
(start start-frames)
(draw (lambda (game frames)
(draw-frame gpu (view-game game) frames)))
(hud game-hud)
(image-url (lambda (drawing image) ""))
(save (lambda (game) (serialize (game-save game))))
(restore
(lambda (bytes) (game-restore (deserialize bytes))))))
(unit))
./snail-scheme build --target browser src/apps/siegework/main.scm
On the page, the host calls the script’s start with a scheduler, as every
host does, and (snail target browser) runs main as its first task, with
the page’s capabilities (targets).
main can wait: run-scene waits for the page’s events as a task does. There are two engines, run-scene for a canvas and run-interface
for a document, and both boot and save through run-page from
(snail shell page). An application with its own loop calls run-page
itself, as tests/apps/requests does. IPC remains outside this contract.
Typed session protocols are future library work.
Scenes
(snail shell app)’s SceneHandler holds a scene’s pure functions over
immutable state, and the two that draw it, which keep a drawing state of
their own:
| Field | Meaning |
|---|---|
initialize : seed width height -> State | The first state. |
update : State Input -> State | Applies a key, pointer, HUD button, screen size, or elapsed milliseconds. |
start : -> Drawing | The drawing state of a fresh page or module. |
draw : State Drawing -> Drawing | Draws a frame through gpu, and answers what drawing keeps for the next. |
hud : State -> (List Panel) | Panels of labels, texts, buttons, dials, links and images. |
image-url : Drawing Key -> String | The address of the image an Image widget names, or "" until there is one. |
save : State -> Bytes | Encodes the durable state, often a record of how to rebuild the full state. |
restore : Bytes -> State | Decodes the durable state and reconstructs the running state. |
The drawing state is never saved: it holds what drawing keeps between frames, such as an atlas and the portraits read back from it, and starts again with each page and each module, as the GPU’s objects do.
Serialization is chosen explicitly by the application; these examples use
(snail shell wire).
run-scene takes the page’s Dom, Events and PageStorage and the
handler, whose draw closes over the Gpu the script was given; it waits
as a task, and never returns. next-event drains the host queue, then waits by ticket when it is
empty. FrameEvent carries elapsed milliseconds; InputEvent carries an
Input. Hidden and SaveRequested save without stopping. A shared
five-second host timer supplies SaveRequested to either engine, so saving
does not require animation frames. The host arms it at boot and after each save.
The engine reports readiness after its first complete frame. Since elapsed time is input, the application decides how its simulation advances. Each task keeps what it closed over across waits. Libraries have no runtime initialization; application state is created by the running script.
A scene draws with the graphics libraries. Hearsay
composes the pictures it needs into an atlas and draws its map as one run
of quads (Atlas and quads).
(snail shell sprite) picks the cell a spritebook of any sheet shows for a
motion, heading and moment, which a quad then draws, and src/lpc uses it
for the Liberated Pixel Cup character art.
Siegework builds a 3D Frame from batches of mesh items, which
draw-frame draws, keeping in its Frames each batch’s packed instances
until the batch’s version changes, so a still scene packs nothing. Each
item also carries where it was, and moves toward where it is as the
frame’s motion goes from 0 to 1. Items are matte, lit by the sun and the
ambient light, and glow from 0, lit, to 1, their own color. Batches may be
solid, translucent, or revealed within a growing disc. The camera is
perspective or orthographic.
HUD panels, built from widgets such as those label and button make,
stack in columns from the screen’s corners, appear as dialogs, or sit in a
banner across the top that lets input through but for its links. A widget’s
tone can mark it suggested, the control to use next. The HUD is a tree in
the page’s document: the scene’s loop builds it as (snail shell ui)’s
Html and changes the document through its Dom only where the tree
differs from the one before, so an element keeps its node while its key
stays, and with it hover and focus. A button’s listeners make the presses
and hovering the scene’s update takes as input; a button removed while the
pointer is over it reports the pointer gone. An image shows the image the
scene’s image-url gives the address of; Hearsay’s portraits are regions
of its atlas read back as PNG data URLs. recognize turns raw pointer events into points, taps, drags
and pinches.
Siegework is the complete example, and Hearsay’s prototypes draw their residents as LPC characters on a 2D map.
Document interfaces
(snail shell ui) builds interfaces from a page’s document rather than a
canvas, in the shape Elm gave them:
| Function | Meaning |
|---|---|
view : Model -> (Html M) | A tree of elements and texts. An element’s attributes, typed properties (StringProperty, NumberProperty, FlagProperty) and listeners (On) are plain data; a listener holds a function from what its event carried to a message M. |
update : Model M -> (Pair Model (List (Fn → M))) | The next model, and the commands the message starts: work run as tasks, each answering a message. |
run-ui dom model start update view window commit checkpoint shows the view in the
document’s root through dom, a Dom of (snail shell dom), updates
it with each message in start, as when it must ask its server before
anything else happens, then handles one delivery at a time until the
document closes, and answers the last model. The window is no node of the
view’s tree, so window : Model -> (List (Attribute M)) gives its
listeners, for what reaches the whole page, such as a shortcut or the page
going back online, and they are patched as an element’s are.
next-event delivers a listener’s event, a wake, a save request, the page
hidden, or the document closed. commit receives each successfully presented
model; checkpoint persists it on a save request, hiding, and close.
Only the interface’s own task waits on the document,
so a command posts its answer to the interface’s mailbox and wakes the
document, and the interface drains the mailbox when it is woken; a command
still running when the document closes never answers. After each update
the interface changes only what differs from the tree it showed before. An element keeps its node while its tag and key stay the
same, so the page keeps its focus, selection and scroll; a child with a
Keyed attribute is matched by key and one without by its place among the
others without one. Attributes and properties the view leaves out are
cleared, and a listener is made again only when its captures or its
prevention change. Since the host decides both while an event is
dispatched, a listener declares them when it is made: the fields its events
carry (Capture) and when the host prevents their default action
(Prevent, never, always, or for listed key chords). A listener with
chords hears only them, so the keys it leaves alone never cross into
snail-scheme, and never a key that ends an input method’s composition.
Functions stay in snail-scheme: the host sees nodes and listeners only as
handles. A selection’s offsets count scalars, as a String’s indices do,
though the page counts UTF-16 code units.
A command does what a view cannot say by finding a node by its id
attribute with element-by-id. It can then focus it, scroll it through
its scroll properties, select a range of it or read its selection
(selection-range), insert text into it as typing
would (insert-text, which the page can undo and which fires the field’s
input event, and which answers whether the field took the text), and
measure it. A command can run after the view has removed its node, so on
a removed node these do nothing, and reads of it answer “” or 0. confirm
asks the person a question and answers whether they agreed. When the view
gives a field a new value, as when another view of its text changed it,
the field keeps its selection and scroll as far as the new text reaches.
Browser installation and fullscreen are shared snail-scheme capabilities. Any
application holding the page’s Dom can invoke them. Every browser target
also receives the default manifest and icons during packaging, unless it
supplies its own manifest. An application chooses its own installation button
or command; the packager does not inject controls into it.
The scalar declarations in (snail runtime browser dom) define the browser
boundary. (snail shell dom page) converts their results into typed values and
task completions; host/browser/install.mjs retains the browser’s opaque offer
and calls its native APIs. Scheme code owns application behavior, and Chromium
tests cover the browser decisions that the memory DOM cannot make.
The same Dom exposes browser window capabilities. installation-status
reports an available installation offer, an installed/standalone app, or no offer.
install-app awaits a single-use offer and returns accepted, dismissed,
unavailable, expired activation, failed, or already installed. Acceptance does not
mean the later appinstalled event has arrived. The host retains the opaque offer
across application generations; an expired activation leaves it available for a
new explicit click. fullscreen? reads the current mode, and set-fullscreen
awaits entering or leaving it, returning whether the request succeeded. Both
requests use task tickets, with no suspended Wasm stack. Stopping a generation
releases its wait even if the browser dialog remains open. The memory Dom
reports unavailable installation and refuses fullscreen.
with-memory-dom from (snail shell dom memory) hands its work a Dom over a
document in memory, delivering a script of cues (events fired at elements
by their id or at the window, and the page hidden), and answers the
document it left, as HTML and as a trace of every operation.
tests/programs/ui-memory.sld, tests/programs/ui-patch.sld and
tests/programs/ui-commands.sld run interfaces this way under make test.
run-interface from (snail shell ui page) runs a document application
from an InterfaceHandler:
(run-interface dom fetch events storage
(new InterfaceHandler
(initialize new-notes) (update update) (view view) (window window)
(messages (lambda (model) (list (Load))))
(save (lambda (model) (serialize (save model))))
(restore (lambda (bytes) (restore (deserialize bytes))))))
An interface without window listeners returns (Nil) from window; one
without startup messages returns (Nil) from messages. Initialization takes
the seed alone, and update’s commands are (Command Message), functions
of the page’s Dom and Fetch, which the loop hands each one: a command
may wait as a task, reach the document, and ask the server through the
Fetch of (snail shell fetch). request method url headers body answers the server’s reply, its status and body, or why there was
none. A stream is the server-sent events of the kinds it names at a URL:
stream-next waits for the next, its kind and data, and answers none once
the stream is closed for good. The host connects again when a connection
drops, and a stream that names the kind error hears an event each time.
One command waits on a stream at a time, and the update that hears
an event issues the next wait, so a stream needs no machinery beyond
one-shot commands.
The shared page lifecycle restores saved bytes; only a start without a save
initializes a fresh model. The engine runs run-ui over the Dom it is
handed and gives commands the Fetch, which a page’s main asks its
target for.
A completed presentation acknowledges startup; the shared saver stores the
encoded model.
The page loads startInterface from
ui.mjs, which a browser build ships, with a container element in place
of the canvas. host/browser/dom.mjs keeps the interface’s nodes and
listeners in tables by handle and frees a removed node’s subtree. A
listener reads what it captures and prevents the default action while
the event is dispatched, then queues the event (kind 14). A wake queues
kind 15 from any task. host/browser/fetch.mjs runs a request or a stream’s next event as a
host operation of the command’s own task, and closes every stream when a
program starts. tests/apps/notes/main.scm is the example, and
tests/browser/ui.mjs drives it in Chromium against a server of its
own.
Both ui.mjs and the scene’s host.mjs delegate loading to
host/browser/application.mjs. Document applications support periodic
saves, as scenes do.
Commands and late replies
A command’s answer is an ordinary message, so an interface sees a reply when it arrives and decides then what it still means. Nothing cancels a command: a reply that is no longer wanted still arrives, and the update ignores it, telling current replies from stale ones by what the message carries.
tests/apps/requests/src/requests/application.sld is a complete example.
Its Model numbers the requests it makes. Load starts the next
number’s request as a command, which answers Loaded with that number
and the reply, and an update shows a reply only if it carries the latest
number. Cancel moves the number on, so a reply that arrives after it,
or after a newer Load, is ignored; the request itself runs to its end.
Its Save contains only display data and a click count. Its script calls
run-requests with the page’s Dom and Fetch, which runs run-page over
the Save itself and calls run-ui. Its commit callback calls report-ready;
the checkpoint callback comes from run-page.
Only Save crosses a reload. A command still running when the page goes
never answers the next page. Restore decides whether interrupted work should
be restarted; the example shows an interrupted request as such.
tests/browser/ui-requests.mjs holds server replies while input
continues, verifies that a canceled request cannot install a late reply,
and saves and reloads while a request is pending. The next page restores
its save and can request again. tests/programs/ui-checkpoint-wait.sld
runs a command that finishes while a checkpoint waits, over the memory
DOM.
Task lifetime
The script is the first task of the program’s
scheduler. The host creates a scheduler, passes it to
the program’s main, and turns it until no task is live or one fails. A trap
in any task fails the run and closes the scheduler; tasks:running
identifies the failing task for the report. An engine’s loop never returns,
so a page runs until it is left or traps.
Event waits and storage wait by ticket, as any host operation does (waiting on the host). Their abort signals belong to the run that began the call, and closing the run aborts them.
One loop consumes the page’s events. The runtime buffers input and coalesces frames; it does not own an implicitly shared current world. Seed and canvas dimensions are available to all tasks.
Event and save boundaries
host/browser/runtime.mjs owns a run’s queue and storage bindings;
application.mjs owns loading and the start without an unreadable save.
host.mjs retains the scene devices and gives the HUD the page’s overlay as
its document, while ui.mjs resets the document and fetch devices for each
run. DOM listeners enqueue input rather than calling
Wasm. Consecutive moves for the same pointer and consecutive resizes coalesce
without crossing other input. Consuming a pending frame requests the next
animation frame, so slow work does not accumulate ticks. HUD values update at
most every 100 milliseconds and periodic saves occur every five seconds.
Event waits and complete storage operations wait by ticket on the
snail-scheme scheduler. Starting a save copies its byte argument before the
IndexedDB request begins; a failed save is a warning, and the page keeps
running. GPU drawing waits only to request the device, decode an image or read a
buffer back, by ticket. No import suspends Wasm, so the linear-memory stack of the Rust scalar services is
never left mid-call.
The engine acknowledges its first completed presentation: a scene handles resize and a zero-time frame, while a document presents its initial model and startup messages. Input sent before then is delivered after it.
A save the application cannot read traps before the page boots; the page then starts again without it. A trap after boot ends the page, which keeps its last save: up to five seconds of work, or what happened since the page was last hidden, is lost. Keep state that must survive a reload in the application’s Save.
Proposed durable state
Durable application data remains application work. Process replacement alone preserves no managed state; killing a process cannot promise cleanup or a final commit.
The typed state prototype proposes durable base tables and disposable,
read-only cached views. Ordinary entry startup opens the same store, recreates
sockets/windows and requests views. There is no application resume method,
heap snapshot or state-transfer IPC. Managed objects, closures and suspended
computations never cross code versions. This API remains under review.
Failed startup retains stored records and reports the failure, without automatic rollback to the old running loop. Reverting code does not undo data writes. The state chapter defines transaction outcomes, explicit schema migration and cache validity; process replacement supplies none of those guarantees by itself.
Keep storage identities stable, database files/journals outside source watching and output directories, and independent browser stores separately named. One concrete server database binding is sufficient; browser storage needs its own transaction and commit proof. The existing save/restore implementation remains until the replacement is reviewed and tested.
Workspaces and builds
A workspace is a folder that holds src/. Every library lives under src/,
at the path its name gives, and every import resolves there, then in the
standard libraries. A script is a source file anywhere in a workspace;
snail-scheme build --target TARGET FILE builds it for node or
browser, and snail-scheme run builds it and becomes its program
(scripts). A script’s workspace is the nearest folder above it
that holds src/. There is no project file: what is built, and for which
platform, is on the command line.
This repository is one workspace. The applications are scripts (application model):
./snail-scheme build --release --target browser src/apps/siegework/main.scm
python3 -m http.server 4191 --directory build/src/apps/siegework/main
An editor opening a workspace runs snail-scheme lsp, which checks each
open script and library (editors). The
toolchain describes command lifetimes.
Output directories
A script’s build produces one directory at WORKSPACE/build/PATH, PATH
being the script’s path in its workspace without its extension. It holds
one module, NAME.wasm, NAME being the script’s file name without its
extension: the whole program compiled as one and fused with its runtime.
Each file the program links (linked files) is an
object of the workspace’s store,
WORKSPACE/build/.snail-store/sha256/AB/DIGEST, named for the SHA-256 of
its bytes and sharded by its first two hex digits. Every build of every
script shares the store: an object is written once and never rewritten.
The program reads its files from store/ beside its module, at the same
paths, where each is another name for the store’s object, a hard link (a
copy where the two lie on different file systems). A program’s bulky files
are then on disk once, and its directory still holds them itself, so it
can be served or shipped on its own. Nothing reclaims the store: delete
build/ and rebuild from time to time. On Node the native runner,
host/native/run-snail.mjs, runs the module, which a Node build packages
with it (a Node package), and a page links it through
linkModule in load.mjs.
A release build, --release, differs in one thing: the module is then
optimized by Binaryen’s wasm-opt -O2, which can inline the runtime’s
functions into the program. wasm-opt is found on PATH.
A browser build adds the shared browser host and recursively copies the
public/ folder beside the script, if there is one. Supply index.html
there; no page is generated. The builder names the program’s module in
the page, with a
snail-modules meta element, which host.mjs, or ui.mjs for a
document interface, links the
program from; a linked file is fetched when the program first reads it.
Public files cannot overwrite generated files. At the root, every name the
build generates is reserved: the manifest, the release module, store, the browser host’s files
and the .snail-target ownership marker. .snail-publish is reserved at
every depth. Public trees must
contain only regular files and directories, include no build output,
and have no symlink components, including in the path to the public directory.
The public output is a relative symlink to a completed generation beside it.
Rebuilds replace that link atomically after compilation and packaging succeed.
Previous generations remain available to readers: snail-scheme build reclaims none. Resolve the link once before reading several files as one artifact.
An ordinary file, directory or unrelated link at the output path is rejected
and never removed by the builder.
The builder, (snail shell project build), builds the script’s generation
in private scratch before publishing it. A compile or packaging failure
removes the generation and changes no published output. Publication checks
the destination, makes a temporary link beside the generation and renames it
into place, which is atomic. These guarantees concern complete outputs, not
an atomic source snapshot or power-loss durability.
A Node package
A Node build’s directory is an npm package around its module, which runs wherever it is copied:
build/apps/hello/main/
package.json {"name": "main", "private": true,
"scripts": {"start": "node main.mjs"}, "bin": {"main": "main.mjs"}}
main.mjs runs main.wasm with its arguments
main.wasm
store/ the files the program links, if any
host/native/ the Node host, as the repository keeps it
host/browser/ the three files of the browser host it shares
npm runs it as Cargo runs a crate:
cd build/apps/hello/main
npm install # fetches its dependencies, if it has any
npm start -- ARGUMENT ... # runs it, as `cargo run -- ARGUMENT ...` does
npm install -g . # installs its command, `main`, as `cargo install --path .` does
npm prints the command it starts before the program’s output; npm start --silent leaves the output the program’s alone. npm runs a script in the
package’s folder, where Cargo stays in the caller’s. node main.mjs ARGUMENT ... runs the program in the caller’s directory, as snail-scheme run does, with nothing to install. A program that holds
(snail runtime gpu) may ask for a device and decode an image, so its
package depends on npm’s webgpu and @napi-rs/canvas packages, at the versions
the repository’s package.json pins, and loads each when it is first
needed, at the program’s first request-device and its first
decode-image (WebGPU on Node).
Inside the repository, Node finds the copies make fetch installed;
elsewhere, npm install in the package fetches them. Other programs
depend on nothing.
The package is private, so npm will not publish it until its author gives
it a name and a version of their own. What becomes of it after that is
the Node ecosystem’s work, not the builder’s: npm publish ships it, and
any bundler or packager that takes an npm package takes it. Nothing
installs a dependency but npm, so a package is installed before it is
packed. A single executable application, for one,
is Node’s own binary with a script built into it
(SEA). The
script can load only Node’s built-in modules, so it loads the package
beside the executable through createRequire. main.mjs and the host
avoid top-level await, so require can load them. The output is a link
to its generation, which the copy follows:
mkdir -p dist && cp -RL build/apps/hello/main dist/hello && (cd dist/hello && npm install)
echo "require('node:module').createRequire(__filename)('./hello/main.mjs');" > sea-main.cjs
echo '{"main": "sea-main.cjs", "output": "dist/hello-run"}' > sea-config.json
node --build-sea sea-config.json
dist/hello-run ARGUMENT ...
The executable runs with dist/hello/ beside it. Node 26.9 and later can
also serve the package from inside the executable, as one file, with
"useVfs": true and the package zipped as its "vfsArchive".
Embedding a build
A build embeds another through a generate-library recipe whose producer
builds it. build-script in (snail shell project build) builds and
publishes a script as snail-scheme build does, and answers its
generation’s directory; producer-tools reads the tools the build ran the
producer with from its command line. The library the recipe returns links
each file of that generation, so the embedding program reads them as
resources, and the files ship with it:
(generate-library (embedded client)
(import
(snail core base)
(snail shell project build)
(snail shell project embed)
(only (snail core io) Arguments ProcessEnvironment Fs Clock)
(only (snail shell process) Processes))
(lambda ((arguments Arguments)
(environment ProcessEnvironment)
(processes Processes)
(fs Fs)
(clock Clock))
(files-library fs (list "embedded" "client")
"client-files"
(build-script processes fs clock (producer-tools arguments)
(script-at fs environment "client/main.scm")
(Browser)
(Debug)))))
files-library, in (snail shell project embed), lists the generation
and links each file by its absolute path (tests/embedding/). link-file
takes a path relative to the recipe, .. included, or an absolute one. A
generation’s store/ contains the immutable objects. The linked bundle
can serve the same catalog and objects under its own URL prefix.
A producer runs in its workspace’s directory, in every build that reaches
it, so a changed client file reaches the next build of the server. A build
that compiles a generated library whose output it has not yet produced
prints the producer into its scratch, compiles, links and runs it, and
compiles again (producing in build.sld). The producer’s own compile does
the same, and the libraries loading when it was reached begin its source,
so a producer that needs the library it generates, at once or once another
producer has run, is an import cycle and never runs. A producer is also
handed the scripts whose builds it is part of, after the tools on its
command line, and build-script refuses one of them: a script that embeds
its own build fails with the chain of scripts, where it would otherwise
build without end.
Scripts and targets
A script is a source file that defines main, and a target is what runs
it. snail-scheme behaves like an interpreter first and a compiler second:
./snail-scheme run --target node examples/fibonacci.sld
./snail-scheme build --target browser --release src/apps/siegework/main.scm
There is no project file, no target registry, no planner and no development service: what is built, and for which platform, is on the command line. Workspaces and builds describes the output and how one build embeds another.
The workspace
A workspace is a folder that contains src/. Every library lives under src/,
at the path its name gives, and every import resolves there. That is the whole
rule. It is built for this repository’s monorepo and nothing more. The editor’s
open folder is the workspace the language server uses.
A script may sit anywhere in the workspace. Since imports resolve under src/,
an application keeps its script beside its libraries:
src/apps/siegework/main.scm imports most of its code from
(apps siegework ...).
Scripts
A script is a source file anywhere in the workspace. It imports libraries
and defines main, its entry, whose parameters are the capabilities it
asks its target for, as examples/fibonacci.sld does:
;; The smallest complete program: a typed recursive function and output.
(import
(snail core base)
(snail core io))
(define (fibonacci (n I64)) (→ I64)
(if (< n 2) n (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
(define (main (out OutputPort)) (→ Unit)
(display out (fibonacci 30))
(newline out)
(unit))
A top level holds definitions alone, a script’s as a library’s: nothing
runs when a library loads, and what runs when a program starts is its
main. A top-level statement would have nothing to write to, since a
program is handed each capability it uses, so the parameters of main are
where a program says what it needs.
A GUI program is an ordinary script that hands control to a library’s event
loop, in the style of Rust’s winit:
its main builds a handler, a record of functions, and calls
(run-scene dom events storage handler). Such libraries are
conveniences, not part of the language or the toolchain.
On the page a program cannot block, so main runs as the scheduler’s first
task, and run-scene waits for events as a task does
(application model).
Targets and capabilities
Each build names its runtime target explicitly, with --target, such as
--target node or --target browser. Nothing infers a target.
What a platform offers is split into capabilities, one value for each service: an output port, an input port, the page’s document, sockets, processes. There is no marker for a platform as a whole, and no object that holds everything a host has.
An entry’s parameters, main‘s or an exposed function’s, are what it
requires, as a dependency-injection interface. A target is a library,
(snail target node) for instance, and provides a type by exporting a
function of no parameters that answers it. The build calls each entry with
what the providers of its parameters’ types answer. A parameter of main
whose type the target does not provide is a build error naming it
(capabilities).
The host’s capabilities answer by calling the host through extern
imports. An extern’s type is its library author’s claim, trusted as
written: a file or socket extern is declared as a plain function, and its
library keeps it behind the capability, so code outside reaches the host’s
files only through an Fs. Building a sensible abstraction over its
externs is the library’s job. The foreign functions that were pure, the
math functions, Unicode tables and float printing, have moved into
snail-scheme code.
Code meant for several targets asks only for the capabilities it uses. A
library that writes text takes an OutputPort, not “Node”, so any target
that provides one can run it. A capability’s library declares the type and
the function that makes the host’s; whether a target provides it belongs to
the target.
There are two targets, each a library under src/snail/target/:
node, the program on Node (host/native);browser, the program in a page (host/browser).
A target exports its providers and start, which runs main as the first
task of the host’s scheduler.
Capabilities fall into three groups. The portable subset is what both targets provide, and what a target for another host, such as workerd, would provide too; a library that asks only for these runs anywhere.
| Portable capability | Library | On Node | In a page |
|---|---|---|---|
Host | (snail core io) | makes any capability below | makes any capability below |
Arguments, ProcessEnvironment | (snail core io) | the command line, variables and working directory | none, and no working directory |
OutputPort | (snail core io) | standard output | the console |
Clock | (snail core io) | the monotonic clock | the monotonic clock |
Resources | (snail shell resource) | files beside the module | files fetched beside the module |
Wasm | (snail shell wasm) | Node’s WebAssembly | the page’s WebAssembly |
Tasks need no capability: any code may wait (suspension, tasks).
Node adds the local machine:
| Node’s capability | Library |
|---|---|
InputPort | (snail core io), standard input |
Fs | (snail core io) |
Files | (snail shell async-files) |
Processes, Signals | (snail shell process) |
Tcp, Udp | (snail shell socket) |
Web | (snail shell web) |
A page adds itself:
| The page’s capability | Library |
|---|---|
Events, PageStorage | (snail shell page) |
Gpu | (snail shell gpu) |
Dom | (snail shell dom) |
Fetch | (snail shell fetch) |
FilePicker | (snail shell files) |
A program on Node that draws asks for the Host and makes its Gpu from
it, with host-gpu, so one that draws nothing links no device
(Host).
The tables state the rule the build checks, so changing what a host
provides means changing them and the target together: a program that asks
for Tcp fails to build for browser instead of trapping when it
connects.
A script that imports (snail shell assembler) links with the runtime that
includes the assembler’s services, and any other links with the smaller one.
Assembling is deterministic, so it is no capability.
Commands
Every command that builds takes the same build flags, parsed in one place and documented once:
--target TARGET, required: the runtime target.--release: a release build. Without it, the build is a debug build.
The commands:
snail-scheme build FLAGS FILEbuildsFILE.snail-scheme run FLAGS FILE [ARGUMENT ...]buildsFILEexactly asbuilddoes, then runs it on Node. Its output stays on disk, so a failure can be diagnosed, and future caching needs no new path.snail-scheme lspserves an editor (the language server), andsnail-scheme formatformats standard input onto standard output.
A producer that calls the compiler passes the same flags, as a record, so a build embedded through a generated library is configured the way the command line configures one.
No command takes an output path. A build of src/apps/siegework/main.scm writes
under build/src/apps/siegework/main, the script’s path without its extension.
That path cannot collide, and it is stable, which is what future caching needs.
Output: one linked module
Every build is fully linked: the whole program compiled as one module and
fused with the runtime, main.wasm, with the files it links under
store/sha256/ab/abcdef…, each named for the SHA-256 of its bytes. Each
is a hard link to the one copy in the workspace’s store,
build/.snail-store, which every build of every script shares.
Node and a page each run it directly. The output
folder can be served or run as it is, as python3 -m http.server --directory build/src/apps/siegework/main serves a browser program.
A release build, --release, also optimizes the module with Binaryen’s
wasm-opt -O2, which can inline the runtime’s functions into the program.
That is the modes’ one difference.
Linked files
link-file takes a path relative to its library, .. included, or an
absolute one, so a library may link a producer’s output. Every build
places each linked file in the workspace’s store, named by its digest, and
the generation’s store/ holds another name for it, as above
(linked files). Browser programs reuse the linked bytes from an origin-wide Cache Storage cache keyed by SHA-256. A fresh build can reuse every digest it shares with a previous build. HTML and the executable still load on navigation so the page can discover the current build.
A program that serves another, such as a server shipping its browser client, embeds that build through a generated library whose producer builds it (embedding a build). A producer that imports the compiler compiles the compiler on every build; that is accepted for now.
Static resource catalogs
Put the files a script publishes in a directory beside it with the same stem, for example main.resources/maps/city.bin beside main.scm. Both browser and Node builds publish resources.json and store/sha256/AB/DIGEST. The catalog maps each relative name to its SHA-256 and byte length. Files with identical contents share one object. The directory may contain regular files and subdirectories. Changes to its contents update the catalog without adding imports to the client’s Wasm.
Serve the generation under any URL prefix. Keep the catalog revalidatable and give the digest URLs a long immutable cache lifetime. A Snail server can link the generation using (snail shell project embed) and mount its catalog with (snail shell static-resource serve). A browser uses (snail shell static-resource) to request the catalog and acquire files. Resource libraries
Not yet
- Reuse between builds, and sharing work between a producer and its consumer.
snail-scheme watchand live reload, removed; they come back only if they are needed.- Reclaiming the store.
Development toolchain
Every build compiles the whole program to one module and fuses it with the
runtime (output directories). A release
build, --release, also optimizes it with Binaryen’s wasm-opt. Stage 0
links a single program into one module the same way.
| Command | Build |
|---|---|
snail-scheme build, snail-scheme run | Debug: one linked module |
snail-scheme build --release, make site | Release: the same module, optimized |
A script, a single source file, is built and run with an explicit target,
node or browser
(scripts): ./snail-scheme run --target node FILE [ARGUMENT ...]
builds it into build/PATH, PATH being its path in its workspace without
the extension, and runs it, and ./snail-scheme wat --target TARGET FILE prints its whole
program’s text. Its main is its entry, whose parameters are the
capabilities it asks its target for. A program links with the toolchain runtime, whose services
include the assembler, exactly when it links (snail shell assembler).
wat runs no producer, so a script that reaches a generate-library
recipe must be built instead.
Node runs the command line and every program it builds
(host/native/run-snail.mjs). Stage 0 links the command line with
snail-link, a small native program in crates/snail-scheme-support
(running and linking). One native
snail-scheme that replaces the launcher is proposed in
#562.
The builds chapter defines workspaces, output directories and embedding one build in another.
snail-scheme run --target node FILE [ARGUMENT ...] builds the script and
runs that exact completed generation on Node, passing the arguments after
the script unchanged. The program inherits the caller’s working directory,
environment and terminal IO.
After compiler and scratch cleanup, the native command replaces itself with the runtime using Node’s process replacement. Its PID, exit status and signals therefore belong to the application. This uses the existing Node 26 POSIX host. Compilation and generator execution retain the cold builder’s synchronous behavior.
Contributor checks
make test runs the compiler’s unit tests on Chez (tests/unit.scm), then
tests/run.mjs: every program fixture, built by ./snail-scheme build as a
user’s is and run on its host, and the host, build and application checks.
A fixture NAME.sld must print NAME.out, or fail to build with each line
of NAME.err. Each build has private scratch and its own output, so eight
run at once. A fixture folder with libraries of its own, as
tests/programs, is a workspace: they live under its src/.
CI reports formatting, both Rust crates, tool building and the snail-scheme suite
as separate steps under the required Complete correctness checks job. It
caches Cargo’s test targets and the driver’s native and WASI target
directories; Cargo checks their freshness on every build. Test debug symbols
and incremental compilation are disabled there to keep these caches small.
The bootstrapped compiler has a separate exact cache key covering its source,
bootstrap hosts, Rust runtime and pinned tools. On an exact hit, CI refreshes
its timestamp to account for checkout’s new source timestamps. A changed
input rebuilds the bootstrap, and test outputs are rebuilt on every run.
Assembly, linking and optional optimization
(snail shell assembler) offers assemble for an independent module and
link for a standalone program, taking program text and runtime bytes and
returning a Result of bytes or an error message. The toolchain runtime’s
assembler feature provides wat and wasm-fuse; plain program runtimes
carry neither. Stage 0 calls the same Rust functions through snail-link.
No Binaryen installation is required.
Linking resolves the program, runtime and diagnostics/cleanup adapter before
removing snail:* and diagnostics/* exports. All other exports survive,
including GC globals and dynamic functions. A second wasm-fuse pass prunes
unreachable definitions and remaps debug names. Function bodies are not
optimized here; a release build then runs wasm-opt -O2 over the linked
module (output directories). The internal
source driver also continues to accept --release.
Optimization can be a separate user-owned step, with Binaryen installed independently:
wasm-opt program.wasm -o program.optimized.wasm -O3 \
--enable-gc --enable-reference-types --enable-tail-call --enable-bulk-memory \
--enable-nontrapping-float-to-int --enable-sign-ext --enable-mutable-globals \
--always-inline-max-function-size=40 --converge
Optimize a copy, outside a published generation and its cache. Avoid
--closed-world: hosts and separately linked libraries can retain function
references and access each other’s GC values.
Editors
snail-scheme has no editor of its own. An editor gets what it needs from two
pieces in the repository: a tree-sitter
grammar for what it can tell from the text alone, and snail-scheme lsp, a
Language Server Protocol
server, for what takes the compiler. editors/zed is the extension that puts
them together for Zed.
The grammar
editors/tree-sitter-snail-scheme parses the reader’s data: lists in () or [],
#u8( byte arrays, quotes, strings, and the comments the reader discards,
; lines, nested #| |# blocks and #; datum comments. Its external scanner,
src/scanner.c, reads every other token to a delimiter and classifies it as
token-kind in src/snail/shell/compiler/read.sld does: a boolean, a number,
a character or a symbol. A token the reader rejects, such as . or #x1F, is
a symbol to the grammar, so Chez’s own files still parse. The grammar is for
editors alone; the compiler keeps its reader. The generated parser is
committed, and tests/tree-sitter.mjs (in make test) checks that
grammar.js still generates it, runs its corpus tests and parses every
tracked Scheme file without an error.
The grammar colours nothing: the server does. Zed requires a grammar for a
language, and its queries live with the extension, under
editors/zed/languages/snail-scheme/: brackets.scm, indents.scm and
outline.scm, which lists a library by its name and then its definitions.
The language server
snail-scheme lsp is the command line’s lsp, (snail shell lsp). It reads
Content-Length framed JSON-RPC on standard input, answers on standard output,
and serves the workspace at the root folder the editor opens, which holds
src/. It offers:
- Diagnostics. When a file is opened and on each save, it checks each
open document as a build would, producers and all, with scratch under
build/snail-run/, writing no output (check-scriptandcheck-library). A.scmfile is a script, checked as a page when apublic/folder is beside it and for Node otherwise; an.sldfile undersrc/is checked as the program that imports it. Each failure is reported on its file, once however many documents meet it, over the range(snail shell highlight)derives for its point: the token there, or the datum that starts there. A file is cleared once it checks. A failure with no point, or in a file that does not exist, is reported on the document checked. A check reads the disk, so diagnostics follow what was saved. - Formatting. The open text, formatted by
(snail shell format), as one edit of the whole document. - Hover and definition. The last checks’ programs give each
variable’s use its type and the binding that introduces it: a top-level
definition, perhaps in an imported library, a
letbinding or a lambda’s parameter. Hover shows the name, its type and the library it comes from; definition goes to the name in its binding form. - Colours. Semantic tokens for the whole open text, from
(snail shell highlight)’s classes: comments, strings and characters, numbers, keywords and booleans, type names, and the name a definition introduces, as afunctionwith thedeclarationmodifier. Other names and punctuation are left to the editor. A token that spans lines is split at each line’s end, since a client need not accept one that does not.
Positions are counted in UTF-16 code units, as the protocol’s default
encoding is. tests/lsp.mjs (in make test) drives the server through
each of these on a workspace of its own.
Zed
editors/zed is a Zed extension: extension.toml names the grammar, by
repository and revision, and the language server, and languages/snail-scheme/
holds the language’s configuration and queries. Zed runs extensions in a
wasmtime without its garbage-collection feature and loads only Rust, so the
extension is a small Rust crate, src/snail_scheme.rs, compiled to
wasm32-wasip2. It only finds the command: the binary path the user’s
settings give under lsp.snail-scheme, then a snail-scheme on the
worktree’s PATH, then the repository’s own ./snail-scheme launcher. To try it, choose
Install Dev Extension in Zed’s extensions page and pick editors/zed.
Zed colours with the server’s semantic tokens once a setting asks:
"languages": {"snail-scheme": {"semantic_tokens": "full"}}
VS Code
editors/vscode is a VS Code extension of a few lines of JavaScript,
extension.js, on vscode-languageclient. It contributes the
snail-scheme language for the files Zed’s extension claims, with
language-configuration.json for comments and brackets, and no TextMate
grammar: the server’s semantic tokens colour the text. It starts the
command the snail-scheme.path setting names, else the workspace’s
./snail-scheme launcher, else snail-scheme on PATH, with lsp. To try
it, run npm ci --prefix editors/vscode, then choose Developer: Install
Extension from Location… and pick editors/vscode. tests/vscode.mjs
(in make test) loads it with stand-ins for both modules.
The formatter
The command-line formatter, snail-scheme format (and scripts/format-scheme,
which runs it), runs the same library as the language server, in the same
program. With no arguments it formats
stdin to stdout; optional --width COLUMNS selects a positive width instead of
100. --check FILE ... reports every file needing formatting on stderr and
exits with status 1; --write FILE ... updates only changed files.
make check, make format and snail-scheme lsp all use this implementation.
Binding forms are recognized by name: let, let*, and any name ending in
-let or -let*. A user-defined result-let* or retry-let needs no formatter
registration. Bindings align with each other, and the body is indented two
spaces from the form’s opening parenthesis. Forms ending in -let also use
named-let layout when a loop name precedes the bindings. This is a formatting
convention; the formatter does not expand macros or inspect their definitions.
Browser packaging
Packaging has three steps: copy host and public assets, generate the default
manifest only when the public folder has none, and add typed page metadata. The
manifest is a normal bundled file. (snail shell project web-app) renders
metadata constructors with HTML attribute escaping and inserts them at the
page’s head boundary, preserving the supplied HTML, head attributes, comments
and doctype. A module manifest’s snail-scheme datum text travels in a meta element’s
content attribute; browser decoding precedes datum parsing. Scheme fixtures
cover this encoding and page construction; Chromium checks the browser’s
resolved URLs and standards mode.
Browser bundles expose a web-app manifest by default. The
manifest gives a standalone window, the application name, theme colors, and
192/512-pixel icons. A browser target can provide public/manifest.webmanifest
to replace the default entirely, including its icons and display mode; it is
served unchanged. The builder links the manifest from UTF-8 index.html pages.
The web manifest’s relative start_url and scope resolve at the output
directory, and the default identity is that resolved start URL (no explicit
id is emitted). A bundle’s relative manifest link works under a deployment
subdirectory. HTTPS or a loopback origin is needed for browser installation.
These manifests do not add offline caching or a service worker.
Code highlighting
The book colors code with (snail shell highlight), and so do editors,
through the language server.
It walks text with the compiler reader’s own lexical rules, the “Lexemes”
section of src/snail/shell/compiler/read.sld: what starts at an index, where
it ends, and what a token’s text is to the reader, a boolean, a number, a name
or an error. The reader is built on the same functions, so a highlighter
cannot disagree with it about where a string, a character such as #\(, a
comment or a token ends. The classifier adds what a reader discards, the
comments and whitespace between data, and it never fails: a string the text
ends inside is a string to the end, and a token the reader rejects, such as
., is classed invalid. Its tokens tile the text. The core forms it colors
as keywords are the compiler’s own list, core-keywords in core.sld; the
derived forms and declaration words are listed once in the classifier. It
also marks the name a define, define-syntax or : introduces, and colors
what #; comments out as a comment.
mdbook runs scripts/highlight-book as a preprocessor, which book.toml
registers after the links preprocessor has included the examples. It is a
snail-scheme script, tools/highlight-book.scm, which reads the book as mdbook
writes it, JSON on its standard input, and writes it back. It replaces each fenced block whose language is scheme with a
<pre><code class="nohighlight"> of tok- spans, one per token but
whitespace, which doc/highlight.css colors for mdbook’s light and dark
themes; highlight.js skips code of class nohighlight, and still highlights
the book’s other blocks. scripts/highlight-book runs it with
snail-scheme run --target node, so mdbook build works from a fresh checkout
that can build the compiler. tests/highlight-book.mjs runs the preprocessor on a small book.
Proposed: once the book is itself built by a snail-scheme script, the classifier can run
in a generate-library recipe that writes the highlighted pages, and the mdbook
preprocessor goes away.
Application and networking integration
A program target runs with snail-scheme run. A browser target’s output is a
static directory any HTTP server can serve. Durable
state remains proposed work.
Production serve and package installation still need their own contracts;
neither is a current public command.
The concrete socket capabilities provide TCP streams and UDP datagrams to native CLI programs, and a test makes its own. Their native owners define bounded buffering, cancellation and close behavior. UDP keeps message boundaries without guaranteeing delivery or order.
The HTTP library provides bounded parsing, response framing and one complete exchange over TCP. Wait on the host by ticket, as the runtime’s sockets do, and test real sockets as well as intercepted operations. Networking work tracks this boundary. No transport hierarchy or generic provider framework is needed. TLS, HTTP/2 and deployment infrastructure are separate work.
Traces
Measure performance from a trace: a file in Chrome’s JSON trace format,
which Perfetto opens and chrome://tracing
reads. A trace shows where a run’s time goes among the program, the host
and the device, and it measures every run the same way, so compare two
runs by their traces, not with a timer added for the occasion.
- A program on Node writes one as it ends when
SNAIL_TRACEnames the file:SNAIL_TRACE=run.json node build/.../main.mjs ARGUMENT .... Node keeps every span until then, so trace a short run, such as a few hundred of the trainer’s steps. - A page traces when its URL’s query has
trace.TRACE=page.json node tests/browser/page.mjs URL SCREENSHOT SECONDSopens the page so and records Chromium’s own trace of the visit: the page’s spans beside its main thread’s tasks, V8’s work and the GPU process’s.startTraceandstopTraceintests/browser/chromium.mjsdo the same for any test.
The spans are the host’s, in host/browser/trace.mjs, and they stay in
the checked-in code, costing one test of a flag in a run that is not
traced. On the main track, each turn is a turn of the scheduler, the
time the program’s own code ran, and each gpu submit is a submission;
a wait is a host operation that a task waits on, such as gpu read,
gpu done or decode image. On a device with timestamp-query, a
traced run times every pass, and the gpu track shows each pass for as
long as the device ran it, named for the pipelines it set. A pass the
program times itself keeps its own queries. WebGPU puts timestamps only
at the ends of passes, so a pass is the finest span the trace has, and
the queries cost the device a little. The device’s clock has an origin
of its own, and a pass cannot start before its submit, so the host puts
the device’s clock as early as it can be with no pass before its submit.
Durations are exact, and starts are exact once the device has been idle
at some submit. A browser
rounds the device’s times to 100 μs unless its WebGPU developer features
are on, as they are in tests/browser/chromium.mjs. On a page, a span is
a performance.measure, which Chromium’s trace records under
blink.user_timing. Node’s traces do not record measures, so Node’s host
writes its file itself, a thread for each track.
A span marks a boundary where time passes from one party to another. When
measuring something calls for a new one, add it with span or traced
and keep it, so that later measurements see it too.
(profile-program gpu program) ((snail shell tensor lower)) is the
finer tool for a tensor program: it times each step in a pass of its own.
Process boundaries and future debugging
| Boundary | Information crossing it |
|---|---|
| Editor ↔ language server | LSP over standard streams: open text, saves, diagnostics, formatting edits, hovers and definitions. |
| Browser ↔ application server | Ordinary HTTP. |
A future debugger attaches to a program’s process and build. Its inspector
endpoint expires with that process. run-snail.mjs executes Wasm on the process’s main
thread, so attachment reaches the program itself. Debug commands use the inspector
connection rather than compiler requests or parsed stdout. The editor
stays responsive while an application is paused. Source mappings and
breakpoints require a separate compiler/assembler proof; debugger support is
not implemented. Editor and debugger work
tracks these extensions.
Build-tooling and package decisions track complete rebuilds, producer-input observation and package installation.
Compiler architecture
The compiler has four main phases: expand, check, prepare, and emit. Reading supplies located syntax. Preparation closes specialization requests and produces fixed concrete code. Emission consumes that result without revisiting source semantics.
text ──read───▶ located syntax
──expand─▶ resolved program unique names, declarations, field paths
──check──▶ typed program types, instances
──prepare▶ concrete code suspensions known, yield points explicit
──emit───▶ WasmGC text ──assemble/link──▶ executable module
Prepared contains declarations, concrete function definitions, an optional
root entry, exports and host exposures. Every definition is function code.
A top-level value is one too: the expander wraps its initializer as
(prim:cached-thunk (lambda () value)) and turns each read into a call, so
no later pass knows values exist. The backend emits that definition as a
function over two globals, a state and a slot: it runs the initializer on
the first call, panics if the initializer reads its own value, and answers
the slot afterwards. A value whose initializer is a literal needs no slot
and is the plain function that answers it.
The compiler is written in snail-scheme under src/snail/shell/compiler/.
Its host boundary consists of (snail core base), (snail core table) and
(snail core io).
Chez runs the source closure for stage zero; the normal
compiler is itself a linked Wasm program. Most passes thread state through
pure functions. The emitter uses a locally owned mutable Module to collect
Wasm declarations and intern types. Neither representation requires Ref.
A global or data segment that a module declares once, such as a string
literal’s, comes from a function wrapped in cache and held
in a top-level value: its key is the module and the text that names the
item, so a second use skips the declaration. Those caches live as long as
the compiler process, and so does each module they were asked about.
Every build compiles the whole program to one module and links it with
the Rust scalar services, as stage 0 does the command line.
Start with examples/fibonacci.sld, inspect its output with
./snail-scheme wat --target node examples/fibonacci.sld, then follow the passes
below.
The passes
Reading and expansion
read.sld turns text into atoms, identifiers and forms, each carrying a
Loc. The reader’s token boundaries are also used by syntax highlighting.
It decodes generated-library syntax directly from bytes. A pass stops a
compile by suspending to its prompt, stopping, with either diagnostics
or a typed request for a missing input; compiling is that boundary for
each compiler entry.
core.sld defines Type, Scheme, class evidence, expressions, patterns,
declarations and the program tables shared by the passes. expr-children
is the common structural inventory; each analysis still decides which
children execute, bind names or start a new scope. Data fields contain a
name and type, with no mutable/immutable flag. Every source field has one
runtime slot.
library.sld reads a library’s file before any of it is expanded: where the
source is among the search directories, and what the file declares, a
define-library’s sections through its cond-expands or a
generate-library’s producer program. It knows no binding and holds no
state.
expand.sld alone knows binding syntax. It loads libraries, resolves import
sets, expands hygienic syntax-rules, assigns unique names and converts
forms into expressions and declarations. Top-level names are discovered
before their bodies, allowing recursive and mutually recursive functions. Local bodies remain sequential. Typed define and bodyless declare share a header grammar here; Fn is the built-in callable type former.
Struct field paths remain unresolved only while the receiver type is
unknown. Once its nominal type is known, checking substitutes the record’s
type arguments and resolves each label to a declared field. Each hop becomes
an ordinary accessor operation. Nested fields follow object references;
there is no inline-layout path to reconstruct. set! is a form, not a
function: (set! (● receiver label ...) value) resolves its last label the
same way and becomes a call of that field’s writer, so no later pass sees a
place.
Expansion generates constructors and field operations. A derived instance
is a use of a syntax-rules macro that the class’s library defines beside
the class, derive-serialize in (snail shell wire) for one; the expander
writes only that use, from the declaration’s head, cases, field labels and
field types. derive-pod alone resolves where the declaration is, which
imports (snail shell graphics pod) to derive it.
Every body and its evidence then go through ordinary checking.
A program’s entry is its main: a top level holds definitions alone, and
a producer recipe gets an explicit entry function. The expander writes the
entry’s start, which calls main with what its target provides for each
of its parameters’ types (“Entries”).
Named record construction
Resolution turns new into a constructor and a list of initializers in written
order. Each initializer carries its resolved slot and a fresh temporary name;
the slots form a complete permutation of the record’s fields. The checker
supplies the instantiated field types before checking each value, so callbacks
and generic records retain contextual typing. It then erases named construction:
fields already in declaration order become an ordinary constructor call;
reordered fields become sequential typed bindings followed by that call.
Specialization and Wasm emission use their existing operations.
Chez performs the same ordering at macro expansion time, using private
constructor procedures and hygienic record descriptors, with no runtime keyword
lookup for construction.
Types and conversions
check.sld infers types, solves class requirements and
records selected instance evidence at uses. Library checking is independent
of importers. Named functions state their parameter and result types;
polymorphic definitions state their quantifiers and requirements.
A function’s type has no row: types unify, and nothing is subsumed. What a function may reach of the host is in its parameters, and the checker tracks nothing about what a call does.
Explicit (Any value) and (downcast T boxed) become BoxAny and
Downcast terms. Packaging preserves type identity; extraction returns Some
only for the requested type, and None on mismatch. Neither inserts conversions
at unrelated boundaries.
A top-level value’s thunk takes nothing, so its initializer holds no
capability. The checker knows a value in one place: it does
not generalize the thunk’s type, and refuses one its library leaves
undecided.
Specialization and preparation
specialize.sld is one call, specialize: from the program’s entry and
exposures it copies each definition reached once for each set of types it is
used at, and answers the copies with their declarations, each copy’s type. It
reserves a copy’s name, with its type, before copying the body, which
permits recursion. A copy’s name keys its types. Asking for a
reserved name again does not spend the finite specialization budget.
prepare.sld specializes the whole reachable graph before reading any
body, and then finds what no type says: which calls may suspend. For each
definition, and for the function values of each type, it writes down what a
call may suspend to, in terms of the calls it makes, and solves those
equations to their least answer. A suspension is named by its prompt when a
top-level value holds it, so a with-prompt of that value is known to
catch it; any other prompt is known only by whether anything may resume it.
Lowering uses a subset of the same expression language, not a separate CPS
language. A call that may yield stays in tail position or is named by a
let; operands that execute before it are named first. The backend can
therefore test for a pending yield before executing the rest of the
expression. Code that never suspends is left as it was.
WasmGC emission
wasm.sld selects one representation per concrete type. Numeric primitives
and booleans are Wasm scalars. A record is always a GC struct reference;
its field is one scalar or reference slot. An enum has a tagged base and
case subtypes. An array is an exact-sized WasmGC array; its length comes from
the array, and there is no capacity or replaceable storage. No object
carries a header beyond its fields. There is no inline record flattening or
reconstruction on field writes.
Completed source references are non-null. Internal Wasm storage and signatures
admit null so uninitialized slots and suspended results need no fabricated
source value. A control return leaves zero or null; its caller checks the yield
record before reading the result. Tail calls forward
that outcome directly. Normal construction and initialization establish when
a slot contains a source value. Host handovers keep their non-null contracts
except for the explicit nullable Option Any encoding, and dynamic type tests
still reject null. Linked modules must use the same internal calling convention.
A direct tail call to the current function can branch to a Wasm loop. This
also covers a named let and calls through a proven alias of its recursive
closure. The emitter evaluates all arguments left to right, then assigns
parameters from the operand stack in reverse order. At the loop header it
clears reference locals from the previous invocation. Captured bindings are
loaded once on function entry. The emitter keeps a Wasm tail call when
a call changes a managed parameter. Record construction and list traversal
were faster with that transfer in the WasmGC benchmarks. Tail calls to
other functions use return_call, and indirect tail calls use return_call_ref.
A pure replacement creates a shallow copy of the record with one field replaced. A mutable update writes the field in place, after both its receiver and its value have run. Array copies support overlapping ranges. Strings remain character arrays; conversions copy storage, and host byte staging copies only an array’s live prefix.
The emitter interns concrete Wasm types before traversing their fields, allowing recursive object graphs. Finite budgets diagnose expanding type or specialization families instead of exhausting the host. Ordinary recursive nominal types reuse their existing type entry.
The cache and lru-cache primitives preserve their callback’s parameter
types and result type. The checker requires a known function
signature at final inferred types, including when a primitive is used as a
function value.
Preparation rejects raw Funcref keys. The Wasm
backend builds an ordinary closure capturing its callback and a private typed
hash table; no module globals are involved. The Chez adapter implements the same wrapper and key
semantics. See cached functions.
Suspension and frames
suspend sets a yield record: the prompt it is aimed at, its value, and
whether anything may resume it. As execution returns through named yield
points, the remainder of each scope becomes a frame: a closure of its join
function and the locals its body reads. The with-prompt of the record’s
prompt takes the frames as a continuation and calls its handler with a
resume that holds it. Calling resume marks the continuation resumed,
detaches the frames and executes them from inside out, under the
with-prompt again; calling it again panics. A with-prompt a yield
passes on its way out is saved among the frames as one frame. A yield
nothing can resume saves no frame, and a resumption that is never called
is reclaimed like any other value.
A prompt counts its with-prompts that are running, so suspend panics
when there is none to catch it. Three places are the backend’s own code
and cannot be left as a frame: the loop that generates an array, which
lets through only a yield nothing resumes; a cache and a top-level value,
which keep nothing of a call that yielded; and a host entry, which a yield
may not leave.
This is ordinary calls and explicit frames, not stack switching: any
WasmGC engine executes the same linked code, and no JavaScript continuation
mechanism is required. call/cc, dynamic-wind and multishot continuation copying are
not language features.
Whole programs
The unit of checking is a library, and the unit of compilation is the
program (source->wat in src/snail/shell/compiler.sld). The checker
settles each library’s types before it checks the libraries that import it,
so a definition’s type comes from its own library and not from how an
importer happens to use it. Emission then keeps only what the program
reaches from its entry and its exposures: each generic function is
specialized at the types it is used at, and every call is a direct call
within the one module. Capabilities travel as arguments, and the one global
of suspension is the yield record, which the module declares and exports.
Every invocation expands current sources, checks every library, specializes and emits every reachable function again. There is no compiler Session, interface fingerprint, invalidation graph or retained checked-code/Wasm cache. Each build rebuilds its program and runs its producers. A program was once also compiled a library at a time, each to a module of its own, linked when it started; that went with the reload it served.
Linking
A build fuses the program’s module with the runtime’s into one
(link in (snail shell assembler), the Rust backend stage 0’s
snail-link also uses), so calls into the runtime are ordinary calls, which
wasm-opt can inline in a release build.
WebAssembly treats two GC types as the same only when their whole recursion groups match. The backend puts each type in the smallest recursion group it can have: the strongly connected component of the graph of references between types, ordered by name, with the groups it refers to emitted first. A module a program loads while it runs that declares the identical group shares the type, by the engine’s canonicalization. A case of an enum without fields declares no type of its own.
snail-scheme types are checked at compile time, each library against its
imports. A value crossing as Any keeps its nominal type identity for
explicit downcast checks.
Linking by hand
A program loads modules while it runs with (snail shell wasm).
compile-bytes compiles a module, module-imports lists its imports, and
link-module accepts one explicit Provider per import in order. A provider
is an instance’s export, a host service, a constant function, or a function
that fails if called. Missing or incompatible providers return LinkFailed.
Linking runs _initialize when present; the loader calls main separately.
module-export returns an untyped Funcref. unsafe-cast wraps it in an Fn
closure at the requested type. The Wasm
cast checks representation, not snail-scheme nominal identity: the caller
must establish that contract. run-export calls a scalar export by name.
loading-program identifies the loader. bind-runtime selects the loaded
program’s runtime for staging bytes and reporting errors without changing the
loader’s identity. No host registry or plugin namespace participates in
linking.
tests/programs/wasm-linking.sld checks provider selection and failures.
wasm-instance-identity.sld verifies that existing imports keep their original
provider when a new link uses another instance, and that linking consumers
does not initialize their providers again. Both run on Node; the identity
test also runs in Chromium.
Hosts
The host compiles bytes, lists imports, binds explicit providers and finds exports. Node and the page install these operations; the page’s are exercised by the Chromium fixture.
Every import module a host provides is named for the runtime interface it
implements, snail.runtime.… (#566): snail.runtime.link,
snail.runtime.resource and snail.runtime.gpu on every host,
snail.runtime.wasm, snail.runtime.native.socket,
snail.runtime.native.process, snail.runtime.native.async-files and
snail.runtime.native.web on Node,
and snail.runtime.browser.events, .storage, .dom and
.fetch on the page. A (snail runtime …) library declares one of these
interfaces as externs, and nothing else, so it has no items and emits no
code: the program’s module imports from the host itself.
The Rust support module, built from crates/snail-scheme-support, is
snail.core.support, which a build fuses into the program’s module.
Compiler inputs
Each compiler invocation takes library directories, the current generated-library provider and its target. The provider receives each producer with the libraries loading when it was reached, and answers the bytes of the syntax the producer wrote.
The builder’s provider, generated-syntax in
(snail shell compiler inputs), keys a producer by a hash of its text,
producer-text: the library directories its imports resolve in, then its
program, since two builds with different directories may resolve the same
recipe’s imports to different libraries. It reads KEY.syntax from the
compile’s scratch when a producer has already written it there. Otherwise it
prints the producer as KEY.sld and requests it. The producer names its
recipe after its imports, (recipe "src/sample/blob.sld"), and a path its
own forms write, as a link-file in the recipe’s expression, resolves
against that file rather than the printed copy (written-in in
expand.sld), so a recipe links files beside itself wherever its producer
is printed. The recipe’s path is part of the producer’s text, and so of its
key, since the files it links depend on it. The producer computes the
recipe’s expression in a task, as (write-generated-library producer-fs producer-arguments (lambda () EXPR)), so the expression may read what the recipe links with
read-resource, run processes and build other scripts
(embedding).
Generated syntax is obtained before expanding its library. A build runs each producer its compiles reach once, and the output serves every later compile in that scratch. No build keeps a producer’s output for the next: what a recipe fetches, it keeps itself, pinned by a digest (what a build keeps).
A producer is compiled as a program of its own while the library it generates
is still loading, so the expander’s stack of loading libraries crosses into
that compile. generated-syntax prints it as the producer’s first form,
innermost first, and expand-program starts a program that begins with it
with those libraries loading:
(generating "sample.knot")
(import (snail core base) (snail shell syntax) (sample knot-helper) ...)
A producer that imports, along any chain, the library it generates is then an
import cycle, library import cycle through sample.knot, rather than producers
nesting without end; tests/programs/error-generated-cycle.sld is that case.
The producer’s key leaves the generating line out, since what it writes does
not depend on the chain that reached it. The Chez driver also
refuses a producer requested while it is being built, a backstop should the
stack ever miss a cycle.
Missing inputs and retry
The compiler cannot start a producer. A pass that needs a producer’s output
it was not given stops the compile (stop in
(snail shell compiler read)) with (Requested request), where the
CompilerRequest is (GenerateInput key). The compile’s prompt answers
Never, so nothing after it runs and its yields save no frames. No
signature on the way from the request to an entry point says so, and each
entry point takes it with compiling, which turns the compile into a
Result, here (Err (Requested request)), as it does a source error into
(Err (Failed diagnostics)).
The project builder, (snail shell project build), calls the compiler in its
own process and takes each compile’s Result (producing): a
failure stops the build with its diagnostics, and a request runs the printed
producer, which writes its output into the scratch, and compiles again. No
request file is written or parsed, and nothing traps.
The command-line driver, (snail shell compiler driver), which stage 0 runs
to bootstrap the command line, runs no producer: a program that reaches a
generated library fails there, and is built by snail-scheme build.
Linked files
A linked file’s bytes are an input of the compile, as their digest: the
module imports its handle under that name. Each build binds the current linked
files during expansion. A missing file fails with the library and path;
changed bytes bind a new digest. The store remembers each digest a build
read, with the file’s size and modification time, in
build/.snail-store/digests, and a compile trusts one while its file keeps
both, as make trusts a time, so a large file is hashed once rather than
every build. Every build compiles all libraries and
places every linked file as an object of the workspace’s store,
build/.snail-store/sha256/AB/DIGEST, named again at the same path under
store/ beside the program’s module, checking that the bytes it places
have the digest the compile read; a file edited during the build fails it,
and the next build compiles against the new bytes. The bytes
under such a name never change, so a server can let a browser cache them
for good.
Supporting modules
| Path | Responsibility |
|---|---|
src/snail/shell/compiler/driver.sld | Typed source invocation shared by both hosts, compile-arguments: a compile that fails, or that needs an input after publishing its request, exits with status 1. The command line’s compile action and Chez’s compile mode call it; the command line’s wat uses the same compiler. |
host/chez/load.scm | Chez’s unwind boundary, which turns a failure into the same status. |
crates/snail-scheme-support/src/bin/snail-link.rs | Stage 0’s linker, the assembler and wasm-fuse as a native program, which links the command line for the bootstrap. See the bootstrap. |
host/chez/snail/stage0/build.sld | The bootstrap of the command line, and nothing else. Each compile has private scratch; rebuilding the command line holds build/lock. |
host/chez/snail/stage0/process.sls | Synchronous tool capture through private output files and a constant shell script with positional arguments. The parent reaps before reading or deleting files; stdin is EOF. The host boundary uses Chez process and file primitives. |
crates/snail-scheme-support/ | Rust scalar services: math, Unicode, float text, console and file IO, directory and path operations, the monotonic clock, panics. External resources use explicit handles; managed references remain engine-traced. Its assembler feature builds the toolchain’s runtime, which tools written in snail-scheme link (build-toolchain-tool), with in-process assembly and static linking for (snail shell assembler), shared by the native executable. |
host/native/run-snail.mjs | Node/WASI program execution, the compiled compiler’s included, on Node’s main thread, plus module loading; it drives the program’s task scheduler through host/browser/tasks.mjs, as the page does. A trap is status 2 and a WASI exit its own, as on wasmtime. |
src/, host/chez/ | Typed language libraries and the explicit Chez adapters. host/chez/load.scm permits only the compiler’s source closure and stage-zero tools. |
Builds and publication belong to the builder, the language server to the development toolchain, and task scheduling and resources to the runtime.
Following and checking a change
make test runs the compiler’s unit tests from source on Chez and exercises
emitted Wasm. make bootstrap rebuilds from Chez alone and compares the
compiled compiler’s successive Wasm stages. Keep both hosts working: differences in
integer overflow, table iteration or evaluation order must not change behavior.
Backend changes need execution tests, not only successful compilation.
make check checks formatting; mdbook build builds the book.
The getting-started guide
lists pinned tools and the Rust/browser checks.
Bootstrap and self-hosting
The compiler is a snail-scheme program that compiles itself, inside the
command line, bootstrap/cli.sld, the one program stage zero builds. Everything else,
scripts and the book’s highlighter among them, the command line builds, as
clang builds lli. Chez Scheme
runs that same source for stage zero through a deliberately small host
adapter. This does not make snail-scheme an R6RS or R7RS implementation:
only the compiler’s explicit source closure has an erased host equivalent.
The stage-zero boundary
host/chez/load.scm loads the compiler’s .sld library envelopes as native
Chez libraries. host/chez/ supplies (snail core base), (snail core table),
(snail core io) and the typed-form adapter, plus the build driver. Compiler
modules come from src/snail/shell/compiler/. An application library outside
that closure is rejected. Test mode additionally admits the test support and
project parser fixture.
snail-scheme source | Chez execution |
|---|---|
Typed define and lambda headers | Parameter names and function bodies, with type clauses erased. |
| Top-level values | Ordinary Chez definitions, evaluated in order when their library loads. In the compiler’s own source a value therefore comes after everything its initializer uses, functions included; Chez reports “attempt to reference undefined variable” otherwise. |
record and enum | Distinct constructor identities with mutable fields; pure replacement copies the outer object. |
(new Name (field expression) ...) | Compile-time field selection and sequential initializer bindings, followed by the private constructor. |
(● object field ...), set! | Registered field slots, with ordinary object aliasing. |
match | Case tests and field bindings. |
| Types, quantifiers and constraints | Erased after the host adapter has recognized their syntax. |
make-prompt, with-prompt, suspend | A delimited escape to the nearest with-prompt of the prompt, whose handler runs there. Stage 0 never resumes: the compiler suspends only to stop. |
| Compiler tables | Host tables whose externally visible traversal order agrees with the typed library. |
Chez’s host control facilities are implementation details of this adapter.
They do not expose call/cc, dynamic-wind, a borrow checker or a numeric
tower to snail-scheme programs. The adapter need only execute the suspensions the
compiler makes; a program’s own, which may resume, are compiled by the compiler itself.
All top-level definitions are functions. Runtime values are constructed by
those functions; Chez needs no separate scalar evaluator bridge.
The compiler must not depend on differences in host integer overflow, argument evaluation order or table iteration. Stateful sibling operations are explicitly sequenced; generated identifiers and declaration order are deterministic. The bootstrap checks the resulting text, not just whether both outputs run.
Stages and checks
scripts/bootstrap builds the command line into
build/bootstrap/snail-scheme.wasm, linked with the toolchain runtime, whose
services include the assembler, and prints it and the two runtimes, plain
and the toolchain’s, a line each, which ./snail-scheme caches in
build/tools.txt.
- A working previous command line produces stage one. For a clean bootstrap, Chez executes the compiler’s source to produce it instead.
- Stage one compiles the command line’s source to stage two.
- Stage two compiles it again to stage three.
- Stages two and three must have exactly identical Wasm text.
- When Chez produced stage one, stages one and two must also have exactly identical text: the source host and compiled compiler ran the same input.
make bootstrap removes the old command line and starts from Chez.
./scripts/bootstrap can reuse a working one: when the compiler’s own
sources are older than it, an edit elsewhere under src/ or bootstrap/
cannot change the compiler inside it, so one compile by it is the
fixpoint’s output; an edit to the compiler runs the whole fixpoint.
Set CHEZ to the Chez scheme executable when it is not on PATH.
make test runs the compiler’s unit tests from source on Chez
(tests/unit.scm), then builds every test program with the command line,
as a user’s is built, and runs it (tests/run.mjs). Stage 0 compiles
nothing but the command line: that Chez and the compiled compiler agree is
the fixpoint’s check, on the compiler’s own source. make check verifies
source formatting. There is no Chibi test or bootstrap path.
Running and linking
Node runs every compiled program, the command line among them:
host/native/run-snail.mjs PROGRAM ARGUMENT ... gives a linked module WASI,
the files it links and module loading, calls _initialize, then main
with a new scheduler, which starts the program’s main as its first task,
and drives the program’s tasks until none is live
(driving the scheduler). A file the program
links is an object of store/ beside it, at sha256/AB/DIGEST, read when a
task first asks for it.
The status is 0, or 1 when a task trapped or exited after the first turn;
a WASI exit in the first turn is its own status, and ends the program
before its other tasks run. A trap in the first turn or a failure of the
host is status 2, with the message after snail: , and so is a run whose
tasks all wait on tickets nothing will complete.
A compile is the command line’s compile action,
compile TARGET SOURCE OUTPUT DIRECTORY ..., which stage 0 runs for the
bootstrap: one that fails exits with status 1. Stage 0 links the command
line with snail-link INPUT.wat RUNTIME.wasm OUTPUT.wasm, a small native
program in crates/snail-scheme-support that calls the assembler and
linker the command line itself holds; Cargo builds it when stale.
There is no native runner: the wasmtime executable that once ran programs without Node is removed, and its history holds it. Other hosts, such as workerd, remain the direction (runtimes). Chez is needed for a clean source bootstrap, not to execute a compiled program.
Libraries
Every library that ships lives under src/, at the path its name gives:
(snail shell graphics scan) is src/snail/shell/graphics/scan.sld. They
come in layers, each importing only from the layers before it:
- Core,
(snail core …), imports nothing outside itself. The compiler imports only itsbase,tableandio, so it can compile itself. - Runtime interfaces,
(snail runtime …), declare one host interface’s WebAssembly imports and nothing else, so they emit no code of their own. - The shell,
(snail shell …), is everything else: written insnail-schemeover core and the runtime interfaces. The compiler, the build and the language server are shell libraries too. - Targets,
(snail target …), run a program’smainand give it the capabilities it asks for. - Application support:
(lpc …)draws Liberated Pixel Cup characters,(datasets …)links published datasets into programs, and each application undersrc/apps/keeps libraries of its own.
There are no (scheme …) compatibility libraries and no dynamic numeric
tower.
Reading a library
A library’s header comment, at the top of its file, says what it is for and
how it is used, usually with an example. Sections, each headed
;; ---- Title ----, divide the rest, and a compiler module’s unit tests
sit in a final Tests section. This reference says what each library is
for, names its main entry points, and records what its code does not say:
why it is shaped as it is, what it costs, and how it fits with the others.
For anything finer, read the source, which each section links.
Three conventions run through the shell:
- A capability is a record of functions a function is handed, such as
an
OutputPort, aGpuor aDom.host-NAMEmakes the host’s from aHost, which only a target holds, andmainasks its target for what it needs by its parameters’ types (capabilities). - A page variant and a test variant.
(… page)libraries make a capability over the browser page, and(snail shell dom memory)and(snail shell gpu record)make ones that need no page or device, so an interface or a graphics library is tested in an ordinary program. - Waiting is suspension. An operation that waits for the host, such as reading a file or a buffer, suspends the task that called it and nothing else (task operations).
Index
Core
| Library | For |
|---|---|
(snail core forms) | The core forms and builtin types, served by the compiler |
(snail core primitive) | The operations the backend implements, with their types |
(snail core base) | The prelude: forms, numbers, Option, Result, lists, arrays, strings, prompts |
(snail core io) | Ports, files and directories, the clock, arguments and environment |
(snail core table) | Immutable tables from strings to values |
Text and data
| Library | For |
|---|---|
(snail shell math) | Elementary functions on F64, bit for bit libm’s |
(snail shell random) | A deterministic generator as a value |
(snail shell text) | Unicode properties and case mapping |
(snail shell utf8) | Strict UTF-8 encoding and decoding |
(snail shell json), (snail shell json read) | JSON values, written as JSON.stringify writes them, and read back |
(snail shell wire) | Values to bytes and back, checked against their schema |
(snail shell syntax) | The syntax a generate-library recipe returns |
(snail shell inflate) | DEFLATE streams, decompressed |
(snail shell zip) | Zip archives, read a member at a time from the bytes given |
(snail shell compiler sha256) | SHA-256, the same on both hosts |
Tasks, files, processes and networks
| Library | For |
|---|---|
(snail shell task) | Cooperative tasks, their scheduler, waits and mailboxes |
(snail shell async-files) | Whole-file reads that wait as a task |
(snail shell resource) | Files a library links instead of embedding |
(snail shell process) | Child processes, commands run to their end, and signals |
(snail shell socket) | TCP and UDP |
(snail shell http), (snail shell http exchange) | A bounded subset of HTTP/1.1, and one exchange over a connection |
(snail shell web) | The length of the file at a URL, and parts of it, on Node |
(snail shell web zip) | Zip archives on the web, pinned, their members kept in the machine’s cache |
(snail shell wasm) | Compiling, linking and calling WebAssembly modules |
(snail shell explore) | Bounded model checking of a state machine |
Pages, documents and interfaces
| Library | For |
|---|---|
(snail shell page) | What every page program shares: its events, its save and its boot |
(snail shell app) | Canvas applications: a scene drawn each frame, and a HUD |
(snail shell ui), (snail shell ui page) | Document interfaces in the shape Elm gave them |
(snail shell dom), (snail shell dom page), (snail shell dom memory) | A document as a capability, over the page or in memory |
(snail shell fetch), (snail shell fetch page) | Requests and server-sent events |
(snail shell files), (snail shell files page) | Files the user drops on the page or picks |
(snail shell base64) | Encode bytes as a data URL |
(snail shell png) | PNG files and data URLs of RGBA pixels |
(snail shell sprite) | Animations on sheets of equal cells |
The GPU
| Library | For |
|---|---|
(snail shell gpu), (snail shell gpu record) | WebGPU as a capability, and one that records instead of running |
(snail shell graphics pod) | Records laid out as WGSL lays out its structs |
(snail shell graphics wgsl) | Shaders as S-expressions, printed to WGSL at build time |
(snail shell graphics kernel) | What every library of compute kernels needs |
(snail shell graphics scan) | An exclusive prefix sum on the GPU |
(snail shell graphics radix-sort) | A stable radix sort of keys and values on the GPU |
Rasterized graphics
| Library | For |
|---|---|
(snail shell graphics atlas) | Pictures composed into texture-array pages |
(snail shell graphics quad) | 2D quads from those pages, one instanced draw a run |
(snail shell graphics mesh) | Meshes as geometry and instance tables |
(snail shell graphics raster) | A G-buffer, and translucent surfaces over it |
(snail shell graphics passes) | The sun, tone mapping and FXAA |
(snail shell graphics fly) | A camera that flies |
Gaussian splats
| Library | For |
|---|---|
(snail shell graphics splat) | Gaussians drawn as sorted, blended quads |
(snail shell graphics ply) | 3D Gaussian Splatting’s PLY files, read and written |
(snail shell graphics colmap) | COLMAP’s sparse reconstructions |
(snail shell graphics splat-view) | Gaussians drawn tile by tile, as training draws them |
(snail shell graphics splat-train) | The differentiable splat renderer, as a tensor graph |
(snail shell graphics splat-fit) | Training: a step, densification and the opacity reset |
Path tracing
| Library | For |
|---|---|
(snail shell graphics bvh) | A BVH over triangles, and ray queries through it |
(snail shell graphics environment) | Light from all around: an HDR file or a sky |
(snail shell graphics gltf) | glTF 2.0 scenes, read |
(snail shell graphics animation), (snail shell graphics gltf animation) | Generic rigs, authored clips and glTF skins |
(snail shell graphics trace scene) | A glTF scene on the device |
(snail shell graphics svgf) | A denoiser for one path a pixel |
(snail shell graphics trace render) | A scene path traced to the canvas |
Game simulation and stories
| Library | For |
|---|---|
(snail shell game physics), terrain, vehicle, boarding | CPU movement, vehicle kinematics and riders |
(snail shell game humanoid), pedestrian | Character poses and walking behavior |
(snail shell game drawing), figure, scenery | Rigid parts and their placement |
(snail shell game quest) | Typed stage and event rules |
(snail shell game dialogue) | Spoken lines, branching replies and saved cursors |
(snail shell game ink) | Generate a dialogue library from linked Ink sources |
Tensors
| Library | For |
|---|---|
(snail shell tensor) | Tensor graphs of nodes and views |
(snail shell tensor grad) | Reverse-mode gradients, as more graph |
(snail shell tensor adam) | Adam’s update, as more graph |
(snail shell tensor fuse) | Fusing maps into fewer kernels |
(snail shell tensor lower) | A graph lowered to WebGPU buffers and dispatches |
(snail shell tensor eval) | A graph evaluated on the CPU, the kernels’ specification |
Tools
| Library | For |
|---|---|
(snail shell compiler) and its passes | Source to WebAssembly text, written in snail-scheme |
(snail shell assembler) | WebAssembly text to a module, and static linking, in-process |
(snail shell project build), (snail shell project web-app) | Builds of scripts, and a page’s web-app manifest |
(snail shell lsp) | The language server |
(snail shell format) | The formatter |
(snail shell highlight) | Source text as classified tokens, for coloring |
Runtime interfaces and targets
| Library | For |
|---|---|
(snail runtime browser …) | The page’s events, save, document, requests and files |
(snail runtime gpu) | The host’s WebGPU device |
(snail runtime native …) | Node’s sockets, processes, asynchronous files and the web |
(snail runtime resource), (snail runtime wasm) | Linked files and WebAssembly on every host |
(snail target node), (snail target browser) | The two targets |
Liberated Pixel Cup art
| Library | For |
|---|---|
(lpc layout) | The geometry of LPC character sheets |
(lpc catalog) | Which LPC bodies, heads, hair and garments the packs draw, and where |
(lpc wardrobe) | Characters dressed from the catalog, as pictures |
(lpc skins) | The skin ramps, read when built |
(lpc credits), (lpc embed) | Credits for what a program embeds, and recipes that embed it |
Datasets
| Library | For |
|---|---|
(datasets mipnerf360) | Mip-NeRF 360’s scenes, read from Google’s archives when built |
(datasets mipnerf360 bicycle), and the other eight scenes | One scene’s reconstruction and photographs, at the size 3D Gaussian Splatting trains it |
Applications’ own libraries
Each application keeps its libraries beside its scripts, under
src/apps/NAME/:
(apps siegework …): the colony game’s land, rules, siege, view and HUD (Siegework).(apps hearsay …): the rumor mill and the favor ledger, their screens and their LPC cast (Hearsay’s README).(apps train …): 3D Gaussian Splatting training, on a page or on Node (training on photographs).(apps splats rings): the cloud the splat viewer opens on (gaussian splats).
Core
(snail core …) imports nothing outside itself, and every program builds
on it. The compiler imports only base, table and io, so it compiles
itself, and Chez runs the same three as stage 0 of the
bootstrap.
(snail core forms)
The core forms and the builtin types: define, lambda, if, begin,
let, define-syntax and syntax-rules, quote, record, new, enum,
type, typeclass, instance, match, ann, downcast, extern,
expose and the field read ●, with I32, I64, F32, F64, U8,
Bool, Char, Unit, String, Array, Bytes, Fn and their kin. The
compiler serves it, so it has no file; (snail core base) re-exports it,
and a program imports that instead (terms,
types).
(snail core primitive)
The operations the backend implements directly, each declared with its type
by (primitive name type), a form accepted only here: as extern declares
a foreign function, primitive declares one the compiler supplies. The
library has no module of its own, since nothing it declares has a body.
(snail core base) gives most of these their everyday names, so a program
seldom imports it.
Of all of them, only array-set! and array-copy! change anything; some,
such as integer division by zero, can trap.
(snail core base)
The prelude. Its exports, by kind:
- Forms: the core forms, and derived syntax:
let*,letrec,cond,case,when,unless,and,or,do,notandset!. - Data:
Option,Result,Pair,List,Neverwithabsurd, andAnywithdowncast(explicitAny). - Numbers: the classes
Num,Ord,IntegralandFractional, with their operations, and every conversion betweenI32,I64,F32andF64, including their bits. - Text: characters, strings,
Show(show) andRepr(repr,derive-repr), andi64->string,string->i64andf64->string. - Collections: lists and their operations, arrays, constant arrays and
Bytes.array-setanswers a new array;array-set!andarray-copy!write the one they are given. - Control:
panic; the cached functionscacheandlru-cache(cached functions); and the promptsmake-prompt,with-promptandsuspend(suspension).
(list-sort before? items) is stable: items for which neither precedes the
other keep their input order. It is a merge sort, O(n log n) comparisons,
and the compiler and the build use it; stage 0 supplies a stable sort of
its own on Chez.
(snail core io)
The capabilities a program starts with: Host, InputPort, OutputPort,
Fs, Clock, Arguments and ProcessEnvironment. A port, a clock, the
arguments and the environment are records of functions, which a program may
make for itself, to keep what is written or to fix the time. Fs holds
nothing: having it is the permission to use the host’s file system. The
host’s own are made from a Host by standard-input, standard-output,
host-fs, host-clock, host-arguments and host-environment, and only
a target holds a Host: unsafe-host makes one from nothing, which a
target does and nothing else should
(capabilities).
Ports
An InputPort is a record of (read-char) → (Option Char), and an
OutputPort of (write-string text) → Unit. Every reading and writing
function takes its port first, so a function reads and writes only the
ports it was given, and a program chooses another stream by passing another
port (making one’s own).
((● in read-char)) consumes one character, None at the end.
(read-line in) answers the next line without its LF: an empty line is
(Some ""), the end after a partial line answers that line, and the end
before any character is (None). Every other character, CR among them, is
kept. Reading standard input first flushes pending standard output, so a
prompt appears before the program waits.
(let ((empty (new InputPort (read-char (lambda () (None))))))
(write out (read-line empty))) ; prints (None)
An output port receives whole strings. One a program makes can collect them, drop them, or forward them:
(let ((bracketed (new OutputPort
(write-string (lambda (text)
((● out write-string) (string-append "[" text "]")))))))
(write bracketed (Some "hello"))) ; prints [(Some "hello")]
(display out value) prints the text a value’s Show instance chooses, and
(write out value) its Repr: strings keep their quotes and escapes,
characters use #\ notation, and containers represent their elements.
Neither adds a newline; (newline out) and (write-line out text) do.
(display out "hello") ; prints hello
(write out (Some "hello")) ; prints (Some "hello")
(write out (list "a" "b")) ; prints ("a" "b")
Scalars have Show instances; containers such as Option, lists, arrays,
Result and Pair have none, so (display out (Some "hello")) is a
compile error. That keeps a string’s quotes from vanishing inside a
container’s notation: write gives the representation, or a program
matches and displays the contents.
(repr value) answers the same representation as a String. Base gives
Repr instances for the numeric scalars, booleans, characters, strings,
Unit, lists, arrays, Option, Result and Pair: lists as
(element ...), arrays as #(element ...), and the others by their
constructors, such as (new Pair (first 1) (second "one")). A record or
enum derives constructor notation:
(enum Action
(Rock)
(Paper)
(Scissors)
(deriving Repr))
(write out (Rock)) ; prints (Rock)
A derived instance represents each field in declaration order; records
print named construction, (new Name (field value) ...), and enum cases
stay positional. Generic parameters require Repr. An explicit
(instance (Repr T) (define repr (lambda (value) ...))) chooses other
notation, and a Show instance alone gives no Repr.
Files and directories
Every file operation takes an Fs first, (read-file fs path), which the
Node target provides; the table below leaves it out. Each path operation
answers a Result, so a failure a program can act on is a value: (Err (NotFound)) for a missing path, (Err (AlreadyExists)) for a name already
taken. read-file, write-file, read-bytes and write-bytes fail the
program instead; read-text-file and write-text-file are the
counterparts for a service, which must answer each failure.
| Operation | Result |
|---|---|
(make-directory path) | One directory, whose parent must exist. |
(make-directories path) | The directory and each missing parent; one already there is success. |
(rename-file from to) | Renames a file or directory, replacing a file at to at once: a reader sees the old file or the new one, never neither. |
(remove-file path), (remove-directory path) | A file or symbolic link; an empty directory. |
(remove-tree path) | What is at path and everything in it, never following a link. |
(list-directory path) | The names in a directory, without . and .., in scalar order whatever the host’s order. |
(file-status path) | A FileStatus: the FileKind (RegularFile, Directory, SymbolicLink or OtherKind), the size in bytes and the modification time in nanoseconds since the Unix epoch, without following a link. |
(followed-status path) | The FileStatus of what a read of path finds, following each link, so never SymbolicLink; a link to nothing is NotFound. |
(make-symbolic-link target path), (read-symbolic-link path) | A link and its target, kept as given. |
(make-hard-link existing path) | Another name for a file, which is not copied; it fails across file systems. |
(read-text-file path limit) | The text of the regular file at path, if it holds at most limit bytes of UTF-8, as one version of the file: its length and modification time stayed the same while it was read. A link is not followed. Else a TextError: ReadFailed with a FileError, NotRegularFile, TooLong, NotText or ChangedWhileRead. |
(write-text-file path text mode) | The whole text, by a WriteMode: CreateNew refuses an existing leaf, even a dangling link; ReplaceExisting refuses a missing file; CreateOrReplace takes either. |
A FileError is NotFound, AlreadyExists, NotADirectory (a path
through a file), PermissionDenied or OtherError, and show describes
it. Each kind is one some program acts on; every other failure, such as
removing a directory that is not empty, is OtherError. The runtime does
each operation through WASI preview1
(crates/snail-scheme-support/src/paths.rs). WASI has no file modes or
owners, and Rust exposes its device and inode numbers only as unstable API,
so a FileStatus holds none of these. A page has no preopened directory,
so every path operation there fails with OtherError.
The clock, arguments and environment
((● clock monotonic-nanoseconds)) reads a Clock. The host’s is WASI’s
monotonic clock, from an origin the host chooses, so only differences mean
anything.
(command-line arguments) lists what the program was started with.
((● environment variable) name) is a variable of the ProcessEnvironment
the program started with, or None when it is unset, and
((● environment directory)) the working directory, against which a
relative path resolves, or None on a host with no file system. The host’s
own channel for the working directory, SNAIL_CWD, reads as unset.
(snail core table)
Immutable tables from strings to values: empty-table, table-ref (an
Option), table-set, table-remove, table-contains?, table-count,
table-keys and table-values. A table is a Patricia trie on each key’s
64-bit FNV-1a hash, after Okasaki and Gill: an update copies the path to
one leaf and shares the rest with the table it came from, so a pass may
keep every version it made.
The order table-keys lists keys in is the trie’s, which stage 0’s tables
on Chez do not share, so the compiler never depends on it.
Text and data
Pure libraries over values: numbers, text, and the encodings that carry values to files, to the host and to the compiler.
(snail shell math)
pi, sin, cos, tan, asin, acos, atan, atan2, exp, log
and expt on F64. They are FreeBSD’s msun (fdlibm) as Rust’s libm crate
carries it: the same polynomials, argument reductions and special cases, so
each result is within one ulp of the true value and equal to libm’s bit for
bit, as tests/programs/math checks. WebAssembly has no floating-point
exception flags, so the originals’ arithmetic done only to raise them is
left out.
half-bits rounds an F32 to the nearest f16, ties to even, and answers
its 16 bits; half-value answers the value of such bits, exactly. Data
that the GPU reads as f16s packs them two to a 32-bit word, low first, as
WGSL’s unpack2x16float reads them (halves in
(snail shell tensor)).
The point of porting rather than importing is that both hosts agree: the same program gives the same bits on Node, on a page and on stage 0.
(snail shell random)
A SplitMix64 generator as a value: make-random from a seed, and
random-next, the generator after it. random-value is a generator’s
number and random-below that number below a bound. Nothing is global, so
a program that threads its generator replays exactly, as Hearsay’s games
and casts do, and as the trainer picks the order of its photographs.
(snail shell text)
Unicode character properties and case mapping: char-upcase,
char-downcase and char-foldcase, the char-unicode-…? and
char-…-case? tests, char-digit-value, and string-upcase,
string-downcase and string-foldcase. They read the constant arrays of
(snail shell text unicode), which make unicode-tables generates from
Rust’s Unicode 17.0.0 properties
(crates/snail-scheme-support/examples/unicode-tables); do not edit that
file, and make check fails when it falls behind its generator.
(snail shell utf8)
string->utf8, and utf8->string, which answers a Utf8Error with the
offset of the first ill-formed sequence rather than replacing it, as a
fatal TextDecoder does; a byte order mark stays text. Bytes become text
only when they are UTF-8, so a String is always well formed.
(snail shell json)
The Json value, with integer numbers apart from others and objects as
ordered members, and json->string, which writes what JavaScript’s
JSON.stringify writes for the same value. It is a writer only.
(snail shell json read)
string->json reads any JSON text back as a Json, such as a language
server’s message or a glTF scene, and json-member finds an object’s
member. It is a library of its own so that a program that only writes JSON
does not carry a parser.
string->json-values reads a stream of consecutive JSON values, including adjacent objects. It returns Some with an empty list for an empty stream and None if any value is malformed. The Ink producer uses it for the reference player’s transcript.
(snail shell wire)
Values as bytes and back. (deriving Serialize Deserialize) at the end of a
record or enum makes both instances; serialize writes a value and
deserialize reads it:
(record Point
((x I64)
(y I64))
(deriving Serialize Deserialize))
(ann (deserialize (serialize (new Point (x 1) (y 2)))) Point)
Each record and enum case has a 32-bit TypeId hashed from its library, its
name and its fields’ schema, and a value is written as its case’s TypeId
followed by its fields. So data written for another schema fails to read at
the first type that changed, instead of being misread. Siegework and Hearsay
encode their saves this way, and (snail shell explore) identifies states
by their encoding.
(snail shell syntax)
The Syntax a generate-library recipe returns: the define-library form
of the library it generates, built with form and library-syntax. Its
producer writes the form as bytes (write-generated-library), which the
compiler decodes, so no text is printed or parsed in between and a byte
array reaches the compiler as the bytes it holds. Generated syntax has no
locations: the compiler places every generated form at the recipe
(generated libraries). linked-files is the
definition of a list of files, each by a path of its own with the linked
file it names, as a dataset’s library holds them
(datasets).
(snail shell inflate)
inflate, which decodes a DEFLATE stream (RFC 1951), the format a zip
archive’s members, gzip files and PNG images keep their bytes in, into the
number of bytes it must make, as a zip archive’s directory gives it. Its
stored, fixed and dynamic blocks are each a section of the source. The
input is read as a stream of bits whose place is threaded through every
step as a number, so decoding allocates nothing but its output and each
block’s codes; a code of up to 10 bits is found in a table, and a longer
one a bit at a time. A stream that breaks the format, or makes more or
fewer bytes than it should, answers why. It decodes about 55 MB a second
on Node.
(snail shell zip)
Zip archives, read a member at a time, as from a server that answers any
range of an archive’s bytes: zip-directory finds the directory from the
archive’s last end-bytes, zip-entries reads it into ZipEntry
records, each with its span of the archive, from its local header to the
next member’s, and entry-contents gives a member’s bytes from its span,
kept as they are or deflated, checked against the directory’s length and
CRC-32 (crc32). An archive past 4 GiB, or of more than 65,535 members,
keeps its wide numbers in Zip64’s records, which every function reads.
Nothing here reads a file or the web: each function reads the bytes it is
given. Encrypted members, other methods and names that are not UTF-8 are
refused.
(snail shell compiler sha256)
sha256 over a byte array, and bytes->hex, the lowercase hex Node’s
digest('hex') writes. The compiler names each file it links by this
digest, so stage 0 must compute the same one: a word is an I64 holding an
unsigned 32-bit value, masked back to 32 bits after each sum and shift,
where WebAssembly’s i32 would wrap and Chez’s integers would grow.
Tasks, files, processes and networks
The libraries that wait on the world. Each operation that waits suspends
the task that called it, through (snail shell task), while the host does
the work; each capability is a record of its operations, so a test makes
its own (runtimes).
(snail shell task)
Cooperative tasks on a scheduler, written in snail-scheme. A host makes
the scheduler, hands it to each turn and wake, and closes it; a program
starts tasks with dispatch (or dispatch-in a scheduler) and waits with
yield, sleep and await. Those stop the task wherever it is, however
deep in its calls, and the scheduler keeps the rest of it to run later. No
function between the wait and the task’s start says so in its type, and
none takes anything for it (suspension).
through-host is how every host operation waits: it starts the operation
under a ticket and suspends until the host wakes it. A Mailbox
(make-mailbox, mailbox-post, mailbox-receive,
mailbox-try-receive) carries values between tasks.
A task runs until it finishes: nothing cancels one, and tasks that want to
stop each other arrange it, through a mailbox. tasks-turn, tasks-wake!
and tasks-close! are the host’s side, which a program never calls.
Task operations and driving the scheduler describe the model in full. Source
(snail shell async-files)
Files, a capability for whole-file reads that wait as a task while other
tasks run, made by host-files on Node. ((● files read-file) path limit)
reads at most limit bytes, up to 16 MiB, and fails as a FileError:
Unavailable, InvalidInput, TooLarge, NotFound, PermissionDenied
or Failed. Neither the read nor its result promises a snapshot of the
disk. Node does the read with its asynchronous file system
(host/native/async-files.mjs)
(native asynchronous file reads).
Use it rather than (snail core io)’s read-bytes when the program has
other work while a large file arrives; read-bytes holds the whole program.
(snail shell resource)
Files a library ships beside the program instead of embedding them, as
Python’s importlib.resources names a package’s data. (link-file "path") ties the file beside the library’s source to the library; the
build copies it beside the program’s module and gives the program a
Resource. read-resource reads one through a Resources, waiting as a
task does, since a page can only fetch it, and read-resources reads
several at once. On secure origins the browser verifies the SHA-256 digest and stores the response in Cache Storage. The page looks up the digest before fetching. Apps on the same origin can reuse a file, and a changed file has a new digest. If the browser evicts the entry or storage is unavailable, the next read can download it again.
Resource is exported without its constructor, so holding one is evidence
that its file ships (linked files).
(snail shell static-resource)
fetch-catalog takes a Fetch and a catalog URL and returns a Result containing named StaticFile records. Pass the same URL and the desired files to acquire-files with the browser’s StaticResources capability. It returns a table of verified bytes by name or an error identifying the failed file. A progress callback receives StaticProgress with downloaded, cached and total byte counts. The first two add up to the completed portion. The total counts each distinct digest once and uses uncompressed byte lengths, including when HTTP omits Content-Length.
(match (fetch-catalog fetch "resources.json")
((Err why) (Err why))
((Ok files) (acquire-files store "resources.json" files show-progress)))
On HTTPS or localhost the browser looks up each digest in Cache Storage, promotes verified entries from the earlier IndexedDB cache, and counts incoming response bytes when it needs a download. An interrupted or invalid response never enters the cache. If storage fills up, the current run can still use the verified response. The page, Wasm and small catalog load on navigation. An offline application shell requires separate handling. Saved application state continues to use IndexedDB.
For a Snail HTTP server, call static-resource-service from (snail shell static-resource serve) once with the server’s Resources and the linked path/resource pairs for the bundle. The returned function takes the request method and decoded path segments relative to the mount. It answers Some Response for a known catalog or object on GET or HEAD, and None lets the server try its next route. The HTTP exchange writes the correct HEAD framing. Publishing a catalog · Linking a client build into a server
(snail shell process)
Child processes, as the capability Processes, made by host-processes:
spawn a Command with piped standard streams and read its output, write
and close its input, signal it and wait for its Exit (Exited or
Signaled); run a command to its end and answer what it Captured; or
exec one in place of the program. Signals, made by host-signals,
answers the termination signal the program was sent
(child processes).
Stage 0’s tool runner on Chez, host/chez/snail/stage0/process.sls, has
the same name; Chez never sees src/.
(snail shell socket)
TCP and UDP as the capabilities Tcp and Udp, made by host-tcp and
host-udp: listen, accept, connect, read, write and finish a Connection,
and bind, send and receive Datagrams on a UdpSocket. An Endpoint is
parsed once, by endpoint; the type is exported without its constructor,
so holding one is evidence that its address is IPv4 and its port in range,
and nothing checks either again (native networking).
(snail shell http)
A deliberately bounded subset of HTTP/1.1: ASCII heads, origin-form targets,
Content-Length bodies, one exchange per connection, and response streams
that end when the connection closes. parse-request-head and
parse-target read a request, encode-response and encode-stream-head
write the answer, and head-limit and body-limit bound what is read; an
HttpError says why a request was refused
(HTTP protocol).
(snail shell http exchange)
One request and its response over a Tcp connection. serve-one is the
whole exchange with one handler. A server that chooses between reading and
answering calls the halves itself: read-request, then respond, which
needs only the request’s method, so a server can answer a request it could
not read. A failure of either leaves the connection open for the caller to
close, as serve-one does.
(snail shell web)
Web, the web as a program on Node reads it, made by host-web:
((● web size) url) answers the length of the file at a URL, and
((● web parts) url spans) the bytes of each Span of it, asked for
together, each a GET with a Range header. Node’s fetch makes the requests
(host/native/web-imports.mjs), over HTTPS or HTTP, following redirects,
while the task that asked waits. A server must answer a part with exactly
its bytes: one that answers with the whole file is stopped before its body
comes, so a program can read a few megabytes of a file of many gigabytes,
as (snail shell web zip) does. The page’s requests are (snail shell fetch)’s.
(snail shell web zip)
Zip archives on the web, read a member at a time and kept in the machine’s
cache, for the recipes of generated libraries. A WebZip names an archive
by its URL and pins it by the SHA-256 of its end: its directory and the
records after it, which give every member’s name, length, CRC-32 and
place. zip-members answers, for each member whose name a predicate
takes, the path of its file in the cache, reading those not yet there
eight at a time, checked against the pinned directory’s CRC-32:
CACHE/zip/PIN.end the archive's end, as pinned
CACHE/zip/PIN/NAME each member read, by its name in the archive
The pin is what makes the cache correct. A file in the cache was read
from the archive the pin names, whatever its server later serves, so a
build that finds it there needs no network and any checkout on the
machine may share it. A server whose archive has another end fails the
build, naming the digest it has. machine-cache is snail-scheme in
$XDG_CACHE_HOME, or ~/.cache/snail-scheme. Each file is written in a
folder made beside its place, which no other writer can share, and renamed
into it, so a reader never sees part of one. Nothing reclaims the cache:
deleting it costs only fetching again.
(snail shell wasm)
WebAssembly modules loaded while a program runs, through the capability
Wasm both targets provide. compile-bytes compiles a module,
module-imports lists its imports, and link-module takes one Provider
per import, in order: (ExportOf instance name), an instance’s export;
(HostProvided), a host service; (ConstantOf n), a constant function; or
(Unprovided), a function that traps if called. A provider that is missing
or does not fit answers LinkFailed. Linking runs _initialize when the
module has one.
module-export answers an untyped Funcref, and unsafe-cast makes it an
Fn at the type the caller asserts: WebAssembly’s cast checks the
representation, not snail-scheme’s nominal types, so the caller
establishes that contract. run-export calls a scalar export by name
(linking by hand).
(snail shell explore)
Bounded model checking of a total state machine: from an initial state,
explore applies every move each state allows, breadth first up to a
depth, and answers the first state that breaks the invariant as a
Violation, with the moves that reach it. States are identified by their
wire encoding ((snail shell wire)), so each is checked once and the path
reported is a shortest one.
HTTP protocol
(snail shell http) implements a pure, bounded request-head parser, a
request-target decoder and response serializers, importing only
(snail core base) and (snail shell utf8). (snail shell http exchange) reads one complete
request, calls application code and writes its response over a
Tcp. Applications own accepting and
scheduling connections; the library supplies no router or server framework.
This is a deliberate HTTP/1.1 subset. Full HTTP/1.1 also requires features this module rejects, including chunked decoding and absolute-form targets. RFC 9112
Request heads
(parse-request-head bytes)
;; Result (Option ParsedHead) HttpError
Ok None means the supplied prefix needs more bytes. Ok (Some parsed) contains
a RequestHead and the offset of the first body byte. Bytes after that offset
are not inspected, so binary content or a large body cannot invalidate a short
head. The exchange reader reports EOF before a complete head as TruncatedHead,
including an empty connection. The parser itself does not establish body receipt.
An incomplete prefix is not a certificate of valid syntax: some errors are
decided once a complete head is available.
The head limit is 16,384 bytes, including the terminating empty line. Input uses
strict CRLF and ASCII, with tab allowed in field values. The method is a token
retained exactly; the target must be origin-form, beginning with /. URI
characters and percent escapes are checked, but spelling is preserved: there is
no decoding, path normalization, filesystem lookup or origin authorization.
CONNECT, other target forms and other HTTP versions are unsupported.
Each Header contains a lowercase name and a value with surrounding spaces/tabs
removed. Ordinary occurrences retain their order and are not merged.
header-values takes the parsed headers and a case-insensitive name, returning
all matching values. It expects the normalized names produced by the parser.
Request targets
(parse-target (● head target))
;; Result Target HttpError
parse-target decodes an origin-form target as new URL and
URLSearchParams read it. Target-path is the segments after the first /,
split before decoding, so / is ("") and /a%2Fb/ is ("a/b" ""). Dot
segments are resolved after decoding, %2e%2e included, as the URL standard
does: /a/b/.. is ("a" ""). Target-query is the query’s name and value
pairs in order: & separates pairs, empty pieces are skipped, the first =
ends a name, and + is a space before decoding, so %2B stays a plus.
assoc-ref finds a name’s first value, as URLSearchParams.get does.
Decoding is strict where the URL standard is lenient. A % without two hex
digits, a character outside the target’s URI characters, and escaped bytes
that are not UTF-8 are all Malformed; Node keeps a bad escape as text and
replaces bad UTF-8 with U+FFFD. Targets that encodeURIComponent builds always
decode. A target without a leading / is Unsupported.
Exactly one Host is required. This implementation accepts a nonempty name made
of ASCII letters, digits, ., - and _, optionally followed by a decimal port
from 0 through 65,535. This is a syntax restriction, not DNS validation. IPv6
literals are unsupported. Exact Host and Origin policy remains with the caller.
A missing Content-Length means body length zero. A single unsigned decimal length may specify at most 8,388,608 bytes; the parser checks that bound before arithmetic or body allocation. Duplicate or comma-list lengths and combined Transfer-Encoding/Content-Length are malformed. Other transfer codings and every Expect field are unsupported, decided before a caller waits for any body.
HttpError distinguishes Malformed, Unsupported, HeadTooLarge,
BodyTooLarge and InvalidResponse. The reason/feature strings are diagnostics;
the codec does not choose HTTP error responses. Public records remain ordinary
constructible snail-scheme values. The parser guarantees its own outputs, rather than
making a claim about records created elsewhere.
Response parts
(encode-response method status headers representation)
;; Result ResponseParts HttpError
The head and body fields of a ResponseParts are separate immutable byte arrays.
This avoids copying a representation into one combined response buffer and
leaves a clear boundary for future streaming. No bytes are written by this call.
The serializer accepts final statuses 200–599, with an empty reason phrase.
Successful CONNECT responses are unsupported. It validates ASCII header names
and values and checks the 16,384-byte head bound before building the output
buffer. Caller-supplied Content-Length, Transfer-Encoding, Connection, Trailer
and Upgrade fields are rejected. It generates Connection: close and owns
content framing; header strings cannot inject another field or status line.
| Response | Generated Content-Length | Returned body |
|---|---|---|
| 204 or 304 | Omitted | Empty |
| 205 | 0 | Empty |
| HEAD, otherwise | Representation length | Empty |
| Other supported response | Representation length | Original bytes |
Status rules take precedence over HEAD. Response representations are not subject to the request-body bound. The caller still has to write all head/body bytes and close appropriately; successful encoding is not delivery.
Stream heads
(encode-stream-head status headers)
;; Result Bytes HttpError
A stream’s head has no Content-Length: its body is every byte written after
it, ending when the server closes the connection
(RFC 9112 §6.3,
rule 8). This is how an event stream is framed in this subset, which has no
chunked coding. The head is checked as encode-response checks one, with the
same Connection: close and framing rules. Statuses that forbid a body, 204,
205 and 304, have no stream; a HEAD request is answered with
encode-response instead.
One exchange
Import (snail shell http exchange) and call serve-one with an exclusively used
Connection, an I32 grace period in milliseconds, and an application function:
;; serve-one contract (summary notation):
;; (∀ (E)
;; (Fn Tcp Connection I32
;; (Fn Request → (Result Response E))
;; → (Result Unit (ExchangeError E))))
Request contains head : RequestHead and body : Bytes. The callback returns
Response, containing status : I32, headers : List Header and body : Bytes,
or an application error of its chosen type E. It may wait as a task does. The callback receives
the request, not the connection.
The reader scans incoming bytes once for the head delimiter and parses the completed head once. It collects exactly the declared body length, including any prefix that arrived with the head. Fragment lists are copied once into the final arrays; one-byte fragmentation does not repeatedly copy the accumulated input. Unneeded pipelined bytes are discarded. The serializer validates the complete response before any output, then the writer sends head and body separately, advancing by each accepted count. HEAD and bodyless statuses use the codec’s rules. No handler call occurs before the complete request body arrives. Each write offers at most twice the previous accepted count, capped at 65,536; this bounds slice copying even when an intercepted write makes tiny progress.
ExchangeError E distinguishes protocol failure (HttpError), transport failure
(SocketError), TruncatedHead, TruncatedBody with expected/received counts,
and ApplicationFailure E. Every returned failure closes the connection while
preserving the original error if close also fails. Empty successful reads or
invalid write counts report transport EIO, rather than looping without progress.
Protocol/application errors do not generate automatic HTTP error responses.
Success ends with graceful completion
through finish-connection: it ends output, discards input and awaits physical
closure with a bounded grace period. Unread incoming data can otherwise cause a
reset that loses the response; see
RFC 9112 §9.6.
This grace is for completion only. There is no request-idle deadline yet.
Exclusive use is a calling convention the checker does not enforce. The caller
must not use another alias during the exchange. Aborting active native socket
I/O, as closing the run does, closes that socket. A trap while the callback
waits cannot execute the snail-scheme cleanup branch;
runtime shutdown cleans the remaining native resource. serve-one does not introduce a task scope
or stronger unwinding guarantee.
read-request and respond are the exchange’s two halves, exported for a
server that decides between reading a request and answering it. serve-one
is them with one handler between, closing the connection when either fails;
called directly, a failure from either leaves the connection open, and the
caller closes it. respond takes the request’s method, or None for a
request that read-request refused, so that a server can still answer it,
with a 400 say; that answer is framed as a GET’s is.
Remaining integration
Artifact serving, writing event streams after their heads, connection scheduling and deadline policy remain networking work. Status and origin policies remain open. Persistent connections, pipelining and streaming uploads are not implemented.
Pages, documents and interfaces
A page’s program is either a scene, drawn on a canvas each frame with a
HUD of document panels beside it ((snail shell app)), or a document
interface, a tree of elements kept equal to a view of its model
((snail shell ui)). Both run on (snail shell page), which owns the
page’s events and its save. The application model
describes both in full.
The capabilities a page offers each come in two or three libraries: one
declares the capability, a page library makes it over the browser host,
and for the document a memory library makes one with no page at all, for
tests.
(snail shell page)
What every page program shares: Events, the host’s queue of input and
lifecycle events (host-events); PageStorage, the page’s one save
(host-storage, load-save); and run-page, which boots from that save,
or fresh, and saves on request. An event is a kind and fields of I32; the
kinds a display frame, the page hidden and a save’s timer are the host’s
own (hidden-kind, save-kind), and each program numbers the rest. A trap
ends the page, which keeps its last save.
(snail shell app)
Canvas applications. An application is pure functions over its state:
init, update over each Input, save and restore, and start and
draw with a drawing state of their own, which holds what drawing keeps
between frames, such as an atlas, and is never saved. hud answers the
Panels of document widgets beside the canvas. A SceneHandler holds the
eight, and run-scene runs one. Time is an input, so the state decides how
its simulation advances, and a save may be much smaller than the state: a
record of how to rebuild it.
A scene draws through its Gpu, itself or as a 3D Frame of mesh Items
in batches, which draw-frame rasterizes and lights
((snail shell graphics raster)), as Siegework does; a 2D scene draws
pictures as quads from an atlas, as Hearsay does. recognize turns pointer
events into Gestures (tap, drag, pinch), and pointer-ray,
screen-axes and ground-point map the pointer into the scene. The HUD is
changed through the page’s document only where it differs after each input,
and after time at most ten times a second
(scenes).
Browser applications can opt into mouse capture by passing pointerLock: true when mounting their canvas. A primary click requests capture. PointerLock reports changes, while PointerDelta reports relative motion in capture or during a right-button drag. Consecutive relative events sum their deltas. Escape releases capture.
(snail shell ui)
Document interfaces in the shape Elm gave them: a model, a view from it to
a tree of Html, and an update from the model and a message to the next
model and the commands it starts. run-ui shows the tree through a Dom,
and after each update changes only what differs, so a node keeps its
identity, and the focus, selection and scroll the page gave it, as long as
the view keeps it. A listener holds a function from what its event carried
to a message, which stays in snail-scheme; the host sees only the
listener’s id. A command is work run as a task, whose answer is a message
posted to the interface’s mailbox. The window’s listeners are a list the
model gives, since the window is no node of the tree.
A program with a loop of its own, as a scene’s HUD has, shows trees itself:
patch-children keeps a node’s children equal to a list of trees, and
listener-table finds the function of a listener that fired
(document interfaces).
(snail shell ui page)
InterfaceHandler and run-interface, a document application’s loop on
the page: it makes the page’s document and fetch, runs run-ui over them,
and hands them to each Command.
(snail shell dom)
A document as the capability Dom: the primitives an interface needs to
build and change it. A Node is a handle the host keeps in a table, so no
host object crosses into snail-scheme and no closure crosses out. A
listener says when it is made what its events carry (Capture) and when the
host prevents their default action (Prevent), since the host decides both
synchronously, while the event is dispatched; a listener with Chords
hears only those keys. Commands find nodes by id to focus, select, insert
text undoably and measure; on a node the view has removed they do
nothing, as on a page. next-event waits for the next Delivery: a
listener Fired, Woken by another task’s wake, a SaveRequested, the
page Hidden, or the document Closed.
(snail shell dom page)
page-dom makes the page’s Dom from a Host, bound to the browser host’s
document (host/browser/dom.mjs), which keeps the interface’s nodes and
listeners by handle under the container the page gives it. A page’s
document never closes.
A game that polls frames and UI input together can read (fired-event events)
immediately after receiving a HudEvent from (snail shell app). Its fields
hold the values captured when the browser listener fired. Read them before
polling the next event. Capturing (Value) on a selector preserves the order of changes made during a slow frame.
(snail shell dom memory)
with-memory-dom hands its work a Dom over a document in memory, which
delivers a script of Cues (Fire, FireWindow and Hide), and answers
the work’s value with the document it left: document->html prints its
tree, and document-trace lists every operation. It is strict where a page
would forgive: a removed node or listener used again, a node inserted into
itself, or a key fired at a listener that does not hear it is a panic, so
an interface’s tests catch what a page would hide. As a page delivers only
between tasks, each delivery waits until every other ready task has run.
(snail shell fetch)
Requests to a server and the events it streams, as the capability Fetch,
so an interface’s commands can ask and a test can answer for the server:
request answers a Reply or why there was none, fetch-bytes a GET’s
body, and a stream of server-sent events is opened, read event by event as
StreamEvents, and closed.
(snail shell fetch page)
page-fetch makes the page’s Fetch over its fetch and EventSource
(host/browser/fetch.mjs). A request or a stream’s next event waits in the
task that asked, so a command’s request never holds up the interface.
(snail shell files)
Files the user hands the program, dropped on the page or chosen with its
pickers, as the capability FilePicker: each file is its path within what
was Chosen and an address a Fetch reads its bytes from. The user
chooses and the program only asks, so a program reads no file it was not
given. open-picker asks for SomeFiles or a Folder and returns at
once; a choice arrives as an event (FilesEvent in (snail shell app)),
and chosen-files lists it. A link dropped on the page is a file whose
path is its address.
(snail shell files page)
page-file-picker makes the page’s FilePicker over its pickers and drops
(host/browser/files.mjs).
(snail shell base64)
data-url takes a media type and bytes and returns a base64 data URL. For example, a page can display an in-memory SVG using its data URL. Source
(snail shell png)
rgba->png writes RGBA pixels as a PNG file, and png-data-url as a data
URL an img element shows, as a HUD shows a portrait the program drew. The
pixels are stored in zlib’s stored blocks, uncompressed: they need no
search, and the images written are small.
(snail shell sprite)
Spritebooks: animations on a picture of equal cells, by motion and heading.
heading picks the heading a viewer should see, and cell-at the cell a
Strip shows at a moment, which a quad then draws. Nothing here knows a
particular sheet: a sheet’s own library, such as (lpc layout), says which
cells each motion uses and in which order the sheet draws its headings.
The GPU
WebGPU as a capability, and the building blocks every graphics and compute library shares: data laid out as shaders read it, shaders written as S-expressions, and a scan and a sort on the device. The WebGPU design explains why the layer is shaped this way, and how Node gets a device.
(snail shell gpu)
Gpu, a record of WebGPU’s own operations, so code that uses it reads
like WebGPU, and a Gpu parameter says exactly which functions touch the
device:
- Device access starts with
request-device. ItsDeviceInforeports the canvas format, enabled optional features and maximum storage-buffer binding size in bytes.work-donewaits for submitted commands to finish. - Objects:
create-buffer,create-texture,create-view,create-sampler,create-shader-module,create-render-pipeline,create-compute-pipeline,create-bind-groupandcreate-query-set, each from a descriptor record, each answering a handle;destroy. - Data:
write-bufferandwrite-texturefromBytes,read-bufferback, anddecode-image, the host’s decoder. - Commands:
create-command-encoder, copies, render passes (begin-render-pass,begin-timed-render-pass), compute passes (begin-compute-pass,begin-timed-compute-pass), what a pass sets and draws or dispatches,finishandsubmit;submit-timedandelapsed-secondsread a timed pass’s device time. - The canvas:
current-texture.
host-gpu makes the host’s from a Host: the page’s, or Dawn’s on Node.
It is WebGPU itself, without bookkeeping, and three rules follow:
- The program keeps its objects. A handle is the id of an object the
host holds, kept for as long as the program uses it, across frames.
destroylets an object go at the nextsubmit, after the commands that use it. An encoder, a pass and a command buffer go once used, and the canvas’s texture at the nextcurrent-texture. - Misuse is WebGPU’s to report. The
Gpuchecks nothing the device checks; Dawn’s validation reports misuse on the page’s console or on Node’s standard error. - Descriptors cross as fields. A descriptor is a list of words and
texts in a fixed order per kind (
fields-bytes), staged asBytesthe host reads into the dictionary WebGPU takes; contents cross as views of the program’s memory, without a copy. A pipeline’s layout is"auto", so a bind group is made against a pipeline and a group index.
An earlier version kept books for the program: objects found by a path each
frame, released at submit, evicted under a budget. Finding every object
again each frame cost Siegework more than its old JavaScript renderer spent
drawing, so the program keeps what it makes
(WebGPU through a capability).
(snail shell gpu record)
with-recorded-gpu hands its work a Gpu that runs nothing: it numbers
the objects made and records a line for each operation a page would send to
its host, so a graphics library’s test reads what it asked of WebGPU. A
buffer reads back as zeros, an image is as large as its PNG header says,
and the canvas is 640 by 480 (tests/programs/gpu-record.sld).
(snail shell graphics pod)
Plain old data, laid out as WGSL lays out its types in storage buffers, so
bytes packed here read in a shader as the struct it declares. A record of
F32, I32, Vec2f to Vec4f, Vec2i, Vec4i, Mat4x4f and other such
records derives Pod; its Shape, found by type with (shape), gives its
WGSL declarations, its stride and alignment, and its vertex-layout.
pack writes a list of values at the stride, and pod-bytes one value:
(record Vertex
((position Vec3f)
(uv Vec2f))
(deriving Pod))
(define vertex-shape (→ (Shape Vertex)) (shape))
(declarations vertex-shape) ; "struct Vertex {\n position: vec3f,\n uv: vec2f,\n}\n"
(pack vertex-shape (list v0 v1)) ; two 32-byte strides
A vec3f takes 12 bytes but aligns to 16, so an F32 may follow it in the
same 16. A Vec4h is four floats kept as f16s, a WGSL vec2u of two
words, which unpack2x16float reads two at a time, without the
shader-f16 some devices lack. A shape is built by walking the record’s fields, so a program
keeps each one it uses as a top-level value, made once. In WGSL a hyphen in
a record’s or field’s name becomes an underscore: Paint-uniform is
Paint_uniform.
(snail shell graphics wgsl)
Shaders as S-expressions, one form to one WGSL construct, printed to WGSL
text by shader-library, a generate-library recipe that reads each
shader file when its library is built. A program ships WGSL, and a form the
printer does not know fails the build at its line. The header of
wgsl.sld tabulates every form. A shader’s structs come from Pod at run
time, prepended with declarations, so a shader names them without
declaring them.
The shader libraries are generated this way:
(snail shell graphics shaders) holds the graphics libraries’ shaders,
(snail shell graphics trace shaders) the path tracer’s, and
(apps train shaders) the trainer’s own.
(snail shell graphics kernel)
What each library of compute kernels would otherwise write for itself:
compute-kernel, a pipeline for one entry point; kernel-group, a bind
group laid out as that kernel expects; dispatch-items, workgroups enough
for every item, in rows past 65,535, and dispatch-texels, a workgroup for
each 8 by 8 tile of texels; uniform-slots and slot-entry, small uniform records side by
side in one buffer, each at an offset a uniform may bind; and
uniform-buffer and storage-buffer, the latter one that binds even when
it holds nothing.
(snail shell graphics scan)
An exclusive prefix sum of a storage buffer’s u32 numbers, in place: each
number becomes the sum of those before it, by Blelloch’s work-efficient
scan. A workgroup scans a tile of 512 numbers and writes its total a level
up, which is scanned the same way, until a level fits in one tile; each
level’s sums are then added back, top down. make-scan makes a Scan once
for a buffer and a count, and dispatch-scan encodes it into a compute
pass as often as the buffer changes; release-scan lets it go. Sums wrap
modulo 2^32.
Since a scan’s value at an index depends only on what comes before it, a scan over a buffer’s whole capacity is correct below any count the device computes, whatever lies past it.
(snail shell graphics radix-sort)
A stable least-significant-digit radix sort of u32 keys and their u32
values, eight bits a pass. make-sorter makes a Sorter once for a
SortLane it reads from (from), one it leaves the sorted pairs in (to),
a capacity, how many low bits of each key to sort (8, 16, 24 or 32), and
optionally a buffer whose first u32 the device writes with how many pairs
to sort. dispatch-sort encodes the sort into a compute pass.
- Lanes. The passes alternate between
toand a spare lane of the sorter’s own, so that the last writesto; a sort of 8 bits, one pass, makes no spare. Sofrommay beto, a sort in place, only for an even number of passes: 16 or 32 bits. A sort that reads its input where it is copies nothing first. - Counts. With a count, the sort writes nothing of
topast it, and its work on keys is that of the pairs counted, whatever the capacity: each pass runs at most 4,096 workgroups, which share the counted blocks of 256 keys in runs. The digit table is sized by the capacity, though: each pass writes and scans 256 counts a workgroup, 1,048,576 for a capacity of a million keys or more, even when the count is zero. Dispatching exactly the workgroups the count needs would take an indirect dispatch, which with Dawn’s validation takes about half a millisecond of wall time, and costs the device more than the runs do (WebGPU on Node). - The digit table holds 256 counts a workgroup, laid out digit-major
and scanned with
(snail shell graphics scan). Laid out by block instead, it would hold as many words as there are keys.
Ranking a key within its block is a count of the matching digits before it in workgroup memory, the simplest stable ranking. At step 7,000 of bicycle’s training, sorting 4.2 million depth keys of 32 bits takes 0.60 ms and 1.66 million tile entries of 16 bits 0.16 ms, on an RTX 5090.
Rasterized graphics
Middleware for drawing: composable pipelines and packers whose interfaces
are buffers and textures, in WebGPU’s own terms. The application decides
what to pack, when to copy and how to stitch passes together; nothing hides
behind a renderer object, and a pipeline’s interface is a Pod record that
changes when the pipeline does. Hearsay draws 2D quads from an atlas, and
Siegework a 3D frame of meshes into a G-buffer lit by the sun
(WebGPU design).
(snail shell graphics atlas)
Pictures composed on the GPU into padded slots of texture-array pages. A
Picture is Layers of regions of encoded images, each with its colors
swapped as listed, so art drawn in one palette is recolored, as LPC’s skin
ramps are. make-atlas makes the Atlas, a value the application keeps
with the rest of its state; atlas-pictures composes the pictures it lacks
in a render pass of the caller’s encoder, and atlas-slot and
slot-region say where each is. atlas-url reads a region back as a PNG
data URL, so a HUD’s img shows a composed portrait.
The host decodes each source image once, and the atlas keeps it. Slots are placed on shelves; when a picture no longer fits, every page is cleared and the pictures asked for are placed again. A slot keeps a transparent texel around its picture, so nearest sampling at its edge never reads a neighbour; gutters of repeated texels would be needed only for filtered textures, with mips, which the atlas does not have (atlas and quads).
(snail shell graphics quad)
2D quads in world units under a 2D camera (View2D), each a rectangle
turned by its angle, showing a region of one page of a texture array,
tinted, over what is drawn before it. make-quads makes a Quads once for
a texture and a target; draw-quads draws a run of Quads as one instanced
draw. Corners snap to the target’s pixels in the vertex shader. A Quads
draws one run a frame, since its buffers are written before the frame’s
commands run, and its instance buffer grows in powers of two.
(snail shell graphics mesh)
Meshes as tables: one geometry table holding eight shapes’ vertices and
indices (Box, Pyramid, Prism, Sphere, Tile, Tetrahedron,
Octahedron, Upright), each standing on y = 0 in the unit cell, written
once by make-geometry; an Instance table of Pod records grouped by
shape; and an indirect draw for each shape from its own first instance,
which the indirect-first-instance feature allows, since core WebGPU has
no multi-draw. upload-batch makes a batch’s buffers when it changes,
draw-meshes draws it, and release-batch lets it go.
An instance carries where it is and where it was, for motion, its yaw, scale, glow, color, metalness and roughness, whether it turns to face the camera, and an id for picking.
(snail shell graphics raster)
Mesh instances rasterized into a G-buffer, and translucent ones lit at once
over it. A program makes its Raster once (make-raster: pipelines,
geometry, and the camera’s and sun’s uniforms), a GBuffer for the
canvas’s size, and a Surface for each batch, remade when the batch
changes. A frame writes the camera and the sun (write-raster), draws the
G-buffer (begin-gbuffer, draw-surface), then opens the lit pass
(begin-lit), where (snail shell graphics passes) lights it and
translucent surfaces are drawn over it.
The G-buffer holds each pixel’s albedo, normal, material (metalness,
roughness and glow) and depth, and, when its Planes ask, the screen
motion since the last frame and the id of the instance drawn there, which
read-id reads back to pick what a tap is on. A plane left out has no
target and costs nothing. A Camera3D carries its view-projection and its
inverse, in closed form for a Pinhole or Parallel lens, so the lighting
recovers each pixel’s position from its depth
(meshes, the G-buffer and the sun).
(snail shell graphics passes)
Full-screen passes over a G-buffer. draw-sun, through a Sunlight made
once and relit when the G-buffer is remade, lights each pixel by
Cook-Torrance under the frame’s sun, with the same lighting translucent
surfaces get. The lit pass draws into a light-format target, rgba16float,
so a highlight can be brighter than 1, and draw-post, through a Post
made for the canvas’s format and size, brings it to the screen: tone mapping
by a Tone, then FXAA. Neutral leaves a color whose largest channel is
under 0.8 as it is, for scenes already in display terms; Filmic is John
Hable’s curve, for physical light.
(snail shell graphics fly)
A camera that flies, +y up. steered takes drags, W, A, S, D, Q, E, the
wheel and the exposure keys [ and ]; flown moves it by the time
elapsed. It starts back from a scene’s box with fly-over, or where it is
put with fly-at and fly-toward; fly-eye, fly-target, fly-fov and
fly-exposure say where it is and how it sees, and fly-camera is the
rasterizer’s camera. upright stands a scene whose up is another way. The
path tracer’s viewer and the splats viewer share it.
Gaussian splats
3D Gaussian Splatting (Kerbl et al., 2023), drawn two ways and trained on
photographs. splat draws gaussians as sorted quads, the fast way to view
a cloud; splat-train is the differentiable renderer, drawing tile by tile,
that training descends through, and splat-view draws a cloud with it, as
training saw it. src/apps/splats views clouds and src/apps/train trains
them (scans, sorts and gaussian splats,
tensors and training).
(snail shell graphics splat)
Gaussians as middleware: a storage buffer of Gaussian Pod records, each
placed by its row of a transforms table, projected to screen-space ellipses
by a compute pass (EWA splatting, with spherical harmonics to degree 3),
sorted far to near by (snail shell graphics radix-sort), and blended in one
instanced draw. A program makes its Splats once (make-splats) with room
for its gaussians and transforms, writes Clouds where it likes
(write-cloud, pack-cloud) and writes the transforms whenever they move
(write-transforms), so clouds are posed and composed without touching
their gaussians. A frame is sort-splats in a compute pass and
draw-splats in a render pass, both the caller’s.
A Gaussian keeps its center as floats and its rotation and its scale
with its opacity as f16s (Vec4h), 32 bytes a record; cloud-gaussian
reads one back. Each gaussian’s 16 colors of coefficients are f16s two to
a 32-bit word
(harmonic-words, 26 a gaussian), each degree from a word of its own,
so that color k’s three start at the word’s half 3k plus its degree
(harmonic-half). write-harmonics! rounds a gaussian’s floats into
them, and cloud-coefficient reads one back.
Gaussians a program has not written are zero, so transparent and culled.
write-cloud sends a cloud 65,536 gaussians at a time, since a write’s
bytes are copied whole into the runtime’s memory on their way and a trained
scene’s run to a gigabyte.
(snail shell graphics ply)
The PLY files 3D Gaussian Splatting trains: read-ply reads one into a
Cloud for splat, its header parsed into where each property sits and
each gaussian activated (scales through exp, opacity through the
sigmoid, the quaternion normalized), every gaussian on one row of the
transforms table, so a file is one posable cloud. write-ply writes a
Trained cloud as the reference implementation would, properties in its
order and nothing activated, so what reads the reference’s files reads
these.
(snail shell graphics colmap)
COLMAP’s sparse reconstructions, cameras.bin, images.bin and
points3D.bin: each camera’s intrinsics (read-cameras), each image’s pose
and file name (read-images), and each point’s position and color
(read-points). A pose maps the world into the camera, with +z forward and
+y down the image. Only the undistorted models training draws through are
read, SIMPLE_PINHOLE and PINHOLE; a distorted one is refused.
camera-sized scales a camera to the size of the photographs actually
loaded, each axis by its own ratio, and poses-up is the mean of the
cameras’ ups, the up a reconstruction lacks.
(snail shell graphics splat-view)
A Splats’s gaussians drawn tile by tile, by splat-train‘s graph
rendered for viewing, lowered to a program that reads the splats’ own
buffers, so writing a cloud or its transforms changes what both draw.
make-splat-view makes it, write-view-camera writes the camera the quads
use, encode-splat-view projects, bins and blends in the caller’s compute
pass, and present-splat-view puts the image on the caller’s target.
It blends front to back in floats over black, stopping where a pixel’s transmittance would fall under 1e-4, as training does; the quads blend back to front in the target’s precision. So it is closer to the photographs a cloud was trained on, and slower (the measurements).
(snail shell graphics splat-train)
Gaussian splatting as a differentiable tensor graph. render draws a
Cloud of params (splat-params) from a camera param (camera-param, 16
floats in COLMAP’s convention) into an image of a Sensor’s size, for
Training or Viewing, and grad differentiates its loss back to every
param (cloud-views); photometric-loss is L1 with D-SSIM.
Projection is ordinary tensor operations, so its gradient is derived. Binning into 16x16-pixel tiles is custom kernels around a filter of the gaussians that reach a tile, a sort of those by depth and a stable sort by tile, and passes no gradient; rasterizing and SSIM are custom nodes with hand-written adjoints. The sensor’s capacity bounds the tile entries, and the entries asked for are counted on the device, so the tile sort and the ranges cover only those (differentiable splatting).
Tiles are tile-side, 16, pixels a side, as gsplat’s are. Smaller tiles
spend less blending on pixels a gaussian misses, but bin each gaussian
into more tiles. On bicycle on an RTX 5090, 8-pixel tiles made training’s
step 7,000 faster on the device, 19.6 ms against 20.6, but the run reached
that step in 130 s against 112, since early gaussians are large and
binning walks every tile each one reaches, a thread a gaussian. They
slowed the viewer’s frame from 5.6 ms to 6.2. 4-pixel tiles, measured
before binning kept to the gaussians that reach a tile, slowed it from
6.0 ms to 9.8.
(snail shell graphics splat-fit)
Fitting a cloud to photographs, as three tensor graphs a host lowers once
for a capacity of gaussians and runs on one set of params:
training-step, the loss against a target photograph, Adam’s step on every
param and the statistics densification decides by; densification, which
clones small gaussians and splits large ones whose screen-space gradient is
large, prunes the transparent and the huge, and lays the cloud out again,
kept rows first; and opacity-reset. Every row of every param is a
gaussian, and live says which are drawn, so a cloud grows within its
capacity. The schedule is the host’s
(training on photographs).
Path tracing
glTF scenes path traced on the GPU, a frame at a time: first hits
rasterized into a G-buffer, the bounces after them traced through a BVH by
a wavefront of kernels, lit by an environment, and denoised. src/apps/viewer
flies through a scene this way. The path tracing primer
explains the physics, and the path tracer how the
pieces run and what they cost.
(snail shell graphics bvh)
Ray queries, which WebGPU lacks: a bounding volume hierarchy over any
Triangles, and kernels that trace queues of rays through it. build-bvh
builds it once, in one compute pass: Morton codes of the triangles’
centroids, a bitonic sort of them, the tree from the sorted codes, and its
boxes refit from the leaves up, then packed so each node holds both its
children’s boxes. make-ray-kernels makes the queries, intersect for the
nearest hit and occlude for any, with the program’s cutout test, and
trace-rays runs one over a queue.
A queue is a buffer of 80-byte rays and its count, so a kernel appends to it with atomics. A query is dispatched over the queue’s capacity, and the invocations past the count return: an indirect dispatch would launch only what the count needs, but with Dawn’s validation each takes about half a millisecond of wall time, more than the idle workgroups cost (the BVH and ray queries).
(snail shell graphics environment)
Light from all around a scene: an equirectangular Environment, made on the
device from a Radiance HDR file (read-hdr, hdr-environment), the format
of Khronos’s glTF sample environments, or drawn from a Sky with a sun
(sky-environment), with the table that samples it by its light. A path
tracer binds environment-group to look it up and to sample it.
read-hdr reads a file’s header and the start of each row, which is all
that can be wrong with one, so a program checks its file before it puts
anything on the device; hdr-environment then decodes the pixels there, a
row a thread, and averages them down to the width asked for.
(snail shell graphics restir)
reservoir-shader supplies the WGSL types and operations for weighted
reservoir sampling. LightSample holds a direction and its scalar target.
Reservoir exposes the sample, weight sum, represented proposal count,
one-based emitter slot (zero for a sky direction), and two packed 16-bit
square coordinates. Reflecting the square across its diagonal yields the
uniform barycentric point on that triangle. reservoir_draw adds a draw
with its proposal density and returns whether it was selected.
reservoir_merge takes a donor, its target at the receiver and
the count it contributes. Each accepts a uniform random draw for selection.
reservoir_weight derives the final shading multiplier.
reservoir-buffer allocates one 64-byte SurfaceReservoir per pixel.
The 32-byte reservoir is followed by the octahedral normal, triangle ID,
clip depth and a 16-byte VisibilityHistory. Its recent and previous
entries each hold an i32 source key and f32 visibility estimate. Key zero is
empty. Positive keys name mesh emitter slots. Sky regions use −1 through −6
and the analytic solar disc uses −7. Punctual keys are −7 minus the one-based
lamp ID. Moving slots come first, followed by static lights in scene order.
All grid copies of a static fixture share its ID. Directly uploaded grid
entries with zero in intensity.w use their texel address. An application that
reorders moving lights gives the new occupant that slot’s recent estimate.
observe_visibility takes a history, a nonzero key, a shadow test result
and an update gain, and returns the updated history.
(light-guiding-rates settings paths-per-pixel) exposes the four
f32 fields uploaded with each wave. They are the exploration probability,
visibility update gain, minimum visibility used in selection, and maximum
temporal donor count in multiples of the fresh count. The settings are a
LightGuiding with exploration-floor in [0, 1] and positive integer
recovery-frames. Pass them to Tracer-guiding-set on an existing tracer
and use the returned tracer for subsequent draws. Learning which lights reach a surface
(snail shell graphics gltf)
A glTF 2.0 scene, a .gltf file’s JSON or a .glb file, read by read-gltf
into what drawing and tracing it need: its buffers and images, each
primitive’s accessors as byte offsets into the buffers laid end to end, its
materials, and each primitive Placed by the default scene’s node
hierarchy. The buffers’ bytes are not read here: they go to the device
whole, and a compute pass unpacks each accessor. gltf-bounds is the
scene’s box.
It reads triangle primitives with positions, normals, a first set of texture coordinates and tangents, indices of any width, metallic-roughness materials with their textures and alpha modes, and KHR_materials_emissive_strength. gltf-transformed composes a column-major instance transform with each placed primitive. Unsupported sparse accessors and Draco or meshopt compression are reported through attempt-reading. Source
Skinned animation
(snail shell graphics gltf animation) reads the hierarchy, skins, vertex influences and animation clips. (snail shell graphics animation) samples and blends the local transforms. posed-nodes evaluates the hierarchy once for an instance. A rigid prop follows the world transform of its named node. skin-palette applies inverse binds to those same world transforms for mesh deformation. Skinning and the tracer · Animation · glTF animation reader
(snail shell graphics trace scene)
A glTF scene on the device, loaded once by load-scene: every triangle in
the world in one vertex and one index buffer, unpacked from the scene’s
buffers by a compute pass; the materials in one storage buffer; and every
image in one layer of one texture array with its mips, since WebGPU binds
no unbounded table of textures. A layer is the same size whatever the
image’s, and a material names its textures by layer. Rasterizing and
tracing read the same buffers, so what is drawn is what rays hit. A
scene’s blended says whether any material is blended, so that the
tracer makes its blended layer only for a scene that has one.
Scene.emitters holds an EmitterTable built during upload. Its
triangles plane contains sorted scene triangle IDs as r32uint,
padded with 0xffffffff. Its distribution plane holds emitted RGB and
inclusive row weights as rgba32float. An extra column holds the cumulative
weight of the rows. The tracing shaders read these planes at scene bindings
6 and 7. Both planes support texture readback. Sampling weights use the upload pose. A reused point reads the
current vertex buffer. make-emitter-table takes sorted, distinct triangle
IDs and the unpacked vertex, index and material buffers. A scene made with
Scene-emitters-set borrows the original geometry, images and sampler.
Release the owning scene once and release a separately allocated replacement
table with release-emitter-table.
(snail shell graphics svgf)
A denoiser for one path a pixel: spatiotemporal variance-guided filtering
(Schied et al., 2017). filter-svgf reads a frame’s noisy radiance and the
G-buffer planes it was traced from, keeps a history across frames, and
writes the filtered light, scaled by an exposure, into a plane the program
gives it, such as a Post’s. A frame is two compute passes: temporal
accumulation, variance and the first à-trous level, then four more levels;
resize-svgf follows the canvas. Its planes are 32-bit floats: a still
camera’s history is a running average, which a frame moves by as little as
1/4096, a step half floats round away.
(snail shell graphics trace render)
A scene path traced to the canvas, composed of the libraries above: the
first hits rasterized into a G-buffer, a wavefront of kernels for the
bounces, each bounce’s rays traced by bvh’s queries and lit by an
environment, then svgf and (snail shell graphics passes)’s tone
mapping and FXAA. A scene with blended materials also gets a blended
layer: the nearest blended surface in front of the first hits, traced and
filtered on its own, then blended over them by its alpha
(the blended layer). make-tracer makes a Tracer once for a scene and the
canvas, resize-tracer follows the canvas, retrace gives it another
scene and environment with the same pipelines and targets, and
draw-traced draws a frame, its paths bouncing as many times as it asks,
up to most-bounces. Its final argument is a TraceSettings record with
display-width, display-height and samples (one or two). Both sizes use
Halton-jittered first hits, SVGF and the stable display resolve.
encode-trace-observation takes a caller-owned command encoder, tracer,
camera, pixel spread, bounce depth and random seed. It writes the G-buffer,
per-layer radiance and noisy targets for one fresh full-resolution sample.
The caller can encode reconstruction or a readback next, then submit.
Submit before writing the next observation into the same kit. The caller
supplies the observation camera, including any chosen subpixel offset.
Independent observations leave the interactive history intact. (snail shell graphics still) provides
read-traced-radiance and trace-reference for the capture format.
tracer-frames counts the frames since the camera last moved or the bounces
changed. A frame
Game simulation and stories
These libraries run on the CPU. An application chooses a fixed timestep and owns the game world, input, renderer and save.
Quests
(snail shell game quest) exports define-quest. Supply the stage and event types and one row per transition. The generated function takes a stage and an ordered list of observations. It returns the result of the first applicable transition, or the original stage. Payloads bind in ordinary patterns, so a counted goal can carry its current count. A tick advances at most one stage. The application decides which observations the world supplies. Quest example · Source
Dialogue
(snail shell game dialogue) reads a Dialogue made of named passages, lines and ordered replies. Each reply names its destination. The game saves a Cursor containing the passage ID and line index. Import a baked Ink library or construct a dialogue directly. open-dialogue, continue-dialogue and answer-dialogue return an optional cursor. An out-of-range answer keeps the current cursor. Ink authoring · Source
Compiling Ink
(snail shell game ink) supplies ink-library for a generate-library recipe. Its first filename is the Ink entry point. Each additional filename links a source used by an INCLUDE. At build time the producer calls inklecate and returns a library exporting conversation as a Dialogue. Games import that generated library. make test-ink builds an independent project, edits its story and included knot, and exercises failed generations. Example recipe and Ink files · Source
Movement and boarding
(snail shell game terrain) reads a GRD1 contact mesh. ground-height evaluates the triangle under an XZ position, ground-slope samples a grade across a given span, and nearby-solids supplies local building and trunk footprints for a sweep. A cell index bounds the triangle search. Ground and kerbs support movement, while obstacles restrict it. Terrain file layout
(snail shell game physics) sweeps a disc through axis-aligned footprints, slides a walking body along a wall, and measures clear paths and shot distances. (snail shell game vehicle) integrates a rear-axle bicycle model and checks its rotated chassis extents. Coordinates are metres in the XZ plane. Heading zero faces north along −Z and positive angles turn east. Physics · Vehicle A caller keeps one DriverControls, advances it with adjust-driver! each tick, and passes its pedal and wheel to road-speed and road-steering. These functions model power-limited acceleration, braking, road grade and a shared longitudinal/lateral grip limit. bicycle-step integrates the resulting signed speed and steering angle.
(snail shell game rigid-body) gives each body a 3D centre, unit quaternion, world-space linear and angular momentum, inverse mass and body-space inverse inertia. Construct a box with box-body. Apply gravity with accelerate! and an impact with apply-impulse! at a world-space point. Rotate local spheres into world space with world-balls. Generate sphere-pair and plane contacts, pass them together to solve-contacts!, then advance every body with integrate!. Each solver sweep accumulates a normal impulse and bounds the tangential impulse by Coulomb friction. The caller chooses the step size and sweep count. Fast objects can cross thin geometry between discrete steps. Sequential impulses
(snail shell game chassis) puts these bodies on a road. road-chassis starts a car aligned with the measured grade. step-cars! applies pedal and steering inputs while the wheels have traction and solves the whole fleet against vehicle bodywork, the terrain and nearby solid footprints. Gravity and collisions can pitch, roll or overturn a car. Four tyre contacts, a compound sphere hull and a local ground plane approximate its shape and support. chassis-body projects the 3D state onto the street map for navigation and boarding.
The chassis solver also accepts walking people through walker-step and step-traffic!. A walking person stays under foot control until a moving chassis makes contact. The solver then integrates a finite-mass body against the cars, terrain and walls in the same substeps.
(snail shell game boarding) advances a saved Rider toward a driver or passenger door, across the sill and into the seat. The car’s placement determines both anchors. An approach uses the four expanded chassis corners to find a clear way around either end. The game holds the car while crossing? is true and may reposition it if a waiting rider’s door is blocked. rider-body and seat-weight locate the actor and blend the seated pose from the same progress. Source
Roads and local traffic
(snail shell game atlas) opens compressed map bands already read through Resources. An Area holds the current sector and its eight neighbours. Call focus-area! as the player moves. The area keeps one eighth of a sector as a margin across its centre’s edge so that a switchback can cross the seam without rebuilding twice. prepare-area! takes a forecast position and inflates at most one missing sector per call. When ready, it returns the candidate area in drawing order. The current area advances only through focus-area!, which reuses completed work and handles teleports immediately. Overlapping sectors keep their decoded contact data, mesh and signs. area-height, area-slope and area-solids query the same geometry the renderer uses.
(snail shell game roads) reads a directed junction and street-name table. road-route uses A* with straight-line distance as its lower bound. follow-edge places a body a given distance along an edge and a lateral distance from its centre. (snail shell game traffic) uses the outgoing edges for its drivers and chooses clear sidewalk segments for pedestrian patrols. replacement-motor checks the snapped lane position against the cab’s actual direction of travel, its stopping space and nearby bodies. It returns an option so a caller can keep an existing car when every candidate is unsuitable. The application supplies the nearby people and vehicles, traffic density and time step. Road graph
Following a moving body
(snail shell game chase) advances a camera focus in world space. Pass follow the previous Chase (or (None) for the first frame), a target position, heading in radians, elapsed seconds and initial boom length. The focus follows a critically damped spring, the heading takes the short arc, and a displacement of 24 metres or more resets the rig at the target. The caller places the camera using that focus and boom. Source
Actors and scenery
(snail shell game humanoid) blends idle, stride, upper-body action and riding clips on a generic rig. Distance walked advances stride. (snail shell game pedestrian) follows waypoints and resumes them after fleeing a nearby disturbance. Humanoid · Pedestrian
(snail shell game drawing) places rigid parts relative to a model. (snail shell game figure) assembles figures from these parts. (snail shell game scenery) places the same shapes into a glTF scene and builds matrices for moving them. Drawing · Figure · Scenery
Tensors
A GPU tensor library in the shape of Resin’s: a program builds a lazy graph of nodes, rewrites it symbolically for gradients and optimizer steps, fuses it, and lowers it explicitly to plain WebGPU objects the caller owns, which run as often as a training loop likes, on the page or on Node. Splat training is its main user (tensors and training).
A program uses them in this order:
(let* ((loss ...) ; (snail shell tensor)
(dw (list-ref (grad loss (list w)) 0)) ; (snail shell tensor grad)
(updates (adam-updates "adam" (adam 0.9 0.999 1e-15)
(list (new Trained (param w) (grad dw) (rate (scalar 0.01))))))
(fused (fuse-program (list loss) updates)) ; (snail shell tensor fuse)
(program (lower gpu "fit" (● fused first) (● fused second))))
(run-program gpu program)) ; (snail shell tensor lower)
(snail shell tensor)
Nodes, ports and views, and the operations that build them. A node computes
one dense buffer for each of its ports, and a program works with Views:
an accessor over a port, an offset, a shape and a pitch for each axis, in
elements. So narrow, transpose, permute, squeeze, unsqueeze and
broadcast-to make no node, and a pitch of 0 repeats an element. View is
an instance of Num and Fractional, so (+ a b) and (sqrt v) build
nodes, broadcasting as NumPy does.
- Leaves:
param(a buffer the host writes, by name),constant,fill,scalar,zeros-like,ones-like. - Maps and reductions: the elementwise operations (
exp,log,sigmoid,where,maximum, comparisons,convert,bitcast, …;halvesreads each u32 of a row as the two f16s it holds),sum,sum-all,mean,amax,aminandmatmul;mappedandreducedtake anExprbody directly, andmapped-portsa map of several bodies, one kernel writing a port for each, as fusing also makes them. - Data movement:
copy,reshape,gather,scatter-add,concat,stackandplace. - Sorts and scans:
sort-pairs,sort-first-pairs(only as many pairs as a one-elementu32view says, the rest unspecified) andexclusive-scan. - Filters:
filter-rowskeeps the rows whose value is not 0, as aFiltered: their indices packed to the front and 0 past them (ids), 1 for each row below their count and 0 from it (live), and the count, oneu32on the device.kept-rowstakes a view’s kept rows by them, 0 past the count. - Custom kernels:
customruns WGSL a library writes, with its own adjoint, on ports the lowering zeroes first.
A node is known by its key, a hash of what it computes: its kind, its parameters, and its arguments’ keys and accessors. Building the same computation twice builds the same node, so a graph shares its common parts, and a custom node’s adjoint can rebuild its forward node and get the same one back (graphs and views).
(snail shell tensor grad)
(grad loss views) answers the gradient of a scalar with respect to each
view, as views of new nodes; nothing runs. It walks the nodes the loss
depends on from last to first, and each kind of node hands each argument
its share of its ports’ gradients: a map back through each of its bodies,
a reduction over its span, a custom node by its own adjoint. A port that
nothing the loss depends on reads has no gradient, and adds nothing.
A body of one operation, as every elementwise operation, matmul, concat
and small reduction builds, hands each argument a node built by that
operation’s rule. A body of several operations, which a library writes with
mapped, is differentiated as one expression: its gradient is one map for
each argument, which a kernel computes whole. The splat trainer writes the
harmonics’ basis so, sixteen numbers a gaussian from its direction
(gradients and Adam).
A port’s shares are gathered once every node reading it has handed one back. A share through a view that reads the whole port comes back as a view. Shares through views that each read a run of one axis, as the columns of a matrix do, are joined along it with zeros between, a concat the reading kernel takes in; anything else is placed among zeros and added. Joining took bicycle’s training step from 35.6 ms to 27.6 ms on an RTX 5090, since placing wrote and read the whole port once a share (gradients and Adam).
(snail shell tensor adam)
Adam (Kingma and Ba, 2015) as more graph. adam-updates builds the update
of each Trained param and of the two moments Adam keeps for it, as
(param new-value) pairs a program commits after each run. The moments and
the step count are params of the program (moment-names), which start at
zeros as every buffer does and which a host may write, as densification
does. A learning rate is a view, so a schedule is a param the host writes
each step.
(snail shell tensor fuse)
fuse-program rewrites a program’s sinks and updates into fewer nodes
computing the same values: a map whose argument another map computes takes
that map’s body in place of the load, so one kernel computes both and the
producer’s buffer is written only if something else reads it. A
reduction’s body takes in maps the same way, so a large matrix product
computes its products as it sums them; nothing takes in a reduction, a
gather, a concat that is not a pack, a sort or a custom kernel.
Two limits shape it: a body stays within 256 distinct expressions, each counted once however many times it is inlined, and a kernel within the eight storage buffers every device allows, its ports among them. A producer read by several kernels is computed in each, so it is taken in only where that holds no more memory, for no longer, than its own buffer would. A producer whose port is kept anyway, such as an update’s value or a buffer a later kernel reads, is written by the map reading it whole, as a port of its own, so Adam’s three updates of a param are one kernel (fusing).
(snail shell tensor lower)
lower turns the nodes a program’s sinks and updates need into plain
WebGPU objects, once: a buffer for each port, a pipeline and bind group for
each dispatch, and their order, all in a Program the caller owns.
run-program runs it in a compute pass of its own, or encode-steps into
the caller’s, as often as it likes; write-param, read-param and
read-sink move data; release-program lets it all go.
- Kernels are generated per node with every size a literal, so two
nodes computing alike share a pipeline. A
Fillargument is a literal too, with no buffer. A choice of zero,(where condition value 0)with one condition a row, computes its value inside anif, so the rows the condition culls skip what the value computes in that kernel: a mask. A kernel computes each choice once, however many places fusing copied it to. A filter packs the rows it keeps, so a choice by itsliveskips the rest together. - Buffers return to a pool once the last node reading them has run; params, constants, sinks and updates keep theirs. An update that a map computes whole is written in place, into its param’s buffer, each port of a map of several into its own param.
- Counts the device computes size the work of sorts and of custom kernels that take them: a fixed number of workgroups loop over the work below the count (lowering and running).
- Sharing params:
lower-withandgiven-bylower programs that take turns on one set of params, as a training step and densification do, andstash-paramsandunstash-paramscarry them into a larger program.profile-programtimes each step alone, andprogram-memorytotals the bytes its buffers take, by use.
(snail shell tensor eval)
(evaluate sinks inputs) evaluates the same graph on the CPU, each port an
array of F64 rounded or wrapped as the GPU computes it: the executable
specification each kind of node’s kernels are tested against, and the way
gradients are checked by finite differences without a device. A custom
node has no CPU form, so a graph with one is not evaluated here.
bytes->values and values->bytes convert a port’s buffer.
Tools
The compiler, the build and the editor support are snail-scheme libraries
too, which bootstrap/cli.sld, the snail-scheme command line, puts
together (development toolchain).
(snail shell compiler)
The compiler’s passes in order, from a program’s source path to
WebAssembly text: source->checked reads, expands and checks a program, and
checked->wat specializes, prepares and emits it; source->wat does both.
Every invocation reads, checks and emits the whole program afresh. Chez
runs this source as stage 0, and Node runs it compiled to WebAssembly, so
it imports only (snail core base), (snail core table) and
(snail core io) and avoids what the two hosts would disagree on, such as
integer overflow and the order of a table’s keys
(compiler architecture).
Its passes and supporting modules, each (snail shell compiler NAME):
| Module | Does |
|---|---|
read | Text to located syntax, by recursive descent; its lexical rules are exported for highlighting; how any pass stops a compile with a diagnostic |
library | Where a library’s file is, and what it declares before it is expanded: a define-library, or a generate-library’s producer |
inputs | The requests a compile makes for what it was not given, such as a producer’s output |
expand | Located syntax to the core program: libraries loaded, every identifier resolved, macros run, entities recorded |
core | The core language every pass after expansion shares: types, expressions and the program’s tables |
check | Hindley-Milner checking with typeclass evidence, each expression rebuilt with its type |
specialize | Each definition reached copied once for each set of types it is used at |
prepare | Fixed declarations and normalized items, with what each call may suspend to |
wasm | Prepared code to WasmGC: representations, closures, tail calls and the frames a suspension saves |
driver | One invocation, shared by stage 0’s entry and the command line’s compile |
sha256 | The digest linked files are named by (text and data) |
The compiler tour follows a program through them.
(snail shell assembler)
assemble, WebAssembly text to a binary module, and link, static linking
of modules into one, in-process. Only a tool linked with the toolchain’s
runtime can use it: the plain runtime leaves the text parser out, so a
program that imports this library links with the toolchain’s instead
(assembly and linking).
(snail shell project build)
A script’s build, which snail-scheme build and run run: build-script
compiles, links and packages a script into a generation of its own, then
publishes it by replacing the script’s link in its workspace’s build/ at
once. A compile that reaches a generated library runs its producer first,
then compiles again. A build that fails removes every generation it made,
and only those, so earlier outputs stay published. check-script and
check-library compile as a build does and write nothing, for the language
server. A build’s Mode is Debug or Release, which also optimizes the
module with wasm-opt; its Platform is Node or Browser
(workspaces and builds).
(snail shell project web-app)
A browser build’s installable web-app manifest and the page’s links to it:
web-app-manifest is the default manifest, and with-web-app inserts into
a page the manifest’s link and the name of the program’s module, keeping
the rest of the page byte for byte. A project’s own
public/manifest.webmanifest replaces the default whole
(browser packaging).
(snail shell lsp)
serve-language, snail-scheme lsp: the Language Server Protocol over
standard input and output for one workspace, the folder an editor opened.
It checks each open document in this process, as a build would, whenever
the editor opens or saves it, and answers diagnostics, hover (a name’s type
where it is used), definitions, formatting and semantic colors. A check
reads the disk, so it reports what was saved. Zed and VS Code start it
through editors/
(the language server).
(snail shell format)
The repository’s formatter, which scripts/format-scheme and the language
server share: format-source puts each import specification and field on
its own line, indents every line under its call’s first argument or two in
for a special form’s body, and breaks a line whose code runs past
format-width (100 columns), never joining lines. make check holds every
tracked Scheme file to it (the formatter).
(snail shell highlight)
highlight-tokens, source text as tokens that tile it, each of a Class
for coloring, by the compiler reader’s own lexical rules, adding only the
comments and whitespace a reader discards. Text the reader would reject
still classifies. The book’s code blocks, the language server’s semantic
tokens and the range it marks for a diagnostic all come from it
(code highlighting).
Runtime interfaces and targets
A (snail runtime …) library declares one host interface’s WebAssembly
imports as externs, and nothing else, so it emits no module of its own. A
shell library imports it under the prefix host- and exports the function
that makes the host’s capability, each operation an extern; a target
provides those capabilities to main. A program uses the shell libraries,
not these (what the host is trusted with,
the host boundary).
Only scalars cross: a handle is an I32 the host gives, a string crosses a
character or a scalar at a time, and a descriptor as staged Bytes. An
operation that waits starts with one call and finishes with another under
the ticket its completion wakes, through (snail shell task)’s
through-host.
The page
host/browser/ provides these on the page:
| Library | Declares | Made into a capability by |
|---|---|---|
(snail runtime browser events) | The page’s event queue and its fields, the random seed, the canvas’s size and the boot report | (snail shell page)’s host-events |
(snail runtime browser storage) | Loading and storing the page’s save, read back a byte at a time | (snail shell page)’s host-storage |
(snail runtime browser dom) | The document’s nodes and listeners as handles, text as UTF-8 | (snail shell dom page) |
(snail runtime browser fetch) | Requests and event streams, staged a part at a time | (snail shell fetch page) |
(snail runtime browser files) | The pickers, and the latest choice of files | (snail shell files page) |
(snail runtime gpu)
The host’s WebGPU device, as host/browser/gpu.mjs provides it on the page
and, over Dawn, on Node (host/native/gpu.mjs): each object an I32 id the
host gives it when it makes it, a descriptor staged as Bytes of words and
texts, and the device, reads and image decodes waited for by ticket. A
submit lets go of each object destroyed since the last one.
(snail shell gpu) makes its Gpu over these.
Node’s own
host/native/ provides these on Node:
| Library | Declares | Made into a capability by |
|---|---|---|
(snail runtime native socket) | TCP and UDP sockets as handles, each wait started under its ticket and answered with numbers and held bytes | (snail shell socket) |
(snail runtime native process) | Child processes and termination signals, answered as the sockets are; a command sent a character at a time | (snail shell process) |
(snail runtime native async-files) | Bounded file reads, a path staged a character at a time | (snail shell async-files) |
(snail runtime native web) | A file’s length at a URL, and parts of it, answered as the sockets are; a URL sent a character at a time | (snail shell web) |
Each file’s header tabulates what its operations answer (the Wasm boundary).
(snail runtime resource)
A linked file’s bytes, read on every host when a task asks: read starts
under a ticket, finish answers the length and holds the bytes, and byte
reads them. (snail shell resource) makes its Resources over these.
(snail runtime wasm)
Compiling and instantiating WebAssembly modules on every host
(host/native/run-snail.mjs and the page’s loader): a module compiled from
bytes into a handle, linked against providers chosen one per import, and
its exports found by name. (snail shell wasm) makes its Wasm over these.
(snail target node)
The Node target, a program run by host/native/run-snail.mjs. start runs
the program’s main as the first task of the host’s scheduler, and main
asks for what it needs by its parameters’ types; a function here of no
parameters provides each, made from the one Host the target holds. Every
host gives Host, Arguments, ProcessEnvironment, an OutputPort
(standard output), Clock, Resources and Wasm. Node adds an
InputPort (standard input), Fs, Files, Processes, Signals, Tcp,
Udp and Web. A program that draws asks for Host and makes its Gpu with
host-gpu (capabilities).
(snail target browser)
The browser target, a page run by host/browser. As on Node, start runs
main as the first task, and main asks by its parameters’ types. Beside
what every host gives (the OutputPort is the console), the page gives
Events, PageStorage, Gpu, Dom, Fetch and FilePicker.
Liberated Pixel Cup art
src/lpc/ holds packs of Liberated Pixel Cup
character art and the libraries that draw from them: bodies and heads from
the character bases, hair, and garments from the clothing updates and
wulax’s sprites. A program dresses its characters from the catalog, and a
generated library embeds exactly the sheets they wear, with their credits,
as (apps hearsay art) does for
Hearsay’s
cast.
(lpc layout)
The geometry every LPC sheet shares: 832 by 1344 pixels of 64-pixel cells,
four rows each of casting, thrusting, walking and slashing, four of
shooting, and one of falling hurt, each motion’s four rows facing away,
left, toward the viewer and right. walk-region is the four walking rows
alone, the first frame of each the figure standing still, and
face-region, in a picture of those rows, the standing figure facing the
viewer from the shoulders up: a portrait. universal-book and walk-book
are a whole sheet and its walking rows as (snail shell sprite)
spritebooks.
(lpc catalog)
What the packs draw, and where: the adult Builds and Heads, Skins,
HairStyles and HairColors, and Garments in their Dyes, each named as
the pack’s files name it. For each layer the catalog gives the file and
region holding its walking rows and the color swaps that recolor it
(body-sheet, head-sheet, hair-sheet, garment-sheet), and which
builds can wear each garment, in which dyes. Children, skeletons and zombies
are not catalogued yet.
(lpc wardrobe)
Characters dressed from the catalog: dress resolves an Outfit into the
sheets of a Character’s walking rows, so a character has a sheet for every
layer it wears, and walk-picture and portrait compose them into
(snail shell graphics atlas) pictures. character-paths lists the files a
character’s layers come from, to embed, and fingerprint hashes its layers
and their swaps: equal characters agree, and a changed one almost surely
differs.
(lpc skins)
A generated library: the skin ramps, read from the character bases’ palette
file when it is built. (ramp "olive") is that skin’s colors, darkest
first; a head drawn in one ramp is recolored to another by swapping each
color for the one at the same place.
(lpc credits)
Who made the sheets a program embeds, and under which licenses, read from
the packs’ own credit files when the program is built: each Credit names
a part as its pack does, with its authors, its licenses and its sources,
which a CC-BY credit asks for. credits-library fails the build when an
embedded sheet has no credit, so what a program credits cannot fall behind
what it carries.
(lpc embed)
Helpers for the generate-library recipes that embed the packs:
embed-library makes image files byte array literals, and ramps-library
makes the packs’ JSON palettes color lists. A recipe runs when its library
is built, so an image’s bytes reach the compiler as they are
(generated libraries).
Datasets
src/datasets/ holds no data. Its libraries are recipes that read a
published dataset into the machine’s cache the first time a program that
imports one is built, and link each of its files, so the program reads
them as resources and ships them in its store/
(generated libraries).
A dataset is then a dependency of the program, as the LPC art is
(LPC): what a program imports is what it carries, and which
scene it trains on is in its source, not in a path given when it runs.
(datasets mipnerf360)
Mip-NeRF 360’s nine scenes (Barron et al., 2022), each photographed from
all around, with COLMAP’s sparse reconstruction, sparse/0, and the
photographs at their full size, images, and at a half, a quarter and an
eighth of it, images_2, images_4 and images_8. Google publishes
seven in one archive of 12.5 GB and flowers and treehill in another of
4.5 GB; each is pinned here by its end’s digest, and a scene’s files are
read from it a member at a time ((snail shell web zip)),
so a scene at the size 3D Gaussian Splatting trains it is a few hundred
megabytes, fetched once a machine.
scene-library is a recipe’s work: the library of a scene’s
reconstruction and one folder of its photographs, exporting files, each
file by its path in the scene, such as "sparse/0/cameras.bin", with its
Resource, and photographs, the folder’s name. A program that wants
another folder makes a library of its own, as each scene’s below does
with the paper’s:
(generate-library (apps train full)
(import
(snail core base)
(only (snail core io) Fs ProcessEnvironment)
(only (snail shell web) Web)
(datasets mipnerf360))
(lambda ((fs Fs) (web Web) (environment ProcessEnvironment))
(scene-library fs web environment
(list "apps" "train" "full")
"bicycle"
"images")))
scene-folder reads the same files and answers where the cache keeps
them, for a program that reads a folder, as the reference trainers of
benches/splat-training
do. Bicycle’s are in
~/.cache/snail-scheme/zip/0be64f576d63b68855fc9746daa2d62262f013c2ddf82abf20aadbf62c0f8477/bicycle/,
its sparse/0/images.bin among them, which the splat viewer turns a
trained cloud upright by.
The scenes
Each scene’s library holds its reconstruction and its photographs at the size the paper trains it: the outdoor scenes at a quarter, the indoor at a half. Its files are what the program ships; the archive keeps them deflated, so less is fetched.
| Library | Photographs | Files | Fetched |
|---|---|---|---|
(datasets mipnerf360 bicycle) | 194 at images_4 | 225 MB | 201 MB |
(datasets mipnerf360 flowers) | 173 at images_4 | 223 MB | 201 MB |
(datasets mipnerf360 garden) | 185 at images_4 | 257 MB | 233 MB |
(datasets mipnerf360 stump) | 125 at images_4 | 139 MB | 125 MB |
(datasets mipnerf360 treehill) | 141 at images_4 | 168 MB | 151 MB |
(datasets mipnerf360 bonsai) | 292 at images_2 | 373 MB | 335 MB |
(datasets mipnerf360 counter) | 240 at images_2 | 320 MB | 291 MB |
(datasets mipnerf360 kitchen) | 279 at images_2 | 431 MB | 385 MB |
(datasets mipnerf360 room) | 311 at images_2 | 336 MB | 315 MB |
The first build of a program that imports bicycle took about 40 seconds here, most of it fetching; later builds, in any checkout, link the files from the cache, and the library’s recipe adds about half a second to a build. An editor that checks such a program runs its recipes as a build does (editors), so it may be the one that fetches first. The build also places each file in the workspace’s store, as it places every linked file, so each checkout that builds the program holds a copy of the scene beside the machine’s.
Runtimes
snail-scheme’s shipping target is WebAssembly GC. Tasks are suspended
computations, scheduled in snail-scheme; a host drives the scheduler and
completes the operations tasks wait on. A runtime supplies the platform’s
capabilities and owns the computations that use them. Each
instance of a program is single-threaded; parallel work runs as several
instances, which will talk through queues and shared memory
(instances, proposed).
The host is the surrounding platform, such as Node or a browser. A runtime owns language tasks; an OS process owns its platform execution environment. The toolchain terms keep these boundaries distinct in the project and development design.
The task contract specifies the replacement for
the actor API. It separates scheduling, capabilities and the
values tasks hold. The actor request/reply API has been removed. Task operations
run in the CLI and GUI. Applications describes
pages’ saves on that runtime.
Values describes sharing, mutation and resources.
The socket capabilities bind typed, replaceable TCP and UDP operations
to native Node resources, with cancellation and shutdown owned by the runtime, and
Processes binds child processes the same way.
Execution and waiting
Every call into Wasm runs until it returns: no import suspends a Wasm
stack. A task waits by returning. Its suspension unwinds through
each frame to the task’s with-prompt, whose handler hands the rest of the
task back to the scheduler, and the host’s call returns. The host then runs its own
event loop, and calls in again for the next turn
(driving the scheduler). A host operation that completes
later starts on one call and finishes on another, under a ticket its
completion wakes. A pending Promise alone does not keep a Node process
alive; a runtime must account for outstanding work and own any required
process-lifetime token.
An event loop, an I/O readiness service and a scheduler serve different
purposes. Linux epoll reports which descriptors can make progress; it
does not schedule language closures. Our hosts
use JavaScript platform APIs for Node and browser I/O notifications,
asynchronous file reads among
them.
snail-scheme’s scheduler owns tasks on both hosts. It does not need its own epoll wrapper. See the
Linux interface.
Scaling the deployed program
For CPU parallelism today, run independent instances in separate execution agents or processes and distribute requests at the service boundary. A reverse proxy can load-balance several processes. Each instance has its own managed heap; communication uses an explicit external protocol.
snail-scheme does not need a second compiler backend to use multiple
independently hosted instances.
Direction
Node and the page are today’s hosts, not the only ones snail-scheme is for.
Others, such as workerd, should be
able to run the same programs, so nothing a program or library does may
depend on
JavaScript: a host provides Wasm imports, and JavaScript is the glue that
provides them on Node and in the page.
Both hosts already do only what a host must: WASI, the Wasm primitives of
(snail shell wasm), their device services, WebGPU among them, which Node
gets from Dawn (WebGPU on Node), and
the loop that turns the scheduler. A program is one module linked with its runtime, which each
instantiates. An engine written in snail-scheme once linked programs
compiled one library at a time
(#660); it went when
every build became one linked module.
A native executable embedding wasmtime once ran
programs that needed only WASI and files; it is removed, since its
collector made the compiler compiling itself take 46 s against Node’s 1.3 s
(#562) and it was a
second host to keep for no program that needed it. A target for a new host
handles the portable subset of capabilities
(scripts) and adds its own. workerd’s isolates
are not OS processes, and its WasmGC and import support must be checked
before promising compatibility.
The Rust support module, snail.core.support from
crates/snail-scheme-support, is what lies beneath (snail core …), not a
runtime interface. The Unicode tables, the transcendental math and float
printing are snail-scheme code, so what remains is I/O. Proposed: it
moves through WASI once memory primitives exist (the crate’s README has the
plan).
Future work
Instances, queues and shared memory proposes how several single-threaded instances will cooperate. Continuations and parallel execution retains the earlier backend research.
Task operations
(snail shell task) defines tasks and the scheduler that runs them, both
in snail-scheme:
| Operation | Meaning |
|---|---|
(dispatch work) | Run a thunk as an independent local task. |
(yield) | Let every other ready task run first. |
(sleep milliseconds) | Wait for an I64 number of milliseconds. |
(ticket) | A fresh I64 ticket, naming one wait. |
(await tickets) | Wait until every ticket in the list is woken. |
(tasks-wake! scheduler ticket) | Cross the ticket off the task waiting on it, readying the task once none is left; a stale ticket does nothing. |
(tasks-close! scheduler) | Forget every queued, sleeping and waiting task; none runs again. |
(through-host start finish) | Wait on a host operation by ticket (below). |
(make-mailbox) | A new, empty (Mailbox T): a queue of messages between tasks. |
(mailbox-post mailbox message) | Add a message at the back. Posting never waits. |
(mailbox-receive mailbox) | Take the message at the front, waiting until one is posted. |
(mailbox-try-receive mailbox) | Take the message at the front, or answer None at once when there is none. |
(import
(snail core base)
(snail core io)
(snail shell task))
(define (main (out OutputPort)) (→ Unit)
(dispatch
(lambda ()
(yield)
(write-line out "the child finishes after main returns"))))
A task waits by suspending: yield,
sleep and await stop it where it is, however deep in its calls, and
the scheduler keeps the rest of it. Waiting needs no capability and is in
no type, so an ordinary function may call a callback that waits, and a
function that waits is written like any other.
The host creates one explicit Scheduler for a program and passes it to
the program’s main export, turns, wakes and closure. That export is the
entry’s start, which calls its target library’s start with the scheduler
and a thunk that calls the root main with its capabilities, so main
runs as the scheduler’s first task and may
yield, sleep or await like any other task. A child starts when
the parent yields or returns. Every task runs until it finishes: nothing
cancels one. Tasks that should stop early agree on it between themselves,
for example through a mailbox or a flag in a record they share. A trap
fails the run. The host reports it and closes the
scheduler, which forgets its queued work; Wasm traps do not unwind, so
nothing more runs in the trapping frame.
Whole-program and separately linked builds use this same explicit scheduler.
Libraries have no runtime initializers.
The operations are not actors: there are no request/reply protocols or supervisors. A task’s id names it to the host, which reports a trap under it, and to an application, whose loop is a task (applications).
How a task runs
A task is a function that runs one step of it. Its first step runs the
work under a with-prompt of the prompt every wait suspends to, waiting,
whose handler does not resume: it answers a Step holding the rest of the
task, to run when the wait is over.
(enum Wait
(Yield)
(Sleep ((delay I64)))
(Await ((tickets (List I64)))))
(define waiting (→ (Prompt Wait Unit)) (make-prompt))
(define (start-task (work (Fn → Unit))) (→ Step)
(with-prompt waiting
(lambda ()
(work)
(Finished))
(lambda (wait resume) (Stopped wait (lambda () (resume (unit)))))))
(enum Step
(Finished)
(Stopped ((wait Wait) (next (Fn → Step)))))
The scheduler keeps every task that is not running in exactly one list:
the ready tasks, the timers, sorted by deadline, or the waiters, by
ticket. A turn takes the ready list whole and runs those tasks, so tasks
that yield to each other cannot keep the host from its events, files
each step where it says, then readies the sleepers whose deadline has
passed. tests/programs/tasks.sld shows the order: yields interleave,
sleepers with one deadline wake in the order they slept.
A task holds what it uses in its closures, so a child keeps the
capabilities its parent handed it after the parent returns, and at every
resumption. A waiting task holds no stack. Its with-prompt returned when
it waited, through each frame of the work, which saved the rest of itself
in the resumption (resuming).
A task asks for tickets and dispatches children without being handed its
scheduler: a turn notes the scheduler it runs each step for, and ticket,
dispatch and a mailbox’s wait read that. It is the library’s one piece
of state outside a scheduler, set and restored around each step.
Scheduling
The policy is cooperative first-in, first-out, with no priorities:
dispatchadds a new task to the ready list. A turn begins by taking the whole list, leaving an empty one, and runs what it took in the order it became ready; a task that yields joins the new list, so it runs again only in the next turn. Tasks that yield to each other therefore cannot keep the host from its events.sleepmoves the task to the timers, kept sorted by deadline, a new timer after every timer due no later, so sleepers with one deadline wake in the order they slept. After the ready tasks have run, every timer whose deadline has passed joins the ready list, in deadline order.awaitparks the task among the waiters, holding its tickets. When a host operation settles, the host callswakewith its ticket, which crosses it off; a waiter with none left moves to the ready list. A ticket nothing waits on wakes nothing, as after a trap or a close.- Between turns,
turnanswers what the host should do next (driving the scheduler): 0 when a task is ready, the milliseconds until the earliest deadline, -2 when every live task waits on a ticket, and -1 when no task is live. - After a trap,
runningstill names the trapped task for the host’s report, and the host closes the scheduler instead of running more tasks.
Scheduler is an ordinary record whose fields hold its lists as
immutable values. Closing marks the scheduler closed and empties every
list. A task that stops after its scheduler has closed is forgotten, as is
the rest of the turn’s tasks, and a late wake finds nothing.
Locality
Dispatched work is an (Fn → Unit): what it may change is what it
closed over. It may suspend to any prompt whose with-prompt runs inside
it; a suspension to a with-prompt around the dispatch finds none
running when the task runs later, and panics there
(prompts).
A program can run tasks itself, for a simulated clock in a test or a
scheduler of its own: make-scheduler, dispatch-in and tasks-turn are
ordinary functions, and a with-prompt of its own prompt gives it waits of
its own (tests/programs/prompt-handoff.sld hands the rest of a generator
from one task to another).
Local dispatch may capture shared mutable objects, because the work stays in this single-threaded instance. Work for another instance travels as bytes through a queue, never as a closure (#553, proposed).
Only yield, sleep and await let other tasks run. Console and
the core Fs services remain synchronous; using a capability does not by
itself wait, and the scheduler does not preempt a CPU loop.
Dispatching a filesystem operation from (snail core io) defers it but
does not make the kernel operation asynchronous;
the native capability below supplies
asynchronous reads.
Native asynchronous file reads
(snail shell async-files) exports the capability Files. Its
read-file : Files String I32 -> Result<Bytes, FileError> reads
an entire file up to the supplied byte limit. It suspends the calling task
while other tasks run. A task that has other work meanwhile dispatches the
read and receives its result through a mailbox:
(let ((results (make-mailbox)))
(dispatch (lambda ()
(mailbox-post results (file-read-file files "notes.txt" 1048576))))
;; Other work can happen here; dispatch did not wait.
(consume-result (mailbox-receive results)))
Here file-read-file is imported with a file- prefix, and the dispatched
task closes over the Files it was handed (tests/async-files/main.sld).
Limits range from zero through 16 MiB. The host reads at most limit plus
one bytes, distinguishing an exact fit from TooLarge; metadata is not
proof that the subsequent read fits. Other error values are Unavailable,
InvalidInput, NotFound, PermissionDenied, and Failed. Reads of a
changing file are not snapshots. This first capability does not change
core filesystem operations.
Node does each read with its asynchronous file system
(host/native/async-files.mjs): it opens the file, reads at most the limit
plus one bytes, and closes it, while the program’s other tasks run. There
is no periodic polling and no worker pool of the language’s own; Node’s
event loop wakes the read’s ticket when it completes. A page has no
Files, since it has no file system to read.
A suspended read holds only its request’s id. The host keeps the path, the buffer and the file handle until the read completes, then closes the file before letting the operation go. A completed result whose ticket wakes no task, because the task trapped or the run closed, is discarded.
Only scalar operation IDs, tickets, path characters and bytes cross the
host boundary. The runtime makes the managed Bytes after the read
completes, so no managed object is shared with the host while it reads.
Mailboxes
A Mailbox is how tasks hand each other values. Messages are received in
the order they were posted. Its queue of messages and the wakers of the
tasks waiting for one are snail-scheme data in its fields: tasks share a
mailbox, so its contents are the one piece of state this library cannot
thread through a single task. A post queues its message and wakes every
waiting task, and each takes a message for itself when it runs; one that
finds none waits again. Each message, such as a work item, goes to exactly
one receiver, and no message is handed to a task that may never run, as
one whose scheduler closed. The price is fairness: a task that asks while
a message waits takes it, even ahead of receivers woken for it that have
not run yet (tests/programs/mailbox-order.sld). The name is mailbox-receive,
not receive, because (snail shell socket) exports UDP’s receive, and a
program importing both libraries would have conflicting imports.
(let ((mailbox (make-mailbox)))
(dispatch (lambda () (write-line out (mailbox-receive mailbox))))
(dispatch (lambda () (mailbox-post mailbox "hello"))))
A receiver that finds the queue empty takes a ticket, keeps in the
mailbox a waker, (Fn → Unit), closed over its scheduler and that
ticket, and awaits the ticket. A waker only moves its task to the ready
list, so any code may call it: another task, or code between turns. A
call after the task was woken, or once its scheduler has closed, wakes
nothing. A waiting task does not run again until it is woken, so waiting
costs nothing while nothing is posted, where a loop of yields would run
every turn. tests/programs/mailbox.sld has two tasks posting and one
receiving.
Waiting on the host
A host operation that completes later, such as a socket read, waits the same way. The host’s capability takes a ticket, starts the operation on the host, which reads its arguments and returns at once, awaits the ticket, and finishes by taking the result the host built for it:
(define through-host
(lambda (start finish) (let ((id (ticket)))
(start id)
(await (list id))
(finish id))))
(snail shell socket), (snail shell process) and the application’s
event and storage waits all wait through through-host, from whichever
task called them. Waiting needs no lock,
because a task runs until it waits: nothing else runs between taking a
ticket and awaiting it, so neither a post nor a host completion can come
first.
A task may also start several operations and await them together:
(await tickets) parks it until every one has completed, and each
completion only crosses its ticket off, so the order they settle in does
not matter. read-resources in (snail shell resource) reads a
program’s linked files this way, so a page fetches them together rather
than one after another.
The host boundary
The host sees the scheduler only through five exports of
(snail shell task):
| Export | Meaning |
|---|---|
tasks:turn now | Run a turn at the host’s clock, in milliseconds. Answers 0 when a task is ready, -1 when none is live, -2 when every live task waits on a ticket, and otherwise the milliseconds until the next deadline. |
tasks:wake ticket | Ready the task waiting on a ticket, answering whether one was. |
tasks:close | Forget every task, as ending a program does. |
tasks:running | The id of the running task; after a trap, the task that trapped. |
tasks:live | How many tasks have not finished. |
A host’s loop calls turn, rests until the answer says, or until a
completion wakes a ticket, and calls it again until no task is live
(host/browser/tasks.mjs’s drive). A trap unwinds out of turn.
The host reports the trap under tasks:running, closes the scheduler and
ends the run. An
answer of -2 while no host operation is outstanding is a deadlock: no
completion will wake a ticket, so the run fails.
A host operation’s start and finish are synchronous imports.
host/browser/tasks.mjs keeps each outcome under its ticket until the
finish takes it. The finish answers with numbers, from which the library
builds its result in the waiting task’s own call; a host never builds a
managed value (the native boundary). An outcome
whose ticket wakes nothing, because its task trapped or its run closed, or
that is still held when the run closes, is disposed of instead: an
accepted connection is closed.
Tickets count from 1 in each scheduler. Every wake names its scheduler as
well as its ticket: a host’s through the scheduler it created, and a
waker’s through the scheduler it closes over. A restarted run has a new
scheduler, so a waker that a Mailbox in the application’s state kept
from the old one finds that scheduler closed and wakes nothing in the
new one.
A task runs on the host’s ordinary Wasm stack, and keeps none while it waits. Deep non-tail recursion can overflow it; use tail calls for loops requiring constant stack space.
Driving the scheduler
The scheduler is written in snail-scheme (task operations); a
host only drives it and completes the operations its tasks wait on.
host/browser/tasks.mjs is the driver Node and the browser share. It runs
on one execution agent and creates no workers.
Turns
drive calls tasks:turn with the host’s clock and rests as the answer
says, until no task is live:
| Answer | The host rests |
|---|---|
| 0, a task is ready | until the next turn of the event loop, so the host’s own events run between turns: setImmediate in Node, a message in a browser, whose zero timeouts are clamped |
| a positive number of milliseconds | until that deadline, or until a completion wakes a ticket |
| -2, every task waits on a ticket | until a completion wakes one; with no operation outstanding, nothing will, and the run fails |
| -1, no task is live | not at all: drive returns |
A trap unwinds out of turn. The driver reports the trap with the id
tasks:running gives, closes the run and returns; Wasm does not unwind
the trapping frame, and closing forgets the rest of the scheduler’s
tasks. drive takes a stopped test,
asked after each turn: the application runtime stops at the loop’s answer
and only then decides whether its children may go on. interrupt ends a
rest early, so that stopped is asked again. A CPU loop that does not
wait still monopolizes the execution agent; the scheduler does not
preempt it.
An engine (runtimes) runs its own work, linking
and reading linked files, as tasks on the program’s scheduler, so the two
share one ticket space and one turn. The driver turns that scheduler
through the engine’s engine:turn, engine:wake, engine:close-tasks,
engine:running and engine:live.
Host operations
An operation that completes later is started through a synchronous import
with the ticket its task took, and finished through another
(waiting on the host). The driver’s
start(ticket, operation, deliver, dispose) runs the operation with the
run’s AbortSignal and counts it outstanding until it settles. Settling
wakes the ticket and keeps the outcome under it until the task’s finish
calls finish(ticket), which runs deliver on a success, making the
answer the library reads, or throws a failure into the finish, where it
traps the task. coded turns a native failure
with an error code, such as ECONNRESET, into the operation’s Err
value, and leaves an abort or an uncoded failure a failure.
A success whose ticket wakes nothing, because its task trapped or its run
closed, is disposed of exactly once, through the operation’s synchronous
dispose: an accepted connection is closed. Delivered results and
failures are not disposed of.
Closing a run
close aborts the run’s signal, forgets every task through tasks:close,
and disposes of each outcome still held. An operation that cannot abort
may finish normally afterwards; its ticket then wakes nothing, and its
outcome is disposed of. Its external effects are not rolled back.
An adapter receives the AbortSignal and returns one Promise covering
both its operation and its owned cleanup. It must handle an already
aborted signal, remove listeners on normal completion, and settle only
after owned cleanup finishes. Timers and event waits can disarm promptly.
A disposer must not suspend or reenter snail-scheme; if it starts OS
resource closure, the native owner awaits that remaining cleanup during
shutdown. An adapter that never settles keeps its run from ending.
A task failure ends the run, including its siblings. A Node host holds a
process-lifetime token until drive returns, since a task waiting on a
timer or a ticket is live work that no OS handle keeps Node alive for.
Native networking and processes
(snail shell socket) provides concrete, replaceable Tcp and Udp capabilities. The
Node target’s are bound to host/native/tcp.mjs and host/native/udp.mjs through
host/native/socket-imports.mjs: an operation that waits starts there and waits for its
ticket (waiting on the host), as a task
does. Child processes follow the
same model, through host/native/process.mjs and host/native/process-imports.mjs. Static and separately linked programs use the
same binding. The HTTP library implements one complete
request/response exchange over TCP. Browser sockets are not implemented.
The networking issue tracks the
remaining work.
snail-scheme API
Import (snail shell socket) and hand a Tcp or Udp to the code using it: every operation is a field of one, called as ((● tcp listen) endpoint).
Every operation returns Result with a SocketError whose code is a string
such as "EBADF", "EINVAL" or a native network error code. Nothing
cancels a waiting task: it resumes when its operation settles. When the run
ends, the host aborts the operations still outstanding, and the tasks
waiting on them never resume.
An Endpoint is an IPv4 address and a port, and only (endpoint address port) makes one, from dotted text: four decimal octets from 0 to 255
without leading zeros, and a port from 0 to 65,535, or EINVAL. The type
is exported without its constructor, so holding an Endpoint is evidence
that both are usable, and no host checks them again. Endpoint-address
gives the dotted text and Endpoint-port the port. Hostnames are outside
this API. TCP operations are:
| Operation | Success value |
|---|---|
listen endpoint | Listener; (● listener port) is the actual bound port. |
connect endpoint | Connection. |
accept listener | Connection. |
read connection maximum | Some Bytes containing an available nonempty prefix, or None at EOF. |
write connection bytes | I32 count accepted locally, possibly smaller than the input. |
finish-connection connection grace | Unit after ending output, discarding input and awaiting native closure; grace is an I32 millisecond deadline. |
close-listener listener | Unit. |
close-connection connection | Unit. |
TCP read limits are 1–65,536 bytes; one write accepts at most 65,536. Reads may split or combine peer writes. Callers must loop to transfer an exact length. Listen port 0 selects a free port. TLS and stream framing are outside this API.
UDP operations are:
| Operation | Success value |
|---|---|
bind endpoint | UdpSocket; (● socket port) is the actual bound port. |
send socket peer bytes | I32 count of the entire datagram accepted locally, including zero; never a partial prefix. |
receive socket maximum | Datagram with an Endpoint peer and immutable bytes. |
close-udp socket | Unit. |
UDP payloads and receive bounds are 0–65,507 bytes. Empty packets are messages,
not EOF. An oversized receive consumes and discards that packet with EMSGSIZE;
the next receive starts at the next packet. (● datagram peer) supplies the sender’s
address and port, and (● datagram bytes) supplies the whole payload. Bind port 0
selects a free port; a send to port 0 fails with EINVAL before it reaches
the host. UDP does not guarantee
delivery, order or uniqueness.
Listener, Connection and UdpSocket carry an opaque Any token belonging to the
Tcp or Udp that made them. They are reusable values that stay within their instance. Closing
revokes all aliases; closing the same native token again succeeds. Native
token types stay private to the library. Another capability’s token reaching
the native binding reports EBADF instead of being cast to an integer handle.
TCP and UDP owners may issue the same numeric handle, but their private token
types differ. Tokens must remain with the runtime that issued them.
A replacement Tcp is a record of eight operations; a Udp, of four.
They may create endpoint values with their own tokens. For example, a test
can put a record with a mutable Bytes field in a connection token, or a
mutable Datagram field in a UDP token, accessed through operation arguments
(tests/programs/tcp-handler.sld, udp-handler.sld).
Wasm boundary
(snail runtime native socket) declares the interface, and only numbers
cross it. A listener, connection or UDP socket crosses as its handle, and
an endpoint as two I32s: its port, and its address, whose four octets are
the I32’s unsigned bits, most significant first. The host enters no Wasm
and builds no managed value. (snail shell socket) builds every Result
itself, in the waiting task’s own call, from what the host answers.
Native I/O runs while the task waits on its ticket. The task’s finish
then answers with a number: -1 for a failure, and otherwise the
operation’s own number, such as a handle or a count. The host holds what
else the answer carries until it answers again
(host/native/answers.mjs):
- a number, such as a listener’s port;
- byte strings, such as the bytes read or a failure’s error code.
The shell reads them at once, before its next host call, a call per byte.
The runtime library’s header has the table of what each operation answers.
A datagram’s sender is held as Node’s dotted text, which endpoint parses.
Outgoing bytes are copied from staging before any other Wasm call or await.
A pending acquisition carries its native handle and bound-port metadata, where
applicable. The scheduler disposes a successful acquisition that no task can
receive, because the run has closed or the waiting task trapped. Once
finish answers with a handle, the handle is the shell’s. Successful delivery
hands responsibility to user code: close explicitly, or leave cleanup to
runtime shutdown. Nothing closes a socket when its last reference goes. The
runner closes the scheduler, then all socket resources, then its scalar
resources when execution ends or initialization fails.
TCP operations
Each createTcp() owns one set of native resources and its own positive I32
handle namespace. Handles never repeat within that owner. They are not global
identities, transferable capabilities or references to Wasm-managed objects.
Every operation must use the owner that issued its handle.
| Operation | Result |
|---|---|
listen(signal, address, port, backlog) | Listener handle after binding; port 0 chooses a free port. |
port(listener) | The listener’s bound port. |
connect(signal, address, port) | Connected socket handle. |
accept(signal, listener) | One connection, independent of its listener after delivery from this operation. |
read(signal, connection, maximum) | A nonempty available byte prefix of at most maximum bytes, or null at EOF. |
write(signal, connection, bytes) | A count of bytes accepted locally, at most 65,536; empty input returns 0. |
finish(signal, connection, grace) | End output, discard input and await physical closure; grace bounds graceful progress in milliseconds. |
close(handle) | Immediate revocation of aliases and initiation of native cleanup; repeated close does nothing. |
shutdown() | Reject new work, close all resources, and await native cleanup. |
The arguments are the library’s, which decided them, and the host checks
none of them again: the address is the dotted text of an Endpoint’s and
the port its port, a read’s maximum is 1–65,536, a grace is not negative,
and the backlog is how many unclaimed connections the listener keeps, 64.
There is one pending accept
per listener and at most one pending read and one write per connection; a read
and write can overlap. Duplicate operations fail with EBUSY and revoked
handles with EBADF. Native network errors retain
their codes. Receiving EOF leaves the connection writable; available bytes are
read before EOF. No operation promises peer receipt or message framing.
Write borrows its bytes unchanged until settlement. The Wasm binding copies staging memory before awaiting; native callers must not mutate or detach the supplied storage. An aborted write may already have transmitted bytes, so retrying the whole buffer is not automatically safe.
Finishing a connection
snail-scheme’s finish-connection binds the native finish operation. It takes an idle
connection and a grace period in milliseconds, which the library refuses
with EINVAL when it is negative. Pending read or write rejects with EBUSY
without changing ownership.
Once accepted, finish ends output and consumes remaining input without keeping
it. Node’s writableEnded state prevents aliases from starting further I/O;
close can still abort the connection. EOF plus completed output lets Node close
the socket naturally. This staged teardown avoids discarding a final HTTP
response when unread input remains; see RFC 9112 §9.6.
Success reports local completion, not proof that the peer application processed
the response.
The deadline is elapsed time, not an idle timeout renewed by incoming data.
Expiry forces closure and reports ETIMEDOUT; zero means immediate expiry.
An abort preserves its exact reason. Transport failure, explicit close,
timeout or abort records the first cause; clean native closure records
success. A later abort cannot rewrite that native outcome, although the
scheduler still disposes of a result that no task receives. Every accepted
finish waits for physical closure before settling. The grace bounds graceful
progress; forced cleanup still needs event-loop scheduling.
Native resources and aborts
The signal each native operation takes is the run’s: the scheduler aborts it when the run closes, and nothing else does.
Node accepts eagerly. A listener retains at most its backlog of unclaimed connections in a paused state, using native stream buffers. Overflow connections close immediately. Revoked queued connections are skipped by accept. Aborting accept leaves its listener and unclaimed connections usable; closing a listener releases its queue but leaves already handed-out connections independent.
Native ownership lasts from creation through the close callback. A public handle
exists only after successful listen/connect/accept. Immediate close removes it;
graceful finish disables ordinary I/O but retains the handle for an explicit
abort until physical closure. Failed creation and rejected incoming sockets therefore participate in
shutdown without receiving a handle. Exhausting the handle namespace reports
EMFILE; an accept that cannot publish leaves its connection listener-owned.
Aborting listen/connect closes the pending resource and waits for cleanup. Aborting an installed read or write closes that connection and wakes its other pending operation. Completed operations detach the abort. A success arriving just before an abort is checked again before it can publish a handle or write count. Abort failures preserve the exact abort reason.
Ordinary close does not wait: Node can defer a listener’s close callback until its handed-out connections finish. Shutdown closes those connections too and waits for all ownership, including late arrivals during listener closure. The task scheduler separately holds successful native results until delivery; the binding supplies its disposer for when no task can receive a newly created handle. No native cleanup record retains a managed wrapper.
Native UDP owner
host/native/udp.mjs owns IPv4 datagram sockets behind the host’s Udp. It is tested
against real loopback sockets, including forced asynchronous native sends.
It uses Node’s synchronous numeric bind,
available from 26.4. Binding is a nonblocking local operation, so it needs no
opening state, DNS lookup or bind cancellation registration.
| Operation | Result |
|---|---|
bind(signal, address, port, queued) | Positive I32 handle; port 0 selects an available port. |
port(handle) | The actual bound port. |
receive(signal, handle, maximum) | One whole datagram: {bytes, address, port}, including the sender’s endpoint. |
send(signal, handle, address, port, bytes) | Entire payload length after local completion; no peer delivery guarantee. |
close(handle) | Immediate alias revocation and initiation of cleanup; repeated close does nothing. |
shutdown() | Stop new binds, close remaining sockets and await native cleanup. |
Handles never repeat within their owner, including after failed bind attempts.
Addresses and ports come from Endpoints, as for TCP. The library limits a
payload and a receive’s maximum to 0–65,507 bytes, refusing an oversized
send with EMSGSIZE before it reaches the host. Zero-length datagrams are
messages, not EOF. If the next datagram is larger than a receive’s maximum,
it is consumed and discarded with EMSGSIZE; there is no partial result or
remainder to read. UDP makes no delivery, order or uniqueness guarantee.
queued is how many complete datagrams the
socket queues, 32 from the library; excess arrivals are dropped,
preserving the queued messages. One receive and one send may be pending at a
time and may overlap; duplicates fail with EBUSY. Receive cancellation removes
its registration and preserves the socket and remaining queue. A datagram
already consumed before cancellation wins is not requeued.
Send borrows immutable bytes until its callback. The Wasm binding snapshots staging before calling it. Cancelling send waits for native completion and then rejects with the exact cancellation reason. It cannot retract the datagram. A send callback failure affects that operation; a socket-level error closes the socket. Closing wakes pending receives and discards queued datagrams.
Node still resolves numeric send addresses asynchronously. Closing during that lookup can suppress the send callback, and a native close event can otherwise precede pending send completion. The owner therefore revokes aliases immediately but defers native close until the single send settles. The closed record remains owned until its close event. Shutdown cannot finish while that send or cleanup is outstanding. Failed bind closes and awaits cleanup before rejecting.
As for TCP, the scheduler holds successful acquisitions until delivery; the shared binding supplies the existing native disposer. The owner adds no second delivery protocol and retains no managed wrapper.
Child processes
(snail shell process) provides Processes: child processes with
their standard streams piped to the program. Import it and hand a
Processes to the code using it. Every operation returns Result with a
ProcessError whose code is a string such as "EBADF" or a native error
code. As for sockets, nothing cancels a waiting task.
| Operation | Success value |
|---|---|
spawn (Command program arguments directory) | Process; (● process id) is the operating system’s process id. |
read-output process stream maximum | Some Bytes, an available nonempty prefix of (Stdout) or (Stderr), or None at its end. |
write-input process bytes | I32 count of bytes the pipe took, at most 65,536. |
close-input process | Unit; the child reads EOF once written bytes drain. |
send-signal process signal | Unit after sending (Terminate), (Kill) or (Interrupt). |
wait-exit process | (Exited code), or (Signaled name) with the signal’s name, such as "SIGTERM". |
close-process process | Unit. |
run (Command …) input | (Captured exit stdout stderr), once the command has run to its end with input, a Bytes, as its standard input. |
exec (Command …) | Nothing: the command replaces the program. It returns a ProcessError, not a Result, and only when the command could not start. |
A Command’s program is found on PATH when it has no slash, as execvp
finds it: in the first entry holding a regular file the process may
execute, where an empty entry is the command’s directory and a relative
one is taken from it. (snail shell process) searches, for spawn, run
and exec alike, and the program still runs as the name it was given.
Its arguments follow that name, and it runs in directory. The
program is a field of its own, so no command is empty. A missing executable
or directory is ENOENT, an argument the platform cannot pass (one with a
NUL) is EINVAL, and a signal to a child that has exited is ESRCH.
Writing after close-input is EPIPE.
Output stays in the pipe until it is read, even after the child exits, so
waiting first and reading after loses nothing. The pipes keep backpressure,
though: a child that writes more than a pipe and its stream buffer hold,
about 64 KiB each, blocks until it is read, so a program expecting more
output than that reads while it waits. Read limits are 1–65,536
bytes, which the library checks. There is one pending read per stream and one pending write; a read
of each stream and a write can overlap, and any number of wait-exits may
be pending. A write waits until the pipe takes its bytes, so a child that
does not read holds it. Closing a process that is still running kills it
with SIGKILL and revokes the handle, as closing a socket does; closing it
again succeeds. A Process carries an Any token belonging to the
Processes that spawned it, and another’s token reaching the native binding is EBADF.
tests/programs/process.sld runs /bin/sh through each operation.
run and exec are for a tool that runs once, such as a command line
program, not for a service. run blocks the program: no task runs until the
child exits. Its outputs are kept whole, with no pipe to fill, so a child may
write any amount before it exits. exec replaces the program as execve
does: the command takes over the process, its id and its standard streams,
its exit status becomes the process’s, and nothing of the program runs
after, not even its tasks; children it spawned keep running. Both find a
program and report failures as spawn does
(tests/programs/process-run.sld, tests/programs/process-exec.sld).
Termination
Signals, also in (snail shell process), has one operation,
((● signals termination)), which waits for SIGINT or SIGTERM and returns
(Interrupt) or (Terminate). A program opts in by waiting: a signal that
arrives while tasks wait in termination is the result of every such wait,
and one that arrives while none waits ends the program, as it always has.
A service runs a task that waits for termination and then shuts down in
order, here by terminating a child and waiting for it:
(dispatch
(lambda ()
((● signals termination))
((● processes send-signal) child (Terminate))
((● processes wait-exit) child)))
A wait ends with its signal, so a second Ctrl-C during that shutdown ends
the program at once, unless a task waits again. A second Ctrl-C that comes
so quickly it is still on its way while the first ends the wait is kept for
the program’s next wait instead, at most one, so a double tap reaches a
program that waits again, and does not end one that does not. The program
runs on Node’s main thread, which receives the signals. The runner handles
them only while a task waits, from the moment the wait starts, or has yet
to finish a wait a signal ended; a signal then is kept when it finds no
waiter. At any other time Node’s default ends the process by the signal at
once, even while a turn computes, when no handler could run. A task that
waits for termination while another computes without yielding hears of a
signal when that turn ends. tests/termination/check.mjs sends SIGTERM and
SIGINT to a waiting program, which observes each and exits cleanly, SIGTERM
to one that does not wait and SIGINT to one that computes without end,
which they end, and delivers a double tap by calling the handlers as two
signals would.
The process boundary
createProcesses() in host/native/process.mjs owns one set of children
behind positive I32 handles, which never repeat within that owner. A child is
owned from spawn until it has exited and its pipes have closed; its public
handle exists from a successful spawn until close. (snail runtime native process)
declares the interface. A command is sent a character at a time, as the
strings of a host command are: its directory, the program’s path, the name
it runs as, then its arguments. While it searches PATH, the library asks
executable about each candidate, a directory and a path sent the same
way, and the host answers with access(2) and a regular-file test, which
WASI lacks. A process crosses as its handle and a stream as its descriptor,
and the operations answer as the socket operations do.
| Operation | Result |
|---|---|
spawn(signal, directory, program, name, arguments) | {handle, pid} once Node reports the child running. |
read(signal, handle, descriptor, maximum) | A nonempty prefix of stream 1 or 2, or null at its end. |
write(signal, handle, bytes) | A count after the pipe accepts it. |
closeInput(handle) | Ends input. |
kill(handle, number) | Sends signal 15, 9 or 2, the numbers the library gives. |
wait(signal, handle) | {code} or {signal} once the child exits. |
close(handle) | Revokes the handle, kills a running child and destroys its pipes. |
shutdown() | Rejects new spawns, closes every child and waits until each has exited. |
runChild(directory, program, name, arguments, input) in the same file is
run’s spawnSync, which blocks the program until the child exits; a
signal sent meanwhile reaches the program once it returns.
replaceProcess(directory, program, name, arguments) is exec: it changes
to the command’s directory and calls process.execve with the path the
library found. Only a failure answers, with its code, after the directory
is changed back.
createTermination() in the same file holds the termination waiters and
the process’s handlers for SIGINT and SIGTERM while they are needed:
wait(signal) resolves with the signal’s number, 2 or 15; settled() says
a task finished the wait a signal ended, or that its result was disposed of;
and a signal resolves
every waiter or keeps itself while a delivery is unsettled.
Node discards a child’s output when it exits unless a 'readable' listener
is waiting for it, so each output stream keeps one, and its bytes wait in
the stream until read. A successful spawn waiting for delivery belongs to
the scheduler; if no task can receive it, the binding’s disposer closes the
handle, which kills the child. Aborting a read consumes nothing and leaves
the process usable; aborting a pending write destroys the child’s input,
since the bytes may be partly written. The runner shuts the owner down
with the socket owners when a program ends, so no child outlives a program
that ends normally. Only the child is killed: a process it started, as a
shell does for a command it does not exec, is the child’s to end. No native record retains a managed wrapper. The browser has
no processes and no snail.runtime.native.process imports, so a program performing
process links only on the native runner.
Tasks, values and runtimes
This is the language contract for tasks and capabilities. The runtime overview distinguishes its implemented subset from future requirements. There is one shipping target: WebAssembly GC, on one execution agent. A second backend is future research.
Computations
A task is a single execution of a zero-argument closure. A runtime holds tasks and the platform operations they await. Dispatch turns a closure into a task; it does not create an actor instance, mailbox or request/reply protocol. A task finishes by returning or failing. There is no terminate operation and no supervisor hierarchy.
Tasks may overlap in lifetime. The language permits a runtime to execute eligible tasks on different threads. The current implementation interleaves them cooperatively: a task runs until it returns, fails, explicitly yields, or awaits a runtime operation. A CPU loop that never yields monopolizes the execution agent. Waiting is not CPU parallelism.
A runtime is exhausted only when all its tasks have settled. A waiting task and an outstanding host operation remain live work. Nothing cancels a task; tasks that should stop early arrange it between themselves. An empty ready queue is not exhaustion. Dispatch counts the new task live before returning to the caller, so a parent can finish immediately after dispatch without letting the runtime exit early.
Values in tasks
Every value may be shared (values). Capturing a value in a closure, or dispatching that closure as a task, keeps the value reachable from there, and the engine’s collector reclaims it once nothing reaches it. A resource outside the managed heap has an explicit close operation; nothing closes it when its last reference goes. A suspended computation whose resumption is never called runs nothing more.
Each instance of a program runs on one thread, and no value it holds is reachable from another thread. So the language has no thread-safety markers, and a capability or a task may capture mutable state. Instances will talk to each other only through queues, which copy bytes, and through shared memory holding plain data; that design is proposed in #553. Foreign code and host capabilities are explicit trusted boundaries.
Capabilities and suspension
What code may do to a platform is in the capabilities it holds: values the
runtime’s target hands the program’s main, which passes them on
(capabilities). An application
makes its own for abstractions and tests. Holding no capability, code can
reach no platform resource.
A capability is an ordinary value, usually a record of closures, each of which may be called repeatedly, may capture mutable state, and may allocate local mutable storage. A task keeps the capabilities it closed over across its waits, and a newly dispatched task has those its closure captured.
Waits are suspensions to the task library’s prompt: the scheduler retains
a one-shot resumption and later makes it ready, when a timer passes or the
host wakes its ticket. Like every suspension they compile to ordinary calls
and saved frames, with a one-shot, first-class resume (see
suspension), and never reach the host,
which only drives the scheduler (task operations). A second
resume of one continuation panics.
Events and application state
The runtime turns platform callbacks into completed waits. It may buffer input while application code waits, and coalesce redundant motion, resize and frame notifications. A frame wait can return the input received since the previous frame. Each input is consumed once by its owning loop. The runtime does not infer a shared current application state.
An application owns its state as loop arguments. For example, in schematic syntax:
animate(window, world):
frame = next_frame(window)
next = update(world, frame.inputs, frame.dt)
render(window, next)
animate(window, next)
A page’s save keeps its state across a page reload. It is an application protocol on top of tasks, not the definition of a task.
The typed state proposal would replace application saves with durable records and disposable views; that API remains under review.
Instances, queues and shared memory
Proposed, not implemented. The design is #553.
GC is the only heap, and each instance of a program is strictly single-threaded: one Wasm instance, one GC heap, one thread. Parallel work runs as several instances, which share nothing that the GC manages. They talk the way processes do, through explicit queues, which makes the cost of crossing between cores visible.
That follows from WebAssembly itself. Only linear memory can be shared between threads; GC objects, tables and globals belong to one instance, and a WasmGC object cannot be posted to another worker. So values cross as bytes.
Queues
(snail shell queue) copies, and works on every host, including a browser
page without cross-origin isolation.
- A queue has many senders and one receiver, like Rust’s
mpsc. A second sender comes from an explicitclone-sender, each sender is closed explicitly, and the receiver can tell when every sender has closed. - Queues are bounded. A full queue makes
sendwait;try-sendreturnsFull. - Endpoints can travel inside messages, as file descriptors do.
- Typed messages through
(snail shell wire)are a convenience on top. The fast path is bytes.
Shared memory
(snail shell shared) is unsafe and zero-copy, and in a browser it needs
cross-origin isolation. It follows the owner’s mpmc_ndarray_queue: a
fixed pool of equal slots in shared memory, with ordinary queues carrying
only slot indices. The queues do all the waking. Shared memory holds data
and slot headers only, never a lock or a queue, so an instance that dies
leaks its slots but cannot wedge the others.
A slot’s header packs a state and a generation. Taking, publishing, accepting and releasing a slot each move it one step, by compare-and-swap. A copied or stale slot id therefore cannot be accepted twice, nor return an index to the free list twice.
The runtime keeps its private memory; only programs that use the shared tier import a second, shared memory. Programs that never share need no isolation.
Instances
spawn-instance starts another instance of the same program, from one of
its entry points, on a new worker. The host that started the program
supervises every instance. A child is handed its target’s capabilities and
none of its parent’s, because capabilities are values of one instance. When the program
stops, every child is stopped and the shared memory is discarded.
Continuations and parallel execution
Research recorded on 2026-10-24. This page describes future options, not shipping features. We ship one WasmGC backend.
Decisions have been made since. One-shot suspension is implemented by
ordinary calls and saved frames (suspension),
and the runtime’s tasks are suspensions, scheduled in snail-scheme, so
no host suspends a Wasm stack (task operations). Effect
declarations and handlers have gone since this page was written
(#877); what it says of
ctl operations and handlers reads as suspend and with-prompt.
And each instance of a program is single-threaded, talking to others only
through queues and shared memory (instances, proposed). So
the shared-heap thread pool below is not the plan. The native alternatives
remain research.
What the Wasm target needs
Existing Wasm threads share linear memory. That does not make ordinary WasmGC objects, closure displays or references transferable between workers. The Shared-Everything Threads proposal addresses that larger sharing model. A prototype engine flag is not a deployment baseline; we require default support in the runtimes we ship on.
Typed stack switching provides typed continuation creation, suspension and resumption. JSPI gives host-driven asynchronous suspension, but not a language-level first-class continuation API or arbitrary migration of suspended stacks, and it has no counterpart outside the browser engines, so the tasks no longer use it.
These extensions solve different problems. Stack switching does not make the heap shareable. Sharing the heap does not establish handler lifetimes. An implementation of both still needs to preserve the language’s invariants.
Option A: restore a Wasm-to-LLVM backend
The archive archive/llvm-backend-20261012, at
5c277ab6,
used BDWGC and translated Binaryen’s folded text into LLVM. The later
backend removed by PR #341
was substantially different. Its last revision,
fc8bf59a,
read Wasm binaries, resolved their types, emitted LLVM, and used a custom
Immix collector. Research should start from that later revision, rather
than assuming the named archive contains the final implementation.
The later backend’s exact writable roots are a useful foundation. Reference
locals lived in root slots; temporary references were published before
collecting calls and reloaded after objects could move. The collector was
synchronous and single-threaded. RUNTIME and native_roots were process
globals explicitly assumed never to be shared between threads. Native
worker isolation was not a shared-heap thread pool. See its
roots contract
and runtime.
A stackful implementation would allocate stacks, switch between them at delimited suspension points, and represent a continuation as a suspended stack chain. The Wasm type checker supplies the continuation’s type; LLVM need not gain a first-class continuation type. One-shot resumptions avoid copying stacks to support repeated resumes. A historical WasmFX prototype, section 5, implemented this using Wasmtime’s fibers and native register/stack switching. That establishes feasibility, not readiness of our old backend.
LLVM’s coroutine intrinsics instead
support splitting a function into entry, resume and destruction functions
with saved state in a frame. They do not automatically capture arbitrary
nested ordinary calls. We would either transform every potentially
suspending path or supply a stack-switching runtime. The
coro.id.retcon.once convention describes a coroutine yielding once; it
does not by itself implement our rule that a captured resumption runs at
most once.
The substantial work is making the runtime correct:
- Give each suspended computation a root chain. Publish live references before suspension and reload them after resumption, since other tasks may have caused a moving collection in between.
- Enumerate roots from every running and suspended computation. A first multithreaded collector can stop all mutators; it need not collect concurrently. It still needs safepoints and safe allocation coordination.
- Implement stack limits and foreign-call boundaries. Cross-thread resume must account for thread-local state, not just copy a stack pointer.
- Implement the shared Wasm memory/object operations and their atomic semantics. Native pointer accessibility alone does not provide them.
A useful first experiment would suspend with live managed references, force a moving collection in another computation, resume, and check the references. Only then should two native mutators run concurrently.
Option B: a C backend informed by Koka
Koka’s usual C backend lowers effects through a selective monadic transformation and generalized evidence passing. At an operation that yields, generated code returns through ordinary C frames. Each relevant caller adds a closure for its remaining computation. At the matching handler, the collected closures form the resumption. Resuming invokes those closures with the appropriate handler bindings. It does not preserve the physical C frames. The compiler transformation and handler runtime show both halves.
The generalized evidence passing paper, sections 2.5–2.8
explains the optimizations: effect types help select handler evidence;
tail-resumptive operations can execute in place; generated code builds
continuation closures on the yielding path. A yielding flag distinguishes
ordinary return values from suspension. Capture does work along the
continuation’s path, whereas native stack switching can retain the stack
without rebuilding that path as closures. These are different cost models;
neither establishes a performance result for snail-scheme without measurement.
Koka supports multiple resumptions. snail-scheme restricts them to one: a
second call of resume panics. A C
backend would still need closure conversion, effect lowering, a
managed-memory strategy, a foreign ABI and a portable runtime.
Adopting this technique does not mean embedding Koka or obtaining those
pieces automatically. Koka’s reference-counting implementation is also not
a requirement of the continuation technique.
Koka explicitly finalizes abandoned resumptions so finally clauses run,
and its raw ctl exposes a resume context that must eventually be resumed
or finalized; the
tour
describes that contract. snail-scheme has no finally: a resumption that is
never called is reclaimed by the collector, and nothing in its frames runs. The related
libmprompt project takes a separate
native stack-switching approach; it is not the mechanism described above.
The compiler transformation could also target today’s WasmGC. Therefore
waiting for typed stack switching is a choice to avoid another substantial
lowering strategy, not proof that ctl is impossible on today’s Wasm.
Handlers and scheduling
A with-prompt’s handler may be invoked repeatedly. Each invocation
receives its own resumption. A continuation retains the frames and the
with-prompts inside it. The implemented frame translation establishes
these lifetimes; alternative backends would need to preserve that same
contract.
A shared-heap backend would want a conventional work-stealing pool. That is not the plan: each instance schedules its own tasks, and parallel work runs as more instances (instances). For now, deploy independent Wasm instances and balance requests externally. Neither native backend is on the implementation path of the task rewrite.
Deliberate language limits
snail-scheme is a statically-typed Scheme successor, not an R7RS
implementation. call/cc, dynamic-wind, reusable continuations and a separate
Scheme compatibility runtime are outside the language. Its implemented
control model is one-shot delimited suspension: a second resume panics, and a
resumption that is never called runs nothing. Future backends must preserve
that contract rather than add a second continuation model.
Foreign callbacks
A pending operation holds the ticket its task waits on. Its completion settles it once and wakes the ticket; a result whose ticket wakes no task is disposed of by the host. An empty ready queue is not runtime exhaustion while waits remain live. Nothing walks language frames: neither GC reachability nor a native Rust/JavaScript exception unwinds them.
Foreign callbacks return normally. They copy transient inputs or hand over
an explicitly owned buffer, settle a registration and enqueue snail-scheme work.
They do not capture a foreign stack as part of a continuation. Browser
operations that need an immediate response, such as event suppression,
keep that decision in the synchronous adapter.
Graphics
Applications draw through a Gpu, a capability that is a thin wrapper around WebGPU,
and the (snail shell graphics ...) libraries of composable pipelines and
packers built on it, all written in snail-scheme. Hearsay draws 2D quads
from an atlas; Siegework draws a 3D Frame of mesh batches, which
(snail shell app)’s draw-frame rasterizes into a G-buffer and lights;
Splats draws gaussians, sorted on the GPU by a radix sort built on a scan.
- The WebGPU design explains the capability and how the libraries are built on it; the library reference lists them.
- Tensors and training describes the tensor library, its gradients, Adam, and the compiler that runs them on the device.
- The path tracing primer explains the physics of the light a path tracer computes.
- The path tracer traces glTF scenes with that physics: a
BVH, a wavefront of kernels, environment light and SVGF, flown through
by
src/apps/viewer. - Open Splats in a browser with WebGPU: rings of
gaussians, or a trained scene’s
.plydropped on the page with its COLMAPimages.bin.
WebGPU design
Applications draw through two layers written in snail-scheme: a Gpu
capability that is a thin wrapper around WebGPU, and (snail shell graphics ...) libraries of pipelines and packers on top of it. They replaced a
fixed JavaScript renderer, host/browser/renderer.mjs, and its picture
store. This chapter explains how the layers work and why they are shaped
as they are; the library reference lists each
library and its entry points. Open work on them is tracked in
the graphics issue.
Device requests, decoding, pipeline creation and readbacks need only ordinary
functions and the runtime’s waits. Those waits are suspensions,
scheduled in snail-scheme (task operations), so nothing
here depends on an engine extension.
WebGPU through a capability
The Gpu of (snail shell gpu) mirrors WebGPU’s own operations and
descriptors, each a field of the Gpu:
(let* ((encoder ((● gpu create-command-encoder)))
(frame ((● gpu current-texture)))
(pass ((● gpu begin-render-pass)
encoder
(new RenderPassDescriptor
(colors (list (new ColorAttachment
(view (view-of gpu (● frame texture) 1))
(load (Clear (new Color (red 0.0) (green 0.0) (blue 0.0) (alpha 1.0))))
(store #t))))
(depth (None))))))
((● gpu set-pipeline) pass pipeline)
((● gpu set-bind-group) pass 0 group)
((● gpu draw) pass 3 1 0 0)
((● gpu end-pass) pass)
((● gpu submit) (list ((● gpu finish) encoder))))
Its operations make buffers, textures, views, samplers, shader modules,
render and compute pipelines, bind groups and query sets, write buffers and
textures, encode copies, render passes and compute passes, and submit
them. A pass begun timed (begin-timed-render-pass,
begin-timed-compute-pass) writes the device’s time into two queries, as
it begins and as it ends; submit-timed resolves the queries after the
encoder’s commands, submits it and reads the times, and elapsed-seconds
answers the time between two. request-device, read-buffer and
decode-image wait for the host by ticket, as does work-done, which
waits until the device has done what was submitted, so a loop whose
frames cost the device more than a display frame does not queue them
without bound. The calls are procedural;
the capability keeps them reasonable. A Gpu parameter says exactly which
functions touch the device, and a Gpu is a record of the operations, so
another one changes what the calls do without changing their callers.
host-gpu, in (snail shell gpu) itself, runs them on the host’s device
through host/browser/gpu.mjs: the browser target provides it to a page’s
main, and a program on Node makes it itself, where it uses Dawn
(WebGPU on Node).
with-recorded-gpu ((snail shell gpu record)) records them instead, so a
library is tested without a device (tests/programs/gpu-record.sld).
tests/browser/gpu.mjs draws, reads back, decodes and dispatches a compute
shader on Chromium’s software WebGPU, and tests/gpu.mjs runs the checks
that need no screen on Node’s device.
It is WebGPU itself, without bookkeeping:
- Objects are kept by the program. Each
create-...call makes an object and answers a handle, the id the host gave it. A program makes its pipelines, bind groups, buffers and textures once, keeps them in its state across frames, and makes them again only when what they depend on changes, as a WebGPU program in JavaScript keeps its objects.destroylets an object go at the nextsubmit, after the commands that use it: a buffer’s or texture’s memory is freed, as WebGPU’sdestroydoes, and the host forgets any other kind, as JavaScript’s collector would. So a library destroys what it replaces as soon as it replaces it. - A frame’s objects go once used. An encoder goes at
finish, a pass atend-pass, a command buffer atsubmit, and the canvas’s texture and its views at the nextcurrent-texture. - Misuse is WebGPU’s to report. The host’s
Gpuchecks nothing a device checks: a destroyed object reaches WebGPU’s validation, which reports it on the page’s console. - Descriptors are fields. A descriptor is a list of words and texts in
a fixed order per kind: an object it names is its id, an enum value
WebGPU’s name for it, a list its count and then its items. An object
being made crosses to the host as those fields’ staged bytes, which
host/browser/gpu.mjsreads with aDataViewinto the dictionary WebGPU takes. A render pass and every other command crosses as calls with scalar arguments, an attachment’s view and then its load and store, and a timed pass’s query set and indices before the pass begins. Buffer and texture contents cross asBytes, which the host hands to WebGPU as a view of the program’s memory, without a copy. A pipeline’s layout is WebGPU’s"auto", so a bind group is made against a pipeline, render or compute (GpuPipeline), and a group index.
An earlier version kept books on the program’s behalf: objects found by a
resource path each frame, ended at submit, evicted under a memory budget
and checked by generation. Finding every object again each frame cost
Siegework more than the old JavaScript renderer spent drawing, so the books
are gone and the program keeps what it makes.
Pod and WGSL
A record of F32, I32, WGSL’s vectors (Vec2f, Vec3f, Vec4f,
Vec2i, Vec4i), Mat4x4f and other such records derives Pod. Its
Shape, found by type with (shape), holds its WGSL layout: offsets by
WGSL’s rules, so a vec3f aligns to 16 and an f32 may follow it in the
same 16 bytes; the struct declarations it needs; and, for a vertex buffer,
vertex-layout’s attributes. pack writes a list of values at the
shape’s stride, and pod-bytes one value. derive-pod is a macro beside
the class, as the other derivations are; a deriving macro receives each
field’s type, so a shape needs no value. Derived record and field names
use underscores in WGSL wherever their Scheme names have hyphens. For
example, shaders refer to the record Paint-uniform as Paint_uniform.
A shader is a file of forms, one per WGSL construct, which
shader-library prints when its recipe runs; its header in
src/snail/shell/graphics/wgsl.sld tabulates the forms. A form the
printer does not know fails the build at its line. The device test
(tests/gpu/) draws with a shader from src/gpu-test/paint.wgsl.scm and a
uniform from a Pod record, so the browser’s WGSL compiler checks what the
printer writes; tests/programs/graphics-wgsl.sld and graphics-pod.sld
check the printing and the layouts.
Atlas and quads
An Atlas is a value the application keeps, made with make-atlas once
the device answers: its pages, one rgba8unorm texture array; the
pipeline that composes into them; each source image decoded, by its key;
the packer’s cursor; and a table of slots, each a picture’s page, corner
and version.
atlas-pictures places each picture whose version the atlas lacks on the
next shelf, a texel of transparency around it, and composes it in a render
pass of the caller’s encoder: each layer is a piece that copies a source
region texel for texel, its colors swapped by a run of a storage-buffer
table, over the layers before it (atlas.wgsl.scm). A picture that no
longer fits clears every page, and the pictures asked for are placed
again. The host decodes each source image once, and the atlas keeps it.
A composing’s buffers go at its submit. atlas-url copies a
region back and encodes it as a PNG data URL ((snail shell png)), so an
img in the HUD can show a composed portrait.
A Quad is a Pod record: center and size in world units, an angle, a
page, a texel region and a tint. A Quads, made once for a target’s
format and a texture array, holds the pipeline, the camera’s uniform, the
instance buffer and their bind group; draw-quads writes a run’s
instances and its View2D camera and draws them instanced as a triangle
strip, one run a frame. The vertex shader snaps each corner to the
target’s pixels (quad.wgsl.scm). Both shaders are printed by the recipe
(snail shell graphics shaders).
Hearsay draws this way (src/apps/hearsay/drawing.sld). Its shapes are
pictures too, white texels and a hexagon drawn by the program as PNGs, so
each frame is one run of quads in the old renderer’s order: ties, markers
and rings, bases, figures from far to near, then pips. Its frames match
the old renderer’s within a pixel along edges. On headless Chromium’s
software WebGPU, both keep 60 frames a second, and the page’s main thread
spends 58 to 60 ms a second in tasks against the old renderer’s 47 to 48:
Hearsay rebuilds and packs its quads every frame, where the old renderer
kept batches by version. An atlas composes one picture a call, so a frame
decodes one character’s sheets, each 4.4 MB once decoded.
Slots have transparent gutters, not repeated edge texels: pixel art samples nearest, which never reads past a slot’s edge, so gutters of repeated texels wait for filtered textures, with mips.
Meshes, the G-buffer and the sun
(snail shell graphics mesh) holds eight shapes, each standing on y = 0
within the unit cell, in one geometry table written once. meshes packs a
batch’s Instance records grouped by shape, with one DrawArgs per
shape, so a batch is one drawIndexedIndirect per shape from its own first
instance. An instance carries where it is and where it was, its yaw, scale,
glow, color and whether it turns to face the camera. Its material is a
Vec2f holding metalness and roughness. Its id is an I32 for picking.
(snail shell graphics raster) keeps what a scene draws with. A program
makes its Raster once: the G-buffer’s and the translucent pipelines, the
geometry, and the camera’s and sun’s uniforms with their bind groups; a
GBuffer for the canvas’s size, made again when it changes; and a
Surface for each batch, its style’s uniform and bind group and its
instances and indirect draws, made again when the batch changes. A frame
writes the camera and the sun, and draws. A Camera3D carries its
view-projection and its inverse, computed in closed form for a pinhole or
parallel lens, so the sun pass recovers each pixel’s position from its
depth. A solid surface writes albedo, normal, material (metalness,
roughness, glow) and depth; a revealed batch discards outside its disc.
The Raster and the GBuffer are made for the same Planes, which may
add two more. Motion, rg16float, is the screen motion in texture
coordinates from where the pixel’s surface was in the last frame:
write-raster returns the raster with the frame’s camera kept, so the
next frame’s vertices are placed under both cameras. An upright sprite
faces each frame’s viewing direction when computing its motion. The r32uint plane
holds all 32 bits of each instance’s id field, with 0 where nothing
is drawn. read-id returns those bits as an I32 for picking. A plane
left out has no target in the pipeline and no attachment in the pass,
WebGPU’s null target, so the shader’s output there costs nothing. Siegework draws with
color-planes, the four without motion or ids.
A second pass, begin-lit, clears the target to the background and holds
the G-buffer’s depth read-only, so the pass can both sample it and test
against it. In it, draw-sun of (snail shell graphics passes), through
its Sunlight (the pipeline, and a bind group over the G-buffer), lights
each surface by Cook-Torrance under the sun and the ambient light
(lighting.wgsl.scm). Translucent surfaces are then drawn over it, lit by
the same function, tested against the G-buffer’s depth.
The lit pass draws into a light target of light-format, rgba16float,
so a highlight may be brighter than 1. draw-post, through a Post made
for the canvas’s format and size, brings it to the screen in two
full-screen passes (post.wgsl.scm). The Post‘s Tone chooses the
curve. Neutral, for light already in display terms, takes the shoulder
of Khronos’s PBR Neutral curve without its toe: a color whose largest
channel is under 0.8 passes unchanged, so a scene keeps the colors it was
drawn in, and a brighter one is scaled toward 1, keeping its hue, and
desaturated a little. Filmic, for physical light, is John Hable’s curve
from Uncharted 2 with a white point of 11.2, then encoded as sRGB, since
the canvas’s 8-bit formats are not sRGB formats. FXAA, in the reduced form of Lottes’s algorithm many
WebGL renderers use, then blends each pixel along the edge its diagonal
neighbors’ brightness shows.
(snail shell app)’s draw-frame draws Siegework’s Frame this way,
keeping each batch’s surface until the batch’s version changes, so a still
frame writes only the camera and the sun. Siegework’s frames keep the old
renderer’s shading below the tone curve’s knee, with smoothed edges. On an
RTX 5090, through headless Chromium on Vulkan, the page’s main thread
spends 0.28 to 0.35 ms a frame at 60 frames a second, against the old
renderer’s 0.24. Per frame the program makes one object, the canvas’s
view, writes the camera and the sun, and draws over four passes: the
G-buffer, the lit pass, tone mapping and FXAA. On Chromium’s software
WebGPU, three passes and finding every
object by path each frame cost 31 to 33 ms a second of tasks, and 48 to 52
when descriptors crossed as JSON, against the old renderer’s 20 to 21.
Textured meshes and sprites are gone from Frame; pictures are drawn as
quads from an atlas.
Scans, sorts and gaussian splats
(snail shell graphics scan) computes an exclusive prefix sum of a storage
buffer’s u32 numbers in place, by Blelloch’s work-efficient scan
(scan.wgsl.scm). A workgroup of 256 invocations scans a tile of 512
numbers in workgroup memory, an upsweep building a tree of partial sums and
a downsweep handing each node the sum to its left, and writes the tile’s
total to a buffer of sums one level up. That level is scanned the same way
until one fits in a tile, and each level’s scanned sums are then added back
to the tiles below it, top down. A Scan is made once for a buffer and a
count, keeping each level’s sums, uniform and bind groups, and
dispatch-scan encodes it into a compute pass; dispatches in a pass see
the writes of those before them.
(snail shell graphics radix-sort) sorts u32 keys and their u32 values,
least-significant digit first, eight bits a pass (radix-sort.wgsl.scm).
A pass’s workgroups share the blocks of 256 keys in runs, the first
workgroup taking the first run. A pass counts each run’s keys by digit into
a table laid out digit-major, 256 words a workgroup, and scans the table
with a Scan, which gives where each run’s keys of each digit start. It
then scatters each key and its value there, a block at a time, after the
keys of its digit earlier in the run. A key’s rank in its block is a count
of the matching digits before it in workgroup memory, the simplest stable
ranking, so every pass is stable and the passes together sort. A table
laid out by block, as the sort’s was at four bits a pass, would hold as many
words as there are keys at 256 digits; by workgroup it holds a million at
most. A Sorter sorts 8, 16, 24 or 32 bits from one pair of keys and
values into another. Its passes alternate between the second pair and a
spare pair of its own so that the last pass writes the second pair, so it
sorts a pair in place only when the passes are even: 16 or 32 bits. Both
libraries are building blocks with no knowledge of what they order.
(snail shell graphics splat) renders 3D Gaussian Splatting (Kerbl et
al., 2023) with them. A Gaussian is a Pod record: its center, the row
of the transforms table that places it, a unit quaternion, its standard
deviations and its opacity, already activated. Its quaternion and its
deviations with its opacity are f16s (Vec4h), so a record is 32 bytes
where floats took 48; its center stays a float, since f16s step by 0.004
six units from the origin, more than a tenth of the size of three in four
of bicycle’s trained gaussians. Its 16 spherical-harmonic
colors, to degree 3, sit beside it in a buffer of f16s two to a 32-bit
word, 26 words a gaussian: 104 bytes where 48 floats took 192. Each degree
starts a word of its own, so a kernel reading one degree reads only its
words, and kernels unpack them with WGSL’s own unpack2x16float, which
every device has, where shader-f16 is missing from Dawn on NVIDIA’s
Vulkan driver and from SwiftShader. A
program makes its Splats once with room for its gaussians and its
transforms, writes Clouds of packed gaussians where it likes, and writes
the transforms table whenever things move, so clouds are posed and
composed without touching their gaussians. A frame is a compute pass and a
draw, each in a pass the caller begins:
sort-splatsprojects every gaussian, an invocation each (splat-project.wgsl.scm): its transform carries its center and its covariance R S Sᵀ Rᵀ into the world, the view and the pinhole’s Jacobian at its center carry the covariance to the screen (EWA splatting), 0.3 pixels² of blur keeps it at least a pixel wide, and its inverse is the conic the fragment stage evaluates. Its color is its harmonics seen from the eye in its own frame, through the inverse of its transform. Its key is its depth’s bits inverted, so a radix sort of the keys puts far before near; a culled gaussian keeps radius 0 and the largest key.draw-splatsdraws a square of each gaussian’s radius per instance, in sorted order (splat-draw.wgsl.scm), whose fragments blendexp(-dᵀ conic d / 2)times its opacity over what is drawn.
This is the reference’s math with a global sort and blended quads in place
of its tiled rasterizer, so it needs no per-tile lists. (snail shell graphics ply) reads the binary PLY files 3DGS trains into a Cloud, its
header parsed into where each property sits, every gaussian activated and
given the same transform row. Its write-ply writes such a file from a
cloud as training keeps it, a Trained: the properties in the reference’s
order, nothing activated, the rows that are no gaussian left out. write-cloud sends a cloud to the device
65,536 gaussians at a time, since a write’s bytes are copied whole into the
runtime’s memory on their way and a trained scene’s run to a gigabyte.
(snail shell graphics splat-view) draws the same splats tile by tile, as
training renders them (differentiable
splatting): splat-train‘s graph,
rendered for viewing, lowered to a program that is given the splats’ own
gaussians, coefficients and transforms with bound. Its params view each
Gaussian record as a row of floats, narrowed at the offsets its Pod
layout gives. Each activated scale and opacity goes back to the logarithm
and logit the renderer activates. Each transform row becomes a
Placement, gathered per gaussian. The program’s steps go into the
caller’s compute pass, and a triangle in the caller’s render pass presents
the image. It blends front to back in floats, over black, and stops where a
pixel’s transmittance would fall under 1e-4. The quads blend back to front
in the target’s eight bits and never stop early. Both clamp alpha to 0.99,
skip what is under 1/255, and cull a gaussian under 1/255 opacity. Where
two gaussians stand at one depth, the quads draw the later one over the
earlier, and the tiles put the earlier in front.
src/apps/splats/compare.scm measures the two on Node, at the views a
scene was photographed from, each frame’s passes timed on the device. On
bicycle as src/apps/train trains it (4,194,304 gaussians), at
1237x822, on an RTX 5090, over eight photographs’ views:
| Compute pass | Render pass | PSNR against the photograph | |
|---|---|---|---|
| Quads | 1.37 ms | 2.98 ms | 25.23 dB |
| Tile by tile | 16.10 ms | 0.01 ms | 25.55 dB |
The tiles’ image is closer to the photographs at every view, since training fitted the cloud to this renderer. The PSNR between the two renderers’ images is 38.3 dB on average, and 31.4 at the least. The tiles take 3.7 times as long. Their blend alone took 1.72 ms, less than the quads’ draw. Their two sorts took 1.92 and 0.85 ms. When this was measured, before tensor graphs were fused (#875), most of the rest of their 273 steps were the projection’s tensor kernels, a buffer each.
src/apps/splats opens on one procedural ring written three times on three
transform rows, which it turns each frame, and shows a trained scene in
their place: a .ply dropped on the page, picked, or named by
?cloud=ADDRESS. A reconstruction’s frame has no up of its own, so the
viewer takes it from the cameras that photographed the scene, COLMAP’s
images.bin, read by (snail shell graphics colmap), whose poses-up is
the mean of their ups. It turns the cloud upright by its transform row,
where the harmonics turn with it, and starts at the first camera. (snail shell graphics fly) flies the view, as it does the path tracer’s, and its
upright is the turn. Mip-NeRF 360’s bicycle as
src/apps/train trains it, a 1 GB file of 4,194,304 gaussians, took 22
seconds to read in Chrome and flew at the display’s 60 frames a second on
an RTX 5090. T toggles drawing tile by tile. Every two seconds the console
has the frame rate and one frame’s compute and render passes, timed on the
device where it has timestamps.
tests/programs/graphics-splat.sld reads a PLY file and records the
dispatches of a frame of 300,000 gaussians; tests/browser/gpu.mjs scans
300,000 numbers in three levels and checks each, sorts 5,000 keys and
checks the order is stable, and splats three gaussians, then turns one by
its transform, as quads and tile by tile; both agree to a step of a texel. On an RTX 5090, through headless Chromium on Vulkan, the
viewer keeps 60 frames a second with room for 60,000, 1,000,000 and
4,000,000 gaussians, the gaussians it does not write culled but sorted and
drawn; from submit to the queue’s completion takes 3.9, 3.8 and 5.8 ms at
the median.
Middleware, not a renderer
The graphics libraries are middleware: composable WebGPU pipelines and packers whose interfaces are buffers and textures, in WebGPU’s own terms. The application decides what to pack, when to copy, and how to stitch passes together. A higher-level operation such as drawing a sphere is a helper that prepares the buffers a pipeline expects, not a call into a renderer.
The ABI is not stable, on purpose. A pipeline’s interface is a snail-scheme
record deriving Pod, and it changes when the pipeline does. Nothing is hidden
behind a renderer object: every pass, buffer and layout is a value the
application can read, replace or extend.
- No bindless. Core WebGPU has no binding arrays, so material textures live in atlas arrays, and the quad pass draws runs of quads that share a texture. The path tracer puts every image in one texture array for the same reason (scenes).
- No multi-draw. The G-buffer pass issues one
drawIndexedIndirectper geometry; theindirect-first-instancefeature lets each start at its own instance. - A low-poly game packs its geometry, material and instance tables, renders albedo, normal and depth, lights them with a sun pass of its own or the library’s, and composites the result to the canvas with quads. A richer game builds its own passes from the same pieces.
- Filtered textures are proposed: the atlas would then carry gutters
of repeated edge texels and mips, UVs would wrap in slot space (
fractto repeat,clampto clamp) with samples half a texel inside the slot, and a filtered sample would usetextureSampleGradwith derivatives of the unwrapped UVs, so the wrap cannot spike the mip level. Pixel art samples nearest today, which needs none of this.
WebGPU on Node
On Node the device is Dawn’s, the
WebGPU implementation inside Chromium, through Dawn’s own Node binding,
dawn.node, as npm’s webgpu
package publishes it prebuilt. The repository’s package.json pins it and
make fetch installs it; a Node build of a program that may ask for a
device depends on the same version
(a Node package). On Linux,
Dawn reaches the GPU through Vulkan, opening the loader by name, and the
loader finds the system’s driver. NixOS keeps no loader where the dynamic
linker looks, so shell.nix names nixpkgs’ in LD_LIBRARY_PATH; outside
the shell, NixOS needs the same, or vulkan-loader among nix-ld’s
libraries. The shell also adds Mesa’s lavapipe, Vulkan on the CPU, to the
system’s drivers: Dawn prefers a GPU, and on a machine without one, as
CI is, the checks run on lavapipe. host/native/gpu.mjs hands Dawn to the same
host/browser/gpu.mjs the page uses, at the program’s first
request-device, so a program that never asks for a device needs none. A
program on Node makes the Gpu itself, as tests/gpu/node.scm does:
(define (main (host Host) (out OutputPort)) (→ Unit)
(let* ((gpu (host-gpu host)) (info ((● gpu request-device))))
(write-line out (string-append "format: " (texture-format-name (● info format))))
(device-checks gpu out)
((● gpu work-done))))
Node has no screen: there current-texture fails, so a program draws into
textures of its own, which are rgba8unorm, and reads them back.
Dawn rounds timestamps to 65,536 ns unless told not to, as Chromium rounds
a page’s to 100 μs, so that a page cannot time what it should not see.
host/native/gpu.mjs tells it not to: a program on Node is no page, and
can time a kernel of a few microseconds.
Node decodes no images of its own either, as a browser does, so
decode-image there is npm’s
@napi-rs/canvas package, a 2D
canvas over Skia, pinned and installed as webgpu is and loaded at a
program’s first decode. It reads what a browser reads, JPEG, PNG, WebP, GIF
and AVIF among them, and gives the same texels: turned as the image’s EXIF
orientation says, with straight alpha. An image is decoded off the
program’s thread, then drawn on a canvas and read back on it. A canvas
keeps each color multiplied by its alpha, as a page’s bitmap does, so both
hosts give a color exactly where the image is opaque and round it alike
where it is not: (200, 100, 50) under an alpha of 3 comes back
(170, 85, 85), and under an alpha of 0, black. A 4946 by 3286 JPEG took 127
to 171 ms, about 50 ms of it on the program’s thread, and four at once 256
to 265 ms; a 1237 by 822 one took 10 to 16 ms. The package is MIT. The
binary it installs holds Skia, which is BSD-3-Clause, and its bill of
materials lists four MPL-2.0 crates among permissive ones.
Dawn runs in the program’s process. Chromium’s runs in a GPU process that each call is sent to. On an RTX 5090, under Vulkan, a chain of 10,000 dependent one-workgroup dispatches, alternating among eight pipelines and bind groups, measured:
| Per dispatch | Node | Chromium 152 |
|---|---|---|
| Encoding, on the program’s thread | 1.4 μs | 0.06 μs |
| Encoding and running | 2.3 μs | 1.9 μs |
| Submitting one and waiting for it | 19 μs | 500–600 μs |
The page only records each call for the GPU process, which encodes in parallel, so a long batch runs about as fast on either. A program that waits on the device often, as a training loop that reads its loss does, waits a thirtieth as long on Node. Chromium coarsens the page’s clock to 100 μs, which the last row’s range shows.
Node keeps Dawn’s guards, as a browser does: validation of every call, bounds checks on shaders’ memory, and zeroed workgroup memory and resources. Turning the first three off, which Dawn’s toggles allow, saved 0.1 μs of the 1.4 that encoding a dispatch takes on the 5090, and a shader that gathers 268 million words at computed indices took the same 7.84 ms without bounds checks. The zeroing cannot go: WebGPU promises zeroed buffers, and a tensor program’s params start at zeros, Adam’s moments among them. What Node gains is Dawn in its own process.
An indirect dispatch is the exception. Dawn checks its arguments on the
device with a dispatch it adds before it, and gives that dispatch a new
uniform buffer each time, written at creation through a staging buffer the
host can map. Dawn’s Vulkan backend gives every mappable buffer memory of
its own (crbug.com/dawn/849), and making one took about 0.23 ms on the
5090. Submitted one at a time, a validated indirect dispatch took a median
of 0.26 ms of wall time through submission and 0.22 ms more waiting for
completion, against 9 and 11 μs for a direct one; with validation skipped
it took what a direct one does. The wait may be the release of the staging
buffer, but onSubmittedWorkDone waits for the device as well, and only a
trace would tell them apart. Chromium takes about the same for a page.
Nothing needs indirect dispatches. A kernel that a count the device
computes sizes runs a fixed number of workgroups, at most 4,096, which
read the count and loop over the work below it, so the work is the
count’s (radix-sort.sld, bvh.sld). That costs the device less than
launching exactly the workgroups the count needs: eight dispatches of a
kernel storing each key took 0.026 ms over 1.65 million keys, and 0.034
ms dispatched indirectly with validation skipped; over 33.5 million keys,
0.637 and 0.821 ms. A few thousand long-lived workgroups beat a workgroup
for each block. So validation costs a training step nothing measurable:
bicycle’s 30,000 steps took 857.5 s with it and 857.1 s without.
Device baseline
Required features: indirect-first-instance, float32-filterable and
rg11b10ufloat-renderable. Used when present: texture-compression-bc,
which phones lack, shader-f16, which SwiftShader, the tests’ adapter,
lacks, timestamp-query, for profiling, and subgroups, which splat
training’s backward pass sums over; request-device answers which it got.
Raised limits, as far as the adapter allows: buffer and storage-binding
sizes of 1 GiB, 16384-texel textures, 64 bytes of color attachments per
sample, since a full G-buffer fills the default 32, and 32 KiB of
workgroup memory. Texture
heaps start uncompressed; a later reset may choose BC.
Design choices
- Images are decoded by the host behind
decode-image, a host operation that waits, rather than insnail-scheme. It answers nothing for bytes the host does not decode. updateonly computes: prefetching happens fromdraw.- Shader sources are S-expression files printed by
generate-libraryrecipes, since a quoted form is a literal only. A shader’s structs come fromPodat run time:(string-append (declarations shape) shader).
Tensors and training
(snail shell tensor) is a GPU tensor library in the shape of
Resin’s: a program builds a lazy graph of
nodes, rewrites it symbolically for gradients and optimizer steps, and
lowers it explicitly to plain WebGPU objects the caller owns, which run as
often as a training loop likes, on the page or on Node (WebGPU on
Node). Its six libraries, from (snail shell tensor) to (snail shell tensor eval), are listed with their entry points
in the library reference; this chapter explains
how they work, and how 3D Gaussian Splatting trains on them.
Graphs and views
A node computes one dense buffer for each of its ports. Programs work with
views, each an accessor over a port: an offset, a shape, and a pitch for
each axis, in elements. So narrow, transpose, permute, squeeze,
unsqueeze and broadcast-to make no node; a pitch of 0 repeats an element
along its axis. Binary operations broadcast as NumPy’s do, and View is an
instance of Num and Fractional, so (+ a b) and (sqrt v) build
nodes.
| Kind | Computes |
|---|---|
Param, Constant, Fill | A buffer the host writes, bytes given at build time, one value everywhere |
Map | A typed expression, a value or a small tile, at each element of its leading axes |
Reduce | A typed expression summed, or its maximum or minimum taken, over trailing axes |
Place | A gradient placed at a view’s addresses |
Gather, ScatterAdd | Rows by u32 index, and their adjoint |
Concat | Views joined along an axis; stack joins them along a new one |
Sort, PrefixSum | u32 keys and values sorted stably, all or as many as a count says; an exclusive prefix sum |
Compact | The rows whose flag is not 0: their indices packed to the front, which rows are below their count, and the count |
CustomKind | Kernels a library writes in WGSL, with their own adjoint |
A map’s body is an Expr: Load k, argument k’s element at the map’s
index; a Literal; or Apply, one of 34 operations (Op) on others. Each
carries its element type, so a body may convert or reinterpret between
types. A load never addresses: its argument is a view, and the view’s
accessor says where its elements are. An operation such as +, exp or
where builds a map of one Apply over loads, a Fill operand becoming a
literal, so a map reads only buffers. A copy is a map of one load, and it is
the one way a view becomes a buffer.
Each expression also carries its tile: the shape of the block of values it
is, () for one value. A map computes its body once at each element of its
leading axes, and its port is those axes followed by the body’s tile. A
load of a tile reads as many trailing axes of its argument there, and an
elementwise operation applies to each element of its operands’ tiles, a
value standing for every element. Four operations are of tiles: Pack
joins its operands’ elements into one tile, Pick takes elements at
places counted row-major, so it transposes, reshapes and selects, Product
multiplies a tile of (m, k), or a row of k, by one of (k, c), and
Fold combines a tile’s elements into one. So a map can build a gaussian’s
rotation matrix from its quaternion and multiply it by its scales, one
thread a gaussian.
A reduction has a body too. It computes it at each element of its
arguments’ shape, its port’s axes followed by its span, and combines it
over the span. The constructors choose between the two by size. (matmul a b), of (..., m, k) by (..., k, c), is a map of tiles when k and c
are at most 16: the whole product at each matrix when it has at most 16
elements, a row at a time otherwise. An outer product, with k of 1, goes
a row at a time too: its rows share nothing, so nothing is computed twice,
and a kernel taking it in runs a thread for each row. A larger product sees both at (..., m, c, k) and sums their product over k. sum, amax and amin see
their operand with the reduced axes last and keep those axes at size 1;
over at most 16 elements each is a map folding a tile, and over more a
reduction of one load. concat along the last axis into at most 16 is a
map packing each element’s tile; any other is a Concat.
A node is known by its key, a 64-bit hash of its kind, its parameters, its ports and its arguments’ keys and accessors. The language has no reference equality, and content addressing gives more: building the same computation twice builds the same node, so a graph shares its common parts, and a param is known by its name and shape. A constant snapshots its input bytes and includes them in its key, so constants can reuse a label across uploads.
Gradients and Adam
(grad loss wrt) walks the nodes the scalar loss depends on from last to
first, as Resin’s grad does. Each kind answers the gradient of each
argument given the gradients of its ports, and a custom node answers with
its own adjoint. A map’s gradient goes back through each of its bodies
from the top, whose value is the body’s port, and a map of several ports
adds what its bodies hand back; a port with no gradient, which nothing the
loss depends on reads, adds nothing. Through a body of one operation, as
the library’s operations build, the operation hands its operands their
shares as nodes, and each load adds its share to its argument’s. The
shares of tile operations are built of the same operations: a product’s
are two products, a pack’s its gradient narrowed to each operand, and a
fold’s its gradient spread over the tile, or over the elements equal to
the result. A body of several operations is differentiated as one
expression instead: the port’s gradient is carried back through every
operation inside one map for each argument, an operand’s value computed
again where a rule needs it, and a load picked apart takes each element’s
share at its place. So such a map’s gradient is as many kernels as its
arguments, not one for each share. A
reduction’s gradient is spread over its span, to every element for a sum
and to those equal to the result for a maximum or minimum, and goes back
through its body the same way, so a large matrix product’s gradients are
products summed again. A view’s gradient reaches its port through the
view’s accessor: it is summed over the axes the view broadcasts, then seen
back through the view when the view reads its whole port in some order of
its axes. Otherwise it is a part, kept with the addresses it reads, and a
port’s parts are gathered once every node reading the port has handed one
back. Parts that each read a run of one axis of the port, all of its other
axes in the port’s order, are joined along that axis in order, with zeros
where none reads: a concat, which a kernel reading the gradient takes in
when the axis is the last and at most 16 wide. Any other part is placed
among zeros at the addresses it reads, and the places are added. Placing
every part so, as this once did, wrote and read the whole port once a
part: the harmonics’ basis, 16 numbers a gaussian that each degree reads a
run of, cost 2.5 ms of step 7,000 in three places and their sum. Sorts, prefix
sums, comparisons and bit operations pass no gradient. A custom node’s
adjoint that needs the node’s other ports, as a backward pass needs what
its forward pass kept, builds the same node again from its arguments, and
content addressing gives back the node itself.
(adam-updates prefix settings trained) builds Adam’s step for each
Trained param, gradient and rate, the rate being a view so a schedule is
a param the host writes. The moments and the step count are params named
under prefix (moment-names). They start at zeros, as every buffer does,
and a host may write them, as densification does when it changes how many
gaussians a param holds.
Fusing
(fuse-program sinks updates) rewrites a program’s graph so that a map
takes in the maps it reads, as Resin’s fuse_elementwise fuses its
dispatches. One kernel computes both, and the producer’s buffer is not
written unless something else reads it. The answer is views of the same
values computed by fewer nodes, for lower to lower as it lowers any
graph; (fuse roots) does the same for a list of views.
(let ((fused (fuse-program sinks updates)))
(lower gpu "step" (● fused first) (● fused second)))
A producer is inlined into each map that reads it: the consumer’s load becomes the producer’s body, whose loads are seen through the consumer’s view. A view of a view is an accessor when each axis of the outer view steps along the axes of the port it sees without carrying into the next. Broadcasting, permuting, narrowing, squeezing and splitting an axis all do that, and any view passes through a producer that read its argument densely. Merging the axes of a port whose producer read a strided view is not an accessor, so that producer stays a node. A map of tiles computes each tile once, so a view of it is taken in only where it reads whole tiles, the same places of each, which a pick takes: a column of a map of 3×3 matrices is three places of each. A map of values that reads a map of tiles a whole tile at a time becomes a map of those tiles to take it in, so Adam’s moments of the harmonics’ coefficients, whose gradient is computed a row of three colors at a time, are too. A body stays within 256 distinct expressions, each counted once however many times fusing inlined it, since lowering names each once: counted as a tree, the harmonics’ basis, which each degree’s product reads, was too large to take into the color’s kernel, so the viewer’s frame wrote 16 floats a gaussian and read them back, 6.7 ms where it is now 5.9. A kernel binds at most eight buffers, its ports among them, so a sum of eight params is two maps. Types do not stop fusing: each expression carries its own. A reduction’s body takes in maps as a map’s does, so a large matrix product computes its products as it sums them, but nothing takes in a reduction. Any other node keeps the map that feeds it, so reductions, gathers, concats, sorts and custom kernels are where fused kernels end.
Fusing plans from the roots down: a map takes in what it can, from its first argument on, until nothing more fits, before anything it reads takes in anything. So what a map took in never leaves it too wide for the map reading it. A kernel taking in a producer reads what the producer reads in place of its port, and that may be more: a pick of one element of each tile of a product reads every tile the product reads, since a view stepping through a buffer a few elements at a time touches all of its memory. So a producer is taken in only where, were every reader to take it in and its own kernel go, they would read no more than they save. One that a reader planned before keeps is computed anyway, at its first place in the fused order, so it is taken in only where that reads less than its port. A producer whose readers see more than its elements is computed again in each kernel taking it in, and what it reads stays alive until the last of them, so it is taken in only where that also holds no more bytes, for no more of the program’s steps, than its own buffer would. What it reads is the buffers under the maps only it reads, which go with it, and any map others read too, which stays a buffer; one the kernel binds already, or one that a later node reads anyway, counts as nothing. So the quaternions’ gradient, gathered from the columns the rotation matrices read, is written once for Adam’s moments to read; the projected covariances that some twenty kernels of the backward pass read are written once rather than computed from the rotations in each; and the rotations, which the backward pass reads by column, are written in the forward pass rather than kept as their parts until then. Since this weighs every node reading a producer, a program’s sinks and updates are fused together.
A producer whose port is kept anyway keeps its own kernel where a map
reads it, since taking it in would only compute it twice. Its port is
kept for an update’s value or a sink, or for a later kernel that reads
its buffer. A map can write it instead, if it reads the producer whole
and in order, at the elements each of its threads computes, and nothing
that runs before the map reads it. The map then takes it in and writes
its port as one of its own, for what runs later to read. That makes a
map of several ports, one kernel computing each of its bodies, which
share every expression they have in common (mapped-ports). Adam’s update of a param reads the two moments it updates
whole, so the three updates of each param become one kernel of three
ports. A value of the forward pass that a later forward kernel reads whole,
and the backward pass reads again, is written by that forward kernel
rather than by a kernel of its own. Each port counts toward the kernel’s
eight buffers. A param that a port writes in place shares that port’s
binding, but lowering decides which ports it writes in place, after
fusing. So fusing counts the shared binding only for a param nothing else
reads, as nothing but Adam reads its moments, where lowering is sure to
write in place, and lowering refuses a map of more than eight.
On bicycle, fusing took a training step from 779 dispatches to 348, and the splats viewer’s frame from 272 to 80. With gradients’ parts joined, Adam’s updates of each param in one kernel, and the backward pass reading what forward kernels wrote, the step at 7,000 was 155; with the harmonics’ basis one map, whose gradient is then one map too, it is 127. Of the viewer’s 6.9 ms for 4 million gaussians on an RTX 5090, most goes to the generated kernels that project every gaussian, culled or not; of them, the harmonics’ color costs most, reading each gaussian’s 48 coefficients, f16s two to a word.
Lowering and running
(lower gpu label sinks updates) lowers what the sinks and updates need to a
Program, once. Sinks are views to read back; updates are
pairs of a whole param and the value it takes after the run. Both need
the same element count and element type. Use convert for a numeric
conversion or bitcast to reinterpret the stored bits. Every sink and
update reads the params as they were at the start of the step. Two params
can swap values in one run, and an update can initialize a param that no
sink reads.
(let ((program (lower gpu "fit" (list loss) (adam-updates "adam" settings trained))))
(write-param gpu program "points" bytes)
(for-each (lambda (_) (run-program gpu program)) (iota 1000))
(read-sink gpu program 0)) ; loss used by the last update
Everything a program holds is ordinary WebGPU, and the caller’s: its
steps, each a dispatch with its WGSL text, entry, pipeline, bind group and
workgroups, or a sort or a scan; its params and sinks, each with its
buffer; and made, every buffer it made, with its use and size.
(encode-steps gpu pass program) encodes the steps into a compute pass the
caller began, among its own work; run-program is that in a pass and a
submission of its own. release-program destroys what the program made and
nothing it was given.
Each node’s kernel is generated as WGSL text whose shapes, pitches and
offsets are literals, a thread per output element, or per element of a
map’s leading axes, so two nodes that compute alike share a pipeline. A
Fill argument is a literal too and gets no buffer. A map’s body becomes
one let for each element of each distinct load and operation, a product
written out as sums of products and a pack or a pick only renaming its
operands’ elements, so an expression fusing copied into two places is
computed once and no expression nests another, and a map binds each port
its arguments see once. A choice of zero, (where condition value 0)
whose condition is one value however wide the value, is an if: the
value’s lets run only where the condition holds, so a row it culls reads
and computes nothing for it in the kernel the choice is in. What fusing
left in a kernel of its own runs for every row. A choice met again, as
fusing copies a map into each place that reads it, takes the names its
first if set, so a kernel computes each choice once. The splat renderer
chooses a culled gaussian’s harmonics so, which in a training step skips
a quarter of their kernels’ time. The viewer’s frame is no faster: its
sum of the harmonics’ products, which reads their coefficients, is a
kernel apart from the choice. A reduction computes its body as it combines it: a
thread an output element when its span is at most 256 elements, and in
levels otherwise, a workgroup combining each part of 4,096 elements in
shared memory, the first level computing the body, until one part is left.
A float ScatterAdd adds with a compare-and-swap loop. Sorts and prefix
sums run on the radix-sort and scan middleware (the WebGPU
design). Every dispatch is in one
compute pass, so each sees the writes of those before it, and dispatches of
more than 65,535 workgroups are laid out in rows.
Shapes are fixed when a program is lowered, so a buffer has room for the
most it may hold, but a count the device computes can size the work: a
port of one u32, read where it is written, never by the host, so nothing
waits. sort-first-pairs sorts as many pairs as its count says and writes
none past them, which are unspecified. Each of the sorter’s passes runs a
fixed number of workgroups, at most 4,096, that share the blocks counted in
runs, so a pass costs the keys counted, not the capacity. A custom kernel
does the same with a count among its arguments. Dispatching only the
workgroups a count needs would take an indirect dispatch, which with
Dawn’s validation takes about half a millisecond of wall time each, against
microseconds for a direct dispatch
(WebGPU on Node).
A filter is a Compact after an exclusive scan of its flags, which gives
each kept row its place among them. Its kernel runs a thread a row: a
kept row writes its index at its place, a thread at or past the count
writes 0 at its own, and the first thread writes the count, the last
row’s place plus its flag. So kept-rows, a gather by those indices
chosen by live, packs the kept rows to the front, and a choice by
live after it skips the rows past the count together, where a mask’s
culled rows sit among the kept ones, and nearly every group of threads
the device runs at once holds one it keeps.
A sort’s first pass reads its keys and values where they are, and its last writes its ports, so a sort copies nothing. A fill or a part of a buffer is copied first into scratch the pool lends for the sort.
A kernel binds at most the eight storage buffers every device allows, so
concat joins more than six views in a tree, whether as a map packing them
or as a Concat, and a custom node packs what it reads.
Buffers are pooled by liveness: once the last node reading a port has been dispatched, its buffer returns to a pool, and a later port of its size takes it. Params, constants, sinks and updated values keep their buffers. What is left in the pool once a program is lowered is its scratch, which holds nothing between runs. An update is copied into its param after every node, unless a map computes the whole of it and nothing could tell the map wrote it in place: the map reads the param only at the elements each of its threads writes, and no later node, sink or other update reads the param. Then the map’s port is the param’s buffer, which its kernel binds once and reads the param from, since WebGPU lets a dispatch bind a buffer it writes no other way. Adam’s updates are such maps, so a step holds no second copy of the cloud’s params and moments. A map of several ports writes each of its updates in place, each read through its own port.
A caller gives a program buffers with (lower-with gpu label sinks updates given). A Given holds buffers for params by name, which the program
reads and writes in place of making its own, and free scratch to start its
pool with. (bound given view buffer) adds the caller’s buffer for the
param view sees whole, as a viewer gives the buffer its gaussians are
already in; the buffer must be the param’s size. Programs that take turns
on one set of params, as a training step and densification do, give the
second what the first has, (given-by first): its params, and its scratch,
so the second costs little more than its own sinks, which it copies out of
the scratch. It is released no later than the first. To grow, a host
stashes the params (stash-params, copies on the device), releases its
programs, lowers larger ones, and gives the params back (unstash-params,
as much of each as both hold), so two sets of scratch are never held at
once.
(profile-program gpu program) answers each step’s seconds on the device,
with its kernel’s entry and code. Each step runs in a compute pass of its
own, begun with timestamp writes, and every pass goes in one submission,
so the device runs the steps back to back, as a run does, and the times
are read once, after the last. It needs the device’s timestamp-query
feature. Node’s times are not rounded; a browser’s are, to 100 μs, so a
program is best profiled on Node. A pass per step costs a little that one
pass would not, so the sum is a little more than a run takes.
A traced run (Traces) shows
instead each pass a run makes for as long as the device ran it, with no
passes added.
tests/programs/tensor.sld evaluates each kind on the CPU and checks every
gradient grad builds against central differences. On the device, which
tests/browser/gpu.mjs and tests/gpu.mjs run, (gpu-test tensor)
lowers sinks covering the generated kernels, including reductions in
levels, float scatters, a sort, and small products, packs, picks and folds
with a gradient through them, unfused and fused. It compares integer
outputs exactly and float outputs to a part in a thousand against the CPU.
It runs a program whose param is a buffer the test made, in the test’s own
pass, and reads the buffer back after releasing the program. It then fits a
line with Adam in 1,000 runs of one program.
Differentiable splatting
(snail shell graphics splat-train) is the renderer 3DGS training descends
through, built as a tensor graph. render draws a Cloud of params
(splat-params) from a camera param into an H x W x 3 image, and answers
the projection too, whose centers’ gradient densification watches. A
cloud’s spherical harmonics are a param for each degree, each shading only
while its entry of degrees is 1, so a schedule raises them. Its live
mask culls the rows it has not used yet, so a program lowered for a
capacity holds a cloud that grows. Unused rows can be left at zero through
training.
A rendering has a Purpose. One for Training keeps what the backward
pass starts from. One for Viewing keeps only the image, and has no
gradient. The trainer renders its held-out views for viewing, and so does
the splats viewer, which draws its clouds with this renderer as well as
with quads (splat-view). A
viewer’s cloud may also carry a Placement: each gaussian’s affine map
into the world, which carries its center and covariance there and a
direction back into its own frame for its harmonics. A training cloud
stands in the world and has none, so its graph is unchanged.
- Projection is ordinary tensor operations, so
gradderives its gradient. Each gaussian’s normalized quaternion and exponentiated scale make its covariance R S Sᵀ Rᵀ. The camera carries it to the screen through the pinhole’s Jacobian at its center (EWA splatting), with the center’s slope clamped and 0.3 pixels² added, as the reference does. Its spherical harmonics, seen from the eye, give its color, each degree’s basis times its coefficients as a matrix product. The basis, sixteen numbers a gaussian, is one map of its direction, sogradcarries its gradient back as one map: built of sixteen maps and a concat, it came back as a node for each operation, which fused into fifteen kernels, and step 7,000 took 25.15 ms on the device against 21.64 ms now. A gaussian is culled, its radius 0, behind the near plane, when degenerate, or when the square of its radius about its center misses the image, as the reference culls. Densification counts the views that drew a gaussian by that radius: counting every gaussian in front of the camera, as this once did, diluted their mean gradient on bicycle’s 360° views, and the cloud grew to 750,000 gaussians where the reference’s grows to millions. - Binning is custom kernels around the middleware’s sorts. The kernels
are
splat-count,splat-keysandsplat-ranges. A filter keeps the gaussians that reach a tile, in order, about a quarter of bicycle’s trained cloud in a view; only they are sorted by depth, and each one’s tiles emitted in that order at the prefix sum of their counts, so a gaussian off the image costs no more than the count of its tiles. A gaussian’s tiles are those it reaches: those with a pixel center where its alpha is at least 1/255, the least the rasterizer blends, so binning drops nothing the rasterizer would draw. Each tile in the bounding box of the gaussian’s ellipse at that alpha is tested where its conic’s quadratic is least over the tile’s pixel centers, on the side nearest the center across or down. Binning as the reference does, every tile of the square three standard deviations along the widest axis about the center, made 4.5 million entries for step 7,000’s view of bicycle where this makes 1.7 million, and cut an opaque gaussian at three deviations, where its alpha passes 1/255 out to 3.33. A stable sort by tile then leaves each 16x16 tile’s entries near to far. The radix sort includes enough bits for every tile’s key, including on grids with 65,536 or more tiles. The entries asked for, the last gaussian’s offset and count, are counted on the device, and the tile sort andsplat-rangescover only those, so the capacity’s room costs memory and no time. Binning passes no gradient. The sensor’s capacity bounds the entries; past it the farthest gaussians’ are dropped, so a rendering answers how many entries its gaussians asked for, and a host lowers room for more before they run out. - Rasterizing is a custom node (
splat-forward), a workgroup per tile. It blends as the paper does and hands each pixel’s final transmittance and its count of entries tokeep. The purpose chooseskeep‘s text: rendering for training putssplat-forward-state.wgsl.scmfirst, which binds two buffers and stores both, and rendering for viewing an empty function. A WGSLoverridecould only skip the stores. The bindings would stay, since WGSL counts a binding named in a dead branch as used. Its adjoint is another custom node (splat-backward), which walks the entries far to near, undoing the transmittance, from as deep as the tile’s deepest pixel went. Many pixels add to one gaussian’s nine gradients, so each subgroup sums its pixels’ first, and skips a gaussian none of them blended. Each tile sums its subgroups’ in workgroup memory and adds one sum a gaussian into the gradients with a float compare-and-swap loop. On an RTX 5090 at 4946x3286 that takes 18 ms; adding every pixel’s gradients straight into the gradients took 4 seconds. It needs WebGPU’ssubgroupsfeature, which the browser host asks for when the adapter has it. - The loss is
photometric-loss: (1 − λ) L1 + λ (1 − SSIM), the reference’s. SSIM is a custom node (splat-ssim), fused as fused-ssim is (Mallick et al., 2024): a workgroup blurs a tile’s moments by the 11-pixel window in workgroup memory, so no blurred moment fills a buffer, and keeps each pixel’s derivatives by the moments. Its adjoint (splat-ssim-backward) blurs those back into the image’s gradient.rgba8-imageturns texels copied from a texture into the target image.
(gpu-test splat-train) checks the renderer on the device at 64x48 pixels:
- one gaussian’s pixel equals the paper’s blend computed by hand, rendered for training and for viewing;
- each of three gaussians’ 59 params’ gradients equals a central difference of the loss on the device, to 5%;
- Adam brings a dimmer, smaller cloud’s loss against a rendered target down by more than four times in 200 steps.
The gradient check’s gaussians are wide, so the contour where alpha falls to 1/255, which the rasterizer skips, is off the image. A pixel crossing that step changes the loss by more than a small nudge’s gradient does, and the reference’s gradient, like this one, ignores the step.
Training on photographs
(snail shell graphics colmap) reads the sparse reconstruction COLMAP’s
structure from motion leaves: cameras.bin, each camera’s pinhole;
images.bin, each photograph’s pose and file name; and points3D.bin,
each point’s position and color. A reader answers (Ok records) or why
not, a truncated file or a camera model other than SIMPLE_PINHOLE and
PINHOLE, whose photographs must be undistorted first. camera-sized is
a camera as it took photographs of another size, as a dataset’s smaller
copies are, scaled across as their width is and down as their height
is, since the two round apart. camera-values turns a camera and a pose
into the 16 numbers of camera-param.
(snail shell graphics splat-fit) is the reference’s training as three
tensor graphs a host lowers for a capacity of gaussians, on one set of
params:
training-steprenders from the camera param, takes the loss against the target param, a photograph’s texels copied from its texture, and answers Adam’s updates of the cloud at the reference’s rates, the centers’ at the paramrate, which falls from 1.6e-4 to 1.6e-6 times the scene’s extent (rate-of-means). It also adds each drawn gaussian’s screen-space gradient’s length, in units of half the image, to densification’s statistics, and counts the views that drew it. Its sinks are the loss, the image and the entries binned.densificationdecides, a 0 or 1 a row, which gaussians are kept, cloned and split: one whose mean screen-space gradient reaches 2e-4 is cloned when its largest scale is within 1% of the extent and split otherwise, and one is pruned under 0.005 opacity or, once the paramprune-bigis 1, past a tenth of the extent. Exclusive scans of the kept and the new give each row’s place, a custom kernel (splat-place) writes each slot’s source row and kind, and gathers lay every param and moment out again, kept rows first. A split’s two children take its center plus R (s n) for normal samples n (splat-normals) and its scale over 1.6; a new row’s moments start at zero; the statistics are cleared; a sink counts the live. The reference’s cloud has no capacity; this one’s does, so rows clone and split in order only while what they add fits beside the rows that stay, and the rest wait for a roomier program. A full cloud never drops a split gaussian’s children. The paper also prunes a gaussian drawn wider than 20 pixels, but its code clears the radii before testing them, so it never does; neither does gsplat by default, nor this.opacity-resetbrings every opacity down to 0.01 and clears its moments.
src/apps/train runs the reference’s schedule, on Node or in a page, in
three parts:
- The trainer,
(apps train trainer), knows no file, address or format. It trains on aScene: the camera, the posed views to train on and those held out, and the sparse points, as data. It asks itsPhotographsfor a view’s photograph, a texture on the device, and is given how a step’s image is shown: on the page’s canvas, or nowhere. - The dataset,
(apps train dataset), is a COLMAP dataset as such a scene: how its files are read, the camera scaled to its photographs, the decoding, and every eighth photograph held out. - The entry points link the dataset, Mip-NeRF 360’s bicycle as
(datasets mipnerf360 bicycle)gives it (datasets), and say what is kept. A page fetches the files from its store and keeps nothing; a program on Node reads them from its package and keeps the cloud.
A program whose scene is made or embedded calls the trainer alone, with a
Scene of its own and a texture for each view asked for.
The trainer starts a
gaussian at each sparse point, its scale the root of the mean squared
distance to its three nearest neighbours (splat-knn, on the device), its
opacity 0.1. Each step trains on a photograph not yet visited in this
round, copied on the device into the target param. A photograph is asked
for four steps ahead, in a task of its own that posts it to a
mailbox, and let go after its step, so the device holds five photographs
and not the scene’s: bicycle’s 194 at full resolution would take 12.6 GB
as textures. It raises the
harmonics’ degree every 1,000 steps, densifies every 100 steps from 500 to
15,000, and resets opacity every 3,000. When more than half the capacity is
live, up to the page’s gaussians, or the step’s binning asked for more
than three quarters of the entries, it lowers larger programs: it
stashes the params, releases the old programs and gives the params back to
the new ones. A step and densification make about 1.6 KB a gaussian of
capacity, mostly Adam’s: each param’s value and moments, which its
updates write in place, and its gradient in scratch. So the 4,194,304
gaussians gaussians allows by default take 6.6 GB beside the sorts and
photographs, and the 8,388,608 that doubling would reach next would take
13 GB. The PSNR on the views held out is reported at the end.
train answers the programs it trained, and trained-cloud reads their
cloud back from the device as arrays. The program on Node writes those
with write-ply, as the .ply file the reference implementation writes,
at cloud=PATH, and src/apps/splats flies through it.
On Mip-NeRF 360’s bicycle at images_4, the paper’s resolution for its
outdoor scenes, on an RTX 5090, the 30,000 steps take 14.3 minutes on
Node, to a held-out PSNR of 25.29 against the paper’s 25.25. The cloud
fills its 4,194,304 gaussians at step 10,300, while the reference’s grows
on until densifying stops at 15,000, to 4.9 million.
A bench
trains the reference and gsplat beside it on the same GPU: they take 17.2
and 10.4 minutes, to 25.23 and 25.15. Their steps take longer as their
clouds grow; the programs here have shapes fixed by their capacity, so a
step takes nearly as long with a million gaussians live as with four:
26 ms against 31. At full resolution the photographs no longer limit a
run, since they are streamed; the step’s own buffers do. Before binning kept to the tiles a gaussian
reaches, the default cloud’s entries reached 2^27 near step 6,500, and the
programs for them no longer fit a 32 GB device beside the cloud’s 14 GB.
A cloud of 2,097,152 left them room: the 30,000 steps took 48 minutes on
Node, and the held-out PSNR at 4946 by 3286 was 23.76, which the paper,
training at a quarter of that width, has no number to set beside. Until about step 9,000 a step waits on the
program’s thread, where each photograph’s bytes arrive and its texels are
read, and takes about 90 ms; after that it waits on the device.
Path Tracing Theory Primer
This primer gives a high-level overview of the physical and mathematical principles behind path tracing, derived from the Rendering Equation. It was written for the compute-shader path tracer of resin, and describes the lighting the path tracer here computes.
1. The Rendering Equation
At its core, physically based rendering solves Kajiya’s Rendering Equation. For a point $p$ on a surface, the outgoing radiance $L_o$ in a direction $\omega_o$ is the sum of emitted light and reflected light:
$$ L_o(p, \omega_o) = L_e(p, \omega_o) + \int_{\Omega} f_r(p, \omega_i, \omega_o) L_i(p, \omega_i) (\omega_i \cdot n) d\omega_i $$
Where:
- $L_e$: Emitted light (if the object glows).
- $\int_{\Omega}$: Integral over the hemisphere of all incoming light directions.
- $f_r$: The BRDF (Bidirectional Reflectance Distribution Function).
- $L_i$: Incoming radiance from direction $\omega_i$.
- $(\omega_i \cdot n)$: The cosine law (Lambert’s law), attenuating light based on the angle of incidence.
2. The BRDF ($f_r$)
The BRDF defines how a material reflects light. In modern PBR (Physically Based Rendering), the Cook-Torrance microfacet model is the standard. It splits into diffuse and specular terms:
$$ f_r = k_d f_{lambert} + k_s f_{microfacet} $$
Diffuse Term ($f_{lambert}$)
Models light that enters the surface, scatters internally, and exits in a random direction. $$ f_{lambert} = \frac{c}{\pi} $$ Where $c$ is the albedo color. The $\frac{1}{\pi}$ ensures energy conservation when integrating over the hemisphere.
Specular Term ($f_{microfacet}$)
Models the surface as millions of microscopic mirrors. $$ f_{specular} = \frac{D(h) F(v, h) G(l, v, h)}{4 (\omega_i \cdot n) (\omega_o \cdot n)} $$
This is composed of three statistical functions:
- D (Normal Distribution Function): Fraction of microfacets aligned to reflect light from $\omega_i$ to $\omega_o$. (e.g., GGX/Trowbridge-Reitz).
- F (Fresnel Equation): Fraction of light that reflects vs. refracts/absorbs based on view angle. (e.g., Schlick’s Approximation).
- G (Geometry Function): Fraction of microfacets not blocked (shadowed/masked) by others. (e.g., Smith-GGX).
3. The Monte Carlo Estimator
The integration $\int_{\Omega}$ is impossible to solve analytically for complex scenes. Path tracing approximates it using Monte Carlo integration:
$$ L_o \approx \frac{1}{N} \sum_{k=1}^{N} \frac{f_r(\omega_i, \omega_o) L_i(\omega_i) (\omega_i \cdot n)}{p(\omega_i)} $$
- $N$: Number of samples (rays).
- $p(\omega_i)$: The Probability Density Function (PDF)—the likelihood of choosing a specific random direction.
To reduce variance (noise), we use Importance Sampling, choosing directions where light is likely to come from (e.g., towards the sun) or where the BRDF is strong (e.g., the specular reflection angle).
The term commonly tracked in a path tracer’s “throughput” is the weight: $$ \text{Throughput} = \frac{f_r(\omega_i, \omega_o) (\omega_i \cdot n)}{p(\omega_i)} $$
When the PDF $p(\omega_i)$ is perfectly matched to the BRDF geometry (e.g., Cosine-weighted sampling for diffuse), terms cancel out effectively: $$ \text{Diffuse Weight} = \frac{(\frac{c}{\pi}) (\omega_i \cdot n)}{\frac{\omega_i \cdot n}{\pi}} = c $$
4. Q&A: From First Principles
Q: Why is the integral a simple multiplication? Why not a more complex function?
The integral form $\int f_r \cdot L_i \cdot (n \cdot \omega_i)$ relies on two key physical assumptions:
- Linearity (Superposition): Light does not interact with other light. The result of two light sources is simply the sum of them individually. This allows us to use an integral (a continuous sum).
- Locality: The strict definition of a BRDF assumes light enters and exits at the exact same point ($x_i = x_o$).
- For metals, this is true (reflection is immediate).
- For dielectrics (plastic/paint), light penetrates but exits so close to the entry point that it appears local.
- Note: Materials where this fails (skin, wax) require a BSSRDF (Subsurface Scattering), which integrates over an area, not just a hemisphere.
Q: Why split materials into Lambertian + Specular?
This split models the two distinct paths a photon takes when hitting a dielectric interface:
- Path A (Specular): The photon hits the surface boundary and reflects immediately due to Fresnel forces. It interacts only with the surface, not the pigments inside.
- Path B (Diffuse): The photon enters the material (refracts), hits pigment particles, scatters chaotically, and exits in a random direction. The “Russian Roulette” logic in path tracing (choosing to bounce diffusely OR specularly) explicitly models this bifurcation.
Q: Why do we multiply by $(\omega_i \cdot n)$ but then divide by it in the Specular BRDF?
- The Multiplier $(\omega_i \cdot n)$: This is the Cosine Law. It effectively spreads the light energy over a larger area when hitting a surface at a glancing angle. A tilted surface physically intercepts fewer photons.
- The Denominator: The Microfacet BRDF contains a division by $4 (\omega_i \cdot n) (\omega_o \cdot n)$. This is a Jacobian correction factor. It converts the distribution of microfacets (which don’t care about the macro-surface normal) into the macroscopic reflection ratio.
- The Result: For specular reflections, the two terms cancel out. This physically means a mirror doesn’t get darker at grazing angles; it simply reflects a larger slice of the environment. For diffuse surfaces, the denominator doesn’t exist, so the cosine law applies, and the surface darkens as it turns away from the light.
Q: Is the Geometry (G) term actually important?
Yes, it is critical for energy conservation. Without $G$, the specular term would divide by zero near grazing angles ($(\omega_i \cdot n) \approx 0$), causing edges to glow infinitely bright. $G$ represents micro-shadowing and masking—at grazing angles, surface bumps block most light, mathematically cancelling the singularity and keeping the result finite.
Q: Why does Fresnel’s Equation make sense physically?
Why do surfaces become mirrors at grazing angles?
- Physics: When a light wave hits a surface head-on, it “sees” the empty space between atoms and enters (refracts).
- Grazing Angle: The surface appears compressed to the incoming wave. Atoms appear stacked impenetrably tight, presenting a “wall” of electrons. The wave cannot penetrate and is forced to bounce off (reflect). This is why even matte objects (asphalt, Toast) exhibit specular reflections at extreme grazing angles.
The path tracer
(snail shell graphics trace render) path traces a glTF scene into the
canvas a frame at a time. SVGF filters the light before tone mapping.
It is composed of graphics middleware, each a library usable
on its own: a BVH and its ray queries, an environment light, a denoiser.
The primer gives the physics; this chapter gives the
program. src/apps/viewer flies through the user’s own scenes with it, or
through Khronos’s glTF sample models: open the viewer.
A frame
| Stage | Library | What it does |
|---|---|---|
| Surfaces | trace/surface.wgsl.scm | Rasterizes the first hits into a G-buffer: shading normal, albedo, material, motion, the triangle drawn, and depth. A scene with blended materials also gets the nearest blended surface in front of them, in a second G-buffer, the blended layer. |
| Direct light | restir, trace/restir.wgsl.scm | Resamples sky directions and points on emissive triangles at each first hit, with candidates from this pixel, the previous frame and a neighbor. |
| Paths | trace/path.wgsl.scm, bvh | A wavefront of compute kernels, each bounce’s rays traced by the BVH’s queries, for each layer. |
| Filter | svgf | Temporal accumulation, variance, five à-trous levels, then remodulation by albedo and exposure, for each layer. |
| Compose | trace/compose.wgsl.scm | Blends the blended layer’s light over the first hits’, by its alpha. |
| Display | upscale, passes | Reconstruct on the stable display grid, then tone map, encode sRGB and apply FXAA. |
resize-tracer sets the internal render grid. Every draw traces every internal
pixel. Pass the dimensions of the output view and the number of paths per
pixel to the same entry point at every render scale.
(draw-traced gpu tracer canvas camera spread exposure bounces moved
(new TraceSettings (display-width width) (display-height height) (samples 1)))
Choose one or two paths per pixel and one to eight bounces. Report geometry
or lighting motion with moved. The tracer compares the unjittered cameras
to detect camera motion. tracer-frames counts still frames since the
last movement or history reset.
A Tracer holds a record for each lifetime: a Kit of what is made once,
the pipelines and uniforms; a World of the scene, its BVH and the
environment; Targets of what the canvas’s size sets; and Bindings,
every bind group over the three, which bind alone makes. resize-tracer
and retrace each replace one record and bind again, so no bind group
names a target or a scene that is gone. The libraries share the few steps
every set of compute kernels repeats, in (snail shell graphics kernel).
Temporal reconstruction
Each frame offsets the camera by the next point of a Halton sequence in bases 2 and 3. The sequence starts at index one, with half a pixel subtracted from each coordinate. The first two offsets are (0, −1/6) and (−1/4, 1/6) in internal pixels. Both paths at two spp share that first hit, trace separate light and BSDF draws, and contribute to a mean before SVGF. Both update visibility. Only the first carries a reservoir into the next frame. Halton sampling in Physically Based Rendering
The per-layer radiance buffer holds summed RGB with the observation count
in alpha. read-traced-radiance returns these accumulator bytes. gather
divides RGB by the requested path count when writing the noisy texture for SVGF.
SVGF uses the motion between the two jittered G-buffers to find past observations of the same surface. The display resolve runs at native size as well as at larger output sizes. In a stationary view it averages linear HDR at each display pixel. Its history grows to 16 frames, after which each new observation has weight 1/16. At a silhouette, samples can legitimately see different surfaces within that pixel. During motion, the resolve removes the change in jitter from the G-buffer motion vector. Each of its four display-history taps must match the triangle and previous projected depth. Moving sky and blended surfaces use current samples. Tone mapping and FXAA run at the output size.
Camera or reported scene motion limits temporal ReSTIR to two batches of
old candidates, or one above 1.5 pixels of motion. Moving SVGF keeps up
to four observations and gives the current one at least 40% weight.
Use discard-trace-history for a camera cut. A changed sky, scene, bounce
depth or render grid starts fresh history. Changing only the display
size or exposure starts a new display history and preserves render-grid
history.
The wavefront
A path is not one long kernel but a sequence of small ones, each its own pipeline, so each stays simple and keeps its registers few:
temporal_reservoirs → primary → [occlude → connect → intersect → shade] × bounces → gather
temporal_reservoirsdraws fresh light candidates and merges reprojected history.primaryplaces the first hit on its triangle, merges a neighbor’s reservoir, emits the selected shadow ray and scatters the BSDF ray.shadesamples the surface’s BSDF for the next bounce and direct lighting for a shadow ray, appending each to its queue.occludeandintersectare the BVH’s queries over a queue.connectadds the selected light’s weighted contribution when the shadow segment is clear. It records the outcome of the first hit’s shadow test in the owning layer’s history.gatherwrites each pixel’s radiance for SVGF.
Two ray queues alternate between bounces, with one shadow queue. Each holds
80-byte Ray records (origin and limit, direction and random seed, the hit,
the throughput and the scatter density), one record so the kernels stay
under WebGPU’s default eight storage buffers a stage. Rays append with an
atomic count kept per bounce, 256 bytes apart. Russian roulette may end a
path after its third bounce.
A queue kernel is dispatched over the maximum number of paths for this draw. Each layer dispatches one lane per internal pixel. Threads past the actual queue count return at once. Chromium validates each indirect dispatch, which takes about half a millisecond of wall time, more than the wasted threads cost.
The counts and each bounce’s bind groups are made for most-bounces, and
the wave’s uniform is written each frame, so a frame of fewer bounces marks
an earlier one the last and runs only that many.
First hits
A ray leaves a surface lifted off it by 1/10,000 of its coordinates’ size,
toward the side it goes, so it does not meet the surface again. Depth alone
places a first hit less well than that far from the eye: the projection’s
near plane is 0.1 units away, and 30 units out Sponza’s outer wall came back
a millimetre in front of or behind itself. Rays from behind it met the wall
and darkened it in bands that moved with the camera. So the surface pass
draws three corners a triangle, reading each corner’s vertex through the
scene’s indices, and writes the triangle it drew; primary moves the
depth’s point onto that triangle’s plane and takes the triangle’s normal,
facing the eye, as the geometric one. The G-buffer keeps only the shading
normal, so it is no larger for the triangle.
Biased ReSTIR direct lighting
Each path draws four fresh candidates at its first hit. When both the sky and mesh emit, each candidate has equal odds of coming from either family. A single emitting family gets all the draws. The sky sampler chooses a direction from its importance table and solar disc. The mesh sampler chooses a triangle in proportion to its initial world-space area times its emitted luminance, then a uniform point on it. Opaque triangles with constant emission are eligible. Textured, masked and blended emitters still contribute when a path hits them.
Consider a patch of area dA on a triangle of current area A. If the
sampler chooses that triangle with probability p including the family
choice, the chance of landing in the patch is p × dA / A. The area
density is therefore q = p / A. In the shader the sampling domain is the
triangle with unit mass, so q = p and the RGB integrand contains
J = A × abs(cos at the light) / distance². This puts it in the same
units as the proposal and preserves the point when the light moves or
changes area. The sky uses solid angle directly.
The scalar target t is the luminance of the unshadowed RGB contribution
times the receiver’s estimate of visibility. The RGB includes emitted
radiance, the receiver’s BSDF and cosine, the change of measure above, and
the power-heuristic weight for light sampling. A BSDF ray that hits the
emitter or escapes to the sky supplies
the complementary weight. A camera looking directly at the sign sees its
full emitted radiance.
A reservoir holds the selected direction and its target, a weight sum S,
a count M, and the identity and coordinates of a selected emitter. A
fresh draw with proposal density q contributes t / q
to the sum. Zero-weight draws still count. A draw of weight w replaces
the selection with probability w / S after the addition. The selected
sample’s multiplier is W = (S / M) / t, or zero for an empty selection.
The proposal and the replacement draw answer different questions. A light
arrives at rate q, so giving each arrival weight t / q makes its expected
weight proportional to t. After seeing the stream, candidate i has
selection probability w_i / S. Every later replacement multiplied its
survival odds by the old sum divided by the new sum. Those factors telescope.
With equal weights the next candidate replaces the previous selection with
probability 1 / M, the ordinary unknown-length reservoir rule.
The motion vector locates one previous pixel. Its normal must agree with
the current normal (dot product at least 0.9), and the two depths must
agree within 2% in the previous camera’s projection. The surface pass projects the previous pose of the same triangle and carries its clip-space depth in the emission target’s alpha channel. Both ReSTIR and SVGF check the temporal donor’s triangle identity and compare against that depth when geometry moves. The donor represents
up to 20 times the number of fresh candidates at the receiver. The spatial
step chooses one of the four axial neighbors. Each donor belongs to the
completed temporal pass and uses the same surface test in the current
projection. Each accepted donor contributes its represented count m and
weight target_here × W_donor × m. The biased estimator
divides by the total represented count even when a sample could have
contributed at only some of those surfaces. This can lose energy at surface
boundaries. Bitterli et al., 2020
Only the final direction needs a visibility test. Its shadow ray carries the receiving surface’s RGB contribution with its sampling correction into the BVH query. Each layer owns its final history and both take turns using one temporal scratch buffer. A sky or uncovered pixel writes empty history. A sky bake increments the environment revision. The next draw starts every pixel with fresh proposals. A direction on last minute’s dim sky can now fall inside the bright solar disc, so its old selection weight belongs to a different proposal distribution. Resizing or replacing the scene or environment also starts a new history.
upload-lit-scene takes finite-range punctual lights and capacity for moving ones. A ground-plane grid lists static lights whose influence overlaps each cell. Vehicles update a short list of moving lights with update-moving-lights!. The punctual lights compete with the weighted sky or mesh estimate for one shadow ray. A finite ray runs from the offset receiver to the selected light. Later bounces use one fresh sky or mesh candidate and the same visibility step. Emissive storefront strips illuminate the shop and pavement from their actual triangles.
The GPU regression lights a white wall with a two-triangle rectangle against a black sky. Numerical integration at its center gives 0.3000 linear radiance. Across its 9×9 near-constant wall patch, direct sampling measured 0.2981 over 12 frames and BSDF-only sampling measured 0.2980 over 24. Raw sample variances were 0.0369 and 0.2151 respectively. Moving the blocker behind the sign preserves the light. Moving it between the wall and sign extinguishes it. A separate pose test moves the sign across a stationary receiver while reusing its reservoir.
Learning which lights reach a surface
Each first hit remembers the two distinct sources its shadow rays most recently tested. A new source starts with a visibility estimate of ½. A shadow observation moves the estimate toward one for a clear ray or zero for a blocked ray. A source can be one emissive triangle, a punctual light, the analytic solar disc, or one of six sky regions. Points on a partly covered triangle can give different answers.
The estimate scales the target for fresh candidates, reused candidates at the receiver, and the final choice among punctual lights and the ReSTIR sample. Each selection divides out its own priority when weighting the RGB. An interior surface can therefore spend more rays on a dim lamp it can see. A fresh shadow test on the winning direction determines its contribution.
A fraction of shaded first hits scores its candidates by unshadowed energy to explore. Both kinds of selection update the receiver from the ray they actually traced. A surface that fails reprojection starts with empty visibility history. A spatial neighbor can suggest a light sample, while visibility estimates always belong to the receiver. Independent reference samples use neutral priorities.
Set the minimum exploration fraction and the recovery target in displayed frames on the tracer. This example asks for at least one exploratory path in eight and a 12-frame response (0.4 seconds at 30 fps).
(Tracer-guiding-set tracer
(new LightGuiding (exploration-floor 0.125) (recovery-frames 12)))
Recovery means closing 90% of the expected gap from the old visibility to
the new one for a retained light that wins every probe. Let N be the
number of shadow opportunities per receiver in the requested frames.
With T displayed frames and s paths per pixel, N = T × s.
The per-opportunity response is r = 1 − 0.1^(1/N). The actual probe
probability is p = max(exploration-floor, r), and each observation
uses gain a = r/p. With probes alone the expected remaining gap after
N opportunities is (1 − p a)^N = 0.1. A higher exploration floor
buys more frequent probes with smaller updates. A shorter target can raise
exploration so that one clear observation suffices.
For a fully uncovered light that wins a fraction s of probes, the chance
of at least one rediscovery is 1 − (1 − p s)^N under constant independent
odds. Its expected residual visibility error from probes alone scales as
(1 − p s a)^N. Guided wins also teach the receiver. Actual reservoir
selection depends on the light’s energy relative to the other candidates.
Rare proposals, partial occlusion and eviction can extend the wait.
The same response rate sets a positive visibility floor min(½, r) for
candidate weighting. Temporal donor count is capped at (1 − r)/r times
the fresh count, using one reservoir write per frame at either sample count. Thus fresh proposals account for at least r of
the represented temporal stream. The existing caps of 20, or less while
driving, can shorten this memory. The default is a ⅛ exploration floor
and a 48-frame recovery target.
In the 9×9 indoor regression a screen blocks a bright patch of sky and a weaker lamp lights the wall. Each receiver casts one shadow ray per frame. Energy-only selection with reservoir reuse sends 75% of those rays toward the blocked sky and gives raw red-channel variance of 0.0156. With a ⅛ exploration floor, shortening the recovery target spends more rays on the blocked sky and finds the opening sooner.
| Recovery target | Sky rays while blocked¹ | Raw variance while blocked | Sky rays in first 4 open frames | Sky rays in next 12 | Mean radiance in those 12 |
|---|---|---|---|---|---|
| 48 frames | 38% | 0.00460 | 47% | 75% | 0.2856 |
| 12 frames | 46% | 0.00580 | 60% | 77% | 0.2876 |
¹ Measured over 12 frames after 20 warm-up frames. The open-room reference averaged 32 independent samples per pixel and gave 0.2886.
The blended layer
A glTF material is opaque, masked or blended. The first hits’ G-buffer
holds only opaque and masked surfaces, and a masked one is discarded below
its cutoff. A scene with a blended material, whose Scene says
blended, gets a second G-buffer of the same targets, the blended layer.
Every triangle is drawn again over a copy of the first hits’ depth, so
the depth test keeps the nearest blended surface in front of them, with
its alpha in the albedo’s. A texel whose alpha is under 1/255 is no
surface and hides nothing.
The layer is lit as the first hits are:
- Paths. Its paths run as a second wavefront after theirs, over the same queues once the counts are cleared. Its radiance comes after theirs in the same buffer, so the bounces need no change, and a pixel the layer does not cover makes no path.
- Filtering. It is gathered into its own noisy plane and filtered by its own SVGF, with its own normals, depth and motion. So each layer’s history follows its own surface, where a stipple of the two would mix them.
- Composing. A triangle over the screen then blends the layer’s light over the first hits’, in the light target, through the target’s blend state: α·T + (1 − α)·O, before tone mapping.
Only the nearest blended surface is in the layer: a blended surface behind another one is not seen through it. Rays treat blended surfaces as cutouts, passing through with the odds of their alpha, so shadows and reflections see them in part.
A scene without a blended material makes none of the layer’s targets,
bind groups or filters. retrace remakes the targets when a new scene
changes that. On an RTX 5090 at 1280 by 657, AlphaBlendModeTest took 3.3
to 5.4 ms a frame, the same as before the layer within the timing’s noise.
The BVH and ray queries
(snail shell graphics bvh) builds a linear BVH on the device in one
compute pass: Morton codes of the triangles’ centroids, a bitonic sort of
them, Karras’s tree over the sorted codes, and boxes refit from the leaves
up. It takes any triangles: a positions buffer read
as 32-bit words at a stride and an offset, and an index buffer. Each node
holds both its children’s boxes, and a child pointer with the high bit set
names a triangle. Traversal visits the nearer child first, with a 64-entry
stack and a cap of 8192 steps.
make-ray-kernels builds intersect (the nearest hit) and occlude (any
hit) for a caller’s cutout(triangle, barycentric, seed), the WGSL that
says whether a hit counts; the tracer’s discards alpha-masked texels.
trace-rays runs a query over a queue.
Environment light
(snail shell graphics environment) makes an Environment from a Radiance
HDR file, decoded on the device a row a thread and averaged down to at most
4096 texels wide, or from a drawn Sky with a sun. Either way it then
builds a table that samples directions in proportion to their light: each
row’s cumulative distribution, weighted by sin θ for the solid angle it
spans, and the rows’ distribution in the last column.
environment-light.wgsl.scm gives kernels the radiance of a direction, the
density it is sampled with, and a sampled direction.
For an art-directed sky, make-sky-light and update-sky! take a Sky. For outdoor light, make-atmosphere-light and update-atmosphere! take an Atmosphere with a sun direction, horizontal wind displacement in kilometres, and cloud cover from zero to one. Each update refreshes the same GPU resources and their sampling distribution. Release them with release-sky-light.
The outdoor sky integrates molecular and aerosol scattering along a ray through a spherical atmosphere. Slant paths through the air and ozone change the colour of the setting sun. A diffuse term approximates higher orders of scattering. A second ray march integrates extinction and in-scattering through a marine cloud layer from 650 to 1,850 metres. Short marches toward the sun give the banks self-shadowing. Overhead density governs how much skylight reaches their undersides. The directional environment represents the view from street level. Buildings share the cloud cover above that reference point. Atmospheric transport and spherical geometry · Real-time volumetric clouds
The sky texture contains scattered radiance. Two additional texels hold the solar disc’s direction, angular radius and cloud-attenuated irradiance. The sampler chooses between the sky and the disc by their integrated luminance, then samples solid angle inside the chosen region. This keeps the sun round at its apparent diameter of 0.53° even in a small environment map. Camera rays, water reflections and shadow rays see the same light. The outdoor environment also adds distance haze to long camera sightlines. A PinholeRange lens takes the vertical field of view in radians and the near and far clip distances in world units.
Scenes
(snail shell graphics gltf) reads a scene’s file, a .gltf file’s JSON
or a .glb file, into the meshes, materials, images and buffers it names.
Each buffer and image has a Source: a file named by a URI relative to
the scene’s, bytes the scene holds (a base64 data: URI or a .glb
file’s binary chunk), or for an image a range of a buffer. A buffer also
has the length the scene reads of it and where it starts once the buffers
are laid end to end, which is where the device gets it.
load-scene of (snail shell graphics trace scene) takes a function that
reads several paths at once, so a page fetches every buffer and image
together (fetch-all-bytes).
Only the files the sources name are read; the rest come with the scene’s
file. It unpacks the buffers on the device into one vertex and one index buffer,
draws each image into a layer of one array texture with its mipmaps, and
scales a scene less than a unit across up to one.
Moving geometry
A moving cast uses the same surface, path, SVGF and post passes as a static scene.
A MovingScene owns a static prefix of world vertices and one contiguous range
of local vertices per moving object or skinned mesh. pose-scene! writes the posed vertices
and their displacement from the previous draw. The surface pass uses that
displacement for motion vectors and the expected previous depth. SVGF stores the current clip-space depth and octahedral normal for validation on the next frame. During motion each new observation receives at least 40% of the accumulated illumination weight. Both primary visibility and secondary rays
consume the same world-space triangles. Mesh topology and materials stay fixed.
make-moving-tracer keeps the leaf order and binary tree for those triangles.
After a simulation tick, refit-tracer! refreshes the leaf boxes, propagates
their bounds and packs them into the original query buffer. Bindings survive
a refit. An application can choose a tone curve at construction with make-graded-moving-tracer.
Photographic gives highlights a hue-preserving shoulder followed by sRGB encoding.
The viewer can discard build scratch for static scenes. The final FXAA pass samples
normalized screen coordinates so a small traced image fills a larger browser canvas.
Skinned animation
Start with a mesh and one joint. A vertex fully weighted to that joint follows its matrix. Add a hinge and let a vertex share two joints. Its position becomes a weighted sum of the two transformed bind positions. A character uses the same operation with up to four influences per vertex.
- Call
read-rigged-gltfin(snail shell graphics gltf animation). It reads the buffers once and returns the mesh, its per-vertex influences, a parent-first hierarchy, inverse binds and named clips. A primitive with a skin starts in mesh coordinates. A rigid attachment gets a slot for its own node. Multiple skins can order their joints differently. - Use
sample-posein(snail shell graphics animation)at the desired clip time. Untargeted local transforms keep their authored values. STEP holds a key until the next key. LINEAR interpolates translations and scales and takes the shortest quaternion arc for rotations.clip-timewraps or clamps a clock.blend-posescrossfades local poses andblend-branchrestricts a blend to chosen nodes. - Call
joint-palettewith the pose and the instance placement. It walks the hierarchy, including non-joint ancestors, and multiplies each joint’s world matrix by its inverse bind. For a prop attached to a hand, resolve its index withnamed-node, callposed-nodesonce, and compose the prop with that node’s world matrix. Pass the same array toskin-palettefor deforming the mesh. A joint’s inverse bind belongs only in the skin palette. Instances share the rig and clips and sample their own poses. - Give
skin-scenethe fixed topology and vertex influences once. At each draw,deform-scene!blends the palette matrices on the GPU, transforms positions, normals and tangents, and records the displacement back to the preceding draw. Refit the BVH after a pose changes. Camera visibility and Monte Carlo shadow queries then use the same triangles. SVGF receives their motion vectors and FXAA runs after tone mapping.
The reader supports floating-point transform keys, unsigned byte or unsigned short joint indices, and floating-point or normalized unsigned integer weights. It reports unsupported cubic samplers, morph-weight channels, sparse accessors and additional vertex influence sets. The mechanical hinge fixture in tests/programs/data/hinge.gltf has a non-joint ancestor, reversed node order and mixed weights. glTF skins and animations
Render a still
The Node host can render a PNG directly from a local glTF or GLB with the same WebGPU tracer. Run from the repository root.
./snail-scheme run --target node tools/render.scm scene=scene.glb output=preview.png width=1280 height=720 samples=64 bounces=4
./snail-scheme run --target node tools/render.scm scene=tests/programs/data/crew.glb minute=1040 output=portrait.png
A model resolves buffers and images relative to its file and is framed from its bounds. Supply both eye and target to choose a camera in scene coordinates. minute is local solar time in minutes after midnight. layers sets the square texture-layer size for sampled materials.
(snail shell graphics still) renders a fixed camera into an offscreen texture and returns the updated tracer and tightly packed RGBA bytes. It traces every pixel on every sample, with up to 4,096 observations and eight bounces. Image dimensions must fit the device’s ray-buffer limit. Offline frames use the stationary SVGF history.
Capture reconstruction inputs and a reference
Supply a capture prefix to save a cold, full-resolution 1 spp input and an independent high-sample reference at the same camera pose. This example runs from the repository root and frames the model from its bounds.
./snail-scheme run --target node tools/render.scm scene=tests/programs/data/crew.glb minute=1040 \
width=240 height=135 bounces=2 samples=128 capture=gallery
gallery.noisy.rgba32f and gallery.reference.rgba32f contain row-major,
little-endian float32 RGB radiance and a coverage marker. The reference
averages fresh observations on the GPU using a disjoint seed range with
temporal and spatial reuse disabled. Both images precede SVGF, exposure and
tone mapping. Each file holds all opaque pixels first, followed by the
blended layer when present. The blended layer’s albedo alpha gives its
compositing weight. The JSON file records dimensions, layer order, seeds,
sample count and bounce depth.
The matching .opaque.* and .blended.* files contain the native,
tightly packed G-buffer planes. Their names give the channel formats.
They carry octahedral normals, emission and previous clip depth, sRGB
albedo with linear alpha, material factors, UV motion, triangle IDs
and hardware depth. The .camera file contains the actual jittered Camera3D Pod bytes. The reference uses that same subpixel position for every independent lighting observation.
The viewer
./snail-scheme build --target browser src/apps/viewer/main.scm
The viewer ships no scene. It shows the files its user chooses: a .glb,
or a .gltf with the files it names, and an .hdr file to light it;
without one, a drawn sky and sun light it. Files come dropped on the page,
a folder at a time or several files, or through the browser’s pickers, O
for files and Shift+O for a folder, which the File System Access API’s
showDirectoryPicker opens where the browser has it. (snail shell files)
is that capability, FilePicker: open-picker asks the user and returns, a FilesEvent
says files were dropped or picked, and each file the user chose is its
path within the choice and an address that fetch reads, a blob: one
for a file of theirs. retrace keeps the tracer’s pipelines for the new
scene, and the old scene and light are destroyed. Drag to look, WASD to
fly, Q and E down and up, the wheel for speed, [ and ] for exposure.
Keys also set what a frame costs: 1 to 8 how many times its paths bounce,
four at first, and - and = halve and double the pixels traced, each
side by the square root of two, down to an eighth of each side. The page
says the settings as they change and keeps them in its save for the next
visit. Inside Sponza on an RTX 5090 at 2000 by 1217, four bounces at full
resolution took 18.9 ms a frame, and two at 50% resolution 5.3 ms.
A link dropped on the page is a file too, one whose path is its address,
and a scene chosen by address names its files relative to it, so the
browser fetches them from where the scene is published
(fetch-all-bytes, every file of a scene together). The page’s samples
are such links: Khronos’s sample models, at a pinned commit of
glTF-Sample-Assets,
and four of Poly Haven’s environments.
Clicking one drops it on the page. So the site publishes none of them,
and a model’s license is its publisher’s to state. The page’s query
chooses the same way: ?model=ADDRESS&env=ADDRESS, each an address
fetch reads, such as a path on the page’s server, and
&eye=x,y,z,yaw,pitch for the camera. The viewer starts with one path per internal pixel.
Use ?spp=2, or append &spp=2 to an existing query, for two paths.
Files that cannot be shown leave the view as it was, and the page says why:
a .gltf chosen without the files it names, an address that answers 404, a
file shorter than the scene says, an image the browser does not decode, a
scene whose geometry is compressed by Draco or meshopt, an HDR file that
is not one. Reading a
scene stops through a prompt of (snail shell graphics gltf): unreadable
stops it with a reason, anywhere from the JSON to the last image, and
attempt-reading turns the reading into a Result. Nothing refused is
left on the device, by the order of the work rather than by cleaning up:
the viewer reads the HDR file (read-hdr) before it loads the scene, and
load-scene loads the layers, the one step on the device that can refuse,
before anything else of the scene.
Water surfaces
A glTF material can opt into the tracer’s water shading with "extras": { "snailWater": true }. Use a nonmetallic material and a dark linear base colour for light returned by the water body. The dielectric interface reflects about 2% of the light at normal incidence and approaches full reflection at grazing angles. A ray can reflect geometry as well as the sky.
Set Camera3D.scene-time in seconds to move wave trains in world metres. Rasterized first hits and traced secondary hits share their normals. Each wave is filtered along its direction across the pixel footprint. Unresolved waves contribute their slope variance to the material roughness. The mapped surface supplies depth, visibility and ray origins. The model represents deep water with a fixed shoreline and a bulk colour.
Performance
On a matte white wall under a uniform environment, first-hit ReSTIR reduced the variance of unfiltered radiance from 0.0864 to 0.0491. Mean radiance was 0.984 before and 0.983 after. This measured 256 one-bounce frames after 16 warm-up frames, over the center 32 by 32 pixels of a 96 by 96 image.
On an RTX 5090 through Dawn, a 768 by 512 scene with two boxes on a ground
plane took 0.264 ms for the four-bounce wavefront before ReSTIR, 0.390 ms
with full-rate ReSTIR and 0.263 ms with the still-frame checkerboard.
These are median GPU pass times over 405 frames per mode, after 15 warm-up
frames in each of three runs, before visibility guiding. The current
SurfaceReservoir occupies 64 bytes, including 16 for visibility history.
Fewer path samples
The following historical comparison includes the retired checkerboard schedule.
The two boxes on a ground plane were lit by a sky with a sun and rendered at 384 by 256 from empty history, with four bounces. The reference averaged 4,096 unfiltered samples from the original tracer using a separate range of random seeds. Error is linear RGB root-mean-square error (RMSE) on the 54,781 surface pixels across 32 cold starts. Each unfiltered average counts newly traced paths. The SVGF column measures the filtered light before tone mapping.
| Tracer | Frames | Path spp | Raw RMSE | SVGF RMSE | GPU time to image |
|---|---|---|---|---|---|
| Original | 8 | 8 | 0.1811 | 0.02085 | 2.312 ms |
| ReSTIR, full rate | 2 | 2 | 0.1601 | 0.01580 | 0.846 ms |
| ReSTIR, checkerboard | 3 | 2 | 0.1620 | 0.01629 | 1.094 ms |
| ReSTIR, checkerboard | 8 | 4.5 average | 0.1138 | 0.01662 | 2.401 ms |
GPU time sums the six pass durations from the G-buffer through FXAA over the indicated frames. The table gives the median of 93 cold starts on the RTX 5090 through Dawn, excluding scene setup. At 768 by 512, the median GPU pass time per still frame was 0.420 ms for the original tracer, 0.547 ms for full-rate ReSTIR and 0.422 ms for the checkerboard across 405 frames per mode.
On the uniform white wall at 384 by 256 with one bounce, the same two-spp checkerboard budget gave 0.00646 filtered RMSE. The original tracer at eight spp reached 0.00541.
A second comparison kept learned visibility enabled on both schedules, immediately before adding native-resolution jitter. At two accumulated paths per pixel, full coverage in two frames took 0.633 ms with filtered RMSE 0.01462. Alternating coverage needed three frames and 0.888 ms, with filtered RMSE 0.01526. A single warm frame on the alternating schedule took 0.286 ms versus 0.318 ms at full coverage. This used the same 384×256 scene and 54,781 surface pixels, a fresh 4,096-spp reference, 32 cold starts for error, and the median GPU time over 124 cold starts on the RTX 5090.
Subpixel jitter
At 192×128, the same two-box scene was rendered with four bounces and one path per pixel per frame. Both runs used the same seeds, SVGF and display resolve. Only the camera offsets changed. The reference averages 128 independent paths at each of 16 regularly spaced subpixel positions (2,048 spp). Error covers the entire resolved linear-HDR image over 16 cold starts, before tone mapping and FXAA.
| Frames | Fixed pixel centers, RMSE | Halton jitter, RMSE |
|---|---|---|
| 8 | 0.02268 | 0.01489 |
| 16 | 0.02233 | 0.01403 |
Browser scenes
Before first-hit ReSTIR, the following frame times were measured on an RTX 5090 through Chromium on Vulkan at 1280 by 657.
| Scene | Frame |
|---|---|
| Sponza, inside, sky | 8.7 ms |
| Sponza, inside, footprint_court | 8.9 ms |
| Sponza, from outside | 6.3 ms |
| DamagedHelmet, helipad | 3.7 ms |
| FlightHelmet, footprint_court | 3.7 ms |
| SciFiHelmet, sky | 3.2 ms |
All 151 of Khronos’s sample models with a glTF variant load and render. Fetched from GitHub by the page’s sample links, FlightHelmet was drawn 3.9 s after its link was clicked and Sponza 7.3 s.
Games
Games are complete snail-scheme applications: the rules, the scene and the HUD are
all snail-scheme, and the browser only forwards input, draws frames and stores the
save.
- Siegework: explore a seeded map, wire an energy network across it, and destroy three nests before their attacks destroy your hub. Play it.
- Hearsay: a design for a role-playing game about what a city believes, with two prototypes to play: the rumor mill and the favor ledger. Play them. Its characters are drawn from Liberated Pixel Cup art, credited on the Credits screen of its menu.
Siegework
Play Siegework in a browser with WebGPU. The game saves itself in the browser and continues where you left it.
Explore a seeded map, wire an energy network across it, and destroy three nests before their attacks destroy your hub.
Playing
- The land. Each map’s seed picks one of four biomes. Meadows have lakes and mountains; deserts have no water, only mesas and winding canyon walls; tundra has frozen lakes, mountains and scattered boulders; an archipelago is sea but for its islands. Open ground is walked and built on. Rock stops walkers, sight lines and wires until burrowers dig it out. Water stops only walkers, so wires reach islands enemies cannot. Ice is walked but not built on. Every nest has a way in to the hub, though it may wind through a pass or over a causeway.
- Energy. The colony runs on one store of energy, starting at 160. Extractors draw it from violet crystals until they run dry: the starter, four cells from the hub in a direction the seed picks, yields 2 a second, richer crystals more, and each extractor level multiplies its yield. A destroyed nest exposes a rich crystal of its own.
- The network. Every finished building is wired to every other within reach whose line to it crosses no rock (water is fine). The hub reaches 9 cells, pylons 7, 10 and 12 by level, turrets 6 and extractors 4. A building the hub cannot reach through wires is unpowered and does nothing: no energy, no shots, no sight. Rebuild the link and it wakes up.
- Building takes time. A new building needs visible open ground and a powered building that can wire to it. Its cost is paid at once and it is built while it holds one of the hub’s build slots: pylons take 2 s, extractors 3 s and turrets 4 s, and the colony’s first extractor is ready at once. Nothing happens until it is ordered: the crystals in sight pulse white under a title banner that points to them and links to this guide; the camera opens on the starter crystal. Once a crystal is selected, the banner points to the build button, which pulses. The hub starts with one slot; upgrading it adds a second and a third. Further orders wait in the queue, and an unpowered site waits without blocking the others.
- Rush. Rushing finishes work at once for four times the share of its cost that remains: five times the price when rushed as it is ordered, less later. Cancelling refunds the cost.
- Upgrades, repair and scavenging. Each building has three levels. Upgrades raise pylon reach, extractor yield, and turret damage (one and a half, then two times, with a gun more each level), and restore full health. Repair restores the hub to full health at one energy for each two health it lacks. Scavenging returns a fifth of what a building cost.
- The siege. The first attack leaves the nests at 0:45, then one every 30 seconds; raids aimed at exposed outposts replace every other attack from 1:45, and a boss leads an attack every nine minutes. Enemies grow stronger every 90 seconds, less for each nest destroyed, and some burrow through rock. Turrets shoot the nearest enemy in sight and range, harder up close, and their guns stay where they last fired. A wounded enemy turns on the first turret that hit it and hunts that one until it falls, whatever else shoots it; a raider then goes back to its outpost.
- Winning. Destroy all three nests to win. Lose the hub and you lose.
Controls
The same controls work with a mouse, a pen and fingers. Drag to pan, pinch or use the wheel to zoom, and tap a cell to select it; the selection alone never orders anything. The dock on the side of your hand shows hub health, energy and the nests’ strength with the time to the next attack, then the build menu for the selected cell: a pylon, a turret, an extractor, an upgrade, a rush and closing. A button that may work later, waiting on energy, work, the network or the first extractor, turns flat blue with faint lines; one that cannot apply to the selection fades. Rush finishes the selected work, or else makes new buildings rushed. A selected building or hub adds cancelling its work and scavenging it, or at the hub repair. Beside it come the menu and turning buttons and the build queue, with a ring while a work builds and ! while it is unpowered; tap one to go to it. Under the nests in the opposite corner, a red alert throbs while the colony is under attack and goes to the latest attack, and a notice says why an order was refused.
| Key | Action |
|---|---|
| 1, 2, 3 | Build a pylon, a turret or an extractor on the selected cell |
| 4 | Rush the selected work, or make new buildings rushed |
| 5 | Close the selection |
| U | Upgrade the selected building, or add a build slot at the hub |
| R | Rush, as 4 does |
| C, X | Cancel the selected work, scavenge the selected building |
| F | Repair the hub to full health |
| WASD, arrows | Pan |
| Q, E | Turn a quarter |
| H | Return to the hub |
| P | Open or close the menu |
| Escape | Back out of a dialog, then clear the selection |
Keys held with ⌘, Ctrl or Alt go to the browser, so its shortcuts, such as reloading, keep working. With Shift, WASD and the arrows pan as they do alone, and other keys do nothing.
The menu also restarts on a new map, resigns, and moves the dock to the left or right edge.
Saves
The colony depends only on its seed and the orders given at each tick, so the save is a journal: the seed, the tick reached and each accepted order with its tick, plus whether the game was paused and for which hand. Loading replays the journal. Under rules that have changed since it was written, an order that is now rejected is dropped and the colony grows differently; there are no save versions.
Reading the code
Siegework’s source is a tour of a complete application: seeded terrain, an energy network derived from the buildings, a siege on a fixed schedule, a world that changes only through orders and ticks, and a scene and HUD drawn from the state alone.
Terrain generation and enemy routing share the map’s breadth-first search queue. The queue holds cell indices and marks each cell when it enters. Each route keeps its own distance array, so walkers and burrowers can follow different goals across the same map.
Typed tables and cached views
Proposed API, not implemented. The application model proposes preserving server and browser data through durable typed tables and disposable views. This chapter develops that state model for review; its forms are illustrative library syntax, not runnable examples. Storage semantics, checking rules and performance need proof before replacing current save/restore. The state issue tracks that review.
One owner for retained state
All base tables are durable. A view computes a value from a consistent database
snapshot and explicit arguments; caching that value is optional. There are no
independently mutable volatile tables, application resume methods or automatic
heap migrations. A new program starts at its ordinary entry point, opens its
store, recreates platform resources and asks for the views it needs.
| Concept | Representation | Lifetime |
|---|---|---|
| Entity | Stable typed key, shared by its component tables | As long as the application retains the identity |
| Component | Ordinary record/enum stored as a table row | Committed database data |
| View | Typed computation over a snapshot and explicit arguments | Cached result may be evicted at any time |
| System/action | Ordinary computation inside a write transaction | One invocation |
| Resource | Socket, window, renderer or other ordinary runtime resource | Its owning runtime/task |
Split components by how they are used, not by a rule requiring a table for every field. Key types distinguish domains; they do not prove that an entity or component exists. Missing-row results and referential constraints remain explicit. IDs are values, not array positions or pointers.
Schema from ordinary types
(record EntityId
((value I64))
(deriving Serialize Deserialize))
(record Paragraph
((text String)
(font-size F32))
(deriving Serialize Deserialize))
(record Document
((title String)
(paragraphs (Array EntityId)))
(deriving Serialize Deserialize))
(define-store Notes
(table documents EntityId Document)
(table paragraphs EntityId Paragraph))
define-store names one database schema and generates concrete operations.
The prototype starts with lookup, insert, replace, delete and scans. It does
not compile arbitrary Scheme predicates into SQL. A server may use a concrete
SQL database and a browser may use IndexedDB behind the same record operations;
this is one storage contract with platform bindings, not a provider/plugin API.
SQL indexes and richer typed queries are separate additions.
Illustrative generated operations are written as effects, as the language
had them when this was proposed. Effect declarations have since gone
(#877): read each
effect below as a capability, a record of these operations that code is
handed (capabilities), and each handler as the
value that implements it.
(effect NotesRead
((paragraphs-ref (Fn EntityId → (Option Paragraph)))
(documents-ref (Fn EntityId → (Option Document)))))
(effect NotesWrite
((paragraphs-insert! (Fn EntityId Paragraph → Bool))
(paragraphs-replace! (Fn EntityId Paragraph → Bool))
(paragraphs-delete! (Fn EntityId → Bool))))
Insert returns false if the key exists; replace/delete return false if it is missing. Other tables receive the same operations. Ordinary helper functions can combine them. Scans have a documented stable key order or require explicit sorting before order affects a result; storage iteration order is not an input to application behavior. A durable document referring to a paragraph must check existence and enforce deletion policy in the same write transaction.
Rows are a deliberately limited data subset: scalars, text, arrays, records and
enums composed of supported data. Storage reads and writes must take independent
snapshots rather than expose shared mutable state. No procedures, resource owners,
opaque managed values or platform handles. Durable keys/rows additionally need
codecs. Serialize serves its existing purpose; it alone is not a
certificate for this complete storage contract. This does not add
a general-purpose Immutable marker.
Reads and writes have scopes, not exposed tokens
The examples use the existing (Result A E) from (snail core base), with (Ok A)
and (Err E).
The following comment-form types summarize the proposed generated API; they are
not separate implementation declarations:
;; notes-read contract (summary notation):
;; (∀ (A)
;; (Fn (Fn → A ! NotesRead)
;; → (Result A StoreError) ! store))
;; notes-write contract (summary notation):
;; (∀ (A E)
;; (Fn (Fn → (Result A E) ! NotesRead NotesWrite)
;; → (Result A (WriteError E)) ! store))
notes-read binds one consistent snapshot for the whole computation, including
nested views. notes-write binds one transaction and reads its own staged writes.
Both execute their action once; the first version has no automatic retry or
nested transactions. A conflict is a result the caller may explicitly retry.
Writes require serializable isolation, not merely snapshot isolation: checks
across several rows must not admit write skew. The backend must either serialize
writes or detect conflicts that would violate this contract.
Pure helper calls are permitted. Networking, rendering, timers and task dispatch
are absent from the action’s closed effect row. Storage operations themselves
may suspend; an unrelated application wait cannot keep a transaction open.
Returned values must satisfy the structural data restriction too. No cursor,
transaction token, mutable storage view or effectful closure escapes. Static
checking must also reject hidden captures that can mutate the transaction.
Shared mutable module values also need consideration; source borrows do not
exist. The arrows above do not, by themselves, establish those restrictions. define-view and named
action declarations are possible checking boundaries; this is a compiler gap
to settle before implementing the API.
There are no top-level defaults for NotesRead or NotesWrite. Their handlers
exist only in the appropriate scope. A test can intercept the underlying
store effect; runtime implementations own the actual synchronized storage.
A reusable, shareable handler is not itself a lock or an isolation guarantee.
The simple operation results above require a runtime-owned recoverable abort
boundary: an engine failure aborts the enclosing action and becomes its
StoreError, rather than being reported as a missing row or false result.
Ordinary value-returning effect handlers do not establish this boundary.
Implementing it is explicit runtime/compiler work; an alternative is to expose
typed storage errors on every operation. User-defined control handlers are not
required, but pure library expansion of the runner is not yet established.
An edit action might be:
(define (replace-text (id EntityId) (text String)) (→ (Result Unit EditError)) (! NotesRead NotesWrite)
(match (paragraphs-ref id)
((None) (Err (MissingParagraph id)))
((Some paragraph)
(begin
(paragraphs-replace! id (Paragraph-text-set paragraph text))
(Ok (unit))))))
;; Called from an ordinary event handler with the store effect available.
(notes-write (lambda () (replace-text paragraph-id edited-text)))
The read and replacement share a serializable transaction. This action overwrites the text; it cannot detect that a client prepared it from an older UI snapshot. To reject stale-editor writes, pass an expected row version/value and compare it inside the action. Transaction isolation alone does not supply that policy. Domain errors roll back; storage errors remain distinct. A trap also aborts unpublished work. Once commit succeeds, later cancellation cannot undo it. A lost response may leave the caller uncertain whether the operation committed; no exactly-once delivery guarantee is implied. Send a response or present UI only after the write result, outside the transaction.
Views are ordinary typed computations
Assume Layout is ordinary immutable data and typeset is a pure function:
(define-view (paragraph-layout (id EntityId) (width F32))
(→ (Option Layout))
(! NotesRead)
(match (paragraphs-ref id)
((None) (None))
((Some paragraph)
(Some (typeset paragraph width)))))
(define-view (document-layout (id EntityId) (width F32))
(→ (Option (Array (Option Layout))))
(! NotesRead)
(match (documents-ref id)
((None) (None))
((Some document)
(Some (array-map (lambda (paragraph-id)
(paragraph-layout paragraph-id width))
(Document-paragraphs document))))))
These are cacheable read functions, not mutable derived tables. Calling a view with caching disabled must produce the same result. Arguments such as viewport width, locale or a font asset’s identity are explicit. There is no hidden clock, random generator, mutable capture or renderer dependency. Changing database rows requires a write action. Changing parameters selects a different view result. Changing code discards the cache.
One frame/response obtains all related values through one read scope:
(match (notes-read (lambda () (document-layout document-id viewport-width)))
((Ok layout) (present layout))
((Err error) (show-storage-error error)))
Presentation happens after the read scope ends. No database transaction spans the wait for the next frame or request. Nested views share the snapshot; they do not begin independent reads. The result is internally consistent, not a promise that no newer commit exists by the time presentation finishes.
Cache correctness before fine-grained invalidation
The first cache key includes the database identity/incarnation, its revision, the code generation, the view identity and argument values. Initially use an exact structural encoding with bit-preserving floating-point arguments, including signed zero; numeric equality alone can merge observably different inputs. Hashes require collision checks against that encoding. Read the revision inside the same snapshot that supplies the rows. A view that started under revision 8 may finish after revision 9 commits; its result remains an answer for revision 8 and cannot populate revision 9’s cache.
Every managed write advances the revision in the same database transaction. Multiple server processes therefore agree on it. Replacing/restoring a database also changes its incarnation or invalidates every associated cache. If arbitrary external writers bypass this protocol, disable reuse across read scopes until the backend supplies reliable change detection. A local counter is insufficient.
Initially any committed write makes all earlier cached results ineligible for new snapshots. Keep caching bounded and evict freely; old read scopes retain their own consistent result. Inside a write transaction, bypass shared view caches because a committed revision does not identify its staged writes.
This coarse policy can be expensive. Later table-version tracking can avoid invalidating unrelated views, including dependencies inherited from nested views and missing-row lookups. Row-level dependencies, incremental query maintenance and subscriptions are not prerequisites for the first contract.
Startup, reload and schema changes
The runtime opens the configured store and binds store around the ordinary
entry point. A new application may perform a transaction that inserts missing
initial records. There is no special init or resume method, and no second
authoritative in-memory world to reconstruct. Sockets and windows are created
by the entry point in the normal way. Views are computed when requested.
On code replacement, finish or abort the old instance’s transactions according to their commit boundary, close its resources, discard its view cache and start the new code against the same durable tables. No Wasm object or continuation crosses. If startup fails, retain the database and report the failure; automatic old-code rollback is not promised, and reverting code cannot undo committed writes. Database files and journals stay outside compiler watch inputs and build directories. Independent browser applications have distinct store names.
Changing a view implementation or result type needs only cache invalidation. Changing a durable row schema requires an explicit migration. Existing wire TypeIds detect mismatches; they do not migrate data. Keep stable table identity and schema versions separate from compiler type hashes. Refuse incompatible data without clearing it. Automatic migration inference is outside this design. Initially migrations are offline/exclusive: stop every store user and exclude concurrent access before changing the schema. Old instances must not continue using an incompatible schema. Online migration and fencing live instances are separate work; checking only when an instance first opens is insufficient.
A successful write means the backend completed its configured transaction commit, preserving records across code/process replacement under that platform’s storage contract. It is not an identical power-loss or retention promise on every host; browser storage eviction remains a platform policy. Do not report success merely because a write request was accepted or a RAM cache changed.
Performance and implementation boundaries
Reads may use memory and indexes; durability does not imply a physical disk read for every lookup. Durable writes still cost work. A game’s live positions can be derived only if durable inputs, a journal or checkpoints reconstruct them. Otherwise they are authoritative data that must be stored. View caches cannot preserve facts absent from those inputs.
Batch work and return ordinary typed values for inner loops. Do not promise ECS array-loop performance from one host call or SQL query per entity. An actual SQL database plus generated typed record access is enough for the first server proof; this project does not need its own database engine. Browser transaction lifetime, cancellation and commit failures must be proved against its actual storage API, not inferred from the server implementation.
| Existing foundation | Work still required |
|---|---|
| Records/enums, generic functions, concrete effect operations | Schema/library forms and generated typed operations |
| Serialize/Deserialize and schema-sensitive TypeIds | Stable database schema identity and explicit migration boundary |
| Closed effect rows and handler capture checks | A precise structural data/capture check for cached views and actions |
| Task waits by ticket | Recoverable storage-abort boundary, serializable writes, consistent snapshots and commit/abort handling |
| Compiler generation identity | Bounded view caching tied to database identity and snapshot revision |
No associated types, borrow checker, user-defined control handlers or new application typeclass is required by the surface model. Whether its proposed forms can expand entirely to existing checks is still to be proved. Transactions and cache coherence remain runtime work; a type annotation cannot supply them.
Review and verification
Before adopting this API, prove: a typed key/row mismatch is rejected; a view cannot write or depend on mutable hidden state; a write cannot perform network I/O; an engine failure reaches the runner as an error; an aborted write exposes no changes; writes reject write skew; migration excludes old instances; two views share one snapshot; a late old view cannot contaminate a newer revision; another process’s write invalidates reuse; database replacement cannot collide with an old cache; and code reload preserves committed data while permitting view result types to change.
Measure whole-frame/request cost, transactions at realistic write rates, cache misses after writes and first-view latency after reload. These determine whether coarse invalidation is sufficient. These measurements and checks are acceptance criteria for adopting the API, not claims about the current runtime.
Related prior art: SpacetimeDB tables and transactional reducers combine typed records and transactions; Flecs queries illustrate component-oriented access. The prototype borrows those organizing ideas without adopting their entire runtimes or claiming their performance.