Builtins

These functions are part of the language and available everywhere. Their names cannot be assigned to. The builtin methods are called on a value instead, as in xs.len(). The builtin modules, os, math, random, time, fs, net, gui, and json, are imported like module files, as in use math. The same descriptions appear on hover in the editor.

print

print(values...)

Prints the values separated by spaces, followed by a newline. print() prints an empty line. Floats print like Python’s repr, bools as true and false, lists with their elements in brackets, with strings inside a list in single quotes, enum values as they are written, and struct values with their fields named, as in Point(x=1.0, y=2.0), unless the struct implements the trait display, whose display method then says how it is written. The whole line is built before any of it is written, so a print that fails writes nothing:

print("total", 3, 0.5, true, some(1), [1, 2], ["a"])   // total 3 0.5 true some(1) [1, 2] ['a']

print returns no value, so a call to it is a statement of its own.

eprint

eprint(values...)

Writes the values to standard error exactly as print writes them to standard output. Use it for messages about the run, such as warnings and progress, so they stay out of the output when it is piped into another program:

eprint("warning: skipping line", 3)   // on stderr: warning: skipping line 3

Each line is written as soon as it is built, so when both streams go to the same place, as with 2>&1, lines appear in the order the program wrote them.

range

range(end) | range(start, end)

Counts from start, or 0, up to but not including end. It can only be the iterable of a for loop, and its bounds are evaluated once, before the loop starts.

for i in range(2, 5):
    print(i)   // 2, then 3, then 4

Conversions

Conversions are calls of a type by its name with one value, as int(x), which the prelude’s traits from and try_from make. A conversion that cannot fail gives the type, and one that can gives a result[T, str], which ? passes on or unwrap takes apart. A program gives its own types conversions the same way; see Conversions.

int

int(value: int) -> int | int(value: float | str) -> result[int, str]

An int converts to itself. A float converts to ok of the int toward zero, dropping any fraction, so int(-2.5) is ok(-2), or to err("cannot convert float to int (nan or out of range)") if it is nan or does not fit in an int.

Given a string, it reads a decimal int: an optional + or -, then one or more digits, with spaces, tabs, and line breaks allowed at either end. Anything else, such as "1.5", "0x10", or "", is err("invalid literal for int() with base 10: '...'"), and a number that does not fit in an int is err("int() argument out of range: '...'").

print(int(2.9), int(-2.9), int(7))     // ok(2) ok(-2) 7
print(int(" -42 "), int("+7"))         // ok(-42) ok(7)
print(int("4.5"))                      // err("invalid literal for int() with base 10: '4.5'")
print(int("12").unwrap() + 1)          // 13

float

float(value: int | float) -> float | float(value: str) -> result[float, str]

Converts a number to a float, rounding to the nearest float if needed.

Given a string, it reads a decimal float such as 2.5, -.5, 3., or 6.02e23, or inf, infinity, or nan in any case, each with an optional sign and with whitespace allowed at either end, giving ok of it. A number too large for a float is inf. Anything else, such as "1e" or the hex float "0x1p3", is err("could not convert string to float: '...'").

print(float(3), float(9007199254740993))   // 3.0 9007199254740992.0
print(float("2.5e3"), float("-inf"))       // ok(2500.0) ok(-inf)
print(float("x").unwrap_err())             // could not convert string to float: 'x'

str

str(value) -> str

Returns the text print would write for value, of any type, so strings inside a list or another value are quoted and a string on its own is not. A struct that implements the trait display is written as its display method says, wherever it appears. Every type converts to str this way, so a program implements display, never from, to choose the text.

print("x = " + str(1.5) + ", done = " + str(true))   // x = 1.5, done = true
print(str([1, 2]) + str(some("a")))                  // [1, 2]some('a')

bytes

bytes(values: list[int]) -> result[bytes, str]

Returns ok of the bytes whose values are values, each from 0 to 255, or an err naming the first value outside that range, as err("byte out of range (value 300)"). See Bytes for the type itself.

print(bytes([104, 105, 0]))   // ok(b'hi\x00')
print(bytes([1, 300]))        // err('byte out of range (value 300)')

input

input() | input(prompt: str) -> result[str, str]

Writes prompt, if given, with no newline, then reads the next line from standard input and returns ok of it without its newline. Only \n is removed, so a line ending in \r\n keeps its \r (strip removes it), and a last line with no newline is still a line. Once the input is over, input returns err("end of input"), so an empty line, ok(""), never looks like the end. In a function that returns a result[T, str], ? passes the end on:

fn read_number() -> result[int, str]:
    line = input("number? ")?
    ret int(line)

print(read_number())   // ok(42) for the line 42, err('end of input') with no input

byte

byte(value: int) -> bytes

Returns bytes of the one byte value, stopping the program with byte out of range (value N) unless value is from 0 to 255. It appends a single byte without making a list or a result, and compiled it allocates nothing:

fn varint(n: int) -> bytes:
    out = b""
    v = n
    while v >= 128:
        out += byte(v % 128 + 128)
        v = v / 128
    ret out + byte(v)

print(varint(300))   // b'\xac\x02'

eof

eof() -> bool

Returns whether standard input has nothing left to read, so whether input would return an err. If no input has arrived yet, as when someone is typing, it waits for some. The usual way to read every line is:

while not eof():
    line = input().unwrap()
    print(line.len())

args

args() -> list[str]

Returns the command-line arguments given after the program, without the program’s own name. stone run sum.stn -- 1 2 and a built ./sum 1 2 both see ["1", "2"]. Each call returns a new list.

total = 0
for a in args():
    total += int(a).unwrap()
print(total)

Methods

A method is called on a value with a ., as in items.append(4). The value before the . is evaluated first, then the arguments, left to right, except that a method that changes its value evaluates the indexes of its value, then the arguments, then makes the change. A method must be called: items.len on its own is an error. Method names are not reserved, so they also work as ordinary names.

len

(str | bytes | list[T] | map[K, V] | set[T]).len() -> int

Returns the number of bytes in a string or bytes, elements in a list or set, or entries in a map.

print("stone".len(), [1, 2, 3].len(), {"a": 1}.len())   // 5 3 1

append

list[T].append(item: T)

Adds item to the end of the list. Since lists are values, this changes only the variable append is called on, or the element of one, as in grid[0].append(1), and never another variable that was assigned from it. It is always a statement of its own.

names = []
names.append("ada")
print(names)   // ['ada']

pop

list[T].pop() -> option[T] | list[T].pop(index: int) -> T | map[K, V].pop(key: K) -> option[V]

Without index, removes the last element and returns it as some(x), or returns none if the list is empty. With index, removes the element there and returns it; a negative index counts from the end, as in indexing, and the program stops with pop from empty list if the list is empty and with pop index out of range if index is past either end. Like append, it changes only the variable it is called on. Unlike append, it may be inside any expression, as in print(xs.pop().unwrap()) or while xs.pop().is_some():, as long as nothing else in that statement uses the list it changes: print(xs, xs.pop()) is an error, since xs would be read around the change, so write x = xs.pop() first. The whole value of an assignment, such as xs[0] = xs.pop(1), may use it anywhere, since the value is evaluated before the target.

On a map, pop removes the entry for key and returns some of its value, or none if the map has no entry for it. The other entries keep their order, and adding key again puts it last. It takes about the same time however large the map is.

stack = [1, 2, 3]
top = stack.pop()
first = stack.pop(0)
print(top, first, stack)   // some(3) 1 [2]
stack = []
nothing = stack.pop()
print(nothing)             // none
ages = {"ann": 31, "bob": 27}
gone = ages.pop("ann")
missing = ages.pop("cy")
print(gone, missing, ages)   // some(31) none {'bob': 27}

insert

list[T].insert(index: int, item: T)

Puts item at index, moving the elements from there on up by one, so xs.insert(0, x) adds x at the front and xs.insert(xs.len(), x) at the end. A negative index counts from the end. Unlike Python, which quietly clamps the index, it stops the program with list index out of range if index is below -len or above len. It is a statement of its own.

