Source grammar#
This page is the exact syntax reference. New to the language? Start with source files . Parsing checks shape only; expression rules and type rules decide legality.
Source characters and tokens#
- Source is UTF-8 without a byte-order mark. CRLF is normalized to LF; a lone CR is rejected everywhere, comments included.
- Bidirectional text controls (U+202A to U+202E and U+2066 to U+2069) are rejected in comments and text, since they can make source display differently from how it is read; write
\u{202E}in text when the character is needed. - Identifiers are
[A-Za-z_][A-Za-z0-9_]*and case-sensitive. A lone_is a pattern placeholder. Unicode is allowed in text and comments only.
The language uses these keywords:
and break continue else enum export extern false fixture fn for if
import in interface match not or return self test true type
void var while- Most keywords are reserved only where they mean something. After
., and as aname:label that starts a line or follows(or,(a record or enum field, a parameter, an argument label), these are ordinary names:break continue enum export extern fixture for if import in interface match return test type while. - So
type Options { ... }can declarecontinue Boolandif Int,Options(continue: true)sets it, andopts.continuereads it. A binding or function still cannot use these words.and,or,not,else,fn,var,self,void,trueandfalsestay reserved everywhere. tryandimplare not keywords. Writing the oldtry f(x)or animplblock reports the replacement: a postfix?(f(x)?) propagates a Result error, andfn Type.name(...)declares a method.opaqueis contextual: it modifies atypedeclaration only directly beforetype(export opaque type Name { ... }), soopaque := 1is valid.asrenames an import name only after an imported name; elsewhere it is an ordinary name.fromends an import’s names andbenchstarts a benchmark only before a string literal at a module item; both are contextual, sofrom := 2andbench := 3are valid.- Words from other languages (
def,lambda,elif,True,False,None,class,except,raise,finally,async,await,yield,global,nonlocal,del,is,pass,throw,catch,null,undefined,new,this,function) and Python spellings (f"...",from "p" import x,Callable[[Int], Int],a if c else b,casearms,()for Void) are not syntax and get a targeted diagnostic naming the Manuscript form (fn,else if,true,null,void,expr?, and so on). fixturenames the file fixture inside test blocks when a localmake_fixturefactory returns a concreteTestHooksimplementer.fixtureandself(the implementation receiver) cannot be declared as parameters or bindings.- Built-in type names and alternative constructors are not keywords.
//starts a comment through the end of the line.#is not syntax./* ... */is a block comment. It starts its own line (after indentation), ends at the first*/, and only blanks or a//comment may follow the*/. Block comments do not nest (a/*inside one is an error), and an unterminated block is an error at its opening/*. The block counts as comment-only lines for layout, so its contents are free-form.- A tab is allowed only in a line’s leading whitespace (four columns), never between tokens. Tabs are allowed in text and comments. Control characters in text are rejected; use text escapes . Semicolons and backslash continuation are rejected.
Numeric tokens:
Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
NonzeroDigit = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
Digits = Digit, { [ "_" ], Digit } ;
Whole = "0" | NonzeroDigit, { [ "_" ], Digit } ;
Fraction = ".", Digits ;
Exponent = ("e" | "E"), [ "+" | "-" ], Digit, { Digit } ;
HexLiteral = "0x", HexDigit, { [ "_" ], HexDigit } ;
BinLiteral = "0b", ( "0" | "1" ), { [ "_" ], ( "0" | "1" ) } ;
IntLiteral = Whole | HexLiteral | BinLiteral ;
FloatLiteral = Whole, (Fraction, [ Exponent ] | Exponent) ;
DecimalLiteral = Whole, [ Fraction ], [ Exponent ], "d" ;HexDigit is 0-9, a-f or A-F. _ sits between two digits of an integer or of a fraction, never leading, trailing, doubled or beside the prefix, ., e or d; the exponent takes none.
No identifier character may follow a numeric token except the d suffix. Leading zeros, octal (0o), uppercase prefixes (0X, 0B), .5, and 1. are rejected. 1e3 is a Float. A sign is an operator, not part of the token (range checking
). A dot starts a fraction only before a digit, so 2.seconds() is an Int, a dot, and a method name.
Blocks and line ends#
- A block is
{, statements,}. Every compound statement and every declaration body uses one, even for a single line:if c { return 1 }. A block is never empty, except that...stands for a runtime-bound body or a schema with no fields (see below). There is nopass. - A statement ends at the end of its line, or at the
}that closes its block. Inside(),[]and a map’s{}, newlines are suppressed.;and backslash continuation are rejected. - Indentation carries no meaning.
ms fmtindents each block four spaces (a tab per level on disk) and puts{at the end of the header line and}at the start of its own line. A block that fits on one line may stay on it. elsefollows the closing brace on the same line:} else {and} else if c {. A line that starts withelseafter a}line is accepted and joined by the formatter.- A line starting with
|, or.not followed by a digit or., continues the previous statement (pipe flows ). - A
{opens a block unless it follows a token that expects an operand ((,[,,,=,:=,:,return, an operator,in) or its matching}is followed by:=or=; there it is a map literal or a destructuring pattern.=> {is always a block, so a map returned from an arrow body is written in parentheses:() => ({"a": 1}). A block belongs to a declaration,if,while,for, match arm or closure; a bare{ ... }statement is not a scope. - Delimiters must balance. Trailing commas are allowed only in comma-separated forms below.
Anonymous functions inside delimiters#
Inside a call, list, or grouping, a function expression may have a => body (ending at the enclosing comma or closer) or a block body. A block body is delimited by its braces, so a following comma belongs to the enclosing arguments:
fn offset() Int {
return apply(
transform: fn(value Int) Int {
return value - 1
},
value: 3,
)
}Use value => value - 1 when context supplies the parameter type; a => body is one expression and returns its value (it can be a conditional expression: value => if value > 0 { value } else { 0 }). A longer body goes in braces after => (value => { ... }, with explicit returns) or after the signature of a typed closure (fn(value Int) Int { ... }).
Modules, declarations, and types#
In the EBNF, braces repeat, brackets are optional, and quoted brackets are source tokens. StringLiteral is defined in text and bytes
, Expression in expressions
.
Module = { Import | Declaration } ;
Import = "import", ( ImportNames | "(", ImportNames, [ "," ], ")" ), "from", PlainStringLiteral, NEWLINE ;
ImportNames = ImportName, { ",", ImportName } ;
ImportName = Name, [ "as", Name ] ;
Declaration = [ "export" ], (TypeDeclaration | AliasDeclaration | EnumDeclaration | InterfaceDeclaration | FunctionDeclaration
| ConstantDeclaration | ExternDeclaration)
| Implementation | TestDeclaration | BenchDeclaration ;
ConstantDeclaration = Name, ( ":=", Expression | Type, ":=", Expression ), NEWLINE ;
TypeDeclaration = [ "opaque" ], "type", Name, [ TypeParameters ], "{", ( "...", "}" | RecordBody, "}" ) ;
AliasDeclaration = "type", Name, [ TypeParameters ], "=", Type, { "|", Type }, NEWLINE ;
EnumDeclaration = [ "opaque" ], "enum", Name, [ TypeParameters ], "{", AlternativeBody, "}" ;
RecordBody = { Field } ;
Field = Name, { ",", Name }, Type, [ "=", Expression ], NEWLINE ;
AlternativeBody = VariantDeclaration, { VariantDeclaration } ;
VariantDeclaration = Name, [ "(", Parameters, ")" ], NEWLINE ;
InterfaceDeclaration = "interface", Name, [ TypeParameters ], "{", ( "...", "}" | ContractBody, "}" ) ;
ContractBody = OperationSignature, { OperationSignature } ;
OperationSignature = [ "var" ], "fn", Name, [ TypeParameters ], "(", [ FunctionParameters ], ")", ResultType, NEWLINE ;
FunctionDeclaration = "fn", Name, [ TypeParameters ], "(", [ FunctionParameters ], ")",
ResultType, FunctionSuite ;
ResultType = Type ;
MethodDeclaration = "fn", [ "var" ], Receiver, ".", Name, [ TypeParameters ], "(", [ FunctionParameters ], ")",
ResultType, FunctionSuite ;
Receiver = Name, [ "[", ReceiverArgument, { ",", ReceiverArgument }, "]" ] ;
ReceiverArgument = Name, [ Bound ] | Type ;
(* The receiver names the declared type, with one argument per type parameter: its name, optionally bounded, or a concrete type. *)
ExternDeclaration = "extern", "fn", Name, "(", [ FunctionParameters ], ")", ResultType, NEWLINE
| "extern", "type", Name, [ TypeParameters ], NEWLINE ;
FunctionSuite = "=>", (Expression | SimpleStatement)
| "{", ( "...", "}" | Statement, { Statement }, "}" ) ;
ArrowFunction = (Name | "(", [ ParameterNames ], ")"), "=>", (Expression | SimpleStatement) ;
ParameterNames = ParameterName, { ",", ParameterName } ;
ParameterName = [ "var" | "move" ], Name | Pattern ;
TestDeclaration = "test", PlainStringLiteral, Block ;
(* A test body behaves as if it returns Result[Void, Error]: completing, bare return, or `return` succeeds; a postfix `?` or return error(...) fails it. *)
(* Only canonical TestHooks implementations may omit operations; missing hooks are no-ops. *)
BenchDeclaration = "bench", PlainStringLiteral, [ "per", PositiveInteger ], Block ;
(* `bench` is contextual: it starts a declaration only before a string literal. The body is one iteration (`per N` says it performs N operations, and `ms bench` then reports per operation), with a test body's result rules and no `fixture`; `ms bench` repeats and times it. *)
Parameters = Parameter, { ",", Parameter }, [ "," ] ;
Parameter = Name, { ",", Name }, Type ;
(* `width, height Int` declares two names of one type; the default of `FunctionParameter` and `Field` applies to each. *)
FunctionParameters = FunctionParameter, { ",", FunctionParameter }, [ "," ] ;
FunctionParameter = [ "var" ], Parameter, [ "=", Expression ] ;
CallbackParameters = CallbackParameter, { ",", CallbackParameter }, [ "," ] ;
CallbackParameter = [ "var" ], Name, [ Type ], [ "=", Expression ] ;
TypeParameters = "[", TypeParameter, { ",", TypeParameter }, [ "," ], "]" ;
TypeParameter = Name, [ Bounds ], [ "=", Type ] ;
Bounds = NamedType, { "&", NamedType } ;
Type = ( NamedType | FunctionType | "(", Type, ")" ), { "?" | "!", [ NamedType ] } ;
NamedType = TypePath, [ TypeArguments ] ;
TypePath = Name, { ".", Name } ;
TypeArguments = "[", Type, { ",", Type }, [ "," ], "]" ;
FunctionType = "fn", "(", [ [ "var" ], Type, { ",", [ "var" ], Type } ], ")", Type ;- A type suffix
?isOptional[T];!isResult[T, Error], and!EwithEdirectly after the bang isResult[T, E]. Suffixes apply left to right. - A
type Name = Typedeclares an alias : another name for the same type, or with|a type set that bounds a type parameter. Atype Name { ... }declares record fields; anenumdeclares one or more variants. Their methods are receiver methods,fn Type.name(...), written beside the type; a type satisfies an interface by having methods that match it. Aninterfaceholds only operation signatures. A payloadless variant isReady, without(). Names are unique per scope. - A result type follows the parameter list with no arrow (
fn double(value Int) Int { ... });->is rejected with the remedy. An anonymous function with untyped parameters is writtenvalue => value * 2,(a, b) => a + bor() => 1; typing a parameter or declaring a result keepsfn(fn(value Int) Int => value * 2). A longer body goes in braces aftervalue =>or after the signature offn(value Int) Int. - Named functions (
fn) need explicit parameter and result types; anonymous ones may infer them (callback inference ). - Defaults: function parameters
, record fields
, and
= nullon Optional interface parameters. Function types and enum payloads have none. Parameter names in a function type do not exist: two function types are the same when their parameter types,varmarkers and result type match, and calls through function values are positional. No variadics or parameter patterns. - A named function or method body may be
...(fn read_bytes(count Int) Bytes { ... }), as may a type schema (type Duration { ... }); the standard library uses this for runtime-bound implementations. In the standard library, a property interface usesinterface Name { ... }; an empty implementation may supply a marker interface. Test, bench, and control-flow blocks are nonempty. - Imports and declarations may interleave; order does not affect resolution. Import paths, test names, and bench names are plain literals (escapes allowed; plain
"..."text, neverf"..."). exportapplies to records, aliases, enums, interfaces, named functions, constants and extern declarations, not tests, benches, or methods.- A receiver method is accepted only in the module that declares its type, and repeats the type’s parameters (
fn Box[T].get() T), optionally bounded (fn Box[T Equal].same(...)) or fixed (fn List[Int].sum()). Methods may also declare their own type parameters . Methods of one name on one receiver form are rejected as contracts describe. &only combines generic bounds, as inT Read & Closeable; order is irrelevant. There is no intersection or refinement syntax for value types.- No module-level statements or
var; a top-level:=is a constant . Snippets of local bindings are body fragments. Type paths add no wildcard imports; see module rules .
Statements and patterns#
Block = "{", Statement, { Statement }, "}" ;
(* A statement ends at NEWLINE or at the "}" that closes the block, so `{ return 1 }` is a block of one statement. *)
Statement = SimpleStatement, NEWLINE
| IfStatement | WhileStatement | ForStatement ;
SimpleStatement = Binding | Assignment | CompoundAssignment | ReturnStatement | "break" | "continue"
| CallStatement ;
Binding = ImmutableBinding | "var", ( VarEntry
| "(", NEWLINE, { VarEntry, NEWLINE }, ")" ) ;
ImmutableBinding = ( Name | PositionalPattern | RecordPattern ), ":=", Expression
| Name, Type, ":=", Expression ;
VarEntry = (Name, [ Type ] | PositionalPattern | RecordPattern), "=", Expression ;
Assignment = AssignmentTarget, "=", Expression ;
AssignmentTarget = Name, { ".", Name | "[", Expression, "]" } ;
CompoundAssignment = AssignmentTarget, ( "+=" | "-=" | "*=" | "/=" | "%=" ), Expression ;
ReturnStatement = "return", [ Expression ] ;
CallStatement = Expression | "void", Expression ;
IfStatement = "if", [ Name, ":=" | "var", Name, "=" ], Expression, Block,
{ "else", "if", [ Name, ":=" | "var", Name, "=" ], Expression, Block },
[ "else", Block ] ;
WhileStatement = "while", Expression, Block ;
ForStatement = "for", BindingPattern, "in", Expression, Block ;
MatchExpression = "match", Expression, "{", MatchArm, { MatchArm }, "}" ;
MatchArm = (CasePattern | LiteralPattern | "_"), ArmSuite ;
LiteralPattern = [ "-" ], Number | String | "true" | "false" ;
ArmSuite = "=>", (SimpleStatement | Expression)
| "=>", "{", { Statement }, [ Expression ], "}" ;
CasePattern = CasePath, [ "(", PayloadNames, ")" ] ;
CasePath = Name, [ TypeArguments ], { ".", Name } ;
PayloadNames = (Name | "_"), { ",", (Name | "_") }, [ "," ] ;
BindingPattern = Name | PositionalPattern | RecordPattern ;
PositionalPattern = "[", [ BindingPattern, { ",", BindingPattern }, [ "," ] ], "]" ;
RecordPattern = "{", RecordEntry, { ",", RecordEntry }, [ "," ], "}" ;
RecordEntry = Name, [ ":", BindingPattern ] ;void expressionruns the expression and drops its result on purpose;voidalone is the Void value.CallStatementaccepts a call or match and discards the result, orcall()?when the success type isVoid(propagation ). Bare names and arithmetic are not statements.- Assignment replaces a
varor record field.target op= valuemeanstarget = target op (value); write the operator and=adjacent. The target is mutable storage: a name, field path (box.inner.count += 1), list index (values[i] += 1), or map entry (stock[line.sku] -= line.qty). The index of a compound target is a name, field path or literal, so it is read twice without effect; the store takes a clone of the key and the name stays usable. Calls cannot be assignment targets.+=appends text;-=on text is an error. - Only a simple name takes a type annotation. Positional patterns may be empty; empty record patterns are rejected.
_discards a binding or match payload and is the wildcard match arm; it cannot be read as a value. - A block may be written on one line,
if c { return 1 }, and then holds one statement. A one-line function or method body is written=>and holds one expression, which is returned:
fn double(value Int) Int => value * 2
fn positive(value Int) Bool {
if value > 0 {
return true
} else {
return false
}
}else ifandelsefollow the closing brace on its line:} else if c {,} else {. One-line and multi-line blocks may mix;ms fmtwrites every block of a chain the same way.- A match arm is
pattern => value(or one statement) on one line, orpattern => { ... }with statements and then a value. - Match patterns use positional payloads, not labels. On an interface value, a pattern names a complete concrete type and one receiver binding, with a final wildcard (pattern matching ).
matchis an expression even when discarded; loops are statements, andifis a statement. The conditional expression isif c { a } else { b }; theelseis required and chains continue withelse if. An arrow body may be one:x => if x > 0 { 1 } else { 0 }.- Local type, implementation, import, test, and bench declarations are rejected; a local function is a
fnstatement, sugar for binding afn(it cannot call itself). - Resources follow the scope-end cleanup
contract. There is no spawn or deferred-call syntax. Ownership markers in signatures are
move(callee takes the argument),hold(result borrows from the argument), and&(borrowed result or field); see mutation and references .
Rejected forms#
var count = 3 // Module-level var is rejected (use := for constants).
fn wrong() Int:
return 1 // A block opens with a brace, not a colon.
fn wrong() Int {
(first, second) := pair // Parentheses are not a binding pattern.
}Each example is an independent rejected form.
Nesting limits#
The parser rejects nesting deeper than 1000 levels (expressions, types, patterns, blocks, interpolated literals) and chains longer than 10000 operators, member accesses, calls, or indexes, reporting parse: nesting exceeds 1000 levels.