# Syntax

This is a descriptive grammar. `{ X }` means zero or more repetitions, `[ X ]`
means optional, and `|` expresses alternatives. Terminals appear in quotes;
uppercase names are lexical tokens.

## File and declarations

```ebnf
program          = [ NL ], [ module_doc ], { declaration },
                   [ private_line, { declaration } ], EOF ;
private_line     = "private", NL ;
module_doc       = DOC, NL, NL ;
declaration      = import_decl | reexport_decl | extern_decl
                 | [ DOC, NL ], ( constant_decl | function_decl | struct_decl | enum_decl
                 | alias_decl ) ;
constant_decl    = CONST_NAME, [ ":", type ], "=", expression, NL ;
import_decl      = "import", ( TYPE_NAME | name_list ), "from", STRING, NL ;
name_list        = "{", import_name, { ",", import_name }, [ "," ], "}" ;
import_name      = ( NAME | TYPE_NAME ), [ "as", ( NAME | TYPE_NAME ) ] ;
reexport_decl    = "export", TYPE_NAME, ".", ( NAME | TYPE_NAME ), NL ;

function_decl    = "def", NAME, [ type_parameters ], "(", [ parameters ], ")",
                   "->", type, ( NL, block, "end" | "=", expression ), NL ;
parameters       = parameter, { ",", parameter }, [ "," ] ;
parameter        = NAME, ":", type, [ "=", expression ] ;

extern_decl      = "extern", STRING, NL, { extern_member }, "end", NL
                 | "extern", "module", STRING, NL, { module_member }, "end",
                   NL ;
extern_member    = [ DOC, NL ],
                   ( extern_function | resource_decl | callback_decl
                   | c_struct_decl ) ;
extern_function  = [ "compute" ], "def", NAME, "(", [ c_parameters ], ")",
                   "->", ( c_type | TYPE_NAME | "Void" ), [ "=", STRING ], NL ;
c_parameters     = c_parameter, { ",", c_parameter },
                   [ ",", "...", { ",", c_parameter } ], [ "," ] ;
resource_decl    = "resource", TYPE_NAME, ",", "free", ":",
                   ( NAME | TYPE_NAME | "C", ".", "Function" ), NL ;
callback_decl    = "callback", TYPE_NAME, "(", [ c_parameters ], ")",
                   "->", ( c_type | "Void" ), NL ;
c_parameter      = [ "out" ], NAME, ":",
                   ( c_type | "C", ".", ( "Bytes" | "Function" ) | TYPE_NAME ) ;
c_type           = "C", ".", ( "Int32" | "Int64" | "Double" | "Float" | "Bool"
                   | "String" | "Pointer" ) ;
c_struct_decl    = "struct", TYPE_NAME, NL, c_field, { c_field }, "end", NL ;
c_field          = [ DOC, NL ], NAME, ":", ( c_field_type | TYPE_NAME ),
                   [ "=", expression ], NL ;
c_field_type     = "C", ".", ( "Int32" | "Int64" | "Double" | "Float" | "Bool"
                   | "Pointer" ) ;
module_member    = [ DOC, NL ], [ "compute" ], "def", NAME,
                   "(", [ parameters ], ")", "->", type, NL ;

struct_decl      = "struct", TYPE_NAME, [ type_parameters ], NL,
                   { field_decl }, [ "private", NL, { field_decl } ], "end",
                   NL ;
field_decl       = [ DOC, NL ], NAME, ":", type, [ "=", expression ], NL ;

enum_decl        = "enum", TYPE_NAME, [ type_parameters ], NL,
                   variant_decl, { variant_decl }, "end", NL ;
alias_decl       = "type", TYPE_NAME, [ type_parameters ], "=", type, NL ;
type_parameters  = "[", TYPE_NAME, { ",", TYPE_NAME }, "]" ;
variant_decl     = [ DOC, NL ], TYPE_NAME, [ "(", type, { ",", type }, ")" ], NL ;

qualified_type   = TYPE_NAME, [ ".", TYPE_NAME ] ;
type             = qualified_type, [ "[", type, { ",", type }, "]" ] ;
```