xs = [1, 3]
xs.insert(1, 2)
xs.insert(-3, 0)
print(xs)   // [0, 1, 2, 3]

extend

list[T].extend(items: list[T])

Adds every element of items to the end of the list, in order. A list can extend itself. It is a statement of its own. Since + on lists works element by element, extend is how to join two lists.

xs = [1, 2]
xs.extend([3, 4])
xs.extend(xs)
print(xs)   // [1, 2, 3, 4, 1, 2, 3, 4]

sort

list[T].sort()

Puts the elements of a list of int, float, str, or a type that implements ord in ascending order, in place. Strings compare byte by byte, so "Z" comes before "a" and a prefix before the longer string. Floats go in the order -inf, the negative numbers, -0.0, 0.0, the positive numbers, inf, then every nan, so no two values a program can tell apart tie and the result never depends on how the list was sorted. Values of a struct that implements ord go in the order its cmp gives, and values it finds equal keep the order they were in. It is a statement of its own; to keep the list as it was, sort a copy (ys = xs, then ys.sort()).

xs = [3.5, -1.0, 0.0, -0.0]
xs.sort()
print(xs)   // [-1.0, -0.0, 0.0, 3.5]

Compiled programs sort a list that is already in order, or in reverse order, in one pass. Long lists of ints or floats are sorted by radix, a pass per byte in which the values differ, after subtracting the smallest, so ints from a small range take one or two passes; this borrows memory as large as the list until it is done. Other lists of numbers and strings use a quicksort that never takes more than n log n time. A list of a struct is sorted by a merge sort written in stone in the prelude, which calls cmp about n log n times.

sort_by_key

list[T].sort_by_key(key: fn(T) -> K)

Puts the elements in ascending order of what key gives for each, in place. The keys must be of a type < orders: int, float, str, or a type that implements ord, and they compare as sort compares them. key is called once for each element, in order, before anything moves, and elements with equal keys keep the order they were in. It is a statement of its own.

fn length(s: str) -> int:
    ret s.len()

words = ["pear", "fig", "kiwi"]
words.sort_by_key(length)
print(words)   // ['fig', 'pear', 'kiwi']

The methods from here to max_by_key take a function, and are written in stone in the prelude. A call that passes a function by its name, as words.sort_by_key(length) does, compiles to a copy of the method that calls that function directly.

map

list[T].map(f: fn(T) -> U) -> list[U]

Returns a new list of what f gives for each element, in order.

fn double(x: int) -> int:
    ret x * 2

print([1, 2, 3].map(double))   // [2, 4, 6]

filter

list[T].filter(keep: fn(T) -> bool) -> list[T]

Returns a new list of the elements keep gives true for, in order.

any

list[T].any(test: fn(T) -> bool) -> bool

Returns whether test gives true for any element. It calls test on each element in order and stops at the first that gives true, so an empty list gives false.

all

list[T].all(test: fn(T) -> bool) -> bool

Returns whether test gives true for every element. It calls test on each element in order and stops at the first that gives false, so an empty list gives true.

min_by_key

list[T].min_by_key(key: fn(T) -> K) -> option[T]

Returns some of the element with the least key, the first of several with an equal key, or none for an empty list. It calls key once for each element, in order, and the keys compare as for sort_by_key.

max_by_key

list[T].max_by_key(key: fn(T) -> K) -> option[T]

Returns some of the element with the greatest key, the last of several with an equal key, or none for an empty list. With min_by_key, it gives the two ends of what sort_by_key would put in order.

fn length(s: str) -> int:
    ret s.len()

words = ["fig", "pear", "kiwi"]
print(words.min_by_key(length), words.max_by_key(length))   // some('fig') some('kiwi')

strip

str.strip() -> str

Returns the string without the spaces, tabs, and line breaks (\t, \n, \v, \f, and \r) at either end.

print("[" + "  a b  ".strip() + "]")   // [a b]

split

str.split() | str.split(separator: str) -> list[str]

With a separator, splits the string at each occurrence of it, from left to right, keeping empty pieces, so there is always one more piece than separators. An empty separator stops the program with empty separator. Without one, it splits at runs of whitespace and drops empty pieces, so leading and trailing whitespace make no difference.

print("a,,b".split(","), "a::b".split("::"))   // ['a', '', 'b'] ['a', 'b']
print("  3 4   5 ".split())                    // ['3', '4', '5']

splitlines

str.splitlines() -> list[str]

Splits the string into lines at each \n, \r\n, or \r, without their endings. A line ending at the very end ends the last line rather than starting an empty one, so a file’s text splits into its lines whether or not it ends with a newline, and an empty string has no lines. Unlike Python, other characters Python counts as line breaks, such as \x0c, stay in the line.

print("one\r\ntwo\nthree\n".splitlines())   // ['one', 'two', 'three']
print("a\n\nb".splitlines(), "".splitlines())   // ['a', '', 'b'] []

join

str.join(items: list[str]) -> str

Returns the strings in items with this string between each pair, so joining one item gives that item and joining none gives "". It undoes split with the same separator.

print(", ".join(["a", "b", "c"]))      // a, b, c
print("-".join("1 2 3".split()))        // 1-2-3

find

str.find(text: str) -> option[int]

Returns some of the index where text first appears in the string, or none if it never does. Like len and indexes, it counts bytes. An empty text is found at 0.

line = "key=value"
match line.find("="):
    case some(at):
        print(at, line[:at], line[at + 1:])   // 3 key value
    case none:
        print("no =")
print(line.find("?"))                       // none

rfind

str.rfind(text: str) -> option[int]

Returns some of the byte index where text last appears in the string, or none if it never does. An empty text is found at the end, at s.len().

path = "src/stdlib/net.stn"
match path.rfind("/"):
    case some(at):
        print(path[:at], path[at + 1:])   // src/stdlib net.stn
    case none:
        print(path)

count

str.count(text: str) -> int

Returns how many times text appears in the string, searching from the start and going on after the end of each match, so matches never overlap. An empty text is found between every two characters and at both ends, so it counts one more than the characters.

print("banana".count("a"), "aaaa".count("aa"), "café".count(""))   // 3 2 5

replace

str.replace(old: str, new: str) | str.replace(old: str, new: str, count: int) -> str

Returns the string with each match of old, found as count finds them, replaced by new. With count, only the first count matches are replaced, or every one if count is negative. An empty old matches between every two characters and at both ends, never inside a character.

print("a-b-c".replace("-", "+"), "a-b-c".replace("-", "", 1))   // a+b+c ab-c
print("ab".replace("", "."))                                      // .a.b.

lower

str.lower() -> str

Returns the string with each ASCII letter A to Z made lowercase. Unlike Python, letters outside ASCII stay as they are, so "ÉTÉ".lower() is "ÉtÉ".

print("Hello, World!".lower())   // hello, world!

upper

str.upper() -> str

Returns the string with each ASCII letter a to z made uppercase. Unlike Python, letters outside ASCII stay as they are, so "été".upper() is "éTé".

print("Hello, World!".upper())   // HELLO, WORLD!

startswith

str.startswith(prefix: str) -> bool

Returns whether the string begins with prefix. Every string starts with "".

print("stone".startswith("st"), "stone".startswith("one"))   // true false

endswith

str.endswith(suffix: str) -> bool

Returns whether the string ends with suffix. Every string ends with "".

print("main.stn".endswith(".stn"), "main.stn".endswith("main"))   // true false

bytes

str.bytes() -> bytes

Returns the string’s UTF-8 bytes. It copies nothing, since a string’s bytes never change.

print("café".bytes())   // b'caf\xc3\xa9'

text

bytes.text() -> result[str, str]

Returns ok of the bytes as a string if they are UTF-8 text with no 0 byte, which a string cannot hold, or err("not valid UTF-8 text").

print(b"caf\xc3\xa9".text(), b"\xff".text())   // ok('café') err('not valid UTF-8 text')

u16_le, u32_le, u64_le

bytes.u16_le(index: int) -> int
bytes.u32_le(index: int) -> int
bytes.u64_le(index: int) -> int

