---
title: Expressions and dispatch
description: Operator precedence, built-in functions, narrowing, transaction
  dispatch and envelope writes accepted by the compiler.
url: https://docs.rastok.com/reference/expressions
source_revision: v0.2.0-alpha
---

# Expressions and dispatch

An expression reads its declared inputs and returns a value. Dispatch selects
the statements of an Operator transaction. Neither performs external I/O;
Connectors own that boundary.

## Operators

Rows are ordered from highest to lowest precedence. Parentheses select an
explicit grouping. Operators at the same arithmetic or comparison level
associate left to right; the conditional's false branch associates right.

| Level | Syntax | Rule |
|---|---|---|
| Access and narrowing | `data.name`, `(flag ? left : right).name`, `items[index]`, `value as T` | A named or computed receiver exposes the same declared fields; indexes require a checked collection |
| Unary | `!value`, `-value` | Boolean negation; numeric or duration negation |
| Multiplication | `*`, `/`, `%` | Numeric operations in the operands' common integer or floating type |
| Addition | `+`, `-` | Numeric operations in the common type, string concatenation, supported timestamp/duration arithmetic |
| Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`, `is T` | Equality, ordering, membership and type/case tests |
| Conjunction | `a && b` | Short-circuits when `a` is false |
| Disjunction | `a \|\| b` | Short-circuits when `a` is true |
| Conditional | `test ? yes : no` | Evaluates only the selected branch |

`"red" in ["red", "blue"]` is true: an array tests its elements.
`"red" in {"color": "red"}` is false: a map tests its keys, so
`"color" in {"color": "red"}` is true. Neither form introduces an iteration variable.

An unsupported operand combination reports the written operator and types,
for example `` `+` does not accept array<string> and array<string> ``. List
concatenation with `+` is not available in this version. Optional element
types appear as `array<string?>` in type refusals.

For an optional input carrying null, `data == null` is true and
`data != null` is false. Whole inputs, optional fields and state cells
follow the same comparison rule, including in guards and conditionals.

### Numeric operands in this alpha

The [numeric type table](/reference/types.md#numeric-types) lists source names,
representations and the operations each family supports. A literal first
tries the other operand's type. Otherwise both values need a common type:
`int + double` computes in `double`, but `long + double` is refused because
not every `long` fits. Arithmetic and ordering on `decimal` and
`decimal(p,s)` are not defined. For money, compute in integer minor units
(cents) and keep the exact decimal for carrying and projection.

Each operation on two `float` values rounds its result to binary32 before
the next operation. A `double` uses binary64.

If `u` is a `uint` holding 7, `u == 7` is true and `3 < u` is true:
the literal takes the other operand's integer type if it fits. The rule
also applies across the arms of a conditional: for a `long` named `n`,
`ready ? n : 1` and `ready ? 1 : n` both return a `long`. Comparing a
calculated `int` or `long` with a `uint` uses `long`. A signed integer and
an `ulong` have no common integer type. With `u: uint?`, `u == 7` still tests for
seven; it is false when `u` is null. An `int` compares with a `double`
as a `double`, and every integer compares with a `decimal` as a `decimal`.
A `long` or `decimal` and a `double` have no common type. Use a checked
conversion (`as?`) and handle absence to compare a particular value.
In a `decimal` position, `(7u as decimal) == decimal("7.00")` is true.
Lists, records, map values and Lab expectations use the same rule.
Comparing does not change what you see: `string(decimal("7.0"))`
returns `"7.0"` and `string(decimal("7.00"))` returns `"7.00"`.

`value as T` with `T` a declared `decimal(p,s)` (for example
`type Price = decimal(18,2)`) accepts an exact integer or `decimal` that fits.
`7 as Price` produces exactly `7.00`; exceeding the declared precision or
discarding non-zero digits is a narrowing fault, never rounding. A
`decimal("…")` literal is itself a `decimal`, so a Lab expectation against
a `Price` port can use `expect app.out == { b = decimal("2.50") as Price }`.

Numbers carried by `variant` compare by value: a signed seven, an unsigned
seven and an exact decimal `7.00` are equal. A binary floating value meets
an exact number through its shortest decimal rendering, not a tolerance.

For a JSON number in a `variant`, `as?` checks the carried value: seven
converts to `double`, and 19.99 converts to `decimal(10,2)`. `is` tests
the carrier and never performs the conversion.

Integer overflow and integer division by zero are evaluation faults. An index,
map key or narrowing that can fail refuses at check; `[?i]`, `.?k` and `as?`
return an optional value to test or default. A fault commits no input consumption,
state change or emission from that transaction. Expected domain rejection
must be represented by an authored branch and output.

Expressions are limited to 128 nesting levels. The serialized plan has a
separate 256-level reader bound; nested values can reach it even when the
expression itself fits.

## Functions and contextual references

Empty collections use the type expected at their position. Without one,
`[]` is `array<variant>` and `{:}` is `map<string,variant>`, including in a
binding or an inferred struct field. A destination requiring more precise
elements refuses that binding with `E-PORT-TYPE`: declare
`val members: array<string> = []` or `var counts: map<string, int> = {:}`.
Nonempty collections infer their type from their elements. Numeric elements
meet at their common type; when the elements have no common type, they
infer `variant`. `{}` is a struct, never an empty map.

At a typed position, each list element and each map value is checked
individually. For example, `[null, data]` fits `array<string?>` when `data`
is `string`. A declared `array<decimal>` can hold a whole decimal and a
fraction even when their precisions do not fit in a single fixed decimal.
The same rule applies to both arms of a conditional and to the present
value and the fallback of `.orValue()`. Without an expected type,
`[null, "a"]` remains `array<variant>`.

`{:}` also works inside expressions: `size({:})` is `0`, and map values
and list elements may contain an empty map.

| Signature | Result | Availability and constraints |
|---|---|---|
| `s.contains(t)` | `bool` | Tests whether the string `t` occurs in the string `s` |
| `s.startsWith(t)` | `bool` | Tests the exact prefix, including an empty one |
| `s.endsWith(t)` | `bool` | Tests the exact suffix, without case folding |
| `size(string \| array<byte> \| array<T> \| map<K,V> \| variant)` | `int` | Unicode character count for strings, byte count for byte arrays, entry count otherwise |
| `has(object.member)` | `bool` | Final-member presence on a closed struct or string-keyed map; present null is true; only dotted selection |
| `now()` | `timestamp` | One transaction-fixed civil instant, derived from the run origin and logical time; handler context only |
| `duration(string)` | `duration?` for runtime text, `duration` for a valid constant | Units `h`, `m`, `s`, `ms`, `us`, `ns`, with an optional leading minus. Components can be combined and fractional, but each must resolve to whole nanoseconds. No `min`, `d` or `w`. |
| `timestamp(string)` | `timestamp?` for runtime input | RFC 3339 UTC spelling ending in `Z`; an unsupported offset or invalid date yields null |
| `decimal(string)` | `decimal?` for runtime input | Exact decimal at its written scale, with no binary-float conversion |
| `string(x)` | `string` | Renders a string, bool, integer, exact number, float, UTC timestamp, duration or enum symbol. Narrow optional and variant values first. |
| `asset(path)` or `asset(path, content_type)` | `array<byte>` | Build-time file contents; the second argument is for a whole-payload position and sets its content type |
| `env(name)` | Boot reference | Admitted at the HttpClient URL setting, resolved by the deployment profile |
| `secret(name)` | Boot reference | Admitted at HttpClient `auth_bearer`; no raw secret value in graph data |

`duration("4.1ms")` and `duration("4100us")` are equal. A fraction such as
`0.1ns` is refused at check for a constant and yields null for a runtime string.
For all four string constructors a valid constant keeps the ordinary result
type. A malformed constant is an error even inside a reaction.
For a declared decimal type `Price`, use `decimal(string(x)) as? Price` to
recover the same value and type.

`env` and `secret` are references, not evaluator functions. Other sites refuse.
`has` does not establish the value's type: use `is` before reading it as a
number or another narrower type. The receiver still has to be evaluable.
`now` has no arguments and is unavailable in keys, settings or boot values.

## Narrowing and dispatch

| Form | Selection | Requirement |
|---|---|---|
| `value is T` | Tests a type or tagged case | A positive fact narrows the right side of `&&`, a conditional's true branch, a guarded handler or a guarded match arm; the narrowed value can be used directly, without repeating `as T`. Assigning its state cell or the cell containing its path ends the fact for subsequent statements, which see the declared type again |
| `value as T` | Proven conversion | The types fit, a constant converts exactly, or an `is` or closed-case arm proves this path |
| `value as? T` | Optional conversion | A mismatch returns null; an ambiguous or malformed discriminator is still a fault |
| `rows[?i]`, `entries[?key]`, `entries.?name` | Optional lookup | Returns null for an absent receiver, an out-of-range index or a missing key |
| `row.?name` | Optional struct field | The field must be declared; a null receiver gives null |
| `result.orValue(default)` | Default for `T?` | Both numeric choices must fit a declared result type; otherwise their common type is inferred. The default runs only when the result is absent. For a `uint?`, `.orValue(3)` and `.orValue(3u)` are equivalent. |
| `match value { Case => ... }` | Closed match | Tagged union, enum or bool; exhaustive, disjoint case sets. A single-case arm exposes the matched path's payload fields; the whole value keeps its case |
| `match { predicate => ...; _ => ... }` | Ordered predicates | First true predicate wins; fallback is mandatory |
| `on in where predicate { ... }` | Single-input filter | False consumes the input and emits nothing |
| `on (a, b) where predicate ...` | Join candidate selection | False consumes nothing; bounded waiting is covered in [Instances, state and time](/guide/06-instances-state-and-time.md) |

A positive `data is Line` branch can construct an output record with
`{ id = data.id }`: the field keeps the type that `Line` declares.

A dynamic string may be too long for `string(3)?`. Use
`data as? string(3)` and handle null. For a narrower array element,
check the element before constructing the array.

With an `array<long>?` destination, `data.c ? [1] : null` yields the
declared list or null. The same rule applies to a map literal.

Between numeric types, `as?` returns null if the value would change. A
binary float is worth the number shown by its shortest rendering:
`0.1 as? decimal` gives the exact number 0.1, while `7.5 as? int` gives
null. A float also accepts an exactly representable value even if it displays
fewer digits: `4.099999904632568359375 as float` displays `4.1`. A literal
that fits `double` and whose resulting binary64 value is exact in `float`
also fits: `0.10000000149011612 as float` displays `0.1`. A declared
decimal can be the target directly: `n as? decimal(5,2)`.

For a `map<string,variant>`, `m[?k]` returns the stored value or null.
Use `(m[?k] as? string).orValue("missing")` if you need a string even
when the key is missing or the stored value is not a string.

A match is the final control form of its block or arm. Only pure `val`
declarations precede it. Dispatch permits at most 32 nested decisions,
including a single-port `where`. A `variant` must be narrowed before member
or index access. A negative test or disjunction supplies no inferred positive
type fact.

Inside `Stored => { ... }`, a match on `data` permits `data.name` when
`Stored` declares that field. `out = data` and `out = .` still emit the
complete `Stored { ... }` value. Several cases in one arm do not expose
case-specific fields. Assigning the matched state cell ends the selection.

Later `is` tests can read paths narrowed by earlier tests, for example
`data is Booked && data.receipt is Receipt && data.receipt.note is string`.
Each test is evaluated only after the preceding tests succeed.

After a type test, fields, indexes and `has` read the selected value of an
input just as they read a state cell. This also applies after `val copy = data`.
Copying or passing the value without reading its structure does not decode
it; type tests and conversions still use its retained union branch.

For a tagged union `Event` with cases `Opened` and `Closed`, an `Event?`
value satisfies `value is Event` whenever either case is present. It
satisfies `value is Opened` only for that case. Both tests are false for
null. After a successful case test, its payload fields can be read.

A struct assigned to a declared type also constructs any optional fields
that the destination requires. You can bind an inferred struct first and
then use it in a typed field or output; the original binding keeps its type.

Route selection is separate: `source -> match { Case -> target }` chooses
among declared destinations using a tag, enum or bool. Its arms contain
destinations, not expressions. A simple route may coexist with a match,
but duplicate destinations for one case refuse.

## Fan-out and emission

The shipped fan-out is bounded by the graph and the selected match arm.
There is no collection-iteration statement in that arm.

| Form | Result |
|---|---|
| `source -> { left; right }` | One emitted envelope delivered along two declared edges |
| `(left, right) = data` | Evaluate once, then emit a distinct ordered envelope on each output |
| `(left, right) = (first, second)` | One value per named output, committed together |
| `out = .` | Re-emit the exact single input envelope |
| `out = nothing` or `nothing` | No emission |
| `out = { count = 1 }` | New structured data, inherited metadata |
| `out = { data = replacement, meta.app.label = "checked" }` | New payload plus explicit metadata writes |

Emission order within each port and transaction contributes to identity.
An edge fan-out does not duplicate the emission itself. Iteration over state
uses [Loop](/guide/07-loops-and-retries.md), whose manager admits subsequent
applications outside the spatial DAG.

## Envelope fields and bindings

On a struct port, `out = { data = data; meta.app.tag = "copy" }` copies
the input payload and sets metadata. A field named `data` inside a
payload struct is written under the outer `data` root.

| Surface | Read | Write |
|---|---|---|
| `data` | Payload of the current single input | Construct a new output payload or checked patch |
| `meta.sys.id`, `parent_id`, `origin_id`, `graph_version` | Runtime identity and version fields | Runtime only, including in the Lab |
| `meta.app.*` | A required read has the field type inferred from graph-authored writes; no cast is needed | Declared-by-use application metadata; conflicting types refuse |
| `meta.ext.*` | Contract-declared boundary context | Declared fields only; the payload/content-type coupling remains enforced |
| `instance.key` | Selected key of this owner, with fields for a struct key | Read-only in handlers, owner bindings and instance-bound settings; not in its own definition or an unkeyed child |
| `Loop.state` | Envelope admitted to the current Loop application | Replaced through a manager command, not mutated directly |
| `<port>.data`, `<port>.meta` | Named inputs in a join | Emissions select a named source explicitly |

In this build a metadata leaf is a scalar (`int`, not `uint`; no duration
or timestamp) or an array of scalars.
The `app` and `ext` namespaces have prefix-free field names. Heavy or nested
payload structures belong in `data`. A Lab cannot introduce application
metadata fields absent from the production graph.

`val name = value` is immutable and lexical. Unit/App constants can be
referenced by Lab declarations; instance-level values can use that owner's
key and enclosing immutable values.

`var name: Type = value` is mutable Operator state for one instance
generation. Its initial value is required, even when the type allows null.
Inside a handler an assignment takes effect at once: later
statements read the new value. The change is committed with the
transaction; a faulted transaction keeps the previous value. Children do
not inherit it.

## Tagged frontends

| Form | Result | Boundary |
|---|---|---|
| `json! <JSON value>` | `variant` | One complete JSON value; duplicate keys refuse. A number must fit `long`, `ulong` or `double` without loss. |
| `string! { ... }` | `string` | Verbatim text, closing-delimiter margin, no interpolation |
| `base64! { ... }` | `array<byte>` | Padded standard base64; whitespace ignored |

The name and `!` are adjacent. A frontend fills a complete value position,
not an expression atom. Bind its result before combining it with arithmetic.
`base64!("image/png") { ... }` may also declare content type in a whole-payload
position.

## Specified, not shipped

| Item | Specification |
|---|---|
| Regular expression matching (`s.matches(pattern)`) | Not part of the three string predicates in D-2026-11-28-1 |
| Per-item fan-out (`foreach` is reserved); `for item in` is not accepted | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), reserved-keyword section |
| Expression macros `exists`, `exists_one`, `all`, `map` and `filter` | [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md), expression production; current subset in [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1 |
| Array concatenation with `+` | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1.1; use a list literal for known elements. |
| jq, SQL and additional registered guest-language implementations | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §§2–3 |
| `map<string, array<scalar>>` metadata leaves | [`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) §0 |
| Unit/App boot values using `env` or `secret` outside the declared settings | [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md) §1 |

Sources: [`docs/spec/expressions.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/expressions.md), [`docs/spec/grammar.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/grammar.md),
[`docs/spec/envelope.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/envelope.md) and [`docs/spec/execution-model.md`](https://github.com/rastok-io/rastok/blob/v0.2.0-alpha/docs/spec/execution-model.md) §1.1.
