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

Enums & Unions

An enum declares a fixed set of named cases. Enum cases carry no associated data — a type whose cases carry data is a union. A case may have a raw value (see Raw-Value Enums).

enum Direction
north
south
east
west
end 'Direction'
function main() returns ExitCode
let dir = Direction.north
if dir == Direction.north 'up'
print("{dir.name}\n") // north
end 'up'
return 0
end 'main'

A case is written Type.case. Enum values compare with == and !=, and every payload-free enum is automatically Equatable and Hashable, so it can be a Map key or Set element. Inside match arms, cases are written bare (see Match Statement).

An enum can declare instance methods after its cases. Inside one, self is the case value; inspect it with match self. Self.case names a case of the enclosing enum.

enum Direction
north
south
function opposite() returns Direction
return match self 'flip'
north gives Self.south
south gives Self.north
end 'flip'
end 'opposite'
end 'Direction'
function main() returns ExitCode
print("{Direction.north.opposite().name}\n") // south
return 0
end 'main'
  • A method carries its own visibility — export or public — and is visible to its declaring directory’s subtree without one, whatever the enum’s own visibility. Calling an unmarked method from another directory is E3008.
  • Inside a method, self.name, self.ordinal and self.rawValue read the case, and a struct-backed enum’s backing field reads through self (self.latency). Any other self.x, and any assignment through self, is E2015.
  • static function is not supported on an enum (E2015).

An extension of an enum adds methods the same way, in any file, and each is the enum’s own at every call:

typealias Width = int(0 to 9)
enum Suite
hearts
spades
end 'Suite'
extension Suite
function width() returns Width
return 3
end 'width'
end 'Suite'

A method name belongs to the enum once, so an extension method that repeats one the enum declares is E3006. An extension member is an instance method: a static function is E2015, and a nested typealias is E2010. The header may declare implements, which joins the enum’s own.

Every enum case has:

Property Result
.name the case name as a String
.ordinal the zero-based declaration position, an ElementIndex
.rawValue the case’s raw value (the ordinal when none is declared), of the backing type — a FullRangeInt for an integer backing

and every enum type has:

Member Result
Type.allCases an Array of every case, in declaration order
Type.allCaseNames an Array with String of every case name
Type.fromName(name) the case with that name; throws noSuchCaseName when none matches
Type.fromRawValue(raw) the case with that raw value; throws noSuchRawValue when none matches
enum Color
red
green
blue
end 'Color'
function lookup(name String) returns Color
return try Color.fromName(name) otherwise Color.red
end 'lookup'
function main() returns ExitCode
for color in Color.allCases 'each'
print("{color.name}={color.ordinal} ") // red=0 green=1 blue=2
end 'each'
print("\n{lookup("blue").name} {lookup("purple").name}\n") // blue red
return 0
end 'main'

A literal name or raw value that matches no case is caught at compile time (E3034). Both lookups throw, so they need try.

A case’s raw value can be a record of compile-time constants, which attaches metadata to each case. Read it through .rawValue:

typealias Latency = int(0 to 50)
type OpMeta
export let latency as Latency
export let isMemory as bool
end 'OpMeta'
enum Instruction
add = OpMeta{latency: 1, isMemory: false}
load = OpMeta{latency: 4, isMemory: true}
store = OpMeta{latency: 3, isMemory: true}
end 'Instruction'
function main() returns ExitCode
let op = Instruction.load
print("{op.rawValue.latency} {op.rawValue.isMemory}\n") // 4 true
return 0
end 'main'
  • Every case uses the same struct type and provides a value.
  • Field values are compile-time constants: numbers, booleans, enum cases, top-level constants.
  • The enum is stored as its ordinal; .rawValue builds the record on demand. fromRawValue is not available for a struct-backed enum.
  • A backing field also reads directly off the value: op.latency is op.rawValue.latency. A field named name, ordinal or rawValue is reached only as op.rawValue.name, because the case accessors take those spellings.

An enum or a union can declare conformances after its name, and the clause means exactly what a type’s means — most often Error, which has no requirements:

enum FileError implements Error
notFound
permissionDenied
end 'FileError'
enum HttpError implements Error
badRequest = 400
notFound = 404
end 'HttpError'

The header is only enum Name and an optional implements clause; the backing type is inferred from the raw values, never written. Anything else on the header line — enum Colour int — is E2001 (unexpected token: 'int'), and the same holds for a union header.

