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

Standard Library

The standard library is a directory of ordinary Maxon source files, stdlib/, that ships beside the compiler. Every program is compiled together with it, so there is nothing to import: print, String, Array, File, Json and everything else on these pages are in scope in every file.

Most modules are a type used as a namespace (File.readText, Clock.nowNanos, Json.parse) or a type with instance methods (String, Array, FilePath). A handful of names are free functions (print, printError, sleep, sha256, spreadHash) and a handful are type aliases used across the library (ByteArray, StringArray, ExitCode).

A message or a spawn factory that calls a library operation which waits on another party, such as HttpServer.serve, TraceCapture.stopCapture or Scheduler.quiesce, is E3221; the reference names each such operation. A service that makes a file, socket, subprocess or HttpClient call, or reads stdin, is held for as long as the peer takes, and messages queue behind it.

Generic types are used through a type alias that names the element type:

typealias Score = int(0 to 100)
typealias ScoreArray = Array with Score
function main() returns ExitCode
let scores = ScoreArray.create(0)
scores.push(90)
print("{scores.count()}\n")
return 0
end 'main'
Page Sections
Core Core Functions
Text String, Character, Ascii, Unicode, CharacterSet
Collections Array, List, Map, Set, Slot, FixedArray, Range, Iterators, Interfaces
I/O and processes File, FilePath, Directory, Console, Stream, CommandLine, Log, TraceCapture, Process, Subprocess, SharedMemory, Debuggee, Sampler
Network TcpClient, TcpListener, HttpClient, HttpServer, URL
Data Json, Base64, Pem, Der, Sha2, Hmac, Hkdf, Rsa, Aead, AesGcm, ChaCha20Poly1305, Aes, ChaCha20, Poly1305, X25519, Ed25519, EcdhP256, Ecdsa, EcdsaP256, EcdsaP384, Hasher
System Clock, Scheduler, HeapStats, Reply, SharedValue, Random, TrustStore, Math, Primitive Extensions
Testing Testing
Build Build
Name Definition Declared by
ExitCode int(0 to u32.max) on Windows, int(0 to 255) elsewhere Process
Byte int(0 to u8.max) String
ByteArray Array with Byte File
Count int(0 to u64.max) implements ElementIndex — what a collection’s count() returns Array
StringArray Array with String Json
CharSet Set with Character CharacterSet
FilePathArray Array with FilePath Directory
FullRangeInt / FullRangeIntArray int(i64.min to i64.max) / Array with FullRangeInt Builtins
FullRangeFloat float(f64.min to f64.max) Builtins
IndentDepth int(0 to u64.max) — a nesting depth while Json renders Json
RandomDraw / RandomBound / RandomByteCount int(0 to u64.max) / int(1 to u64.max) / int(0 to u64.max) Random
RootCertificates Array with ByteArray TrustStore
BytePos, GraphemeIndex int(0 to u64.max) String
Codepoint int(0 to 1114111) Character
CodepointDelta int(-1114111 to 1114111) Character
AsciiValue int(0 to 127) Character
HashValue int(0 to u32.max) Interfaces
IterStep int(0 to u64.max) Interfaces
RangeBound int(i64.min to i64.max) Range
HashDigest bits(64) Hasher
OrderedWord bits(64) — a word read from or appended to a ByteArray in a byte order Builtins
SourceLineNumber int(1 to i32.max) Builtins
FileSize, Timestamp int(0 to u64.max) File
DurationMs, InstantMs, DurationNanos, InstantNanos int(0 to u64.max) Clock
UnixSeconds, UnixNanos, UnixDays int(i64.min to i64.max) Clock
SchedulerProcessorCount int(1 to u64.max) Scheduler
MailboxCapacity int(1 to 2147483648) — how many messages a service’s mailbox may queue, set by spawn(capacity: n) (Services) Builtins
DefaultMailboxCapacity the constant 1024 as MailboxCapacity — the capacity a bare spawn gives a mailbox Builtins
ForeverMs the constant u64.max as Milliseconds — a sendTimeout: that waits for room as long as it takes, untimed (Services) Sleep
NetworkPort int(0 to 65535) TcpClient; also URL.port()
EnvMap Map with String, String Subprocess
JsonNodeId / JsonNodeIdArray int(0 to u64.max) / Array with JsonNodeId Json
SegmentByteCount, SegmentOffset, SegmentWord see SharedMemory SharedMemory

