Core Language Specification

Core Language Specification

rill is an embeddable, sandboxed scripting language designed for AI agents.

Experimental. Active development. Breaking changes will occur before stabilization.

Overview

rill is an imperative scripting language that is dynamically typed and type-safe. Types are checked at runtime, but type errors are always caught. There are no implicit conversions. Type annotations are optional, but variables lock their type on first assignment. The language is value-based: all values are immutable, all comparisons are by value. Empty values are valid (empty strings, lists, dicts), but null and undefined do not exist. Control flow is singular: no exceptions, no try/catch. Data flows through pipes (->), not assignment.

Design Principles

For design principles, see Design Principles.


Quick Reference Tables

Expression Delimiters

DelimiterSemanticsProduces
{ body }Code block: runs where control flow reaches it, never a valueIts last statement’s value, or a held entry
( expr )Eager (immediate evaluation)Result value

Operators

CategoryOperators
Arithmetic+, -, *, /, %
Comparison==, !=, <, >, <=, >=
Comparison.eq, .ne, .lt, .gt, .le, .ge methods
Logical! (unary), &&, ||
Pipe-> — evaluates its target by kind (type converts, data selects; block, string, function, method, call take the value); auto-fill rule: no $ in args → piped value prepended; explicit $ rule: $ in args → manual placement, no auto-prepend; zero-parameter callable → piped value is an excess argument, halts RILL-R045; block or string target must read $ (RILL-P031); list or dict literal target must not read $ at top level (RILL-P030)
Capture=> — binds the value and passes it on unchanged; never converts, calls, or selects; => $x:T asserts
Spread... (list/tuple spread), ordered[...] spread
Extractiondestruct<> (destructure), slice<> (slice)
Conversion-> type (convert type)
Type:type (assert), :?type (check), :union(T1, T2) (union assert/check)
Member.field, [index]
Default?? value
Existence.?field, .?$var, .?[expr], .?field&type, .?field&union(T1, T2) (union), .?field&list(T) (parameterized)
Status probe.! (bool: is the value invalid), .!field (sidecar field: code, message, provider, trace, or a raw key)
Presence probe.? (presence bool, current $)

See Operators for detailed documentation.

Control Flow

SyntaxDescription
cond ? then ! elseConditional (if-else, supports multi-line)
$val -> ? then ! elsePiped conditional ($ as condition, supports multi-line)
while (cond) do { body }While loop (condition checked before each iteration)
do { body } while (cond)Do-while (body runs at least once, condition checked after)
do(limit: N) { body }Construct option: set maximum iterations; N is a written positive integer literal
break / $val -> breakExit loop
return / $val -> returnExit block or script
passReturns current $ unchanged (use in conditionals, dicts)
pass { body }Run body for side effects; pipe value flows through unchanged; halts propagate
pass(ignore_halts: true) { body }Same as pass { body } but suppresses catchable halts in the body
pass(async: true) { body }Fire-and-forget: dispatches body without blocking; pipe value flows through immediately
pass(async: true, ignore_halts: true) { body }Fire-and-forget with error suppression in the body
timeout(total: d, idle: d) { body }Bound body by a wall-time limit, an inactivity limit, or both; the first to fire halts with #RILL_R082 (total) or #RILL_R083 (idle), catchable
assert cond / assert cond "msg"Validate condition, halt on failure
error "msg" / $val -> errorHalt execution with error message
guard { body }Run body; replace halt with invalid value
retry(attempts: N) { body }Retry body up to N times on caught halt; N is a written positive integer literal

Options written in angle brackets, such as retry<limit: 3>, halt with RILL-P025. Write retry(attempts: 3). limit and attempts must be written positive integer literals, and a spread in retry, do, or while ... do options is RILL-P004. An unknown, missing, or wrong-typed option halts #TYPE_MISMATCH.

See Control Flow for detailed documentation. Script-level exit functions must be host-provided.

Code Blocks

A code block is a braced body that runs where control flow reaches it. It is never a value.

{ 5 } => $x binds 5. fn { 5 } => $x stores a function. A pipe target v -> { } runs with $ bound to v.

A block that is a collection entry is held and runs on each selection. A whole-argument block such as seq({ }) converts to a function. See Functions and Code Blocks for held entries, selection, dispatch path steps, $@ scope, annotations, and held-block halts.

{ body }:T asserts and { body }:?T tests the result. Every block that runs takes the suffix: conditional branches, pipe targets, head and parenthesized blocks, and held entries, as in { 5 }:number. Loop, guard, retry, pass, and timeout bodies do not.

Collection Operators