An enum satisfies requirements with its own methods, and its values widen. Any interface may be named, not only Error: the enum’s methods are checked against the interface’s requirements the same way a type’s are, and a value of the enum is then accepted wherever that interface is the declared type — an interface-typed parameter, an interface-typed return, or an interface-typed field. Calls on it dispatch through the witness table, as they do for any other conformer:

typealias Integer = int(0 to 255)
interface Greeter
function greet() returns Integer
end 'Greeter'
enum Step implements Greeter
one
two
function greet() returns Integer
return match self 'which'
one gives 41
two gives 7
end 'which'
end 'greet'
end 'Step'
function callGreet(g Greeter) returns Integer
return g.greet()
end 'callGreet'
function main() returns ExitCode
return callGreet(Step.one) // 41
end 'main'

A union conformer carrying a payload widens the same way; the widened value releases its box when it drops.

A requirement no method of the enum matches is E3016, and a clause naming an interface that does not exist is E3015 — both reported at the enum’s name, exactly as for a type.

extension Step implements Greeter declares the same conformance from an extension, on an enum or a union, and it is checked and dispatched like the enum’s own clause. The extension’s methods, or the enum’s, satisfy the requirements, and a requirement none matches is E3016.

A payload-free enum may also name Hashable or Equatable explicitly. The compiler grants both to every payload-free enum already, and the granted implementation satisfies the declared requirement; writing the clause is a statement of intent, not a demand for a hand-written hash().

A raw value gives each case a constant: an integer, a float, a string, a character, a record, or a function.

enum HttpStatus
ok = 200
notFound = 404
serverError = 500
end 'HttpStatus'

Cases without a value count up from 0, or from the previous explicit integer value plus one. Negative values are allowed:

enum Priority
low // 0
medium // 1
high = 10
critical // 11
end 'Priority'
enum Temperature
cold = -10
freezing = 0
warm = 25
end 'Temperature'

Counting up applies only to integer raw values; a case without a value beside non-integer values is an error.

The raw values decide the backing type:

enum Threshold
low = 0.1
high = 0.9
end 'Threshold'
enum ContentType
json = "application/json"
html = "text/html"
end 'ContentType'
enum Escape
newline = '\n'
tab = '\t'
end 'Escape'

.rawValue has the backing type — ContentType.json.rawValue is the String "application/json". Struct-backed enums attach a record per case.

Function backing attaches a function to each case; all cases share one signature, and .rawValue is the function value:

typealias Operand = int(i64.min to i64.max)
function doubleFn(x Operand) returns Operand
return x * 2
end 'doubleFn'
function tripleFn(x Operand) returns Operand
return x * 3
end 'tripleFn'
enum Op
doubleOp = doubleFn
tripleOp = tripleFn
end 'Op'
function main() returns ExitCode
let f = Op.tripleOp.rawValue
print("{f(14)}\n") // 42
return 0
end 'main'

fromRawValue is available for integer, float, string and character backings, not for struct or function backings.

Cases compare with == and !=. A string-backed case also compares directly with a String, and a character-backed case with a Character, by its raw value:

enum ContentType
json = "application/json"
html = "text/html"
end 'ContentType'
function isJson(c ContentType) returns bool
return c == "application/json"
end 'isJson'

Comparing .rawValue itself with == is E3097 — compare the case (value == Type.case) instead.

A match on an enum names every case, bare (E2026 lists any that are missing). Type.case in an arm is E3075, a plain default arm is E2046, and covering a case twice is E2027. An arm covering several cases lists them with or, one per line:

enum Priority
low
medium
high = 10
critical
end 'Priority'
function urgency(p Priority) returns String
return match p 'check'
low or
medium gives "not urgent"
high or
critical gives "urgent"
end 'check'
end 'urgency'

Implicit Coercion to the Backing Primitive

Section titled “Implicit Coercion to the Backing Primitive”

A case of a simple, integer-backed or float-backed enum is used as its raw value wherever a number is expected — a function argument, a collection element, a comparison, a return, a struct field — with no .rawValue:

enum JsonByte
lBracket = 0x5B
space = 0x20
end 'JsonByte'
function main() returns ExitCode
let out = ByteArray.create(0)
out.push(JsonByte.lBracket) // pushes 0x5B
out.push(JsonByte.space)
let first = try out.get(0) otherwise 0
print("{first == JsonByte.lBracket}\n") // true
return 0
end 'main'

