Overview
This reference describes the syntax and semantics of the Maxon language. The grammar is in
BNF_SYNTAX.md, the standard library in the standard library reference, and
the maxon command in the CLI reference.
Program Structure
Section titled “Program Structure”Entry Point
Section titled “Entry Point”A program starts at a function named main that returns ExitCode:
function main() returns ExitCode print("Hello, world!\n") return 0end 'main'The value main returns is the process exit code. ExitCode’s range depends on the target: 0 to
u32.max on Windows, 0 to 255 on Linux, macOS and WASI. A literal outside that range is a compile error,
and a computed one panics at the return. A project run with maxon test
needs no main; a program compiled with maxon build or maxon execute without one is E3001.
main takes no parameters, since it is called with no arguments: function main(code ExitCode = 0) is
E3225, a parameter with a default value included. A program reads its command-line arguments with
CommandLine.args().
On Linux and macOS a program started with its standard input, output or error closed finds that stream open
on /dev/null: reads see end of input, writes are discarded, and a child that inherits the stream gets the
same. When the stream cannot be opened there, the program writes fatal error: cannot open standard fds to
standard error and exits with code 2 before main runs.
On Linux and macOS a write to standard output or standard error whose reader has gone ends the program by
SIGPIPE, which a shell reports as status 141. A write to any other closed pipe, such as a child’s stdin,
fails with an error the program can handle, and a SIGPIPE sent to the program from outside is ignored. A
child the program starts begins with the default SIGPIPE action.
Files and Projects
Section titled “Files and Projects”- A program is one
.maxonfile or a directory of them, compiled together. There are noimportstatements. - A file contains top-level declarations: functions, types, enums, unions, interfaces, extensions,
typealiases, variables and — in
*.maxtestfiles — tests. There are no top-level statements. - A file’s namespace comes from its directory (see Namespaces).
- An unmarked declaration is visible to its directory and that directory’s subdirectories;
exportandpublicmake it visible to every file (see Visibility). - Declaration order does not matter: a function may call one declared later or in another file.
- The standard library is available to every file. A program that is one file also compiles your scriptlib packages (The scriptlib directory).
Blocks and Labels
Section titled “Blocks and Labels”Every block opens with a keyword and a quoted label, and closes with end and the same label:
typealias Count = int(0 to 100)
function countDown(from Count) var n = from while n > 0 'tick' print("{n}\n") n = n - 1 end 'tick'end 'countDown'A function’s label is its name; a type’s, enum’s, union’s, interface’s or extension’s label is the type’s
name; a test’s label is its quoted name. Labels on if, else, while, for, match, try and otherwise
blocks are chosen by you and name the block for break and continue. A label written after end must be
the block’s own label: anything else is E2008 (Mismatched end label: expected 'tick', got 'loop'), and
E2043 for a match. Only a test must write it; on every other block the label after end may be
omitted. A block may not reuse the label of a block that encloses it, nor the name of the function, method
or type it sits in (E2081), because end '<label>' closes the innermost block it names; two blocks
that do not enclose one another may share a label. Statements end at the end of the line, except inside
an open (, [ or { (see
Line Breaks Inside Brackets), and a block runs from its label to its
end. A block label, a statement and a match arm each end their line, so the next one starts on a line
of its own; a token after one on the same line is E2001:
if ready() 'x' return 1 end 'x' // error E2001: Expected newline after block label, got 'return'A token after a statement or a match arm that is an error in its own right is reported as that error
ahead of E2001: an otherwise with no try is E3058, a statement after a return, throw, panic,
break or continue is E3071 (even when it is also a self-assignment), a self-assignment is
E3067, a token that opens no statement is E2001 unexpected token, and an arm after a default
is E2029.
Conditional Compilation
Section titled “Conditional Compilation”#if, #else and #endif include or exclude code by compilation target. They are evaluated while parsing:
#if os(Windows)let separator = "\\"#elselet separator = "/"#endif
function main() returns ExitCode #if (os(Linux) or os(Macos)) and arch(x64) print("x64 Unix\n") #else print("separator {separator}\n") #endif
return 0end 'main'Conditions:
os(Windows),os(Linux),os(Macos),os(Wasi)— the target operating systemarch(x64),arch(arm64),arch(wasm32)— the target architecturetesting(...),rcSanitize(...)andleakReport(...)name build flags the compiler does not have, so each flag is off:testing(false)holds andtesting(true)never does, including undermaxon testdebugstream(true)holds in a--debugstreambuild anddebugstream(false)otherwise
An os or arch argument the compiler does not recognize is false rather than an error, so portable code
can name a platform the compiler does not target.
Conditions combine with not, and and or (in increasing looseness) and parentheses. An unknown condition
is E2064.
Directives may surround top-level declarations, statements inside a function body, and members inside a
type, enum, union, interface or extension body. #if blocks nest.
Lexical Elements
Section titled “Lexical Elements”Maxon source is UTF-8 text, and a UTF-8 byte order mark at the start of a file is accepted. Outside
string literals and comments, every character belongs to a token. Any other character there — ?, ;,
|, &, $, %, ~, ^, a backtick, a control character or a non-ASCII character — is E1010
(Unexpected character).
Comments
Section titled “Comments”// A line comment runs to the end of the line.
/* A block comment may span lines. */Block comments do not nest: the first */ ends the comment. An unterminated block comment is E1007.
Doc Comments
Section titled “Doc Comments”A line starting with /// is a doc comment. Consecutive /// lines directly above a declaration
document it; editors show them when hovering over the declaration or its uses, and maxon fmt preserves
them.
typealias Size = int(0 to 100)
/// Doubles a size./// Shown when hovering over `twice` in an editor.function twice(n Size) returns Size return n * 2end 'twice'A doc comment is not a statement, so a block containing only a doc comment is still empty (E3082).
A /// after code on the same line is an ordinary comment.
Shebang Line
Section titled “Shebang Line”When a file’s first two bytes are #!, the first line is ignored, so a Maxon file can be run directly as a
script:
#!/usr/bin/env maxon
function main() returns ExitCode print("Hello, world!\n") return 0end 'main'The line must start at the very first byte of the file; #! anywhere else is E1009 (Unknown compiler directive). Line numbers in diagnostics still count the shebang line. maxon fmt keeps it as written.
Running such a file is maxon execute.
Identifiers
Section titled “Identifiers”identifier = [a-zA-Z_][a-zA-Z0-9_]*- An identifier starts with a letter or underscore, continues with letters, digits and underscores, and is case-sensitive.
- A keyword cannot name a variable (
let type = 3is E2010). A keyword can name a function, a parameter, or an enum or union case, since those are always written in a position where the keyword reading is impossible. - Names beginning with
__are reserved for the compiler and runtime (E2051). selfis the method receiver and cannot be bound by any declaration._alone is the discard name, not a variable.
Keywords
Section titled “Keywords”and as async await bool break continue countofcstring default else end enum export extends extensionfallthrough false float for from function gives ifignore implements in int interface is let matchmod not or otherwise panic public return returnsself Self shl shr sizeof static then throwthrows to true try type typealias union uptouses var where while with xorContextual keywords have a special meaning only in one position and are ordinary identifiers everywhere else:
| Word | Special when |
|---|---|
test |
at the top level, followed by a quoted name (see Testing) |
spawn |
followed by a type’s static factory call, optionally after (capacity: n) (see Services) |
bits |
followed by ( on the right-hand side of a typealias |
mutable |
before a parameter’s type, or a function-type parameter’s, and as mutable self (see Parameter Passing) |
isolated, immutable |
before a type, and before self as a receiver capability; isolated also after is in a where constraint (see Regions and Capabilities) |
modify |
at the start of a statement, followed by a name or self and ending its line with a label (see modify Blocks) |
freeze, swap, merge |
before an operand: a name, self, Self, try, or a parenthesis set apart by a space; swap path with value (see Regions and Capabilities) |
unique |
after is in a type header (see Unique Types) |
sendable |
after is in a where constraint of a generic type (see Region Bounds) |
mutates, captures |
the clause mutates captures ending a function type (see Capabilities at Function Types and Requirements) |
mutable, isolated and immutable are qualifiers exactly where the grammar expects a type, and
ordinary names or operands everywhere else (see Regions and Capabilities).
__line__ and __file__ are valid only as parameter defaults (see
Caller-Location Defaults).
Integer Literals
Section titled “Integer Literals”let decimal = 42let negative = -17let hex = 0xff // 255let binary = 0b1010 // 10let octal = 0o17 // 15let million = 1_000_000 // underscores separate digitsAn integer literal in any radix lies between -9223372036854775808 (i64.min) and 18446744073709551615
(u64.max); one outside that range is E2011. A literal has no typealias of its own, so it fits any integer
alias it is in range for. A literal above i64.max is the unsigned value, and it is legal only where a type
that admits it receives it: an as cast, a typed parameter, field, return or slot, a range bound, an operand
beside an alias that admits it, a merge arm or otherwise fallback of such a type, or a float slot. Anywhere
else it is E2011 (Integer literal '9223372036854775808' is above i64.max, so it needs an alias whose range admits it: write '9223372036854775808 as <alias>'); into a signed or narrower alias it is E3005.
Float Literals
Section titled “Float Literals”let pi = 3.14159let small = -2.5let big = 1.5e3 // 1500.0A float literal contains a decimal point, optionally followed by an exponent (e or E, with an optional
sign). 1e10 without a decimal point is not a float literal. A value beyond the float range is E2011.
Boolean Literals
Section titled “Boolean Literals”true and false.
Character Literals
Section titled “Character Literals”A character literal holds exactly one user-perceived character — which may be several codepoints and several UTF-8 bytes — in single quotes:
function main() returns ExitCode let letter = 'A' let accented = 'é' let cjk = '中' let emoji = '🎉' let quote = '\'' let sigma = 'Σ' print("{letter}{accented}{cjk}{emoji}{quote}{sigma}\n") // Aé中🎉'Σ return 0end 'main'An empty literal '', or one holding two characters, is E2016. A character literal beside an integer
operand is its codepoint, a Codepoint (cp - '0').
A Character is made of Unicode scalar values, U+0000 to U+D7FF and U+E000 to U+10FFFF. The surrogate block
U+D800 to U+DFFF has no UTF-8 spelling, so a character or string literal that spells one ('\uD800') or holds
malformed UTF-8 is E1004. Character.advanceBy counts scalar values and steps over the block, and a
character range such as '\uD7FF' to '\uE000' skips it. Codepoint is an integer range, so it can hold a
surrogate as a number; a Character or String is built from scalar values only.
String Literals
Section titled “String Literals”let greeting = "Hello, World!"let lines = "Line1\nLine2"let quoted = "Quote: \"text\""let hi = "\x48\x69" // "Hi"let bang = "hello!" // "hello!"A string literal cannot contain a raw newline; use \n.
Escape sequences:
| Escape | Meaning |
|---|---|
\n \t \r \0 |
newline, tab, carriage return, NUL |
\\ \" \' |
backslash, double quote, single quote |
\{ \} |
literal braces (string literals only) |
\xNN |
the codepoint U+00NN (exactly two hex digits) |
\uXXXX |
the codepoint U+XXXX (exactly four hex digits, outside the surrogates U+D800 to U+DFFF) |
In a String, \xNN is a codepoint, not a raw byte: "\xFF" is the character ÿ, two bytes in UTF-8. Use a
byte string for raw bytes. A malformed escape is E1004, and so is a literal whose text is not well-formed
UTF-8.
String Interpolation
Section titled “String Interpolation”{expression} inside a string literal inserts the expression’s value:
function main() returns ExitCode let name = "World" let x = 5 print("Hello, {name}!\n") // Hello, World! print("{x} * 2 = {x * 2}\n") // 5 * 2 = 10 print("Use \{braces\}\n") // Use {braces} return 0end 'main'Numbers, bool, Character and String interpolate directly. A type interpolates if it has a
toString() method (Stringable). A { that does not open an interpolation must be escaped as \{
(E1006).
Format specifiers. {expression:spec} formats a number, or quotes a String or Character:
- Integers:
[0][width][base]—0pads with zeros,widthis the minimum width (right-aligned), andbaseisx,X,oorb(decimal otherwise). Hexadecimal, octal and binary print the bit pattern, never a sign. - Floats:
[0][width][.precision]—precisionis the number of decimal places, rounded half to even; without it the float keeps its shortest round-trip spelling. A width never changes the digits. StringandCharacter:[width]q— the value prints as a valid Maxon literal, between double quotes for aStringand single quotes for aCharacter, with the escapes a literal spells:\"and\\,\{and\}in aString,\'in aCharacter,\n,\tand\r, and every other control character as\uXXXX.widthpads the quoted text on the left with spaces. Every other type prints plain underq.
function main() returns ExitCode let n = 42 print("{n:04} {n:6} {n:x} {n:04X} {-42:06} {255:08b}\n") // 0042 42 2a 002A -00042 11111111
let f = 3.14159 print("{f:.2} {f:.4} {f:8.2} {-3.14:08} {2.5:.0}\n") // 3.14 3.1416 3.14 -0003.14 2 return 0end 'main'Any other specifier leaves a String or bool as it is. A type that implements FormattedStringable receives the
specifier text in toString(format String), so {value:verbose} calls value.toString("verbose").
Byte String Literals
Section titled “Byte String Literals”b"..." creates a ByteArray (Array with Byte) directly:
let bytes = b"hello" // [104, 101, 108, 108, 111]let empty = b""let raw = b"\xFF\x00" // [255, 0]let latin = b"À" // [192]Every character becomes exactly one byte: \xNN is the byte NN, and a character or \uXXXX escape from
U+0000 to U+00FF is its Latin-1 byte. A character above U+00FF has no single-byte encoding and is
E1004. \{ and \} are not valid in a byte string.
Every b"..." literal is immutable image data (see Constant Data): it allocates nothing at
run time and nothing may write it. A mutable copy comes from .clone(), or from building the array with
ByteArray.create and push; "text".toByteArray() makes a mutable array from text. Binding a literal with
var and then writing it is refused (E3207).
Array and Dictionary Literals
Section titled “Array and Dictionary Literals”typealias Age = int(0 to 150)typealias AgeArray = Array with Age
let primes = [2, 3, 5, 7] // a constant Arraylet ages = ["ada": 36, "alan": 41] // a constant Maplet known = ["ada": 36 as Age].clone() // a Map with (String, Age) that can growlet seen = AgeArray from [36, 41] // an AgeArray that can growThe element type comes from the first element (or pair), and every later element is converted to it the
way an argument is to its parameter: [1.5, 1] holds 1.0, and ["a", 1] is E3005. A let bound to a literal of bare numbers is a
constant: its elements fit any element alias that admits them at each use, and it is immutable image data
(see Constant Data) — a method that writes it is refused (E3207). A var of such a literal is E2004: cast the numbers, or name the alias of an
Array, Set, List or FixedArray (AgeArray from [...]). See
Initializing From Literals for literals of other collection types.