Skip to content

Standard Library

A tour of the compiler-installed Atoll stdlib — scalars, collections, outcomes, concurrency, and host I/O.

The stdlib is installed by the compiler before your source is checked. Its core needs no import: string, []T, Map, Option, println, and the core traits are simply in scope.

The rest is modules — a directory under the standard library, exactly as a directory of your own .at files is — so their names are reached through the module rather than being global. Host I/O is one group: tcp, http and fs (tcp.connect, http.get, fs.File.read). time and task are modules the same way json is, not root names: import time for time.Duration and time.sleep, import task for task.Task and task.Stream. spawn, race and select are syntax, and a task’s or stream’s methods come with the value, so none of those needs an import. text is a module too, and adds methods rather than names: with import text, string.to_lower and char.to_upper map Unicode’s case, and a program that never imports it carries none of that code. path is a module for the bytes a file is named with: fs takes a path.Path or a string wherever it takes a name, and answers a Path wherever it names one. intrinsics, the compiler’s primitives, is no module but is named the same way: after import intrinsics, as intrinsics.size_of[int]().

fn main() void {
    names := ["Ada", "Grace", "Lin"]
    for name in names.filter(n => n.len() > 3).collect().sorted() {
        println("Hello, ${name}!")
    }
}

Most of the stdlib is written in Atoll itself, in the stdlib files under stdlib/. Those files are the authoritative signature inventory, and generic bodies specialize against your code exactly like any other Atoll source.

What is in scope

Area Types
Scalars bool, int, i8…i128, u8…u128, isize, usize, float, f32, char, byte
Text and binary string, []byte
Collections List, Map, Set, Range
Outcomes Option, Result
Concurrency spawn, race, select (syntax); the structural Selectable
Tasks and streams (module) task (Task, Stream, join_all, first_of, yield_now)
Time (module) time (Duration, DateTime, Date, Time, TimeZone, ZonedDateTime, sleep, after, monotonic_nanos)
Tracing and metrics (modules, designed, not built) trace (info, warn, …, capture, Context), metric (Counter, UpDown, Gauge, Histogram), and the @trace and @metric decorators
Host I/O (modules) fs (File, Dir), http (Client, WebSocket), tcp (Conn, Listener)
Addresses (module) net (IpAddr, SocketAddr), shared by tcp, udp, dns and http
Unicode case (module) text (string.to_lower, to_upper; char.to_lower, to_upper, is_upper_case, is_lower_case; CaseIter)
Identity and entropy (modules) pointer (same, same_or_none), random (below, bytes)
Compiler primitives (imported) intrinsics (size_of, alloc, load, store, …), after import intrinsics
Traits Equatable, Hashable, Comparable, Display, Numeric, Iterator, Iterable, Bytes, Buffer, Clone, Default, Drop, and the operator traits

Scalar type names stay lowercase; nominal types and traits are PascalCase; methods are snake_case.

Scalars and text

Integer arithmetic wraps rather than trapping, and wrapping_add is the explicit spelling of that. A string is a []byte, so it is measured and indexed in bytes; every accessor that could run off the end returns an Option.

fn main() void {
    count: u8 = 250u8
    println("${count.wrapping_add(10u8)}")       // 4

    name := "Ångström"
    println("${name.len()} bytes")               // 10
    println("${name.get(0) ?? 0u8}")             // 195 — the first BYTE of Å
}

There is no character-oriented access: len() counts bytes, get(i) answers a byte?. "Ångström" is eight characters and ten bytes, and only the second number is one Atoll will tell you.

See Numbers, Strings, and Bytes.

Collections

[]T is the workhorse. The whole higher-order surface — map, filter, fold, sorted_by, distinct, sum_of — lives on it directly, so there is no separate iterator type to opt into.

struct Sale { region string, cents int }

fn totals(sales []Sale) []string {
    mut out: []string = []
    for region in sales.map(s => s.region.clone()).distinct().collect().sorted() {
        total := sales.filter(s => s.region == region).sum_of(s => s.cents)
        out.push("${region}: ${total}")
    }
    return out
}