A one-line def, `def name(params) -> Type = expression`, is the def with
`expression` as its body, and the form `agentica fmt` writes for such a def when
it fits on its line and holds no comment: it checks and runs the same way,
generics, defaults and a `##` doc included. The expression starts on
the line of `=` (`PARSE-UNEXPECTED-TOKEN` at the end of the line otherwise)
and goes on to other lines only as any expression does: inside parentheses or a
block, or on a next line that starts with `.name`. A `case` or an `if` after `=`
is `PARSE-UNEXPECTED-TOKEN`: they are statements. A `Void` function returns no
value, so `-> Void =` is `PARSE-UNEXPECTED-TOKEN` at the `=`, with a help to
write the def with a body; this includes `main`. The return type is required
(`def f(x: Int) = x` is `PARSE-UNEXPECTED-TOKEN` at the `=`). Like constants,
one-line defs may follow each other with no blank line (below). In an `extern`
block, `= "name"` after the signature is the C name of the function instead
(below), not a value.

A parameter may end with a default value, `NAME: type = expression`. The parser
takes any expression after `=`, so that the checker can say why a default is not
allowed; the rules are in section 6, "Default parameter values". A block
parameter (`do |x|`) takes no default. A field of a struct may end with a
default the same way (`retries: Int = 3`), with the same rules; section 6,
"Structs and lists", says what a constructor does with it.

A struct body may have one `private` line: the word alone on its line, with a
blank line before it unless it is the first line of the body and a blank line
after it unless it is the last. The fields after it are private (section 6,
"Private fields"). A missing blank line is `PARSE-MISSING-BLANK-LINE` and a
second `private` is `PARSE-SECOND-PRIVATE`. `private` is a plain name, so a
field may be called `private` (`private: Int`). A C struct of an extern block
has no `private` line.