SyntaxDescription
-> seq({ body })Sequential iteration, all results
-> acc(init, { body })Sequential with accumulator ($@)
-> fan({ body })Parallel iteration, all results
-> filter({ cond })Parallel filter, matching elements
-> fold(init, { body })Sequential reduction, final result
-> sort / -> sort({ key })Stable ordering, optional key extractor

Arity differs by operator:

OperatorFunction receivesWrong arity
seq, fan, filter, sort, start_when, stop_when, iterate, chainElement, or current value, aloneseq({ 5 }) halts RILL-R045; seq({ $@ }) halts RILL-R044
fold, accElement and accumulatorFewer than two parameters halts RILL-R045; a third required parameter halts RILL-R044

See Collections for detailed documentation. All six operators work on streams. They consume chunks as they arrive and return collected results when the stream closes.

Slicing and Restructuring Operators

SyntaxDescription
-> take(n)First n elements as a list
-> skip(n)All elements after the first n as a list
-> cycleIterator that repeats input indefinitely (bound at consumer)
-> batch(n, options?)Stream of non-overlapping chunks of size n; options is dict[idle_flush: duration, drop_partial: bool]
-> window(n, step?)Stream of sliding windows; step defaults to n
-> start_when({ pred })Stream of elements from first predicate match onward
-> stop_when({ pred })Stream of elements through first predicate match (inclusive)
iterate(seed, fn)Infinite source stream: emit seed, then call fn with $ to produce each next value
$seed -> iterate(fn)Pipe form: seed is the piped value; fn produces next values
-> debounce(duration)Suppress rapid emissions; emit latest chunk after duration of silence
-> throttle(duration)Emit first chunk per duration interval; discard subsequent chunks in that interval
-> sample(duration)Emit latest chunk seen at each fixed duration interval

iterate is stream-only and produces an unbounded stream. Combine with take or batch to bound output. debounce, throttle, and sample are stream-only operators; passing a list halts with #INVALID_INPUT.

The batch option idle_flush: duration flushes the current buffer early when no chunk arrives within the given duration. The drop_partial: bool option discards the final incomplete batch when the stream ends.

See Collection Slicing for detailed documentation, edge cases, and error contracts.

Types

TypeSyntaxExampleProduces
String"text", """text""""hello", """line 1\nline 2"""String value
Number123, 0.542, 0.9Number value
Booltrue, falsetrueBoolean value
List[a, b] or list[a, b] (canonical)list["file.ts", 42], list[...$a, 3]List value
Dict[k: v] or dict[k: v] (canonical)dict[output: "text"], dict[$key: 1], [...$d, b: 2]Dict value
Orderedordered[k: v]ordered[a: 1, b: "hello"]Ordered value
Tupletuple[...]tuple[1, 2]Tuple value
Mapmap[k: v, ...]map[404: "missing"]Entries keyed by one scalar kind
Datetimedatetime(...) or now()datetime("2024-01-15T10:30:00Z"), now()Datetime value
Durationduration(...)duration(...dict[days: 1, hours: 2])Duration value
Vectorhost-provided$app.embed("text") (after use<ext:app> => $app)Vector value
Functionfn() { }fn(x) { $x * 2 }ScriptCallable
Stream:stream(T):Rhost-providedStream value
Block{ body }{ $ + 1 }Runs in place; yields its last statement’s value, or is a held entry (never a value)
Atom#NAME#TIMEOUT, #wired:atom value
Declared literalT literallist(number)[1, 2], union("a", "b") "a"Literal checked against T, carrying T as its declared type

Type names (valid in :type assertions, :?type checks, and parameter annotations): string, number, bool, fn, list, dict, ordered, tuple, map, vector, iterator, datetime, duration, stream, atom, error_code, any, type

union is also a type name, valid only as union(T, ...); see Type System.

Parameterized forms (list(T), dict(k: T, ...), tuple(T, ...), map(K, V), stream(T):R, union(T, ...)) are also valid in all annotation positions and deep-validate element types at runtime. See Types for stream type documentation and Functions and Code Blocks for stream function syntax.

Union types (union(T1, T2), union(T1, T2, T3)) are valid in all annotation positions. A union matches if the value satisfies any member. A member is a type or a string, number, bool, or atom literal: union("c", "f"). Type members can be parameterized: union(list(string), dict). See Type System for union type documentation.

List and dict syntax: Both [1, 2] and list[1, 2] produce a list; both [a: 1] and dict[a: 1] produce a dict. The keyword forms (list[...], dict[...]) are canonical: they appear in formatValue output and the LLM reference. Use either form in source; they behave identically, except that a bracket of only spreads ([...$a]) is a list; write dict[...$d]. [] is the empty list, [:] the empty dict; a bracket mixing positional and keyed entries halts RILL-P001.

dict[a: 1] => $d
list[[...$d, b: 2] == dict[a: 1, b: 2], dict[...$d] == $d, [] == list[], [:] == dict[]]
# Result: list[true, true, true, true]
# Error: RILL-P001
[1, a: 2]