Returns the 2, 4, or 8 bytes from index on as a little-endian int. The first two are never negative, and u64_le wraps to a negative int when its last byte is 128 or more. A negative index never counts from the end, and a read that does not fit in the bytes stops the program with u32_le index out of range (index 5, length 8). Compiled, each is one load after one check, so comparing four bytes at once is a.u32_le(i) == a.u32_le(j).

data = b"\x01\x02\x03\x04\x05\x06\x07\x08"
print(data.u16_le(0), data.u32_le(4), data.u64_le(0))   // 513 134678021 578437695752307201

is_some

option[T].is_some() -> bool

Returns whether the option holds a value.

is_none

option[T].is_none() -> bool

Returns whether the option is none.

print(some(1).is_some(), some(1).is_none(), none.is_none())   // true false true

unwrap

(option[T] | result[T, E]).unwrap() -> T

Returns the value the option or the ok holds. It stops the program with cannot unwrap none if the option is none, or, if the result is an err, with cannot unwrap err: and the error as print writes it, such as cannot unwrap err: invalid literal for int() with base 10: 'x'. Use it where that cannot happen, and match, unwrap_or, or ? elsewhere.

print(some("a").unwrap(), ok(2).unwrap())   // a 2

unwrap_or

(option[T] | result[T, E]).unwrap_or(default: T) -> T

Returns the value the option or the ok holds, or default if it is none or an err.

print(some(3).unwrap_or(0), none.unwrap_or(0), int("x").unwrap_or(-1))   // 3 0 -1

is_ok

result[T, E].is_ok() -> bool

Returns whether the result is an ok.

is_err

result[T, E].is_err() -> bool

Returns whether the result is an err.

r = int("12")
print(r.is_ok(), r.is_err())   // true false

unwrap_err

result[T, E].unwrap_err() -> E

Returns the error the err holds. It stops the program with cannot unwrap_err ok: and the value, as print writes it, if the result is an ok, such as cannot unwrap_err ok: 12.

print(float("x").unwrap_err())   // could not convert string to float: 'x'

ok

result[T, E].ok() -> option[T]

Returns some of the value an ok holds, or none for an err, which turns a result into an option, as a function that returns an option needs before ?.

err

result[T, E].err() -> option[E]

Returns some of the error an err holds, or none for an ok.

r = int("7")
print(r.ok(), r.err())   // some(7) none

contains

str.contains(text: str) -> bool | bytes.contains(part: bytes) -> bool | list[T].contains(value: T) -> bool | map[K, V].contains(key: K) -> bool | set[T].contains(value: T) -> bool

Returns whether the string has text in it (the empty string is in every string), the bytes part in them, the list an element equal to value, the map an entry for key, or the set the element value. A list compares its elements with value in order, as value == element does, and stops at the first that is equal, so its elements must be values == can compare, and a struct with its own eq compares by it. The operators in and not in make the same test: value in c is c.contains(value), except that it evaluates value first.

ages = {"ann": 31}
print(ages.contains("ann"), ages.contains("bob"))   // true false
print([3, 1, 4].contains(4), "hello".contains("ell"))   // true true

get

map[K, V].get(key: K) -> option[V]

Returns some of the value of key’s entry, or none if the map has no entry for it. Unlike m[key], which stops the program with key not found, it never fails.

ages = {"ann": 31}
print(ages.get("ann"), ages.get("bob"))   // some(31) none
print(ages.get("bob").unwrap_or(0))      // 0

keys

map[K, V].keys() -> list[K]

Returns a new list of the map’s keys, in the order they were first added. A for loop over a map goes through the same keys without making a list.

ages = {"bob": 27, "ann": 31}
print(ages.keys())   // ['bob', 'ann']
for name in ages:
    print(name)      // bob, then ann

values

map[K, V].values() -> list[V]

Returns a new list of the map’s values, in the order their keys were first added.

ages = {"bob": 27, "ann": 31}
print(ages.values())   // [27, 31]

items

map[K, V].items() -> list[tuple[K, V]]

Returns a new list of the map’s entries as (key, value) tuples, in the order their keys were first added, so for k, v in m.items() goes through both. It shares the map’s storage until one of them changes, so it copies nothing.

ages = {"bob": 27, "ann": 31}
print(ages.items())   // [('bob', 27), ('ann', 31)]
for name, age in ages.items():
    print(name, age)

add

set[T].add(value: T)

Adds value to the set in place, after its other elements, unless the set has it already. Like append, it changes its set and returns nothing, so it is a statement of its own.

seen = {}
for word in ["a", "b", "a"]:
    seen.add(word)
print(seen)   // {'a', 'b'}

remove

set[T].remove(value: T) -> bool

Takes value out of the set in place and returns whether the set had it, leaving the other elements in order. A set closes up the gaps once removed elements are more than half of it.

s = {1, 2, 3}
print(s.remove(2), s.remove(9))   // true false
print(s)                          // {1, 3}

union

set[T].union(other: set[T]) -> set[T]

Returns a new set of the elements of either set: the set’s own, in order, then those of other it lacks.

print({1, 2}.union({2, 3}))   // {1, 2, 3}

intersection

set[T].intersection(other: set[T]) -> set[T]

Returns a new set of the set’s elements that other has too, in the set’s order.

print({1, 2, 3}.intersection({3, 2}))   // {2, 3}

difference

set[T].difference(other: set[T]) -> set[T]

Returns a new set of the set’s elements that other lacks, in the set’s order.

print({1, 2, 3}.difference({2}))   // {1, 3}

is_subset

set[T].is_subset(other: set[T]) -> bool

Returns whether other has every element of the set, so every set is a subset of itself.

print({1}.is_subset({1, 2}), {3}.is_subset({1, 2}))   // true false

is_superset

set[T].is_superset(other: set[T]) -> bool

Returns whether the set has every element of other.

print({1, 2}.is_superset({2}))   // true

is_disjoint

set[T].is_disjoint(other: set[T]) -> bool

Returns whether the two sets have no element in common.

print({1}.is_disjoint({2}), {1}.is_disjoint({1}))   // true false

eq

T.eq(other: T) -> bool

Returns whether two values are equal, as == does, for any type that implements the trait eq: every type == compares part by part, and a struct whose impl eq block says what equal means for it.

print(3.eq(3), (1, "a").eq((1, "b")))   // true false

cmp

T.cmp(other: T) -> ordering

Returns less, equal, or greater as the value comes before, with, or after other, for any type that implements the trait ord: int, float, str, and a struct with an impl ord block. Floats are in the order sort uses, so unlike <, cmp puts -0.0 before 0.0 and nan after every other float, with all nans equal.

print(1.cmp(2), "b".cmp("a"), (-0.0).cmp(0.0))   // less greater less

min

T.min(other: T) -> T

Returns the lesser of the value and other, for any type that implements ord, keeping the value itself when they are equal. It compares with <, as math.min does, so 0.0.min(-0.0) is 0.0 and a nan receiver stays nan.

print(5.min(3), "pear".min("apple"))   // 3 apple

max

T.max(other: T) -> T

Returns the greater of the value and other, for any type that implements ord, keeping the value itself when they are equal. It compares with >, as math.max does.

print(5.max(3), 1.5.max(2.5))   // 5 2.5

clamp

T.clamp(lo: T, hi: T) -> T

Returns lo if the value is less than lo, hi if it is greater than hi, and the value itself otherwise, for any type that implements ord. It stops the program if lo is greater than hi, or if either is nan, as Rust’s clamp does.

print(12.clamp(0, 10), (-3).clamp(0, 10), 0.5.clamp(0.0, 1.0))   // 10 0 0.5

abs

(int | float).abs() -> int | float

Returns the number without its sign, as the same type, exactly as math.abs does: -0.0 gives 0.0, and it stops the program with integer overflow in abs for the smallest int, whose absolute value does not fit in an int.

print((-7).abs(), (-2.5).abs(), 3.abs())   // 7 2.5 3

floor

(int | float).floor() -> int

Returns the greatest int that is at most the number, exactly as math.floor does. An int is returned as it is, and a float that is nan or does not fit in an int stops the program.