An `extern` block declares functions of a native library (section 6d, "Native
code"). The library is a plain string: a name without `/` or an absolute path
(`PARSE-EXTERN-LIBRARY` at the string). Each line is the signature of one C
function: no body, no default (`PARSE-EXTERN-DEFAULT` at the parameter), C types
only (`PARSE-EXTERN-TYPE` at the type), at most 64 parameters
(`PARSE-EXTERN-ARITY` at the 65th) and a `def` name without `?` or `!`, even
with a C name (`PARSE-EXTERN-NAME` at the name). Anything else in the block, a
body or a library given as a heredoc is `PARSE-UNEXPECTED-TOKEN`. A `##` doc
goes on a `def` inside the block. Each function is a `def` for the rest of the
language: it is public or private as the block is (above or after `private`,
section 5b; `export` before a member is `PARSE-UNEXPECTED-TOKEN`, and a block
with both kinds of function is written as two blocks), it takes the place of a
`def` in the declaration order (except in a block that declares a resource,
below), the whole block needs the blank line of a declaration, and the checker
sees each C type as the Agentica type that section 6d gives it. `compute def`
declares a function that runs off the scheduler while the task waits (section
6d). `extern` is contextual: it is a keyword only at the start of a top-level
declaration, and `compute` only before `def` in an extern block. `C.UInt64` and
`C.ULong` are `PARSE-EXTERN-TYPE` (section 6d).

`resource Name, free: c_name` in an extern block declares a resource: a type for
the C pointers that the block's functions return, freed by the C function
`c_name` of the same library (section 6d). `c_name` is any C identifier, also
one that starts with a capital letter (`PQfinish`, `SSL_free`): only the dotted
`C.Function` after the colon is a type, so a bare name is always a C name,
whatever types the program declares. `resource Name, free_ref: c_name` names a
C function that takes a reference to the pointer instead (`void c_name(T **)`,
as `duckdb_close`; `ref` as in Ruby's `Fiddle::Pointer#ref`), checked as a
`free:` name. A resource has one free word: a second one is `PARSE-EXTERN-FREE`
at it, and `free_ref: C.Function` is `PARSE-EXTERN-FUNCTION`. It is a type for
the rest of the language: it is public above `private`, and it takes the place
of a type in the declaration order. So does every `def` of a block that
declares a resource or a struct, public or not: such a block is one
declaration among the types, and its functions do not count as functions for the
order (a block with neither keeps the rule of the `def`). A `def` of the block
may use it in its signature after the line that declares it (`PARSE-EXTERN-TYPE`
before): a parameter takes the resource, and a result of the resource is
`Result[Name]` for the checker. A `def` of the block whose C name is the free
function is `PARSE-EXTERN-FREE` at that name; the check is per block, so another
block of the same library may still declare it. `C.Pointer` is the type of a C
pointer anywhere in a program; `C.Bytes` is a parameter only, a `Bytes` for the
checker. `resource` is a keyword only at the start of a member of an extern
block.

`out NAME: type` in an extern function is an out parameter: C gets a pointer to
a slot and writes the value there (section 6d). The caller does not pass it.
A function with out parameters returns its record, a struct that the parser
declares next to it, named after the function in CamelCase (`sqlite3_open` gives
`Sqlite3Open`): a field `result` with the C result (none for `Void`), then one
field per out parameter, in order, named after it. The record is public with
its function and has no place in the declaration order. An out parameter is
an integer type, `C.Double`, `C.Float`, `C.Bool`, `C.Pointer` or a resource of
the block, whose field is the resource itself, not a `Result`;
anything else is `PARSE-EXTERN-OUT` at the type. An out parameter named
`result` of a function with a C result, an in and an out parameter of one name
(at the later), and a function name with no letter for the record's name, are
`PARSE-EXTERN-OUT` at that name; `out` before a parameter outside an extern
block is `PARSE-EXTERN-OUT` at the word. A type of the record's name elsewhere
in the file, and two out parameters of one name, are `CHECK-REDEFINED-NAME`.
`out` is a keyword only before a parameter name.

The C name of an extern function is its `def` name, or the string after the
result (`-> C.Int32 = "fcntl"`), so one C function can be declared in several
shapes (`PARSE-EXTERN-SYMBOL` at a string that is not a plain name). `...` among
the parameters declares a variadic C function: the parameters after it are its
variadic arguments, each with the C type the call passes. The rules and the
codes of a bad one (`PARSE-EXTERN-VARIADIC*`) are in the
[`Types and resources` page](https://www.agentica-lang.com/agentica/library/io-and-system/native/types/index.md#variadic-functions-and-c-names).

A `C.Function` parameter is the address of a C function, a `C.Pointer` for the
checker. As the first parameter it makes the `def` a call through a function
pointer: the call runs the function at that address with the other parameters,
and the `def` has no C name (`= "..."` is `PARSE-EXTERN-FUNCTION` at the
string). `resource Name, free: C.Function` declares a resource whose values each
have their own free function: a `def` that makes one (its result or an out
parameter) takes the address of that function as its last parameter, a
`C.Function`, after any out parameters. The free rule wins: a sole `C.Function`
parameter of a `def` that returns such a resource is its free function, so `def
thing_new(free: C.Function) -> Thing` calls `thing_new` by name; a call through
a pointer that makes one takes two `C.Function` parameters. The parameter names
are free (`fn` and `free` are a convention). Neither address goes to C. A
`C.Function` anywhere else, a `def` that makes such a resource without that
parameter, and a `def` that makes two are `PARSE-EXTERN-FUNCTION` at the type,
and so is a `free:` type other than `C.Function`. A `C.Function` result is
`PARSE-EXTERN-TYPE`, an out one `PARSE-EXTERN-OUT` and a variadic one
`PARSE-EXTERN-VARIADIC-TYPE`; a variadic part needs a C parameter before the
`...` besides the `C.Function` ones (`PARSE-EXTERN-VARIADIC-FIXED`).

`callback Name(params) -> result` in an extern block declares the type of a C
function pointer that C calls (section 6d). It takes the C types of a `def`
that cross by value: an integer type, `C.Double`, `C.Float`, `C.Bool`,
`C.String` (a parameter only) or `C.Pointer`, and returns one of them but
`C.String`, or `Void`; any other type is `PARSE-EXTERN-TYPE` at the type. It
has no default (`PARSE-EXTERN-DEFAULT`), no out parameter (`PARSE-EXTERN-OUT`
at the parameter), no `...` (`PARSE-EXTERN-VARIADIC`) and at most 64
parameters (`PARSE-EXTERN-ARITY`); a parameter name used twice is
`CHECK-REDEFINED-NAME` at the second. For the rest of the language it is a
resource: a type, with the place of a type in the declaration order (a block
that declares one goes with the types). A `def` of the block
below it takes it as a parameter, also in the variadic part, and so is
`Optional[Name]`, which C gets as NULL for `none`; a callback result, or an
`Optional` of anything else, is `PARSE-EXTERN-TYPE` and an out one
`PARSE-EXTERN-OUT`. `callback` is a
keyword only at the start of a member of an extern block, before a type name.

`struct Name ... end` in an extern block declares a C struct that the block's
functions take and return by value (section 6d). Its fields come in the order of
the C header, each an integer type, `C.Double`, `C.Float`, `C.Bool`,
`C.Pointer` or a struct declared above in the block; any other type, `C.String`,
`C.Bytes`, `C.Function` and a resource included, is `PARSE-EXTERN-TYPE` at the
type (a `char *` field is a `C.Pointer`). A struct with no field is
`PARSE-EXTERN-TYPE` at its name, and one with more than 1024 fields or 16
levels, nested structs counted, `PARSE-EXTERN-ARITY` there. For the rest of the
language it is an ordinary struct whose fields have the Agentica types (`Int`,
`Float`, `Bool`, `C.Pointer`, the nested struct), with field defaults, `.with`.
Like a resource, a `def` of the block may use it after its
declaration (`PARSE-EXTERN-TYPE` before), as a parameter or a result; an out
struct is `PARSE-EXTERN-OUT` and a variadic one `PARSE-EXTERN-VARIADIC-TYPE`.

`extern module "NAME"` declares the functions of a native module, C code
written against the VM's C API (section 6d). `NAME` follows the library rule
above, `[native.NAME]` of a package included. Each member is a `def` or
`compute def` with no body, named as the module's table names it (`?` and `!`
allowed), with Agentica types; the checker says which cross
(`CHECK-NATIVE-TYPE`, section 6d). A member may also be `resource Name`, a
resource of the module's resource table, which frees it. A `callback` or
`struct` line, an out parameter, a `...` and a C name after `=` are
`PARSE-EXTERN-MODULE` at the word, the parameter, the `...` or the `=`, and so
is a comma after a resource's name (the module frees it, so it has no `free:`);
a `C.` type anywhere in a type is `PARSE-EXTERN-TYPE` at it; a default is
`PARSE-EXTERN-DEFAULT` and a 65th parameter `PARSE-EXTERN-ARITY`. For the rest
of the language each function is a `def`, as in an extern block, and each
member, a resource too, takes the place of a `def` in the declaration order.
`module` is a word only between `extern` and the string.

An import is one of two forms. `import Util from "util"` gives the file the
alias `Util`. `import {area, Square as Sq} from "shapes"` brings exported names
into the file, each with an optional new name after `as`, and the list may span
lines, may end with a comma, and may not be empty. `from` and `as` are not
reserved words: the parser reads them by their text at those two places, so a
parameter or a function called `from` or `as` still works, and `{as}` imports a
function called `as`. One line does one thing: `import Util, {area} from "util"`
is `PARSE-UNEXPECTED-TOKEN` at the comma. Writing the path first is
`PARSE-UNEXPECTED-TOKEN` at the string, with the help
`write import Alias from "path"`. What each form means is in section 5b.

A function, struct, enum or type alias declaration needs a
blank line before the next declaration; a line with only a comment counts, but a
doc line does not, because it belongs to the declaration after it: the blank
line goes before the doc block. Otherwise `PARSE-MISSING-BLANK-LINE` is reported
at the next declaration, or at the first line of its doc block. Imports may
follow each other directly, but an import after a declaration also needs the
blank line. A constant follows the imports, and another constant, with no blank
line, also when the next constant has a doc block; the blank line is
still needed between a constant and a `struct`, `enum`, type alias or `def`, and
before an import. In the same way a one-line def may follow a one-line def with
no blank line, also when the next one has a doc block; after a
one-line def the blank line is still needed before any other declaration, and
before a one-line def after any other declaration but an import, a constant or
a def with a body included. Other text after a declaration's `end` is
`PARSE-TOP-LEVEL-STATEMENT`.

Declarations follow a fixed order in every file, the root program, imported
files and embedded `std/` modules alike: the module doc and the imports first,
then the public part (the constants and re-exports, then the `struct`, `enum`,
type alias and `module` block declarations, then the functions), then
`private` and the private part (constants, then types and blocks, then
functions) when the file or module block has one (section 5b). An extern block
that declares a resource or a struct goes with the types, as a whole. `type` is
contextual in an alias declaration and remains an ordinary name elsewhere. The
order is a style rule only: a function may still call a function, use a struct
declared later or read a constant in the same group. The first declaration that
comes after a declaration of a later group is `CHECK-DECL-ORDER`, reported at
the start of that declaration (at `import` when it is one), with help that says
where it goes. The module linker checks it for each file before linking, so a
file with a parse error reports `PARSE-` first and a file that imports another
reports its own order first.

A constant is `NAME = expression` or `NAME: Type = expression` at the top level,
public when it is above `private` (section 5b). `NAME` is a `TYPE_NAME`
token whose text is `UPPER_SNAKE_CASE`: capital letters, digits and `_`,
starting with a capital letter, at least two characters. Any other name (`Limit
= 1`, `X = 1`) is `PARSE-CONSTANT-NAME` at the name, with the closest constant
name as help when there is one. The built-in all-capitals names (`IO`, `JSON`,
`TCP`, `TLS`) are reserved type names and cannot be constants. The type is
optional: `NAME = expression` takes the type of the expression, and `NAME: Type
= expression` checks it against `Type` and gives `[]`, `{}` and `Set.new([])`
the type they need, as for a local. The value is one expression that starts on
the line of the `=`; it may span lines inside brackets or a `do ... end` block.
What the expression may contain and how a constant is read are in section 6.

A doc block (a `DOC` token, section 4) documents what comes on the next line: a
`def`, `struct`, `enum`, type alias or constant declaration, a field inside a `struct`, or a variant inside an `enum`. The first
doc block of a file is the module doc when only blank lines and ordinary `#`
comment lines come before it and a blank line follows it; a `#` comment line
right after it does not count as that blank line. A file has at most one module
doc. Any other doc block is `PARSE-DETACHED-DOC`, reported at its first line: a
block followed by a blank line (other than the module doc), by a `#` comment
line, by an `import`, or by the end of the file, a block inside a function body,
and a block inside `(...)`, `[...]` or `{...}`. Docs are optional and have no
effect when the program runs.

```ruby
## Adds two numbers.
def add(a: Int, b: Int) -> Int = a + b
```

Struct, enum, type alias and function declarations appear only at the top level.
A type alias is transparent (section 6, "Enums and pattern matching"). The
parser accepts type applications such as
`List[Int]`. The checker allows them only for supported builtins, declared
structs and enums that take type parameters, and generic aliases. Structs,
enums, aliases and functions are the declarations that take type parameters. A
struct with type parameters is in section 6, "Generic structs", and a function
in "Generic functions". A call writes no type arguments: `first_or[Int](xs, 0)`
is `PARSE-UNEXPECTED-TOKEN` at the `(`, because `first_or[Int]` reads as an
index. A `def` in an `extern` block takes no type parameters.

A generic alias, `type Matrix[T] = List[List[T]]`, is pure substitution:
`Matrix[Int]` means exactly `List[List[Int]]`. The parameters follow the enum
rules (type names, no repeats, no reserved names:
`CHECK-REDEFINED-NAME`). A use gives exactly one argument per parameter, and
a bare `Matrix` is not a partial application; a wrong count is
`CHECK-UNKNOWN-TYPE` at the use, as for enums, and a non-generic alias takes
none. A parameter may go unused. The arguments are never inferred. An alias
may use other aliases, generic or not (`type Grid = Matrix[Float]`), and a
cycle, also through the arguments, is `CHECK-TYPE-ALIAS-CYCLE`. A parameter
may be a `Map` key or `Set` element in the target; the key rule is judged on
the expanded type at each use (`CHECK-MAP-KEY-TYPE`, at the argument). A bad
key or a `Void` item written in the target itself (`type B[T] = Map[Float, T]`)
is reported at the declaration. The target is read where the alias is declared:
only its own parameters are in scope, so a name in it is never taken for a type
parameter of the use. An enum type parameter that hides a type the alias names
(`struct Item`, `type Items = List[Item]`, `enum E[Item] V(Items) end`) is
`CHECK-UNKNOWN-TYPE` at the use. The argument of an unused parameter is still
checked. A public generic alias is used through an import (`S.Matrix[Int]`,
or `import {Matrix} from "m"`). Like any alias it is neither a constructor nor a
pattern.

## Statements and blocks

```ebnf
block            = { statement } ;
statement        = simple_statement, NL
                 | if_statement
                 | case_statement
                 | while_statement
                 | for_statement ;

simple_statement = binding | compound_binding | return_statement | loop_control | expression
                 | guard ;
binding          = NAME, [ ":", type ], "=", value ;
compound_binding = NAME, ( "+=" | "-=" | "*=" | "/=" | "%=" ), value ;
return_statement = "return", [ value ] ;
value            = expression | case_expression ;
loop_control     = "break" | "next" ;
guard            = ( return_statement | loop_control ), "if", expression ;

if_statement     = "if", expression, NL, block,
                   { "elsif", expression, NL, block },
                   [ "else", NL, block ], "end", NL ;
while_statement  = "while", expression, [ "do" ], NL, block, "end", NL ;
for_statement    = "for", NAME, "in", expression, [ "do" ], NL,
                   block, "end", NL ;
case_statement   = case_expression, NL ;
case_expression  = "case", expression, [ "do" ], NL,
                   match_arm, { match_arm }, "end" ;
match_arm        = pattern, { ",", pattern }, [ "if", expression ], "->",
                   ( NL, block | simple_statement, NL, block ) ;
pattern          = "_" | literal | "-", INTEGER | "-", FLOAT
                 | variant_pattern ;
variant_pattern  = qualified_variant, [ "(", pattern_slots, ")" ]
                 | ( "ok" | "error" | "some" ), "(", pattern_slots, ")"
                 | "none" ;
qualified_variant = TYPE_NAME, ".", TYPE_NAME, [ ".", TYPE_NAME ] ;
pattern_slots    = pattern_slot, { ",", pattern_slot } ;
pattern_slot     = NAME | "_" | literal | "-", INTEGER | "-", FLOAT
                 | variant_pattern ;
```

Assignments, `if`, `while` and `for` are statements, not expressions. A `case`
is a statement too; it gives a value only where the grammar above says `value`
(the right side of an assignment, after `return`) and as the last line of a
block, and is `PARSE-UNEXPECTED-TOKEN` anywhere else (`puts(case ...)`,
`1 + case ...`). `x += e` (also `-=`, `*=`, `/=`, `%=`) means `x = x op e`, with
the same checks as the long form.

`break` leaves the innermost `while` or `for`; `next` skips to its next
iteration. Both are `CHECK-LOOP-CONTROL` outside a loop of the same function or
block: a block cannot break or skip its caller's loop. Inside a block, `return`
leaves the block. There is no `continue`, and no assignment to fields or
indexes.

A guard, `return x if c`, `return if c`, `break if c` or `next if c`, is the
`if c` with that one statement and `end` written out: it checks and runs the
same way. Its `if` is on the line where the statement starts, so a `case` value
or a block that spans lines cannot take one, and nothing follows the condition
(no `elsif`, `else` or second `if`); each is `PARSE-UNEXPECTED-TOKEN`. The
condition reads as an `if` condition: a method call with a block needs no
parentheses, and a function called by its plain name keeps them.
A guard is a simple statement, so it can be the one-line body of a `case` arm
(`1 -> return x if c`) or of a one-line `do` block.
No other statement takes a modifier (`puts(x) if c`, `x = 1 if c`), and there
is no `unless`: both are `PARSE-UNEXPECTED-TOKEN`.

A statement that follows a terminator in the same block is
`CHECK-UNREACHABLE-CODE`, at the first such statement; remove it or move it
before the terminator. The terminators are `return`, `break` and `next`; an `if`
with an `else` whose every branch ends in a terminator; and a `case` whose every
arm does (any mix). The check does not look into loops or calls: `System.exit`,
a `!` function such as `unwrap!`, `while true` without a `break` and `try` are
not terminators. A branch is its own block: `if c` with a `return` and no `else`
is not a terminator, but a statement after that `return` inside the branch is
dead.

## Expressions and precedence

```ebnf
expression       = or_expr, [ ( ".." | "..." ), or_expr ] ;
or_expr          = and_expr, { ( "or" | "||" ), and_expr } ;
and_expr         = equality_expr, { ( "and" | "&&" ), equality_expr } ;
equality_expr    = comparison_expr,
                   [ ( "==" | "!=" ), comparison_expr ] ;
comparison_expr  = pipe_expr,
                   [ ( "<" | "<=" | ">" | ">=" ), pipe_expr ] ;
pipe_expr        = additive_expr, { "|>", pipe_target } ;
pipe_target      = [ "try" ], call_with_parentheses ;
additive_expr    = multiplicative_expr,
                   { ( "+" | "-" ), multiplicative_expr } ;
multiplicative_expr = unary_expr,
                   { ( "*" | "/" | "%" ), unary_expr } ;
unary_expr       = ( "-" | "not" | "!" | "try" ), unary_expr | postfix_expr ;
postfix_expr     = primary, { ".", NAME
                            | ".", "with", "(", named_arguments, ")"
                            | ".", NAME, "(", [ call_arguments ], ")"
                            | "[", expression, "]"
                            | block | brace_block } ;
block            = "do", [ "|", block_param, { ",", block_param }, "|" ],
                   block_body, "end" ;
brace_block      = "{", [ "|", block_param, { ",", block_param }, "|" ],
                   lambda_body, "}" ;
block_param      = NAME, [ ":", type ] ;
block_body       = NL, { statement } | simple_statement ;
lambda           = "->", [ "(", block_param, { ",", block_param }, ")" ],
                   "{", lambda_body, "}" ;
lambda_body      = NL, { statement } | simple_statement ;

primary          = literal
                 | "&", ( NAME | TYPE_NAME, ".", [ TYPE_NAME, "." ], NAME )
                 | NAME, [ "(", [ call_arguments ], ")" ]
                 | TYPE_NAME, ".", TYPE_NAME, ".", TYPE_NAME, [ "(", [ arguments ], ")" ]
                 | TYPE_NAME, ".", TYPE_NAME, "(", [ arguments ], ")"
                 | qualified_type, "(", [ named_arguments ], ")"
                 | qualified_type
                 | list_literal
                 | map_literal
                 | lambda
                 | "(", expression, ")" ;

arguments        = expression, { ",", expression }, [ "," ] ;
call_arguments   = arguments | named_arguments
                 | expression, { ",", expression }, ",", named_arguments ;
named_arguments  = named_argument, { ",", named_argument }, [ "," ] ;
named_argument   = NAME, ":", expression ;
list_literal     = "[", [ arguments ], "]" ;
map_literal      = "{", [ map_entry, { ",", map_entry }, [ "," ] ], "}" ;
map_entry        = expression, ":", expression ;
literal          = INTEGER | FLOAT | STRING | "true" | "false" | "nil" ;
```

Calls are to named functions, or to function values through `.call(...)`; there
are no user methods. A struct field of type `Fn` is called by its name:
`store.put(a, b)` means `store.put.call(a, b)`. `call` is not a reserved word:
it means a function-value call only right after a `.` and before `(`.
Parentheses are required for every call. They may be dropped only for builtin
methods, and for module functions without arguments, builtin or reached through
an import alias: `s.length`, `IO.gets!`, `while !IO.eof? do`, `Util.reset`. So
`f = Util.helper` calls `helper`; write `&Util.helper` for the function value.
`&name` references a declared top-level function without captures, and
`&Time.now_ms` or `&Int.to_s` a builtin (06-semantics.md, "Function values").
A call without arguments drops its `()` before a block: `xs.each do |x| ... end`,
`run do ... end` for a function `run`, and `xs.map { |x| x * 2 }`. A bare name
without a block is never a call. `run() do ... end` still parses, and
`agentica fmt` drops the `()`. A `{ ... }` block follows only a call written
without `(`, and its body is a lambda's: one line or several, up to the `}`;
`xs.map() { ... }` and `xs.map(1) { ... }` are `PARSE-UNEXPECTED-TOKEN`, since
a call with parentheses takes a `do` block. The `()` stays after `|>`
(`PARSE-PIPE-TARGET` without it), for `lambda`, `proc` and `loop`, and for a
function called by its plain name in an `if`, `elsif`, guard or case arm guard
condition: there `ready do` is `PARSE-UNEXPECTED-TOKEN` (the `do` reads as a
mistake for the end of the line), and no call takes a `{ ... }` block. Inside
parentheses, brackets, a map literal or `#{...}`, a condition or a `while`,
`for` or `case` head takes any block: `if (xs.any? { |x| x > 0 })`.
A lambda, `->(x) { x + 1 }`, is a block written as a value; inside a call's
parentheses, in the place of the block, it is that block:
`xs.map(->(x) { x * 2 })`. One without parameters has no parentheses
(`-> { 42 }`), and its body is always in braces.
`->() { ... }`, `->x { ... }`, `->(x) do ... end`, `lambda { ... }`,
`lambda do ... end`, `proc do ... end` and `fn(x: Int) ...` are
`PARSE-UNEXPECTED-TOKEN`, with a help that shows the lambda.
A bare `Enum.Variant` of an enum in the same file is that nullary variant, and
`M.Enum.Variant` through an import alias is one too.

A struct update `value.with(name: expr, ...)` is the one postfix form with named
arguments, and it needs at least one. `with` is not a reserved word: it has this
meaning only after a `.` and before `(`, so `value.with` without parentheses
still reads a field named `with`, and `Alias.with(...)` (an import alias before
the dot) is a call of the module's function `with`. `user.with()` and a
positional value such as `user.with(31)` are `PARSE-UNEXPECTED-TOKEN`, with help
that shows the form: `value.with(age: 31)`. Like a call, the update is a link of
a chain (`a.with(x: 1).with(y: 2)`), and a `do` block cannot follow it.

A method chain may span lines (§4). Nothing chains after the `end` of a
`do ... end` block: a `.name`, `.call(...)`, `.with(...)`, `[index]` or `|>`
right after that `end`, on its line or as a leading `.name` on the next, is
`CHECK-CHAIN-AFTER-END`, from the `end` to the name, index or call that
follows. Parentheses around the call do not change it: `(xs.map do |x| f(x)
end).size` is the same chain, and `agentica fmt` prints it without them. Pass a
lambda and pipe, `xs |> map(->(x) { f(x) }) |> join(", ")`, write a one-line
block in braces, `xs.map { |x| f(x) }.join(", ")`, or bind the result to a
name first. A chain after a block in braces or after a lambda is
fine, and so is a binary operator after `end` (`xs.map do |x| x end + ys`).

`x |> f(a, b)` means `f(x, a, b)`: the left value becomes the first argument of
the call on the right. The right side is a call with parentheses, `name(args)`
or `Alias.name(args)` (a user function, an imported function or a builtin),
optionally preceded by `try`: `x |> try f(a)` is `try f(x, a)`. A trailing block
works: `xs |> each_pair() do |a, b| ... end`. Anything else on the right (a bare
name, a field, an index, a method chain such as `f(1).g`, a literal) is
`PARSE-PIPE-TARGET` at the right side; wrap the expression in parentheses and
use `.` on the result, as in `(x |> f()).unwrap!`. A bare name that is no
function of the file, no function it imports by name and no builtin function
is a method of the left value: `xs |> map(->(x) { x * 2 })` is
`xs.map(->(x) { x * 2 })`, and `xs |> sum()` is `xs.sum`; a name that is no
method of the value either, a struct field (an `Fn` field too) included, is
`CHECK-UNKNOWN-NAME` at the right side. A function of the program with the
same name as a method wins. A builtin written
with its type, `x |> String.strip()`, is `CHECK-PIPE-METHOD` at the right side,
with the method form as help. The styles mix: `s.strip |> try parse() |> try
validate()`. `|>` binds lower than `+` and
`-` and higher than the comparisons, and groups from left to right: `a + 1 |>
f()` is `f(a + 1)`, `x |> f() == y` is `f(x) == y`, and `x |> f() |> g()` is
`g(f(x))`. `try` and unary operators bind tighter: `try x |> f()` is `f(try x)`.
The call keeps its normal order of evaluation (the left value first, then the
other arguments) and its normal diagnostics: the piped argument's span is the
left expression's span. A chain over several lines goes in parentheses, one step
per line.

`a..b` and `a...b` have the lowest precedence and do not chain: `1..2..3` is
`PARSE-UNEXPECTED-TOKEN` at the second operator, and `0...n + 1` is `0...(n +
1)`. A method on a range needs parentheses: `(1..5).to_a`. `1..5` lexes as two
integers. A line that ends in `..` or `...` does not continue on the next line.

`and` and `or` short-circuit. Operators group from left to right, except that
comparisons and equality do not chain: `a < b < c` is invalid. From high to low,
the precedence is: named call, field, index and grouping; unary `-`, `not`, `!`
and `try`; `*`, `/`, `%`; `+`, `-`; `|>`; comparisons; equality; `and`; `or`;
ranges. `not` binds tighter than comparisons, so to negate one, write `not (age
>= 18)`.

Nesting is limited to 1,000 levels (`PARSE-TOO-DEEP`, at the token that passes
the limit). Each statement, expression, prefix operator (`-`, `not`, `!`, `try`)
and type counts one level inside the one around it. So does each operator of a
chain (`a + b + c`, `x |> f() |> g()`) and each `.name`, `[index]` or `do` block
after a primary (`a.b.c`): what follows the k-th operator or suffix of a chain
(its right operand, its arguments, its block) starts k levels deeper than the
chain. Real programs stay far below it; it keeps the parser inside the VM call
limit of 10,000. The checker has its own limit on the depth of the tree: more
than 1,000 levels of expressions and statements, one level for each, is
`CHECK-TOO-DEEP` at the node that passes the limit. It also stops an alias
expansion after 1,000 type references with the same code, so repeated aliases
cannot grow exponentially. A chain of operators is as deep as it is long, and
the parser counts the right operand of the first operator of a chain as one more
level only, so a nested chain passes the parser and stops in the checker.