See Types for detailed documentation.

Atom Literals

Atom literals use #NAME syntax. They produce a :atom value identifying a named condition. Atoms are identified and compared by name. Names are case-sensitive, so #timeout and #TIMEOUT are different atoms.

FormExampleProduces
#NAME#TIMEOUT:atom value
#NAME in invalid value#NOT_FOUNDstatus code on invalid result

#TIMEOUT -> string converts a :atom value to its string name. "TIMEOUT" -> atom converts a string name to a :atom value. See Types for :atom documentation and Built-in Atoms and the Core Error Set for the atoms that serve as error codes.

# lexes as an atom when a letter or _ follows it; any other # starts a comment. See Comments for the full rule and the parse errors it produces.

Functions

SyntaxDescription
fn(p: type) { } => $fnDefine and capture function; type can be parameterized (e.g., fn(x: list(string)))
fn(p: type):rtype { }Define function with enforced return type; rtype can be parameterized (e.g., :list(string))
fn(p = default) { }Parameter with default; the parameter type is any, since a default does not infer a type
fn(^(min: 0) p) { }Parameter with annotation
fn { $ } => $fnUnnamed-parameter function; fn { } takes the parameters its body reads: none gives fn():any, $ gives one, $@ gives two
$fn(arg)Call function directly
arg -> $fn()Call with pipe value as single arg
arg -> $fn(...)Spread pipe value into call arguments
$fn(...$expr)Spread a variable into call arguments
$fn(a, ...$rest)Mix fixed args with a spread
arg -> $fnPipe-style invoke

Spreading is opt-in via ... or ...$expr. Passing a tuple or ordered value without ... passes it as a single argument. The implicit auto-spread behavior has been removed. At most one spread is permitted per call.

See Functions and Code Blocks for detailed documentation.

Special Variables

VariableContainsSource
$Piped value (current scope)Grammar
$ARGSPositional args (list)Host, when bound
$ENV.NAMEEnvironment variableHost, when bound
$nameNamed variableCapture or host

See Variables for detailed documentation.

$ Binding by Context

Context$ contains
Inline block -> { }Piped value
Each loop -> seq({ })Current item
While-loop while (cond) do { }Accumulated value
Do-while do { } while (cond)Accumulated value
Conditional cond ? a ! bPipe value entering the conditional, in either branch (block or bare)
Piped conditional -> ? { }Piped value
Named-parameter fn fn(x) { }N/A: use params
Unnamed-parameter fn fn { }First argument (when the body reads $)
fn() { }Not bound; a body that reads $ or $@ raises RILL-P029

Property Access

SyntaxDescription
$data.fieldLiteral field access
$data[0], $data[-1]Index access
$data.$keyVariable as key
$data[$i + 1]Computed key
$data.field ?? default, $data[i] ?? defaultDefault if the final key or index is missing; a miss on an earlier step still halts RILL-R009
$data.?fieldExistence check (literal)
$data.?$keyExistence check (variable)
$data.?[expr]Existence check (computed)
$data.?field&typeExistence + type check
$data.^key, $data.?^keyAnnotation reflection; .?^key is a presence check yielding bool
FormReaches or halts
.$k, [expr], .?Dict data fields, list and tuple positions, ordered entries, map entries by key
.name, .?name, and -> .name on a type valuename, signature, inner, outer, defaults, annotations, where the type has them; .$k and [k] halt RILL-R002
.len, .keysWork only as a written .name or a pipe method
.?lenfalse
["len"]Halts RILL-R002 on a list, tuple, string, or function; RILL-R009 on a dict or ordered
.?ktrue exactly when ["k"] does not halt
tuple[1, "a"] => $t
1 => $k
$t.$k
# Result: "a"

[index] is a postfix operator: it applies after any expression yielding an indexable value, not only a $-variable.

list[1, 2, 3][0]
# Result: 1

.?field and a :type / :?type assertion may follow any postfix operator, the same as after $var[i]:

list[dict[a: 1]][0].?a
# Result: true
list[1, 2, 3][0]:number
# Result: 1

Tuples and ordered values index the same way as lists.

Reserved Words as Member Names

Reserved words are legal member names immediately after a dot. The lexer retypes any keyword token following . or .? to a member name. These words never trigger their statement parsing.

Affected words: true, false, break, return, yield, pass, assert, error, guard, retry, while, do.

dict["error": "not found"] => $result
$result.error
# Result: "not found"
dict["retry": 3] => $settings
$settings.?retry
# Result: true

The same rule applies to use<> resource segments, so use<host:pkg.error> resolves error as a path segment, not a statement keyword.