print((-2.5).floor(), 2.5.floor(), 7.floor())   // -3 2 7

trailing_zeros, leading_zeros

int.trailing_zeros() -> int
int.leading_zeros() -> int

Count the zero bits below the lowest set bit, or above the highest, of the int’s 64 bits, so both give 64 for 0 and a negative int has no leading zeros. Compiled, each is one or a few instructions (tzcnt and lzcnt at x86-64 v3, rbit and clz on arm64), so the number of equal bytes at the start of two 8-byte reads is (a ^ b).trailing_zeros() / 8.

print(40.trailing_zeros(), 40.leading_zeros(), 0.trailing_zeros())   // 3 58 64

display

T.display() -> str

Returns the text print writes for the value, as str does, for any type: every type implements the trait display, and a struct whose impl display block says how to write it uses that.

print([1, 2].display().len())   // 6

send

socket.send(text: str) -> result[int, str]

Sends all of text over the connection and returns ok of the number of bytes sent, or err of the reason it could not, such as broken pipe or connection reset by peer once the other end has closed the connection.

read_line

socket.read_line() -> result[option[str], str]

Waits for the next line from the connection and returns ok of some of it, without its \n or \r\n, or ok(none) once the other end has closed the connection and every line has been read. A last line without a line ending is still a line. Data that is not UTF-8 text is the error not valid UTF-8 text.

use net

fn greeting(host: str, port: int) -> result[str, str]:
    c = net.connect(host, port)?
    ret ok(c.read_line()?.unwrap_or(""))

read

socket.read() -> result[str, str]

Waits for data from the connection and returns ok of whatever has arrived, or ok("") once the other end has closed the connection. A character whose bytes arrive in two parts comes whole with the second read, so the text is never cut inside a character.

read_all

socket.read_all() -> result[str, str]

Reads from the connection until the other end closes it, and returns ok of everything that arrived.

accept

listener.accept() -> result[socket, str]

Waits for the next connection to the listener’s port and returns ok of a socket for it.

port

listener.port() -> int

Returns the port the listener waits on, which is the port the system picked if net.listen was given 0.

close

(socket | listener).close()

Closes the connection, or stops listening, now. A socket or listener also closes by itself right after the last statement that uses it, so close is only needed to close one sooner, as when the other end reads until the connection closes. Once closed, a socket’s methods return err("socket is closed"), and accept returns err("listener is closed").

set_timeout

(socket | listener).set_timeout(seconds: float)

Makes each later wait on the socket or listener give up after seconds with err("timed out"): waiting for data to read, for room to send, or for a connection to accept. The time is per wait, so read_all keeps going for as long as data keeps arriving. It counts in whole milliseconds, rounded up, and zero, a negative number, or nan waits forever, as a new socket or listener does.

use net

l = net.listen("127.0.0.1", 0).unwrap()
l.set_timeout(0.1)
print(l.accept())   // err('timed out'), since nothing connects

send_bytes

socket.send_bytes(data: bytes) -> result[int, str]

Sends all of data over the connection, as send sends text, and returns ok of the number of bytes sent.

read_bytes

socket.read_bytes(max: int) -> result[bytes, str]

Waits for data from the connection and returns ok of what has arrived, at most max bytes, or ok(b"") once the other end has closed it, or at once for a max of 0 or less. Text and byte reads take from the same data, so a protocol can read a line of headers with read_line and then a body with read_exact.

read_exact

socket.read_exact(n: int) -> result[bytes, str]

Waits for exactly n bytes and returns ok of them, or err("connection closed early") if the other end closes the connection first, leaving the bytes that did arrive to read.

use net

fn body(c: socket) -> result[bytes, str]:
    length = int(c.read_line()?.unwrap_or("0"))?
    ret c.read_exact(length)

read_all_bytes

socket.read_all_bytes() -> result[bytes, str]

Reads from the connection until the other end closes it, and returns ok of every byte that arrived.

The os module

os is a builtin module: it has no file, and a program imports it like any other module, with use os to call os.env("HOME"), use os.env to call env("HOME"), or use os as system to call system.env("HOME"). Its names are only reserved once imported, so a program can still have its own env or pid. A file named os.stn next to the entry file cannot be imported, since use os always means this module.

Both stone run and a built program answer from the same C library calls, so they agree on every machine. The examples show values from one machine.

os.env

os.env(name: str) -> option[str]

Returns some of the value of the environment variable name, or none if it is not set, so an empty value, some(""), differs from a missing one. A name that is empty or holds = is never set.

use os

print(os.env("HOME"))                         // some('/home/ada')
print(os.env("NO_SUCH_VARIABLE").unwrap_or(""))   // prints an empty line

os.has_env

os.has_env(name: str) -> bool

Returns whether the environment variable name is set, even to "", as os.env(name).is_some() does.

use os

if os.has_env("DEBUG"):
    print("debugging")

os.platform

os.platform() -> str

Returns the operating system the program runs on: "linux", "macos", or "windows".

os.arch

os.arch() -> str

Returns the processor architecture the program runs on, "x86_64" or "aarch64". A program built with --target aarch64 reports "aarch64" wherever it runs.

os.hostname

os.hostname() -> str

Returns the name of the machine the program runs on.

os.cpu_count

os.cpu_count() -> int

Returns the number of processors that are online, which is at least 1.

os.pid

os.pid() -> int

Returns the process ID of the running program. Under stone run, that is the interpreter’s process.

os.cwd

os.cwd() -> str

Returns the absolute path of the current working directory, the one the program was started from unless something changed it. It stops the program with could not read the current directory if the directory cannot be read, such as after it was deleted.

os.exit

os.exit(code: int)

Stops the program at once with the exit status code. Nothing after it runs, and it prints nothing. The system keeps only the low 8 bits of the status, so os.exit(256) exits with 0 and os.exit(-1) with 255.

use os

if args().len() == 0:
    print("usage: greet NAME")
    os.exit(2)
print("hello", args()[0])

os.run

os.run(cmd: str, args: list[str]) -> result[output, str]

Runs the program cmd with the arguments args, waits for it to finish, and returns ok of an output, a struct from the prelude with three fields:

  • status: int, the status the program exited with, or minus the number of the signal that stopped it (-9 for kill -9), as Python’s subprocess gives it

  • stdout: str, everything it wrote to stdout

  • stderr: str, everything it wrote to stderr

The program gets the environment and working directory of the one that runs it, and reads nothing from stdin, as if it were /dev/null. No shell is involved, so each argument reaches the program exactly as written, spaces and * included; to run a shell command, run os.run("sh", ["-c", "ls *.stn | wc -l"]).

A cmd holding / names the program’s file, relative to the working directory unless it starts with /. Any other cmd is looked for in each directory of PATH in turn, the working directory for an empty one, or /bin and /usr/bin if PATH is not set, as a shell looks. A directory where the file is missing is skipped, and so is one where it cannot be run, though that error is kept in case nothing else runs.

A program that exits with a status other than 0 has still run, so its result is ok: check out.status. Only a program that cannot start is an err, of a message naming cmd, such as no such file or directory: 'gti' or permission denied: './notes.txt', and so is a program whose stdout or stderr is not UTF-8 text, or holds a null byte (not valid UTF-8 text: 'cmd'), and a cmd or argument holding a null character. A file with no #! line is not run through a shell, so it gives exec format error.

On Windows, a cmd holding \ or / names the program’s file, and any other is looked for in each directory of PATH (separated by ;), never in the working directory first. A cmd whose file name has no extension gets .exe, so os.run("git", [...]) finds git.exe. The arguments reach the program on one command line, quoted as Rust’s std::process::Command quotes them, which the C runtime and Rust split back into the same arguments; the program’s own name on it is the path that was found. The status is the exit code, and no program is stopped by a signal. A batch file (.bat or .cmd) is not started directly, since cmd.exe would read its arguments by other rules: it gives exec format error, and os.run("cmd", ["/c", "build.bat"]) runs one. Text a Windows program writes usually ends its lines with \r\n.

use os

out = os.run("git", ["rev-parse", "--short", "HEAD"]).unwrap()
if out.status == 0:
    print("at", out.stdout.strip())
