Skip to content

std

The std module provides core language facilities.

Types

TypeDescription
AbortError Raised when execution is aborted by the host trap mechanism.
Array[T] Arrays are ordered, mutable sequences of values.
@Assign[S @ {...}] A value that implements the (assign) protocol for the keys in S, which it need not already have.
@AssignMap[S @ {...}] A Map supporting assignment, which replaces every value of a key. It need not support adding or removing keys.
@AssignSeq[T] A Seq whose items can be replaced, but not added or removed.
BaseArray[T] The read-only half of an Array, whose elements it holds covariantly: an Array[Str] is a BaseArray[Str | Sym].
BaseDict[S @ {...}] The read-only half of a Dict, whose items it holds covariantly: a Dict[{a: Int}] is a BaseDict[{a: (Int | Str)}]. A parameter that only reads a dict takes a BaseDict, so it accepts dicts with narrower items.
@BaseIter[T] A value that implements the (next) protocol. Only an Iter also has its methods.
@BaseIterable[T] A value that implements the (iter) protocol, as for and spreading require. Only an Iterable also has its methods.
@BaseMap[S @ {...}] Iterates as the entries in S, and spreads and destructures as S, leaving rests of the same kind and *name rests that are a BaseSeq. The core of a Map, and what a pattern's rest of a dictionary supports.
@BaseSeq[S @ {...}] Iterates as the values in S, and spreads and destructures as S, leaving rests of the same kind. The core of a Seq, and what a pattern's rest of an array, or the *name rest of a dictionary, supports.
@BaseSink[T] A value that implements the (put) protocol. Only a Sink also has its methods.
@BaseSinkable[T] A value that implements the (sink) protocol. Only a Sinkable also has its methods.
BaseStruct[S @ {...}] A read-only view of a Struct, covariant in its schema: a Struct[{a: Int}] is a BaseStruct[{a: (Int | Str)}]. A parameter that only reads a struct takes a BaseStruct, so it accepts structs with narrower items.
Bin Binary data; an immutable sequence of bytes.
BinBuf Mutable byte buffer; the mutable counterpart to Bin.
Bool Boolean values: true and false.
CanceledError Raised when a strand is canceled. During finally blocks, cancellation is masked so cleanup can complete. See Concurrency for details.
CompileError Raised on compilation errors.
ConcurrencyError Raised when a concurrent access violation is detected.
CyclicImportError Raised when a cyclic module dependency is detected.
DataError Raised when an external document or stream being parsed, decoded, or read is invalid.
Dict[S @ {...}] Dictionaries are ordered, mutable key-value mappings. They preserve insertion order and are multi-maps: a single key can have multiple values.
Error The abstract base type for all errors. All error types in std inherit from Error, so it can be used as a catch-all in typed catch handlers.
FieldError Raised when accessing a nonexistent field on an object.
@FieldProxy[S @ {...}, M @ {...}] A fields proxy, which reads the members in S and sets those in M. A captured rest reads the members left over and sets none.
Float 64-bit floating point numbers.
Fmt[V, S @ {*, *(Int | Sym): Value}] Preserves literal text, bound interpolations, and unbound parameters from a t"..." string.
FmtParam An unbound interpolation in a Fmt.
FmtSpec Stores reusable formatting options.
FmtValue[T] Binds a value to reusable formatting options.
Func Func is the abstract supertype of function values.
@Getter[T, R] What getter makes from a function of the object read.
ImmutableError Raised when attempting to mutate an immutable value.
ImportError Raised when a module import fails (e.g. module not found).
@Index[S @ {...}] A value that implements the (index) protocol for the keys in S. A key must be one of S's, though an item S may omit can still be missing.
IndexError Raised when accessing an array or other indexed collection with an out-of-bounds index.
Int 128-bit signed integers.
Iter[T] Abstract type for iterators, whose instances have the methods below. Built-in iterators are Iter; a class that only implements (next) is not.
Iterable[T] Abstract type for iterable values, whose instances have the methods below. Arrays, dicts, and ranges are Iterable; a Record, or a class that only implements (iter), is not.
IterStop Error raised to signal that an iterator is exhausted. This is used internally by the iteration protocol and can be caught in try/catch statements.
@Map[S @ {...}] Reads dictionary-like entries, including multiple values for a key. Integer keys retain the positional structure described by S.
MissingItemError Supertype of errors for a missing positional or key item. Abstract, like ShapeError.
MissingKeyError Raised when a required key item is not provided.
MissingPosError Raised when a required positional item is not provided.
Module A module object, produced by import or by loading a compiled module. Its fields are the module's exported bindings.
@MutMap[S @ {...}] A Map supporting assignment and removal.
@MutSeq[T] A Seq whose items can be replaced, added, and removed.
Nil The type object for the nil value.
Null Acts as an empty iterator and a sink that discards every value.
Num Abstract supertype for numeric values.
OverflowError Raised on integer overflow.
Range[T @ Num] Describes a numeric interval for iteration and slicing.
Record[...Ts] Stores an immutable sequence of positional items and symbol-keyed items.
RuntimeError Supertype of ordinary catchable runtime failures, and a generic runtime error in its own right when no more specific type applies.
@Seq[T] An iterable sequence of T, which integers index, slices, spreads, and destructures.
Set[T] Sets are ordered, mutable collections with unique membership semantics.
@Setter[T, V] What setter makes from a function of the object assigned and its new value.
ShapeError Supertype of errors where items are missing or unexpected, in a call's arguments or a destructured value.
Sink[T] Abstract type for sinks, whose instances have the methods below. Built-in sinks are Sink; a class that only implements (put) is not.
Sinkable[T] Abstract type for values that sinks can be obtained from, whose instances have the methods below. An Array is Sinkable; a class that only implements (sink) is not.
SinkStop Error raised to signal that a sink has been closed.
@Spread[S @ {...}] A value that implements the (spread) protocol, spreading as the items in S.
StateError Raised when an operation is invalid for the current object or runtime state, such as using a closed handle or stale reference.
@StaticGetter[R] What getter makes from a function with no parameters, the getter of a static computed field.
@StaticSetter[V] What setter makes from a function of only the new value, the setter of a static computed field.
Str Strings are immutable sequences of UTF-8 bytes.
StrBuf Mutable UTF-8 string buffer; the mutable counterpart to Str.
Struct[S @ {...}] A mutable sequence of positional and symbol-keyed items, whose plain names are its keyed items. A struct has no methods of its own, so s.name reads the item keyed :name: and s.name = value replaces or adds it. Calling s.name args calls the item.
Sym Symbols are interned identifiers used for dictionary keys and enum-like values.
TimedOutError Raised when a strand times out. As with cancellation, a strand raises it the next time it suspends.
Tuple[*Ts] Tuples are immutable, ordered sequences of values. They are produced by certain operations such as iterating over key-value pairs. The Tuple type object is in the prelude, so Tuple(iterable) is available without an explicit import.
Type[T] The type of a class whose instances are T. Type is the type of all types and cannot be constructed directly.
TypeError Raised when an operation receives a value of the wrong type.
UnexpectedItemError Supertype of errors for an unexpected positional or key item. Abstract, like ShapeError.
UnexpectedKeyError Raised when a key item is unexpected or repeats a named parameter.
UnexpectedPosError Raised when an unexpected positional item is passed.
@Unpack[S @ {...}, :Rest @ Spread[S] = Spread[S], :Pos @ Spread[S] = Rest] A value that implements the (unpack) protocol, destructuring as the items in S without changing the receiver.
@UnpackIter[T] An iterator whose remaining elements can be unpacked without advancing it. Spreading and next still consume it. Captured rests are separate iterators over what is left.
@UnpackIterable[T] An iterable whose iterator supports read-only unpacking.
UnsupportedError Raised when an unsupported operation is attempted.
Value Value is the abstract supertype of all values.
ValueError Raised when the caller passes a value with an acceptable type but invalid contents, range, or meaning for the operation.
ZeroDivError Raised on integer division or modulo by zero.
AssignItem[S @ {...}, K] The values that fit every item of S that a key selects, which a write at a key of type K must fit. AssignItem[{a: Int, b: Str}, :a:] is Int, and a value fits AssignItem[{a: Int, b: Str}, (:a: | :b:)] if it fits both Int and Str. A key S doesn't admit is an error.
Clearable[S @ {...}] S, where every item admits zero, so removing all of them leaves a value of S. Clearable[{?a: Int, *Str}] is {?a: Int, *Str}, but Clearable[{a: Int}] is an error.
Deletable[S @ {...}, K] S, where removing every item that a key of type K selects leaves a value of S. Each item selected must be keyed and admit zero: Deletable[{a: Int, ?b: Str}, :b:] is {a: Int, ?b: Str}, but Deletable[{a: Int, ?b: Str}, :a:] is an error.
Entries[S @ {...}] The union of a Tuple of key and value for each of a schema's items, which keeps each key with its own value. A positional item's key is its index, as in Keys. Entries[{a: Int, b: Str}] is (Tuple[:a:, Int] | Tuple[:b:, Str]).
Fields[T] The keyed schema of the public members of T that can be read: a required item for each field, at its type, and each getter, at its result. A class that isn't final may have subclasses with more members, so its schema also admits other keys, as Value. For #[final] class Point with pub field x y @ Int, Fields[Point] is {x: Int, y: Int}.
FmtAlign An alignment for formatted output.
FmtFill A fill for formatted output: a single character, or :ZERO: for numeric zero padding.
FmtKind A representation kind for formatted output. See FmtSpec.kind.
FmtSegment[V] A segment of a Fmt: literal text, a bound interpolation, or an unbound parameter.
FmtSign A sign display for formatted numbers.
IndexItem[S @ {...}, K] The union of the values of the items of S that a key selects, which a read at a key of type K may give. A positional item's key is its index, as in Keys. IndexItem[{a: Int, b: Str}, :a:] is Int, and IndexItem[{a: Int, b: Str}, (:a: | :b:)] is (Int | Str). A key S doesn't admit is an error.
InsertItem[S @ {...}, K] The values that fit every item of S that a key selects, as in AssignItem, which a value added at a key of type K must fit. Each item selected must be keyed and admit repetition: InsertItem[{*(Str): Int}, Str] is Int, but InsertItem[{a: Int}, :a:] is an error.
Keys[S @ {...}] The union of a schema's keys, as a collection indexes it: positional items are indexed by Int. Keys[{a: Int, b: Str}] is (:a: | :b:), Keys[{**Int}] is Sym, and Keys[{Int, Str}] and Keys[{*Int}] are Int.
MutFields[T] The keyed schema of the public members of T that can be set: an optional item for each field, at its type, and each setter, at the value it takes. A class that isn't final also admits other keys, as Never, so that no value can be set at a key its subclasses might add.
Never The type with no values, which a function that never returns can declare as its result.
Phantom[...Ts] An opaque type that mentions its type arguments, for a field that only marks how a class varies with its binders. A field of this type uses its arguments covariantly, although a field is otherwise invariant, so Phantom[T] marks a class covariant in T and Phantom[(T -> nil)] contravariant. A schema binder is mentioned by expanding it: Phantom[...S].
Union[...Ts] The union of its type arguments. Union[Int, Str] is (Int | Str), and an expanded schema adds its items' types, as in Union[T, ...Us].
Unknown The unchecked type. Unlike Value, which admits every value but allows few operations without narrowing, Unknown converts to and from every type, so the checker accepts any use of it. A strict file may write it to leave one declaration unchecked.
Values[S @ {...}] The union of the values of a schema's items, positional or keyed. Values[{Bool, a: Int, b: Str}] is (Bool | Int | Str).