The 10 non-boolean reserved words are valid bare dict keys and parse as string keys, so dict[error: 1], dict[while: 1], and dict[break: 1] all work. true and false are bare keys too; they store the strings "true" and "false".

dict[error: 1, while: 2, break: 3] => $d
$d.error
# Result: 1

A bare true/false key names the string key "true"/"false", so member access .true reads it. See Types for dict keys.

dict[true: 1] => $d
$d.true
# Result: 1

Type Constructors

Type constructors are primary expressions that produce structural type values. They describe the internal structure of a collection type.

ConstructorSyntaxExample
List typelist(T)list(number), list(list(string))
Unspecified innerlist()list() equals list(any); dict() equals dict
Dict typedict(k: T [= literal], ...)dict(a: number, b: string = "x")
Dict field, quoted/number/bool keydict("k": T, ...)dict("a b": number)
Tuple typetuple(T, T2 [= literal], ...)tuple(number, string = "x")
Map typemap(K, V)map(atom, number)
Ordered typeordered(k: T [= literal], ...)ordered(a: number, b: string = "x")
Dict field with annotationdict(^(...) k: T, ...)dict(^("label") name: string)
Ordered field with annotationordered(^(...) k: T, ...)ordered(^("x") x: number, ^("y") y: number)
Tuple field with annotationtuple(^(...) T, ...)tuple(^("x") number, ^("y") number)
Function typefn(p: T):Rfn(x: number):string
Function type with param defaultfn(p: T = literal):Rfn(x: string = "gpt-4"):string
Function type, zero paramsfn():Rfn():string
Function type with annotated paramfn(^(...) p: T):Rfn(^("label") x: string):int
Annotation defaultfn(p: dict(k: T = literal))fn(a: dict(b: number = 5))

When using -> type to convert a value, the runtime applies two default behaviors for collection-typed fields:

  • Nested synthesis: A missing field with no explicit default is synthesized as an empty collection when all its children have defaults. Missing children are filled from the nested type.
  • Explicit default hydration: An explicit collection default is hydrated through the nested type. Child defaults fill any fields the explicit default omits.

If any required child field has no default, -> type raises RILL-R044.

^type returns a structural type value, not a coarse string:

[1, 2, 3] => $list
$list.^type.name
# Result: "list"
[a: 1, b: "hello"] => $d
$d.^type.name
# Result: "dict"

Type constructors appear as values and can be compared:

[1, 2, 3] => $list
$list.^type == list(number)
# Result: true

.^type.name returns the coarse type name string; under a declared type it reports the declaration (see .^effective in Type System). .^type returns a type value; .name then accesses the dot-notation property on that type value (not annotation interception):

[1, 2, 3] => $list
$list.^type.name
# Result: "list"

Type constructors are also valid in annotation positions:

fn(x: list(number)) { $x -> seq({ $ * 2 }) } => $fn
$fn(list[1, 2, 3])
# Result: list[2, 4, 6]
list[1, 2, 3] -> :list(number)
# Result: list[1, 2, 3]

Type constructor defaults work in annotation position. The runtime fills missing fields from the annotation defaults when a value is passed:

fn(a: dict(b: number = 5)) { $a.b } => $fn
$fn(dict[])
# Result: 5

See Type System for detailed structural type documentation.

Dispatch

Pipe a value to a collection (dict, list, tuple, ordered, or map) to retrieve the corresponding element. A tuple selects by index and an ordered selects by key, as a list and a dict do. A map selects by a key of its key kind; a held block runs with the key as $.

Dict Dispatch: Match keys and return associated values.

SyntaxDescription
$val -> [k1: v1, k2: v2]Returns value for matching key
$val -> [k1: v1, k2: v2] ?? defaultReturns matched value or default
$val -> [["k1", "k2"]: shared]Multi-key dispatch (same value)
$value -> [apple: "fruit", carrot: "vegetable"]  # Returns "fruit" if $value is "apple"
$value -> [apple: "fruit"] ?? "not found"        # Returns "not found" if no match
$method -> [["GET", "HEAD"]: "safe", list["POST", "PUT"]: "unsafe"]  # Multi-key dispatch

Dict keys are strings and multi-key syntax [k1, k2]: value maps several keys to one value; see Dict Keys Are Strings.

Hierarchical Dispatch: Navigate nested structures using a path list.

SyntaxDescription
[path] -> $targetNavigate nested dict/list using path of keys/indexes
[] -> $targetEmpty path returns target unchanged
[k1, k2, ...] -> $dictSequential navigation through nested dicts
[0, 1, ...] -> $listSequential navigation through nested lists
[k, 0, k2] -> $mixedMixed dict keys and list indexes

