Control Flow
Overview
rill provides singular control flow with no exceptions and no try/catch. Errors halt execution. guard captures halts as invalid values for explicit recovery. retry retries a body when it returns an invalid result.
| Syntax | Description |
|---|---|
cond ? then ! else | Conditional (if-else) |
$val -> ? then ! else | Piped conditional (uses $ as cond) |
while (cond) do { body } | While loop (cond is bool, evaluated before each iteration) |
do { body } while (cond) | Do-while (body first, cond after) |
do(limit: N) { body } | Construct option: sets iteration limit |
break / $val -> break | Exit loop |
return / $val -> return | Exit block |
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 |
timeout(total: d, idle: d) { body } | Bound body by a wall-time limit, an inactivity limit, or both; expiry → #RILL_R082 (total) or #RILL_R083 (idle) |
Conditionals
? is the conditional operator. The condition precedes ?, and ! introduces the else clause.
Syntax Forms
condition ? then-body
condition ? then-body ! else-body
$val -> ? then-body ! else-body # piped form: $ is the condition
# Multi-line forms (? and ! work as line continuations)
condition
? then-body
! else-body
value -> is_valid
? "ok"
! "error"Standalone Form
Condition precedes ?:
true ? "yes" ! "no" # "yes"
false ? "yes" ! "no" # "no"
(5 > 3) ? "big" ! "small" # grouped comparison as conditionPiped Form
Use $ as condition:
true -> ? "yes" ! "no" # "yes" (pipe value must be bool)
5 -> ($ > 3) ? "big" ! "small" # "big"Method Conditions
Methods that return booleans work directly as conditions:
"hello" -> .contains("ell") ? "found" ! "missing" # "found"
"abc" -> !.empty ? "has content" ! "empty" # "has content"Condition Forms
"test" -> ($ == "test") ? "match" ! "no" # grouped comparison
"test" -> .eq("test") ? "match" ! "no" # comparison method
"xyz" -> .contains("x") ? "found" ! "no" # method as conditionOptional Else
The else branch (! ...) is optional:
true ? "executed" # "executed"
5 -> (false ? "skipped") # 5: when false, returns the current $Without an else branch, a false condition returns the current $. If no $ is bound, the conditional halts with RILL-R005, the same way bare pass does:
false ? "skipped" # Error: RILL-R005 Variable '$' not definedElse-If Chains
"B" => $val
$val -> .eq("A") ? "a" ! .eq("B") ? "b" ! "other" # "b"Multi-line else-if chains improve readability:
"B" => $val
$val -> .eq("A") ? "a"
! .eq("B") ? "b"
! "other"
# Result: "b"Return Value
Conditionals return the last expression of the executed branch:
true -> ? "yes" ! "no" => $result # "yes"
false -> ? "yes" ! "no" => $result # "no"Block Bodies
Use braces for multi-statement branches:
true -> ? {
"step 1" -> log
"step 2" -> log
"done"
} ! {
"skipped"
}Block bodies work with multi-line conditionals:
"data" => $input
$input -> .empty
? { error "Empty input" }
! { $input -> .upper }
# Result: "DATA"A conditional branch accepts a type assertion after its block. :T asserts the branch result and :?T yields whether it has type T:
true ? { 5 }:number ! { 6 }
# Result: 5The suffix does not parse on while, do, guard, retry, pass, or timeout bodies. See Code Blocks for the block rules.
While Loop
Pre-condition loop. Condition is evaluated before each iteration. The body result becomes the next iteration’s $.
Loop bodies cannot modify outer-scope variables. Use $ to carry all state. For multiple values, pack them in a dict.
Syntax
while (condition) do { body }
initial -> while (condition) do { body }Basic Usage
# Count to 5
0 -> while ($ < 5) do { $ + 1 }
# Result: 5# String accumulation
"" -> while (.len < 5) do { "{$}x" }
# Result: "xxxxx"Condition Forms
0 -> while ($ < 10) do { $ + 1 }
# Result: 10"" -> while (.len < 4) do { "{$}x" }
# Result: "xxxx"Pipe-Seeded While Loop
Pipe a seed value to while to prime the accumulator $:
0 -> while ($ < 3) do { $ + 1 }
# Result: 3"start" -> while ($ != "done") do {
($ == "start") ? "middle" ! "done"
}
# Result: "done"Infinite Loop with Break
0 -> while (true) do {
$ + 1 -> ($ > 5) ? break ! $
}
# Result: 6Iteration Limit
Use do(limit: N) as the construct option to set maximum iterations (default: 10,000):
0 -> while ($ < 10) do(limit: 100) { $ + 1 }
# Result: 10Exceeding the limit halts with RILL-R010.
The do(limit: N) construct option applies only to that specific loop evaluation, not to the loop body. limit is a written positive integer literal; a variable, a computed value, zero, or any spread in while ... do(...) or do(...) { } while is a parse error (RILL-P004). A repeated limit is RILL-P027. An unknown option halts #TYPE_MISMATCH. The old angle-bracket form do<limit: N> is a parse error (RILL-P025).
Multiple State Values
When you need to track multiple values across iterations, use $ as a state dict:
use<ext:app> => $app
# Track iteration count, text, and done flag
[iter: 0, text: $input, done: false]
-> while (!$.done && $.iter < 3) do {
$.iter + 1 => $i
$app.process($.text) => $result
$result.finished
? [iter: $i, text: $.text, done: true]
! [iter: $i, text: $result.text, done: false]
}
# Access final state: $.text, $.iterThis pattern replaces the common (but invalid) approach of trying to modify outer variables from inside the loop.
Do-While Loop
Post-condition loop. Body executes first, then condition is checked. Use when you want at least one execution.
Syntax
do { body } while (condition)
initial -> do { body } while (condition)Basic Usage
# Execute at least once, continue while condition holds
0 -> do { $ + 1 } while ($ < 5)
# Result: 5# String accumulation
"" -> do { "{$}x" } while (.len < 3)
# Result: "xxx"Pipe-Seeded Do-While Loop
Pipe a seed value to prime the accumulator $ before the first iteration:
0 -> do { $ + 1 } while ($ < 3)
# Result: 3"" -> do { "{$}!" } while (.len < 4)
# Result: "!!!!"When to Use
- While
while (condition) do { body }: condition checked BEFORE body (may execute 0 times) - Do-while
do { body } while (condition): condition checked AFTER body (executes at least once)
Retry Pattern
Do-while is ideal for retry patterns:
use<ext:app> => $app
do(limit: 5) {
$app.prompt("Perform operation")
} while (.contains("RETRY"))
# Loop exits when result doesn't contain RETRYIteration Limit
0 -> do(limit: 100) { $ + 1 } while ($ < 10)
# Result: 10Break
Exit a loop early. A while or do loop yields the value piped to break, or the current $ if break is bare. seq and acc yield the results collected before the breaking element and discard the piped value.
Syntax
break # exit with current $
$value -> break # exit with value (while/do; seq and acc discard it)In seq Loop
[1, 2, 3, 4, 5] -> seq({
($ > 3) ? ("found {$}" -> break)
$
})
# Result: list[1, 2, 3]seq discards the piped "found 4" string and yields the results collected before the break.
In While Loop
0 -> while (true) do {
($ + 1) -> ($ > 3) ? break ! $
}
# Result: 4Break Value
In seq, break returns partial results collected before the break:
["a", "b", "STOP", "c"] -> seq({
($ == "STOP") ? break
$
})
# Result: list["a", "b"]acc also catches break and returns the partial results list collected up to that point.
Break Not Allowed
break is not supported in fan, filter, or fold:
[1, 2, 3] -> fan({ break }) # ERROR: break not supported in fanReturn
Exit a block early. Returns the value piped to return, or current $ if bare.
Syntax
return # exit with current $
$value -> return # exit with valueIn Blocks
5 => $x
($x > 3) ? ("big" -> return)
"small"
# Result: "big"Multi-Phase Pipeline
"content" => $content
# "Read failed" when $content contains ERROR
$content -> .contains("ERROR") ? ("Read failed" -> return)
"processed: {$content}"
# Result: "processed: content"Assert
Validate conditions during execution. Halts the script with a clear error if the assertion fails.
Syntax
assert condition
assert condition "error message"
$value -> assert conditionBasic Usage
Assert halts execution when the condition evaluates to false. If the condition is true, the piped value passes through unchanged.
# Passes: the condition is true
5 -> assert ($ > 0)
# Result: 5-1 -> assert ($ > 0) # Error: Assertion failedCustom Error Messages
Provide a descriptive message as the second argument:
"" -> assert !.empty "Empty input not allowed"
# Error: Empty input not allowed[1, 2, 3] -> assert (.len > 0) "List cannot be empty"
# Result: list[1, 2, 3]Type Assertions
Combine with type checks to validate input:
# Passes: the type check succeeds
"hello" -> assert $:?string
# Result: "hello"42 -> assert $:?string # Error: Assertion failedIn Loops
Assert validates each iteration. The loop halts on the first failing assertion:
[1, 2, 3] -> seq({
assert ($ > 0) "Must be positive"
})
# Result: list[1, 2, 3][1, 0, 3] -> seq({
assert ($ > 0) "Must be positive"
})
# Error: Must be positivePipe Passthrough
When the assertion passes, the piped value flows through unchanged:
"data" => $input
$input
-> assert !.empty "Input required"
-> .upper
-> assert (.len > 0) "Processed value required"
# Result: "DATA"Error Behavior
Assert halts when:
| Condition | Error Code | Message |
|---|---|---|
Condition is false | RILL-R015 | Custom message or “Assertion failed” |
| Condition is not boolean | RILL-R002 | “assert requires boolean condition, got {type}” |
# Non-boolean condition
"test" -> assert $ # Error: assert requires boolean condition, got string
# Failed assertion with location
-1 -> assert ($ > 0) # Error: Assertion failedValidation Patterns
Guard clauses at function start:
fn(data) {
assert $data:?list "Expected list"
assert !$data.empty "List cannot be empty"
$data -> seq({ $ * 2 })
} => $process
trueMulti-step validation:
use<ext:app> => $app
$input
-> assert $:?string "Input must be string"
-> .trim
-> assert !.empty "Trimmed input cannot be empty"
-> assert (.len >= 5) "Input too short (min 5 chars)"
-> $app.process()Error
Halt execution immediately with a custom error message. Unlike assert, which validates a condition, error always halts.
Syntax
error "message" # Direct form
$value -> error # Piped formBasic Usage
Use error with a string literal to halt with a message:
error "Something went wrong"
# Halts execution with: Something went wrongThe message argument accepts string literals or piped string values (see Piped Form below).
Piped Form
Pipe a string value to error to use dynamic error messages:
"Operation failed" -> error
# Halts with: Operation failedThe piped value must be a string:
"Error occurred" => $msg
$msg -> error
# Halts with: Error occurred
"Status: " => $prefix
404 => $code
"{$prefix}{$code}" -> error
# Halts with: Status: 404Piping non-string values throws a type error:
42 -> error # Error: error requires string, got numberString Interpolation
Use interpolation for dynamic error messages:
404 => $code
error "Unexpected status: {$code}"
# Halts with: Unexpected status: 4043 => $step
"timeout" => $reason
error "Failed at step {$step}: {$reason}"
# Halts with: Failed at step 3: timeoutConditional Usage
Combine error with conditionals for guard clauses:
5 => $x
($x < 0) ? { error "Number must be non-negative" } ! $x
# Result: 5$data -> .empty ? { error "Data cannot be empty" } ! $data
# Proceeds with $data if not emptyIn Blocks
Use error in blocks for multi-step validation:
fn(age) {
($age < 0) ? { error "Age cannot be negative: {$age}" }
($age > 150) ? { error "Age out of range: {$age}" }
"Valid age: {$age}"
} => $validate_age
trueError Behavior
Error halts with RILL-R016:
| Pattern | Halts With | Message Source |
|---|---|---|
error "msg" | RILL-R016 | String literal |
$val -> error | RILL-R016 | Piped value (must be string) |
error "" | RILL-R016 | Empty message |
error 123 | Parse error | RILL-P004 |
All error responses include the source location from the error statement.
Multiline Messages
Use triple-quoted strings for formatted error messages:
error """
Error occurred:
- Line 1
- Line 2
"""Comparison with Assert
| Statement | Condition | Behavior |
|---|---|---|
assert cond "msg" | Validates condition | Halts if condition is false, passes through if true |
error "msg" | None | Always halts with message |
Use assert when you need to validate a condition. Use error when you’ve already determined that execution cannot continue.
In Loops
Error halts the loop immediately:
[1, 2, 3] -> seq({
($ == 2) ? { error "Halted at 2" }
$ * 2
})
# Halts on second iteration with: Halted at 2Pass
The pass keyword returns the current pipe value ($) unchanged. Use it for explicit identity pass-through in conditional branches and dict values.
In Conditionals
Use pass when one branch should preserve the piped value:
"input" -> .contains("in") ? pass ! "fallback"
# Result: "input""data" -> .empty ? { error "Empty input" } ! pass
# Result: "data"In Dict Values
Use pass to include the piped value in dict construction:
"success" -> { [status: pass, code: 0] }
# Result: dict[code: 0, status: "success"]In Collection Operators
Preserve elements conditionally:
[1, -2, 3, -4] -> fan({ ($ > 0) ? pass ! 0 })
# Result: list[1, 0, 3, 0]Why Use Pass?
The pass keyword provides clearer intent than bare $:
# Less clear - what does $ mean here?
$cond ? do_something() ! $
# More explicit - reader knows this is intentional no-op
$cond ? do_something() ! passPass Behavior
| Pattern | Returns | Context |
|---|---|---|
cond ? pass ! alt | $ if true, alt if false | Conditional branch |
cond ? alt ! pass | alt if true, $ if false | Conditional branch |
[key: pass] | Dict with $ as value | Dict construction |
-> { pass } | $ | Block body |
Note: pass requires pipe context. Using pass without $ bound throws an error (RILL-R005).
Pass Body Forms
The body forms run a block for side effects, then pass the original pipe value through unchanged. The block’s result is always discarded.
| Form | Suppresses catchable halts? |
|---|---|
pass { body } | No — halts in body propagate normally |
pass(ignore_halts: true) { body } | Yes — catchable halts in body are suppressed; the pipe value flows through |
5 -> pass { log($) }
# Logs 5; result is 5range(1, 4) -> seq({ $ * 10 }) -> pass { log($) }
# Logs the list; result is [10, 20, 30]10 -> pass(ignore_halts: true) { 1 / 0 }
# Result: 10 (body halt suppressed)pass accepts the bool options ignore_halts and async. An unknown option or a non-bool value halts #TYPE_MISMATCH, and a spread that repeats a written option halts #INVALID_INPUT. The old form pass<on_error: #IGNORE> is a parse error (RILL-P025). Non-catchable halts (for example error and assert) and ControlSignal (break, return) always propagate out of either body form. See Collection Slicing for the full reference.
Operational Recovery with guard
guard { body } executes its body. When the body raises a catchable halt (a runtime error such as division by zero, or a failing extension call), guard replaces the halt with an invalid value instead of stopping execution. Halts from non-catchable sources (for example error, assert, and a halt inside a module loaded by use<>) are never caught and stop the script. The invalid value carries a :atom value identifying the failure.
use<ext:app> => $app
guard { $app.fetch("https://api.example.com/data") } => $result
$result.? ? $result.data ! error "fetch failed: {$result.!}"The .? operator tests whether $result is valid. The .!code probe reads the error atom when it is not.
Invalid Value
An invalid value is a first-class rill value that carries a :atom value. It is not an exception. Capture, ??, and the .! and .? probes handle it without halting; using it in a pipe, an operator, an interpolation, or a collection literal halts. See Access vs Non-Access.
use<ext:app> => $app
guard { $app.risky_call() } => $r
$r.!code # #ok if valid, else an error code such as #TIMEOUT
$r.! # bool: true if invalid
$r.? # bool: true if validUsing an invalid value in a pipe, an operator, an interpolation, or a collection literal halts execution. Test with .? before use. See Access vs Non-Access.
See Error Handling for full patterns and Error Reference for error codes. The atoms that serve as codes are listed in Built-in Atoms and the Core Error Set.
Bounded Retry with retry(attempts: N)
retry(attempts: N) { body } runs its body up to N times. Each attempt that raises a catchable halt triggers the next attempt. The result is the first successful value, or the final invalid value when all attempts halt.
use<ext:app> => $app
retry(attempts: 3) { $app.fetch("https://api.example.com/data") } => $resultretry is strictly bounded; N must be a written positive integer literal. A variable, a computed value, or any spread in retry(...) is a parse error (RILL-P004), and omitting attempts halts #TYPE_MISMATCH. retry catches the same catchable halts as guard; non-catchable halts (for example error and assert) propagate without retry.
use<ext:app> => $app
retry(attempts: 3) {
guard { $app.fetch("https://api.example.com/data") }
} => $result
$result.? ? $result ! error "all retries failed: {$result.!}"When to Use retry vs. do-while
| Pattern | Use when |
|---|---|
retry(attempts: N) { guard { ... } } | Fixed maximum attempts, automatic backoff not needed |
do { } while (cond) | Custom retry logic, delay, or condition-based exit |
See Error Handling for retry with backoff patterns.
Timeout Blocks
Timeout blocks bound the execution time of a body. On expiry, the body is cancelled and the block raises a catchable halt. Wrap with guard to convert the halt into an invalid value, then use ?? for a fallback.
Two limits are available, singly or together:
| Option | Bounds | Expiry atom |
|---|---|---|
total: duration | Wall-time from block entry | #RILL_R082 |
idle: duration | Inactivity: time since the last stream chunk or host call return | #RILL_R083 |
One head may carry both limits, in either order. The first limit to fire ends the body, and the halt carries that limit’s atom. A repeated key is a parse error (RILL-P027). timeout() with neither limit arms nothing and has no effect; the checker reports it as TIMEOUT_TRIVIAL. timeout(...$policy) supplies the limits from a dict; a spread field that repeats a written limit halts #INVALID_INPUT. The old form timeout<total: d> is a parse error (RILL-P025).
timeout(total: duration("5s"), idle: duration("500ms")) {
$stream -> seq({ $ })
}Wall-Time Bound (total)
use<ext:app> => $app
timeout(total: duration("500ms")) {
$app.fetch("https://api.example.com/data")
}The body must finish within 500 ms. If it does not, the block aborts the body and raises a catchable halt carrying #RILL_R082. Wrap with guard to convert it into an invalid value.
Inactivity Bound (idle)
timeout(idle: duration("200ms")) {
$stream -> seq({ $ })
}The idle timer restarts each time a stream chunk arrives in the body or a host function call returns, and the restart reaches the idle limit of every enclosing timeout. A body doing neither, such as a pure computation, counts as idle. If 200 ms pass with no activity, the block aborts and raises a catchable halt carrying #RILL_R083. Wrap with guard to surface the halt as an invalid value.
Duration Argument
The duration expression must evaluate to a duration value. A non-duration argument or an unknown option halts with #TYPE_MISMATCH. A duration with a months part (duration("1mo"), duration("1y")), which has no fixed length, halts #INVALID_INPUT, as does a total or idle limit above 2147483647 ms, about 24.8 days:
# Error: #TYPE_MISMATCH — total must be a duration value
timeout(total: 500) { "x" }See Duration for the ways to construct a duration value.
Recover from expiry with guard and ??; see Timeout Recovery.
Nesting
Timeout blocks may be nested. The outer timer fires independently of the inner timer:
use<ext:app> => $app
timeout(total: duration("1s")) {
timeout(total: duration("200ms")) {
$app.fetch("https://api.example.com/fast")
}
}When the outer timer fires before the inner body completes, the outer expiry takes precedence. The inner expiry is confined to the inner block’s scope. Each timeout block creates a scoped AbortController that chains to ctx.signal; when the timer fires the controller aborts, halting cooperating host functions. Expiry also stops CPU-bound bodies within roughly the yield interval plus the current step, because evaluation yields to the event loop periodically; a single synchronous built-in operation finishes first. The RILL_R010 iteration ceiling (10,000 elements) applies inside timeout bodies regardless of timeout state.
Control Flow Summary
| Statement | Scope | Effect |
|---|---|---|
break | Loop | Exit loop; while/do yield current $, seq/acc yield results so far |
$val -> break | Loop | Exit loop; while/do yield $val, seq/acc discard it |
return | Block/Script | Exit block or script with current $ |
$val -> return | Block/Script | Exit block or script with value |
pass | Any | Returns current $ unchanged |
pass { body } | Pipe stage | Run body for side effects; pipe value unchanged; halts propagate |
pass(ignore_halts: true) { body } | Pipe stage | Run body; suppresses catchable halts in body; pipe value unchanged |
assert cond | Any | Halt if condition false, pass through on success |
assert cond "msg" | Any | Halt with custom message if condition false |
error "msg" | Any | Always halt with error message |
$val -> error | Any | Always halt with piped error message (must be string) |
guard { body } | Any | Replace halt with invalid value |
retry(attempts: N) { body } | Any | Retry up to N times on caught halt |
timeout(total: d, idle: d) { body } | Block | Abort body on the first limit to fire; catchable halt #RILL_R082 (total) or #RILL_R083 (idle); use guard to recover |
Patterns
Guard Clauses
Exit early on invalid conditions (assumes host provides error()):
use<ext:app> => $app
fn(data) {
$data -> .empty ? $app.error("Empty input")
$data -> :?list ? $ ! $app.error("Expected list")
$data -> seq({ $ * 2 })
} => $processRetry with Limit
use<ext:app> => $app
do(limit: 3) {
$app.prompt("Try operation")
} while (.contains("RETRY"))
.contains("SUCCESS") ? [0, "Done"] ! list[1, "Failed"]State Machine
"start" -> while ($ != "done") do {
($ == "start") ? "processing" ! ($ == "processing") ? "validating" ! ($ == "validating") ? "done" ! $
}
# Walks through states: start -> processing -> validating -> doneFind First Match
seq discards the value piped to break, so it cannot return the match. Filter, then take the head.
list[1, 2, 3, 4, 5] -> filter({ $ > 3 }) -> .head
# Result: 4Loop Syntax Migration
rill previously used @ as the loop operator with ^(limit: N) annotations. The current syntax uses while/do keywords with the do(limit: N) construct option.
| Old syntax | New syntax |
|---|---|
initial -> (cond) @ { body } | initial -> while (cond) do { body } |
initial -> @ { body } ? (cond) | initial -> do { body } while (cond) |
initial -> (cond) @ ^(limit: N) { body } | initial -> while (cond) do(limit: N) { body } |
initial -> @ ^(limit: N) { body } ? (cond) | initial -> do(limit: N) { body } while (cond) |
See CHANGELOG.md for the full change history.
See Also
- Variables: Scope rules and
$binding - Collections:
seq,fan,filter,fold,acciteration - Operators: Comparison and logical operators
- Error Handling:
#RILL_R082and#RILL_R083recovery patterns;guard,??, and atom inspection - Reference: Quick reference tables