AssignItem[S @ {...}, K]

The values that fit every item of S that a key selects, which a write at a key of type K must fit. AssignItem[{a: Int, b: Str}, :a:] is Int, and a value fits AssignItem[{a: Int, b: Str}, (:a: | :b:)] if it fits both Int and Str. A key S doesn't admit is an error.

Clearable[S @ {...}]

S, where every item admits zero, so removing all of them leaves a value of S. Clearable[{?a: Int, *Str}] is {?a: Int, *Str}, but Clearable[{a: Int}] is an error.

Deletable[S @ {...}, K]

S, where removing every item that a key of type K selects leaves a value of S. Each item selected must be keyed and admit zero: Deletable[{a: Int, ?b: Str}, :b:] is {a: Int, ?b: Str}, but Deletable[{a: Int, ?b: Str}, :a:] is an error.

Entries[S @ {...}]

The union of a Tuple of key and value for each of a schema's items, which keeps each key with its own value. A positional item's key is its index, as in Keys. Entries[{a: Int, b: Str}] is (Tuple[:a:, Int] | Tuple[:b:, Str]).

Fields[T]

The keyed schema of the public members of T that can be read: a required item for each field, at its type, and each getter, at its result. A class that isn't final may have subclasses with more members, so its schema also admits other keys, as Value. For #[final] class Point with pub field x y @ Int, Fields[Point] is {x: Int, y: Int}.