Path element types: string keys for dict lookup, number indexes for list access (negative indexes supported). A string key on a list halts RILL-R002; a non-string key on a dict follows Dict Keys Are Strings; a missing key or an out-of-range index halts RILL-R009.

A terminal held block receives $ bound to the final path key. A terminal function is returned uncalled.

["name", "given"] -> [name: dict[given: "Alice"]]              # "Alice" (dict path)
[0, 1] -> list[list[1, 2, 3], list[4, 5, 6]]                      # 2 (list path)
["users", 0, "name"] -> [users: list[dict[name: "Alice"]]]    # "Alice" (mixed path)
["req", "draft"] -> [req: dict[draft: { "key={$}" }]]         # "key=draft" (terminal held block)

List Dispatch: Index into a list using a number.

SyntaxDescription
$idx -> [a, b, c]Returns element at index (0-based)
$idx -> [a, b, c] ?? defaultReturns element or default if out of bounds

The index must be an integer; a non-integer number halts with #INVALID_INPUT and is not truncated.

0 -> ["first", "second", "third"]     # "first"
1 -> ["first", "second", "third"]     # "second"
-1 -> ["first", "second", "third"]    # "third" (last element)
5 -> ["a", "b"] ?? "not found"        # "not found" (out of bounds)
1.5 -> ["a", "b"]  # Error: #INVALID_INPUT

Variable Dispatch: Use stored collections.

[apple: "fruit", carrot: "vegetable"] => $lookup
"apple" -> $lookup                    # "fruit"
["a", "b", "c"] => $items
1 -> $items                           # "b"

Error Messages: a miss reads the same in $c[k], .$k, pipe selection, a dispatch table, hierarchical dispatch, and destruct<k: $x>.

ScenarioCodeMessage
Dict key not foundRILL-R009Undefined dict key: {key}
Ordered key not foundRILL-R009Undefined ordered key: {key}
List index out of rangeRILL-R009{Kind} index out of bounds: {index}
List index not an integer#INVALID_INPUT{Kind} index must be an integer, got {index}
List dispatch with a non-numberRILL-R002List index must be number, got {type}
Tuple dispatch with a non-numberRILL-R002Tuple index must be number, got {type}
Pipe into a variable that holds no targetRILL-R002cannot pipe into ${name}: it holds a {type}
Pipe into a value selected from a variableRILL-R002cannot pipe into a value selected from ${name}: it is a {type}

Core Methods

MethodInputOutputDescription
.lenAnyNumberLength
.trimStringStringRemove whitespace
.headString/ListAnyFirst element
.tailString/ListAnyLast element
.at(idx)String/ListAnyElement at index; negative counts from end
.split(sep)StringListSplit by separator
.join(sep)ListStringJoin with separator
.linesStringListSplit on newlines
.lowerStringStringLowercase
.upperStringStringUppercase
.replace(pat, repl)StringStringReplace first match
.replace_all(pat, repl)StringStringReplace all matches
.contains(text)StringBoolContains substring
.starts_with(pre)StringBoolStarts with prefix
.ends_with(suf)StringBoolEnds with suffix
.match(regex)StringDictFirst match info
.is_match(regex)StringBoolRegex matches
.emptyString/List/Dict/Tuple/Ordered/MapBoolIs empty
.has(value)ListBoolCheck if list contains value (deep equality)
.has_any([values])ListBoolCheck if list contains any value from candidates
.has_all([values])ListBoolCheck if list contains all values from candidates
.keysDict/Ordered/MapListAll keys
.valuesDict/Ordered/MapListAll values
.entriesDict/Ordered/MapListtuple(K, V) pairs

.keys, .values, and .entries halt RILL-R003 on a receiver that is not a dict, ordered, or map (tuple, stream, string, number, and so on); ?? and guard do not recover the halt, so check the receiver first. See Maps for map keys and selection.

See Strings for detailed string method documentation.

Method Signatures

Methods marked “runtime checked” accept any receiver at parse time and halt at runtime when the receiver type is wrong.

MethodReceiver TypesParamsReturn
.lenstring, list, dict, tuple, ordered, map(none)number
.trimstring(none)string
.head, .tailstring, list(none)any
.firststring, list, dict, iterator (runtime checked)(none)iterator
.atstring, list, tuple (runtime checked)index: numberany
.splitstringseparator: string = "\n"list
.joinlistseparator: string = ","string
.reverselist(none)list
.linesstring(none)list
.emptystring, list, dict, tuple, ordered, map(none)bool
.starts_with, .ends_withstringprefix: string for .starts_with, suffix: string for .ends_withbool
.lower, .upperstring(none)string
.replace, .replace_allstringpattern: string, replacement: stringstring
.containsstringsearch: stringbool
.matchstringpattern: stringdict
.is_matchstringpattern: stringbool
.index_ofstringsearch: stringnumber
.repeatstringcount: numberstring
.pad_start, .pad_endstringlength: number, fill: string = " "string
.eq, .neanyother: anybool
.lt, .gt, .le, .genumber, string, datetimeother: anybool
.keys, .values, .entriesdict, ordered (runtime checked)(none)list
.haslist (runtime checked)value: anybool
.has_any, .has_alllist (runtime checked)candidates: listbool
.modelvector (runtime checked)(none)string
.similarity, .dot, .distancevector (runtime checked)other: anynumber
.dimensions, .normvector (runtime checked)(none)number
.normalizevector (runtime checked)(none)any

