Vector Labs

Arra — Surface Syntax

Status

This document is the normative parsing contract for Essential Arra. Semantic rules live in the Essential specification. Syntax for deferred features is intentionally absent.

Normative parsing is deterministic and type-agnostic. Types may improve a diagnostic, but they never change, retry, or backtrack a parse.

1. Notation

Grammar fragments use extended EBNF:

Layout is normalized to explicit scope and separator tokens before syntactic parsing (§4). The grammar therefore describes explicit scopes only.

2. Lexical structure

2.1 Names

LOWER          = [a-z] [a-zA-Z0-9_]*
UPPER          = [A-Z] [a-zA-Z0-9_]*
TRAVERSAL_NAME = "'" LOWER
FIELD_NAME     = "." LOWER
Form Role
lowerName value or type variable
UpperName type, constructor, named pattern, or module
'lowerName traversal name
.lowerName field name

The keywords are:

app as assign assume certify determines distinct effect except exposing export
to fun gen implementation implies import interface iter law model models module
opaque open op pat prim project rec require return theory type with

total is contextual inside law declarations. trait, iso, derived, and metaprogramming forms are not keywords in Essential Arra.

2.2 Literals

INT     = DECIMAL | HEX | BINARY | OCTAL
DECIMAL = DIGIT ("_"? DIGIT)*
HEX     = "0x" HEX_DIGIT ("_"? HEX_DIGIT)*
BINARY  = "0b" BINARY_DIGIT ("_"? BINARY_DIGIT)*
OCTAL   = "0o" OCTAL_DIGIT ("_"? OCTAL_DIGIT)*

FLOAT = DECIMAL "." DIGIT ("_"? DIGIT)* EXPONENT?
EXPONENT = ("e" | "E") ("+" | "-")? DECIMAL

STRING = '"' STRING_CHAR* '"'
       | '"""' RAW_CHAR* '"""'

CHAR   = "'" CHAR_VALUE "'"
CHAR_VALUE = CHAR_SCALAR | CHAR_ESCAPE

SYMBOL = "`" NAME_START NAME_CONTINUATION*
       | "`:" RESOURCE_SYMBOL_CHAR* "`"
RESOURCE_SYMBOL_CHAR = !("`" | NEWLINE | TAB) ANY | "``"

DIGIT             = "0".."9"
HEX_DIGIT         = DIGIT | "a".."f" | "A".."F"
BINARY_DIGIT      = "0" | "1"
OCTAL_DIGIT       = "0".."7"
NAME_START        = "a".."z" | "A".."Z"
NAME_CONTINUATION = NAME_START | DIGIT | "_"
STRING_CHAR       = !('"' | '\\' | NEWLINE) ANY | STRING_ESCAPE
CHAR_SCALAR       = Unicode scalar other than "'" | '\\' | NEWLINE | TAB
CHAR_ESCAPE       = '\\' ('\\' | "'" | "n" | "r" | "t"
                  | "u{" HEX_DIGIT+ "}")
RAW_CHAR          = !('"""') ANY
STRING_ESCAPE     = '\\' ('\\' | '"' | "n" | "r" | "t"
                  | "u{" HEX_DIGIT+ "}")

Numeric underscores may separate digits but may not lead or trail a literal. Negative numbers use the postfix unary operator; the sign is not part of the literal token.

Strings support \\, \", \n, \r, \t, and \u{HEX_DIGIT+} escapes. Triple-quoted strings are raw and may span lines. String is immutable valid UTF-8 text, not a regular character array.

Single quotes delimit exactly one Unicode scalar literal. Character escapes are \\, \', \n, \r, \t, and \u{HEX_DIGIT+}. Empty, multi-scalar, surrogate, out-of-range, multiline, and unterminated character literals reject. A closing quote distinguishes 'm' from the traversal name 'map; the lexer requires no parser context. The literal defaults to Char; a demanded U8 context accepts scalar values through U+00FF and rejects larger values during typing. Character patterns use the same contextual rule.