FmtAlign = (:LEFT: | :RIGHT: | :CENTER:)

An alignment for formatted output.

FmtFill = (Str | :ZERO:)

A fill for formatted output: a single character, or :ZERO: for numeric zero padding.

FmtKind

@let FmtKind = $
  | :STR:
  | :DBG:
  | :VERBATIM:
  | :HEX:
  | :OCT:
  | :BIN:
  | :DEC:
  | :EXP:
  | :FIXED:

A representation kind for formatted output. See FmtSpec.kind.

FmtSegment[V] = (Str | FmtValue[V] | FmtParam)

A segment of a Fmt: literal text, a bound interpolation, or an unbound parameter.

FmtSign = (:PLUS: | :SPACE:)

A sign display for formatted numbers.

IndexItem[S @ {...}, K]

The union of the values of the items of S that a key selects, which a read at a key of type K may give. A positional item's key is its index, as in Keys. IndexItem[{a: Int, b: Str}, :a:] is Int, and IndexItem[{a: Int, b: Str}, (:a: | :b:)] is (Int | Str). A key S doesn't admit is an error.

InsertItem[S @ {...}, K]

The values that fit every item of S that a key selects, as in AssignItem, which a value added at a key of type K must fit. Each item selected must be keyed and admit repetition: InsertItem[{*(Str): Int}, Str] is Int, but InsertItem[{a: Int}, :a:] is an error.