A program may declare one of these names itself. Its declaration is then what the bare name means in every file of the program, and the library’s is reached as stdlib.ByteArray (see Qualified Names); the two are two types, and a value crossing between them needs a cast. Prefer the library’s alias where it fits, and otherwise give your own a different name. A file reads its own directory’s declaration of a name bare; two project declarations of one name a file can both see, in directories other than its own and the root, are E3063.

A signature may not name a type less visible than the function itself, so every alias and type a public library signature mentions is public too and can be written down in your own code — as a cast target, or to declare a value you are about to pass in. They are listed here because they are part of the surface, not because a program normally spells them: a value cast to the alias the signature asks for is the usual reason to name one. Float aliases are distinct types as integer aliases are, so a value of a program’s own float alias reaches a FullRangeFloat or JsonFloat parameter through as; a float literal needs no cast.

Name Definition Declared by
ElementIndex int(0 to u64.max) Array
ReportedCapacity int(i64.min to i64.max) Array
EntryCount int(0 to 9223372036854775808) Map
MemberCount int(0 to 9223372036854775808) Set
IterPos int(0 to u64.max) Range
ElementTransform, ElementPredicate function(Element) returns Element / returns bool, on the Iterable extension Interfaces
TableCapacity int(0 to 9223372036854775808) Map, Set
GreenThreadHandle int(0 to u64.max) — the handle a Promise holds Builtins
JsonInt int(i64.min to i64.max) Json
JsonFloat float(f64.min to f64.max) Json
Milliseconds int(0 to u64.max) Sleep
CivilYear / CivilMonth / CivilDay int(i64.min to i64.max) / int(1 to 12) / int(1 to 31) Clock
LogInteger, LogRank int(i64.min to i64.max) / int(i32.min to i32.max) Log
LogReal float(f64.min to f64.max) Log
LogGroupPath, LogFieldArray Array with String / Array with LogField Log
TraceKeyArray Array with String TraceCapture
SocketDeadlineMs int(0 to 4294967295) — a socket deadline TcpClient
ReadCapacity int(1 to i64.max) — the most bytes one readSome returns Stream
LineCap int(0 to u64.max), implementing BytePos — the longest line a read takes Stream
HttpByteCap int(0 to 1099511627776) HttpServer
HttpAcceptRetryMs int(0 to 1000) HttpServer
Pid, ByteLimit int(0 to u64.max) Subprocess
ExitInt int(0 to u32.max) Subprocess
WaitDeadlineMs int(1 to u64.max) — the milliseconds a WaitDeadline.within allows Subprocess
OsErrorCode int(0 to u32.max) — the Windows error code a SubprocessError case carries: GetLastError on Windows; on Linux and macOS the errno mapped onto its Windows equivalent, 31 when it has none Subprocess
EnvSourceValue int(0 to 1) Subprocess
StdioKindValue int(0 to 4) Subprocess
SpawnEnvironment, StdioRuntimeTriple the records Subprocess hands the runtime Subprocess
AssertedReal float(f64.min to f64.max) Testing
Tolerance float(0.0 to f64.max) Testing
CownTortureSize int(1 to u32.max) (CownTorture) Testing
CownTortureViolations int(0 to u64.max) (CownTorture) Testing

Byte and BytePos are declared once, in String (see the table above). BytePos, GraphemeIndex, JsonNodeId and Count implement ElementIndex; EntryCount, TableCapacity and SchedulerProcessorCount implement Count; and MemberCount implements EntryCount. So each indexes an Array with no cast, and any two of them compare with no cast through their common ancestor; an index of any other alias, or of a non-integer type, is E3005 (see Subtypes With implements). An ElementIndex goes where a Count is declared only by cast.

