Skip to content

2. Grammar

Draws on: ADR 0007, ADR 0012, ADR 0013, ADR 0014, ADR 0017, ADR 0019, ADR 0020, ADR 0021, ADR 0022, ADR 0023, ADR 0025, ADR 0026, ADR 0027, ADR 0028, ADR 0029, ADR 0031, ADR 0035, ADR 0042, ADR 0055, ADR 0059, ADR 0060, ADR 0063, ADR 0073, ADR 0112.

The grammar is one set of productions, in grammar.ebnf, and one set of word lists, in grammar.toml. This chapter shows both and states the rules they can’t. What each construct means is in the chapters that follow.

  • Predictive: a Core parses with a fixed lookahead of two tokens and no backtracking. Every choice between productions is made on the next token, or on the next two where a decision below says so.
  • One grammar: the grammar is the same on every Host. Neither Hosts nor Scripts can add syntax (ADR 0012). A Handler’s Argument Labels are parsed the same whatever Handlers exist.
  • What is normative: for source that parses, the parse, since a different parse lowers differently (chapter 8). For source that doesn’t, the first syntax error: its code and position.

The Recovery Offer, choice and Recovery Catch forms below use chapter 4’s structured recovery and chapter 8’s two-phase catch search (ADR 0060).

  • The EBNF is that of the W3C XML Recommendation, as chapter 0 says.
  • Tokens come from chapter 1: Word, Name, Number, Text, Unit and NL, plus CallOpen (a ( straight after a Name), PatternOpen and PatternClose (the < and > of a Text Pattern) and BinaryOpen (<< in operand position).
  • A quoted word such as 'put' matches a Word with that spelling. If it is a Reserved Word, it is only ever that Reserved Word. Otherwise it is a contextual keyword, which has its meaning only where a production quotes it, and is an ordinary Name everywhere else.
  • Overlaps: where a contextual keyword could also be read as a Name, a two-token decision picks the reading.
  • Comments in a production state a rule that the notation can’t, such as “the Name after end is the Handler’s name”.

add, after, and, ask, be, catch, delete, divide, else, end, exit, false, finally, for, function, given, if, in, into, is, it, let, match, me, multiply, not, nothing, of, offer, on, or, pass, put, repeat, replace, return, send, set, subtract, tell, the, then, throw, to, true, try, until, veto, wait, when, where, while

A Reserved Word is never a Name, anywhere. Each one is reserved for a reason:

  • Block structure: end, else, when, catch, finally and after end or continue a block at the start of a statement, and then ends a condition. None of them can be a Handler name.
  • The words that start statements: if add were contextual, add 1 to x and a Command Call add 1 would differ only at to, arbitrarily far in. The same holds for every word that starts a statement, except next: next repeat is decided on its two tokens, so next stays contextual.
  • given starts a Lambda, decided on its first token.
  • in makes x is in r (membership) a decision on one token, not three. wait makes … and wait a decision on two. the, of, is, not, and and or are the expression words.
  • to, into, be, then and where aren’t needed to parse valid source. They are reserved because they put first errors on the right token: put 1 + into x fails at into, not at x.
  • Constants: true, false, nothing, it and me.

Note. A Reserved Word can still be a map key, since a word followed by : in {…} is always a key ({to: who}), and it can be read back with the to of m or m's to. It can’t be a variable, a parameter, a Capture or a Handler name, and one written where the grammar wants a Name is the syntax error reserved word, reported at the word (#2089).

Contextual keyword Positions
a after is or is not, before a kind; after can be; before a kind in a Text Pattern (a Typed Element); at the start of a Shape Term, before quantity of
all straight after wait for (a Join)
an as a
any after on, pass or a Handler’s end, before message (the Fallback Handler)
as after an operand (a conversion); after a pattern (binding the whole value); after the Library name in use, before the new name; after a Text Pattern element; after the value of a Binary Pattern build field
at after is or is not, before least or most; operator position, Path Access x at p; directly in a Command Call’s or Operation call’s arguments, only before a Path Literal
before after the value in put; after a catch pattern, before unwind; after comes
begin after does not, before with
begins operator position, before with
by after the Container in multiply and divide; after delimited
can operator position, before be
case after ignoring
choose at the start of a statement, before offer
civil before date in a kind
collecting after a repeat head, before the collected expression
comes operator position, before before or after
constant at the start of a top-level declaration
contain after does not
contains operator position; after when, before <
date after civil, in a kind
deciding after a comma in a Handler head
delimited after a Chunk Expression, before by
div operator position
does operator position, before not
dropping after a comma in a Handler head
during after a comma in a Handler head, before a name
each after repeat for
element operand position, before a token that can start an index (an Object Element Reference); after the and an ordinal (an ordinal Object Element Reference); after every, before of (an Every Head)
elements operand position, before a token that can start an index (an Object Element Reference); after the number of, before of (an Element Count); after the, before of (the Built-in property elements)
empty after is or is not
ends operator position, before with
every operand position, before match (the Match Search); at the start of an expression, before a chunk kind’s singular or code (an Every Head)
forever straight after repeat
from after the value in subtract; after the event in wait for; after the imported names in use
greater after is or is not, before than
ignoring after a comparison, a match subject or a Text Pattern element, before case
lazily after a Text Pattern element
least after is at or is not at
less after is or is not, before than
list at the start of a Shape Term, before of
matches operator position
message after any (the Fallback Handler)
mod operator position
most after is at or is not at
next at the start of a statement, before repeat
number after the, before of elements of (an Element Count)
object at the start of a Shape Term, before of
optional after the, unless followed by of; at the start of a Shape Term, or straight after a Shape Map field’s :
otherwise between default expression operands
private at the start of a top-level declaration, before on, function, constant or shape
quantity in a Shape Term, after a or an and before of
queued after a comma in a Handler head
replacing after a comma in a Handler head
script at the start of a top-level declaration, before variable
shape at the start of a top-level declaration
target after the, when of doesn’t follow
than after is greater or is less, with or without not after is
timeout after with at the start of a statement (a Timeout Block); after a Timeout Block’s end
times after the count in repeat
unwind after before in a catch head
use at the start of a top-level declaration
variable after script at the start of a top-level declaration
whose after an Every Head, or an ordinal Chunk Expression or ordinal Object Element Reference that is a whole operand (a Whose Clause)
with after the message name in send; after the Container in replace; after begins or ends; after does not begin or does not end; at the start of a statement, before timeout (a Timeout Block)

The chunk kinds, the ordinals, the Built-in property names, the Text Pattern keywords and the Binary Pattern words below are contextual too. Each has its meaning only where the grammar gives it one.

as, before, begins, by, can, collecting, comes, contains, delimited, div, does, ends, from, ignoring, matches, mod, otherwise, times, whose, with

These are the contextual keywords that may come straight after a complete expression. None of them can start a chunk index, which is how a chunk word is told from a Name (Operands). No Unit’s name or plural may be a Reserved Word or in the FOLLOW set, and the generator checks this against units.toml.

Any Name may be an Argument Label, except these. Of the Reserved Words, only these may be one.

  • Reserved Words that may be labels: on, to.
  • Names that may not be labels: from, otherwise.
Source ::= NL* ( Declaration NL* )*
Declaration ::= 'private'? ( Handler | Function | Constant | ShapeDecl ) | ScriptVariable | Use
ScriptVariable ::= 'script' 'variable' Name ( '=' Expression )? NL
Constant ::= 'constant' Name '=' Expression NL
ShapeDecl ::= 'shape' Name 'is' ShapeExpr NL
ShapeExpr ::= ShapeTerm ( 'or' ShapeTerm )*
ShapeTerm ::= 'optional' ShapeTerm
| ( 'list' | 'object' ) 'of' ShapeTerm
| Article 'quantity' 'of' Name
| '(' ShapeExpr ')'
| ShapeMap
| Kind | Unit
/* `list` and `object` without `of` are kinds; after `object of`, only a Name;
whether a Name is a kind, a Unit or a named Shape is a load rule */
ShapeMap ::= '{' ( ShapeField ( ',' ShapeField )* ( ',' '...' )? | '...' )? '}'
ShapeField ::= MapKey 'optional'? ShapeExpr
Use ::= 'use' Name ( ( ',' Name )+ 'from' Name | 'from' Name ( 'as' Name )? ) NL
Function ::= 'function' Name ( Parameter ( ',' Parameter )* )? NL Block 'end' Name? NL
/* a Name after `end`, if present, is the function's name */
Parameter ::= Name ( '=' Expression )?
/* a default; only trailing parameters may have one */
Entry ::= NL* ( Declaration | Statement NL | Expression NL )
/* at a Session prompt only; decided on its first token */
  • Top level: a Script or Library is a sequence of declarations, and a top-level line can only start one. A statement at top level is a syntax error at its first token.
  • Declarations are decided on their first token, except script variable, which is decided on two. use, constant, shape, private, script and variable are contextual, since a top-level line can’t start anything else.
  • = in a Script Variable or Constant means “starts as”, and in a function’s parameters “defaults to”. It is equality everywhere else.
  • use … as renames a single imported name (use trim from text as tidy). After two or more names, as is a syntax error.
  • private goes before a Handler, a function, a Constant or a Shape declaration. It is a load error in a Script (chapter 7).
  • Shape declarations: shape Name is and a Shape Expression declare a named Shape (ADR 0168). or joins Shape Terms and binds loosest; brackets group. At the start of a Shape Term, optional wraps the next term, list or object followed by of is a wrapper, and a or an followed by quantity of names a Unit Kind; otherwise those words are kinds or Names. Straight after a Shape Map field’s :, optional marks the field optional instead. ... may only be a Shape Map’s last entry. A Unit in a Shape Term may be a Compound Unit, lexed as after as. A text literal is a syntax error there, left for literal-value Shapes. Which Name is a kind, a Unit or a named Shape is a load rule (chapter 7).
  • Functions take a list of names, with no Destructuring. A Name after end, if present, must be the function’s name.
  • Defaults: name = expression gives a parameter a default, which a call may leave off (ADR 0035). The default runs to the next top-level comma or the end of the line. Only trailing parameters may have one, and what a default may use is a load rule (chapter 7).

Example.

use pad, trim from text
use sum from list as total
script variable visits = 0
constant welcome = "Hello"
function tax amount, rate = 0.2
return amount * rate
end tax

An Entry is what a Session reads at its prompt (ADR 0014, chapter 12). It is decided on its first token, with no second parse:

  • A word that starts a declaration (on, function, private, use or constant, and script before variable) starts one.
  • A Reserved Word that starts a statement (put, if, wait, …) starts one, and so do next before repeat and with before timeout.
  • Any other Name starts a Command Call only if the Session Script has a Handler whose Selector starts with that Name, or the Name is say (chapter 12). Anything else, including an Entry that starts with the, not, given or a constant, is an expression, and its value is echoed. So n - 1 echoes a value rather than calling a Handler n with -1.
Handler ::= 'on' ( 'any' 'message' FallbackHead | MessageName HandlerHead ) NL Block
( 'finally' NL Block )? 'end' ( 'any' 'message' | Name )? NL
/* `any message` is the Fallback Handler, and closes only it; a Name
after `end`, if present, is the Handler's name */
HandlerHead ::= ( HeadParam ( ( ',' HeadParam )* | ( Label HeadParam )+ ) )? Guard? ( ',' Suffix )*
FallbackHead ::= HeadParam Guard? ( ',' Suffix )*
HeadParam ::= Pattern ( 'is' 'not'? Article Kind )?
/* a Clause Shape; `is not` parses, and is the load error `negated shape` */
Label ::= Name | 'to'
/* an Argument Label: any Name but those grammar.toml's [labels]
excludes, or one of its Reserved Words; never the start of an
operator that can continue the expression before it */
Suffix ::= 'queued' | 'dropping' | 'replacing' | 'deciding' | 'during' Name
Guard ::= 'where' Expression
MessageName ::= Name /* not `all` */
  • Handler and message names are one Name each (beforeClose), and so is each part of a Selector. all can’t name a Handler, a message or an event, since wait for all starts a Join.
  • The head is the parameters, then an optional Guard, then the suffixes, in that order. Each parameter is one Destructuring pattern, optionally followed by a Clause Shape. The parameters are a comma-separated list, or one parameter followed by Argument Labels, each with its parameter.
  • Clause Shapes: is a or is an and a kind or Shape name after a parameter’s pattern is that parameter’s Clause Shape, as in on move item is a Thing to place is a Place. It comes before the parameter’s Argument Label, if any. is is a Reserved Word, so it is never a label. is not a parses, and is the load error negated shape (ADR 0171).
  • Suffixes: after a comma in a head, queued, dropping, replacing and deciding are always suffixes, so none of them can be a parameter name there. during followed by a Name is the during suffix. Which suffixes may combine is a load rule (chapter 5).
  • The end: a Name after end, if present, must be the Handler’s name, which for a labelled Handler is its first word (end move). If an inner repeat is still open, end handlerName is a syntax error at handlerName; it cannot close through the repeat.
  • The Fallback Handler: on any message m declares a Fallback Handler. any followed by message is decided on two tokens, so on any x still declares a Handler named any. Its head is exactly one Destructuring pattern, with an optional Clause Shape and no labels, then the usual Guard and suffixes. It ends with end any message or a bare end, and end any message closes nothing else (ADR 0064).
  • finally may end a Handler’s body, as sugar for a try around it (chapter 6).

Example.

on handle {type: "invoice", amount: a} as inv where a > 1000
send review with inv to approvals
end handle
on search term, replacing
send query with term to index and wait
end search
on beforeMove m, dropping, deciding
if the to of m is in own then veto "Your own piece is on that square."
pass beforeMove
end beforeMove
on error {code: c}, during msg
tell log to write c
end error

An Argument Label names the parameter after it, in a Handler’s head and at its call sites (ADR 0055). An Operation Declaration may declare labels too, and then a call to the Operation may write them (ask world to move "pass" to "red hangar", ADR 0115).

  • The Selector: the message name and its labels make the message’s Selector, written with a colon after each part. on move piece to square handles move:to:, and on move piece handles move, a different message. A message with no labels keeps its plain name.
  • Where labels go: one leading parameter or argument, then any number of label parameter pairs. There is no comma after a label, no label before the first parameter, and no labels after a comma-separated list. The same shape holds in a Handler head, a Command Call, an event of wait for, the phrase of a target-first send, and the arguments of an Operation call (ask, the one-line tell and a tell block line).
  • Decided on one token: after a complete parameter or argument, a label word in operator position starts a label. Any reading that continues the expression comes first, so as, mod, div, contains and matches, and at, begins, ends, can, does, comes, ignoring and delimited when their two-token decision gives the operator, are never labels there. at is the one operator that yields to a label: directly in a Command Call’s or Operation call’s arguments it is Path Access only before a Path Literal, so dock ship at bay keeps its label and dock ship at /bay reads Path Access. Everywhere else, inside brackets and a function call’s ( … ) included, at takes any operand, so dock (ship at p) passes a computed Path. The parser always knows when it is in such arguments, so one token still decides (ADR 0184).
  • Lines: a label at the end of a line doesn’t continue the line. A long labelled call goes in brackets.
  • Traps: the existing reading wins. A chunk word before an open label starts a Chunk Expression (move word toward x reads word toward …), and a number before a Unit-named label is a Quantity (scale 3 m 4). Brackets avoid both: move (word) toward x, scale (3) m 4.
  • Errors: a word in operator position after an argument is now a label, so a mistake such as log error rest fails at the end of the line, where rest has no argument.

Example.

on move piece to square where square is not "e1", queued
put square into the location of piece
end move
on play
move knight to "e4" and wait
send to board: move knight to "e4"
wait for move p to sq or 30 s
end play
Block ::= ( Statement? NL )*
Statement ::= If | Repeat | Match | Try | Wait | TellBlock | TimeoutBlock | Simple
Inline ::= Simple | 'wait' ( 'for' Event Timeout? Guard? | Expression )
Simple ::= Put | Let | Set | Add | Subtract | Multiply | Divide | Delete
| Send | Ask | Tell | Return | Veto | Pass | Exit | Next | Throw
| Replace | ChooseOffer | CallStatement | CommandCall
Put ::= 'put' ( Expression ( 'into' | 'after' | 'before' )
| '...' Expression ( 'after' | 'before' ) ) Container
Let ::= 'let' Pattern 'be' Expression
Set ::= 'set' PropertyTarget 'to' Expression
Add ::= 'add' Expression 'to' Container
Subtract ::= 'subtract' Expression 'from' Container
Multiply ::= 'multiply' Container 'by' Expression
Divide ::= 'divide' Container 'by' Expression
Delete ::= 'delete' Container
Container ::= ChunkLevel ( 'at' ChunkLevel )*
/* only chunks and keys on the path to a root Name, then any `at` Path levels, or else `not a container` */
PropertyTarget ::= ChunkLevel /* a Container, or a key target with only chunks and keys on the path to me, it or the target; see chapter 4 */
Send ::= 'send' ( ( MessageName | '(' Expression ')' ) ( 'with' SendList )? 'to' Expression
| 'to' Expression ':' CommandPhrase ) ResultTarget? AndWait?
Ask ::= 'ask' Expression 'to' Word OperationArgs? ResultTarget? AndWait?
Tell ::= 'tell' Expression 'to' Word OperationArgs?
ResultTarget ::= 'into' Name
AndWait ::= 'and' 'wait'
Return ::= 'return' Expression?
Veto ::= 'veto' Expression?
Pass ::= 'pass' ( 'any' 'message' | MessageName Label* )
Exit ::= 'exit' 'repeat'
Next ::= 'next' 'repeat'
Throw ::= 'throw' Expression
Replace ::= 'replace' 'first'? ChunkLevel 'in' Container 'with' Expression
CallStatement ::= Call ResultTarget? AndWait?
CommandCall ::= CommandPhrase ResultTarget? AndWait?
CommandPhrase ::= Name ( Expression ( ( ',' Expression )* | ( Label Expression )+ ) )?
ExpressionList ::= Expression ( ',' Expression )*
OperationArgs ::= Expression ( ( ',' Expression )* | ( Label Expression )+ )
SendList ::= ListItem ( ',' ListItem )*
  • Every word that starts a statement is reserved, except next, so a statement that starts with any other Name is a Command Call or a call statement.
  • say: the grammar reads say x as an ordinary Command Call. Chapter 12 makes it short for tell console to write x.
  • Command Calls: a Name, then its arguments, if the next token can start an expression. So greet "Ann" passes one argument, blink and wait passes none, and n - 1 passes -1 to a Handler n. The arguments are a comma-separated list, or one argument followed by Argument Labels (move knight to "e4"), and the call names the Selector they make.
  • Call statements: a Name straight followed by (, with no space, is a call (refresh()), not a Command Call. With a space, ( groups an argument, so say (1 + 2) & "!" passes one argument.
  • send names its receiver last (send greet with "Ann" to board), or, after send to, first, then : and a Command Call’s phrase (send to board: move knight to "e4"). to can’t name a message, so one token decides. Only the target-first form carries labels. A bracketed expression in place of the message name computes it (send (next) with order to me), and ( can’t start a Name, so one token decides that too. In the receiver-last form, ...e in the with list spreads a list into the arguments, as in a list literal (send log with "seen", ...rest to me).
  • and wait ends a send, an ask, a Command Call or a call statement, and only as a whole statement. put f(x) and wait into y is a syntax error at and.
  • Result Targets: into and a bare Name may follow the arguments of an ask, a tell-block Operation line or a Command Call, the closing ) of a call statement, or the receiver/phrase of a send. It precedes any and wait: ask storage to load key into saved and wait. into is reserved and isn’t an operator or an Argument Label, so it ends the last expression without changing argument parsing. ask g to op into item 1 of xs is a syntax error at 1, and ask g to op and wait into x at into; the same restrictions apply to every form. One-line tell … to has no Result Target. Whether the call has a result and what the Name refers to are load rules (chapter 4).
  • Operations: the Word after ask … to or tell … to is always an Operation name, even a Reserved Word (ask files to delete path). Its arguments are a comma-separated list, or one argument followed by Argument Labels (ask world to move "pass" to "red hangar"). Labels don’t change the Operation a call names: they are checked against its declaration at load (chapter 4). No operator reads to, so after a complete argument it can only be a label, and into and and aren’t labels, so a Result Target and and wait still end the arguments. The one-line tell never takes and wait. After tell’s receiver, to gives the one-line form and the end of the line opens a tell block, so one token decides.
  • Containers: a Container is a Name, or a Chunk Expression or key path rooted in one, optionally followed by at Path levels (product at /reviews/2/rating). A Container whose root isn’t a Name, or whose path to that root contains a Built-in property, is not a container, reported at the Container’s first token (put 1 into 3, put 1 into the length of x, delete item 1 of the items of x). This applies to every statement taking a Container. set takes a property target instead: a Container, or a path whose final step is a key rooted in me, it or the target; the same Built-in property ban applies. A property target may also read through an Object Element Reference, which no other Container may contain. Bare implicit roots and chunk writes through them are not a container at the target’s first token. Property reads inside computed keys, chunk indexes or delimiters are allowed: they are expressions evaluated to select the target, not levels on its path to the root. What a root Name refers to is a load rule.
  • put ... splices a list, and so takes only after or before.
  • return and veto take an expression if one starts next. return is never an operand (chapter 1).
  • pass names the message it passes, by its name and then its labels: pass move to passes move:to:. A Fallback Handler passes its message with pass any message, decided on two tokens as in its head, so a Handler for any:message: can’t name itself in pass. exit only takes repeat, and next repeat is decided on two tokens, so next is otherwise a Name.
  • replace: at the start of a statement, replace <p> in c with e rewrites the Container c. In operand position, the same words give the new text. There, c is any expression but a Lambda, and e an expression at the level of &, so put replace <"-"> in s with "+" & x into t replaces with "+" & x, and into ends the expression, since it isn’t an operator. replace first replaces only the first match.

Offers precede every catch in a try, and finally remains last. A try may offer actions without a local catch. An offer’s parameters are plain Names separated by commas, with no defaults, patterns or Argument Labels and fixed exact arity. They follow ordinary local binding rules. Duplicate parameters report duplicate name at the second parameter; duplicate offer Names in the same try report duplicate offer at the second name. Nested tries may shadow offer Names.

choose offer skip and choose offer skip() pass no arguments; choose offer useValue(0) passes one, and choose offer useValue([1, 2]) passes one list. Parentheses use the ordinary adjacent Call opener, arguments evaluate left to right, and the formatter prints the bare form for zero arguments. A Recovery Catch places before unwind after its pattern and before an optional where Guard. Guard restrictions are unchanged.

offer is reserved, including as an identifier or bare map key: rename existing identifiers and quote map keys as "offer". choose is contextual at a statement’s start before offer, so Handlers and Command Calls named choose still work. unwind is contextual after before in a catch head; elsewhere it remains a Name.

Choice permission is lexical within a Recovery Catch and its nested blocks. Entering a function or Lambda resets it; its own Recovery Catch can grant permission again. Choices outside permission report not in recovery at choose. Dynamic availability is not a load requirement: no visible offer is needed.

A Recovery Catch has no possible Suspension Point: direct suspension and statically or transitively suspending calls report can't suspend here. Creating a Lambda does not run it; suspension through a dynamic Function Value raises would suspend at runtime. Immediate Operations remain permitted. Return, veto, pass and loop jumps to loops outside the Recovery Catch report leaves recovery catch at their first token; internal loop exits retain their normal rules. A choice is the designated recovery transfer. Existing finally restrictions also apply inside nested cleanup. All three forms are Advanced Constructs.

  • Optional endings: every block closes with end, optionally followed by its matching Name (a Handler or function) or keyword (if, repeat, match, try, wait, tell, timeout or given). Each ending closes exactly one innermost open block, regardless of indentation. Bare and explicit endings may be mixed, and a supplied suffix must match that block.
  • Lines: a closing suffix belongs on the same physical line as end; a word on the following line is never consumed as its suffix. A statement block’s ending must finish its statement. After a block Lambda’s ending, the enclosing expression continues under the usual rules, including commas, closing brackets and separators such as into.
  • Style: the full endings used in the Spec’s examples also introduce the Beginner Surface. Bare endings have the same meaning and are not Advanced Constructs. The prefer-explicit-end Lint advises explicit endings in the beginner profile (chapter 12).
If ::= 'if' Expression 'then'
( Inline ( 'else' Inline )?
| NL Block ( 'else' 'if' Expression 'then' NL Block )* ( 'else' NL Block )? 'end' 'if'? )
Repeat ::= 'repeat' ( 'for' 'each' Pattern 'in' Expression | 'while' Expression
| 'until' Expression | 'forever' | Expression 'times' )
Collecting? NL Block 'end' 'repeat'?
Collecting ::= 'collecting' Expression 'into' Name
Match ::= 'match' Expression IgnoringCase? NL ( NL | When )* ( 'else' Body NL* )? 'end' 'match'?
When ::= 'when' 'contains'? Pattern Guard? 'then' Body
Body ::= Inline NL | NL Block
Try ::= 'try' NL Block OfferClause* CatchClause* FinallyClause? 'end' 'try'?
OfferClause ::= 'offer' Name ( Name ( ',' Name )* )? NL Block
CatchClause ::= 'catch' Pattern RecoveryMarker? Guard? NL Block
RecoveryMarker ::= 'before' 'unwind'
FinallyClause ::= 'finally' NL Block
ChooseOffer ::= 'choose' 'offer' Name ( CallOpen ExpressionList? ')' )?
Wait ::= 'wait' ( 'for' ( Join | WaitBlock | Event Timeout? Guard? ) | Expression )
Join ::= 'all' NL Block 'end' 'wait'?
WaitBlock ::= NL ( NL | WaitBranch )* 'end' 'wait'?
WaitBranch ::= 'when' Event Guard? 'then' Body | 'after' Expression 'then' Body
Event ::= MessageName ( Pattern ( ( ',' Pattern )* | ( Label Pattern )+ ) )? ( 'from' ChunkLevel )?
Timeout ::= 'or' Expression
TellBlock ::= 'tell' Expression NL ( OperationLine? NL )* 'end' 'tell'?
OperationLine ::= Word OperationArgs? ResultTarget? AndWait?
TimeoutBlock ::= 'with' 'timeout' 'of' Expression NL Block 'end' 'timeout'?
  • One-line if: if … then followed by a statement on the same line is the one-line form, and its else must be on that line too. Each branch is one Inline statement: not an if, repeat, match, try, Join or block wait for.
  • Block if: if … then at the end of a line opens a block, closed by end or end if. An else if … then or else ends its line too.
  • repeat: forever straight after repeat always means a loop with no end, and never a count. A count is any expression before times.
  • collecting: any repeat head may end with one collecting e into v, where v is a Name. collecting is in the FOLLOW set, so repeat for each c in item collecting c into cs reads item as a Name, and into ends e, since it isn’t an operator. So collecting x into item 1 of xs is a syntax error at 1, and a second collecting at that word (ADR 0059).
  • match: each when has one pattern, then an optional Guard. when contains <…> searches rather than matching the whole value. At most one else comes last. A branch body is an Inline statement on the same line, or a block.
  • wait for: an event, optionally with from and a timeout (wait for click from okButton or 30 s). An event’s patterns take Argument Labels as a head’s parameters do (wait for move p to sq), and since from is never a label, it always starts the source. from takes a postfix-level operand, so the or there is the timeout. A Guard comes last, after any timeout (wait for pressed key or 30 s where key = "Y"): the timeout’s expression ends at where, and the Guard runs to the end of the line, so an or in it is boolean (ADR 0109). At the end of a line, wait for starts a block of when and after branches, and wait for all starts a Join. Neither block has a one-line form.
  • try: catch clauses are Destructuring heads with optional Guards, tried top to bottom (chapter 6).
  • tell block: tell g at the end of a line opens a block of Operation lines, closed by end or end tell (ADR 0063). A line’s first word is always an Operation name, even a Reserved Word, except that end always closes the block. So put url, {json: order} and wait in a tell http block calls http’s put. Nothing but Operation lines, blank lines and comments goes in the block, so a line starting if or tell is an Operation named if or tell, and an empty block is allowed. It is a full statement, not an Inline, so a one-line if or when can’t hold one. What each line calls is in chapter 4.
  • Timeout Block: with timeout of and an expression at the end of a line opens a block, closed by end or end timeout (ADR 0073). At the start of a statement, with followed by timeout always opens one, and otherwise with starts a Command Call. timeout is a keyword only there and after the block’s end, and stays a Name elsewhere. There is no one-line form, and it is a full statement, not an Inline. What it bounds is in chapter 5.

Example.

if the length of fruit > 3 then say "lots" else say "a few"
repeat for each [k, v] in pairs
if v is empty then next repeat
say k
end repeat
match msg
when <"ID-", num: 4 digits as number> then put num into id
when contains <"WARN"> then tell log to write msg
else put nothing into id
end match
wait for all
repeat for each s in stations
send allReadings with s to me and wait
end repeat
end wait

Default is the lowest ordinary binary precedence, left-associative. A trailing Whose Clause still requires an ordinal Chunk Expression as its whole preceding operand. Restricted replace subjects and replacements need parentheses around a default expression.

After the, optional followed by of selects the existing ordinary key; otherwise the registered optional-key two-token decision selects an optional map-key read. Neither otherwise nor optional is Reserved or Advanced. otherwise is excluded as an Argument Label and belongs to FOLLOW, so an index variable of that name must be grouped: item (otherwise) of xs. See the migration guide before changing labelled message producers or consumers.

Expression ::= Lambda | EveryHead Whose | Default Whose?
/* `Whose` after `Default` only when it is an ordinal Chunk Expression, with or without its `delimited by`,
or an ordinal Object Element Reference */
Default ::= Or ( 'otherwise' Or )*
OptionalKey ::= Key | Text | '(' Expression ')'
Lambda ::= 'given' ( Pattern ( ',' Pattern )* )? ( ':' Expression | NL Block 'end' 'given'? )
Or ::= And ( 'or' And )*
And ::= Not ( 'and' Not )* /* never `and` before `wait` */
Not ::= 'not' Not | Comparison
Comparison ::= Concat ( Comparator IgnoringCase? )?
Comparator ::= ( '=' | '<>' | '<' | '>' | '<=' | '>=' | 'contains' | 'matches'
| 'begins' 'with' | 'ends' 'with' | 'comes' ( 'before' | 'after' )
| 'does' 'not' ( 'contain' | 'begin' 'with' | 'end' 'with' | 'match' ) ) Concat
| 'is' 'not'? ( 'in' Concat | Article Kind | 'empty' | Ordering Concat | Concat )
| 'can' 'be' Article? Kind
Ordering ::= ( 'greater' | 'less' ) 'than' | 'at' ( 'least' | 'most' )
Article ::= 'a' | 'an'
IgnoringCase ::= 'ignoring' 'case'
Concat ::= Range ( '&' Range )*
Range ::= Additive ( '..' Additive )?
Additive ::= Multiplicative ( ( '+' | '-' ) Multiplicative )*
Multiplicative ::= Power ( ( '*' | '/' | 'mod' | 'div' ) Power )*
Power ::= Unary ( '^' Power )?
Unary ::= '-' Unary | Conversion
Conversion ::= PathAccess ( 'as' ( Unit | Kind ) )*
/* inside a BuildField, `as` before an integer type, a number, `(` or `^` ends the value */
Kind ::= 'civil' 'date' | 'function' | Name
PathAccess ::= ChunkLevel ( 'at' ChunkLevel )*
/* directly in a Command Call's or Operation call's arguments, `at` must be followed by a PathLiteral */

The operators, lowest precedence first:

Level Associativity Operators
1 left otherwise
2 left or
3 left and
4 prefix not
5 none =, <>, <, >, <=, >=, is, is not, is in, is not in, is a, is not a, is empty, is not empty, can be, contains, begins with, ends with, matches, does not contain, does not begin with, does not end with, does not match, is greater than, is not greater than, is less than, is not less than, is at least, is not at least, is at most, is not at most, comes before, comes after
6 left &
7 none ..
8 left +, -
9 left *, /, mod, div
10 right ^
11 prefix -
12 postfix as
13 left at
14 postfix of, 's, f(…)
  • Lambdas have the lowest precedence of all. The body of given r: … runs to the next top-level comma or closing bracket, so map(xs, given r: r * 2, 2) passes 2 as a third argument. A block Lambda (given r at the end of a line) ends with end or end given. Zero parameters are written given: e, or given alone at the end of a line.
  • Whose Clauses are whole expressions too, as Lambdas are. The condition after whose runs to the next top-level comma, closing bracket or word that ends an expression, such as into or then. Inside an operand a Whose Clause needs brackets: the length of (every item of xs whose it > 1), and (the first item of xs whose it > 3) is empty. Without them, 1 + every item of xs whose … is a syntax error at item, and if the first item of xs whose it > 3 is empty then … one at is, since comparisons don’t chain.
  • Comparisons don’t chain: a = b = c is a syntax error at the second =.
  • is: after is or is not, in tests membership, a or an before a kind tests the kind, empty tests emptiness, greater than, less than, at least and at most order, and anything else is equality. So x is a number is a kind test, and x is a then … compares x with a variable a. Likewise x is at least 3 orders, and x is at compares x with a variable at.
  • English comparison words spell existing comparisons (ADR 0075). does not takes contain, begin with, end with or match, and anything else after it is a syntax error at that token. comes takes before or after. Each is decided on its first two words: does without not, and comes without before or after, end the expression, as begins without with does.
  • Kinds: a kind or Unit after is a, can be or as is a Name, civil date, or function, the one Reserved Word that names a kind, so f is a function works. After is a, the Name may also be a named Shape. Which names are kinds or Shapes is a load rule (chapter 3).
  • Unary minus binds tighter than ^, so -2 ^ 2 is 4.

Each trailing modifier attaches to its own construct:

Modifier Attaches to
as the operand before it, as a postfix operator above every binary operator but at, and below at, chunk of, 's and calls
ignoring case the nearest comparison before it, a match subject, or a Text Pattern element
delimited by the outermost Chunk Expression of an of chain
whose an Every Head, or an ordinal Chunk Expression or ordinal Object Element Reference that is a whole operand, and ends the expression, as a Lambda does
lazily a Text Pattern element
and wait a send, an ask, a Command Call or a call statement, and only as a whole statement
little, big an integer field of a Binary Pattern or build
  • as: item 2 of line 3 of r as number * 2 means ((item 2 of line 3 of r) as number) * 2.
  • ignoring case binds to the nearest comparison, so in a is b and c is d ignoring case it applies only to c is d. Functions take no ignoring case, so a case-insensitive search passes a Text Pattern, as in offset(<"abc" ignoring case>, s).
  • delimited by: in item 2 of line 3 of r delimited by ";", the delimiter belongs to the whole chain.
ChunkLevel ::= Postfix ( 'delimited' 'by' Postfix )?
/* `delimited by` only after a Chunk Expression or a plural chunk property */
Postfix ::= Primary ( "'s" Key )*
Key ::= 'code' 'points' | Word
Primary ::= Number Unit? | Text | InterpolatedText | PathLiteral | TextPattern | BinaryBuild | '(' Expression ')'
| List | Map | 'true' | 'false' | 'nothing' | 'it' | 'me'
| The | ReplaceExpression | MatchSearch | ObjectElement | Chunk | Call | Name
Call ::= Name CallOpen ExpressionList? ')'
Chunk ::= ChunkWord Range 'of' Postfix
ChunkWord ::= 'code' ( 'point' | 'points' ) | Name /* a chunk kind's singular or plural */
ObjectElement ::= ( 'element' | 'elements' ) Range 'of' Postfix
/* an Object Element Reference, decided as a Chunk is */
The ::= 'the' ( 'optional' OptionalKey 'of' Postfix
| '(' Expression ')' 'of' Postfix | Text 'of' Postfix | 'target'
| Ordinal ( 'code' 'point' | Name ) 'of' Postfix
| 'number' 'of' 'elements' 'of' Postfix | Key 'of' Postfix )
/* the Name after an Ordinal is a chunk kind's singular or `element`;
`number` `of` is an Element Count only before `elements` `of` */
Ordinal ::= Name /* one of grammar.toml's ordinals */
MatchSearch ::= 'every' 'match' 'of' ChunkLevel 'in' Concat
EveryHead ::= 'every' ( 'code' 'point' | Name ) 'of' Postfix ( 'delimited' 'by' Postfix )?
/* the Name after `every` is a chunk kind's singular or `element`; `delimited by` never follows `element` */
Whose ::= 'whose' Expression
/* a Name operand that is the Expression's first token is a Whose Key, a key or property of `it` */
ReplaceExpression ::= 'replace' 'first'? ChunkLevel 'in' Or 'with' Concat
List ::= '[' ( ListItem ( ',' ListItem )* )? ']'
ListItem ::= '...'? Expression
Map ::= '{' ( MapKey Expression ( ',' MapKey Expression )* )? '}'
MapKey ::= ( Word | Text ) ':' /* a Word key may not be `offer` */
  • Chunk words: a chunk word followed by a token that can start an index is a Chunk Expression. An index starts with a Number, a Text, -, [, ( with a space before it, a Name that isn’t in the FOLLOW set, or the, it or me. Anything else makes the chunk word a Name. So put 5 into line and line 3 of report both work, but put line - 1 into x reads line -1 of … and fails at into, and needs (line) - 1.
  • Object Element References: element or elements followed by a token that can start an index is an Object Element Reference, decided as a chunk word is: element 3 of thisPage, element ("cell_" & n) of p. An ordinal followed by element after the is one too: the last element of p. After the number of, elements followed by of is an Element Count, the number of elements of p; otherwise the number of x reads the key number. None of these words is reserved, so put element into e and element(3) still work, but put element - 1 into n reads element -1 of … and needs (element) - 1. An Object Element Reference takes no delimited by and no Whose Clause (the object element contract).
  • Keys and properties: the <word> of x reads a key, unless the word is a Built-in property below. Any Word may follow the or 's, Reserved Words included, and code points is read as one. the "any key" of m always reads a key, and the (k) of m computes one.
  • Ordinals name a chunk only after the, and only when a chunk kind’s singular follows (the last word of s). Otherwise the ordinal is a key.
  • the target is the object a message was sent to. the target of x is a key named target.
  • Calls need a name: name( with no space is the only call. A call’s result can’t be called again, so times(3)(14) is a syntax error at the second (.
  • Lists and maps: ... spreads a list into a list literal. In a map literal, a Word other than offer or a Text followed by : is a key, other Reserved Words included. A map literal has no computed keys.
  • The Match Search is every match of <p> in s.
  • Whose Clauses: at the start of an expression, every followed by a chunk kind’s singular, or by code, starts an Every Head, every item of xs, which must be followed by whose (ADR 0074). An ordinal Chunk Expression that is a whole operand may be followed by whose too, after its delimited by if it has one: the first item of s delimited by ";" whose it is empty. whose after any other operand is a syntax error, and so is whose in a Container. A Name operand that is the condition’s first token is a Whose Key, a key or property of it (chapter 4), so whose amount > 1 parses as whose the amount of it > 1, and whose (amount) > 1 reads the name amount. Any other every is a Name.

The chunk kinds:

Chunk kind Plural
character characters
word words
line lines
item items
byte bytes
code point code points

The ordinals:

first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, last

The Built-in property names, which the <name> of x reads instead of a key:

length, keys, values, items, lines, words, characters, bytes, code points, elements

Example.

put word 2 of line 3 of report into w
put characters 2..4 of w into mid
put the last word of s into tail
put the length of the words of s into count
put person's age into a
put the "full name" of person into fn
put item 2 of "a;b;c" delimited by ";" into b
put [...fruit, "plums"] into more
put every match of <digits> in "a1 b22" into hits
Pattern ::= PatternPrimary ( 'as' Name )?
PatternPrimary ::= ListPattern | MapPattern | PathPattern | TextPattern | BinaryPattern | Pin | Literal | '_' | Name
PathPattern ::= PathLiteral ( 'is' Pattern )?
ListPattern ::= '[' ( ListPatternItem ( ',' ListPatternItem )* )? ']'
ListPatternItem ::= '...' Name? | Pattern
MapPattern ::= '{' ( MapPatternEntry ( ',' MapPatternEntry )* )? '}'
MapPatternEntry ::= MapKey Pattern | Name
Pin ::= '^' Name
Literal ::= Text | '-'? Number Unit? | 'true' | 'false' | 'nothing'
  • Where Destructuring goes: Handler heads, let, match … when, catch, repeat for each, Lambda parameters and wait for events.
  • A Name binds, and _ matches anything without binding. In a map, a Name alone is short for {name: name}.
  • as name after a pattern binds the whole value it matched.
  • Literals match by =: a Text, a Number with an optional sign and Unit, true, false and nothing. A text literal in a catch or on error head is short for {code: "…"} (chapter 6).
  • The pin ^name compares with an existing variable instead of binding.
  • No kind tests inside a pattern: a kind test goes in the Guard, as in where a is a number.
TextPattern ::= PatternOpen ( Alternation ( ',' Alternation )* )? PatternClose
Alternation ::= Element ( 'or' Element )*
Element ::= Atom ( 'as' Kind | 'lazily' | 'ignoring' 'case' )*
Atom ::= Text | Number Atom | TextPattern | '(' Expression ')' | Capture
| Anchor | PatternClass | Repetition | Article Kind | PatternKeyword
Capture ::= Name ':' Alternation
Anchor ::= ( 'text' | 'line' ) ( 'start' | 'end' ) | 'word' 'break'
PatternClass ::= ( 'uppercase' | 'lowercase' ) ( 'letter' | 'letters' )
Repetition ::= ( 'one' | 'zero' ) 'or' 'more' 'of' Atom | 'optional' Atom
PatternKeyword ::= Name /* one of grammar.toml's Text Pattern keywords */
  • Keywords: character, characters, digit, digits, letter, letters, punctuation, space, spaces, text, whitespace, word, words.
  • Classes: lowercase letter, lowercase letters, uppercase letter, uppercase letters.
  • Anchors: line end, line start, text end, text start, word break.
  • Repetitions: one or more of, optional, zero or more of.
  • Bare words: a bare Word inside <…> is a Text Pattern keyword, part of a class, anchor or repetition, the article of a Typed Element (a number), or, when a : follows, a Capture. Anything else is a syntax error at the word.
  • Captures: a Word followed by : names a Capture, and a Reserved Word can’t, so <end: word> is a syntax error at end.
  • Anchors are two words, decided on two tokens. end alone means nothing inside <…>.
  • Grouping is a nested <…>: one or more of <letter or digit>. ( … ) always holds an expression, whose value is spliced in (<"ID-", (idPat)>), so (letter or digit) would splice a boolean.
  • Modifiers trail the element they modify: "x" ignoring case, text lazily, 4 digits as number.
BinaryPattern ::= BinaryOpen ( Field ( ',' Field )* )? '>>'
Field ::= '...' Name? AsText? | Number | Text | ( Name | '_' ) ':' FieldType
/* the Name after `...` isn't `as` */
FieldType ::= IntegerType ByteOrder? | Size SizeUnit AsText?
IntegerType ::= Name /* one of grammar.toml's integer types */
ByteOrder ::= 'little' | 'big'
Size ::= Number | Pin | Name | '(' Expression ')'
/* inside the parentheses, a Pin is also a Primary */
SizeUnit ::= 'byte' | 'bytes' | 'bit' | 'bits'
AsText ::= 'as' 'text'
BinaryBuild ::= BinaryOpen ( BuildField ( ',' BuildField )* )? '>>'
BuildField ::= Concat ( 'as' FieldType )?
  • Integer types: int8, int16, int32, int64, uint8, uint16, uint32, uint64.
  • Size units: bit, bits, byte, bytes.
  • Byte orders: big, little.
  • Fields: in a Binary Pattern, a Word followed by : names a field, and a Number or Text is a literal field. ... ends the pattern, optionally binding the rest.
  • Sizes are a Number, a Name bound earlier in the pattern, a pinned ^n, or a parenthesised expression, inside which ^n may also appear ((^n * 2) bytes).
  • Building: in << … >> in operand position, each field is a value with an optional as type. as followed by an integer type, a number, ( or ^ ends the value and starts the field type, so << the length of b as uint16, b >> and << flags as 4 bits, mode as 4 bits >> need no parentheses. A size held in a name is written in parentheses, v as (n) bytes, since as n would read as a conversion. Inside brackets within the value, as is a conversion again.

Example.

on packet << 0x02, id: uint32, x: int16 little, body: len bytes, ...rest >>
send moved with << 0x02, id as uint32, x as int16 >> to lobby
end packet

These are the only places where the parser reads a second token before it chooses. Everywhere else, one token decides.

Decision Rule
and-wait and followed by wait ends the expression before it, and is never a boolean and
any-message after on, pass or a Handler’s end, any followed by message names the Fallback Handler; otherwise any is a Name
as-in-build inside << >>, as followed by an integer type, a number, ( or ^ ends the value and gives the field type
at-path directly in a Command Call’s or Operation call’s arguments, at followed by a Path Literal is Path Access, and otherwise the word ends the argument, so it may be an Argument Label; everywhere else at in operator position is Path Access
begins-with begins or ends followed by with is the operator; otherwise the word ends the expression
binary-field in a Binary Pattern, a word followed by : names a field
can-be can followed by be is the kind test; otherwise the word ends the expression
capture in a Text Pattern, a word followed by : is a Capture
choose-offer at the start of a statement, choose followed by offer is a choice; otherwise choose starts a Command Call
chunk-word a chunk word, element or elements followed by a token that can start an index, and isn’t a FOLLOW-set word, is a Chunk Expression or an Object Element Reference; otherwise it is a name
code-point code followed by point or points is the chunk kind
comes comes followed by before or after is the operator; otherwise the word ends the expression
delimited-by delimited followed by by is the modifier
does-not does followed by not is the operator, and contain, begin with, end with or match must follow; otherwise the word ends the expression
during after a comma in a Handler head, during followed by a word is the modifier
element-count after the number of, elements followed by of is an Element Count; otherwise number was an ordinary key
every-chunk at the start of an expression, every followed by a chunk kind’s singular, or by code, starts an Every Head
every-match every followed by match starts a Match Search; otherwise every is a name, unless every-chunk applies
ignoring-case ignoring followed by case is the modifier
is-a after is or is not, a or an followed by a word that isn’t reserved, or by function, starts a kind test; otherwise it is a name
kind civil followed by date is the kind civil date
map-key in {…}, a word or text followed by : is a key, Reserved Words except offer included; in a map pattern, a word without : is the shorthand {name}
next-repeat at the start of a statement, next followed by repeat is the loop statement; otherwise next starts a Command Call
optional-key after the, optional followed by of is an ordinary key; otherwise it introduces an optional map-key read
ordinal after the, an ordinal followed by a singular chunk word (or code) is an ordinal chunk, and followed by element an ordinal Object Element Reference; otherwise it is a key
ordering-words after is or is not, greater or less followed by than, or at followed by least or most, is the operator; otherwise the word is a Name
pattern-anchor in a Text Pattern, text, line or word followed by the second word of an anchor is that anchor
replace-first after replace, first followed by anything but in means only the first match
repeat-with straight after repeat, with followed by a Name that isn’t in the FOLLOW set is HyperTalk’s counted loop, the syntax error repeat with; otherwise with starts the count
shape-of at the start of a Shape Term, list or object followed by of is a wrapper, and a or an followed by quantity starts a Unit Kind Shape; otherwise the word is a kind, a Unit or a Shape name
script-variable at top level, script followed by variable starts a Script Variable
target after the, target not followed by of is the target
wait-from in an event, from followed by a token that can start an operand is the sender; otherwise it is a name in the event’s patterns
when-contains after when in a match, contains followed by < is a search; otherwise contains is a name
with-timeout at the start of a statement, with followed by timeout opens a Timeout Block; otherwise with starts a Command Call

The second token of each decision is lexed in the same mode under both readings, so choosing never changes how a token was lexed.

Note. tools/grammar/ holds a parser that follows this chapter, reads its word lists from grammar.toml, throws on a third token of lookahead and names every two-token decision it takes. bun run grammar:check runs it over the syntax sketch, every talk block in docs/ and spec/, the corpus, and the broken cases in tools/grammar/broken.talk, whose first errors it checks. CI runs it on every pull request. Like all tooling, it isn’t normative (ADR 0028).

Every Core accepts every construct. These are tagged Advanced for tooling only, and a Lint in the beginner Lint Profile flags them (ADR 0027). The tags are published with the language version but aren’t covered by parity.

Advanced Construct Written Beginner Surface form
The pin ^name in a pattern, e.g. {order: ^orderId} {order: o} where o = orderId
A pinned Binary Pattern size ^n bytes, or ^ inside a parenthesised size a Guard on the length the pattern read, or ...rest and then bytes 1..n of rest
The code point chunk code point 1 of s, code points 2..3 of s Characters
The code points property the code points of s Characters
lazily after a Text Pattern element, e.g. text lazily a narrower element
A computed message name send (e) with a to r, e.g. send (next) with order to me a match or if that picks between sends that name their message
A Recovery Offer offer name with optional plain parameters and a recovery block a local catch that calls an explicitly supplied policy callback
A Recovery Catch catch pattern before unwind with an optional Guard an ordinary local catch with an explicitly supplied policy callback
An offer choice choose offer name with optional call arguments a policy callback that returns a decision to a local catch
A spread in send … with ...e in a receiver-last send’s with list, e.g. send (the name of m) with ...(the args of m) to other the arguments listed one by one in with
Code Raised when
bad path A Path Literal ends with /, or a segment runs straight into another segment’s characters, such as /user${id} or /2a
bad character A character outside a text literal or comment starts no token
unterminated text An ordinary text literal is unclosed at its line end, or a fenced literal is unclosed at EOF; reported at its opener
bad unit A Unit after a numeric literal names a factor the Unit Catalogue doesn’t have, has a malformed or negative exponent, or names two Units of one Unit Kind
unit without number A Unit word can’t continue the parse and follows a Name or a closing bracket on its line; a Unit follows only a number literal, so write x as s, x * 1 s, or the Unit in the Constant; reported at the Unit word
unexpected token A token can’t continue the parse, including the end of a line or of the source
reserved word A Reserved Word stands where the grammar wants a Name: a Container root (other than the, which starts a property path, or a Constant), a Handler, message, function or Capture name, a parameter, a pattern binding, a let name, a collecting target, a Result Target or a Whose Key (a Reserved Word that can’t start the Whose Clause’s condition); checked before unexpected token and not a container, and reported at the Reserved Word
repeat with repeat is followed by with and a Name that isn’t in the FOLLOW set, as in HyperTalk’s repeat with i from 1 to n or repeat with i = 1 to n; NorthTalk counts with repeat for each i in 1..n; reported at with
not a container A Container’s root isn’t a Name, or its path to the root contains a Built-in property or, outside a set property target, an Object Element Reference; reported at the Container’s first token
unterminated interpolation A hole is unclosed at EOF; reported at its dollar-brace opener
empty interpolation An interpolation hole contains no expression
invalid text escape A backtick escape is malformed, octal, or produces an unpaired surrogate
invalid text indentation Fenced text does not match its closing margin
invalid text delimiter A raw closing quote run is longer than its opening fence
  • Only the first syntax error is normative: its code and its position. The parse stops there.
  • Its position is the first token that can’t continue the parse. A lexical error is reported where its token starts, except bad path, at the character that breaks the Path Literal, reserved word at the Reserved Word, and not a container at the Container’s first token. Where a Name is wanted, one token decides whether the word is a Reserved Word, so reserved word comes before unexpected token and not a container: put 1 into replace reports replace, not the end of the line. Argument Labels aren’t Name positions here, since a Reserved Word after a parameter can end a Handler head.
  • Its range runs from its position to the end of the token there, so a Host can mark the whole token. A line end and the end of the source have no characters, so their range is empty: it ends where it starts. A load-time diagnostic’s range is the same: the token it is reported at, or for a use line, its use, and an empty range where no token starts at its position. A range crosses a line only for a multi-line text literal. Ends are given like positions, in lines and columns, and are exclusive.
  • Error order: lexical and parse errors come first, then load-time diagnostics in source order. Since the parse stops at the first syntax error, source with one has no other load-time diagnostics.

Example. In put 5 into followed by a comment, the error is at the end of the line, after the comment. In if count > then say "x", it is at then. In put <"a", bogus> into x, it is at bogus.

Source that parses is then checked, and each rule it breaks is a load error: the Script, Library or Entry doesn’t load. The chapters state the rules, and diagnostics.toml gives each one its code. A code covers a family of rules, and no code is shared with a syntax error, an Error Code or a Host error.

A local Handler may share a Script Variable’s or Constant’s name without a name clash, regardless of declaration order. Value references and Command Calls resolve separately (chapter 4).

Code Raised when Reported at Sources
unknown name A Name resolves to nothing (chapter 4), including a well-known object the Host didn’t bind, or a Binary Pattern size names a name that isn’t bound earlier in the pattern the Name ADR 0016, ADR 0019, #115
not a value The bare name of a Handler or a Built-in function is used as a value the name ADR 0025, #115
name clash A name has two meanings: a variable named like a function of the unit or an Import, a parameter, pattern binding, Capture or collecting target named like a Script Variable, a Constant or a well-known object, a collecting target named like a name its own repeat for each pattern binds, an imported name, after any rename, named like a local Handler, function, Constant, Script Variable or well-known object, two Imports of one name, or a Library Handler that an importer also defines the later of the two in the source; for an Import, its name in the use line ADR 0020, ADR 0059, #115
duplicate name One pattern binds the same Name twice, a Text Pattern has two Captures with one name, or an offer repeats a parameter Name the second ADR 0010, #115
duplicate offer A try declares two offers with the same Name the second offer Name ADR 0060, #387
not in recovery A choice is outside a lexically enclosing Recovery Catch; functions and Lambdas reset permission choose ADR 0060, #387
leaves recovery catch A Recovery Catch contains return, veto or pass, or a loop jump whose loop is outside it the statement’s first token ADR 0060, #387
duplicate key A map literal names a key twice the second key #115
unknown kind A name after is a, as or can be isn’t a kind name, integer or a Unit, nor, after is a, a named Shape in scope, or a Text Pattern’s a or an is followed by a kind other than number the kind name ADR 0003, ADR 0034, ADR 0168, #115
bad shape A Shape declaration names a Name that is no kind, Unit or named Shape in scope, a Unit that doesn’t parse, or a Unit Kind or, with a Host Manifest, an Object Kind that doesn’t exist, repeats a key in one Shape Map, reaches itself through named Shapes, or is named like a kind, any, value, a Unit or a Unit Kind (chapter 7) the offending token: the Name, Unit or key, the first Name on a cycle in source order, or the declared name ADR 0168, #2055
no conversion as names a kind that has no conversion, or a Text Pattern’s as number follows an element that can match something other than ASCII digits or a number as ADR 0003, #115
bad number A number literal has more than 34 significant digits, a magnitude of 10^34 or more, or more than 6176 fraction digits the literal ADR 0002, ADR 0034, #115
pattern too large A Text Pattern with no splices compiles to a program over the Script’s patternSize, counting every copy of a counted repetition the pattern’s opening < ADR 0007, #92, #115
wrong argument count A call to a function, the unit’s own or imported, passes fewer arguments than its parameters without defaults, or more than all of them, a Capability call passes a number of arguments its Operation Declaration doesn’t take, or say has no argument or more than one the function’s or Operation’s name, or say ADR 0030, ADR 0035, #115
wrong argument A literal argument of a Capability call breaks its parameter’s Shape: a literal of the wrong kind, or a closed map literal whose keys don’t fit the argument’s first token ADR 0030, #115
wrong labels A labelled ask, tell or tell block line writes an Argument Label that isn’t the one its Operation Declaration gives that position, or labels an Operation that declares none; a wrong argument count is wrong argument count instead the first label that doesn’t match ADR 0115, #1341
unknown operation ask, tell or a tell block names a Grant the Script doesn’t hold, including one revoked before a Reload, or an Operation its Grant doesn’t declare the Grant’s name, or the Operation’s ADR 0012, ADR 0015, ADR 0063, #115
wrong mode A call doesn’t fit its Operation’s mode: ask … and wait on an immediate Operation, ask without and wait on a suspending one, ask on a fire-and-forget one, tell … to on one that isn’t fire-and-forget, a tell block line or Host Command whose and wait is there on an Operation that isn’t suspending, or missing on one that is, or a fire-and-forget tell block line or Host Command (including say) with a Result Target ask or tell, a tell block line’s Operation name, or the Host Command’s name ADR 0012, ADR 0063, ADR 0094, ADR 0114, #115, #1350
missing and wait A Command Call to a Handler that may suspend has no and wait, or a send or a Command Call resolved to the Message Path has a Result Target without and wait the Handler’s name, send, or the Command Call’s name ADR 0012, #115, ADR 0114, #1350
needless and wait A Command Call with and wait names a Handler that can’t suspend, or say has and wait the Handler’s name, or say ADR 0012, #115
can't suspend here A possible Suspension Point is in a finally block or a Recovery Catch, or a named function, or a Handler called function-style, reaches one, directly or through what it calls, or a Script loaded with forbidSuspension holds one or calls a Handler that may reach one the Suspension Point, or the call in the function or Handler through which it reaches one, or the call to a Handler that may suspend ADR 0017, ADR 0020, #115, ADR 0178, #2237
unknown import A use line names a Library the Group doesn’t hold, or a name the Library doesn’t export the Library’s name, or the name ADR 0020, #115
import cycle Libraries import each other in a cycle the use line that closes the cycle ADR 0020, #115
missing grant A Library the Script imports, directly or through another Library, needs an Operation that the Script’s Grants don’t give the use line ADR 0020, #115
not in a library Library code uses me, the target, pass, veto, send or a well-known object name, names a Script in a wait for’s from, or has a top-level script variable or a Fallback Handler its first token, or the Script’s name ADR 0016, ADR 0020, ADR 0064, ADR 0113, #115
not in a script A Script’s declaration starts with private private ADR 0020, #115
not in a lambda pass or the target is inside a Lambda pass or the ADR 0025, #115
not in a guard A Guard calls anything but a Built-in, a call through a name that shadows a Built-in included, holds a Lambda, reads a non-id key of a Host Object known at load, or holds an Object Element Reference or Element Count; a computed key on such an object must be the text literal id the call’s name, the Lambda’s given, the key’s the or 's, or the reference’s first token ADR 0025, ADR 0100, #115, #1143
not in a whose A Whose Clause’s condition calls anything but a Built-in, a call through a name that shadows a Built-in included, or holds a Lambda the call’s name, or the Lambda’s given ADR 0074, #525
not in a join A Join’s body holds wait, wait for, a nested Join, name … and wait, f(x) and wait, return, veto, pass, an exit repeat or next repeat whose loop is outside the Join, a member inside a try its first token or the member’s ADR 0026, #115, ADR 0114, #1350
empty join A Join has no member in its source its wait ADR 0026, #115
not in a timeout A Timeout Block’s body holds name … and wait or f(x) and wait outside a Lambda the call’s first token ADR 0073, #524
empty timeout A Timeout Block has no Suspension Point in its source outside a Lambda, which includes every Timeout Block in a Join’s body its with ADR 0073, #524
leaves finally A return, veto or pass is inside a finally block, or an exit repeat or next repeat inside one belongs to a loop outside it its first token ADR 0017, #115
outside a loop An exit repeat or next repeat is outside any loop its first token #115
veto outside a decision veto is outside a , deciding Handler: in a function, a Lambda, or a Handler reached by a local call, Command Call or function-style veto ADR 0031, #115
after a suspension A veto or pass in a , deciding Handler is reached, on some path from the Handler’s start, through a possible Suspension Point veto or pass ADR 0031, #115
wrong message pass m names a message other than the one its Handler handles, pass any message is outside a Fallback Handler, or a Fallback Handler’s pass names a message the message’s name, or any ADR 0064, #115
negated shape A Handler head’s Clause Shape is written is not a or is not an; write the test as a Guard not ADR 0171, #2056
bad suffixes A Handler head has more than one of queued, dropping and replacing, a suffix twice, , queued with , deciding, , during on a Handler other than on error, or , deciding on a Fallback Handler the first suffix that breaks the rule ADR 0031, ADR 0064, #115
can't write A Container or Result Target writes a Constant, a Lambda puts into a captured local, the body of a repeat that collects writes its collecting target, through a Container rooted in it, a Result Target, a pattern that binds it or an inner loop that collects into it, or set writes a read-only property of a Host Object whose kind and key are known at load, or delete names the empty Path Literal / the Container’s root, the Result Target’s Name, the binding, the inner loop’s collecting target, set, or the / ADR 0016, ADR 0025, ADR 0059, #115, ADR 0114, #1350, ADR 0184
not a property set writes a bare variable or an Object Element Reference, not a key of a Host Object set ADR 0016, #115
not constant The initialiser of a Constant or a Script Variable, or a parameter’s default, uses anything but literals, Constants declared above it and Built-ins, calls random, or holds an Object Element Reference or Element Count the first token that isn’t allowed ADR 0035, #115
default order A parameter without a default follows one with a default the parameter ADR 0035, #115
initialiser failed An initialiser raises an error when the unit loads the raising instruction’s position in the source map #115
nothing to fold ignoring case follows is a, can be or is empty, which compare no text ignoring #115
no item chunk delimited by ends a Chunk Expression chain that has no item chunk delimited #115
capture in repetition A Text Pattern’s Capture is inside a repetition the Capture’s name ADR 0007, #115
rest not last A ... or ...rest is anywhere but last in a list pattern or a Binary Pattern the ... ADR 0013, #115
bits not whole bytes A run of bit fields in a Binary Pattern or a << … >> build doesn’t add up to whole bytes the run’s first field ADR 0013, #115
bad position A Path Literal has the position 0 or -0, a position written with a leading zero such as 007, or one whose magnitude is past the Path position limit, 2147483647 (chapter 3) the Path Literal ADR 0184
  • All of them are normative: every diagnostic, its code and its position, which is the token its entry gives, in the unit’s own lines and columns.
  • Order: by position, and at one position in the order the table lists their codes.
  • One per construct: a construct that breaks one rule several times, such as a call with two arguments too many, has one diagnostic.
  • Messages: the wording of a syntax error. Its code and position are normative.
  • Recovery: anything a Core or tooling reports after the first syntax error (ADR 0028).
  • Syntax trees: the shape of a Core’s tree. Only the parse, as the lowering shows it, is normative.
  • Tags and Lints: the Advanced tags and every Lint (ADR 0027).