else:
    print("not a repository:", out.stderr.strip())

// ? passes on an err, as anywhere else
fn word_count(path: str) -> result[int, str]:
    out = os.run("wc", ["-w", path])?
    ret ok(int(out.stdout.split()[0]).unwrap_or(0))

The math module

math is a builtin module like os: use math to call math.sqrt(2), or use math.sqrt to call sqrt(2). Since its functions are only reachable through the module, a program can still name its own variables min, max, or abs. A file named math.stn next to the entry file cannot be imported.

Each function takes ints or floats. math.min and math.max never take a mix of the two in one call: convert with float() or int() first, as for arithmetic. The others convert an int argument to a float. Both stone run and a built program compute every result to the same bit, on every machine, since neither calls the system’s math library.

math.abs

math.abs(x: int | float) -> int | float

Returns x without its sign, as the same type, so math.abs(-2.5) is 2.5 and math.abs(-0.0) is 0.0. The smallest int, -9223372036854775808, has no positive counterpart, so its absolute value stops the program with integer overflow in abs.

use math

print(math.abs(-3), math.abs(2.5))   // 3 2.5

math.min

math.min(values: int | float...) | math.min(values: list[int | float])

Returns the least of two or more numbers of the same type, or of the numbers in one list. Equal values keep the first, so math.min(0.0, -0.0) is 0.0. As in Python, a later value only replaces the one kept so far when it is less, so a nan is kept only if it comes first. The least of an empty list stops the program with min of an empty list.

use math

print(math.min(3, 1, 2))          // 1
print(math.min([2.5, 0.5, 1.5]))  // 0.5

math.max

math.max(values: int | float...) | math.max(values: list[int | float])

Returns the greatest of two or more numbers of the same type, or of the numbers in one list, with the same rules as math.min. The greatest of an empty list stops the program with max of an empty list.

use math

fn clamp(x: int, low: int, high: int) -> int:
    ret math.min(math.max(x, low), high)

print(clamp(12, 0, 10), math.max([4, 8, 7]))   // 10 8

math.sqrt

math.sqrt(x: int | float) -> float

Returns the square root of x, correctly rounded, so math.sqrt(2) is 1.4142135623730951. An int is converted to a float first. The square root of a negative number stops the program with math domain error, as in Python, while math.sqrt(-0.0) is -0.0 and the square root of nan is nan.

use math

fn distance(x: float, y: float) -> float:
    ret math.sqrt(x * x + y * y)

print(distance(3.0, 4.0))   // 5.0

math.floor

math.floor(x: int | float) -> int

Returns the greatest int that is at most x, so math.floor(2.5) is 2 and math.floor(-2.5) is -3, where int(-2.5) would drop the fraction and give -2. An int comes back unchanged. A float that is nan or does not fit in an int stops the program with cannot convert float to int (nan or out of range), as int does.

use math

print(math.floor(7.0 / 2.0), math.floor(-0.5))   // 3 -1

math.sin

math.sin(x: int | float) -> float

Returns the sine of x radians, so math.sin(math.pi / 6.0) is 0.49999999999999994, as in Python, since math.pi is not exactly pi. The result is within one ulp (one step between floats) of the exact sine for every x, however large: math.sin(1e22) is -0.8522008497671888. The sine of an infinity stops the program with math domain error, as in Python, and the sine of nan is nan.

Compiled code computes the sine inline, with no call, so the values around it stay in registers, and computes each value once: a second math.sin(x) of the same x reuses the first, and a math.sin(x) and a math.cos(x) reduce x once between them, as C’s sincos does. Only an x of at least 2^20 * pi/2 (about 1.6 million) takes a slower path, which reduces it by pi/2 with the exact bits of 2/pi it needs (Payne and Hanek’s method).

use math

print(math.sin(0), math.sin(math.pi / 2.0))   // 0.0 1.0

math.cos

math.cos(x: int | float) -> float

Returns the cosine of x radians, with the same accuracy and errors as math.sin.

use math

print(math.cos(0), math.cos(math.pi))   // 1.0 -1.0

math.tan

math.tan(x: int | float) -> float

Returns the tangent of x radians, with the same accuracy and errors as math.sin. Since math.pi / 2.0 is a little less than pi/2, its tangent is large rather than infinite: math.tan(math.pi / 2.0) is 1.633123935319537e+16.

use math

print(math.tan(math.pi / 4.0))   // 0.9999999999999999

math.asin

math.asin(x: int | float) -> float

Returns the arcsine of x in radians, from -pi/2 to pi/2, within one ulp. An x greater than 1 or less than -1 stops the program with math domain error, and the arcsine of nan is nan.

use math

print(math.asin(0.5), math.asin(-1))   // 0.5235987755982989 -1.5707963267948966

math.acos

math.acos(x: int | float) -> float

Returns the arccosine of x in radians, from 0 to pi, with the same accuracy and errors as math.asin.

use math

print(math.acos(0.5), math.acos(1))   // 1.0471975511965979 0.0

math.atan

math.atan(x: int | float) -> float

Returns the arctangent of x in radians, from -pi/2 to pi/2, within one ulp. It never fails: the arctangent of an infinity is pi/2 or -pi/2, and of nan is nan.

use math

print(math.atan(1), math.atan(-1e300))   // 0.7853981633974483 -1.5707963267948966

math.atan2

math.atan2(y: int | float, x: int | float) -> float

Returns the angle in radians, from -pi to pi, between the positive x axis and the point (x, y): note that y comes first, as in Python and C. Unlike math.atan(y / x), it knows which quadrant the point is in, so x may be 0, and it is within one ulp, as the others are, since it corrects for the rounding of the quotient y / x that math.atan(y / x) would keep. It never fails, and follows C for zeros and infinities: math.atan2(0, 0) is 0.0, math.atan2(0.0, -0.0) is pi, and math.atan2(-0.0, -1.0) is -pi.

use math

fn degrees(radians: float) -> float:
    ret radians * 180.0 / math.pi

print(math.atan2(1, -1), degrees(math.atan2(3.0, 3.0)))   // 2.356194490192345 45.0

math.pi, math.tau, and math.e

math.pi: float
math.tau: float
math.e: float

The constants pi (3.141592653589793), tau, 2 * pi (6.283185307179586), and e, the base of the natural logarithm (2.718281828459045), each the float nearest the exact value. They are read without parentheses, and use math.pi makes pi alone name it. A constant cannot be called or assigned. Compiled code reads each as an immediate, as it does a literal.

use math
use math.pi

print(math.tau == 2.0 * pi, math.e)   // true 2.718281828459045

The random module

random is a builtin module like os: use random to call random.randint(1, 6), or use random.randint to call randint(1, 6). A file named random.stn next to the entry file cannot be imported.

The numbers come from xoshiro256**, a fast generator whose numbers look random but follow from its seed, so they are fine for games and simulations but not for passwords or keys. After random.seed(n), stone run and a built program draw exactly the same numbers on every machine. Without a seed, the first draw seeds the generator from the system’s entropy, so each run differs.

random.seed

random.seed(n: int)

Starts the numbers over from n, so the same seed always gives the same numbers.

use random

random.seed(42)
print(random.randint(1, 6), random.randint(1, 6), random.randint(1, 6))   // 1 1 6

random.random

random.random() -> float

Returns a float from 0.0 up to but not including 1.0, each of the 2^53 multiples of 2^-53 in that range equally likely.

random.randint

random.randint(low: int, high: int) -> int

Returns an int from low to high, including both, each equally likely, as Python’s random.randint does. A low greater than high stops the program with empty range for randint.

use random

roll = random.randint(1, 6)
print("you rolled", roll)

random.choice

random.choice(items: list[T]) -> T

Returns an element of the list, each equally likely, drawing the same number as random.randint(0, items.len() - 1) would. Since lists are values, the result is a copy that changes independently of the list. An empty list stops the program with cannot choose from an empty list.

use random

print(random.choice(["rock", "paper", "scissors"]))

The time module