Array, List and FixedArray count(), JsonDoc.arrayLength, Character.byteLength() and the count() of a string’s codepoint and UTF-16 views return Count. String.count() returns a GraphemeIndex and a byte view’s count() a BytePos.

The inner typealiases a library type’s public members name are public as well and can be written qualified: Array.ElementIterator, Array.ElementMemory, Map.Entry, List.ListIter, Set.SetIter, FixedArray.FixedArrayIter and the like. The others are Array.ElementIterable, Array.ArrayIter, Array.ElementArray, HttpHeaders.CaseInsensitiveHeaders, Iterable.WithIterSelf, List.EManagedList, Map.IterKeyArray, Map.IterValueArray, Map.IterStateArray, Set.IterElementArray and String.ByteMemory.

Everything that is pure computation (strings, collections, Json, Base64, Pem, DerReader, the SHA-2, HMAC and HKDF functions, Hasher, Math, URL parsing) works on every target, and so does Random. Operating-system facilities are available on x64-windows, arm64-macos, arm64-linux and x64-linux. CommandLine, Process.environmentVariable and Process.currentEnvironmentEntries also work on wasm32-wasi.

On wasm32-wasi a call that needs a facility the target does not provide is refused at compile time, at the call site, rather than failing at run time:

Refused on wasm32-wasi Error
File, Directory, Console E3104
Clock.osTickMs, Clock.threadCpuTicks, MachinePin, every Scheduler member but parallelBoundary E3104
Log, Logger, LogSink and the log handlers: logging runs on services, which need green threads E3104
TcpClient, TcpListener, HttpClient, HttpServer E3104
Process.executablePath, FilePath.resolvedPhysically, SharedSegment, TrustStore E3104
Subprocess, StreamingSubprocess, Configuration E3074

E3104 means this compiler has not implemented the facility for the target; E3074 means the platform has no process-spawn primitive at all. Guard such calls with #if not os(Wasi).

Text the operating system hands a program, or takes from it, is UTF-8 on every target: command-line arguments, environment variable names and values, file and directory names and the names a directory listing answers, the working directory, the executable path and shared-memory section names. On x64-windows the runtime converts that text to and from UTF-16 at each call, so a name holding any Unicode character reaches the OS intact, and a Subprocess child receives its arguments, environment and working directory as UTF-16. Invalid UTF-8 handed to the OS, and an unpaired UTF-16 surrogate handed back, each become U+FFFD.

Files, directory searches and sockets are held by compiler-managed handle types (__ManagedFile, __ManagedDirectory, __ManagedSocket) that release the operating-system resource when their last reference goes out of scope. Programs use them through the library types (File, Directory, TcpClient, TcpListener); names beginning with __ are reserved for the compiler and the library.

The raw surface the library is written against belongs to the library tier: a source file under stdlib/ or runtime/. Anywhere else each of these is E3185 (see Raw Memory and the Library Tier):

  • every __Builtins.* intrinsic;
  • .managed, __ManagedMemory and __ManagedMemoryCursor;
  • String.cstr() and cstring;
  • Promise.inner;
  • the raw handle types __ManagedFile, __ManagedDirectory, __ManagedSocket, __ManagedPages, __ManagedHandle and __ManagedPin.

A program reaches the same facilities through the library:

Reading or action API
The allocator’s counters, levels, census and scavenger HeapStats
The machine’s uptime, a thread’s CPU time Clock.osTickMs(), Clock.threadCpuTicks()
This process’s id, namespace and priority; another process’s liveness Process.id(), Process.namespace(), Process.enterBackgroundPriority(), Process.isAlive(pid)
Logical CPUs, scheduler counters, stack size, pinning Scheduler.machineCpuCount(), Scheduler.counters(), Scheduler.currentStackBytes(), Scheduler.pinToMachine(), MachinePin
A float’s IEEE 754 bits Math.bitsOf(x), Math.fromBits(bits)
Terminal colour, raw standard input Console.stdoutWantsColor(), Console.stdin().readBytes(n)
Whether a promise has finished; the first of several p.isComplete(), promises.awaitAny()
Driving or sampling another process Debuggee, Sampler

