Open App Definition (OAD) 0.2: Expressions#
Status: working draft.
The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT and MAY are to be read as in RFC 2119.
This chapter defines the expression language used throughout an app definition: in fields marked expression, in dynamic values (strings that start with =), and in paths (core.md, section "Values and expressions"). Its syntax is a subset of the Common Expression Language (CEL) plus template strings. Its values are the JSON data model. Section 15 lists every place where it differs from CEL. Section 17 defines the static types a validator infers to find expressions that are certain to fail, and section 18 defines the pattern dialect used by matches and by a type's pattern.
Expressions are side-effect free, have no user-defined functions, assignment, loops or recursion, and every evaluation runs under a cost budget, so every evaluation terminates.
1. Values#
Every value is one of six kinds:
| Kind | Description |
|---|---|
null |
The null value. |
boolean |
true or false. |
number |
An IEEE 754 binary64 (double) value that is finite. There is a single number kind: an integer is a number with no fractional part. |
string |
A sequence of Unicode code points. |
list |
An ordered sequence of values (a JSON array). |
map |
A set of string keys, each with a value (a JSON object). |
- Numbers. No expression ever produces NaN or an infinity. An operation whose mathematical result is not finite fails with subcode
range. Negative zero is never produced: wherever a result would be negative zero, it is zero. Where this chapter says integer, it means a number with no fractional part. - Strings. Lengths, indexes and positions within strings count Unicode code points, not bytes or UTF-16 code units. Strings are compared by code point. Strings are never normalized:
'é'and'é'are different strings. - String length limit. A string built by
+, a template,t,join,replace,padStart,padEnd,upper,lower, orstring()of a list or map MUST NOT exceed 1,048,576 code points. An operation that would build a longer string fails with subcodebudget. Where the length of the result can be computed from the operands (+, templates,t,join,padStart,padEnd, and an upper bound forreplace), an implementation MUST detect this before building the string. Every other operation returns either a string of small fixed length (such as a formatted number or date) or one no longer than one of its string operands. Strings in the scope are not limited; work on a long string is paid for by the rules of section 10. - Maps. Keys are strings, and maps are unordered. Every operation that exposes an order of a map's keys (
keys,values,entries, conversion of a map to a string bystring()or a template, and any other place where an order of iteration is observable) MUST use ascending code point order of the keys. For examplekeys({'b': 1, '10': 2, '9': 3})is['10', '9', 'b']. The order of members in a map an evaluation returns to its host is not significant. - Dates and times are strings in ISO 8601 form (section 9). There is no separate date kind.
A host supplies data to an expression through the scope (section 4). Scope data MUST be made of the six kinds above. Where a host language has an undefined or absent marker distinct from null, a map member holding it MUST be treated as absent. Any other value outside the data model (for example a host object or a function) MUST fail with subcode type when it is used as an operand.
2. Lexical structure#
Expression source is a sequence of Unicode code points.
- Whitespace is space, tab, line feed and carriage return. It separates tokens and is otherwise ignored. There are no comments.
- Identifiers match
[A-Za-z_][A-Za-z0-9_]*. The reserved wordstrue,false,nullandinare not identifiers, except directly after a., where any identifier-shaped word is a member name (sostate.inreads the keyin). - Numbers match
(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?. A number literal MUST NOT be immediately followed by an identifier character. A literal whose value rounds to a non-finite double is a syntax error. Leading zeros, a leading or trailing., hexadecimal forms and suffixes are syntax errors. A negative number is the unary-operator applied to a literal. - Strings are enclosed in
'or". A string MUST NOT contain a raw line feed or carriage return. The escapes are:
| Escape | Meaning |
|---|---|
\\ \' \" \` |
The character itself. |
\n \r \t \b \f \v |
Line feed, carriage return, tab, backspace, form feed, vertical tab. |
\uXXXX |
The code point with exactly four hexadecimal digits. |
\UXXXXXXXX |
The code point with exactly eight hexadecimal digits. |
A \u or \U escape that names a surrogate (U+D800 to U+DFFF) or a value above U+10FFFF is a syntax error, as is any other escape.
- Template strings are enclosed in backticks. They may contain raw line breaks, the escapes above, and
\$, which is a literal$. A${begins an interpolation, which contains one expression and ends at the matching}. A$not followed by{is a literal$. An empty interpolation is a syntax error. Templates may nest inside interpolations. - Punctuators are
== != <= >= && || < > ! ? : + - * / % . , ( ) [ ] { }. A lone=,&or|is a syntax error.
3. Grammar#
expr = cond
cond = or [ "?" expr ":" cond ]
or = and { "||" and }
and = rel { "&&" rel }
rel = add { ( "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" ) add }
add = mul { ( "+" | "-" ) mul }
mul = unary { ( "*" | "/" | "%" ) unary }
unary = ( "!" | "-" ) unary | postfix
postfix = primary { "." NAME [ args ] | "[" expr "]" }
primary = NUMBER | STRING | TEMPLATE | "true" | "false" | "null"
| IDENT [ args ] | "(" expr ")" | list | map
args = "(" [ expr { "," expr } ] ")"
list = "[" [ expr { "," expr } [ "," ] ] "]"
map = "{" [ entry { "," entry } [ "," ] ] "}"
entry = ( STRING | IDENT ) ":" expr
Operators by precedence, lowest first:
| Level | Operators | Associativity |
|---|---|---|
| 1 | ? : |
right |
| 2 | \|\| |
left |
| 3 | && |
left |
| 4 | == != < <= > >= in |
left |
| 5 | + - |
left |
| 6 | * / % |
left |
| 7 | unary ! - |
right (prefix) |
| 8 | .name, [index], f(args), x.f(args) |
left (postfix) |
Further rules that are part of the syntax:
IDENT [ args ]is a function call.x.NAME(args)is a method call: it calls the functionNAMEwithxas its first argument, followed byargs.has,default,let,can,canSendandtare only global calls: written as a method call (x.has(y)), each of them is a syntax error. The list macros (section 7.3) are only method calls.- A map key written as a bare identifier is the literal key name; it is not a variable. Reserved words are not allowed as bare keys. Duplicate keys in one map literal are a syntax error.
has(e)requires exactly one argument, which is a member access or an index expression.default(a, b)requires exactly two arguments.let(n, v, e)requires exactly three arguments, andnis an identifier. A list macro callx.m(v, e)requires exactly two arguments, andvis an identifier. Anything else with those names in those positions is a syntax error.can(a)andcan(a, i)requireato be a string literal.canSend(f, e)andcanSend(f, e, k)requirefandeto be string literals. Any other number or form of arguments tocanorcanSendis a syntax error.t(k)andt(k, v)requirekto be a string literal that is a key (section 8.7: it matches^[A-Za-z][A-Za-z0-9_.]{0,79}$) andv, when present, to be a map literal, whose values are any expressions. Any other number or form of arguments totis a syntax error. A variable or member namedt(item.t, the variable of a list macro or oflet) is not affected: only a call writtent(...)is the function.- When the pattern argument of
matches(the second argument ofmatches(s, p), the only argument ofs.matches(p)) is a string literal, it MUST be a pattern in the dialect of section 18, or the expression is a syntax error. A pattern computed at run time is checked when it is used (section 8.3). - Chained relations parse left to right (
1 < 2 < 3is(1 < 2) < 3, which then fails withtype).
3.1 Limits#
To keep hostile definitions from exhausting a host:
- Source longer than 10000 code points is a syntax error.
- An expression whose nesting depth exceeds 100 is a syntax error. The nesting depth is the height of the syntax tree: a literal, an identifier, an empty list or map, and a template with no interpolations have height 1; every other construct has height one more than its tallest operand, and a parenthesized expression has height one more than its contents. The operands are: the target of a member access; the target and index of an index; the arguments of a call; the receiver and arguments of a method call; the receiver and body of a list macro; the argument of
has; both arguments ofdefault; the value and body oflet; the elements of a list; the values of a map; the interpolations of a template; and the operands of unary, binary and conditional operators. For example((1))has depth 3. Chains of binary operators are not flattened: each operator is one level, so1 + 1 + ... + 1with 101 terms has depth 101 and is rejected.
Implementations MUST reject exactly the expressions these rules reject, so that a definition that parses on one host parses on every host.
4. Scope and identifiers#
An expression is evaluated against a scope: a map from root identifier to value, supplied by the host.
- An identifier that is not bound by an enclosing list macro or
letresolves to the scope member of that name. If the scope has no such member, evaluation fails with subcodeunknownIdentifier. Only the scope's own members count; names inherited from an implementation's object model never resolve. - These root names are reserved for hosts and have the meanings given in
core.md, section "Expression scope":state,input,env,user,event,flows,parts,capabilities,sources,grants,view,item,index,error,output. A host supplies only the roots that apply where the expression is evaluated, together with any local names the definition binds there (as,indexAs,letsteps and slot scope variables). Which names apply at each position is listed invalidation.md, section "Expression scope". - A variable bound by a list macro or by
letis bound only inside the body. Inside the body it shadows any outer name, including reserved roots such asitemand outer macro variables:state.items.map(item, item.price)is valid, anditemthere is the element.
5. Evaluation#
Evaluation is deterministic and has no side effects. The only exceptions are random() and uuid() (section 8.5). The functions of sections 8.6 to 8.8 are deterministic for a given scope, host locale data, table of texts and app state.
- Order. Operands and arguments are evaluated left to right, and all of them are evaluated before the operator or function applies, except where this chapter says otherwise:
&&,||,? :,default,has,letand the list macros. - Errors. An evaluation either produces a value or fails with an error whose
codeisexpression.errorand whosesubcodeis one of those in section 11. The first error raised ends the evaluation unless a construct defined here catches it: onlyhasanddefaultdo, and only formissing(section 7). What a host does with a failed expression is defined incore.md, section "Errors". - Results are values in the data model. Evaluation MUST NOT modify any value in the scope. Lists and maps an expression constructs are new values; values read from the scope may be returned as they are.
- Resources. If an evaluation exhausts a resource of the implementation that this chapter does not otherwise meter (for example stack depth while comparing deeply nested scope data), it MUST fail with subcode
budgetrather than with any other kind of failure.
5.1 Member access and indexing#
x.nameon a map yields the value of keyname. If the map has no such key, it fails withmissing. Ifxisnull, it fails withmissing. On any other kind, it fails withtype.x[k]on a map requires a stringk(elsetype) and behaves likex.k. On a list it requires a numberk(elsetype) that is an integer (elserange). An index out of range (below zero, or not less than the list's size) fails withmissing, notrange, sohasanddefaulttreat an absent element like an absent key. Onnullit fails withmissing. Strings cannot be indexed: usesubstring. On any other kind it fails withtype.- Only a map's own keys are members. In particular
constructor,toStringand__proto__are ordinary keys: absent unless the data contains them.
5.2 Logical and conditional operators#
a && bevaluatesa, which MUST be a boolean (elsetype). Ifaisfalse, the result isfalseandbis not evaluated. Otherwisebis evaluated and MUST be a boolean (elsetype), and is the result.a || bis the same with the roles oftrueandfalseexchanged.!arequires a boolean.c ? a : bevaluatesc, which MUST be a boolean (elsetype), then evaluates and returns only the chosen branch.
There is no truthiness: null, 0, '' and empty collections are never treated as booleans.
5.3 Equality#
a == b is deep structural equality and never fails. Values of different kinds are unequal. Numbers are equal when numerically equal (1 == 1.0, 0 == -0). Strings are equal when they have the same code points. Lists are equal when they have the same size and pairwise equal elements. Maps are equal when they have the same set of keys and equal values for each key. a != b is !(a == b).
5.4 Ordering#
<, <=, > and >= require two numbers or two strings, else they fail with type. Numbers compare numerically. Strings compare lexicographically by code point. ISO 8601 dates and datetimes in the canonical forms of section 9 therefore compare chronologically.
5.5 Membership#
a in b: if b is a list, the result is true when some element equals a (section 5.3). If b is a map, a MUST be a string (else type) and the result is true when b has the key a (a key whose value is null is present). Any other b fails with type.
5.6 Arithmetic#
a + badds two numbers, concatenates two strings, or concatenates two lists into a new list. Any other combination fails withtype; there is no implicit conversion (usestring()or a template).a - b,a * b,a / banda % brequire two numbers (elsetype)./is true division:7 / 2is3.5.%is the remainder of truncating division and has the sign of the dividend:-7 % 3is-1,7.5 % 2is1.5. Division or remainder by zero fails withdivideByZero, including0 / 0.- Unary
-requires a number. - Arithmetic is IEEE 754 binary64 with round-to-nearest-even. A non-finite result fails with
range. A negative zero result is zero.
5.7 Templates and string conversion#
A template evaluates to its literal text with each interpolation replaced by its value converted to a string. Conversion follows string():
null,trueandfalsebecomenull,trueandfalse.- A number becomes the string produced by ECMAScript
Number::toStringin radix 10 (ECMA-262): the shortest decimal that round-trips, without exponent for magnitudes from 1e-6 up to but excluding 1e21 (100,1.5,0.000001), with exponent otherwise (1e+21,1e-7). Zero, including negative zero, is0. - A string is itself.
- A list or map becomes compact JSON text (RFC 8259) with no whitespace, map members in ascending code point order of keys, numbers as above, and strings escaped as follows:
"and\are escaped with a backslash; U+0008, U+0009, U+000A, U+000C and U+000D become\b,\t,\n,\f,\r; other code points below U+0020 become\u00XXwith lowercase hexadecimal digits; everything else, including non-ASCII characters, is written as is.
For text meant for people, use the formatting functions of section 8.6 instead.
6. Dynamic values#
A dynamic value (core.md, section "Values and expressions") is a JSON value in which strings may be expressions:
- A string that starts with
==is a literal string: the first=is removed ("==x"is=x,"=="is=). - Any other string that starts with
=is an expression: the rest of the string is the source."="alone is an expression with empty source, which is a syntax error. - Any other string, and every number, boolean and null, is a literal.
- Arrays and objects are walked recursively. Object keys are never expressions.
A host MUST parse every expression in a dynamic value when it loads the definition, and MUST report a syntax error together with the JSON Pointer (RFC 6901) of the offending string, relative to the dynamic value. Evaluation produces a new value of the same shape. Expressions are evaluated depth first, array elements in index order and object members in ascending code point order of their keys, so every host reports the same first error; each expression is evaluated with its own budget. An evaluation error is reported with the JSON Pointer of the expression that failed.
7. Macros#
Macros are written like calls but control how and whether their arguments are evaluated.
7.1 has(path)#
path is a member access or index chain, such as has(state.form.amount) or has(state.items[0].name). The innermost operand of the chain (usually a root identifier) is evaluated normally, so an unknown root identifier still fails with unknownIdentifier. Then each step is applied in turn:
- If the current value is
null, the result isfalse. - If the step would fail with
missing(an absent key, or a list index out of range), the result isfalse. - Any other error, including
typefor stepping into a number, and any error raised while evaluating an index expression, propagates.
If every step succeeds, the result is true. A path whose final value is null is present: has(state.x) is true when state.x is null.
7.2 default(value, fallback)#
Evaluates value. If that evaluation fails with subcode missing (anywhere inside it), or produces null, the result is the evaluation of fallback. Otherwise the result is the value, and fallback is not evaluated. Errors with any other subcode propagate. default(state.form.note, '') reads an optional field; default(false, true) is false.
7.3 List macros#
A list macro has the form list.m(v, body). list MUST evaluate to a list (else type; maps and strings are not iterated). For each element visited, body is evaluated with the identifier v bound to the element. Elements are visited in order.
| Macro | Result |
|---|---|
l.map(x, e) |
New list of e for each element. |
l.filter(x, p) |
New list of the elements for which p is true. |
l.all(x, p) |
true if p is true for every element. Stops at the first false. true for an empty list. |
l.exists(x, p) |
true if p is true for some element. Stops at the first true. false for an empty list. |
l.find(x, p) |
The first element for which p is true, or null. Stops at the first match. |
l.count(x, p) |
The number of elements for which p is true. |
l.sortBy(x, k) |
New list sorted ascending by key k, stable. |
l.groupBy(x, k) |
Map from each key k to the list of elements with that key, in element order. |
l.indexBy(x, k) |
Map from each key k to the element with that key. When several elements have the same key, the last one is kept. |
l.sumBy(x, e) |
Sum of e over the elements, added left to right. 0 for an empty list. |
l.minBy(x, k) |
The element with the smallest key, the first one on ties, or null for an empty list. |
l.maxBy(x, k) |
The element with the largest key, the first one on ties, or null for an empty list. |
l.distinctBy(x, k) |
New list of the first element for each distinct key (keys compared with section 5.3). |
Predicates (p) MUST be booleans, else type. The keys of sortBy, minBy and maxBy MUST be all numbers or all strings, else type. groupBy and indexBy keys MUST be strings, else type. sumBy values MUST be numbers, else type.
state.answers.indexBy(a, a.itemId) builds a lookup map once; m[item.id] then reads one element without scanning the list again. To visit elements together with their positions, iterate enumerate(list) (section 8.1): enumerate(state.tiles).map(e, {id: e.value.id, pos: e.index}).
7.4 let(name, value, body)#
Evaluates value, then evaluates body with the identifier name bound to the result, and returns the result of body. name is bound only inside body, not inside value, and shadows any outer name there as a list macro variable does (section 4). let names a sub-result once instead of repeating it:
let(limit, state.limits[e.category][0], e.amount > limit.max ? limit.max : e.amount)
let(open, state.tickets.filter(t, t.status == 'open'), size(open) == 0 ? 'none' : open[0].subject)
let calls nest: let(a, 1, let(b, a + 1, a + b)) is 3. An error raised by value propagates and body is not evaluated.
8. Functions#
Every function can be called globally, f(a, b), or as a method on its first argument, a.f(b), except can and canSend, which are global only (section 3). Calling a name that is not a function fails with unknownFunction; this check happens before the arguments are evaluated. Calling with the wrong number of arguments fails with arity, also before the arguments are evaluated. A wrong argument kind fails with type. A right kind with a value the function does not accept fails with range; this includes a non-integer number where an integer is required and a string that is not in the format the function requires. Section 17.5 gives the signature of every function and macro.
8.1 Collections and aggregates#
| Function | Result |
|---|---|
size(x) |
Code points of a string, elements of a list, or keys of a map. |
sum(list) or sum(n, ...) |
Sum of numbers, added left to right. 0 for an empty list. |
avg(list) or avg(n, ...) |
Arithmetic mean, or null for an empty list. |
min(list) or min(v, ...) |
Smallest value, or null for an empty list. Values MUST be all numbers or all strings. |
max(list) or max(v, ...) |
Largest value, or null for an empty list. Same rule as min. |
keys(map) |
List of keys, in ascending code point order. |
values(map) |
List of values, in ascending code point order of their keys. |
entries(map) |
List of { "key": k, "value": v } maps, in ascending code point order of keys. |
merge(a, b) |
New map with the members of both maps. Where both have a key, the value from b is kept. Only the top level is merged. |
compact(map) |
New map with the members whose value is not null. Only the top level is examined. |
reverse(x) |
New list in reverse order, or a string with its code points reversed. |
slice(x, start, end?) |
New list (or string) of the elements from start up to but excluding end (default: the size). Negative indexes count from the end. Indexes are then clamped to the range 0 to size; if end is not greater than start, the result is empty. |
first(list) |
First element, or null when empty. |
last(list) |
Last element, or null when empty. |
flatten(list) |
New list in which each element that is a list is replaced by its elements (one level). |
distinct(list) |
New list of the first occurrence of each distinct element (section 5.3). |
enumerate(list) |
New list of { "index": i, "value": v } maps, one for each element in order, with i counting from 0. |
range(n) |
The list 0, 1, ..., n - 1. n MUST be a non-negative integer (else range). |
contains(x, y) |
For a list: true if some element equals y. For strings: true if y occurs in x. |
indexOf(x, y) |
For a list: the index of the first element equal to y. For strings: the code point index of the first occurrence of y. -1 when not found. |
In the variadic forms, a call with exactly one argument that is a list uses that list; any other call uses its arguments.
merge and compact together build a map with optional members: compact(merge(base, {receipt: input.receipt, note: default(input.note, null)})) drops the members that are null.
8.2 Numbers and conversions#
| Function | Result |
|---|---|
abs(n), floor(n), ceil(n) |
As in mathematics. |
round(n, digits?) |
n rounded to a multiple of 10 to the power -digits (default 0), with ties away from zero. digits is an integer from -15 to 15. The decision is made on the shortest decimal form of n that round-trips, so round(1.005, 2) is 1.01 and round(-2.5) is -3. |
int(x) |
A number truncated toward zero, or a numeric string (as for number) parsed and truncated. |
number(x) |
A number unchanged, or a string parsed as a decimal number matching [+-]?([0-9]+(\.[0-9]*)?\|\.[0-9]+)([eE][+-]?[0-9]+)?, with no surrounding whitespace. Other strings fail with range. |
string(x) |
Conversion as in section 5.7. |
bool(x) |
A boolean unchanged, or the string "true" or "false". Other strings fail with range. |
type(x) |
One of "null", "boolean", "number", "string", "list", "map". |
8.3 Strings#
| Function | Result |
|---|---|
startsWith(s, prefix), endsWith(s, suffix) |
Booleans. |
lower(s), upper(s) |
Full Unicode default case conversion, without locale tailoring (upper('straße') is STRASSE). |
trim(s) |
s without leading and trailing code points that have the Unicode White_Space property. |
split(s, sep) |
List of the parts of s between occurrences of sep. An empty sep splits into code points. split('', ',') is ['']. |
join(list, sep?) |
The elements, which MUST all be strings, joined with sep (default ''). |
replace(s, from, to) |
s with every non-overlapping occurrence of from, scanning left to right, replaced by to. Both are literal text. An empty from fails with range. |
substring(s, start, end?) |
Code points of s selected as in slice. |
padStart(s, length, pad?), padEnd(s, length, pad?) |
s extended to length code points by repeating pad (default ' '), truncating the last repetition. Unchanged if s is already at least length long or pad is empty. |
matches(s, pattern) |
true if some part of s matches pattern, a pattern in the dialect of section 18. Anchor the pattern with ^ and $ to test the whole string. A pattern outside the dialect fails with range. |
join, replace, padStart, padEnd, upper and lower are subject to the string length limit (section 1).
A pattern is a string, so its backslashes are escaped once for the expression's string literal and, inside a JSON document, once more for JSON: the expression matches(input.code, '^[A-Z]{3}\\d{4}$') is written in a definition as "=matches(input.code, '^[A-Z]{3}\\\\d{4}$')". Classes such as [0-9] need no backslash.
8.4 Dates and times#
In this table, date means a calendar date or a datetime, and the result has the same form as the argument unless stated. Formats are defined in section 9.
| Function | Result |
|---|---|
addDays(date, n) |
n (an integer) calendar days later. For a datetime, n times 86400 seconds later. |
addMonths(date, n) |
n (an integer) calendar months later, with the day clamped to the last day of the resulting month: addMonths('2024-01-31', 1) is 2024-02-29. The time of day is kept. |
addDuration(datetime, duration) |
Applies years and months as in addMonths, then weeks and days as 86400 seconds each, then hours, minutes and seconds. A calendar date argument fails with range. |
daysBetween(a, b) |
Integer number of calendar days from a to b (negative if b is earlier). A datetime counts as its UTC calendar date. |
durationBetween(a, b) |
Seconds from a to b, which may be fractional. A calendar date counts as midnight UTC. |
datePart(date, part) |
An integer: year, month (1 to 12), day, weekday (1 = Monday to 7 = Sunday), hour, minute, second (whole seconds). Time parts of a calendar date, and any other part, fail with range. |
startOf(date, unit) |
The first instant of the day, week (starting Monday), month or year containing date. Any other unit fails with range. |
toDate(date) |
The UTC calendar date of a datetime, or a calendar date unchanged. |
seconds(duration) |
The length of a duration in seconds. Durations with a non-zero year or month component have no fixed length and fail with range. |
atTime(date, time, zone?) |
The datetime, in canonical UTC form, at which the clocks in time zone zone show the calendar date date and the time of day time (section 9). zone defaults to env.timezone. A datetime as date fails with range. |
dateIn(datetime, zone?) |
The calendar date in time zone zone at the instant datetime. zone defaults to env.timezone. A calendar date is returned unchanged, and env.timezone is then not read; a zone argument is checked all the same. |
Apart from atTime and dateIn, these functions work in UTC. There is no function for the current time. Hosts expose it as env.now, and the current date in the person's time zone as env.today (core.md, section "Environment").
Time zones. A zone is a time zone name of the IANA time zone database, such as Europe/Paris or UTC, matched exactly (case-sensitive). A name the host does not know fails with range; so does a zone taken from env.timezone when that is not a known name. A local time that occurs twice (when clocks go back) gives the earlier of the two instants. A local time that does not occur (when clocks go forward) is moved forward by the length of the gap: in a zone that moves from 02:00 to 03:00, 02:30 gives the instant shown as 03:30. Hosts use their own copy of the time zone database, so results for instants whose rules changed recently may differ between hosts; conformance vectors use zones and instants whose rules are long settled.
atTime(addDays(state.deadline, -3), '09:00') is nine in the morning, local time, three days before the deadline, as a UTC datetime that a scheduler can use. dateIn(env.now, 'Asia/Tokyo') is today's date in Tokyo.
8.5 Effectful functions#
| Function | Result |
|---|---|
random() |
A number in the range 0 (inclusive) to 1 (exclusive). |
uuid() |
A UUID in lowercase canonical form (8, 4, 4, 4 and 12 hexadecimal digits separated by -). Hosts SHOULD generate random (version 4) UUIDs as defined in RFC 9562. |
These are the only functions whose results are not determined by their arguments, the scope, the host's locale data and the app's state. A host makes them available only where effects are allowed: in step expressions (core.md, section "Execution semantics"; validation.md, section "Expression scope"). Elsewhere, calling either fails with subcode effect. An implementation MUST also fail with effect if the host's source of randomness returns a value outside the stated result.
8.6 Formatting for people#
| Function | Result |
|---|---|
formatNumber(n, options?) |
Text showing the number n. |
formatDate(d, style?) |
Text showing the calendar date or datetime d. |
relativeTime(d) |
Text saying how far the calendar date or datetime d is from now, such as "12 minutes ago" or "in 3 days". |
plural(n, forms) |
The member of forms for the plural category of the number n. |
Their results are for display only. They depend on the host's locale data, so an app MUST NOT parse them, compare them, or store them as data, and two hosts may return different text for the same call. Each reads, from the scope, env.locale (a BCP 47 language tag) and the other env fields named below, exactly as the expression env.locale would read them: a scope without env fails with unknownIdentifier, a missing field with missing, and a field of the wrong kind with type. A host that has no data for env.locale uses the nearest locale it has (such as fr for fr-CA), and otherwise a default of its choosing.
formatNumber(n, options?). options is a map with these optional members; a member whose value is null counts as absent, any other member name fails with range, and a member of the wrong kind fails with type:
| Option | Meaning |
|---|---|
style |
decimal (default), percent, currency or compact. Any other string fails with range. |
currency |
An ISO 4217 code of three uppercase letters A to Z, else range. Defaults to env.currency. Used only with currency style. |
digits |
An integer from 0 to 6 (else range): the number of digits after the decimal separator. |
decimalshowsnwith grouping. Withdigits, exactly that many fraction digits are shown; without it, up to 3, with trailing zeros dropped.percentshowsntimes 100 with a percent sign, withdigitsfraction digits (default 0). The multiplication is exact: it moves the decimal point of the shortest round-trip decimal form ofntwo places, soformatNumber(0.285, {style: 'percent'})shows 29.currencyshowsnas an amount ofcurrency, withdigitsfraction digits, by default the currency's minor unit (2 forUSDandEUR, 0 forJPY; 2 for a code the host does not know). When neithercurrencynorenv.currencygives a code, the number is formatted asdecimalwithdigits(default 2) fraction digits.compactshowsnscaled to the locale's short form, such as1.2Mor12K, with at mostdigitsfraction digits (default 1) in the scaled number.
The number shown is n rounded as round does (ties away from zero, decided on the shortest decimal form) to the number of fraction digits stated, after scaling for percent and compact. A decimal, percent or currency result never uses exponent notation.
formatDate(d, style?). style is short, medium (default), long or time; any other string fails with range. A calendar date is shown as it is, with no time zone. A datetime is first converted to the local date and time in env.timezone (section 8.4). short shows the date in numeric form, medium with an abbreviated month name, and long with the full month name; for a datetime each of them also shows the hour and minute. time shows only the hour and minute of a datetime, and fails with range for a calendar date. Seconds and the time zone are never shown.
relativeTime(d). For a datetime, the difference is durationBetween(env.now, d) in seconds. Its size is expressed in the largest of these units it reaches: year (365 days), month (30 days), week (7 days), day (86400 seconds), hour, minute and second. The count is the size divided by the unit, rounded toward zero. A size under one second is shown as the present moment ("now"). For a calendar date, the difference is daysBetween(env.today, d) in days, expressed in years, months, weeks or days in the same way, and a difference of zero is shown as the present day ("today"). A negative difference is in the past ("3 days ago") and a positive one in the future ("in 3 days"). A host MAY use the locale's words for a count of one day ("yesterday", "tomorrow").
plural(n, forms). forms is a map whose members are strings: other is required, and zero, one, two, few and many are optional. A missing other, or any other member name, fails with range; a member that is not a string fails with type. The result is the member for the cardinal plural category of n in env.locale, as the Unicode CLDR plural rules define it for the shortest decimal form of n, or other when forms has no member for that category. Categories belong to the locale: in English, 0 is in category other, so a zero form is never chosen there; to say something special for none, test n == 0. `${n} ${plural(n, {one: 'check', other: 'checks'})} left` gives "1 check left" and "3 checks left" in English.
What every host shows the same, and what may vary:
| Fixed by this section | Varies with the host's locale data |
|---|---|
| The number after rounding, its sign and its count of fraction digits; the currency; the percentage after scaling. | Digit shapes, grouping and decimal separators, the minus sign, the form and position of the currency symbol and the percent sign, compact scaling and abbreviations. |
The calendar date and local time after conversion to env.timezone; which parts each style shows. |
Month names, the order of the parts, separators, a 12-hour or 24-hour clock. |
For relativeTime, the unit, the count, and whether it is past or future. |
The wording. |
For plural, that the result is one of the strings in forms. |
Which category a number falls in. |
These functions fail with type when n is not a number, d is not a string or options or forms is not a map, and with range when d is not a calendar date or a datetime (section 9).
8.7 Texts of the app#
| Function | Result |
|---|---|
t(key, values?) |
The app's text named key, in the language the host shows, with its blanks filled from the map values. |
An app keeps the texts it shows to people in a table of texts, one table per language; core.md defines the table, its languages and how a host chooses the language it shows. t points at a text of that table from any expression. It may stand wherever an expression may stand. Where its result is stored (in a state entry's initial, by a step, in a notification sent or an audit record), it is stored as a plain string in the language of that moment and does not change when the language changes afterwards.
Keys. A key is an ASCII letter followed by at most 79 ASCII letters, digits, _ or .: it matches ^[A-Za-z][A-Za-z0-9_.]{0,79}$. Case matters. Dots only group keys for a reader; the table is flat.
Entries. The entry of a key is a text, or forms.
- A text is read from its start.
{, a blank name and}is a blank, where a blank name is an ASCII letter or_followed by ASCII letters, digits or_.{{writes one{, and}}writes one}. Any other{or}makes the text malformed. There is no other syntax. The empty text is a text. - Forms are an object
{ "by": name, "forms": { key: text, ... } }with no other member.byis a blank name: the value passed for that blank chooses the form. Every form is a text, and may hold blanks, thebyblank among them. The form keys areother, which is required; the plural category nameszero,one,two,fewandmany;=followed by a finite number exactly asstring(n)writes it (=0,=1,=12,=-1,=1.5); and any other non-empty string that does not begin with=, which is an exact text. The empty key, and a key that begins with=without being=and such a number (=,=1.0,=01,=+1,=-0,=abc), make the entry malformed: they could never be chosen.
What the host gives. An implementation of this chapter evaluates t through a provider of texts the host gives it, as it does can (section 8.8). For a key, the host looks the key up in the app's table for the language it shows, as core.md defines, and answers with four things: the entry; the language of the table the entry was taken from; the locale of the text, which writes its numbers and gives their plural categories; and the direction of the text, ltr or rtl. When the entry is taken from the table of the language shown, the locale of the text is env.locale and its direction is env.direction; when it is taken from another language's table, they are that language's own. A key the host does not know fails with missing. Where the host gives no provider, t fails with effect.
Evaluation. t(key, values) evaluates its arguments (values defaults to {}), asks the host for the entry of key, and then:
- Checks the entry. A malformed entry, in any of its forms, fails with
range, whichever form the values would choose. Validation reports a malformed entry before the app runs (validation.md), so a host meets one only in a table that was not validated. - Chooses the form, for forms. Let
vbe the member ofvaluesnamed byby. Whenvalueshas no such member,tfails withmissing. -vis a number: the form=NwhereNisstring(v); else the form named by the cardinal plural category ofvin the locale of the text, exactly aspluraldefines the category (section 8.6); elseother. A category the language never yields is simply never chosen: in English azeroform is never chosen, and it is not an error. -vis a string: the form whose key equalsv, except that a string never matches the keysother,zero,one,two,fewandmanyor a key that begins with=; elseother. -vistrueorfalse: the formtrueorfalse; elseother. -visnull:other. -vis a list or a map:tfails withtype.
The form is chosen from the value passed, not from the digits its blank then shows. formatNumber shows at most three fraction digits, so 1.0004 is shown as 1 in the form chosen for 1.0004, which in English is other: an app that passes such a number rounds it first.
- Fills the blanks of the chosen text (of the entry, when it is a text). Each blank is replaced by the member of
valuesof its name: a string as it is; a number asformatNumber(n)with no options writes it, in the locale of the text;nullas nothing. A boolean, a list or a map fails withtype, so a boolean is a value only for abyblank that the chosen form does not insert. A blank whose namevalueshas no member for fails withmissing. Only the blanks of the chosen form need values. A member ofvaluesthat no blank names is ignored. A value is inserted once and never read again: braces inside it are characters, not blanks. - Keeps each inserted value in one piece. In a text whose direction is
rtl, every inserted value that is not empty is wrapped in U+2068 FIRST STRONG ISOLATE and U+2069 POP DIRECTIONAL ISOLATE. In a text whose direction isltr, only an inserted value that holds a right-to-left character is wrapped so. A right-to-left character is a code point from U+0590 to U+08FF, U+FB1D to U+FDFF, U+FE70 to U+FEFC, U+10800 to U+10FFF or U+1E800 to U+1EFFF; digits and punctuation in those ranges count. The characters of the entry itself are never wrapped, and the table does not store these characters for this purpose.
The result is a string, subject to the length limit of section 1. Like the functions of section 8.6, a number in it depends on the host's locale data, so an app MUST NOT parse it, compare it or store it as data.
With a table whose language en holds
{
"appName": "Trip planner",
"welcome": "Welcome back, {name}",
"nights": { "by": "count", "forms": { "one": "{count} night", "other": "{count} nights" } }
}
and ar holds "welcome": "مرحبًا بعودتك يا {name}" and no nights:
| Shown | Expression | Result |
|---|---|---|
en, env.locale en-US |
t('appName') |
Trip planner |
en, env.locale en-US |
t('welcome', {name: 'Ana'}) |
Welcome back, Ana |
en, env.locale en-US |
t('welcome', {name: 'دانة'}) |
Welcome back, + U+2068 + دانة + U+2069 |
en, env.locale en-US |
t('nights', {count: 1}) |
1 night |
en, env.locale en-US |
t('nights', {count: 3}) |
3 nights |
en, env.locale en-US |
t('nights', {count: 1250}) |
1,250 nights |
ar, the person's languages ar-EG, env.locale ar-EG |
t('welcome', {name: 'Ana'}) |
مرحبًا بعودتك يا + U+2068 + Ana + U+2069 |
ar, the person's languages ar-EG, env.locale ar-EG |
t('nights', {count: 3}) |
3 nights: there is no Arabic entry, so the English one is used, with the English plural rule, its number written as en-EG writes it and its direction ltr |
t fails with effect without a provider, missing for a key the host does not know or a blank or by without a value, type for a value of the wrong kind, and range for a malformed entry.
8.8 Questions about the app#
| Function | Result |
|---|---|
can(action, input?) |
true when invoking the action action with input now would pass its checks; otherwise false. |
canSend(flow, event, key?) |
true when sending event to the flow flow now would take a transition; otherwise false. |
These let a view or a step ask in advance what an invocation would answer, instead of repeating its guards. Both are answered by the host from the loaded definition and the app's current state; an implementation of this chapter evaluates them through a provider the host gives it, as it does random() and uuid(). Where the host provides neither, calling them fails with effect. Where they may be used is listed in validation.md, section "Expression scope".
can(action, input?). action is a string literal naming an action as a run step does: an action of this definition, or part.action for an exported action of a part. input defaults to {}. The host:
- validates
inputagainst the action'sinputfield map after applying field defaults, as an invocation does; if it does not conform, the result isfalse; - evaluates the action's
allow, if any; if it is nottrue, the result isfalse; - evaluates each entry of the action's
requirein order; if one's condition is nottrue, the result isfalse(core.md, section "Actions").
Otherwise the result is true. Confirmation, grants, the caller's access to the action, and the guards of anything the action's steps would do are not considered.
canSend(flow, event, key?). flow is a string literal naming a flow of this definition and event a string literal naming an event. key identifies the element of a collection flow and is given exactly when the flow is a collection flow. The host finds the flow instance (for a collection flow, the first element of the collection whose key field equals key; if there is none, the result is false), takes its current state, and walks the transitions for event in that state as a send would: the first transition whose if is absent or true is the one that would be taken. If there is none, the result is false. Otherwise the result is that transition's allow (true when it has none). In these conditions event is null, and in a collection flow item and index are the element and its position (core.md, section "Flows").
Both functions:
- evaluate the guards with the scope the calling expression has (the same
user,envand state, including the pending writes of the current action) except forinput,event,itemandindex, which are set as stated above; - treat a guard that fails with an error as not
true, except forbudgeterrors (section 10); - never run steps, never call a capability or code module, never raise events and never change anything.
9. Date, datetime and duration formats#
All dates use the proleptic Gregorian calendar with years 0000 to 9999. A result outside that range fails with range.
- Calendar date:
YYYY-MM-DD. It has no time zone. - Datetime:
YYYY-MM-DDTHH:MM:SS, optionally followed by.and 1 to 9 fractional digits, followed byZor an offset+HH:MMor-HH:MM.TandZare uppercase. Hours are 00 to 23, minutes and seconds 00 to 59 (no leap seconds). A datetime denotes an instant; offsets are applied to obtain UTC. Precision is milliseconds: further fractional digits are truncated. Functions that return a datetime always return the canonical UTC formYYYY-MM-DDTHH:MM:SSZ, with.mmm(exactly three digits) before theZwhen the milliseconds are not zero. - Duration:
[-]P[nY][nM][nW][nD][T[nH][nM][nS]], where eachnis a non-negative integer, except that seconds may have a fraction of 1 to 9 digits. At least one component is required, andTmust be followed by at least one time component. A leading-negates every component. - Time of day:
HH:MM, with hours 00 to 23 and minutes 00 to 59, as taken byatTime. It has no time zone.
A string argument that is not in the form a function requires fails with range; an argument that is not a string fails with type.
10. Cost budget#
Every evaluation has a budget of cost units. For expressions in a definition the budget is fixed at 100000: hosts MUST NOT use a different budget, so that an expression that evaluates on one host evaluates on every host. Each expression in a dynamic value has its own budget. When the total cost of an evaluation exceeds its budget, the evaluation fails with subcode budget.
The blocks of a string are its number of code points divided by 1,024, rounded down, so a string shorter than 1,024 code points has none. The deep size of a value is 0 for null, a boolean or a number, the blocks of a string, and for a list or map its number of elements or keys plus the deep sizes of its members. Costs are:
- Nodes. Each time a syntax node is evaluated: 1. This includes literals and identifiers, every node of a macro body each time the body is evaluated, and every member or index node in the argument of
has. Parentheses are not nodes. The variable named by a list macro or byletis not a node. - Macro iteration. Each element a list macro visits: 1, in addition to the cost of evaluating its body.
all,existsandfindcount only the elements they visit before stopping. - Function arguments. Each function call: the number of elements of every list argument, the number of keys of every map argument and the blocks of every string argument (the receiver of a method call is an argument), charged after the arguments are evaluated.
- Built collections.
range(n)costsn;splitcosts the number of parts;flattenandenumeratecost the size of their result;+on two lists costs the size of the result. Each is charged before the result is built. - Built strings.
+on two strings, a template,t,join,replace,padStart,padEnd,upper,lower, andstring()of a list or map each cost 1 per 1,024 code points of the string they return, rounded down. A string shorter than 1,024 code points costs 0. Converting a list or map inside a template also costs its number of elements or keys. - Equality. Each comparison of two values for equality costs the smaller of their deep sizes. This applies to
==and!=, to every element compared byinon a list,containson a list andindexOfon a list, which also cost the size of the list (by rule 3, or forindirectly), and to nothing else. Comparing withnull, a boolean, a number or a string shorter than 1,024 code points therefore costs 0. - Distinct values.
distinctcosts the deep size of each element, anddistinctBythe deep size of each key, in addition to rules 2 and 3. These functions compare elements by a canonical form whose construction is proportional to that deep size, rather than pairwise, so their charge does not depend on the other elements. - Patterns.
matches(s, p)costs the weight ofp(section 18.3, and at least 1) times the number of code points ofs, divided by 256 and rounded down, charged before matching. Whenpis not a string literal, the call costs 40 more, for compiling a pattern that is known only when it is used. - Questions.
cancosts the deep size of its input, andcanandcanSendcost every guard expression they evaluate, counted by these rules as though it were part of the calling expression. They are charged to the calling evaluation's budget; when that budget is exhausted inside a guard, the calling evaluation fails withbudget. - Ordering and keys. Each comparison of two strings by
<,<=,>or>=costs the smaller of their blocks.minandmaxgiven a list cost the deep size of each element, andsortBy,minBy,maxBy,groupByandindexBythe deep size of each key, in addition to rules 2 and 3. Indexing a map with a string key (m[k], also insidehas) andinon a map cost the blocks of the key.
For example: 1 + 2 costs 3; size([1, 2]) costs 6 (four nodes plus two elements); [1, 2, 3].map(x, x) costs 11 (five nodes for the call and the list, and two per element); 'a' in ['a', 'b'] costs 7 (five nodes, two for the list, and 0 for comparing two scalars); [[1, 2]] == [[1, 2]] costs 12 (nine nodes plus the deep size 3); padStart('', 2048) costs 5 (three nodes plus 2 for 2,048 code points); size(state.note) costs 3 for a short note and 7 for one of 5,000 code points (three nodes plus 4 blocks).
Every expression has finite size, every macro visits a finite list, every list is paid for when it is built, work on a long string is paid for in proportion to its length, no string an expression builds can exceed the length limit, and every pattern matches in time proportional to its weight times the length of its input, so every evaluation terminates, and the time and memory it can use are bounded.
10.1 Typical costs#
The table shows what common shapes cost by the rules above, for a list of n elements and the largest n the budget of 100000 allows. Use it to judge what fits; where a check is quadratic, build a lookup map once with indexBy or groupBy, or name a repeated sub-result with let.
| Expression | Cost | Largest n |
|---|---|---|
state.goal - state.saved |
5 | |
`Saved ${state.saved} of ${state.goal}` |
5 | |
formatNumber(state.total, {style: 'currency'}) |
6 | |
t('nights', {count: state.nights}) |
6 | |
state.deposits.sumBy(d, d.amount) |
3n + 3 | 33,332 |
sum(state.deposits.map(d, d.amount)) |
4n + 4 | 24,999 |
state.tiles.sortBy(t, t.pos) |
3n + 3 | 33,332 |
state.items.indexBy(i, i.id) |
3n + 3 | 33,332 |
state.items.count(i, i.status == 'open') |
5n + 3 | 19,999 |
state.items.find(i, i.id == input.id) (no match) |
6n + 3 | 16,666 |
state.e.map(a, state.e.count(b, b.day == a.day)) |
6n² + 4n + 3 | 128 |
let(m, state.e.indexBy(x, x.id), state.o.map(o, m[o.itemId].price)), with n elements in each list |
9n + 7 | 11,110 |
matches(input.code, '^[A-Z]{3}-[0-9]{4}$') on a short string |
4 |
11. Errors#
A syntax error has code expression.syntax and a position in the source. An evaluation error has code expression.error, a position, and one of these subcodes:
| Subcode | Raised when |
|---|---|
missing |
A map has no such key, a member or index is applied to null, a list index is out of range, or t names a key the host does not know or leaves a blank without a value (section 8.7). |
type |
An operand or argument has the wrong kind, a condition or predicate is not a boolean, or a value is outside the data model. |
divideByZero |
The right operand of / or % is zero. |
budget |
The evaluation exceeded its cost budget, would have built a string longer than the length limit (section 1), or exhausted a resource of the implementation (section 5). |
unknownFunction |
A call names no function. |
unknownIdentifier |
A root identifier is not in the scope. |
arity |
A function was called with the wrong number of arguments. |
effect |
A function that the host provides only at some positions (random, uuid, can, canSend) was called where it is not provided, or t was called where the host gives no texts. |
range |
A value has the right kind but is not accepted: a non-integer where an integer is required, a malformed date, datetime, time of day, duration or number string, an unknown part, unit, style or option name, an unknown time zone, a pattern outside the dialect of section 18, a numeric result that is not finite, a date outside years 0000 to 9999, or a malformed entry of the app's texts (section 8.7). |
Positions and messages are informative. The code and subcode are normative.
12. Paths#
A path names a writable location, such as the target of a set step or a two-way binding (core.md, sections "Steps" and "Visual surface"). A path is a root name followed by names separated by ., and, where this section allows them, by selectors that pick one element of a list:
path = IDENT { "." NAME | selector }
selector = "[" NAME "=" expr "]"
IDENT and NAME are as in section 2: the first name MUST NOT be a reserved word, and later names may be. Outside selectors a path has no whitespace. Inside a selector, whitespace may surround the field name, the = and the expression. The = is a single =; the expression after it is any expression of section 3, read with the lexical rules of section 2, and ends at the first ] that is not part of it: a ] inside a string or template literal, or one that closes a [ inside the expression, does not end it (state.lines[id=input.ids[0]], state.tags[name='a]b']). A selector expression is subject to the limits of section 3.1 as an expression of its own, and a whole path MUST NOT be longer than 10000 code points. A path that does not match is a syntax error.
state.form.amount
state.answers[id=item.id].note
state.inspections[id=input.inspectionId].checks[key=input.check].result
view.draft.title
Selectors are allowed only in the targets of set, append, remove and patch steps and in bind. A path with a selector anywhere else (a changes trigger, a flow's over.collection, an exported input, a refresh step) is a syntax error.
What a path selects. Starting from the root, each .name selects the member of that name as in section 5.1. A selector [f=e] applies to a list: it selects the first element that is a map with a member f equal (section 5.3) to the value of e. Elements that are not maps, or have no member f, never match. When no element matches, the path selects nothing: a write through it fails with state.noElement, and a binding through it shows an empty, disabled control (core.md, sections "Steps" and "Visual surface"). A selector applied to a value that is not a list selects nothing in the same way.
Evaluating selectors. Selector expressions are evaluated in the scope of the step or node that holds the path, before the step writes or the binding reads, from left to right, each with its own budget. They see the roots and local names of that step or node, but not the item and index that a remove or patch binds for its where (validation.md, section "Expression scope"). An error in a selector expression fails the step; in a binding, the control is shown empty and disabled and nothing is written. How a host writes through a path is otherwise defined by the step or binding that uses it.
13. Static analysis#
Hosts need to know what an expression reads, for example to recompute derived state when its inputs change (core.md, section "State"). The references of an expression are the root-anchored static paths it may read:
- A chain of member accesses and string-literal indexes starting at a free root identifier is one path:
state.m['k'].zreadsstate,m,k,z. - A chain stops at the first index that is not a string literal; the path read so far is reported and the index expression is analyzed on its own.
state.items[input.i].namereadsstate.itemsandinput.i. - Identifiers bound by a list macro or by
letare not references. Paths are reported once each, in the order they first appear. - A function that reads
env(section 8.6, andatTimeanddateInwithout azoneargument) adds theenvfields it may read, after the references of its arguments:formatNumberaddsenv.localeandenv.currency;formatDateaddsenv.localeandenv.timezone;relativeTimeaddsenv.now,env.todayandenv.locale;pluraladdsenv.locale;atTimeanddateInaddenv.timezone. taddsenv.languageandenv.locale, after the references of its arguments. Its text depends on the language shown and on the person's languages, which these two fields follow. A host that changes the person's languages, or the language the person chose for the app, MUST treat both fields as changed even where a value stays the same, because a text taken from another language's table follows the person's languages directly.
A reference to a path means the expression may depend on any value at or below that path.
The references of can and canSend calls are those of their arguments. Their results also depend on the guards they evaluate, which this analysis cannot see; a host that recomputes values when their inputs change MUST also treat a can or canSend call as reading what those guards read (other than input, event, item and index), the collection of a collection flow, and flows.<name> of a singleton flow.
The references of a path are the path with its selectors removed, up to the first selector (state.answers for state.answers[id=item.id].note), together with the references of each selector expression.
14. Examples#
state.goal - state.saved
sum(state.deposits.map(d, d.amount))
state.deposits.filter(d, d.date >= startOf(toDate(env.now), 'month')).sumBy(d, d.amount)
'manager' in user.roles
has(state.profile.email) && state.profile.email.endsWith('@example.com')
default(state.form.note, '')
`You saved ${round(state.saved / state.goal * 100)}% of ${state.goal}`
state.tasks.groupBy(t, t.status)
daysBetween(toDate(env.now), state.trip.departs) <= 7 ? 'soon' : 'later'
`Put aside ${formatNumber(state.weekly, {style: 'currency'})} a week`
`Updated ${relativeTime(sources.tickets.updatedAt)}`
let(byItem, state.answers.indexBy(a, a.itemId), state.items.filter(i, !(i.id in byItem)))
merge(item, {done: true, doneAt: env.now})
matches(trim(input.word), '^[a-z]+$')
atTime(addDays(state.deadline, -3), '09:00')
can('approveRequest', {id: item.id})
t('nights', {count: state.trip.nights})
15. Differences from CEL#
The syntax is a subset of CEL with template strings added. The semantics follow the JSON data model. Concretely:
- One number kind. There are no separate
int,uintanddoubletypes and no integer overflow: every number is a double.int()truncates to an integral number rather than converting to an integer type. - True division.
/always divides exactly (7 / 2is3.5), where CEL truncates integer division.%accepts non-integers. - Errors instead of special values. Results that would be infinite or NaN fail with
range. - Left-to-right logic.
&&and||short-circuit from left to right and require booleans. CEL's commutative error absorption (error || trueistrue) does not apply: an error on the left side propagates. - Equality and
+.==compares deeply across kinds and never fails.+does not mix kinds. - Map literals. A bare identifier key is the literal key name (
{goal: 1}has keygoal), where CEL evaluates it as an expression. Keys are limited to string literals and names. - Template strings with
${...}interpolation are not part of CEL. has()accepts index steps and whole chains, and returnsfalsewhen any step is absent or passes throughnull, where CEL'shas()tests one field and fails if an earlier step is absent.- Local names.
let(name, value, body)plays the part of CEL'scel.bind(name, value, body). - Patterns.
matchestakes a pattern in the restricted dialect of section 18, not full RE2 syntax, and the dialect is also used by a type'spattern. - Added macros and functions.
default,let,find,count,sortBy,groupBy,indexBy,sumBy,minBy,maxByanddistinctByare not CEL macros, and most functions in section 8 are not in CEL's standard library. CEL'sexists_oneand three-argumentmapare not provided. - Not supported: bytes,
uint,timestampanddurationtypes (dates and durations are ISO 8601 strings); protocol buffer messages; type values (type()returns a string); optional values and.?; raw, triple-quoted and byte string literals; octal and hexadecimal escapes; hexadecimal and unsigned number literals; number literals starting with.; comments. - Reserved words. Only
true,false,nullandinare reserved. CEL's other reserved words (if,package,returnand so on) are ordinary identifiers, because they can be names in a definition. - Membership with
inon lists and maps is as in CEL and is not a difference. - Limits. Strings built by an evaluation are limited to 1,048,576 code points (section 1).
- Cost budget. Every evaluation is bounded by the cost model of section 10.
- Static types. CEL type-checks against declared types and rejects an expression that may fail. The checks of section 17 report only what is certain to fail, and treat anything not known as acceptable.
16. Conformance#
A conforming implementation MUST produce, for every vector in conformance/0.2/expressions/, exactly the result or error that vector states. Each file is a JSON array of vectors, grouped by topic. A vector has a name and one of these shapes:
| Shape | Meaning |
|---|---|
{ "expr", "scope"?, "budget"?, "effects"?, "texts"?, "expect" } |
Evaluating expr against scope (default {}) yields expect, compared with section 5.3: lists in order, maps structurally. |
{ "expr", ..., "expectPattern" } |
Evaluating expr yields a string that expectPattern, a pattern in the dialect of section 18, matches. Used for the functions of section 8.6, and for t with a number, whose text varies between hosts. |
{ "expr", ..., "error": subcode } |
Evaluation fails with expression.error and that subcode. |
{ "expr", ..., "syntaxError": true } |
Parsing fails with expression.syntax. |
{ "value", "scope"?, ... } |
As above, for a dynamic value (section 6). An optional pointer is the JSON Pointer the error must carry. |
{ "path", "expect" \| "syntaxError" } |
Parsing a path (section 12) yields the list expect, in which a name is a string and a selector is { "field": name, "expr": source }, with source the text of the selector expression without surrounding whitespace; or parsing fails. |
{ "expr", "references", "functions", "identifiers" } |
Static analysis (section 13): the references, the distinct names of functions and macros called, and the distinct free root identifiers, each in first-appearance order. |
{ "expr", "types", "typeErrors", "resultType"? } |
Static types (section 17): with each root name in types given the static type of the type reference beside it (section 17.2; references are inline JSON Schema objects or primitive shorthands), checking expr reports exactly the codes in typeErrors (expression. or expression.), compared as a multiset, and its type is the static type of the type reference resultType. |
budget overrides the default budget for that vector. effects supplies a provider whose random() always returns effects.random and whose uuid() always returns effects.uuid; without it, effects are not allowed. Vectors for the functions of section 8.6 set env.locale to en-US and env.timezone in their scope; a conforming implementation MUST have locale data for en-US, and the patterns accept the variation that locale data for en-US allows. can and canSend need a loaded definition and are tested by the semantic fixtures of validation.md, not by these vectors.
An evaluation vector may carry texts, the answers of a provider of texts (section 8.7): a map from each key the provider knows to the answer it gives for that key, { "entry", "language", "locale", "direction" }. A key not in texts is one the host does not know, and a vector without texts has no provider, so its t fails with effect. The vectors so do not depend on how a host chooses a language. They write numbers only in the locale en-US (one of them gives en-EG for the number 3, which every English locale writes the same), and test a right-to-left text by giving the direction rtl.
17. Static types#
Before a definition runs, a validator infers a static type for every expression whose types can be known, and reports operations that are certain to fail (validation.md, section "Static types in a definition"). This section defines those types and the rules, so that every validator reports the same diagnostics for the same definition. Static types play no part in evaluation: a host evaluates by sections 1 to 12 alone.
The governing principle is that a diagnostic is reported only when it is certain. Anything whose type is any, null or not known, and any member of an open map that the map does not name, passes.
17.1 Types#
| Static type | Describes |
|---|---|
any |
Nothing is known about the value. |
null |
The value null. |
boolean, number, string |
A value of that kind. |
list<T> |
A list whose elements have type T. |
| map type | A map. It has zero or more named members, each with a type, and is either closed (it has no other members) or open, with a rest type for members it does not name (any when nothing is known of them). |
map<T> stands for the open map type with no named members and rest type T. A type is known when it is neither any nor null. The kind of a known type is boolean, number, string, list or map.
A static type records kinds and shapes only. Whether a number is an integer, a string's format (such as date), enum and const values, pattern, and length and range limits are not part of it; they are checked on literal values by validation and on every value at run time.
Absence and null are not tracked. A named member is assumed to be present, and a type reference marked nullable gives the same static type as the reference without ?. Reading an optional field, or a member of a value that may be null, is therefore never reported, and neither is passing null where a value is expected.
17.2 Types from type references#
A type reference (core.md, section "Types") gives a static type as follows. For a JSON Schema object, the first row that applies is used.
| Type reference | Static type |
|---|---|
string, date, datetime, duration |
string |
number, integer |
number |
boolean |
boolean |
any |
any |
A type name, alias:TypeName, or a schema with $ref |
The static type of the schema referred to. |
T[] |
list<T> |
T? |
The static type of T. |
Schema with type "object" |
A map type with a named member for each entry of properties, typed by its schema. It is closed when additionalProperties is false, and otherwise open with rest type from additionalProperties when that is a schema, else any. required is ignored. |
Schema with type "array" |
list<T> with T from items, or list<any> without items. |
Schema with type "string", "number", "integer", "boolean" or "null" |
string, number, number, boolean or null. |
Schema with type given as a list |
Without "null", a single remaining entry is read as above; otherwise any. |
Schema with enum |
The union (section 17.3) of the static types of its values. |
Schema with const |
The static type of its value. |
Schema with oneOf |
The union of the static types of its members. |
| Any other schema | any |
| A reference that does not resolve | any |
The static type of a JSON value is null, boolean, number or string for a scalar; list<U> for an array, with U the union of its elements' types (list<any> when empty); and for an object, a closed map type with a named member for each key, typed by its value. A dynamic value has the same static type, except that each expression in it has its inferred type.
A field map gives a closed map type with a named member for each field, typed by the field's type. A named type may refer to itself; its members are expanded only as far as an expression reads them, so inference always ends.
17.3 Union#
The union of two types A and B is:
any, when either isany;- the other, when one is
null; - that kind, when both are
boolean, bothnumberor bothstring; list<U>, when both are lists, withUthe union of their element types;- when both are map types, a map type that names every member either names. A member's type is the union of its type in each map that names it and the rest type of each open map that does not. The result is closed when both are closed, and otherwise open with a rest type that is the union of the rest types of the open ones;
anyotherwise.
The union of more than two types is taken from left to right. The members of a union of map types are computed when an expression reads them.
[1, 2] is list<number>; [1, 'a'] is list<any>; c ? {a: 1} : {b: 'x'} is a closed map naming a (a number) and b (a string). A oneOf of closed object types gives a closed map naming every property of every member, so a property that no member has is reported, and one that some member has is not.
17.4 Inference#
| Expression | Static type |
|---|---|
null, true, false, a number or string literal |
null, boolean, number, string |
| A template | string |
[e1, e2, ...] |
list<U>, with U the union of the elements' types; [] is list<any> |
{k1: e1, ...} |
A closed map type with a named member for each key, typed by its value |
| An identifier bound by a list macro | The element type of the macro's receiver (any when the receiver is not a known list) |
An identifier bound by let |
The type of let's value |
| Any other identifier | The type of that root or local name at the expression's position (validation.md, section "Static types in a definition"); any for a name that is not in scope |
x.n, x['n'], x[k] |
Section 17.6 |
has(p) |
boolean |
default(a, b) |
The union of the types of a and b |
let(n, v, e) |
The type of e |
!a, a == b, a != b, a < b, a <= b, a > b, a >= b, a in b, a && b, a \|\| b |
boolean |
-a, a - b, a * b, a / b, a % b |
number |
a + b |
number when either operand is a number, string when either is a string, list<U> when both are lists (U the union of their element types), list<any> when one is a list and the other is not known, otherwise any |
c ? a : b |
The union of the types of a and b |
| A function call or list macro | Its result type (section 17.5) |
Static types are not narrowed by conditions or by has: in type(x) == 'number' ? x + 1 : 0, x keeps its own type in both branches. Every part of an expression is checked, including the branch of a conditional that is not taken and the body of a list macro, which is checked as though the list had an element.
17.5 Signatures#
In this table, T stands for one static type throughout a row, U for another, map for any map type, A | B for a parameter that accepts either, ? marks an optional parameter and ... repetition. A parameter accepts the kind it names; list<number> accepts a list whose element type is number or not known.
| Function | Parameters and result |
|---|---|
size |
(string \| list<any> \| map) -> number |
sum, avg |
(list<number>) -> number; (number, ...) -> number |
min, max |
(list<T>) -> T with T number or string; (T, ...) -> T with every argument of one kind, number or string |
keys |
(map) -> list<string> |
values |
(map) -> list<V>, with V the union of the map's named member types and, when open, its rest type |
entries |
(map) -> list<{key: string, value: V}>, closed, with V as for values |
merge |
(map, map) -> map: see below |
compact |
(map M) -> M |
reverse |
(list<T>) -> list<T>; (string) -> string |
slice |
(list<T>, number, number?) -> list<T>; (string, number, number?) -> string |
first, last |
(list<T>) -> T |
flatten |
(list<list<T>>) -> list<T>; (list<T>) -> list<T> when T is known and not a list; (list<any>) -> list<any> |
distinct |
(list<T>) -> list<T> |
enumerate |
(list<T>) -> list<{index: number, value: T}>, closed |
range |
(number) -> list<number> |
contains |
(list<any>, any) -> boolean; (string, string) -> boolean |
indexOf |
(list<any>, any) -> number; (string, string) -> number |
abs, floor, ceil |
(number) -> number |
round |
(number, number?) -> number |
int, number |
(number \| string) -> number |
string |
(any) -> string |
bool |
(boolean \| string) -> boolean |
type |
(any) -> string |
startsWith, endsWith |
(string, string) -> boolean |
lower, upper, trim |
(string) -> string |
split |
(string, string) -> list<string> |
join |
(list<string>, string?) -> string |
replace |
(string, string, string) -> string |
substring |
(string, number, number?) -> string |
padStart, padEnd |
(string, number, string?) -> string |
matches |
(string, string) -> boolean |
addDays, addMonths |
(string, number) -> string |
addDuration |
(string, string) -> string |
daysBetween, durationBetween |
(string, string) -> number |
datePart |
(string, string) -> number |
startOf |
(string, string) -> string |
toDate |
(string) -> string |
seconds |
(string) -> number |
atTime |
(string, string, string?) -> string |
dateIn |
(string, string?) -> string |
formatNumber |
(number, map?) -> string |
formatDate |
(string, string?) -> string |
relativeTime |
(string) -> string |
plural |
(number, map) -> string |
random |
() -> number |
uuid |
() -> string |
can |
(string, map?) -> boolean |
canSend |
(string, string, any?) -> boolean |
t |
(string, map?) -> string: see below |
When an argument is not known, a function whose result depends on it (reverse, slice, first, last, min, max) returns any. The result of merge(a, b) is, when both are map types, a map type naming every member either names: a member b names has its type in b; any other member has its type in a, joined (section 17.3) with b's rest type when b is open. It is closed when both are closed, and otherwise open with the union of the open ones' rest types. When either argument is not known, the result is map<any>.
Each member of the map given to t is a string, a number, a boolean or null: a member that is known and a list or a map is reported. A boolean passes, because it may be the by blank of the entry, which the static types cannot see; whether the entry inserts it is checked by validation, which knows the table (validation.md).
| Macro | Receiver, body and result |
|---|---|
l.map(x, e) |
list<T>, any e → list<E>, E the type of e |
l.filter(x, p) |
list<T>, p boolean → list<T> |
l.all(x, p), l.exists(x, p) |
list<T>, p boolean → boolean |
l.find(x, p) |
list<T>, p boolean → T |
l.count(x, p) |
list<T>, p boolean → number |
l.sortBy(x, k), l.distinctBy(x, k) |
list<T>, k number or string (any for distinctBy) → list<T> |
l.minBy(x, k), l.maxBy(x, k) |
list<T>, k number or string → T |
l.groupBy(x, k) |
list<T>, k string → map<list<T>> |
l.indexBy(x, k) |
list<T>, k string → map<T> |
l.sumBy(x, e) |
list<T>, e number → number |
has(p) |
any path → boolean |
default(a, b) |
any, any → the union of their types |
let(n, v, e) |
any v, any e → the type of e |
When the receiver of a list macro is not a known list, T is any, and the result is list<any>, any, boolean or number as the row says.
17.6 What is reported#
Two diagnostics come from these rules (validation.md, section "Expressions and references"). Each operation is reported at most once.
expression.unknownMember is reported for a member access x.n, or an index x['n'] with a string literal, when the type of x is a closed map type that does not name n. Its type is then any. A validator reports a more specific diagnostic instead where validation.md names one (such as reference.unknownState for state.n).
Member access and indexing are typed as follows:
| Target type | x.n and x['n'] |
x[k], k not a string literal |
|---|---|---|
any or null |
any |
any |
| A map type | The member's type if named; otherwise the rest type if open; otherwise reported as expression. |
expression. if k is known and not a string; the rest type when the map names no members; otherwise any |
list<T> |
expression.; any |
expression. if k is known and not a number; T |
boolean, number or string |
expression.; any |
expression.; any |
The same rules apply to every step of the path inside has(...) and default(...).
expression.typeMismatch is also reported, at the operation, when:
- the operand of
!is known and not a boolean, or the operand of unary-is known and not a number; - an operand of
&&or||, or the condition of? :, is known and not a boolean; - an operand of
<,<=,>or>=is known and neither a number nor a string, or both are known and one is a number and the other a string; - the right operand of
inis known and neither a list nor a map, or it is a map type and the left operand is known and not a string; - an operand of
+is known and is a boolean or a map, or both are known and of different kinds; - an operand of
-,*,/or%is known and not a number; - a function is called with a number of arguments its signature does not allow;
- an argument is known and of a kind its parameter does not accept, or a list argument has a known element type of a kind the parameter does not accept; for the variadic forms of
minandmax, the known arguments are not all numbers or all strings; forcontainsandindexOfon a string, the second argument is known and not a string; fort, a member of its map is known and a list or a map; - the receiver of a list macro is known and not a list; the predicate of
filter,all,exists,findorcountis known and not a boolean; the key ofsortBy,minByormaxByis known and neither a number nor a string; the key ofgroupByorindexByis known and not a string; the body ofsumByis known and not a number.
Nothing else is reported. In particular ==, !=, template interpolations, string() and type() accept every type, and a call to an unknown function is reported only as expression.unknownFunction (a warning), with type any. An operation that is reported has the type its row in section 17.4 gives when that row does not depend on the operands, and any otherwise, so one fault does not cause others.
17.7 Compatible types#
Where a computed value must conform to a declared type, validation reports expression.typeMismatch when the value's static type is incompatible with the declared one. A type V is incompatible with a type D when:
- both are known and of different kinds;
- both are lists, and
V's element type is incompatible withD's; - both are map types, and a member named by
Vis incompatible with the member of that name inD; orDdoes not name it and is closed; orDdoes not name it, is open, and the member is incompatible withD's rest type.
Otherwise the types are compatible. A comparison that reaches a pair of types already being compared, as happens with a type that refers to itself, takes that pair as compatible, so every comparison ends. any and null are compatible with every type, as is anything with any. Since refinements are not part of static types, a number is compatible with integer and a string with date; such values are checked when they are written.
17.8 Worked examples#
The scope types are state: { goal: number, note: string?, deposits: Transaction[], extra: any, settings: { "type": "object" } }, with Transaction a closed object type with id and memo (strings, memo not required), amount (number) and date (date), and input the closed field map { amount: number }.
| Expression | Reported | Why |
|---|---|---|
state.deposits.map(d, d.amont) |
expression. |
Transaction is closed and has no amont. |
state.goal + ' left' |
expression. |
+ with a number and a string. |
state.deposits.sumBy(d, d.memo) |
expression. |
The body of sumBy is a string. |
state.deposits.filter(d, d.amount) |
expression. |
The predicate is a number. |
size(state.goal) |
expression. |
size does not accept a number. |
{a: 1}.b |
expression. |
A map literal is closed. |
input.amount > 0 && input.amount |
expression. |
The right operand of && is a number. |
state.deposits[0].memo.size() > 0 |
none | memo is optional, but absence is not tracked. |
state.note + '!' |
none | note is nullable, but null is not tracked. |
state.extra.anything + 1 |
none | extra is any. |
state.settings.theme |
none | settings is an open map. |
state.goal + state.extra |
none | One operand is not known; the type is number. |
type(state.extra) == 'string' ? state.extra.size() : 0 |
none | extra is any in both branches. |
`${state.goal} left` |
none | Interpolation accepts every type. |
18. Patterns#
matches (section 8.3) and the pattern keyword of a type schema (core.md, section "Types") use one pattern dialect. Its syntax is a subset of ECMAScript's regular expression syntax with the u flag; its meaning is defined by section 18.2 alone, and every pattern in it can be matched in time proportional to the length of the input. An implementation that matches with another engine, such as RE2, MUST translate the constructs whose meaning there differs, among them ., \s, \S and the \u escapes. Backreferences, lookaround, word boundaries, flags, named groups and Unicode property classes are not part of it.
18.1 Syntax#
pattern = alternative { "|" alternative }
alternative = { term }
term = "^" | "$" | atom [ quantifier ]
atom = char | "." | escape | class | "(" pattern ")" | "(?:" pattern ")"
quantifier = "*" | "+" | "?" | "{" count "}" | "{" count ",}" | "{" count "," count "}"
count = DIGIT { DIGIT }
class = "[" [ "^" ] item { item } "]"
item = classchar [ "-" classchar ] | classescape | "-"
escape = "\d" | "\D" | "\w" | "\W" | "\s" | "\S" | charescape | "\" ( syntaxchar | "/" )
classescape = "\d" | "\D" | "\w" | "\W" | "\s" | "\S"
classchar = any code point except "\", "]", "[" and "-" | charescape | "\" ( syntaxchar | "/" | "-" )
charescape = "\t" | "\n" | "\v" | "\f" | "\r" | "\u" HEX HEX HEX HEX | "\u{" HEX { HEX } "}"
char = any code point except syntaxchar
syntaxchar = "^" | "$" | "\" | "." | "*" | "+" | "?" | "(" | ")" | "[" | "]" | "{" | "}" | "|"
Further rules:
- A slash is an ordinary character, and
\/also stands for it. - In a class, a bare
-item is allowed only as the first item (after any^) or the last, where it is a literal; elsewhere a-joins twoclasschars into a range, whose first code point MUST NOT be greater than its last. A class escape such as\dcannot be the end of a range. A class has at least one item:[]and[^]are outside the dialect. \uescapes name a code point: exactly four hexadecimal digits, or one to six in braces with a value up to 10FFFF. Surrogates (D800 to DFFF) are outside the dialect.- In a quantifier, each count is at most 1000, and in
{m,n},mMUST NOT be greater thann. A quantifier cannot follow^,$or another quantifier: lazy forms such as+?and repeated quantifiers such asa**are outside the dialect. (?followed by anything other than:is outside the dialect.- A pattern MUST NOT be longer than 1000 code points, and its weight (section 18.3) MUST NOT exceed 10000.
Anything else, such as \b, \1, \p{L}, \x41, (?=, (?<name>, (?i) or an unescaped {, is outside the dialect.
18.2 Meaning#
A pattern and its input are sequences of code points. A pattern describes a set of strings:
| Construct | Matches |
|---|---|
char, \/ and the other escaped syntax characters |
That code point. |
\t \n \v \f \r |
U+0009, U+000A, U+000B, U+000C, U+000D. |
\uXXXX, \u{X...} |
The code point with that value. |
. |
Any one code point except U+000A, U+000D, U+2028 and U+2029. |
\d, \D |
One of 0 to 9; any other code point. |
\w, \W |
One of A to Z, a to z, 0 to 9 and _; any other code point. |
\s, \S |
One of U+0009 to U+000D, U+0020, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F, U+3000 and U+FEFF; any other code point. |
[...] |
One code point that is one of the class's items: a code point, every code point in a range (inclusive), or a code point in a class escape's set. |
[^...] |
One code point that is none of them. |
^, $ |
The empty string at the start, or at the end, of the input. |
a b (a sequence) |
A string matched by a followed by one matched by b. An empty alternative matches the empty string. |
a \| b |
A string matched by either. |
( p ), (?: p ) |
What p matches. Groups only group: nothing is captured. |
a*, a+, a? |
Zero or more, one or more, zero or one strings matched by a, one after another. |
a{m}, a{m,}, a{m,n} |
Exactly m, at least m, from m to n strings matched by a. |
Matching is exact by code point: there is no case folding and no normalization, and \d, \w and \s are the fixed sets above whatever the locale. A pattern matches a string when it matches some part of the string, with ^ and $ standing only for the start and the end of the whole string. Since only whether a match exists is observable, which part matches is never defined. The empty pattern matches every string.
18.3 Weight and time#
The weight of a pattern bounds the work of matching it:
- a
char, escape,.or class weighs 1, and so does^or$; - an alternative weighs the sum of its terms, and a pattern the sum of its alternatives;
- a group weighs what its contents weigh;
a*,a+anda?weigh whataweighs;a{m}anda{m,}weighmax(m, 1)times whataweighs, anda{m,n}ntimes.
^[A-Z]{3}-[0-9]{4}$ weighs 10. A host MUST match patterns in time bounded by a constant times the weight times the length of the input, for example with an automaton; a backtracking matcher, whose time can grow exponentially, does not meet this requirement. A pattern outside the dialect is a syntax error when it is a string literal argument of matches (section 3), fails with range when matches receives it at run time, and is type.invalid in a type schema (validation.md, section "Types and values").