time is a builtin module like os: use time to call time.sleep(1), or use time.sleep to call sleep(1). A file named time.stn next to the entry file cannot be imported. In version 0.2.0, time.now and time.clock were os.time and os.clock.

time.now

time.now() -> float

Returns the seconds since 1970-01-01 00:00:00 UTC, with a fraction.

use time

print(time.now())   // 1791512687.8459256

time.clock

time.clock() -> float

Returns seconds from a fixed but arbitrary point, which never go backward, even if the system’s time changes. Only the difference between two calls means anything, which makes it the way to time code:

use time

start = time.clock()
total = 0
for i in range(1000000):
    total += i
print("took", time.clock() - start, "seconds")

time.sleep

time.sleep(seconds: int | float)

Waits for at least seconds, which may have a fraction, so time.sleep(0.25) waits a quarter of a second. The system may wake the program a little later than asked, never earlier. A negative length or nan stops the program with sleep length must be non-negative, and one of 2^63 seconds or more with sleep length is too large.

use time

for i in range(3):
    print(3 - i)
    time.sleep(1)
print("go")

The fs module

fs is a builtin module like os: use fs to call fs.read("notes.txt"), or use fs.read to call read("notes.txt"). A file named fs.stn next to the entry file cannot be imported.

Every function but fs.exists returns a result whose error is a message naming the path, such as no such file or directory: 'notes.txt', so a program decides what a missing file means, or passes the error on with ? from a function that returns result[..., str]:

use fs

fn total(path: str) -> result[int, str]:
    sum = 0
    for line in fs.read_lines(path)?:
        sum += int(line)?
    ret ok(sum)

print(total("numbers.txt"))   // ok(46), or err("no such file or directory: 'numbers.txt'")

A path is relative to the working directory unless it starts with /. The messages are the same under stone run and a built program: the reason the system gives, in lowercase (such as permission denied, is a directory, not a directory, or file exists), or os error N for an error number with no reason in stone’s table. A file, or a name in a directory, that is not UTF-8 text is the error not valid UTF-8 text, and so is a file holding a null byte, since a string cannot hold one.

fs.read

fs.read(path: str) -> result[str, str]

Returns ok of the whole text of the file at path, or err of a message.

use fs

match fs.read("notes.txt"):
    case ok(text):
        print(text.len(), "bytes")
    case err(message):
        print("cannot read:", message)

fs.read_lines

fs.read_lines(path: str) -> result[list[str], str]

Returns ok of the lines of the file at path, without their line endings, or err of a message. A line ends at \n or \r\n, and a file that ends with a line ending has no empty last line, so "a\nb\n" and "a\r\nb" both read as ["a", "b"].

use fs

for line in fs.read_lines("notes.txt").unwrap_or([]):
    print(line)

fs.write

fs.write(path: str, text: str) -> result[int, str]

Writes text to the file at path, creating it or replacing what it held, and returns ok of the number of bytes written, or err of a message. A new file can be read and written by everyone the system’s umask allows.

use fs

fs.write("greeting.txt", "hello\n").unwrap()
print(fs.read("greeting.txt"))   // ok('hello\n')

fs.append

fs.append(path: str, text: str) -> result[int, str]

Writes text to the end of the file at path, creating it if there is none, and returns ok of the number of bytes written, or err of a message.

use fs

for i in range(3):
    fs.append("log.txt", "line " + str(i) + "\n").unwrap()
print(fs.read_lines("log.txt"))   // ok(['line 0', 'line 1', 'line 2'])

fs.read_bytes

fs.read_bytes(path: str) -> result[bytes, str]

Returns ok of every byte of the file at path, text or not, or err of a message.

fs.write_bytes

fs.write_bytes(path: str, data: bytes) -> result[int, str]

Writes data to the file at path, as fs.write writes text, and returns ok of the number of bytes written, or err of a message.

fs.append_bytes

fs.append_bytes(path: str, data: bytes) -> result[int, str]

Writes data to the end of the file at path, as fs.append appends text.

use fs

fs.write_bytes("data.bin", b"\x00\x01").unwrap()
fs.append_bytes("data.bin", bytes([255])).unwrap()
print(fs.read_bytes("data.bin"))   // ok(b'\x00\x01\xff')

fs.list_dir

fs.list_dir(path: str) -> result[list[str], str]

Returns ok of the names in the directory at path, without . and .., sorted by their bytes (so "B" comes before "a"), or err of a message. The names are not paths: join one to path to use it.

use fs

for name in fs.list_dir(".").unwrap():
    if name.endswith(".txt"):
        print(name)

fs.exists

fs.exists(path: str) -> bool

Returns whether there is a file or directory at path, following symbolic links, so a link to nothing does not exist.

fs.remove

fs.remove(path: str) -> result[str, str]

Deletes the file at path and returns ok of path, or err of a message. It does not delete directories.

fs.make_dir

fs.make_dir(path: str) -> result[str, str]

Creates the directory path, whose parent must exist, and returns ok of path, or err of a message, such as file exists: 'out' if something is already there.

use fs

if not fs.exists("out"):
    fs.make_dir("out").unwrap()
fs.write("out/report.txt", "done\n").unwrap()

The net module

net makes TCP connections and Unix-socket connections, and finds the addresses of hosts. Import it like a builtin module, with use net to call net.connect("example.com", 80), or with use net.connect to call connect("example.com", 80). Unlike the other builtin modules, it is written in stone, and a program that uses it is linked with its source, so its functions behave alike under stone run and in a built program, and an editor can show their code. A file named net.stn next to the entry file cannot be imported. TLS (https) is not supported. On Windows, every function but net.connect_unix works: building a program that uses that one for Windows, or running or checking one on Windows, is the error net.connect_unix is not supported on Windows yet.

A connection is a socket, and a port waiting for connections a listener. Both are types a signature can name, as in fn serve(l: listener). A copy of one refers to the same connection, since a connection cannot be copied, and they cannot be compared with ==. Each closes by itself right after the last statement that uses it, at the same point under both backends, or sooner with close. Their methods, send, read_line, read, read_all, send_bytes, read_bytes, read_exact, read_all_bytes, set_timeout, accept, port, and close, are listed with the other methods. Text is sent and read as UTF-8, and other data as bytes, through the same buffer.

use net

fn ask(host: str, port: int, question: str) -> result[str, str]:
    c = net.connect(host, port)?
    c.send("{question}\n")?
    ret c.read_all()

print(ask("localhost", 7777, "hello"))

A program is one thread, so a server handles one connection at a time. A connection to a port the same program listens on completes before the program accepts it, so a program can talk to itself:

use net

l = net.listen("127.0.0.1", 0).unwrap()
c = net.connect("127.0.0.1", l.port()).unwrap()
s = l.accept().unwrap()
c.send("ping\n").unwrap()
print(s.read_line())   // ok(some('ping'))

Errors are messages, as the fs module’s are: the reason the system gives, in lowercase, and the host and port as the program wrote them, such as connection refused: 'localhost:7777', or the reason alone for an error on an open connection, such as connection reset by peer.

Finding addresses

A host is an address, 127.0.0.1 or ::1, or a name. net finds a name’s addresses itself, the same way under both backends:

  1. A name in /etc/hosts has the addresses the file gives it, compared without regard to case.

  2. Otherwise localhost, and any name ending in .localhost, is 127.0.0.1 and ::1.

  3. Otherwise the DNS servers named by nameserver lines in /etc/resolv.conf are asked, as the C library asks them: in turn, waiting timeout seconds for each (5 unless an options line says otherwise), going through them attempts times (2), and trying a name with fewer dots than ndots (1) in each search domain before trying it alone. With no nameserver line, the server on this machine, 127.0.0.1, is asked.

IPv4 addresses come before IPv6 ones. The environment variables STONE_HOSTS and STONE_RESOLV_CONF name other files to read instead, and a nameserver line may give a port of its own, as in nameserver 127.0.0.1:5353, which tests use for a DNS server of their own.