Identifier symbols begin with an ASCII letter and continue with ASCII letters, digits, or _. Paired resource symbols begin with `: and end at the first unpaired backtick. The leading : belongs to the spelling; doubled interior backticks encode one backtick. Every other character is opaque to ordinary tokenization. Empty payload is valid. Literal newline, tab, or end of file before the closing backtick rejects the token.

Symbols are runtime interned values of type Symbol; backtick quotation has no metaprogramming role.

True, False, and None are nullary constructors, not lexer literals.

2.3 Symbolic operators

An operator is a maximal nonempty run of symbolic code points not reserved as structural punctuation or a comment delimiter. User-defined Unicode operators use the same token class as built-ins.

The following are structural in their grammatical contexts:

←  ⇒  ∧  →  ∀  ∃  ⊥  :  ,  ;  |  ( )  [ ]  { }  ⟪ ⟫  ⟦ ⟧  .

⊥ is reserved for the compiler’s bottom result type. Source effect-operation signatures omit that result, and ordinary source types reject ⊥. ⇒ and ∧ remain operator tokens in expression context. They become UCS structure only when unparenthesized at the top level of a conditional path. | likewise separates constructors, record rows, and effect entries only in those grammatical contexts.

All binary operators have one precedence and associate left. Application phrases bind more tightly than that operator precedence. Field projection, field update, and literal removal bind to their immediately preceding atom. Unary operators are postfix. There are no precedence or associativity declarations.

2.4 Comments

line-comment  = "//" (!NEWLINE ANY)*
block-comment = "/'" (block-comment | !("'/") ANY)* "'/"

Block comments nest. The removed /'-Opaque-'/ spelling is a lexical error; opaque nominal records use the opaque type declaration in §12.2. General attributes are deferred.

3. ASCII authoring forms and watcher

ASCII aliases are classified by syntactic role rather than replaced as raw substrings. The parser accepts these structural spellings:

ASCII Unicode Structural role
<- ← definition or unconditional binding
=> ⇒ conditional evidence
&& ∧ conditional path sequencing
-> → production, function type, or clause result
<< >> ⟪ ⟫ effect row in a type position

[[ and ]] are not call-vector aliases; they begin and end nested arrays. Every symbolic source token is first lexed as one maximal run. An ASCII structural alias is recognized only when that complete token is exactly the alias. For example, +=> is one value operator, not + followed by structural =>.

The aliases that can also name value operators are contextual:

Thus a -><<e>> b is a function type, while a -> <<e>> b is rejected; x << n and x >> n are value-level hook sites. ⟪ and ⟫ remain the dedicated canonical effect delimiters.

The watcher and compiler share this role classification. The compiler accepts an ASCII structural spelling even before the file is saved. On save, the watcher rewrites only tokens confidently classified as structural; it never rewrites string, symbol, comment, or ambiguous malformed contents.

Structural aliases are fixed by the language. Value-operator rewrite rules are open to project or user configuration and obey these constraints:

  1. A rule maps one exact value-level operator token to one canonical operator token.
  2. The replacement must itself lex as exactly one OPERATOR.
  3. Rules apply equally to hook declarations and use sites.
  4. A source token is rewritten at most once; replacements never cascade.
  5. Conflicting mappings for the same source token are configuration errors.
  6. Structural tokens and structural aliases cannot be overridden.

Canonical stored source uses Unicode structural punctuation and the configured canonical spelling for value operators.

4. Layout

A newline separates declarations. Indentation may replace an explicit parenthesized block after a definition ←, conditional clause →, nested subject ⇒, module, interface, implementation, effect, theory, model, law, rec, dependency-selector, or 'handle opener. The first token after an opener fixes the block’s reference column. At each subsequent nonblank line:

  1. the same column inserts ;;
  2. a greater column continues the current item;
  3. a lesser column closes blocks until the enclosing column is reached.

Tabs are invalid as source whitespace, including between tokens and in indentation. Only ASCII spaces may indent. Literal contents and comments follow their own lexical grammars: ordinary and raw strings and line or block comments may contain tabs, while resource symbols and unescaped character literals reject them. EOF closes every open layout block.

An explicit ( immediately following an opener suppresses layout for that block. Inside explicit delimiters, newlines are whitespace and required separators remain explicit.

These are equivalent:

unwrap ←
  x Some → x
  None   → default
unwrap ← (x Some → x; None → default)

A same-line ∧, or an indented line beginning with ∧, continues the current conditional path rather than beginning another clause.

→ and ⇒ open layout only in conditional-function grammar. Their occurrences inside types and quantified signatures do not.

5. Programs and modules

Every source file contains one dotted module:

file = module-declaration EOF

module-declaration = "module" module-path module-body
module-body        = "(" interface-block implementation-block? ")"
                   | "(" implementation-block ")"
interface-block    = "interface" declaration-block
implementation-block = "implementation" declaration-block

declaration-block    = "(" (declaration ";")* declaration? ")"
module-path          = UPPER ("." UPPER)*
qualified-lower-name = module-path "." LOWER
qualified-upper-name = module-path "." UPPER
qualified-name       = qualified-lower-name | qualified-upper-name
primitive-name       = "prim" "." LOWER ("." LOWER)*

Layout normally supplies parentheses and semicolons:

module Geometry
  interface
    type Point
    magnitude : Point → F64

  implementation
    type Point ← {x: F64, y: F64}
    magnitude ← p → (p.x * p.x + p.y * p.y) sqrt

An interface contains public declarations and authoritative signatures. Implementation-only declarations are private to the module. An implementation binding may omit its interface signature or repeat it as a fused checked definition. Every owned interface declaration requires a matching implementation declaration.

A module containing an interface may omit implementation when it owns no implementation declarations, as in a forwarding facade:

module Collections
  interface
    export Prelude.Array
    export Prelude.Map

A module without an interface requires an implementation block. An omitted interface exports nothing.

Dependencies use three distinct modes:

import-declaration = "import" module-path ("as" UPPER)?
open-declaration   = "open" module-path ("as" UPPER)? selection?
export-declaration = "export" module-path ("as" UPPER)? selection?

selection      = ("exposing" | "except") selector-block
selector-block = "(" (selector ";")* selector? ")"

selector = LOWER ("as" LOWER)?
         | UPPER ("as" UPPER)?
         | "type" UPPER ("as" UPPER)?
         | "effect" (UPPER | qualified-upper-name) ("as" UPPER)?
         | "effect" qualified-lower-name ("as" LOWER)?
         | "theory" UPPER ("as" UPPER)?
         | "models" UPPER
         | "model" model-head
         | hook-family-selector hook-family-alias?
         | exact-hook-signature hook-family-alias?

hook-family-selector = "fun" LOWER
                     | "op" OPERATOR
                     | "pat" UPPER
                     | "iter" TRAVERSAL_NAME
                     | "gen" TRAVERSAL_NAME
hook-family-alias = "as" (LOWER | UPPER | OPERATOR | TRAVERSAL_NAME)
model-head        = quantifiers? theory-application
exact-hook-signature = hook-signature

import creates qualified access only. open is permitted only in an implementation and contributes an unqualified selected view. export is permitted only in an interface and forwards a selected view. Module aliases use uppercase names:

import Geometry as G
open Geometry exposing (point as origin; fun twice as double; op +;)

G.point
origin double

Hook-family aliases must use the selector’s lexical class: lower case for fun, an operator for op, upper case for pat, and a traversal name for iter or gen. app, project, assign, and to have no family selector and are selected by exact signature. Any hook family may also be selected by an exact bodyless hook signature. model selects one exact ground model or model constructor head; models Theory selects the complete model group for that theory. except uses the same selector grammar and requires exact presence for exact hook and model selectors.

Imports may use a module alias but do not accept exposing or except. Dependency aliases rekey declarations in the receiving view. Qualified hook requests use the closed exported view of the named module. Dotted module declarations map to matching source paths, and the complete dependency graph must be acyclic. Nested and parameterized modules remain absent.

6. Delimiters

Form Meaning
(e) grouping
(e : T) expression ascription
(a, b) tuple
(a; b) sequential scope
(p → e; q → f) conditional function
⟦p; q⟧ → e multivalent function
[a; b] array literal
{x: a, y: b} record value or type, by context
⟦a; b⟧ mapping invocation vector
⟪e⟫ effect row

Parentheses are classified by unparenthesized top-level tokens:

  1. → identifies a conditional function;
  2. otherwise : identifies an expression ascription;
  3. otherwise , identifies a tuple;
  4. otherwise ; identifies a sequential scope;
  5. otherwise the parentheses group one expression.

No classification uses types or backtracking.

7. Expressions

7.1 LTR projection chains

expression = head projection*

head = atom
     | invocation

projection = adjacency
           | postfix-operation
           | binary-operation
           | traversal-projection
           | field-projection
           | field-update
           | field-removal
           | family-projection
           | handler-projection

adjacency            = operand
postfix-operation    = OPERATOR
binary-operation     = OPERATOR operand
traversal-projection = TRAVERSAL_NAME operand
field-projection     = field-selector
field-update         = ".(" (LOWER | INT) "←" expression ")"
field-removal        = "-" field-selector
family-projection    = "pat" constructor-name
                     | "to" type
handler-projection   = "'handle" effect-label handler-block

field-selector = "." (LOWER | INT)
operand        = atom | conditional-function

The parser retains each maximal adjacency spine. Field operations bind to atoms, application phrases bind more tightly than operators, and type checking consumes each application spine left-to-right according to mapping valence:

x f             // unary f; equivalent to ⟦x⟧ f
x f y           // binary f; equivalent to ⟦x; y⟧ f
x f y g z       // (x f y) g z
a + b f c * d   // (a + (b f c)) * d

In x f y, x is the primary argument, f is the mapping expression, and y is the secondary argument. The mapping expression must be pure. Insufficient adjacent arguments are an error, not implicit partial application. If a call returns a function, later expressions are not silently absorbed as arguments to that returned function.

Tuple-unary and multivalent domains are distinct:

pairwise : (A, B) → C
dyadic   : ⟦A; B⟧ → C

(a, b) pairwise
a dyadic b

A traversal projection consumes one modifier operand. Any following primary or secondary arguments belong to the derived mapping rather than to that modifier:

xs 'map mapper
xs 'fold reducer initial

Here reducer is the 'fold operand; xs and initial are the derived mapping’s primary and secondary arguments. Parsing does not reorder this source spine or treat initial as the primary argument.

7.2 Atoms

atom = INT | FLOAT | CHAR | STRING | SYMBOL
     | LOWER | UPPER | qualified-name | primitive-name
     | "(" ")"
     | "(" expression ")"
     | "(" expression ":" type ")"
     | tuple
     | sequential-scope
     | array-literal
     | record-literal
     | parameter-vector "→" expression

parameter-vector = "⟦" (pattern (";" pattern)*)? "⟧"
tuple            = "(" expression "," expression ("," expression)* ")"
sequential-scope = "(" expression ";" expression (";" expression)* ")"
array-literal     = "[" (expression (";" expression)*)? "]"
record-literal    = "{" (record-field ("," record-field)*)? "}"
record-field      = LOWER (":" expression)?
                  | "⟦" name-term "⟧" ":" expression
name-term         = field-selector | LOWER

Array literals reject a trailing ;.

7.3 Operators and grouping

Operators and traversal phrases are mappings only in projection position or after an invocation vector. They are not standalone atoms. Parentheses preserve the expression already inside them:

1-       // postfix negation
(1-)     // the same expression, grouped

Full, left, right, and traversal sections do not exist. Invocation vectors express residual mappings explicitly:

⟦_; _⟧ +
⟦_; 1⟧ +
⟦1; _⟧ +
⟦_⟧ 'map parse

Parentheses force ⇒ and ∧ into expression grammar when they occur in a conditional path:

(a ∧ b) ⇒ True → result
(a ⇒ b) ⇒ True → result

7.4 Traversal names

' is the traversal sigil. It puts the following lower-case name in the open traversal namespace. A traversal name consumes exactly one modifier operand. The reserved 'handle spelling reuses the sigil but is not an iter or gen traversal name.

7.5 Fields, updates, and removal

record.field
record.(field ← value)
record - .field
record - name
tuple.1
value.(0 ← replacement)

Literal field selectors are a dot followed by a lower-case name or nonnegative integer. Projection, update, removal, and literal project/assign heads share this identity. Ordinal spellings normalize by numeric value, so .1, .01, and .0x1 denote the same name.

An invocation vector exposes an abstract static Name through qualified project or assign:

getName ← ⟦_⟧ .user.name
getField ← ⟦_⟧ project name
replaceField ← ⟦_; replacement⟧ assign name

Consecutive literal selectors form one read-only unary path. Dyadic selector paths are rejected; nested updates remain explicit. left + right performs disjoint record concatenation when no direct op + hook matches. Removal accepts a literal selector or a quantified static Name; the latter initially uses the general binary-expression grammar but is not a runtime op - request. Static names do not become runtime values.

8. Invocation vectors, valence, and projection

An invocation vector supplies the complete invocation domain of a mapping. The syntax fixes the hook family and separates invocation slots from dynamic formation operands and static selectors.

invocation = invocation-vector mapping

invocation-vector = "⟦" "⟧"
                  | "⟦" slot (";" slot)* "⟧"

slot = expression | "_"

mapping = operand
        | OPERATOR
        | field-selector+
        | "project" name-term
        | "assign" name-term
        | TRAVERSAL_NAME operand
        | "pat" constructor-name
        | "to" type

Function valence is part of the type. Nullary, unary, tuple-unary, multivalent, and curried functions are distinct:

nullary : ⟦⟧ → R
unary   : A → R
tupled  : (A, B) → R
dyadic  : ⟦A; B⟧ → R
curried : A → (B → R)

⟦⟧ nullary is a nullary invocation. _ is the sole invocation-hole spelling:

f : ⟦A; B; C⟧ → D

⟦a; b; c⟧ f            // : D
⟦a; _; c⟧ f            // : B → D
⟦_; b; _⟧ f            // : ⟦A; C⟧ → D

Leading, consecutive, and trailing separators are errors; an empty slot is not an alias for _. ⟦_⟧ is a unary all-hole projection, distinct from ⟦⟧.

The same vectors expose every hook family:

⟦x⟧ f
⟦x⟧ -
⟦x; y⟧ +
⟦record⟧ .field
⟦record; replacement⟧ .field
⟦xs⟧ 'map mapper
⟦xs; initial⟧ 'fold reducer
⟦seed⟧ 'generate step
⟦value⟧ pat Positive
⟦value⟧ to F64

For app, the target following the vector is a dynamic formation operand. For iter and gen, the traversal operand is a dynamic formation operand. Operators, fields, static project/assign names, traversal names, pattern names, and to target types are explicit static selectors, never runtime slots. A lower-case use selects a static fun family only when no ordinary local, constrained, module, or effect-operation value of that name shadows it; the selected family name is likewise not a runtime slot. _ abstracts only invocation positions.

Supplied slots evaluate once from left to right, followed by dynamic formation operands. With no holes, application happens immediately. With holes, the selected mapping and supplied values are captured and the result is an ordinary closure whose domain contains the missing positions in original order. Hook effects remain latent until every hole is supplied.

source to Target and value pat Selector are concise unary forms. to Target and pat Selector are not standalone mappings; an invocation vector is required to reify them. to consumes a maximal ordinary target type, so a following postfix expression may require grouping.

9. Conditional functions

conditional-function = clause-block
clause-block          = "(" clause (";" clause)* ")"

clause = path "→" expression
       | path-prefix? path-expression "⇒" clause-block

path             = clause-head ("∧" continuation-part)*
path-prefix      = clause-head "∧" (continuation-part "∧")*
clause-head      = parameter-vector | initial-path-part
initial-path-part = pattern | continuation-part

continuation-part = path-expression
                  | path-expression "⇒" pattern
                  | pattern "←" expression

path-expression       = expression | subjectless-projection
subjectless-projection = projection+

path-expression is scanned only as far as the next unparenthesized top-level ←, ⇒, ∧, or →. A syntactically valid pattern wins over an otherwise identical bare expression in path position; consequently valid → body is a binder, while x valid → body is an expression condition. An expression path without an explicit ⇒ pattern succeeds exactly when its result is True. subjectless-projection is permitted in any path part and receives the fixed subject of the enclosing clause list as its missing left operand.

Layout may omit the clause-block parentheses. The single irrefutable clause is an ordinary lambda:

square ← x → x * x

Clauses are tried in source order. Path failure resumes at the next clause in the nearest enclosing clause list:

unwrap ←
  x Some → x
  None   → default

The structural forms are:

Form Meaning
p ← e evaluate e and bind p unconditionally
e ⇒ p evaluate e, match p, and retain successful bindings
a ∧ b continue the successful path with prior bindings in scope
path → result produce the clause result

The first path part matches the clause-list subject. It may instead begin with a projection suffix whose missing left operand is that subject.

A parameter-vector clause head matches structural domain positions directly:

compare ←
  ⟦left; right⟧ ∧ left < right → Less
  ⟦left; right⟧ ∧ left > right → Greater
  _ → Equal

All vector-headed clauses in one list have equal valence. When that valence or a demanded function domain is already known, bare _ → body discards the complete domain. With no demand and no vector-headed sibling, it remains unary. No other bare pattern may stand in for a multivalent domain. Domain elision does not provide valence while choosing among otherwise ambiguous hooks.

classify ←
  < 0 → Negative
  = 0 → Zero
  _   → Positive

consume ←
  safeHead ⇒ x Some ∧ x valid → x process
  _ → fallback

The implicit subject is fixed for one clause-list level. Successful bindings do not replace it. A nested clause block following ⇒ establishes the computed result as a new subject:

handleRequest ←
  decode ⇒
    message Ok → message process
    error Err  → error BadRequest

A lone lower-case name before → is always an irrefutable binder:

valid → body

Applying an implicit predicate requires evidence syntax:

valid ⇒ True → body

At top level on the left of a clause’s →, unparenthesized ⇒ and ∧ are UCS structure. Parentheses select their hookable expression meaning. If inferred types suggest missing parentheses or ⇒ True, the diagnostic reports the likely rewrite without changing the parse.

Every conditional function must be proved exhaustive. A structural pattern matrix proves complete finite algebraic-constructor and Boolean cases, recursively through tuples, records, and exact static-length arrays. Irrefutable matching and binding suffixes preserve the leading subject pattern’s coverage. Totality is propagated recursively through nested clause lists, and clauses after a covering prefix do not contribute effects. Dynamic arrays, infinite scalar domains, pat extractors, computed evidence, and guards remain conservative and therefore require an explicit residual clause such as _ → fallback. The compiler never inserts an implicit Fail.

10. Patterns

pattern = pattern-atom constructor-name*

pattern-atom = "_"
             | LOWER
             | INT | FLOAT | CHAR | STRING | SYMBOL
             | constructor-name
             | "(" ")"
             | "(" pattern ")"
             | "(" pattern "," pattern ("," pattern)* ")"
             | "{" field-pattern ("," field-pattern)* "}"
             | "[" (pattern (";" pattern)*)? "]"
             | "(" pattern ":" type ")"

constructor-name = UPPER | module-path "." UPPER
field-pattern    = LOWER (":" pattern)?

Array patterns reject a trailing ;. Qualified constructor and pat names use the same module-path grammar as qualified construction. A lower name without : is a field pun. {x, y: pattern} means {x: x, y: pattern}. Record literals use the parallel expression shorthand: {x, y: expression} means {x: x, y: expression}.

Postfix constructors and pat hooks share pattern syntax:

x Some
x Ok Some
None

Construction uses the same order in expression context:

x Some                    // construct
x Some → x use            // deconstruct

Computed deconstruction uses ⇒; there is no anonymous view-pattern form:

value (
  validate ⇒ x Ok → x use;
  _ → fallback
)

11. Types and static kinds

type = quantified-type | function-type

quantified-type = quantifiers type
quantifiers     = "∀" quantifier-binder+
                  ("|" constraint (";" constraint)*)? "⇒"
function-type   = function-domain production-arrow type
                | postfix-type
function-domain = postfix-type
                | "⟦" (type (";" type)*)? "⟧"
production-arrow = "→" effect-row?
postfix-type     = atomic-type type-suffix*

type-suffix = LOWER
            | UPPER
            | qualified-upper-name
            | "[" shape "]"

atomic-type = LOWER | UPPER | qualified-upper-name
            | "(" ")"
            | "(" type ")"
            | "(" type "," type ("," type)* ")"
            | record-type
            | existential-type

record-type = "{" "}"
            | "{" field-type ("," field-type)* ("|" row-expression)? "}"
            | "{" "|" row-expression "}"
field-type  = LOWER ":" type
            | "⟦" name-term "⟧" ":" type

row-expression = LOWER
               | row-expression "+" row-expression
               | "(" row-expression ")"

existential-type  = "∃" "(" LOWER ":" "Nat" ")" type
type-binder       = LOWER (":" kind)?
quantifier-binder = type-binder | "(" type-binder ")"

kind = "Type" | "Type" "→" "Type"
     | "Nat" | "Shape" | "Effects" | "Name" | "Fields"

constraint         = theory-application
                   | static-support "⟂" static-support
theory-application = postfix-type
static-support     = name-term | row-expression

shape      = shape-term (";" shape-term)*
shape-term = LOWER | INT | "_"

effect-row   = "⟪" (effect-label ("|" effect-label)* ("|" effect-tail)?
                   | effect-tail)? "⟫"
effect-label = postfix-type
effect-tail  = LOWER

An effect row is lexically attached to its production arrow:

Form Meaning
→ pure production
→⟪e⟫ effectful production

Whitespace may follow the complete arrow form but cannot separate →/-> from ⟪/<<. Canonical forms are a →⟪e⟫ b and a -><<e>> b; a → ⟪e⟫ b and a -> <<e>> b are rejected.

Type application and array shape application are postfix:

a Option
(e, a) Result
(k, v) Map
a[n]
a[n; m]
a[_]
a Option[n]
a[n] Option

A tuple supplies several parameters to a multi-parameter type constructor. Semicolons concatenate dimensions in one array suffix. _ denotes one anonymous runtime dimension. Empty and consecutive suffixes such as a[] and a[n][m] reject. Unit, (), and {} denote the same empty structural record type. A lower-case type suffix denotes a quantified constructor variable. Frame is the built-in constructor from one static Shape to Type → Type; arbitrary constructor variables use the sole supported higher kind Type → Type.

Function domains encode valence:

() → R              // unary empty product
⟦⟧ → R              // nullary
(A, B) → R          // tuple-unary
⟦A; B⟧ → R          // dyadic
A → (B → R)         // curried

Tuple and unit syntax elaborate to structural records with ordinal and empty field maps. Name classifies literal or quantified static field identities. Fields classifies finite field maps. Open records retain row expressions rather than a Boolean openness marker:

{x: I64 | rest}
{| left + right}
{⟦name⟧: value | rest}

+ inside a row expression is disjoint union. ⟂ is the static disjointness constraint over Name and Fields supports. Neither form invokes a value operator.

A quantified header contains one flat constraint list:

∀ (name : Name) a (rest : Fields)
| name ⟂ rest
⇒ {⟦name⟧: a | rest} → a

∀ a | a Equality ⇒ a → Bool

Theory applications must end in a named theory; their preceding postfix type arguments supply its parameters. Theory applications and disjointness propositions are compile-time constraints. Effects introduces an effect-row tail. Unresolved static binders, including Nat, Shape, Name, and Fields, must specialize before executable Core; an existential Nat may instead survive as explicit runtime dimension evidence.

12. Declarations

declaration = value-signature
            | value-binding
            | recursive-binding
            | type-declaration
            | distinct-declaration
            | effect-declaration
            | theory-declaration
            | model-declaration
            | hook-declaration
            | import-declaration
            | open-declaration
            | export-declaration

12.1 Values and recursion

value-signature   = LOWER ":" type
value-binding     = binding-pattern "←" expression
binding-pattern   = LOWER
                  | "_"
                  | "(" binding-pattern ("," binding-pattern)+ ")"
                  | "{" binding-field ("," binding-field)* "}"
                  | "(" binding-pattern ":" type ")"
binding-field     = LOWER | LOWER ":" binding-pattern
recursive-binding = "rec" (recursive-name-binding | declaration-block)
recursive-name-binding = LOWER (":" type)? "←" expression

A checked definition may fuse its type and body:

answer : I64 ← 42

rec factorial : Nat → Nat ←
  0 → 1
  n → n * ((n - 1) factorial)

Nonrecursive bindings admit nested tuple and record patterns, record puns, _, and pattern annotations. Refutable patterns are rejected. Destructuring is forbidden in a recursive group.

One implementation cannot give the same name both a separate local signature and a fused annotation. An unannotated implementation binding may be checked against its interface signature.

The block form introduces mutual recursion. Every value name bound in the block is in scope throughout every right-hand side. Other declarations retain their ordinary role, and the block must contain at least one value binding.

12.2 Algebraic, record, and distinct types

type-declaration = "type" type-head
                 | "type" type-head "←" constructor ("|" constructor)*
                 | "type" type-head "←" closed-record-type
                 | "opaque" "type" type-head "←" closed-record-type

type-head        = UPPER
                 | type-parameter UPPER
                 | "(" type-parameter "," type-parameter
                       ("," type-parameter)* ")" UPPER
type-parameter   = LOWER (":" "Type")?
constructor      = type? UPPER
closed-record-type = "{" (literal-field-type
                            ("," literal-field-type)*)? "}"
literal-field-type = LOWER ":" type
                   | "⟦" field-selector "⟧" ":" type

distinct-declaration = "distinct" UPPER "←" type

Constructor payloads precede their postfix constructors:

type a Option ← None | a Some
type (e, a) Result ← e Err | a Ok
type a Box ← {value: a}
opaque type a Secret ← {value: a}
distinct UserId ← I64

A bodyless interface type is abstract. A transparent nominal record publishes its complete field schema and generated nominal field operations; opaque hides that representation from clients. Nominal record declarations may be parameterized but require a closed literal field schema.

12.3 Effects and handlers

effect-declaration = "effect" type-head effect-body
effect-body        = "(" (operation-signature ";")* operation-signature? ")"
operation-signature = LOWER ":" postfix-type

handler-block  = "(" handler-clause (";" handler-clause)* ")"
handler-clause = LOWER pattern "→" expression
               | "return" pattern "→" expression
effect e Fail
  raise : e

effect IO ()

computation 'handle E Fail
  raise error → error Err
  return value → value Ok

Effect operations and handler clauses use bare lower-case names. An empty effect body declares an operation-free marker effect. A handler names one exact instantiated effect, contains at least one control clause, covers every declared operation exactly once, and contains one return clause. Operation-free effects therefore cannot be handled in source. Operations are non-resumable; no continuation binder exists.

12.4 Hook declarations

hook-declaration = hook-signature ("←" expression)?

hook-signature = "app"     quantifiers? formation ":" function-type
               | "fun"     quantifiers? LOWER ":" function-type
               | "op"      quantifiers? OPERATOR ":" function-type
               | "pat"     quantifiers? UPPER ":" function-type
               | "project" quantifiers? name-term ":" function-type
               | "assign"  quantifiers? name-term ":" function-type
               | "iter"    quantifiers? TRAVERSAL_NAME formation
                   ":" function-type
               | "gen"     quantifiers? TRAVERSAL_NAME formation
                   ":" function-type
               | "to"      quantifiers? ":" function-type

formation = postfix-type | "(" LOWER ":" type ")"

The type after : declares the complete formed mapping. Unary and binary op hooks share one family and are distinguished by their one- or two-position domain. fun introduces a static lower-name family. pat, project, and to require unary mappings; assign requires a dyadic mapping. app, iter, gen, and fun retain the valence written in their type.

app ∀ (e : Effects) a b ⇒
  (a →⟪e⟫ b) : a →⟪e⟫ b
fun ∀ (n : Nat) ⇒ sum : I64[n] → I64
op + : ⟦I64; I64⟧ → I64
op - : I64 → I64
pat Positive : I64 → I64 Option
project .field : Record → Value
assign .field : ⟦Record; Value⟧ → Record
iter ∀ (n : Nat) a b ⇒ 'map (a → b) : a[n] → b[n]
gen ∀ a state ⇒ 'generate (state → (a, state) Option) : state → a[_]
to : I64 → F64

An implementation must name dynamic formation operands:

iter ∀ (n : Nat) a b ⇒ 'map (mapper : a → b) : a[n] → b[n] ←
  values → ...

A bodyless hook signature is valid in interfaces, theory requirements, and dependency selectors. Ordinary implementation hooks require a body.

12.5 Theories, laws, and models

theory-declaration = "theory" theory-head theory-body
theory-head        = theory-parameters? UPPER
theory-parameters  = theory-parameter
                   | "(" theory-parameter
                         ("," theory-parameter)* ")"
theory-parameter   = LOWER (":" ("Type" | "Type" "→" "Type"))?
theory-body        = "(" theory-member (";" theory-member)* ")"
parameter-set      = LOWER | "(" LOWER ("," LOWER)* ")"

theory-member = "require" theory-application ("as" UPPER)?
              | "require" LOWER "(" hook-signature ")"
              | parameter-set "determines" parameter-set
              | law-declaration

law-declaration = "law" LOWER law-body
law-body        = proposition
                | law-binders "⇒" proposition
law-binders     = static-law-binders
                | completed-value-binders
                | static-law-binders completed-value-binders
static-law-binders = "∀" law-binder+
law-binder      = LOWER
                | "(" LOWER (":" law-kind)? ")"
law-kind        = "Type" | "Type" "→" "Type"
                | "Nat" | "Shape" | "Effects"
completed-value-binders = "⟦" completed-value-binder
                          (";" completed-value-binder)* "⟧"
completed-value-binder  = LOWER ":" type

proposition             = implication-proposition
implication-proposition = conjunction-proposition
                          ("implies" implication-proposition)?
conjunction-proposition = atomic-proposition
                          ("∧" atomic-proposition)*
atomic-proposition      = expression "≡" expression
                        | requirement-reference "total"
                        | "(" proposition ")"
requirement-reference   = LOWER | UPPER "." LOWER

model-declaration = "model" model-head model-body?
model-body        = "(" model-member (";" model-member)* ")"
model-member      = "require" theory-application
                  | "certify" qualified-lower-name
                    "with" value-reference
                  | "assume" LOWER
value-reference   = LOWER | qualified-lower-name | primitive-name

Theory parameters have kind Type or Type → Type. A theory may contain prerequisite theory applications, directional determinations, labelled exact hook requirements, and laws:

theory a Equality
  require equal
    op = : ⟦a; a⟧ → Bool
  law reflexive
    ⟦x : a⟧ ⇒ x equal x ≡ True

A model interface declaration contains only its head. An implementation model body explicitly repeats prerequisite evidence, certifies each required hook with an ordinary value or primitive identity, and supplies law evidence:

model I64 Equality
  certify Equality.equal with equalI64
  assume reflexive

Quantified model constructors and constrained value or hook signatures use the same flat header:

model ∀ a | a Equality ⇒ (a Option) Equality

models Theory is a dependency selector, not a declaration.

13. Deferred syntax

The current grammar intentionally contains no separate forms for:

These are rejected syntax, not inert AST nodes.