Syntax Reference
Reference (complete). Learning path: docs/README.md → Language overview. New pages distill this file and link back; this file stays the grammar source of truth.
Lexical Structure
Section titled “Lexical Structure”Comments
Section titled “Comments”// Line comment/* Block comment can span multiple lines */Identifiers
Section titled “Identifiers”Identifiers start with a letter or underscore, followed by letters, digits, or underscores:
name := "ZZ"_private := 42pascal_case := trueKeywords
Section titled “Keywords”| Keyword | Purpose |
|---|---|
import |
Module import |
as |
Import alias |
func |
Function declaration |
return |
Return from function |
if |
Conditional |
else |
Alternative branch |
while |
Loop |
match |
Pattern matching |
for |
Iteration |
in |
Range/array iteration |
struct |
Record type |
break |
Exit loop |
continue |
Skip iteration |
defer |
Defer execution to scope exit |
true / false |
Boolean literals |
Statement Terminator
Section titled “Statement Terminator”Statements end with a newline at bracket depth 0, or a semicolon:
x := 1y := 2
// Equivalent:x := 1; y := 2Newlines inside parentheses, brackets, or braces are not statement terminators:
result := add( 1, 2)Declarations
Section titled “Declarations”Short Declaration (Inferred Type)
Section titled “Short Declaration (Inferred Type)”x := 42 // intpi := 3.14 // floatname := "ZZ" // stralive := true // boolExplicit Declaration (Typed)
Section titled “Explicit Declaration (Typed)”x: int = 42pi: float = 3.14scores: [int] = [1, 2, 3]Shadowing and Assignment
Section titled “Shadowing and Assignment”Both declaration forms bind a new name scoped to the block they appear in. Inside a loop body or an inner block that means a declaration does not update an outer binding — it shadows it:
x := 0i := 0while i < 3 { x := x + 1 // warning: shadows the outer `x` println(x) // 1, 1, 1 — every pass reads the untouched outer 0 i = i + 1}println(x) // 0
while i < 6 { x = x + 1 // `=` updates the outer binding i = i + 1}println(x) // 3zz check warns when a declaration’s initializer reads the very binding it
shadows (x := x + 1, one, b := f(b)), because that shape is almost always a
mistyped assignment; it offers = as a fix when the declaration is neither
typed nor const. Shadowing with a fresh value (x := 5) is deliberate and
stays silent. Assignment to an inner declaration never reaches the outer one.
Type Aliases
Section titled “Type Aliases”type Tokens = [Token]type Pair<T> = (T, T)
toks: Tokens = ["a"]p: Pair<int> = (1, 2)Aliases erase at check time: uses resolve to the target type, so there
is no runtime cost and both engines behave identically. Generic aliases
take plain parameters and name their arguments at use sites
(Pair<int>), exactly like generic structs. type is contextual —
json.type(x) and variables named type keep working. Aliases export
across modules with pub type and import qualified
(shapes.Tokens) or selective (import shapes(Tokens)).
User Enums
Section titled “User Enums”enum Token { Eof, IntLit(int), Name(str),}
t := Token.IntLit(42) // construction is qualifiedmatch t { .Eof => "eof", // patterns name the variant short .IntLit(v) => "int", .Name(s) => s,}Enums erase to qualified objects at runtime, so construction, matching,
equality, and impl methods behave identically on both engines. Matches
are exhaustiveness-checked (missing variants report, or add a _ arm).
Variants hold at most one payload — use a tuple for more
(Pair((int, int))). enum is contextual, like type. Enums export
across modules with pub enum and chain methods inline, including off
payload construction (Token.IntLit(1).add(2) fills the payload with
1, calls add with 2).
Generic enums take plain parameters and name their arguments at use
sites (Box<int>), exactly like generic structs:
enum Box<T> { V(T), E,}
b: Box<int> = Box.EMatch guards (n if n > 0 =>) accept the arm’s pattern bindings,
literals, and operator combinations — on both engines. Anything else
(calls, strings, field/index access) is a check-time error naming the
exact subexpression, so VM and native builds never diverge silently.
Outer variables and helper calls belong in the arm body:
match x { .some(n) => if n > limit && is_valid(n) { println("ok") } else { println("bad") }, .none => println("nothing"),}Functions
Section titled “Functions”Basic Function
Section titled “Basic Function”func add(a: int, b: int) -> int { return a + b}No Return Value
Section titled “No Return Value”func greet(name: str) { println("Hello, {name}")}Default Parameters
Section titled “Default Parameters”func greet(name: str, greeting: str = "Hello") { println("{greeting}, {name}")}
greet("Alice") // "Hello, Alice"greet("Alice", greeting: "Hi") // "Hi, Alice"Named Arguments
Section titled “Named Arguments”func create_user(name: str, age: int, active: bool) { // ...}
create_user("Alice", age: 30, active: true)Generics
Section titled “Generics”func identity<T>(x: T) -> T { return x}Closures
Section titled “Closures”double := |x: int| x * 2add := |a: int, b: int| a + bgreet := |name: str| println("Hello, {name}")
// Trailing comma is allowed after the last paramadd_tc := |a: int, b: int,| a + b
// Optional return type annotationtwice := |x: int| -> int { x * 2 }
// Zero-arg closurenoop := || { println("hi") }
// Multi-line closuresquare := |x: int| { x * x}
// Underscore-prefixed param names are regular names —// use plain names unless you want to signal "unused"route := |req| http.ok("ok")Dotted Names (Cross-Module)
Section titled “Dotted Names (Cross-Module)”func shapes.distance(p1: Point, p2: Point) -> float { // ... return 0.0}Control Flow
Section titled “Control Flow”If / Else
Section titled “If / Else”if age < 18 { println("minor")} else { println("adult")}
// Single-expression (no braces needed for short if)if x > 0 { x } else { -x }If Let (Pattern Binding)
Section titled “If Let (Pattern Binding)”x := .some(5)if let .some(n) = x { println("got {n}")} else { println("nothing")}While Loop
Section titled “While Loop”i := 0while i < 10 { println("{i}") i = i + 1}For Loop (Range)
Section titled “For Loop (Range)”for i in 0..5 { println("{i}")}
// With stepfor i in range(0, 10, 2) { println("{i}")}For Loop (Array)
Section titled “For Loop (Array)”for name in ["Alice", "Bob", "Charlie"] { println("Hello, {name}")}Break and Continue
Section titled “Break and Continue”for i in 0..100 { if i == 5 { break } if i % 2 == 0 { continue } println("{i}")}Executes when the enclosing scope exits:
func process() { println("start") defer println("cleanup") println("done") // Prints: start, done, cleanup}Expressions
Section titled “Expressions”Arithmetic
Section titled “Arithmetic”1 + 2 // 310 - 3 // 73 * 4 // 1210 / 3 // 3 (integer division)10 % 3 // 1 (remainder)2 ** 10 // 1024 (power, right-associative)Signed integer overflow on +, -, * wraps two’s-complement
(9223372036854775807 + 1 is -9223372036854775808) on both engines —
it never traps. Guard manually at the boundary when wrapping would
corrupt the result (counters, timestamps, money math); the toml
package’s exact i64::MIN/MAX checks are the reference pattern.
Integer division by zero (including literal 1 / 0, which fails at
check time) and INT64_MIN / -1 are runtime errors, not wraps.
Comparison and Logic
Section titled “Comparison and Logic”1 < 2 // true1 == 1 // true1 != 2 // truetrue && false // falsetrue || false // true!true // falseBitwise (int-only)
Section titled “Bitwise (int-only)”6 & 3 // 2 (AND)6 | 3 // 7 (OR)6 ^ 3 // 5 (XOR)~6 // -7 (NOT)1 << 10 // 1024 (shift left)1024 >> 3 // 128 (shift right, arithmetic)Precedence (tightest first): ~ > + - > << >> > & >
^ > | > comparison (<, ==, …) > && > ||. So
flags & mask == expected parses as (flags & mask) == expected,
and a + b << c as (a + b) << c.
Both operands (and ~’s operand) must be int — floats, bools,
and strings are type errors. Shifts mask the count to & 63
(1 << 64 is 1); a negative shift count is a runtime error.
>> on negative values shifts arithmetically (sign-extending).
String Interpolation
Section titled “String Interpolation”name := "World"println("Hello, {name}!")
// Format specspi := 3.14159println("pi = {pi:.2f}") // 3.14
n := 255println("hex = {n:x}") // ffprintln("HEX = {n:X}") // FFprintln("oct = {n:o}") // 377println("bin = {n:b}") // 11111111println("dec = {n:d}") // 255Spaces and tabs right after { are insignificant, so { n} is the same
interpolation as {n} (a trailing space was always fine):
n := 5pi := 3.14159println("n is { n}") // n is 5println("pi = { pi:.2f}") // pi = 3.14Literal braces use doubled escapes — {{ renders {, and a }}
that closes a {{ pair renders } — in both "..." and """..."""
strings. This is the preferred way to emit CSS or template syntax:
println("{{name}}") // {name} (no interpolation)println("{{{name}}}") // {World} (literal braces + value)println(".a{{color:red}}") // .a{color:red}
// Multiline works the same way:css := """ .a{{color:red}} """An unmatched }} (no preceding {{ in the same string) stays two
literal braces, so nested JSON needs no escaping at all:
println("{\"a\": {}}") // {"a": {}} — both closes preserved\{ / \} remain accepted for backwards compatibility and mean
the same as {{ / a matched }}, but prefer the doubled form.
Raw strings
Section titled “Raw strings”Backtick strings are fully literal — no interpolation, no \
escapes, no brace collapsing. Braces, quotes, and backslashes stay
exactly as typed, which makes them the right home for JSON, regex,
and Windows paths:
j := json.parse(`{"Club": {"g": 3}}`)pat := `^[0-9a-f]{8}$` // matches 8 hex digits, no doublingwin := `C:\new\test`A doubled backtick is the only escape, yielding one literal
backtick (same doubling philosophy as {{ / }}):
println(`a``b`) // a`bTwo limits to know: inside triple-backtick strings a lone or
doubled backtick is plain content — only closes — so a triple-backtick fence itself cannot appear inside one (split the string or use single-line raw there). And `` ``` means one
backtick in single-line raw but two in triple raw: each form keeps
exactly one way to spell a literal backtick.
Triple-backtick strings span lines and dedent exactly like
"""...""", without any interpolation or escapes:
q := ``` {"x": 1} {"y": [1, 2]} """Brace-heavy payloads with no interpolation belong in backticks;
keep {{ / }} for literal braces inside interpolated strings.
What {...} expands
Section titled “What {...} expands”Both "..." and """...""" strings open an interpolation when { is
followed by an identifier, a digit, or (:
println("{1 + 2}") // 3println("{(a)}") // value of (a){{, {}, and JSON-like {"key" stay literal text in both forms —
double the braces for a literal {:
println("{{1 + 2}}") // {1 + 2} (no interpolation)Regular-expression quantifiers inside "..." must still be
doubled like in Python f-strings or Rust format! — or sidestep
the issue with a raw string:
pat := "^[0-9a-f]{{8}}$" // matches 8 hex digitspat := `^[0-9a-f]{8}$` // same, preferredWhen a string DOES interpolate elsewhere, a bare { that cannot expand
(e.g. "{x} of {!done}") warns at check time naming the exact rule.
Array Literals
Section titled “Array Literals”nums := [1, 2, 3]mixed := [1, "two", true]empty := []Dict Literals
Section titled “Dict Literals”ages := {"Alice": 30, "Bob": 25}empty := {}Tuple Literals and Destructuring
Section titled “Tuple Literals and Destructuring”t := (7, "seven")t[0] // 7 (integer-literal index, checked at compile time)t[1] // "seven"t[-1] // "seven" (negative counts from the end, like arrays)len(t) // 2
// Destructuring — parens or bare form (identical meaning):(a, b) := t // a = 7, b = "seven"c, d := t // same; `_` skips: `_, e := t`Dynamic indices (t[i]) are a compile error — destructure instead.
Out-of-range literal indices are also caught at compile time.
Tuples share the array representation: t[0] = 99 writes in
place, and behavior is identical on the VM and native backends.
Indexing and Slicing
Section titled “Indexing and Slicing”arr := [10, 20, 30, 40]arr[0] // 10arr[-1] // 40 (negative index from end)arr[1:3] // [20, 30]arr[:2] // [10, 20]arr[2:] // [30, 40]arr[:] // [10, 20, 30, 40]
s := "hello"s[1] // "e"s[1:3] // "el"Index Assignment
Section titled “Index Assignment”arr := [1, 2, 3]arr[0] = 99 // [99, 2, 3]
dict := {"a": 1}dict["b"] = 2 // {"a": 1, "b": 2}
struct Box { items: [int] }b := Box{ items: [1, 2, 3] }b.items[1] = 99 // b.items == [1, 99, 3]Compound Assignment
Section titled “Compound Assignment”x OP= y is equivalent to x = x OP y with the receiver evaluated
exactly once (so arr[i()] += f() calls i() then f(), once each —
unlike textual expansion, which would evaluate i() twice):
x := 10x += 1 // 11, like x = x + 1x -= 2 // 9x *= 3 // 27x /= 4 // 6 (integer division)x %= 4 // 2n := 2n **= 10 // 1024
p.x += 5 // struct fields (same targets as `=`)arr[0] *= 2 // indices
// Bitwise forms work too:flags := 0flags |= 4flags &= 7flags ^= 1flags <<= 2flags >>= 1Type rules are exactly the binary operator’s: x += 1.5 is accepted
precisely when x = x + 1.5 is. Cannot be chained (x += y += z
is an error — split it into two statements).
Value Semantics
Section titled “Value Semantics”Function parameters are values (copies) from the programmer’s perspective — a function can never mutate its caller’s variables:
struct Counter { n: int }
func bump(c: Counter) -> int { c.n += 100 // mutates only the local copy return c.n}
c := Counter{ n: 10 }bump(c) // 110c.n // still 10There are no reference parameters, no borrows, and no borrow checker.
value semantics != mandatory physical memcpy: the compiler and
runtime may eliminate physical copies and reuse storage internally
(copy-on-write, in-place slot operations) whenever provably safe, but
such optimizations are never observable — no alias can witness an
intermediate mutation. Correctness always wins over optimization.
Ranges
Section titled “Ranges”0..5 // 0, 1, 2, 3, 4range(0, 10, 2) // 0, 2, 4, 6, 8List Comprehensions
Section titled “List Comprehensions”squares := [x ** 2 for x in range(0, 6)]// [0, 1, 4, 9, 16, 25]
evens := [x for x in range(21) if x % 2 == 0]
doubled := [x * 2 for x in [1, 2, 3, 4, 5] if x < 4]// [4, 6]Elvis Operator (??)
Section titled “Elvis Operator (??)”Provides a fallback when a value is .none:
x := int("not_a_number") ?? 0 // 0name := .some("Alice")greeting := name ?? "stranger" // "Alice"
// Works with non-variant values (pass-through)val := 42 ?? 0 // 42Pipeline Operator (|>)
Section titled “Pipeline Operator (|>)”Passes the left value as the first argument to the right function:
func inc(n: int) -> int { return n + 1 }func dbl(n: int) -> int { return n * 2 }
5 |> inc |> dbl // dbl(inc(5)) = dbl(6) = 12
// Multi-line pipelinesresult := " Hello World " |> str.trim() |> str.to_upper()// "HELLO WORLD"Field Access
Section titled “Field Access”struct Point { x: int, y: int }p := Point{ x: 1, y: 2 }p.x // 1p.y // 2Struct Initialization
Section titled “Struct Initialization”struct Point { x: int, y: int }
p1 := Point{ x: 1, y: 2 } // standardp2 := Point { x: 1, y: 2 } // spaces around braces OKStruct Mutation
Section titled “Struct Mutation”p := Point{ x: 1, y: 2 }p.x = 10println(p.x) // 10Nested Field Access and Mutation
Section titled “Nested Field Access and Mutation”struct Point { x: int, y: int }struct Rect { p: Point, w: int }
r := Rect{ p: Point{ x: 1, y: 2 }, w: 3 }r.p.x = 9println(r.p.x) // 9Struct Embedding (Anonymous Fields)
Section titled “Struct Embedding (Anonymous Fields)”A struct can embed another struct by naming the type without a field name. The embedded struct’s fields and methods are promoted: they resolve on the outer struct as if declared there (transitively; direct members win).
struct Base { id: int, name: str }struct User { Base, age: int } // embeds Base
impl Base { func area(self) -> int { return self.id * 2 }}
zaid := User{ id: 1, name: "Zaid Ajo", age: 19 } // flat init nests into Baseprintln(zaid.id) // 1 — promoted, same as zaid.Base.idprintln(zaid.area()) // 2 — promoted method, receiver is the embedded Basezaid.id = 99 // writes through to zaid.Base.idExplicit (User{ Base: Base{ id: 1, name: "Z" }, age: 19 }) and shorthand
(User{ Base{ id: 1, name: "Z" }, age: 19 }) inits mean the same thing.
Mixing an explicit embedded value with flattened leaves of the same subtree
is rejected as ambiguous.
Generic Structs
Section titled “Generic Structs”Structs take type parameters (struct Box<T> { v: T }). Construction
infers the arguments (Box{ v: 1 } is Box<int>), exactly like generic
function calls — no turbofish needed. Annotate when you want to pin it
(x: Box<int> = Box{ v: 1 }):
struct Box<T> { v: T }
impl Box<T> { func get(self) -> T { return self.v }}
b := Box{ v: 42 } // Box<int>println(b.get()) // 42s := Box{ v: "hi" } // Box<str>
struct Pair<A, B> { a: A, b: B }p := Pair{ a: 1, b: "s" } // Pair<int, str>Rules:
- Use sites name their arguments (
Box<int>); a bareBoxfor a generic struct is an error, as is the wrong count (Pair<int>). Box<int>andBox<str>are distinct types — assigning one to the other is a type mismatch.impl Box<T>scopesTover every method; the receiver unifies the arguments at each call. A plainimpl Boxfor a generic struct is an error, and a method parameter may not shadow an impl parameter.- Type arguments erase at runtime: values store field data only, so generic code runs identically to hand-monomorphized code (same opcodes, same generated C — verified by test, not just claimed). Value semantics hold unchanged: functions receive copies regardless of type arguments.
Method Call Syntax
Section titled “Method Call Syntax”Method calls desugar to function calls with the receiver as the first argument:
struct Point { x: int, y: int }func dist(p: Point) -> int { return p.x + p.y }
p := Point{ x: 3, y: 4 }dist(p) // function callp.dist() // method call equivalentResolution order for value.name(...):
- the receiver’s own
implmethod —impl W { func get(self) }registersW.get, andw.get()reaches it even when a freeget(w)exists; - a free function
name, with the receiver as the first argument (p.dist()≡dist(p)), when the receiver’s type has no such method; - the receiver-typed stdlib namespace (
str.,vec.,dict.,option., …).
Both forms stay reachable, so a same-named impl method and free function can
coexist: w.get() calls W.get, get(w) calls the free function.
Try Operator (?)
Section titled “Try Operator (?)”Unwraps a variant, propagating .none/.err upward on failure:
func process(input: str) -> Option<int> { val := int(input)?; return .some(val + 1) }Note: ? joins with the next line. Use match for branching across lines:
func parse_age(input: str) { match int(input) { .some(val) => println("age: {val}"), .none => println("not a number"), }}Variant Constructors
Section titled “Variant Constructors”.ok(42) // Result variant.err("boom") // Result variant.some("hello") // Option variant.none // Option variant.Point{ x: 1, y: 2 } // Struct variantPattern Matching
Section titled “Pattern Matching”Basic Match
Section titled “Basic Match”x := .some(5)match x { .some(n) => println("got {n}"), .none => println("nothing"),}Separate arms with a comma or a newline — a missing separator names
itself (expected , or newline between match arms) and zz fix
inserts the comma.
Literal Patterns
Section titled “Literal Patterns”match 42 { 0 => "zero", 1 => "one", _ => "other",}Binding Patterns
Section titled “Binding Patterns”match .ok(5) { .ok(n) => n * 2, .err(e) => 0,}.ok, .err, and .some always carry a payload, so their patterns
require an argument — a bare .ok / .err is a type error. Use _
to ignore the payload (.ok(_), .err(e)). Only payloadless
variants (.none) match bare. zz fix rewrites bare patterns
automatically.
Must-use Results
Section titled “Must-use Results”A Result or Option used as a bare statement is a warning, not an
error — the value (and any error) is silently discarded:
fs.write(path, data) // warning: unused `Result`Handle it (match), propagate it (?), or ignore it explicitly
(_ := fs.write(path, data)). Block tails are values, not discards,
so -> Result function bodies never warn. Loop-body tails and
defer expressions do warn — their values are discarded too.
Type mismatches name the fix direction: argument errors name the
expected parameter (parameter `greeting` expects `str` ), and
annotation errors suggest the corrected annotation.
Dead Arms
Section titled “Dead Arms”Arms after a catch-all arm (_ or a bare binding) can never run and
warn as unreachable. A guarded catch-all (_ if cond =>) does not
count — the guard may fail and fall through.
Nested Patterns
Section titled “Nested Patterns”match .some(.ok(2)) { .some(.ok(n)) => n, _ => 0,}Wildcard Pattern
Section titled “Wildcard Pattern”match x { .some(_) => println("has value"), _ => println("nothing"),}Statement Arms
Section titled “Statement Arms”Arms accept statements as well as expressions — assignment, :=
declarations, return, defer — wrapped as if braced. break and
continue keep their expression form so divergence checking is
unchanged.
y := 0match x { .some(v) => y = v, .none => y = 0 - 1,}Modules and Imports
Section titled “Modules and Imports”Import Statement
Section titled “Import Statement”import std.mathimport std.strUsing Imports
Section titled “Using Imports”import std.mathprintln(math.abs(-5)) // 5
import std.strprintln(str.to_upper("hello")) // "HELLO"Package Imports
Section titled “Package Imports”Inside a project (a directory tree with zz.toml), the package name
maps to src/ from any file — so tests/ can import src/ modules
without fragile ../src/... paths:
import app.math // <project-root>/src/math.zz, used as math.*import app.math(add as f) // selective: bare `f`import app.utils.string_helpers as shimport app // <project-root>/src/main.zz, used as app.*Rules: precedence is std > package > registry dependency >
relative file; - and _ spellings agree (my-app ⇔ my_app).
One file may be imported under several namespaces at once
(import tui.keys in one module, import tui.keys as tkeys in
another): the first binding wins as canonical and alias references
rewrite through it, so values and types keep one identity. Two
different files under one namespace stay an error — alias one side.
Blocks as Expressions
Section titled “Blocks as Expressions”Blocks evaluate to their last expression (closures and block expressions
keep this; named func bodies return only through return):
result := { x := 10 y := 20 x + y // result = 30}Unit Type
Section titled “Unit Type”Functions without a return type return unit:
func do_nothing() { // returns unit implicitly (no `return`, no value)}
func double(x: int) -> int { return x * 2 // named functions need an explicit `return`}