Home / Docs / Specification
14. Standard library
Status: Normative, v0.1, with the additions of later editions marked by edition. The standard library is part of the Trusted zone. Everything not listed here does not exist in v0.1. This chapter covers the prelude, std.host and std.testing; the other standard modules are specified with their constructs: std.time and std.drive in spec/26 §2 (edition 0.4), std.limit in spec/27 §10 (edition 0.4), and std.collections in spec/28 §2 (edition 0.5, a preview).
1. Prelude
The prelude is imported into every module.
Types: Int, Nat, Bool, Text, Unit, List[T], Option[T] (Some(value), None), Result[T, E] (Ok(value), Err(failure)), Hashed.
Functions. All are pure and cannot fail. Contracts shown are part of their signatures and are used as hypotheses by callers.
| Signature | Contract |
|---|---|
abs(x: Int) -> Int |
ensures result >= 0 and (result == x or result == -x) |
min(a: Int, b: Int) -> Int |
ensures result <= a and result <= b and (result == a or result == b) |
max(a: Int, b: Int) -> Int |
ensures result >= a and result >= b and (result == a or result == b) |
is_digits(t: Text) -> Bool |
none (use inside opaque predicates) |
starts_with(t: Text, prefix: Text) -> Bool |
none |
trim(t: Text) -> Text |
ensures result.len <= t.len |
to_int(t: Text) -> Option[Int] |
none |
is_empty[T](xs: List[T]) -> Bool |
ensures result == (xs.len == 0) |
first[T](xs: List[T]) -> Option[T] |
ensures (result is None) == (xs.len == 0) |
at[T](xs: List[T], index: Int) -> Option[T] |
ensures (result is None) == (index < 0 or index >= xs.len) |
append[T](xs: List[T], item: T) -> List[T] |
ensures result.len == xs.len + 1 |
contains[T](xs: List[T], item: T) -> Bool |
none |
map[T, U](xs: List[T], each: fn(T) -> U) -> List[U] |
ensures result.len == xs.len |
filter[T](xs: List[T], keep: fn(T) -> Bool) -> List[T] |
ensures result.len <= xs.len |
first_where[T](xs: List[T], keep: fn(T) -> Bool) -> Option[T] |
none |
fold[T, U](xs: List[T], initial: U, step: fn(U, T) -> U) -> U |
none |
sum(xs: List[Int]) -> Int |
none |
is_some[T](o: Option[T]) -> Bool |
ensures result == (o is Some) |
or_else[T](o: Option[T], default: T) -> T |
none |
is_ok[T, E](r: Result[T, E]) -> Bool |
ensures result == (r is Ok) |
Higher-order prelude functions accept only pure, non-failing lambdas in v0.1 (effect polymorphism is deferred).
(v0.2, ADR 0062.) In edition 0.2, map, filter, fold and first_where declare uses of and fails of their function parameter (each, keep, step), so they take effectful and failing functions.
- They call it left to right, once per element, except that
first_wherestops at the first accepted element. - They stop at the first failure. Effects already performed stay performed (spec/11 §5).
- Their
ensureshold on success. The program counter of the function's body is that of spec/07 §7 rule 9.
(v0.2, ADR 0066.) In edition 0.2, min, max, contains and sum are generic over constrained types, and the prelude gains sort (spec/20 §6). abs stays Int-only.
(v0.2, ADR 0069.) In edition 0.2, the prelude gains empty_map() and the kind Entry[K, V]; the operations of a map are built-in methods of the receiver (spec/21 §2).
(v0.2, ADR 0070.) In edition 0.2, the prelude gains the text functions of spec/22 §2 and the kind ParseError (spec/22 §4).
(v0.2, ADR 0073.) In edition 0.2, the prelude gains the kinds Json, JsonNumber and JsonError, the predicate is_json_number, and the functions parse_json, to_json and quote_json (spec/23).
(v0.2, ADR 0056.) The prelude gains set[T](edit xs: List[T], index: Int, item: T) -> Unit, with requires 0 <= index and index < xs.len and ensures xs.len == old(xs).len (spec/17 §8).
(v0.2, ADR 0057.) The conversions, wrapping, saturating and bit operations of fixed-width integers are built-in methods resolved by the receiver, not prelude functions (spec/18 §4, §5). to_int on Text keeps the meaning above.
Result labels (ADR 0038 D3, ADR 0051). The parameters of these functions that are not functions accept arguments of any label, and their results carry those labels as follows (spec/07 §7 rule 8):
- Structural functions label each position of the result with what it holds. The element and accumulator positions carry the labels of their type variables, which every argument they come from joins (spec/07 §7 rule 1). The top label is the top label of what decides the result's shape, so the labels of element values the function does not read never reach it:
append,firstandis_empty: the top label ofxs;at: the top label ofxsand every label ofindex;is_some: the top label ofo;is_ok: the top label ofr;map: the top labels ofxsandeach;fold: the label of the accumulator type, joined with the top labels ofxsandstep;filterandfirst_where: the top labels ofxsandkeep, and the label ofkeep's declared result. A predicate's result flows into that declaredBool, so a predicate over labeled element values is rejected there (U4001). (v0.2, ADR 0067.) In edition0.2, the predicate's result is not checked againstBool's label: its label, symbolic labels included, joins the top label of the result instead, since which elements remain, or which one is found, depends on it.first_wherecallskeeponly up to the first accepted element, so a predicate with effects or failures whose result is labeled is U4002 there (spec/07 §3 rule 4)..lentakes the top label of its operand (spec/07 §7 rule 3).
- The other functions read element or argument values, and their result is labeled with the join of every label of their arguments, element types included:
contains,sum,or_else,min,max,absand the text functionsis_digits,starts_with,trimandto_int. (v0.3, ADR 0114.) In edition0.3, so doparse_f64,f64_from_bits,as_f64andjson_number(spec/29), and the failure ofparse_f64, asparse_int's. - (v0.4, ADR 0073 J5 as amended on 2026-11-09, accepted on 2026-11-10.) The variant constructors of
Json,Boolean,Number,Decimal,Str,ArrayandObject, label their result's top with the join of every label of their arguments, element types included; the positions ofJsonstaypublic(spec/23 §5 rule 2).
The native implementations declare these labels explicitly.
Text works on Unicode scalar values: .len counts them; is_digits holds when every character is an ASCII digit, so it holds of the empty text; trim removes Unicode whitespace at both ends; to_int reads an optional - followed by ASCII digits; starts_with compares scalar values; contains and == are structural; Text orders by scalar values (ADR 0032).
What the functions compute (#692). Beyond their contracts, the prelude's functions compute the following, in the interpreter and in the native backend alike (spec/16 §5). Positions in a list count from 0.
first(xs)isSomeof the element at position 0, andNonewhenxsis empty.at(xs, index)isSomeof the element at positionindex, andNonewhenindexis negative or at leastxs.len. It never fails.append(xs, item)isxswithitemadded after its last element.map(xs, each)is the list ofeach(x)for each elementxofxs, in the order ofxs.filter(xs, keep)is the list of the elementsxofxsfor whichkeep(x)istrue, in the order ofxs.first_where(xs, keep)isSomeof the first elementxofxsfor whichkeep(x)istrue, andNonewhen there is none.keepis not called on the elements after that one.fold(xs, initial, step)starts frominitialand, for each elementxofxsfrom first to last, replaces the accumulatoraccbystep(acc, x). The result is the last accumulator, soinitialwhenxsis empty.map,filter,first_whereandfoldcall their function parameter on the elements from first to last, at most once per element:first_wherestops after the first element it accepts, and in edition0.2and later each stops at the first failure of its function (§1).sum(xs)is the exact sum of the elements as anInt, and0whenxsis empty.Inthas no bound, so the sum never overflows. Edition0.2keeps this meaning for its genericsum(spec/20 §6 rule 1).or_else(o, default)is the valuevwhenoisSome(v), anddefaultwhenoisNone.defaultis an argument like any other, a value by the time of the call whateverois (spec/11 §4); a call with effects is bound withletbefore it is given (U3013).to_int(t)isSome(n)whentis an optional-followed by one or more ASCII digits, leading zeros allowed, wherenis the integer they write ("-0"is0). It isNonefor any other text, among them the empty text,"-", a leading+, whitespace and digits outside ASCII. (Security fix, 2026-10-18, #914, in every edition.) A text of more than 4300 digits, the sign excluded and leading zeros included, isNone, the bound ofparse_int(spec/22 §4) and of a JSON integer (spec/23 §3): converting d digits takes O(d²), so a longer text is refused before any conversion.
The prelude's types mean:
NatisInt where it >= 0(spec/03 §1): anIntflows intoNatwhere the bound is proved (spec/03 §2 rule 2).Option[T]is eitherSome(value), which holds one value ofT, orNone, which holds none.Result[T, E]is eitherOk(value), which holds the success value ofT, orErr(failure), which holds the failure ofE.
2. Built-in operations
.len on Text and List, arithmetic, comparisons, equality and text interpolation are built in (spec/09 §2). Hashed supports only == and !=; it cannot be interpolated or converted to Text (U2001).
3. Host capabilities (part of the prelude)
The host capabilities are declared in the module std.host and are in scope in every module through the prelude (spec/10 §11 rule 8). A module MAY also import them, with their failure kinds, from std.host (spec/10 §11 rule 10).
| Capability | Operation | Fails | Accepts | Notes |
|---|---|---|---|---|
Console |
print(line: Text) -> Unit |
public |
Writes the line and a newline to stdout | |
Clock |
now() -> Int |
public |
Milliseconds since the Unix epoch | |
Env |
get(name: Text) -> Option[internal Text] |
public |
Reads a process environment variable | |
Files |
read(path: Text) -> internal Text |
FileError |
public |
Path relative to the grant prefix |
Files |
write(path: Text, content: Text) -> Unit |
FileError |
internal |
Path relative to the grant prefix |
Keys |
hmac(key_name: Text, data: Text) -> internal Hashed |
KeyError |
public for key_name, any label for data |
HMAC-SHA-256 with a named key; the result carries the label of data |
kind FileError = NotFound | Denied | Io
kind KeyError = | UnknownKeyFilesresolves a path against the prefix fixed by the grant (ADR 0038 D9):- Normalize without following links. An absolute path, and a
..segment that leaves the prefix, fail withDenied. - Resolve intermediate components. Every intermediate directory is resolved with its symbolic links followed, and the resolved directory MUST lie inside the canonical grant prefix (
Deniedotherwise). - Never follow the final component. The final component is opened without following a link: if it is a symbolic link, dangling or not, the operation fails with
Denied. A write never creates a file through a link. - Races are out of the model. A race between the check and the use of a path is outside the v0.1 model, since the interpreter is single-threaded and host capabilities are trusted; the build report lists it (spec/13 §6). (v0.2, ADR 0065.) Concurrent tasks may also operate on one path in any order (spec/19 §3), and the native runtime's host capabilities are safe to call from several tasks at once (spec/19 §8).
- Hard links are out of the model. A hard link inside the grant to a file outside it is an ordinary directory entry, so
Filesreads and writes it. Hard links are outside the v0.1 model, as races are:Fileshas no operation that creates a link, so only someone with other access to the granted directory can plant one, and the build report lists them (spec/13 §6, ADR 0048). - Resource limits are out of the model (ADR 0086). A write can fail on what the environment sets: a full disk (
ENOSPC), a quota, or a file size limit (EFBIG). Such a failure can depend on the length of the content, so it is outside the model, as races and hard links are. - Other processes are out of the model (ADR 0086). Another process, a server on the same machine included, can change the granted directory between two operations of the run. The model treats the file system and the servers as separate, as races are outside it.
- Normalize without following links. An absolute path, and a
Keysloads keys from the file given in the grant (--grant keys:./keys.toml, a table ofname = "<base64>"). Key material never enters Una values.- Labels of
Keys.hmac(ADR 0039). The result of@k.hmac(key_name: n, data: d)is labeledinternal ⊔ ℓ*(d), whereℓ*(d)joins every label of the type ofd; lowering it below that label needs a policy (spec/07 §5).key_nameaccepts onlypublic, so a labeled key name, or a call under a raised program counter, is U4003, and a failure ofhmacdepends only on public data.dataaccepts every label. A user handler ofKeysis checked against the worst caller (spec/07 §7 rule 4): itskey_nameparameter ispublic, itsdataparameter carries every label, and its result may carry the label ofdata. - Labels of
Clockreadings (ADR 0116 amendment of 2026-11-09, accepted, #898). In edition0.4, the result ofClock.nowat a site is labeled with the timing label of the code that ran before it:τ⁰of the body of every ancestor of the site in the call graph, joined withτ_concat it,L_res, and in a driven packageτ⁰ofinit,stepandon_stop, by the ancestors' rule of spec/27 §9 rule 5. The reading then flows by the rules of spec/07: apublicsink refuses one abovepublic(U4003), and no release of timing is added. Its event in a run's trace is redacted at that label, and the report'sinformation.timinglist names each reading abovepublic. The checker computes the label in the probe of spec/27 §5 rule 8 and confirms it after checking (U8001 otherwise). In a package with aservesection, whoseL_srvthe preview makes⊤(spec/31 §7 rule 6), every reading is⊤. A reading in a handler's operation is⊤, so a handler ofClockcannot forward the host's clock (U4001 at its answer). A reading that a policy'sviafunction reaches, in its body or in what it calls, is U4001 when its label is abovepublic(spec/07 §5 rule 7), since no label is checked there. Editions0.1to0.3keep the reading unlabeled, with timing out of model (spec/07 §1). - Labels of failures (v0.2). Whether a host operation fails, and how, is labeled by the arguments that decide it (spec/07 §7 rule 4): the path of
Files.readandFiles.write, not the content; the key name ofKeys.hmac, not the data; forHttp, spec/24 §5 rule 3.Files.writeaccepts aninternalpath, so its failure is theninternal:attemptgives aninternalResult, andif error passis U4002. The other paths and key names arepublic, and so are their failures, except that everyFilesfailure also carries the package's file-state label: the labels that decide where the package's writes land and whether they run (S-14, ADR 0085, spec/07 §7 rule 4).Fileshas two operations,readandwrite, and both carry it. - Host text (ADR 0086, S-16).
Files.readandEnv.getmake aTextfrom bytes the program does not control. When those bytes are not valid UTF-8, the run aborts with U6005 at the operation:Files.readdoes not fail withIo, andEnv.getdoes not returnNone. Their content isinternal, so it cannot decide a failure or anOptiontag that apublicbranch sees; an abort is outside the noninterference model (spec/07 §1). Valid UTF-8 is read unchanged. In a task, the abort stops the task and its block reports it, as U6004 does. - User code MAY write handlers for host capabilities (for example, a fake
Keysin examples). Host implementations are used only byuna run.
(v0.2, ADR 0074.) In edition 0.2, std.host also declares the capability Http and the kinds Header, Response and HttpError (spec/24).
(v0.4, ADR 0123.) In edition 0.4, std.host also declares the capability HttpServer, the kinds Method, Param, Request, Exchange, Status, Reply and ServeError, and the opaque type ReplyRight (spec/31 §1). Unlike the other host capabilities, the prelude does not put these names in scope: a module imports them from std.host, and an import of one is never redundant (spec/10 §11 rule 10).
4. std.testing
Usable only in test code (ADR 0028, ADR 0043):
- A function of
std.testingis called only in example lines and in the operation bodies of handlers that are installed only bygivenlines of examples (tests, writtentestin edition0.3, spec/08 §2, ADR 0105; the messages name them by the edition's word). A call outside a handler operation body or an example is U3015. - A handler whose operation bodies use
std.testingand that is installed by awithbinding is U3015 at thewithbinding, with the use ofstd.testingas a related span. - A function of
std.testingused as a value, not called, is U3015 everywhere, in handler bodies and examples included.
| Signature | Purpose |
|---|---|
fake_hash(seed: Int) -> internal Hashed |
Deterministic Hashed value for tests; equal seeds give equal values |
elapse(d: Int of Millisecond) -> Unit, requires d >= 0 |
(Edition 0.4, ADR 0116 rule 19.) Moves the test's virtual clock forward by d at once, without waiting (spec/26 §8) |
test_request(method: Method, target: Text, body: Text) -> Request, fails TestRequestError |
(Edition 0.4, ADR 0123 rule 21.) The request the host would read for method, target and body, with the header host: test; Refused where the host would answer 400 (spec/31 §8) |
test_exchange(request: Request) -> Exchange |
(Edition 0.4, ADR 0123 rule 21.) An exchange of request with a fresh reply right (spec/31 §8) |
(Edition 0.4, ADR 0123 rule 21.) std.testing also declares pub kind TestRequestError = | Refused.