Windows keeps its hosts file and DNS settings elsewhere, so there localhost is still 127.0.0.1 and ::1, but any other name is asked of the system’s resolver (GetAddrInfoW), under both backends, unless STONE_HOSTS or STONE_RESOLV_CONF is set, which makes net find addresses itself as above. A name the resolver does not know is err("unknown host: 'name'"). A name that no server knows is the error unknown host: 'name'.

net.connect

net.connect(host: str, port: int) -> result[socket, str]

Connects to port on host, trying each of the host’s addresses in the order Finding addresses gives them until one connects, and returns ok of the socket, or err of the last address’s error.

net.connect_timeout

net.connect_timeout(host: str, port: int, seconds: float) -> result[socket, str]

Connects as net.connect does, but gives each address at most seconds, counted as set_timeout counts them, after which it is err("timed out: 'host:port'"). The socket it returns waits forever until its own set_timeout.

net.connect_unix

net.connect_unix(path: str) -> result[socket, str]

Connects to the Unix socket at path, a file through which a server on this machine takes connections, such as a display server or /var/run/docker.sock, and returns ok of the socket, which works as one from net.connect does. A path that does not exist is err("no such file or directory: 'path'"), a file that is not a socket err("connection refused: 'path'"), and a path longer than an address holds (107 bytes, or 103 on macOS) err("file name too long: 'path'").

net.ready

net.ready(s: socket, seconds: float) -> bool

Returns whether a read of s would not wait, waiting at most seconds for something to arrive: true once bytes have arrived that no read has taken yet, once the other end has closed the connection, or once s is closed, since a read then fails at once. Zero, a negative number, or nan does not wait, so net.ready(s, 0.0) checks without waiting. Waits are counted as set_timeout counts them.

net.listen

net.listen(host: str, port: int) -> result[listener, str]

Listens for connections to port at the first address of host: 127.0.0.1 for this machine alone, 0.0.0.0 for every IPv4 address, or :: for every address. A port of 0 lets the system pick a free one, which the listener’s port gives. A port another listener holds is the error address already in use.

use net

l = net.listen("0.0.0.0", 8080).unwrap()
while true:
    match l.accept():
        case ok(c):
            c.send("hello\n").unwrap_or(0)
        case err(e):
            eprint(e)

net.resolve

net.resolve(host: str) -> result[list[str], str]

Returns ok of the addresses of host, as text, in the order net.connect tries them, or err of a message.

use net

print(net.resolve("localhost"))   // ok(['127.0.0.1', '::1'])
print(net.resolve("::FFFF:1.2.3.4"))   // ok(['::ffff:1.2.3.4'])

The gui module

gui draws pictures and shows them in windows: a gui.canvas is an image whose pixels a program sets, draws shapes and text on, and saves, and a gui.window shows one on the screen and reports the keyboard and mouse. Import it with use gui. Like net, it is written in stone, and a program that uses it is linked with its source, so it draws the same pixels and sends the display the same requests under stone run and in a built program, and an editor can show its code. A file named gui.stn next to the entry file cannot be imported. The tutorial shows each part at work.

A color is an int, 0xRRGGBB, as gui.rgb makes it. A canvas is a struct of its width, its height, and its pixels, a list of colors in rows from the top left, so the pixel at x, y is pixels[y * width + x]. It is a value like a list: a copy of a canvas is a canvas of its own. Drawing outside a canvas draws nothing there, so a shape may hang over an edge.

use fs
use gui

c = gui.blank(64, 48, gui.rgb(255, 255, 255))
c.disc(32, 24, 16, gui.rgb(240, 190, 50))
c.text(4, 4, "hi", gui.rgb(0, 0, 0))
fs.write_bytes("picture.ppm", c.ppm()).unwrap()

gui.rgb

gui.rgb(r: int, g: int, b: int) -> int

Returns the color with red r, green g, and blue b, each from 0 to 255, as 0xRRGGBB. A value outside that range is taken as the nearest end, so gui.rgb(300, -5, 1) is gui.rgb(255, 0, 1).

gui.blank

gui.blank(width: int, height: int, color: int) -> canvas

Returns a canvas width pixels wide and height high with every pixel color. A negative size is taken as 0.

gui.text_width

gui.text_width(text: str) -> int

Returns how many pixels wide text is when text draws it: 8 for each character.

Canvas methods

Every method but get and ppm changes the canvas it is called on, as append changes a list.

  • c.get(x: int, y: int) -> option[int] returns the color of the pixel at x, y, or none if it is not on the canvas.

  • c.set(x: int, y: int, color: int) makes the pixel at x, y color.

  • c.fill(color: int) makes every pixel color.

  • c.rect(x: int, y: int, width: int, height: int, color: int) fills the rectangle width by height whose top left pixel is at x, y, and c.outline(...), with the same parameters, draws its edge, one pixel wide.

  • c.line(x0: int, y0: int, x1: int, y1: int, color: int) draws a line one pixel wide from x0, y0 to x1, y1, both ends included.

  • c.circle(x: int, y: int, radius: int, color: int) draws the edge of the circle of radius around x, y, and c.disc(...), with the same parameters, fills it.

  • c.blit(source: canvas, x: int, y: int) draws source with its top left pixel at x, y.

  • c.text(x: int, y: int, text: str, color: int) draws text with the top left of its first character at x, y, in letters 8 pixels square from the public-domain font8x8 font. A newline starts a line 8 pixels below, and a character outside ASCII draws as a box. c.text_scaled(x, y, text, color, scale: int) draws each pixel of a letter scale pixels square.

  • c.ppm() -> bytes returns the canvas as a binary PPM image (P6), which most image viewers and converters read, for fs.write_bytes.

Windows

A window speaks the Wayland or the X11 protocol to the display server itself, over a socket from net, so a built program still needs no C library. gui.open uses the Wayland compositor WAYLAND_DISPLAY names, a path or a name in XDG_RUNTIME_DIR (wayland-0 on most desktops), and if there is none or it fails, the X server DISPLAY names. Setting STONE_GUI to wayland or x11 asks for one of them alone. Every Linux desktop has one or the other, and on macOS XQuartz runs an X server.

On Windows (10 version 1703 or later), a window is an ordinary Win32 window, which needs no display server: STONE_GUI may only be unset or windows there. Each window runs its messages on a thread of its own, so moving or resizing it keeps the program drawing, the window follows the scale of the monitor it is on, and next_frame waits for the desktop compositor’s next frame. A built program imports user32.dll, gdi32.dll, and dwmapi.dll only if it opens a window, and stone build --windows-gui makes it a program with windows rather than a console program, so opening it from Explorer opens no console.

On Wayland, a compositor that draws windows’ frames itself (zxdg_decoration_manager_v1, as KDE, Sway, and Hyprland have) draws the window’s; for one that does not, as GNOME’s and WSLg’s do not, gui draws its own: a title bar with the title and a close button, which moves the window when dragged and maximizes it when clicked twice, and edges to resize it by. Keys are named and type text as the compositor’s keymap says, whatever the layout, and a key held down repeats at the compositor’s rate. Images go through memory the program shares with the compositor, and the compositor’s frame callbacks say when each is on the screen.

On X11, the DISPLAY environment variable says where the server is: :0 is the Unix socket /tmp/.X11-unix/X0, a path such as /tmp/launch-x/org.xquartz:0 is that socket, and host:0 is TCP port 6000 on host. A server that asks for one gets the MIT-MAGIC-COOKIE-1 that XAUTHORITY, or ~/.Xauthority, holds for the display. The display must take 24-bit color, as every current one does. On Linux, a server on the same machine that has the MIT-SHM extension (version 1.2 or later, as Xorg, Xvfb, and XWayland have) gets each image through memory the two share rather than through the socket, which is several times faster for a big window; any other server, or one that turns the memory down, gets the image through the socket, with the same result on the screen. A server with the Present extension, as Xorg, Xvfb, and XWayland have, gets each image in a pixmap that it puts on the window at its next vblank, so images never tear, and says when it has.