fn main() void {
    sales := [
        Sale { region: "emea", cents: 12000 },
        Sale { region: "amer", cents: 8050 },
        Sale { region: "emea", cents: 4550 }
    ]
    for line in totals(sales) {
        println(line)
    }
}

Map and Set cover keyed and unique storage, and both iterate with for.

fn word_counts(words &[]string) Map[string, int] {
    mut counts: Map[string, int] = Map.new()
    for word in words {
        counts.put(word.clone(), (counts.get(word) ?? 0) + 1)
    }
    return counts
}

fn unique(words &[]string) Set[string] {
    mut seen: Set[string] = Set.new()
    for word in words {
        seen.put(word.clone())
    }
    return seen
}

fn main() void {
    words := ["a", "b", "a"]
    println("${word_counts(words).get("a") ?? 0} ${unique(words).len()}")
}

See Lists, Maps, Sets, and Iteration.

Absence and failure

The standard library has no hidden panics: the calls that can stop a program are panic, unwrap and expect, written where they are meant, and the checks whose stop is part of their contract, such as xs[i] out of range. Each says what failed and where (see Panics). Absence is Option[T] and failure is Result[T, E], spelled T ! E in a return type. ?? supplies an Option fallback and ? propagates a Result.

error ConfigError { Missing { key: string }, NotANumber { key: string } }

fn lookup(settings Map[string, string], key string) string ! ConfigError {
    match settings.get(key) {
        Some(value) => return value.clone()
        None => error Missing { key: key }
    }
}

fn read_port(settings Map[string, string]) int ! ConfigError {
    raw := lookup(settings, "port")?
    match raw.trim().to_int().ok() {
        Some(port) => return port
        None => error NotANumber { key: "port" }
    }
}

fn read_port_or_default(settings Map[string, string]) int {
    return read_port(settings).unwrap_or(8080)
}

fn main() void {
    mut settings: Map[string, string] = Map.new()
    settings.put("port", "9000")
    println("${read_port_or_default(settings)}")
}

Numeric edges follow the same rule: parsing returns Option, and out-of-range collection access returns Option rather than trapping.

See Option and Result.

Traits are the extension points

Operators and generic algorithms dispatch through stdlib traits. Implementing one gives your type the corresponding syntax — there is no Add trait, for instance; arithmetic comes from Numeric.

struct Money { cents int }

impl Display for Money {
    fn write_to(&self, out &mut string) void {
        cents := (self.cents % 100).abs()
        out.append_int(self.cents / 100)
        out.append(".")
        if cents < 10 { out.append("0") }
        out.append_int(cents)
    }
}

fn main() void {
    // Display backs string interpolation: write_to appends to its string.
    println("total ${Money { cents: 1250 }}")
}

A struct or enum whose fields all support them gets the mechanical ones, equality, hashing and ordering, with no declaration, which is what makes it a Map key, a Set element, or the element of a list sorted() takes:

struct Point { x int, y int }

fn main() void {
    mut labels: Map[Point, string] = Map.new()
    labels.put(Point { x: 1, y: 2 }, "waypoint")
    println(labels.get(Point { x: 1, y: 2 }) ?? "missing")
}

Write a Comparable[T] impl when the order should be a different one:

struct Version { major int, minor int }

impl Comparable[Version] for Version {
    fn compare_to(&self, other Version) Ordering {
        return self.major.compare_to(other.major).then(self.minor.compare_to(other.minor))
    }
}

fn main() void {
    vs := [Version { major: 1, minor: 4 }, Version { major: 2, minor: 0 }]
    match vs.sorted_descending().first() {
        Some(v) => println("newest ${v.major}.${v.minor}")
        None => println("none")
    }
}

See Traits.

Concurrency and time

spawn yields a Task[T] you await, join, or cancel; Stream carries values between tasks; Duration and DateTime are ordinary values. The types are the task and time modules’ names. spawn and the methods on its handle need no import, so the example below imports only time, for time.Duration.

import time

fn work(n int) int {
    return n * n
}