String-, character-, struct- and function-backed enums do not coerce; use .rawValue.

A keyword can be a case name, since cases are always written qualified (TokenKind.end) or bare inside a match arm:

enum TokenKind
function
return
end
if
end 'TokenKind'
Code Cause
E3030 duplicate case name
E3031 duplicate raw value
E3032 raw values of different backing types in one enum
E3034 an unknown case (Color.purple), or a literal fromName/fromRawValue argument that matches no case
E3097 comparing .rawValue with ==

A union declares a fixed set of cases, each of which may carry associated values. A value of a union is exactly one case with its payload, and match is how you read it.

typealias Amount = int(i64.min to i64.max)
union Outcome
success(value Amount)
failure(code Amount, message String)
pending
end 'Outcome'
function describe(r Outcome) returns String
return match r 'show'
success(v) gives "ok {v}"
failure(code, message) gives "failed {code}: {message}"
pending gives "waiting"
end 'show'
end 'describe'
function main() returns ExitCode
print("{describe(Outcome.success(42))}\n")
print("{describe(Outcome.failure(404, message: "not found"))}\n")
print("{describe(Outcome.pending)}\n")
return 0
end 'main'

A case with a payload is constructed like a call — first argument positional, the rest named after the payload fields: Outcome.failure(404, message: "not found"). A case without a payload is written like an enum case: Outcome.pending.

Payloads may be integers, floats, booleans, strings, records, other unions and collections. An integer literal passed for a float payload widens to the float: Reading.celsius(21) carries 21.0.

Every payload is a let: it is never reassigned for the whole life of the value, like a let field, and assigning to a match binding of it is E2013 ('callee' is a let and cannot be reassigned). Writes reach through it, so a field store or a push on the record or array it holds is legal. To give a union a new payload, assign the union a new case: b = Box.full(42). A union whose payloads are all value types is itself a value type.

A payload takes the capability words a field does, written before its type: named(text immutable ByteArray). An immutable payload holds frozen data. What is stored into it must be immutable (a b"…" literal, a constant let, a freezed value, or data read from another immutable slot); a plain ByteArray is E3196. A payload that is not declared immutable cannot hold immutable data: storing a constant name into named(text ByteArray) is E3196 (cannot store an immutable 'ByteArray' into 'Label.named.text', which holds a mutable 'ByteArray'; declare the payload `immutable ByteArray` ). A match binding of an immutable payload is immutable, so a write through it is E3207.

typealias Weight = int(0 to 100)
union Op
call(callee immutable ByteArray, weight Weight)
nop
end 'Op'
function main() returns ExitCode
let op = Op.call(b"emit", weight: 3)
match op 'show'
call(callee, weight) then print("{callee.count()} {weight}\n") // 4 3
nop then print("nop\n")
end 'show'
return 0
end 'main'

In a match, caseName(a, b) binds the payload for that arm; the bindings are local to the arm.

  • The number of bindings matches the case’s payload fields.
  • Discard one binding with _: failure(_, message).
  • To ignore the whole payload, omit the parentheses: success then …. Writing success(_) with every binding discarded is E3081.
  • An or-chain can list payload cases bare; their payloads are not accessible in that arm.
  • An arm that binds a payload covers exactly one case: every case in the arm’s or-chain must bind the slots the arm reads, so a binding beside a payload-less or bare case (stay or walk(dir)) is E3129. Give each case its own arm.
  • A match on a union must cover every case (E2026); use default throws or default panic(…) for a deliberate catch-all (see Statements).

A match binding names the payload the matched union holds, and it is a let. Writing a field of a payload record in place (value.count = value.count + 1) or handing the record to a function that writes it is legal whatever the scrutinee is. An isolated payload of a union that is not linear and not held in an isolated variable is lent to the arm: see Match Arms That Lend an isolated Payload.

Unions have no == or != (E3066 cannot compare union values using '==', use 'match' instead). Inspecting a union through match means that adding a case later flags every place that must decide what to do with it. For the same reason unions are not automatically Equatable or Hashable; a union may still declare implements Equatable with its own equals method and call it explicitly.