A window is a handle, like a socket: a copy of it is the same window, and it closes by itself right after the last statement that uses it, or sooner with close. Its methods:

  • w.is_open() -> bool says whether the window is open: until close, or until its connection breaks.

  • w.events() -> list[event] returns the events since the last call, without waiting.

  • w.wait() -> list[event] returns the events since the last call, waiting for one if there are none, or [] once the window is closed.

  • w.next_frame() -> list[event] returns the events since the last call, as events does, once it is time to draw the next image: when the display has put the last image show gave it on the screen, at the screen’s own refresh rate, but after a second at most, as for a hidden window, which the display never shows. Where nothing shown is waiting, or the display cannot tell (an X server without Present), it is about 60 times a second. It waits on the display’s connection, using no processor time meanwhile.

  • w.show(c: canvas) shows the canvas in the window, its top left pixel at the window’s. Where the canvas does not reach, the window keeps what it showed on X11, and is black on Wayland and Windows.

  • w.size() -> tuple[int, int] returns the window’s width and height, as the last resize event gave them.

  • w.scale() -> float returns how many of the screen’s pixels each of the window’s is across: 1.0 at 100%, 2.0 at 200%, 1.5 at 150%.

  • w.set_title(title: str) sets the title on the window’s frame.

  • w.close() closes the window.

A window’s sizes, the points of its events, and the canvases it shows are in logical pixels, which gui shows as w.scale() of the screen’s pixels each, to the nearest, so at 150% a canvas pixel is one or two of the screen’s across. The scale is STONE_GUI_SCALE’s, a number from 0.5 to 8, if it is set, and otherwise the display’s: on Windows the monitor’s, which follows the window to another monitor; on X11 the Xft.dpi resource’s (96 is 100%), or 1.0 without one, which follows the desktop’s changes to it; and on Wayland the compositor’s preferred scale for the window, which may be fractional where the compositor has wp_fractional_scale_v1 and wp_viewporter, or for a compositor that says none, the largest scale of the monitors the window is on. A change of the scale keeps the window’s size in logical pixels and gives a redraw event. A Wayland compositor without wp_viewporter takes whole scales only, so STONE_GUI_SCALE is rounded there. The cursor gui draws on Wayland, where the compositor cannot draw one, is scaled too.

events, wait, next_frame, show, set_title, and close change the window, so each is a statement or the whole value of an assignment, as in es = w.events().

gui.open

gui.open(title: str, width: int, height: int) -> result[window, str]

Opens a window titled title, width by height pixels (each from 1 to 32767), on the display Windows describes, and returns it once it is on the screen. Without a display it is err("no display: neither WAYLAND_DISPLAY nor DISPLAY is set"), a compositor that lacks what a window needs gives err("the Wayland compositor has no xdg_wm_base"), a protocol error gives err("Wayland error: ...") with the compositor’s message, an X server that turns the program away gives its reason, as in err("the X server refused the connection: No protocol specified"), and one whose pixels are not 24-bit color is err("unsupported display format: depth 16, 16 bits per pixel"). A STONE_GUI_SCALE that is not a number from 0.5 to 8 is err("STONE_GUI_SCALE is '3x', but must be a number from 0.5 to 8"), a size outside that range is err("invalid window size: 0x480"), and a STONE_GUI other than wayland or x11 is err("STONE_GUI is 'mac', but can only be 'wayland' or 'x11'"), or on Windows, other than windows, err("STONE_GUI is 'x11', but on Windows can only be 'windows'").

Events

events and wait give a list of gui.event values, an enum matched as case gui.event.key_down(key)::

  • close: the close button was pressed. The window stays open until close is called.

  • resize(width: int, height: int): the window is now this big.

  • redraw: the window lost what it showed, so it should be shown again.

  • key_down(name: str) and key_up(name: str): a key went down or came up. A key that types a character is named by it, in lowercase for a letter ("a", "1", "/"); the others are "space", "enter", "escape", "backspace", "tab", "delete", "insert", "home", "end", "page_up", "page_down", "left", "up", "right", "down", "f1" to "f12", "shift", "control", "alt", "super", "caps_lock", or else "unknown". Holding a key down gives one key_down.

  • text(text: str): a key typed this text, with Shift and Caps Lock applied, again for each repeat while it is held. Keys pressed with Control type nothing.

  • mouse_move(x: int, y: int): the mouse moved to this point of the window.

  • mouse_down(button: str, x: int, y: int) and mouse_up(button: str, x: int, y: int): the "left", "middle", or "right" button went down or came up at this point.

  • scroll(steps: int): the wheel turned a step away from the user (1) or toward them (-1).

  • tick(seconds: float): the seconds since the last tick, which only gui.run gives.

  • failed(reason: str): the connection to the display broke, and the window is closed.

gui.run

gui.run[A: app](title: str, width: int, height: int, state: A) -> result[A, str]

Opens a window as gui.open does and runs the app state in it: it draws the state, then at each frame, as w.next_frame() paces them at the screen’s own rate, gives update every event since the last turn followed by a tick, and draws the state again with a canvas as big as the window. It ends once update has seen the close event, or once done returns true after an event, and returns ok of the last state, or the error that opening the window, or a broken connection, gives.

An app is a value of any type that implements the trait gui.app:

trait app:
    // changes the state for the event; by default nothing changes
    fn update(self, e: event)
    // draws the state on the canvas and returns it
    fn draw(self, c: canvas) -> canvas
    // whether the app is done; by default it is not
    fn done(self) -> bool

update may change self, and draw and done only read it.

The json module

json reads JSON text into values and writes values as JSON text. Import it like a builtin module, with use json to call json.parse(text), or with use json.parse to call parse(text). Like net, it is written in stone, so it behaves alike under stone run and in a built program, and an editor can show its code. A file named json.stn next to the entry file cannot be imported, and a package dependency cannot be named json.

A JSON value is a json.value, an enum a signature can name, as in fn show(v: json.value), and a match can take apart:

enum value:
    null
    boolean(bool)
    integer(int)
    number(float)
    text(str)
    array(list[value])
    object(map[str, value])

A number without a fraction or exponent that fits in an int is an integer, and any other number, such as 1.5, 1e3, or 9223372036854775808, a number. An object keeps its keys in the order they first appear, and a key written twice keeps its last value, as Python’s json does.

use json

doc = json.parse("{{\"name\": \"stone\", \"tags\": [\"fast\", \"safe\"]}}").unwrap()
match json.get(doc, "tags"):
    case some(json.value.array(tags)):
        print(tags.len())   // 2
    case _:
        print("no tags")
print(json.write(doc))   // {"name":"stone","tags":["fast","safe"]}

Neither reading nor writing uses recursion, so values nested as deeply as memory allows are read and written; == and print on a json.value still stop past 1,000 levels. Reading shares one string among the keys that repeat in a document, as the objects of an array usually do.

json.parse

json.parse(source: str) -> result[value, str]

Reads source as one JSON value, which whitespace may surround, as RFC 8259 defines it. It is strict: comments, trailing commas, single quotes, leading zeros, +, NaN, Infinity, control characters inside a string, and unknown escapes are errors. \uXXXX escapes are decoded, a pair of surrogates as one character; a lone surrogate, and \u0000, which no stone string can hold, are errors. An error says what is wrong and where, as err("expected ',' or ']' at line 3, column 7"), the column counting characters, or unexpected end of input at ... when the text stops early.

json.write

json.write(v: value) -> str

Writes v as compact JSON text, as Python’s json.dumps(v, separators=(",", ":"), ensure_ascii=False) writes it: ", \, and control characters are escaped (\n, \t, or \u001b), and any other text is written as it is. A float is written as print writes it, which is what Python writes, and nan and infinity, which JSON cannot hold, are written as null, as JavaScript writes them.

json.pretty

json.pretty(v: value, indent: int) -> str

Writes v as json.write does, but with each item of an array and each entry of an object on a line of its own, indented by indent spaces for each level, and ": " after each key, as Python’s json.dumps(v, indent=indent, ensure_ascii=False) writes it. An empty array or object stays [] or {}.

json.get

json.get(v: value, key: str) -> option[value]

Gives the value of key in v, or none if v is not an object or has no such key.

json.at

json.at(v: value, index: int) -> option[value]

Gives the item at index of v, counting a negative index from the end, or none if v is not an array or has no such item.