A runtime/ directory ships beside stdlib/, and the compiler loads both on every compile; a compiler with only one of them beside it cannot compile anything. The runtime that every program links against is written there in Maxon, with privileges no other source has: it may declare __-prefixed names and call the raw __Raw.* intrinsics. A program cannot reach into it:

Rule Error
A __Raw.* call outside runtime/ E3152
Calling a runtime entry from outside the tier E3004
Naming a runtime entry as a function value E3155

The rules for the runtime files themselves are in The Runtime Tier.

A scriptlib/ directory beside stdlib/ holds your own packages, and a program whose root is one file compiles them with the standard library. Every file in it is yours. A package is compiled as the library is, with the raw surface above closed to it as it is to a program (E3185). See The scriptlib directory.

These are free functions and compiler builtins available everywhere.

Function Description
print(value String) Write value to standard output. No newline is added.
printError(value String) Write value to standard error.
sleep(milliseconds int(0 to u64.max)) Suspend the current green thread; other green threads run meanwhile. On wasm32-wasi the whole program waits.
panic(message String) Stop the program: prints panic at <file>:<line>: <message> and a stack trace to stderr, exits with code 1.

To print something that is not a String, interpolate it: print("{count}\n").

Function Returns Description
abs(x float) float Absolute value. A value of an integer alias is converted to float.
sqrt(x float) float Square root. A value of an integer alias is converted.
floor(x float) float Round toward negative infinity.
ceil(x float) float Round toward positive infinity.
round(x float) float Round to nearest; halfway cases round to even (round(2.5) is 2.0).
trunc(x float) FullRangeInt Truncate toward zero; the way to turn a float into an integer. Cast the result to reach a narrower alias.
min(a float, b float) float The smaller value. Integer arguments are converted.
max(a float, b float) float The larger value. Integer arguments are converted.

A float result whose range the compiler knows — from a literal, a let constant or another range-known value — carries that range and fits any float alias admitting it; any other is a FullRangeFloat.

Trigonometry, logarithms and powers are in Math.

Builtin Description
sizeof(TypeName) Storage size of a type in bytes, as a constant Count: int and float are 8, bool and byte are 1.
countof(TypeName) How many elements a fixed-size container type holds, as a Count, such as FixedArray with 3 Coord. A type with no fixed element count, a runtime-sized FixedArray with Coord among them, is refused (E2015); ask the value for count().
__file__, __line__ Legal only as a parameter’s default value; each expands at the call site.

__line__ parameters are declared SourceLineNumber and __file__ parameters String. The file is the calling file’s path relative to the compile root, /-separated on every host. Using either anywhere other than a parameter default is error E2060.

function check(ok bool, from String = __file__, at SourceLineNumber = __line__) returns bool
if not ok 'bad'
printError("{from}:{at}: check failed\n")
end 'bad'
return ok
end 'check'
function main() returns ExitCode
_ = check(1 + 1 == 2)
return 0
end 'main'

int, float, bool and byte each have a static fromString that throws ParseError.invalidFormat on malformed input. A type of your own can offer the same shape by implementing Parsable (static function fromString(input String) returns Self throws <error>).

function main() returns ExitCode
let n = try int.fromString("42") otherwise 0
let f = try float.fromString("3.25") otherwise 0.0
let b = try bool.fromString("true") otherwise false
let y = try byte.fromString("255") otherwise 0
let bad = try int.fromString("x1") otherwise -1
print("{n} {f} {b} {y} {bad}\n")
print("{abs(-5.5)} {floor(-3.2)} {round(2.5)} {trunc(-3.7)} {min(3.0, 5.0)}\n")
sleep(1)
printError("done\n")
return 0
end 'main'

Output: 42 3.25 true 255 -1 and 5.5 -4.0 2.0 -3 3.0 on stdout, done on stderr.

Interpolation also takes format specifiers — "{255:x}" is ff, "{7:04}" is 0007, "{3.14159:.2}" is 3.14, and "{name:q}" prints a String or Character between quotes with the escapes of a literal. See string interpolation in LANGUAGE_REFERENCE.md.