fn main() void {
    a := spawn { work(6) }
    b := spawn { work(7) }
    println("${a.await().unwrap_or(0) + b.await().unwrap_or(0)}")

    budget := time.Duration.of_millis(250)
    println("${budget.total_millis()}ms")
}

await() answers T?, not T: None means the task was cancelled — nothing else — so a task that ran to its end always answers Some, even when its own result is an Option (Some(None) and None stay different facts). Nothing cancels the two tasks above, so unwrap_or is the honest short spelling; match on the Option where cancellation is a real outcome. join() is the wait without the value — true if the task completed, false if it was cancelled — and t.cancel() followed by t.join() is the “stop it and wait until it has stopped” pattern.

Stream[T] names its two enqueues and two dequeues on one rule: a bare name may suspend, a try_ name never does. send blocks while the ring is full (backpressure) and answers false only if the stream closed; try_send answers false at once on a full or closed ring. recv blocks while the ring is empty and answers None only when the stream is closed and drained; try_recv answers None the instant there is nothing buffered, which is not the same fact.

Host operations

Method syntax does not imply an in-memory call. fs.File.read, http.get, and tcp.connect are namespace methods backed by host operations: they can suspend, and they can be denied by the deployment’s capability policy even after they type-check.

import fs

fn line_count(path string) int {
    match fs.File.read(path) {
        Ok(text) => return text.split("\n").count()
        Err(e) => return 0
    }
}

fn load(path string) string ! fs.Error {
    return fs.File.read(path)?
}

fn main() void {
    println("${line_count("/etc/hostname")}")
    match load("/etc/hostname") {
        Ok(text) => println("${text.len()} bytes")
        Err(e) => println("unreadable")
    }
}

Host handles — open files, HTTP bodies, clients, listeners, sockets — represent runtime-owned state. The discipline is: acquire through a fallible constructor, keep one owning scope or task, bound reads and concurrent children, close explicitly when early release matters, and otherwise let Drop run on return, error propagation, or cancellation. Never use a handle after closing it, and never assume copying it duplicates the underlying resource.

Automatic cleanup prevents leaks; it does not define protocol. Dropping a socket releases it but does not prove a response was flushed, a WebSocket close handshake completed, or a transaction committed.

See Files, HTTP, and TCP.

Reading a stdlib signature

When you meet an unfamiliar stdlib method, four questions settle how to use it:

  1. Does it return Option or Result? That is the absence or failure contract, and the compiler will make you discharge it.
  2. Does it return owned storage or a borrowed view? to_bytes() and to_string() own; bytes() and slice() borrow the parent and must be used inside its scope.
  3. Can it suspend? Host operations can, which constrains what may be held across the call.
  4. Does it lower? Open stdlib/ and look at the declaration. A fn with a { ... } body, an @intrinsic, or an @host import will compile. A fn whose signature ends without a body is a semantic-checking declaration and will not — the failure surfaces at atoll build, never at atoll check.

Question 4 is the one that costs time. list.at illustrates all three cases in adjacent lines:

fn distinct(&self) []T {
        // ... real Atoll body: compiles and specializes like your code
}

fn join(&self, separator string) string
fn join_of(&self, separator string, f fn(T) -> string) string

distinct, join and join_of all compile: the excerpt shows the last two as bare signatures, but stdlib/list.at gives both a body. Each chapter page’s Availability table records the current state so you do not have to read the stdlib files yourself.

Names that are not builtins

The older builtin directory lists names the current compiler does not install. There is no stdlib Any, Email, Phone, Queue, Stack, Url, or Money, and no nominal bytes or Buffer struct: binary data is []byte and [..]byte, with no Bytes or Buffer trait. Stack- and queue-shaped logic uses []T; domain types are yours to define.

struct Stack[T] {
    items []T

    fn push(&mut self, value T) void {
        self.items.push(value)
    }

    fn peek(&self) &T? {
        return self.items.last()
    }

    fn depth(&self) int {
        return self.items.len()
    }
}

fn main() void {
    mut s := Stack { items: [1, 2] }
    s.push(3)
    println("${s.peek() ?? 0} ${s.depth()}")
}

Chapter map

Type to search…

↑↓ navigate↵ selectEsc close