Keys[S @ {...}]

The union of a schema's keys, as a collection indexes it: positional items are indexed by Int. Keys[{a: Int, b: Str}] is (:a: | :b:), Keys[{**Int}] is Sym, and Keys[{Int, Str}] and Keys[{*Int}] are Int.

MutFields[T]

The keyed schema of the public members of T that can be set: an optional item for each field, at its type, and each setter, at the value it takes. A class that isn't final also admits other keys, as Never, so that no value can be set at a key its subclasses might add.

Never = Union[]

The type with no values, which a function that never returns can declare as its result.

Phantom[...Ts]

An opaque type that mentions its type arguments, for a field that only marks how a class varies with its binders. A field of this type uses its arguments covariantly, although a field is otherwise invariant, so Phantom[T] marks a class covariant in T and Phantom[(T -> nil)] contravariant. A schema binder is mentioned by expanding it: Phantom[...S].

Union[...Ts]

The union of its type arguments. Union[Int, Str] is (Int | Str), and an expanded schema adds its items' types, as in Union[T, ...Us].

Unknown

The unchecked type. Unlike Value, which admits every value but allows few operations without narrowing, Unknown converts to and from every type, so the checker accepts any use of it. A strict file may write it to leave one declaration unchecked.

Values[S @ {...}]

The union of the values of a schema's items, positional or keyed. Values[{Bool, a: Int, b: Str}] is (Bool | Int | Str).

Functions

array[T] ...values -> Array[T]

Creates an array from positional arguments.

Parameters

NameTypeDescription
...values T

bool value -> Bool

Converts a value to Bool according to its truthiness.

Parameters

NameTypeDescription
value Value

Example

assert_eq (bool 0) false
assert_eq (bool 1) true
assert_eq (bool nil) false
assert_eq (bool "") false
assert_eq (bool "hello") true