bool supports only equality (==, !=). Ordering (<, >, <=, >=) on bool raises RILL-R002.

Global Functions

FunctionParamsReturnDescription
identityvalue: anyanyReturns input unchanged
logmessage: anyanyPrint to console, pass through
jsonvalue: anystringConvert to JSON string
enumerateitems: union(list, dict)listAdd index to elements
rangestart: number, stop: number, step: number = 1iteratorGenerate number sequence
repeatvalue: any, count: numberiteratorRepeat value n times
chainvalue: any, transform: anyanyApply function(s) sequentially
datetimeinput|year, month, day, ...|unixdatetimeConstruct datetime from ISO string, named components, or unix ms
durationa printed-form string, or named components via ...dict[...]durationConstruct duration from a printed form such as "1h30m" or from named unit components
now(none)datetimeCurrent UTC instant
sortlist[T], key_fn?: (item: T) => Comparablelist[T]Sort list; stable, ascending by default
sortdict[K, V], key_fn?: (entry: [key: K, value: V]) => Comparableordered[[key: K, value: V]]Sort dict entries; returns ordered key-value pairs
sortmap[K, V], key_fn?: (entry: dict[key: K, value: V]) => Comparablemap[K, V]Sort map entries by key, or by the key function result; returns a map

json halts #INVALID_INPUT on a function value, including a function held in a dict or list.

The remaining built-ins are seq, fan, acc, fold, filter, take, skip, cycle, batch, window, start_when, stop_when, iterate, debounce, throttle, and sample. See Collection Operators and Slicing and Restructuring Operators for their rows.

See Iterators for range and repeat documentation.

See Collections for detailed sort documentation including multi-key tuple projection and error contracts.


Implied $

When constructs appear without explicit input, $ is used implicitly:

WrittenEquivalent to
? { }$ -> ? { }
.method()$ -> .method()

Extraction Operators

Destructure destruct<>

Extract elements from lists, tuples, or dicts (keyed patterns also accept ordered) into variables:

[1, 2, 3] -> destruct<$a, $b, $c>
# $a = 1, $b = 2, $c = 3

[name: "test", count: 42] -> destruct<name: $n, count: $c>
# $n = "test", $c = 42

Slice slice<>

Extract portions of lists, tuples, and strings using Python-style start:stop:step:

[0, 1, 2, 3, 4] -> slice<0:3>        # list[0, 1, 2]
[0, 1, 2, 3, 4] -> slice<-2:>        # list[3, 4]
[0, 1, 2, 3, 4] -> slice<::-1>       # list[4, 3, 2, 1, 0]
"hello" -> slice<1:4>                    # "ell"

Capture variables accept type annotations: destruct<$a:list(string)>, destruct<$a:union(string, number)>. The runtime validates each extracted element against the declared type; a mismatch halts #TYPE_MISMATCH with Type assertion failed: expected ..., got ..., as a typed capture does. A destructure into an already type-locked variable without an annotation that breaks the lock halts RILL-R001. A destructure pattern is all positional or all keyed; mixing the two is parse error RILL-P026. See Operators for detailed extraction operator documentation.


Annotation Reflection

Access annotation values using .^key syntax. Annotations attach to callables (script functions and host-provided functions). The key type is special-cased and works on any value; it returns the declared type when the value carries one, else the own type.

.^key Dispatch Table

ValueKeyResult
Any valuetypeDeclared type if carried, else the own type, via .^type
Any valueeffectiveOwn type via .^effective, ignoring any declaration
Type valuenameRuntime error: RILL-R008 (use .name dot notation instead)
Any callableany other keyCallable annotation value
Anything elseany keyRuntime error: RILL-R003
^(min: 0, max: 100) fn(x) { $x } => $fn

$fn.^min     # 0
$fn.^max     # 100

Annotations apply only to the function directly targeted by ^(...); a nested function does not inherit an outer annotation. Stacked ^(...) blocks before one target merge. Accessing an undefined key halts RILL-R008; .?^key yields false instead of halting. .?^key tests stored annotations only, so $f.?^type and $f.?^effective are false unless the function stores those keys, although .^type and .^effective read on any value.