A union value is not a number: an arithmetic, bitwise or shift operator, unary - or not refuses a union operand (E2004 Cannot operate on Shape and int, or E3005), and so do a condition and a counted for range bound. Read the case through match, or its tag through .ordinal or .rawValue.

A union value has .name, .ordinal and .rawValue, and a union type has Type.allCaseNames and Type.fromName(name). fromName takes the payload as extra arguments when the name is a literal (Container.fromName("value", 42)); with a run-time string it only produces cases without a payload. There is no .allCases, because a payload case has no single value — use .unionCases below.

A case can declare an explicit integer tag, which becomes its .rawValue (the .ordinal is still the declaration position):

typealias Id = int(0 to 255)
union Instr
add(dest Id, src Id) = 5
neg(dest Id) = 9
end 'Instr'

A union can declare instance methods; inspect self with match:

typealias Amount = int(i64.min to i64.max)
union Shape
circle(radius Amount)
square(side Amount)
point
function area() returns Amount
return match self 'calc'
circle(r) gives 3 * r * r
square(s) gives s * s
point gives 0
end 'calc'
end 'area'
end 'Shape'
function main() returns ExitCode
print("{Shape.square(4).area()}\n") // 16
return 0
end 'main'

As with enums, a method carries its own visibility, and static function is not supported. An extension of a union adds methods under the rules of an enum’s extension. Through self, a method reads self.name, self.ordinal, self.rawValue and a struct-backed union’s backing field; a case’s payload (self.radius) is E2015, and match self binds it.

A union with no payload is a bare tag. A union with at most seven payload cases and at most 32767 cases in all, whose every case carries no payload or exactly one heap record (a String, a Character, a struct, or an array, map or other generic-instance record), and that declares no implements, in its header or in an extension, is one machine word: the payload’s address with the case key in its low three bits. Constructing one allocates nothing beyond the payload, and dropping one releases the payload it holds. Every other union with a payload is a heap box holding the tag and one slot per payload field, and a union that declares implements is always a box. The two forms behave alike: the same ownership, the same match, the same diagnostics. The word layout is described in docs/MEMORY_MANAGEMENT.md.

typealias HttpCode = int(100 to 599)
union FetchError implements Error
notFound
status(code HttpCode)
end 'FetchError'

Unions and enums are the types that can be thrown (see Error Handling).

Each case can also carry a compile-time record, exactly like a struct-backed enum. The payload and the record are independent: match reads the payload and .rawValue reads the record.

typealias Latency = int(0 to 50)
typealias Slot = int(0 to 255)
type OpMeta
export let latency as Latency
export let isMemory as bool
end 'OpMeta'
union MachineOp
movImm(dest Slot, value Slot) = OpMeta{latency: 1, isMemory: false}
load(dest Slot, addr Slot) = OpMeta{latency: 4, isMemory: true}
store(addr Slot, src Slot) = OpMeta{latency: 3, isMemory: true}
end 'MachineOp'
function main() returns ExitCode
let op = MachineOp.load(1, addr: 2)
print("{op.rawValue.latency} {op.rawValue.isMemory}\n") // 4 true
return 0
end 'main'

Every case uses the same record type and provides a value of compile-time constants.

Every union U has a companion enum U.unionCases with one bare case per union case, in declaration order. It is an ordinary enum — .allCases, .allCaseNames, .fromRawValue, .fromName, .name, .ordinal, .rawValue — and a match over it is exhaustiveness-checked.

That makes serialization safe to extend: write a case’s rawValue next to its payload, and on reading, lift the stored tag back with fromRawValue and match on it. Adding a case to U adds it to U.unionCases, so both the writer’s and the reader’s match stop compiling until they handle it.

typealias Amount = int(i64.min to i64.max)
union Shape
circle(radius Amount)
square(side Amount)
point
end 'Shape'
function kindOf(tag Amount) returns String
let kind = try Shape.unionCases.fromRawValue(tag) otherwise panic("unknown Shape tag {tag}")
return match kind 'kind'
circle gives "circle"
square gives "square"
point gives "point"
end 'kind'
end 'kindOf'
function main() returns ExitCode
let s = Shape.square(3)
print("{kindOf(s.rawValue as Amount)}\n") // square
return 0
end 'main'

The tags are declaration positions unless a case declares its own, so reordering cases changes stored tags; treat a persisted union as append-only.