Skip to content
Early preview. Maxon is under active development — incomplete in places, with breaking changes expected before a 1.0 release.

Patterns & Common Errors

function main() returns ExitCode
print("Hello, world!\n")
return 0
end 'main'
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 0
end 'main'
function main() returns ExitCode
let names = ["ada", "alan", "grace"]
for (iter, name) in names.withIterator() 'each'
print("{iter.index()}: {name}\n")
end 'each'
return 0
end 'main'
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 0
end 'main'

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 0
end 'main'
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 0
end 'main'
typealias Percent = int(0 to 100)
enum PercentError implements Error
outOfRange
end '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 0
end 'main'

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 String

Missing return

function compute() returns Tally
print("working\n")
end 'compute' // E3013: missing return statement: 'compute'

Assigning to a let

let x = 5
x = 10 // E2013: 'x' is a let and cannot be reassigned

A 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 Count
return 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 used
incrementAndGet() // E3065: result of 'incrementAndGet' is not used (use '_ = expr' to discard)
_ = 42 // E3067: expected a function call

A 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 immutable

Moving out of a var

var a = Point.create(1)
let b = a
b.x = 2
print("{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 operand

Reaching 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 Tally
print("{word}\n") // E3102: use of moved value 'word': its ownership moved to the closure that captures it

Storing 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 constraints

Mixing 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, info

A redundant loop or match label

while i < 3 'loop'
break 'loop' // E2048: 'break' with label 'loop' targets its own loop
end 'loop'
match n 'pick'
0 then break 'pick' // E2048: 'break' with label 'pick' targets its own match
default then fallback()
end 'pick'

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.

These rules cover the mistakes code generators make most often when writing Maxon.

  1. Label every block and repeat the label on end. if x > 0 'positive' … end 'positive'. Choose labels that say what the block does.

  2. Never use bare int or float in 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
  3. 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.

  4. Construct records through a static factory. Point{x: 1} is legal only inside Point’s own body; elsewhere call Point.create(1).

  5. Prefer let. A var that 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.

  6. Handle every throwing call. Write try call() otherwise <fallback>, otherwise panic("why") when failure is impossible, or a bare try inside a function that throws the same error type.

  7. Access collections through methods, with try. There is no items[i]:

    let value = try items.get(index) otherwise 0
  8. Guard divisions. Use try (a / b) otherwise …, or give the divisor a range that excludes zero.

  9. Build strings with interpolation. "{name}: {count}"; there is no + on String.

  10. Match exhaustively. Name every enum or union case; put several on one arm with or, one per line; use default panic("…") or default throws instead of a plain default.

  11. Cast between typealiases explicitly. Two different aliases never mix; write value as Target.

  12. Use clone() for an independent copy. Assigning a record shares it.

  13. Keep tests in *.maxtest files. A test body calls assertions without try:

    test 'adds two numbers'
    Expect.equal(2 + 2, expected: 4)
    end 'adds two numbers'