dbg value -> Str

Converts a value to its debug representation. Shows internal structure (e.g. quotes strings, shows type tags).

Parameters

NameTypeDescription
value Value

dict[...Ts] ...pairs -> Dict[Ts]

Creates a dictionary from positional and key arguments.

Positional arguments receive incrementing integer keys starting at 0. Key arguments become symbol keys. The function-call syntax cannot specify other key types; use a horizontal dictionary literal or vertical data instead.

Parameters

NameTypeDescription
...pairs Ts

fields[T] value -> FieldProxy[Fields[T], MutFields[T]]

Makes a proxy for a value's public fields and properties.

Indexing the proxy with a member's symbol reads or sets the member, and unpacking or spreading it reads members by key, so a value without its own (unpack) can be destructured through fields. Iterating it gives (key, value) pairs. A member is read when the proxy is indexed, unpacked, spread or iterated, not when it is made.

#[final]
class Point
  pub field x y = 0

let p = Point()
fields(p)[:x:] = 3
let :x :y = fields(p)
assert_eq [x, y] [3, 0]

Parameters

NameTypeDescription
value T

Errors

Indexing the proxy raises IndexError for a key that isn't a member it can read, or set when assigning.

final[T] cls -> Type[T]

Decorator forbidding subclasses of a class.

A class that inherits from a final class fails to be created. Since a final class has no subclasses, the type checker knows that its instances belong to no class other than its supertypes.

#[final]
class Point
  pub field x y = 0

Parameters

NameTypeDescription
cls Type[T]

Errors

Exception Condition
TypeError cls isn't a class written in Do.
StateError A class already inherits from cls.

float value -> Float

Coerces or parses a value as a Float.

Parameters

NameTypeDescription
value (Num | Str)

Errors

Exception Condition
DataError The string is empty or malformed.
TypeError The value cannot be converted.

getter[T, R] func -> Getter[T, R] overload 1 of 2

Makes a field getter from a function of the object read.

Parameters

NameTypeDescription
func ((T, <Value, >Value) -> R) Function called for field reads.

Example

class Config
  field port = 8080

  #[getter]
  pub def port obj
    obj.#port

getter[R] func -> StaticGetter[R] overload 2 of 2

Makes a static field getter from a function with no parameters.

Parameters

NameTypeDescription
func ((<Value, >Value) -> R) Function called for field reads.

hash *values -> Int

Returns a hash code computed over all supplied values in sequence. Passing multiple values is useful for combining fields in a (hash) implementation:

def (hash) self
  hash $self.x $self.y $self.z

An unchanged value keeps its hash code while a program runs, but the code may differ between runs, so don't store hash codes as identifiers.

Parameters

NameTypeDescription
*values Value Values to hash.

int value -> Int overload 1 of 2

Coerces or parses a value as an Int.

Strings accept an optional sign and single _ separators between digits. Without base:, 0x, 0o, and 0b prefixes (in either case) select hexadecimal, octal, and binary; other strings are decimal. No whitespace is stripped.

Parameters

NameTypeDescription
value (Num | Str)

Errors

Exception Condition
DataError The string is empty or malformed.
ValueError The base is outside 2–36.
OverflowError The integer string is out of range.
TypeError The value cannot be converted, the base is not an integer, or base: is supplied with a non-string value.

Example

assert_eq (int "0xFF") 255
assert_eq (int "FF" base: 16) 255
assert_eq (int "1_000") 1000

int value :base -> Int overload 2 of 2

Coerces or parses a value as an Int.

Strings accept an optional sign and single _ separators between digits. Without base:, 0x, 0o, and 0b prefixes (in either case) select hexadecimal, octal, and binary; other strings are decimal. No whitespace is stripped.

Parameters

NameTypeDescription
value Str
:base Int

Errors

Exception Condition
DataError The string is empty or malformed.
ValueError The base is outside 2–36.
OverflowError The integer string is out of range.
TypeError The value cannot be converted, the base is not an integer, or base: is supplied with a non-string value.

Example