Reserved Annotation Keys

The parser rejects annotation keys that conflict with built-in dispatch semantics.

KeyStatusReason
typeReservedIntercepted at evaluation time for any value
effectiveReservedIntercepted at evaluation time for any value; returns the own type
descriptionUser-definedNot reserved; common metadata key
enumUser-definedNot reserved; common metadata key
defaultUser-definedNot reserved; common metadata key
inputUser-definedNot reserved; on a function ^(input: ...) is an ordinary annotation, .^input returns it, and it shadows the function halt. A stream value is not shadowed
outputUser-definedNot reserved; same as input
chunkUser-definedNot reserved; same as input
^(type: "custom") name: string   # Error: annotation key "type" is reserved
^(effective: "x") name: string   # Error: annotation key "effective" is reserved

The name key is not reserved on functions. On type values, .name is a dot-notation property, not annotation access; use .^type.name to read a type value’s name.

Removed Reflection Probes

.^input and .^output on a function halt RILL-R008, .^chunk and .^output on a stream halt RILL-R003, and each message names the replacement:

RemovedUse
$f.^input$f.^type.inner
$f.^output$f.^type.outer
$s.^chunk$s.^type.inner
$s.^output$s.^type.outer

$f.params on a function also halts RILL-R008, and its message names .^type.annotations and .^type.inner.

The function halts are catchable: $f.^input ?? "none" gives "none". The stream halts are not: $s.^chunk ?? "x" still halts RILL-R003 with the replacement hint.

fn(x) { $x } => $f
$f.^input ?? "none"
# Result: "none"
^(input: "csv") fn(x) { $x } => $f
$f.^input
# Result: "csv"
fn(x) { $x } => $f
$f.^input
# Error: Annotation 'input' not found

Field Annotations in Type Constructors

dict, ordered, and tuple type constructors support ^() annotations on individual fields. The list(...) constructor does NOT support field annotations.

ContainerField kindAnnotation position
dict(...)Named (k: T)Before field name
ordered(...)Named (k: T)Before field name
tuple(...)Positional (T)Before field type
list(...)N/ANot supported (RILL-P001)

Multiple ^() blocks before any target merge into one annotation map.

ConditionError
Invalid syntax inside ^()RILL-P014
^() with no following fieldRILL-P014
Missing , or ) after annotated fieldRILL-P014
Unclosed ^(RILL-P005
^() on list(...) fieldRILL-P001

See Closure Annotations for parameter annotations, parameter reflection with .^type.inner, the description shorthand, and dict/ordered/tuple field-annotation examples.


Return Type Assertions

The :type-target postfix after the closing } declares and enforces the function’s return type. The runtime validates the return value on every call; a mismatch halts with RILL-R004.

Syntax: fn(params):returnType { body }

fn(x: number):string { "{$x}" } => $fn
$fn(42)    # "42"

Valid return type targets:

Type TargetDescription
stringString value
numberNumeric value
boolBoolean value
listList value
dictDict value
orderedOrdered container value
anyAny type (no assertion)
list(T), dict(k: T, ...), tuple(T, ...)Parameterized structural types (deep-validates)

Declared return type is accessible via $fn.^type.outer. See Closure Annotations for parameterized-type examples and the mismatch error output.


Ordered and Tuples

ordered[...] produces a named container that preserves insertion order. Use it for named argument unpacking:

fn(a, b, c) { "{$a}-{$b}-{$c}" } => $fmt
dict[c: 3, a: 1, b: 2] -> $fmt(...)    # "1-2-3" (named args by key, key order irrelevant)

Tuples are positional containers. Use tuple[...] with explicit spread ... for positional argument unpacking:

fn(a, b, c) { "{$a}-{$b}-{$c}" } => $fmt
tuple[1, 2, 3] -> $fmt(...)    # "1-2-3" (positional args, explicit spread)

See Types for detailed ordered and tuple documentation.


Operator-Level Annotations

Place ^(...) at the statement level to attach metadata to a statement. For loops, use the do(limit: N) construct option to set an iteration ceiling.

Loops:

0 -> while ($ < 50) do(limit: 100) { $ + 1 }

Collection operators do not accept ^(limit: N) inside the call. The parser rejects this form (RILL-R081). Collection operators (seq, fan, filter, fold, acc, sort) enforce a built-in 10,000-chunk iteration ceiling; use break to stop a stream or iterator early in seq or acc, and bound other sources with take(n).

# Rejected — RILL-R081: ^(limit: N) is not accepted inside collection operators
[1, 2, 3] -> seq(^(limit: 1000) { $ * 2 })
# Accepted — use break inside the body to cap iterations
[1, 2, 3, 4, 5] -> seq({
  ($ > 3) ? break
  $
})

See Control Flow and Collections for detailed examples.

