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
| Delimiter | Semantics | Produces |
|---|---|---|
{ body } | Code block: runs where control flow reaches it, never a value | Its last statement’s value, or a held entry |
( expr ) | Eager (immediate evaluation) | Result value |
Operators
| Category | Operators |
|---|---|
| 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 |
| Extraction | destruct<> (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
| Syntax | Description |
|---|---|
cond ? then ! else | Conditional (if-else, supports multi-line) |
$val -> ? then ! else | Piped 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 -> break | Exit loop |
return / $val -> return | Exit block or script |
pass | Returns 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 -> error | Halt 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
| Syntax | Description |
|---|---|
-> 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:
| Operator | Function receives | Wrong arity |
|---|---|---|
seq, fan, filter, sort, start_when, stop_when, iterate, chain | Element, or current value, alone | seq({ 5 }) halts RILL-R045; seq({ $@ }) halts RILL-R044 |
fold, acc | Element and accumulator | Fewer 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
| Syntax | Description |
|---|---|
-> take(n) | First n elements as a list |
-> skip(n) | All elements after the first n as a list |
-> cycle | Iterator 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
| Type | Syntax | Example | Produces |
|---|---|---|---|
| String | "text", """text""" | "hello", """line 1\nline 2""" | String value |
| Number | 123, 0.5 | 42, 0.9 | Number value |
| Bool | true, false | true | Boolean 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 |
| Ordered | ordered[k: v] | ordered[a: 1, b: "hello"] | Ordered value |
| Tuple | tuple[...] | tuple[1, 2] | Tuple value |
| Map | map[k: v, ...] | map[404: "missing"] | Entries keyed by one scalar kind |
| Datetime | datetime(...) or now() | datetime("2024-01-15T10:30:00Z"), now() | Datetime value |
| Duration | duration(...) | duration(...dict[days: 1, hours: 2]) | Duration value |
| Vector | host-provided | $app.embed("text") (after use<ext:app> => $app) | Vector value |
| Function | fn() { } | fn(x) { $x * 2 } | ScriptCallable |
| Stream | :stream(T):R | host-provided | Stream 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 literal | T literal | list(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]andlist[1, 2]produce a list; both[a: 1]anddict[a: 1]produce a dict. The keyword forms (list[...],dict[...]) are canonical: they appear informatValueoutput and the LLM reference. Use either form in source; they behave identically, except that a bracket of only spreads ([...$a]) is a list; writedict[...$d].[]is the empty list,[:]the empty dict; a bracket mixing positional and keyed entries haltsRILL-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.
| Form | Example | Produces |
|---|---|---|
#NAME | #TIMEOUT | :atom value |
#NAME in invalid value | #NOT_FOUND | status 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
| Syntax | Description |
|---|---|
fn(p: type) { } => $fn | Define 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 { $ } => $fn | Unnamed-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 -> $fn | Pipe-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
| Variable | Contains | Source |
|---|---|---|
$ | Piped value (current scope) | Grammar |
$ARGS | Positional args (list) | Host, when bound |
$ENV.NAME | Environment variable | Host, when bound |
$name | Named variable | Capture 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 ! b | Pipe 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
| Syntax | Description |
|---|---|
$data.field | Literal field access |
$data[0], $data[-1] | Index access |
$data.$key | Variable as key |
$data[$i + 1] | Computed key |
$data.field ?? default, $data[i] ?? default | Default if the final key or index is missing; a miss on an earlier step still halts RILL-R009 |
$data.?field | Existence check (literal) |
$data.?$key | Existence check (variable) |
$data.?[expr] | Existence check (computed) |
$data.?field&type | Existence + type check |
$data.^key, $data.?^key | Annotation reflection; .?^key is a presence check yielding bool |
| Form | Reaches or halts |
|---|---|
.$k, [expr], .? | Dict data fields, list and tuple positions, ordered entries, map entries by key |
.name, .?name, and -> .name on a type value | name, signature, inner, outer, defaults, annotations, where the type has them; .$k and [k] halt RILL-R002 |
.len, .keys | Work only as a written .name or a pipe method |
.?len | false |
["len"] | Halts RILL-R002 on a list, tuple, string, or function; RILL-R009 on a dict or ordered |
.?k | true 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: truelist[1, 2, 3][0]:number
# Result: 1Tuples 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: trueThe 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: 1A 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: 1Type Constructors
Type constructors are primary expressions that produce structural type values. They describe the internal structure of a collection type.
| Constructor | Syntax | Example |
|---|---|---|
| List type | list(T) | list(number), list(list(string)) |
| Unspecified inner | list() | list() equals list(any); dict() equals dict |
| Dict type | dict(k: T [= literal], ...) | dict(a: number, b: string = "x") |
| Dict field, quoted/number/bool key | dict("k": T, ...) | dict("a b": number) |
| Tuple type | tuple(T, T2 [= literal], ...) | tuple(number, string = "x") |
| Map type | map(K, V) | map(atom, number) |
| Ordered type | ordered(k: T [= literal], ...) | ordered(a: number, b: string = "x") |
| Dict field with annotation | dict(^(...) k: T, ...) | dict(^("label") name: string) |
| Ordered field with annotation | ordered(^(...) k: T, ...) | ordered(^("x") x: number, ^("y") y: number) |
| Tuple field with annotation | tuple(^(...) T, ...) | tuple(^("x") number, ^("y") number) |
| Function type | fn(p: T):R | fn(x: number):string |
| Function type with param default | fn(p: T = literal):R | fn(x: string = "gpt-4"):string |
| Function type, zero params | fn():R | fn():string |
| Function type with annotated param | fn(^(...) p: T):R | fn(^("label") x: string):int |
| Annotation default | fn(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: 5See 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.
| Syntax | Description |
|---|---|
$val -> [k1: v1, k2: v2] | Returns value for matching key |
$val -> [k1: v1, k2: v2] ?? default | Returns 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 dispatchDict 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.
| Syntax | Description |
|---|---|
[path] -> $target | Navigate nested dict/list using path of keys/indexes |
[] -> $target | Empty path returns target unchanged |
[k1, k2, ...] -> $dict | Sequential navigation through nested dicts |
[0, 1, ...] -> $list | Sequential navigation through nested lists |
[k, 0, k2] -> $mixed | Mixed 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.
| Syntax | Description |
|---|---|
$idx -> [a, b, c] | Returns element at index (0-based) |
$idx -> [a, b, c] ?? default | Returns 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_INPUTVariable 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>.
| Scenario | Code | Message |
|---|---|---|
| Dict key not found | RILL-R009 | Undefined dict key: {key} |
| Ordered key not found | RILL-R009 | Undefined ordered key: {key} |
| List index out of range | RILL-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-number | RILL-R002 | List index must be number, got {type} |
| Tuple dispatch with a non-number | RILL-R002 | Tuple index must be number, got {type} |
| Pipe into a variable that holds no target | RILL-R002 | cannot pipe into ${name}: it holds a {type} |
| Pipe into a value selected from a variable | RILL-R002 | cannot pipe into a value selected from ${name}: it is a {type} |
Core Methods
| Method | Input | Output | Description |
|---|---|---|---|
.len | Any | Number | Length |
.trim | String | String | Remove whitespace |
.head | String/List | Any | First element |
.tail | String/List | Any | Last element |
.at(idx) | String/List | Any | Element at index; negative counts from end |
.split(sep) | String | List | Split by separator |
.join(sep) | List | String | Join with separator |
.lines | String | List | Split on newlines |
.lower | String | String | Lowercase |
.upper | String | String | Uppercase |
.replace(pat, repl) | String | String | Replace first match |
.replace_all(pat, repl) | String | String | Replace all matches |
.contains(text) | String | Bool | Contains substring |
.starts_with(pre) | String | Bool | Starts with prefix |
.ends_with(suf) | String | Bool | Ends with suffix |
.match(regex) | String | Dict | First match info |
.is_match(regex) | String | Bool | Regex matches |
.empty | String/List/Dict/Tuple/Ordered/Map | Bool | Is empty |
.has(value) | List | Bool | Check if list contains value (deep equality) |
.has_any([values]) | List | Bool | Check if list contains any value from candidates |
.has_all([values]) | List | Bool | Check if list contains all values from candidates |
.keys | Dict/Ordered/Map | List | All keys |
.values | Dict/Ordered/Map | List | All values |
.entries | Dict/Ordered/Map | List | tuple(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.
| Method | Receiver Types | Params | Return |
|---|---|---|---|
.len | string, list, dict, tuple, ordered, map | (none) | number |
.trim | string | (none) | string |
.head, .tail | string, list | (none) | any |
.first | string, list, dict, iterator (runtime checked) | (none) | iterator |
.at | string, list, tuple (runtime checked) | index: number | any |
.split | string | separator: string = "\n" | list |
.join | list | separator: string = "," | string |
.reverse | list | (none) | list |
.lines | string | (none) | list |
.empty | string, list, dict, tuple, ordered, map | (none) | bool |
.starts_with, .ends_with | string | prefix: string for .starts_with, suffix: string for .ends_with | bool |
.lower, .upper | string | (none) | string |
.replace, .replace_all | string | pattern: string, replacement: string | string |
.contains | string | search: string | bool |
.match | string | pattern: string | dict |
.is_match | string | pattern: string | bool |
.index_of | string | search: string | number |
.repeat | string | count: number | string |
.pad_start, .pad_end | string | length: number, fill: string = " " | string |
.eq, .ne | any | other: any | bool |
.lt, .gt, .le, .ge | number, string, datetime | other: any | bool |
.keys, .values, .entries | dict, ordered (runtime checked) | (none) | list |
.has | list (runtime checked) | value: any | bool |
.has_any, .has_all | list (runtime checked) | candidates: list | bool |
.model | vector (runtime checked) | (none) | string |
.similarity, .dot, .distance | vector (runtime checked) | other: any | number |
.dimensions, .norm | vector (runtime checked) | (none) | number |
.normalize | vector (runtime checked) | (none) | any |
bool supports only equality (==, !=). Ordering (<, >, <=, >=) on bool raises RILL-R002.
Global Functions
| Function | Params | Return | Description |
|---|---|---|---|
identity | value: any | any | Returns input unchanged |
log | message: any | any | Print to console, pass through |
json | value: any | string | Convert to JSON string |
enumerate | items: union(list, dict) | list | Add index to elements |
range | start: number, stop: number, step: number = 1 | iterator | Generate number sequence |
repeat | value: any, count: number | iterator | Repeat value n times |
chain | value: any, transform: any | any | Apply function(s) sequentially |
datetime | input|year, month, day, ...|unix | datetime | Construct datetime from ISO string, named components, or unix ms |
duration | a printed-form string, or named components via ...dict[...] | duration | Construct duration from a printed form such as "1h30m" or from named unit components |
now | (none) | datetime | Current UTC instant |
sort | list[T], key_fn?: (item: T) => Comparable | list[T] | Sort list; stable, ascending by default |
sort | dict[K, V], key_fn?: (entry: [key: K, value: V]) => Comparable | ordered[[key: K, value: V]] | Sort dict entries; returns ordered key-value pairs |
sort | map[K, V], key_fn?: (entry: dict[key: K, value: V]) => Comparable | map[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:
| Written | Equivalent 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 = 42Slice 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
| Value | Key | Result |
|---|---|---|
| Any value | type | Declared type if carried, else the own type, via .^type |
| Any value | effective | Own type via .^effective, ignoring any declaration |
| Type value | name | Runtime error: RILL-R008 (use .name dot notation instead) |
| Any callable | any other key | Callable annotation value |
| Anything else | any key | Runtime error: RILL-R003 |
^(min: 0, max: 100) fn(x) { $x } => $fn
$fn.^min # 0
$fn.^max # 100Annotations 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.
| Key | Status | Reason |
|---|---|---|
type | Reserved | Intercepted at evaluation time for any value |
effective | Reserved | Intercepted at evaluation time for any value; returns the own type |
description | User-defined | Not reserved; common metadata key |
enum | User-defined | Not reserved; common metadata key |
default | User-defined | Not reserved; common metadata key |
input | User-defined | Not reserved; on a function ^(input: ...) is an ordinary annotation, .^input returns it, and it shadows the function halt. A stream value is not shadowed |
output | User-defined | Not reserved; same as input |
chunk | User-defined | Not reserved; same as input |
^(type: "custom") name: string # Error: annotation key "type" is reserved
^(effective: "x") name: string # Error: annotation key "effective" is reservedThe 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:
| Removed | Use |
|---|---|
$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 foundField Annotations in Type Constructors
dict, ordered, and tuple type constructors support ^() annotations on individual fields. The list(...) constructor does NOT support field annotations.
| Container | Field kind | Annotation position |
|---|---|---|
dict(...) | Named (k: T) | Before field name |
ordered(...) | Named (k: T) | Before field name |
tuple(...) | Positional (T) | Before field type |
list(...) | N/A | Not supported (RILL-P001) |
Multiple ^() blocks before any target merge into one annotation map.
| Condition | Error |
|---|---|
Invalid syntax inside ^() | RILL-P014 |
^() with no following field | RILL-P014 |
Missing , or ) after annotated field | RILL-P014 |
Unclosed ^( | RILL-P005 |
^() on list(...) field | RILL-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 Target | Description |
|---|---|
string | String value |
number | Numeric value |
bool | Boolean value |
list | List value |
dict | Dict value |
ordered | Ordered container value |
any | Any 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:
| Return | Exit Code |
|---|---|
true / non-empty string | 0 |
false / empty string | 1 |
[0, "message"] | 0 with message |
[1, "message"] | 1 with message |
Comments
Single-line comments start with #:
# This is a comment
"hello" # inline commentA comment needs a space after #. A # followed by a letter or _ starts an atom literal instead.
| Form | Result |
|---|---|
# TODO: fix | comment |
"hello" # note | comment after a value |
#TIMEOUT, #wired, #_internal | atom (:atom value) |
1 #note | parse error RILL-P024 |
#TODO fix this later | parse error RILL-P024 |
#todo alone on a line, or as the whole script | discarded atom statement; the checker warns (ATOM_DISCARDED) |
# Error: atom followed by trailing tokens
"hello" #inlineSee 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:
| Class | Tokens |
|---|---|
| Binary arithmetic | + - * / % |
| Logical | && || |
| Comparison | == != < > <= >= |
| Pipe / capture | -> => |
| Conditional | ? ! |
| Member access | . .? |
| Type annotation | : |
| Spread | ... |
| Annotation | ^ |
| Open delimiters | unclosed [ ( { |
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 +
3Statement-start tokens
These always begin a new statement:
| Token | Starts |
|---|---|
$ | Variable reference or function call |
| identifier | Host function call or loop keyword (while, do) |
fn | Function definition |
| literals | String, 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.
| Code | Description |
|---|---|
RILL-P001 | Unexpected token or invalid syntax |
RILL-R001 | Argument or binding type mismatch |
RILL-R002 | Operation not valid for its operands, including non-boolean conditions |
RILL-R003 | Method receiver type mismatch, or annotation read on a non-function value |
RILL-R005 | Variable not defined |
RILL-R006 | Function not defined |
RILL-R007 | Method not defined |
RILL-R008 | Annotation key not defined |
RILL-R009 | Dict key or list index not found |
RILL-R010 | Iteration limit exceeded |
RILL-R012 | Host call timed out (catchable) |
RILL-R015 | Assertion failed (condition false) |
RILL-R016 | Error statement executed |
#INVALID_INPUT | Invalid regex pattern passed to a string method |
#DISPOSED | Execution 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:
- Types: Type system, type assertions
- Variables: Declaration, scope,
$binding - Control Flow: Conditionals, loops
- Operators: All operators
- Functions and Code Blocks: Late binding, functions held in dicts
- Collections:
seq,fan,filter,fold,acc,sort - Collection Slicing:
take,skip,cycle,batch,window,start_when,stop_when,passbody forms - Iterators:
range,repeat,.first() - Strings: String methods
- Host Integration: Embedding API