assert_eq (int "0xFF") 255
assert_eq (int "FF" base: 16) 255
assert_eq (int "1_000") 1000

mixable[T] cls -> Type[T]

Decorator letting a class be combined with classes unrelated to it.

A class is disjoint unless it is mixable, and no class can inherit from two disjoint classes neither of which inherits from the other. A mixable class takes the place of its nearest disjoint superclass, so subclasses of unrelated disjoint classes may share it as a superclass. The type checker reports a class that breaks this rule, and relies on it to know that unrelated disjoint classes share no instances. See Disjoint Classes.

#[mixable]
class Named
  pub field name = nil

class Shape
class Image
class Square: Shape Named
class Icon: Image Named

Parameters

NameTypeDescription
cls Type[T]

Errors

Exception Condition
TypeError cls isn't a class written in Do.
StateError A class already inherits from cls.

record[...Ts] ...args -> Record[...Ts]

Creates a record from positional and key arguments.

Positional arguments become positional items, and key arguments become symbol-keyed items.

Parameters

NameTypeDescription
...args Ts Positional and key field values.

Example

let r = record name: Alice age: 30
echo $r[:name:]  # Alice

setter[T, V] func -> Setter[T, V] overload 1 of 2

Makes a field setter from a function of the object assigned and its new value.

Parameters

NameTypeDescription
func ((T, V, <Value, >Value) -> nil) Function called for field writes.

Example

class Config
  field port = 8080

  #[setter]
  pub def port obj value
    obj.#port = value

setter[V] func -> StaticSetter[V] overload 2 of 2

Makes a static field setter from a function of only the new value.

Parameters

NameTypeDescription
func ((V, <Value, >Value) -> nil) Function called for field writes.

str value -> Str

Returns the general-purpose Str representation of a value.

Parameters

NameTypeDescription
value Value

struct[...Ts] ...items -> Struct[Ts]

Creates a Struct from positional and key arguments.

let s = struct host: localhost port: 22
assert_eq $s.port 22

Parameters

NameTypeDescription
...items Ts Positional and key item values.

Errors

Raises ValueError when a key is repeated.

sym value -> Sym

Interns a string as a Sym.

Parameters

NameTypeDescription
value (Str | Sym) Value to intern.

tuple[*Ts] *values -> Tuple[...Ts]

Creates a tuple from positional arguments.

Parameters

NameTypeDescription
*values Ts

type[T] value -> Type[T] overload 1 of 2

Returns the value's type

Parameters

NameTypeDescription
value T

Example

assert_eq (type 42) $Int

type[T] value type -> Bool overload 2 of 2

Tests whether value is an instance of type.

Parameters

NameTypeDescription
value Value
type Type[T]

Example

assert (type 42 Int)

verbatim value -> Str

Converts a value to its verbatim representation. Preserves the literal textual form of values where possible, which is useful for passing values as command-line arguments to external programs.

Parameters

NameTypeDescription
value Value

Values

class

Decorator placing a class member in the type-object namespace, where subclasses inherit it.

Applies to a def or a field inside a class body. A class method receives the class it was reached through as its first parameter. Each class in a hierarchy gets its own storage for a class field, seeded from the declared initializer.

class Counter
  #[class]
  pub field count = 0

  #[class]
  pub def bump cls
    cls.count = (cls.count + 1)
    cls.count

assert_eq $Counter.bump() 1

See static for the uninherited counterpart, and Class and Static Members for the full semantics.

null

The singleton Null value.

As an iterator it ends immediately; as a sink it discards every value.

static

Decorator placing a class member in the type-object namespace without making it inheritable.

Applies to a def or a field inside a class body. A static method takes no receiver; it names its class to reach it. Because a static is not inherited, it shadows an inherited class member of the same name without propagating that shadowing to subclasses — which is what makes a static (call) usable as a factory that cannot recurse into itself:

class Shape
  pub field kind = ""

  def (init) self kind
    self.kind = kind

  #[static]
  pub def (call) kind
    Type.(call) $Shape $kind

class Circle: Shape

let c = Circle "arc"   # default instantiation: the factory is not inherited

See class for the inherited counterpart, and Class and Static Members for the full semantics.