Zane Syntax Reference
This document is the canonical reference for Zane’s surface syntax. Topic documents define semantics; this document defines form only. The forms are written without their terminator: a declaration or statement ends with a ;, unless it ends in a } (lexical.md §6.3).
See also:
types.mdfor constructors.functions.mdfor methods.adt.mdforenum,variant,match, and enum maps.control-flow.mdfor branching and loop semantics.error-handling.mdfor abort semantics.operators.mdfor precedence.
1. Declarations
1.1 Symbols
New symbol declarations:
name VarType(args, ...)
name VarType{field = expr; ...}
name VarType{fieldA; fieldB; ...}
name ^VarType(args, ...)
name ^VarType{field = expr; ...}
name ^VarType{fieldA; fieldB; ...}
name VarType = expr
name ^VarType = expr
name &VarType = expr
name ReturnType(param ParamType, ...) { body }
name ReturnType(param ParamType, ...) => expr
name VarType foreign "cGlobal"
VarType{fieldA; fieldB;} is shorthand for VarType{fieldA = fieldA; fieldB = fieldB;}.
The VarType position of name VarType(args, ...) may be a qualified Type.member — a named constructor (see types.md §3.4) or a variant case (see adt.md §3.2). v Vector2.diagonal(Float(3.0)) and e Expr.intLit("5") both instantiate at the base type: the declared symbol holds Vector2 / Expr, never Vector2.diagonal or a per-case type.
The first six forms are the instantiation forms. Each is shorthand for name VarType = expr, with the type written once and the value built from it, and a ^ before VarType stays on the declared type. So name ^VarType(args, ...) declares the same roaming owner (§2.3) as name ^VarType = VarType(args, ...):
car ^Car(Int(1)); // car ^Car = Car(Int(1));
v ^Vehicle.truck(Int(4)); // v ^Vehicle = Vehicle.truck(Int(4));
e ^Expr.intLit("5"); // e ^Expr = Expr.intLit("5");
car ^Car{id = Int(1); seats = Int(4);} // car ^Car = Car{id = Int(1); seats = Int(4);}
car ^Car{id; seats;} // car ^Car = Car{id = id; seats = seats;}
The two lambda forms declare a lambda-valued symbol. They mirror the constructor-call instantiation form name VarType(args, ...): just as text String("hello") instantiates a value of type String, callback Float(x Int) { body } instantiates a function value. The full set of lambda-variable forms — including this, mut, and abort types — lives in §3.8.
The last form declares a foreign variable, whose value is a handle to a C global: it writes foreign and one string literal without interpolation, the global’s symbol, in place of an initializer. Only the root package and the body of an exported lambda declare one (ffi.md §5.1, packages.md §8.4).
Every symbol declaration is directly initialized. Bare forms such as name VarType and name &VarType are not declaration forms.
name VarType // ILLEGAL: symbols require direct initialization
Once a symbol already exists, reassignment uses only:
name = expr
Story:
stories/syntax.md— “The order assignment forced”. Story:stories/syntax.md— “The instantiation forms take^”.
1.2 Package constants
name VarType(value)
1.3 Reference-type bodies (#)
A #-marked body declares a reference type — identity-bearing, may hold & fields, moved rather than copied. It declares fields only and names a type through a type declaration (§1.6). There is no standalone #struct Name { ... } declaration form.
type Name = #struct {
field FieldType;
field &FieldType;
}
1.4 Value-type bodies
A value-type body (unmarked) declares a value type — copied, transitively value, no & or reference-type fields. It declares fields only and names a type through a type declaration (§1.6). There is no standalone struct Name { ... } declaration form.
type Name = struct {
field FieldType;
}
1.5 Imports
import packageName
import packageName as alias
import packageName$member
import packageName$member as alias
import packageName$[memberA, memberB]
import packageName$
import packageName<Argument, ...>
import packageName<Argument, ...> as alias
import packageName<Argument, ...>$member
import packageName<Argument, ...>$member as alias
import packageName<Argument, ...>$[memberA, memberB]
import packageName<Argument, ...>$
An import of a parameterized package writes its argument list in every form; each Argument is a type or a compile-time integer (packages.md §3.10). The trailing $ form carries no member list and no *. An as clause is legal on the whole-package form and on a single-member form, never on the bracket list or the trailing-$ form.
import math$[sqrt, pow] as m; // ILLEGAL: a list has no single name to rename
import math$ as m; // ILLEGAL: nothing is qualified to rename
See also:
packages.md§3 for the declarations each form makes available.
1.6 Type and alias declarations
type Name = TypeExpr
alias Name = TypeExpr
type Name<T Type, n @concepts$Int> = TypeExpr
type Name = struct { field FieldType; ... }
type Name = #struct { field FieldType; ... }
type Name = variant { member FieldType; ... }
type Name = #variant { member FieldType; ... }
type Name = enum [ memberA, memberB, ... ]
type Name = #handle{ cType = "cType"; set = "setter"; free = "freeFunction"; }
type declares a new distinct named type; alias declares an interchangeable name. The right-hand side is any type expression (§2.4), including an inline struct, #struct, variant, #variant, or enum body; a leading # marks a reference type (§2.14). A <> header on the left declares the type’s parameters. See types.md §5.
1.7 Variant declarations
A variant body uses the same grammar as a struct body: { } brackets with ;-terminated members, each a lowercase member name followed by its payload type.
type Name = variant {
memberA TypeA;
memberB TypeB;
}
See also:
adt.md§3 for variant semantics.
1.8 Enum declarations
An enum body is a flat list: [ ] brackets with ,-separated lowercase members. Members are payloadless.
type Name = enum [ memberA, memberB, memberC ]
See also:
adt.md§2 for enum semantics.
1.9 Enum map declarations
An enum map is a package-scope declaration. It names the enum, the property, the property’s type, then a { } body of ;-terminated member = value entries.
EnumName.property FieldType {
memberA = valueA;
memberB = valueB;
}
See also:
adt.md§6 for enum-map semantics.
2. Types
2.1 Fundamental types
Int, Float, I32, F32, U8, Bool, String, Unit, Array<T, n>, ArrayRef<T, n>, List<T>, ListRef<T>
These are the types the core package declares. They are reached through an import like any other package’s members (packages.md §3.3), so import core writes them core$Int and import core$ writes them unqualified. See types.md §2.6 for their semantics.
2.2 Named types
packageName$TypeName
TypeName
2.3 Reference types
&TypeName
^TypeName
&TypeName is a reference type. It is legal in storage sites (local-variable declarations, fields, and nested storage types such as the example below), as well as in function and constructor parameter positions, return-type positions, and abort-type positions.
ArrayRef<&Node, 4>
^TypeName is a roaming owner of a reference type. It is legal on a local-variable declaration, a parameter, a return type, and an abort type, and nowhere else: never on a field, and never inside another type’s arguments, except on the introduction that is the element of a parameter’s own @concepts$Array, where it is the mode each literal element is passed in (generics.md §3.2). In a function type it marks a return or parameter slot (§2.13). ^ and & are the only markers a type may carry, and never together.
spare ^Engine = Engine();
^Car make(power Int) { ... }
Unit park(this Garage, car ^Car) mut { ... }
See memory.md §2.1 for settled and roaming owners, and §2.9 for the semantics of the three passing modes.
2.4 Type expressions
A type expression applies arguments to a parameterized type with <>. Arguments are positional.
TypeName<Arg, ...>
Vector<Int>
Array<Int, 10000>
Matrix<Float, 3>
A type argument fills a type-parameter slot; a number argument fills a number-parameter slot. A type expression is legal in any type position: fields, parameter and return types, aliases, and nested arguments. A constructor call MUST NOT carry a <> list. Inside a verb’s value parameter, a <> entry may also introduce a type or number parameter by carrying its concept (param Array<T Type, n @concepts$Int>); see generics.md §4.4. See generics.md §4 and §5.
A mould — a struct { ... }, #struct { ... }, variant { ... }, #variant { ... }, enum [ ... ], or #enum [ ... ] — MUST appear only as the right-hand side of a type or alias declaration (§1.6); every other type position names a declared type or an instantiation (see types.md §5.3). A leading # marks a reference type (§2.14).
type Operation = #struct { left Expr; right Expr; op Operator; }
type QualifiedIdent = struct { packageName String; member String; }
type Expr = #variant {
op Operation;
qualifiedIdent QualifiedIdent;
}
2.5 Type and number parameters
A parameterized type declares its parameters in a <> header. Each entry is name Type (a type parameter) or name @concepts$Int (a number parameter). Type and @concepts$Int are compiler concept types, legal only in parameter positions (§2.11).
type Vector<T Type> = struct {
x T;
y T;
}
type Buffer<T Type, n @concepts$Int> = struct {
data Array<T, n>;
}
Parameters are referenced by bare name. The case of a parameter’s identifier marks whether it is a type or a number: T is a type, n is a number. Type expressions (§2.4) supply arguments positionally at use sites.
A verb — a function, method, or constructor — has no <> header. It introduces its type and number parameters inline within its value parameters, at each parameter’s first marked occurrence, by carrying the concept there (x T Type, param Array<T Type, n @concepts$Int>); see §3.1 and generics.md §3. See also lexical.md §3.
2.6 Container storage primitives
@primitives$Array<T, n>
@primitives$ArrayRef<T, n>
@primitives$List<T>
@primitives$ListRef<T>
@primitives$Array<T, n> is n contiguous elements of type T, a value type; @primitives$ArrayRef<T, n> is the same layout as a reference type; @primitives$List<T> and @primitives$ListRef<T> are their dynamically sized counterparts, a value type and a reference type. core declares Array<T, n>, ArrayRef<T, n>, List<T>, and ListRef<T> over them (§2.1), and source writes those names. Both parameters of Array may be concrete (Array<Int, 10000>), forwarded from an enclosing scope (Array<T, n>), or inferred by a constructor from a literal (Array([Int(1), Int(2), Int(3)])). See generics.md §8.
2.7 Intrinsic namespaces
@primitives$name
@concepts$name
@operators$name
@math$name
@controlflow$name
@runtime$name
@program$name
An intrinsic is anything reached through @: a type, operation, or instance the compiler supplies rather than a package declares. The @ namespaces are the intrinsic namespaces, and each holds one kind of intrinsic:
@primitives$holds storage primitives: the scalar primitives@primitives$I32,@primitives$I64,@primitives$F32, and@primitives$F64— 32- and 64-bit signed integers and IEEE 754 floats — the byte primitive@primitives$U8, an unsigned 8-bit integer, the machine-word@primitives$Bool, the value-type string primitive@primitives$String, the container primitives of §2.6, the byte set@primitives$ByteSet(types.md§2.12), the worker pool primitive@primitives$WorkerPooland its@primitives$EventSource(concurrency.md§6), opaque runtime primitives used by fundamental types, and the unit type@primitives$Unit, whose one value is written@primitives$Unit(). An intrinsic that returns nothing, or aborts with nothing, uses@primitives$Unit.@concepts$holds compiler concept types, used for source literals and for source constructs that are not storage (§2.8).@operators$holds the machine operations: the arithmetic, comparisons, Boolean connectives, and string join on storage primitives that a package writes its operators over (operators.md§2.6).@math$holds the math functions on scalar primitives: bit operations, square root, rounding, trigonometry, and the rest (math.md§2).@controlflow$holds the control-flow intrinsics, the operations that branch, repeat, and exit (§5.1).@runtime$holds the runtime types@runtime$Consoleand@runtime$Runtimeand their methods (effects.md§6.6).@program$holds the running program’s own instances of those types,@program$consoleand@program$runtime.
An intrinsic operation has one signature, with five exceptions, each an overload set told apart by its argument types like any other (functions.md §4.1):
- intrinsic methods and subscripts that share an identifier on different types, since a method’s or a subscript’s subject is one of its parameters (
generics.md§8.6); - the constructors of
@primitives$WorkerPooland itsstartmethod, each with a form for a pool with shared state and one without, andstartwith and without event sources (concurrency.md§6); - each machine operation of
@operators$and each math function of@math$, which have one signature per operand type they take (operators.md§2.6,math.md§2.1); - the constructors of a scalar primitive and of
@primitives$U8: the anonymous constructor, with one signature from its literal’s concept and, for a scalar primitive, one from each primitive it converts from exactly, and each named one, with one signature per primitive it converts from (types.md§2.9); - the anonymous constructor of
@primitives$String, with one signature from its literal’s concept and one from each scalar primitive (types.md§2.11).
An intrinsic is never an operator, and no operator is declared over storage primitives alone (operators.md §2.2).
A namespace is named for the kind of member it holds or for the purpose those members serve. Every member of every intrinsic namespace is an intrinsic, so no namespace takes that word as its name.
Every intrinsic namespace except @program$ is reachable from every package without an import. @program$ is reachable only from the root package (packages.md §6.1), which passes its instances to any other package that needs one.
Story:
stories/syntax.md— “intrinsicnames the whole@space”.
2.8 Compiler concept types
@concepts$Int
@concepts$Float
@concepts$String
@concepts$Array<T, n>
@concepts$Map<K, V>
These compiler-provided concept types represent source literals before they are lowered into storage types: integer and float literals (lexical.md §7), string literals, array literals (§2.9), and map literals (§2.10). Type in parameter declarations (§2.11) and @concepts$Block (§2.12) are concept types too. Concept types may appear in parameter positions but MUST NOT be used as storage types such as local variables, fields, or nested storage positions. Functions and constructors may use concept-typed parameters to accept literals and lower them into the corresponding fundamental type.
The leaf concept types — Type, @concepts$Int, and @concepts$Float — each represent a single compile-time value wherever they appear, including as an argument to a verb. @concepts$String instead carries literal text and optional interpolation (types.md §2.8); an interpolation may be a runtime value. The entries of an array or map literal are ordinary expressions and may likewise be runtime values, so @concepts$Array<T, n> and @concepts$Map<K, V> carry no compile-time guarantee; a block argument (§2.12) is not a value at all.
A number or string literal becomes storage through a storage primitive’s constructor from its concept (see types.md §2.7). Each primitive has one, and the string primitive a second, escaped. An integer literal may become either integer primitive or the byte primitive, a float literal either float primitive:
@primitives$U8(value @concepts$Int)
@primitives$I32(value @concepts$Int)
@primitives$I64(value @concepts$Int)
@primitives$F32(value @concepts$Float)
@primitives$F64(value @concepts$Float)
@primitives$String(value @concepts$String)
@primitives$String.escaped(text @concepts$String)
Story:
stories/types.md— “How a literal lowers into primitive storage”.
2.9 Array literals
An array literal — a [ ] list of values, not an enum body or a match case group — carries @concepts$Array<T, n>, where T is the type of its elements and n is how many there are. Every element MUST already have type T; there is no search for a common type across elements that differ. The one exception is a literal whose elements are of a reference type T and of &T, both: it carries no element type of its own, and is legal only where it is passed as &T elements, which take each element on its own (generics.md §8.4). Carrying both parameters is what lets a constructor read an element type and a length off a literal — Array([Int(1), Int(2), Int(3)]) fixes T = Int and n = 3 (see generics.md §8.1).
A literal with no elements fixes no T, so an array literal MUST hold at least one element. An empty collection is built by naming its type, which supplies the element type the literal cannot:
nums Array([Int(1), Int(2), Int(3)]); // legal: T and n read from the literal
empty Array(Int, 0); // legal: the type is named, not inferred
empty []; // ILLEGAL: an empty literal fixes no element type
Story:
stories/memory.md— “AnArrayRefconstructor names the mode of its elements”.
2.10 Map literals
A map literal is a { } body whose entries are ;-terminated (§6.1 of lexical.md), each entry exactly two ,-separated expressions — a key and a value. It carries @concepts$Map<K, V>, where K is the type of every key and V the type of every value. As with an array literal, every key MUST already have type K and every value type V; there is no search for a common type. A map literal MUST hold at least one entry, since an empty one fixes neither K nor V.
{
String("first"), Int(1);
String("second"), Int(2);
}
Entries are evaluated in written order. A key is an ordinary expression rather than an identifier, so two entries may resolve to the same key; the later entry then replaces the earlier entry. Equality is generally not decidable before run time, so a duplicate is never a compile-time error.
first String("y");
{
first, String("hello"); // key is the value of `first`, which is "y"
String("y"), String("b"); // same key: replaces the entry above
}
@concepts$Map carries no entry count, unlike @concepts$Array. The map literal is not a general-purpose container literal; it is a specialized form for key-value pairs, and Array is where generic containment lives. A keyed structure that needs its size in its type is therefore built from an array of pair values — an ordinary array literal, which supplies n in the ordinary way — rather than from a map literal.
It could not carry a useful count in any case. Entries with equal keys collapse, and a key is an expression, so the number of entries written is only an upper bound on the number stored — where an array literal’s n is exact.
An empty { } written in a value position with no introducing token is always a code block, never a map literal (§4.8), so the two never compete for the same text. A { } that follows an introducing token — an init{ }, a mould body — is governed by that form, not by this rule.
A map literal is one of the two { } arguments that may trail a call, the other being a block (§4.8). A literal large enough to want the position gets it for the same reason a block does.
The examples above show the literal alone, with no consumer, because this section fixes the literal and the concept type it carries and nothing else; the dynamic container types that consume such a literal — their operations, any ordering, and what they require of a key type — remain unspecified (see generics.md §9).
2.11 Parameter concept types
The concept type Type declares a type parameter, and @concepts$Int — the concept type of an integer literal (§2.8) — declares a number parameter (see generics.md §3). They follow the rule of §2.8: legal in parameter positions, never as storage. A Type parameter accepts a type; an @concepts$Int parameter accepts a compile-time integer.
2.12 The block-argument type
@concepts$Block is the type of a block argument — a braced run of statements written at a call site and executed by the callee (§4.8). It takes no type argument, since a block yields nothing. It follows the rule of §2.8 and may never be stored.
@concepts$Block
See also:
control-flow.md§2 for the behaviour of a block argument.
2.13 Function types
A function type leads with its return type, then lists parameter types inside [ ], then any trailing mut. There is no -> arrow. This mirrors the order of function declarations (§3.1–§3.2) and lambda literals (§3.8): the return contract is written first.
ReturnType[ParamType, ...]
ReturnType?AbortType[ParamType, ...]
ReturnType[this SubjectType, ParamType, ...]
ReturnType[this SubjectType, ParamType, ...] mut
&ReturnType[this SubjectType, ParamType, ...]
ReturnType?AbortType[this SubjectType, ParamType, ...]
ReturnType?AbortType[this SubjectType, ParamType, ...] mut
The abort type stays attached to the return type, exactly as in a declaration’s ReturnType?AbortType name(...) header.
Reference-typed parameters and returns use the ordinary type form. A parameter slot accepts all three passing modes — ParamType, ^ParamType, and &ParamType — and a reference-typed return or abort slot accepts a ^ or & type (§2.3):
ReturnType[&ParamType, ...]
^ReturnType[^ParamType, ...]
&ReturnType[this SubjectType, &ParamType, ...]
ReturnType[this SubjectType, ParamType, ...] mut
When the function type is a value parameter’s own type, a slot may also introduce a type parameter of the verb whose signature contains it, as T Type, ^T Type or &T Type, where the marker is the slot’s mode (generics.md §3.2):
^T Type[Int] // the return slot introduces T
Unit[T Type, Int] // a parameter slot introduces T
mut is legal only when the first parameter is this.
Int[Node, Int] mut // ILLEGAL: mut requires this as first parameter
Unit[Int, this Node] // ILLEGAL: this must be the first parameter
Story:
stories/syntax.md— “Two orders, and the order we had already turned down”.
2.14 The # reference modifier
A leading # marks a reference type. It attaches only to a mould — #struct { ... }, #variant { ... }, or #enum [ ... ] — and only as the right-hand side of a type/alias declaration (§1.6), or to a foreign handle — #handle{ ... } (§2.16) — and only as the right-hand side of a type declaration. The unmarked moulds declare value types; a foreign handle has no unmarked form.
type Cell = #struct { value Int; } // reference product type, declared and named
type Tree = #variant { leaf Int; node Tree; } // reference sum type; `node` recurses
node is written as an ordinary owning member. The compiler boxes such a member because no finite inline layout exists for it — nothing is written for that, and it is not an & (see adt.md §4). A value type may recurse the same way; its boxed member is owned by the value and deep-copied with it (see memory.md §2.3).
& combines with a reference type and never with a bare value type: an &T requires T to be a reference type — a declared #struct/#variant/#enum, a foreign handle declared with #handle (ffi.md §4.1), or a type parameter filled with one (generics.md §3.6) — so a stored reference is written &Cell or &Tree (see memory.md §2.4). See types.md §2.1 for the semantics.
2.15 String literal forms
"text"
"text with \"double quotes\""
"text with \\ and \w"
"hello \%name"
"literal \\%name"
A string is delimited by double quotes. \", \\, and \%name are the language-defined forms inside it. After \%, name is one lowercase value identifier (§4 of lexical.md); it ends at the first character not belonging to that identifier. There is no expression-delimited interpolation form, and qualification, member selection, and calls are not part of the interpolation identifier.
"\%" // ILLEGAL: missing interpolation identifier
"\%TypeName" // ILLEGAL: interpolation requires a value identifier
See also:
lexical.md§7.1 for tokenization and structural escapes.types.md§2.8 for concept typing and interpolation coercion.
2.16 Foreign handles
type Name = #handle{ cType = "cType"; }
type Name = #handle{ cType = "cType"; free = "freeFunction"; }
type Name = #handle{ cType = "cType"; set = "setter"; free = "freeFunction"; }
A foreign handle is declared only as the right-hand side of a type declaration (§1.6). Its { } is written like a field-constructor call (§1.1): named entries, each name = literal;, whose literals are strings without interpolation. cType names a C type and is required; set names the setter and free the free function, and either may be left out, except that a handle with set has free. Each entry appears at most once, and no other entry is allowed. The leading # is required.
type Stream = handle{ cType = "z_stream"; free = "zane_stream_free"; } // ILLEGAL: a foreign handle carries `#`
alias Stream = #handle{ cType = "z_stream"; free = "zane_stream_free"; } // ILLEGAL: declared only by `type`
type Stream = #handle{ cType = "z_stream"; set = "zane_stream_set"; } // ILLEGAL: `set` without `free`
See also:
ffi.md§4 for foreign handle semantics.
3. Functions, Methods, Constructors, and Lambdas
3.1 Functions
ReturnType name(param ParamType, ...) { body }
ReturnType name(param &ParamType, ...) { body }
ReturnType?AbortType name(param ParamType, ...) { body }
ReturnType name(param ParamType, ...) => expr
ReturnType name(param &ParamType, ...) => expr
ReturnType?AbortType name(param ParamType, ...) => expr
ReturnType name(param T Type, ...) { body }
ReturnType name(param Container<T Type, n @concepts$Int>, ...) { body }
A reference-type parameter independently selects one of the three passing modes (see memory.md §2.9): bare ParamType borrows, ^ParamType takes the owner, &ParamType takes a reference. A value-type parameter has no such choice — it is always a read-only borrow — so neither ^ nor & is written on one. A reference-typed return type or abort type carries ^ or & (^ReturnType, &AbortType); a bare one is ill-formed, because a borrow is never returned or aborted.
A function, method, or constructor has no <> parameter header. It introduces a type or number parameter inline within its value parameters, at the parameter’s first marked occurrence — on a value parameter’s type (param T Type, carrying the parameter’s passing mode as param ^T Type or param &T Type) or inside a value parameter’s nested type (param Container<T Type, n @concepts$Int>, where the element of the parameter’s own @concepts$Array may carry the elements’ passing mode as ^T Type or &T Type), or in a slot of a value parameter’s function type (make ^T Type[Int], §2.13) — and references it bare elsewhere, including in positions written earlier such as the return type. Inline parameters are inferred from the value arguments at the call; the same Type / @concepts$Int concepts are used as in a type definition’s header (§2.5). See generics.md §3 and §5.
Story:
stories/syntax.md— “Two orders, and the order we had already turned down”.
3.2 Methods
ReturnType name(this SubjectType, param ParamType, ...) { body }
ReturnType name(this SubjectType, param &ParamType, ...) { body }
ReturnType name(this SubjectType, param ParamType, ...) mut { body }
ReturnType name(this SubjectType, param &ParamType, ...) mut { body }
ReturnType?AbortType name(this SubjectType, param ParamType, ...) { body }
ReturnType?AbortType name(this SubjectType, param ParamType, ...) mut { body }
ReturnType name(this SubjectType, param ParamType, ...) => expr
ReturnType name(this SubjectType, param &ParamType, ...) => expr
ReturnType name(this SubjectType, param ParamType, ...) mut => expr
ReturnType name(this SubjectType, param &ParamType, ...) mut => expr
ReturnType?AbortType name(this SubjectType, param ParamType, ...) => expr
ReturnType?AbortType name(this SubjectType, param ParamType, ...) mut => expr
ReturnType name(this SubjectType<T Type, n @concepts$Int>, param ParamType, ...) { body }
ReturnType name(this S Type, param ParamType, ...) { body }
this is legal only in the first parameter position. A declaration is a method if and only if its first parameter has the name this. The last form introduces a type parameter as the subject’s type, so the method applies to a subject of any type (generics.md §3.7).
The subject takes no marker, for either kind of type: neither ^ nor & is written on this. The subject is always a borrow of the caller’s value or owner, mutable when the method is mut, and never stored or returned as &T. See functions.md §2.4.
=> expr returns expr, including when expr has type Unit.
3.3 Positional constructors
TypeName(param ParamType, ...) {
return init{ field = expr; ... }
}
TypeName(param &ParamType, ...) {
return init{ field = expr; ... }
}
TypeName(param ParamType, ...) => init{ field = expr; ... }
TypeName(param &ParamType, ...) => init{ field = expr; ... }
TypeName<T>(param T Type, ...) { return init{ field = expr; ... } }
TypeName<T, n>(param Container<T Type, n @concepts$Int>, ...) { return init{ field = expr; ... } }
Constructors use the same package-scope declaration shapes as other functions, except that the written type name is the return type. A struct constructor’s body constructs the value with init{ ... }; an enum constructor’s body returns a member, and a variant constructor’s body returns a case (types.md §3.1):
EnumName() => EnumName.member
VariantName(payload PayloadType) => VariantName.case(payload)
A constructor for a parameterized type has no <> header; its name carries the applied return type (TypeName<T>, TypeName<T, n>), whose <...> holds bare references to the parameters. It introduces those type and number parameters inline within its value parameters — directly (param T Type) or inside a parameter’s nested type (param Container<T Type, n @concepts$Int>) — in which case they are inferred from the value arguments; or it accepts a type or compile-time integer as an ordinary value parameter of concept type Type or @concepts$Int (passed explicitly). A constructor is always called by its bare name and MUST NOT carry a <> list at the call. See types.md §3.10 and generics.md §5.
A constructor may be named — carry a .name suffix on the type — in either the positional or the field form (§3.4), giving a type several named construction paths (see types.md §3.4). It is declared and called by that qualified name and yields the base type. Its name MUST differ from every member and case of the type (see types.md §3.4):
TypeName.zeros() => init{ field = expr; ... }
TypeName.fromParts(param ParamType, ...) { return init{ field = expr; ... } }
o TypeName.zeros()
p TypeName.fromParts(arg)
3.4 Field constructors
A field constructor is declared only on a struct or #struct (types.md §3.3).
TypeName{
fieldA FieldType;
fieldB FieldType(args...);
fieldC FieldType = expr;
...
} {
return init{fieldA; fieldB; fieldC;}
}
TypeName{
fieldA FieldType;
fieldB FieldType(args...);
fieldC FieldType = expr;
...
} => init{fieldA; fieldB; fieldC;}
A field-constructor header is a { } body, so its entries are ;-terminated and always trailing (lexical.md §6.1). Each field entry uses either the bare required-field form field FieldType or an initialized storage form such as field FieldType = expr. The bare form declares a required constructor input that the call site must supply, not a standalone symbol declaration with its own storage.
Field-constructor call sites may use explicit or implicit field names:
name TypeName{fieldA = expr; fieldB = expr;}
name TypeName{fieldA; fieldB;}
A field-constructor call may omit any field whose constructor entry includes an initializer.
Story:
stories/syntax.md— “One shape, and everywhere it turned up”.
3.5 Implicit constructors
implicit TypeName(param ParamType) {
return init{ field = expr; ... }
}
implicit TypeName(param ParamType) => init{ field = expr; ... }
Implicit constructors use the implicit modifier and are written only in positional form with exactly one parameter.
Illegal forms:
implicit TypeName() { ... } // ILLEGAL: exactly one parameter is required
implicit TypeName(a A, b B) { ... } // ILLEGAL: implicit constructors are single-parameter only
implicit TypeName{field FieldType;} { ... } // ILLEGAL: field-constructor form is not allowed
3.6 Subscript definitions
(this SubjectType)[param ParamType, ...] => placeExpr
Subscript definitions have no explicit return type annotation. The body MUST be a place expression. If the body is not a place expression, the declaration is a compile-time error.
A subscript definition may declare any number of comma-separated parameters inside []. The surface form is not limited to one or two parameters.
The following forms are not part of the grammar:
ReturnType (this SubjectType)[index ParamType] => expr
[] is not a general function call form. A subscript definition always declares a place projection that references existing storage within the subject.
Story:
stories/syntax.md— “Two orders, and the order we had already turned down”.
3.7 init{ }
init{
field = expr;
otherField;
...
}
init{ } is a { } body, so its fields are ;-terminated and always trailing (lexical.md §6.1). A bare field name inside init{ } is shorthand for fieldName = fieldName.
3.8 Lambda literals and lambda-variable declarations
A lambda literal is a function declaration with the name removed. It writes its own return type, parameter types, abort type, and mut, exactly like a named function:
ReturnType() { body }
ReturnType(param ParamType, ...) { body }
ReturnType(param &ParamType, ...) { body }
ReturnType() => expr
ReturnType(param ParamType, ...) => expr
ReturnType?AbortType(param ParamType, ...) { body }
ReturnType(this SubjectType) { body }
ReturnType(this SubjectType) mut { body }
ReturnType(this SubjectType, param ParamType, ...) { body }
ReturnType(this SubjectType, param ParamType, ...) mut { body }
ReturnType(this SubjectType, param ParamType, ...) => expr
ReturnType(this SubjectType, param ParamType, ...) mut => expr
A lambda literal omits only the function name. this is legal only in the first parameter position. mut is legal only when the first parameter is this. Parameters and the subject carry the same passing modes as a named verb (§3.1–§3.2).
Examples:
element!onClick(Unit(eventData EventData) {
...
return Unit();
});
element!onClick(Unit(this Element, data EventData) mut {
...
return Unit();
});
A lambda-variable declaration binds a lambda literal to a symbol. The shorthand writes the symbol name in front of the lambda literal and drops the separate = literal, mirroring the constructor-call instantiation form name VarType(args, ...):
name ReturnType(param ParamType, ...) { body }
name ReturnType(param ParamType, ...) => expr
name ReturnType?AbortType(param ParamType, ...) { body }
name ReturnType(this SubjectType, param ParamType, ...) mut { body }
The shorthand expands to a symbol declaration whose type is the function type (§2.13) and whose value is the lambda literal:
callback Unit[this Player] mut = Unit(this Player) mut {
this.shooting = Bool(false);
return Unit();
}
callback Unit(this Player) mut { // shorthand for the line above
this.shooting = Bool(false);
return Unit();
}
Story:
stories/syntax.md— “Two orders, and the order we had already turned down”.
A package-scope lambda-variable may end in an export suffix, after its body, naming the C symbol it becomes (packages.md §8.2):
name ReturnType(param ParamType, ...) { body } export "cName"
name ReturnType(this SubjectType, param ParamType, ...) mut { body } export "cName"
name ReturnType(param ParamType, ...) => expr export "cName"
3.9 Operator definitions
ReturnType ~(value ParamType) { body }
ReturnType *(leftParam LeftType, rightParam RightType) { body }
ReturnType /(leftParam LeftType, rightParam RightType) { body }
ReturnType +(leftParam LeftType, rightParam RightType) { body }
Bool ==(leftParam LeftType, rightParam RightType) { body }
Bool <(leftParam LeftType, rightParam RightType) { body }
ReturnType and(leftParam LeftType, rightParam RightType) { body }
ReturnType or(leftParam LeftType, rightParam RightType) { body }
Operator definitions are package-scope verb declarations whose names are operator tokens. They never declare this, so they are not methods and cannot use mut.
3.10 Return statements
return expr
See functions.md §3.5 for return-path requirements.
3.11 Foreign verbs
ReturnType name(param ParamType, ...) foreign "cSymbol"
ReturnType?AbortType name(param ParamType, ...) foreign "cSymbol"
ReturnType name(this SubjectType, param ParamType, ...) foreign "cSymbol"
ReturnType?AbortType name(this SubjectType, param ParamType, ...) foreign "cSymbol"
ReturnType name(this SubjectType, param ParamType, ...) mut foreign "cSymbol"
ReturnType?AbortType name(this SubjectType, param ParamType, ...) mut foreign "cSymbol"
A foreign verb writes foreign and one string literal without interpolation where another verb writes its body, after mut when the verb has it. The literal is the C function’s symbol.
@primitives$I64 now(this Clock) foreign "zane_now" { ... } // ILLEGAL: a foreign verb has no body
@primitives$I64 now(this Clock) => foreign "zane_now"; // ILLEGAL: `foreign` is not an expression
See also:
ffi.md§3 for foreign verb semantics.
4. Calls and Function Values
4.1 Function calls
name(args...)
packageName$name(args...)
4.2 Method calls
subject:method(args...)
subject!method(args...)
subject:packageName$method(args...)
subject!packageName$method(args...)
subject!@namespace$method(args...)
To call a method that an intrinsic namespace supplies for a subject of any type, a program qualifies the method with that namespace, as with the worker intrinsics (§5.1).
4.3 Callables are call-only
Methods, functions, and operators have no value form. A package-scope callable name may appear only in call position; it cannot be written as a bare value.
packageName$functionName(args...) // legal: call position
packageName$functionName // ILLEGAL: callables cannot be referenced as values
+; // ILLEGAL: operators cannot be referenced as values
To obtain a function value, declare a lambda-variable (§3.8). A lambda-variable is an ordinary symbol with a single function type, so it carries no overload set.
4.4 spawn
spawn functionName(args...)
spawn subject:methodName(args...)
spawn subject!methodName(args...)
spawn functionName(args...) ? binder { ... }
spawn subject:methodName(args...) ? binder { ... }
spawn subject!methodName(args...) ?? fallbackExpr
name VarType = spawn functionName(args...)
name VarType = spawn subject:methodName(args...) ? binder { ... }
name VarType = spawn subject!methodName(args...) ? binder { ... }
name VarType = spawn functionName(args...) ?? fallbackExpr
spawn is legal only on function-call and method-call expressions. Package-qualified function and method calls use their ordinary forms (§4.1–§4.2). An abortable call may carry a ? or ?? handler, whether its result is bound or ignored.
4.5 Subscript expressions
placeExpr[argExpr, ...]
[] is legal only when the subject type defines a subscript declaration. A subscript expression is a place projection, not a general function call, so it is legal only when its base is a place expression.
Examples:
list[i];
matrix[row, col];
tensor[x, y, z];
CustomList()[1] is not a valid place expression because the base is a temporary.
4.6 Parenthesized expressions
(expr)
Parentheses group an inner expression explicitly. See operators.md §3 for precedence.
Example:
number Int = (3 + 2) * 2;
4.7 match expressions
A match expression names one or more scrutinees — a ,-separated list in ( ) — then a { } block of arms. Each arm is an optional binder, a case selector, and a body. A match may appear anywhere an expression is legal and may carry a trailing ? (or ??) handler when its arms are abortable.
match (scrutinee) { arm arm ... }
match (scrutinee, scrutinee) { arm arm ... }
name VarType = match (scrutinee) { arm arm ... }
name VarType = match (scrutinee) { arm arm ... } ? binder { ... }
return match (scrutinee) { arm arm ... }
functionName(match (scrutinee) { arm arm ... })
The parentheses delimit the list and build no value from it: the scrutinees are independent values matched jointly on their tags (adt.md §5.6). They also end the last scrutinee before the arms’ {, which an expression ending in a brace of its own would otherwise absorb.
An arm is [binder] selector, with one [binder] selector per scrutinee position, ,-separated in order, followed by its body. A selector is a single case name or a [ ] list of ,-separated case names, written bare (rooted at that scrutinee’s type). The body is either => expr, which a ; terminates, or a { } block, whose closing brace ends the arm with no ; — the rule a statement follows (lexical.md §6.3). An => expr arm whose expression itself ends in a } still takes its ;.
result String = match (e) {
x strLit => x;
[intLit, floatLit] => "number";
b op => render(b);
// every case must be covered — see adt.md §5
}
cost Int = match (mode) {
fast => Int(1);
slow {
console!print("taking the slow path");
return Int(10);
}
}
// several scrutinees: one selector per position
newState State = match (state, event) {
[idle, running], keyPress => State.running;
running, timeout => State.idle;
// every combination must be covered — see adt.md §5.6
}
See also:
adt.md§5 formatchsemantics. Story:stories/adt.md— “Amatchparenthesizes its scrutinees, and a block arm ends on its brace”.
4.8 Block arguments and trailing arguments
A call may carry any number of block arguments, one for each @concepts$Block parameter the callee declares. Each is an ordinary argument written in argument position.
repeatTwice({ console!print("hi"); });
A call’s last argument may instead trail: it is written after the closing ) rather than inside it, and the ) is elided. Only a { } argument may trail — a block or a map literal (§2.10). An array literal is always written inside the parentheses. At most one argument trails per call.
repeatTwice() {
console!print("hi");
}
ran Bool = if(ready) {
start();
}
A trailing argument MUST be the last element of its statement: the } that closes it ends the statement, so neither a ; nor anything that would continue the call may come after it (§6.3 of lexical.md). The brace ends the call and the statement together, a job the elided ) and a ; would otherwise do in two marks.
A call that supplies more than one block writes the earlier blocks as ordinary arguments and may still trail the last. Given a verb declaring two @concepts$Block parameters:
attempt({ prepare(); }) {
handle();
}
The trailing and parenthesized forms are the same call. The ) moves to where the statement ends:
if(true) {
console!print("hi");
}
if(true, { console!print("hi"); }); // the same call, written in full
A block takes no parameters, is never named, and yields nothing (control-flow.md §2.4).
f({ x; }, { y; }); // legal: two block arguments, neither trailing
f({ x; }) { y; } // legal: the same call with the last one trailing
f({ x; }) { y; } () // ILLEGAL: the `}` already ended the statement
g();
{
console!print("oops"); // ILLEGAL: a `{ }` may not open a statement (§6.3.1 of lexical.md)
}
Story:
stories/lexical.md— “Statements end in;so a trailing brace can end one”. Story:stories/syntax.md— “Callback lists stay inside the parentheses” gives the reason a[ ]does not trail.
An argument list with nothing left inside it still writes its ( ); the trailing form elides only the ), never the whole list:
do() {
tmp Int(9);
use(tmp);
}
A constructor call whose ( ) would be left empty is the exception: its block argument stays inside the parentheses. TypeName() { body } is a lambda literal returning TypeName (§3.8), and in statement position also a positional constructor declaration with a block body (§3.3), so a call to a constructor whose only argument is a block writes it in full. A constructor call with anything else inside its ( ) trails its last argument like any other call. A lower-case callee names no type, so do() { ... } has no second reading.
worker Thread(name) { // legal: the block trails a constructor call
poll();
}
worker Thread(name, { poll(); }); // the same call, written in full
pool Threads({ poll(); }); // a constructor call whose only argument is a block
Story:
stories/syntax.md— “A constructor call with an empty list keeps its block inside”.
4.9 Continuing a value that closes on a }
A field-constructor call (§3.4), an init{ } (§3.7), a map literal (§2.10), and a match expression (§4.7) each close on a }. Such a value takes a ? or ?? handler and an operator written directly after its brace, and each of them but the map literal takes a field access . and a method call : or ! there too. A call ( ) or a subscript [ ] is written on the parenthesized value (§4.6), because both of those brackets can open a statement (lexical.md §6.3). A map literal’s field access and method calls are written on the parenthesized literal as well: a value they continue may stand first in its statement, and a map literal there would open the statement with a { (lexical.md §6.3.1).
x Int = Vector2{x = 0; y = 0;}.x;
area Int = Rect{w = 2; h = 3;}:area();
wide Bool = Rect{w = 2; h = 3;}.w > 1;
run Int = (match (mode) { fast => quick; slow => careful; })(input);
run Int = match (mode) { fast => quick; slow => careful; }(input); // ILLEGAL: a call needs the whole match parenthesized
n Int = ({ "a", 1; "b", 2; }):size();
n Int = { "a", 1; "b", 2; }:size(); // ILLEGAL: a method call needs the map literal parenthesized
A trailing argument closes its call on a } as well, and that brace ends the statement, so nothing continues the call (§4.8).
Story:
stories/syntax.md— “A value closed by a brace takes.,:,!,?and??”.
4.10 comptime
comptime functionName(args...)
comptime subject:methodName(args...)
comptime functionName(args...) ? binder { ... }
comptime subject:methodName(args...) ?? fallbackExpr
name VarType = comptime functionName(args...)
name VarType = comptime subject:methodName(args...) ? binder { ... }
name VarType(comptime functionName(args...))
comptime is legal only on function-call and : method-call expressions; a ! call is never marked. A marked call stands wherever an expression may. An abortable call may carry a ? or ?? handler after the marked call. See effects.md §5.6.
comptime list!sort(); // ILLEGAL: a `comptime` call writes no subject
5. Control Flow
Zane has no control-flow grammar. Branching, repetition, and exiting are all calls, declared by the core package (see control-flow.md §3); the first two are ordinary calls with block arguments (§4.8), and the exit is an ordinary call over the intrinsic below.
5.1 Control-flow intrinsics
@controlflow$branch(condition @primitives$Bool, body @concepts$Block)
@controlflow$repeat(count @primitives$I64, body @concepts$Block)
@controlflow$exitFromCall()
@controlflow$work(this S Type, step R Type[this S] mut) mut
@controlflow$register(this S Type, source @primitives$EventSource, step R Type[this S] mut) mut
The first two take storage primitives rather than fundamental types, and the third takes nothing. The worker pair are mut methods of a subject of any type, which a program calls as subject!@controlflow$work(step); they take a function value over the subject and, for register, a primitive event source. None of the five depends on any package (control-flow.md §4.1), and any package may call them.
5.2 Writing an exit
@controlflow$exitFromCall() ends the run of the block that a call to the verb holding it is written in, so an exit is written by calling a verb built on it — core supplies guard — inside a block:
i!to(count) {
guard(shouldSkip);
work();
}
The intrinsic itself appears in the body of such a verb, not at the point an exit is wanted; written in a verb’s own body it makes that verb an exiting one (control-flow.md §4.2). A call to an exiting verb written outside every block argument, such as directly in a verb’s body, is a compile-time error (control-flow.md §2.3).
6. Error Handling
6.1 Abortable return types
ReturnType?AbortType
6.2 ? handlers
expr ? binder { ... }
Every path inside the handler must end with one of:
resolve expr
return expr
abort expr
6.3 ?? shorthand
expr ?? fallbackExpr
7. Operators and Keywords
7.1 Operators
~, *, /, +, -, <, >, <=, >=, ==, ~=, and, or
and and or are written between their operands like every other binary operator:
a == b and c == d // legal
and(a, b) // ILLEGAL: an operator is written in operator position
See also:
operators.md§3 for precedence.lexical.md§4.4 for the reserved words.
7.2 Control-flow keywords
Zane has none.
if, elif, else, and guard are not keywords. They are core declarations called like any other verb (see control-flow.md §3). guard in particular is an ordinary verb over the exit intrinsic (§5.2), not grammar. Counted repetition is a method call on the counter rather than a named construct — i!to(end) (control-flow.md §3.4).
7.3 Comments
// single-line comment
/// doc comment
Zane has no block-comment syntax. // starts a single-line comment. /// starts a documentation comment line. Adjacent /// lines are merged into one documentation block.
Story:
stories/syntax.md— “Every comment line carries its own marker”.
8. Packages
8.1 Package member syntax
packageName$member
8.2 Package declarations
package packageName
package packageName<Param Type, n @concepts$Int, ...>
The second form declares a parameterized library package, and every source file of the package repeats the same list (packages.md §2.4, §2.6).
8.3 Export lines
A plugin or test package may carry export lines beside its imports, each naming a library package whose exported lambdas the build gives C symbols (packages.md §8.3):
export packageName
export packageName<TypeArgument, ...>