Runtime Limits

Iteration Limits

Loops have a default maximum of 10,000 iterations. Use do(limit: N) as the construct option:

0 -> while ($ < 50) do(limit: 100) { $ + 1 }

For do-while loops, the same construct option applies:

0 -> do(limit: 100) { $ + 1 } while ($ < 50)

Concurrency Limits

Parallel concurrency in fan is not controlled by a ^(limit: N) annotation. The runtime rejects ^(limit: N) inside operator calls (RILL-R081). Configure concurrency limits via the host RuntimeContext.

See Host Integration for timeout and cancellation configuration.


Host-Provided Functions

rill is a vanilla language. The host application registers domain-specific functions via RuntimeContext:

import { createRuntimeContext, toCallable } from '@rcrsr/rill';

const ctx = createRuntimeContext({
  variables: {
    prompt: toCallable({ signature: 'fn(text: string):string', fn: async (args) => await callLLM(args.text) }),
    io: {
      read: toCallable({ signature: 'fn(path: string):string', fn: async (args) => fs.readFile(String(args.path), 'utf-8') }),
    },
    config: { apiUrl: 'https://api.example.com' },
  },
});

Scripts call these as prompt("text") or io.read("file.txt").

See Host Integration for complete API documentation.


Script Frontmatter

Optional YAML frontmatter between --- markers. Frontmatter is opaque to rill; the host interprets it:

---
timeout: 00:10:00
args: file: string
---

process($file)

Script Return Values

Scripts return their last expression:

ReturnExit Code
true / non-empty string0
false / empty string1
[0, "message"]0 with message
[1, "message"]1 with message

Comments

Single-line comments start with #:

# This is a comment
"hello"  # inline comment

A comment needs a space after #. A # followed by a letter or _ starts an atom literal instead.

FormResult
# TODO: fixcomment
"hello" # notecomment after a value
#TIMEOUT, #wired, #_internalatom (:atom value)
1 #noteparse error RILL-P024
#TODO fix this laterparse error RILL-P024
#todo alone on a line, or as the whole scriptdiscarded atom statement; the checker warns (ATOM_DISCARDED)
# Error: atom followed by trailing tokens
"hello" #inline

See Atom Literals for the #NAME syntax this carve-out enables.


Newlines

Invariant: whitespace is insignificant inside a syntactic continuation.

Newlines are statement terminators. A newline ends a statement unless the parser is inside a syntactic continuation, meaning any position where the preceding token cannot end a valid statement.

Continuation tokens

A newline after any of these continues the current statement:

ClassTokens
Binary arithmetic+ - * / %
Logical&& ||
Comparison== != < > <= >=
Pipe / capture-> =>
Conditional? !
Member access. .?
Type annotation:
Spread...
Annotation^
Open delimitersunclosed [ ( {

A subset of continuation tokens also work as line-start continuations: placing them at the beginning of the next line continues the previous statement. This applies to ->, =>, ?, !, ., and .?:

"hello"
  => $greeting
  -> .upper
  -> .trim
(5 > 0)
  ? "yes"
  ! "no"

Arithmetic, logical, and comparison operators work as trailing continuations only: place the operator at the end of the line, not the beginning:

1 +
  2 +
  3

Statement-start tokens

These always begin a new statement:

TokenStarts
$Variable reference or function call
identifierHost function call or loop keyword (while, do)
fnFunction definition
literalsString, number, bool, [...], [...], tuple[...], ordered[...]

Disjoint sets

The two token classes are disjoint. No token is both a continuation token and a statement-start token. This makes the grammar unambiguous with one token of lookahead, with no symbol table and no backtracking.


Grammar

The complete formal grammar is in grammar.ebnf.


Error Codes

Lexer, parse, runtime, and check errors carry structured RILL-Xnnn codes for programmatic handling. A runtime halt may also carry an atom such as #INVALID_INPUT, which guard and ?? can match.

CodeDescription
RILL-P001Unexpected token or invalid syntax
RILL-R001Argument or binding type mismatch
RILL-R002Operation not valid for its operands, including non-boolean conditions
RILL-R003Method receiver type mismatch, or annotation read on a non-function value
RILL-R005Variable not defined
RILL-R006Function not defined
RILL-R007Method not defined
RILL-R008Annotation key not defined
RILL-R009Dict key or list index not found
RILL-R010Iteration limit exceeded
RILL-R012Host call timed out (catchable)
RILL-R015Assertion failed (condition false)
RILL-R016Error statement executed
#INVALID_INPUTInvalid regex pattern passed to a string method
#DISPOSEDExecution cancelled by the host (uncatchable)

Error Reference lists every code with causes and resolutions. See Host Integration for error handling details.


See Also

For detailed documentation on specific topics: