Patterns & Common Errors
Common Patterns
Section titled “Common Patterns”Program Template
Section titled “Program Template”function main() returns ExitCode print("Hello, world!\n") return 0end 'main'Loop With an Early Exit
Section titled “Loop With an Early Exit”function main() returns ExitCode var i = 0 as Count while true 'forever' if i >= 3 'done' break end 'done'
print("{i}\n") i = i + 1 end 'forever'
return 0end 'main'Iterating With an Index
Section titled “Iterating With an Index”function main() returns ExitCode let names = ["ada", "alan", "grace"] for (iter, name) in names.withIterator() 'each' print("{iter.index()}: {name}\n") end 'each'
return 0end 'main'Recursion
Section titled “Recursion”typealias Operand = int(i64.min to i64.max)
function factorial(n Operand) returns Operand if n <= 1 'base' return 1 end 'base'
return n * factorial(n - 1)end 'factorial'
function main() returns ExitCode print("{factorial(5)}\n") // 120 return 0end 'main'Building a String
Section titled “Building a String”String has no +; interpolate, or append in place:
function main() returns ExitCode var csv = "" for n in 1 to 3 'each' csv.append("{n},") end 'each'
print("{csv}\n") // 1,2,3, return 0end 'main'A Lookup With a Fallback
Section titled “A Lookup With a Fallback”typealias Age = int(0 to 150)typealias Ages = Map with (String, Age)
function main() returns ExitCode let ages = Ages.create() ages.upsert("ada", value: 36) let known = try ages.get("ada") otherwise 0 let unknown = try ages.get("bob") otherwise 0 print("{known} {unknown}\n") // 36 0 return 0end 'main'A Factory That Validates
Section titled “A Factory That Validates”typealias Percent = int(0 to 100)
enum PercentError implements Error outOfRangeend 'PercentError'
type Progress export let done as Percent
static function create(done Percent) returns Self return Self{done: done} end 'create'
static function parse(text String) returns Self throws PercentError let value = try int.fromString(text) otherwise throw PercentError.outOfRange if value < 0 or value > 100 'range' throw PercentError.outOfRange end 'range'
return Self{done: value as Percent} end 'parse'end 'Progress'
function main() returns ExitCode let p = try Progress.parse("42") otherwise Progress.create(0) print("{p.done}%\n") // 42% return 0end 'main'Common Errors
Section titled “Common Errors”Compile-Time Errors
Section titled “Compile-Time Errors”A compile reports every independent error in the program at once. An error that follows from another is
covered by it: a call to a function whose declaration was refused, an argument typed by that function’s
result, a closure written for its parameter, a conformance a refused extension would supply, or a use
of a binding whose initializer was refused, is reported through that refusal. A parse error abandons the
function body, initializer or declaration it is in, and the rest of its file is checked; one inside a
generic function’s body, or one that leaves the file’s block structure unreadable, fails the whole file. A
generic function’s body is parsed for each instantiation, so it is checked once something instantiates it;
a generic type’s methods are parsed with the type. An
abandoned body is unknown: what it waits for, writes and returns fits every check made of its callers and
its results. A type name that denotes nothing is reported where it is written, and a value of that type
is unresolved, so each use of it is covered by that report. An error inside one method’s body covers that
method, and the rest of its type is checked. Unneeded casts (E3010), unused bindings (E3012,
E3077), unused exports (E3092) and unused unexported declarations (E3219) where
maxon lint checks them, dropped promises (E3212, E3213), target
refusals and the checks made while generating code are reported once the program has no other error, so
fixing every reported error can surface more.
Each example below is refused with the diagnostic shown.
Type mismatch
let x = 5 + "string" // E2004: Cannot operate on int and StringMissing return
function compute() returns Tally print("working\n")end 'compute' // E3013: missing return statement: 'compute'Assigning to a let
let x = 5x = 10 // E2013: 'x' is a let and cannot be reassignedA var started from a bare number
var total = 0 // E2004: A var cannot start from a bare number: write 'var name = expr as Type'.Self-assignment
x = x // E3067: self-assignment has no effect: 'x = x'A var that never changes
var x = 10 as Countreturn x // E3077: variable 'x' is never reassigned; use 'let' instead of 'var'An unused variable
let unused = 3 // E3012: unused variable: 'unused'Discarding a result, refused by maxon lint (E3064, E3065) and by
every compile (E3067)
double(5) // E3064: result of pure function 'double' must be usedincrementAndGet() // E3065: result of 'incrementAndGet' is not used (use '_ = expr' to discard)_ = 42 // E3067: expected a function callA missing try
parseDigit("7") // E3057: throwing function requires try: 'parseDigit'Writing constant data
let name = b"abc"name.push(1) // E3207: 'push' needs a writable receiver; 'name' is immutableMoving out of a var
var a = Point.create(1)let b = ab.x = 2print("{a.x}\n") // E3102: use of moved value 'a'Storing constant data where something may write it
let name = b"abc"let tok = Tok{value: name} // E3196 when Tok.value is a plain ByteArray: cannot store an immutable 'ByteArray' into 'Tok.value', which holds a mutable 'ByteArray'; declare the field `immutable ByteArray`Reading a local in the statement that hands it to a mutable parameter the callee writes
bump(h.n, h: h) // E3186: argument 'h.n' is read by another operand of this statement and passed by reference to 'bump' (parameter 'n') — a hold cannot protect a value its by-reference cell overwrites. Copy 'h' into a `let` in an earlier statement (`.clone()` a record, array or string) and use the copy for the other operandReaching raw memory from a program
let pid = __Builtins.currentProcessId() // E3185: call to '__Builtins.currentProcessId' from outside the library tiers: … — use 'Process.id()'Reading a local a closure captured
let word = "a word padded long enough to heap allocate {1}"let f = function() gives word.byteLength() as Tallyprint("{word}\n") // E3102: use of moved value 'word': its ownership moved to the closure that captures itStoring a closure into what it captures
export function arm() self.read = function() gives self.n // E3183: this closure captures 'self' and is stored into a record 'self' holds, …end 'arm'A bare primitive type
function half(n int) returns int // E3005: Cannot use bare 'int' as a type. Define a typealias with range constraintsMixing typealiases
let bad = score + meters // E3005: operator '+' requires both operands to be the same type: 'Score' and 'Meters' are different typealiases — cast one side with 'as'A mismatched block label
match x 'check' 1 then print("one\n") default then print("other\n")end 'wrong' // E2043: block identifier mismatch: expected 'check', got 'wrong'An empty block
if x > 0 'check'end 'check' // E3082: empty block: 'check'A block holding only a comment is empty too.
A non-exhaustive match
match level 'filter' error then print("error!\n")end 'filter' // E2026: match on enum 'Level' is not exhaustive, missing: trace, infoA redundant loop or match label
while i < 3 'loop' break 'loop' // E2048: 'break' with label 'loop' targets its own loopend 'loop'match n 'pick' 0 then break 'pick' // E2048: 'break' with label 'pick' targets its own match default then fallback()end 'pick'Run-Time Behavior
Section titled “Run-Time Behavior”Nothing in Maxon is undefined behaviour. At run time:
| Event | Behavior |
|---|---|
panic("…"), a failed range check, a negative shift count |
the program prints panic at <file>:<line>: <message> and a stack trace to stderr and exits with code 1 |
a for loop or an array cursor’s current() reading a slot that was never filled |
a panic: empty slot: element <i> of the array was never filled |
an array cursor’s current() past the last element |
a panic, as an index out of range |
| a green-thread stack past 1 GiB, or a recursion that overflows an OS stack | a panic: stack overflow |
| an index past the end of a collection | get/set throw ArrayError.indexOutOfBounds, handled with try |
division or mod by zero |
throws DivisionByZero, handled with try |
| integer overflow | wraps around (two’s complement), with no error; +, - and * over a full-width unsigned alias panic as a failed range check |
| an allocation never released | exit code 101 |
| a green thread neither awaited nor dropped | exit code 75 |
| a promise consumed through a second read of one container slot or struct field | exit code 118 |
HeapStats.census(mode) walking a heap it cannot describe |
exit code 119 |
a deep copy of an interface-typed field whose conformer cannot be duplicated — reachable only if a .clone() the front end should have refused was compiled |
exit code 120 |
| on x64-windows, the green-thread scheduler starting up with a thread-local slot Windows placed past the 64 slots of the thread’s own block | exit code 121 |
a second green thread calling Scheduler.quiesce() while another is waiting in it |
exit code 123 |
| the operating system refusing a green-thread program’s OS thread the event it sleeps on while it waits for a runtime lock | exit code 126 |
| a broken runtime invariant — a bug in the compiler or its runtime | the program prints fatal error: <reason> to stderr and exits with code 70 |
| on x64-windows, a fault on a green thread with too little stack left for the operating system’s exception dispatch | the program prints fatal error: exception dispatched below green thread stack bottom to stderr and exits with code 70 |
| deadlock | exit code 92 |
maxon execute and maxon test report these exit codes; see the CLI reference.
Best Practices for AI Agents
Section titled “Best Practices for AI Agents”These rules cover the mistakes code generators make most often when writing Maxon.
-
Label every block and repeat the label on
end.if x > 0 'positive'…end 'positive'. Choose labels that say what the block does. -
Never use bare
intorfloatin a declaration. Declare a typealias named for the purpose and use it for parameters, returns, fields and type arguments:typealias Tally = int(0 to u64.max)typealias TallyArray = Array with Tally -
Pass the first argument positionally and name the rest.
connect("localhost", port: 8080). The first argument may be named only when its parameter has a default. -
Construct records through a static factory.
Point{x: 1}is legal only insidePoint’s own body; elsewhere callPoint.create(1). -
Prefer
let. Avarthat is never reassigned is an error, even when it is written through (push, a field store). Every declared name must be used; write_for one you do not need. -
Handle every throwing call. Write
try call() otherwise <fallback>,otherwise panic("why")when failure is impossible, or a baretryinside a function thatthrowsthe same error type. -
Access collections through methods, with
try. There is noitems[i]:let value = try items.get(index) otherwise 0 -
Guard divisions. Use
try (a / b) otherwise …, or give the divisor a range that excludes zero. -
Build strings with interpolation.
"{name}: {count}"; there is no+onString. -
Match exhaustively. Name every enum or union case; put several on one arm with
or, one per line; usedefault panic("…")ordefault throwsinstead of a plaindefault. -
Cast between typealiases explicitly. Two different aliases never mix; write
value as Target. -
Use
clone()for an independent copy. Assigning a record shares it. -
Keep tests in
*.maxtestfiles. A test body calls assertions withouttry:test 'adds two numbers'Expect.equal(2 + 2, expected: 4)end 'adds two numbers'