Whisker Standard Library Reference
This document describes Whisker’s built-in functions, how its tests are
written and run, and the Go packages a program reaches. Built-in functions
need no import; Whisker has no packages of its own, and a Go package is
imported by its path, as import go "os".
nil prints as nil, and an error prints its message, such as
error: Division by zero.
Built-in Functions (no import required)
Built-in functions are predeclared: a
program may bind any of their names again, and the binding hides the builtin
for the rest of its scope. Named rather than called, a builtin is a function
value, and can be passed to map or piped into like any other.
Output and errors
print(args...)
Print the values to standard output, separated by spaces, followed by a
newline. Answers with nil.
print("Hello", 42, true) // Hello 42 true
print([1, 2, 3]) // [1, 2, 3]
fail(args...)
Raise an error whose message is the arguments joined with spaces. It fails the
expression it is in, which recover can catch.
fn divide(a int, b int) int {
if b == 0 {
fail("division by zero")
}
return a / b
}
print(recover(divide(1, 0), -1)) // -1
print(try(fn() { fail("bad value:", 42) })) // error: bad value: 42
A typed function that ends in fail still needs a return on its other paths.
try(fn)
Call a function of no arguments. If it succeeds, answer with its result; if it fails, answer with the error instead of failing. The error is then a handled value, which can be printed, stored and passed along.
fn divide(a int, b int) int {
if b == 0 {
fail("division by zero")
}
return a / b
}
let result = try(fn() { divide(10, 0) })
print(is_error(result)) // true
print(result) // error: division by zero
print(try(fn() { divide(10, 2) })) // 5
is_error(v)
Report whether a value is an error.
print(is_error(try(fn() { fail("oops") }))) // true
print(is_error(42)) // false
exit([status])
End the program with the given status, 0 to 255; 0 when none is given. Nothing after it runs, and nothing can catch it. A status is how a program tells the shell, cron job or CI step that started it what it found.
A status outside 0 to 255, or one that is not an int, is refused rather than
wrapped — a shell would see only the low eight bits, and exit(256) would read
as success. The program then carries on, and exit answers with an error that
recover can catch.
print(recover(exit(300), "refused")) // refused
exit(1)In the playground there is no process to end, so the run stops where exit was
called and keeps whatever it printed.
Lists
| Function | Meaning |
|---|---|
len(v) | Length of a list (elements), string (bytes) or dict (entries); an error for anything else |
head(list) | First element, or nil for an empty list |
tail(list) | Everything after the first element; [] when there is nothing after it |
append(list, value) | A new list with value added at the end |
map(list, fn) | A new list of fn applied to each element |
filter(list, fn) | The elements for which fn answers true |
reduce(list, init, fn) | Fold the list into one value, from init; fn takes the accumulator and the element |
sort(list) | A copy in ascending order; an error when the elements are not all one comparable kind |
reverse(list) | A copy in the opposite order |
None of them changes the list it is given.
let nums = [1, 2, 3, 4, 5]
print(len(nums), head(nums), tail(nums)) // 5 1 [2, 3, 4, 5]
print(head([]), tail([])) // nil []
print(append(nums, 6)) // [1, 2, 3, 4, 5, 6]
print(map(nums, fn(x) { x * 2 })) // [2, 4, 6, 8, 10]
print(filter(nums, fn(x) { x % 2 == 0 })) // [2, 4]
print(reduce(nums, 0, fn(acc, x) { acc + x })) // 15
print(nums |> map(fn(x) { x * x }) |> reverse) // [25, 16, 9, 4, 1]
print(sort(["pear", "apple"])) // [apple, pear]
print(recover(sort([1, "a"]), "mixed")) // mixed
print(len("hello"), len({"a": 1, "b": 2})) // 5 2
A list holding more than one kind of value has no order: there is no answer to
whether 1 comes before "a", so sort fails rather than invent one.
Strings
| Function | Meaning |
|---|---|
upper(s) / lower(s) | Change case |
trim(s) | Strip leading and trailing whitespace |
replace(s, old, new) | Replace every old with new; an empty old is an error |
pad(s, width) | Pad with spaces to width characters: on the right, or on the left when width is negative; a longer string is not cut |
contains(s, sub) | Whether s contains sub |
index_of(s, sub) | Character offset of the first sub in s, or -1 |
split(s, sep) | Split s around sep; "" splits into characters |
join(list, sep) | Join a list of strings with sep |
slice(s, start, end) | Characters start up to, not including, end |
Positions count characters, not bytes, so text beyond ASCII behaves the way it
reads. In slice, a negative position counts back from the end, positions are
clamped to the string, and an inverted range gives "". Each of these is an
error when handed something other than the strings (and ints) it takes.
print(upper("cat"), lower("CAT")) // CAT cat
print("[" + trim(" cat ") + "]") // [cat]
print(replace("a-b-c", "-", "+")) // a+b+c
print("[" + pad("ab", 5) + "]") // [ab ]
print("[" + pad("ab", -5) + "]") // [ ab]
print(contains("hello,world", "world")) // true
print(index_of("hello,world", "world")) // 6
print(index_of("hello,world", "dog")) // -1
print(split("a,b,c", ",")) // [a, b, c]
print(split("abc", "")) // [a, b, c]
print(join(["a", "b", "c"], "-")) // a-b-c
print(slice("hello,world", 0, 5)) // hello
print(slice("hello,world", -5, 11)) // world
print(slice("こんにちは", 1, 3)) // んに
Conversions
| Function | Meaning |
|---|---|
int(v) | An int from a number (a float is truncated), a bool (1 or 0) or a numeric string |
float(v) | A float from a number or a numeric string |
string(v) | The value as it prints; a non-empty list of bytes becomes its text again |
to_bytes(s) | The UTF-8 bytes of a string, as a list |
to_runes(s) | The characters of a string, as a list of one-character strings |
round(x, places) | x rounded to places decimal places (0 to 15), half away from zero; an int comes back unchanged |
Every conversion is the target type’s name, as
the specification describes: int(x), float(x),
string(x), and the sized types uint8(x), int64(x), float32(x). A
numeric type reads a string as a number, ignoring space around it, and text
that is not one is an error, which recover catches. Everything a program takes
from outside — the environment, a file, an HTTP body — arrives as text, so this
is how a number gets in.
print(int("42") + 1) // 43
print(recover(int("forty"), 0)) // 0
print(int(3.7), int(true)) // 3 1
print(float(42), float("3.5")) // 42 3.5
print(string(7) + " lives") // 7 lives
let big = 300
print(uint8(big)) // 44
print(round(3.14159, 2)) // 3.14
print(round(2.5, 0)) // 3
The elements of a list from to_bytes are byte values, which nothing else
makes: a list written out as [65] holds an int. That is how string tells a
list of bytes from any other list and turns it back into its text. An empty
list is the exception, so string(to_bytes("")) is "[]".
print(to_bytes("ABC")) // [65, 66, 67]
print(string(to_bytes("hello"))) // hello
print(to_runes("ABC")) // [A, B, C]
print(join(to_runes("abc"), "")) // abc
Tests
| Function | Meaning |
|---|---|
assert(cond [, msg]) | Fails unless cond holds |
assert_eq(got, want [, msg]) | Fails unless got and want print the same (it compares printed forms, so assert_eq([1], "[1]") holds) |
assert_not(cond [, msg]) | Fails if cond holds |
seed(values...) | One entry of a fuzz corpus, or one example of a prop_ function |
The assertions work anywhere, not only under whisker test. One that holds
answers with nil; one that fails answers with an error carrying its message,
which fails the enclosing test under whisker test and can be caught with
recover anywhere else.
print(assert(1 == 1, "one is one")) // nil
print(recover(assert(1 == 2, "nope"), "caught")) // caught
See Testing for how test files are run.
Testing
whisker test runs the functions of a test file by their names, and the
assertions are built-in functions, so a test file needs no import.
Test files
A file named foo_test.wsk is a test file. whisker test reads foo.wsk
alongside it, and runs every function named by one of these prefixes:
test_*takes no parameters, and fails when an error escapes it, such as a failed assertion.catwalk_*takes no parameters, and compares what it prints with the// Output:comment block written as the last lines of its body.prop_*is a property, run on generated inputs (see below).fuzz_*is run underwhisker test -fuzzon inputs the Go fuzzer makes, starting from itsseed(...)corpus.
Each pure fn in foo.wsk with an ensures contract is also tried on
generated inputs, and reported as contract of <name>; see
Contracts.
fn add(a int, b int) int { a + b }
fn test_add() {
assert_eq(add(1, 2), 3, "one and two")
}
fn catwalk_greeting() {
print("Hello, Tama!")
// Output:
// Hello, Tama!
}
fn prop_add_commutative(a int, b int) {
seed(3, 4)
assert(a + b == b + a)
}whisker test prints a line per test and a summary, and exits with status 1
if any failed:
PASS: test_add
PASS: prop_add_commutative (100 cases)
PASS: catwalk_greeting
All 3 tests passed!
or, on failure, 5 passed, 2 failed.
Properties
A prop_ function runs on 100 generated inputs, and an unhandled error fails
it. Every parameter needs a type annotation (int, float, bool, string
or list) and there must be at least one. A failing input is shrunk, and the
report shows the shrunk input, the original and the seed:
$ whisker test -seed 42 -prop-count 500 math_test.wsk
FAIL: prop_small - falsified after 5 cases
x = 10
assertion failed: expected truthy value
original: x = 9223372036854775807
seed: 42
-seed <n> replays a run, and -prop-count <n> changes the number of inputs.
A seed(...) example is worked out before the body runs, so it may not use a
parameter or a name the body binds at its top level. The specification’s
Property tests gives the rules in full.
seed(values...)
Written as a statement directly in the body of a fuzz_ function, seed(...)
adds one input to the corpus whisker test -fuzz starts from; its arguments
must be literals (an int, float, string or bool, a number optionally negative),
passed to the parameters in order. In a prop_ function it adds one example,
run first and not counted, and its arguments may be any expression. A seed
nested in a block or used inside an expression is not collected, and anywhere
else seed collects nothing and answers with nil.
fn fuzz_add_commutative(a int, b int) {
seed(1, 2)
seed(0, 0)
assert_eq(a + b, b + a)
}Go packages
Whisker has no packages of its own. A program reaches Go’s with
import go "path", and what a package offers is called with Whisker’s
spelling of its names; the specification’s
Importing a Go package describes how values
cross between the two.
import go "strings"
import go "strconv"
print(strings.repeat("ab", 3)) // ababab
print(recover(strconv.atoi("x"), "not a number")) // not a number
A package is called by the last element of its path (os for "os"). A name
written before the path renames it, which a path such as "math/rand/v2" is
glad of:
import go rand "math/rand/v2"
print(rand.int_n(1) == 0) // true
Go’s own spelling works too: strings.ToUpper and strings.to_upper are the
same function. A Go function that returns an error as its last result gives
an error value when it fails, which try, is_error and recover handle like
any other.
The usual jobs
| To | Import | Write |
|---|---|---|
| Read a file | os | string(os.read_file(path)) |
| Read a file’s lines | os, strings | strings.split(strings.trim_suffix(string(os.read_file(path)), "\n"), "\n") |
| Write a file | os | os.write_file(path, to_bytes(text), 420) (420 is the mode 0644) |
| Read an environment variable | os | os.getenv(name), or os.lookup_env(name) for [value, is_set] |
| Read the program’s arguments | os | tail(os.Args), since the first element is the program itself |
| Tell the time | time | time.now().unix(), or time.now().format(time.RFC3339) |
| Wait | time | time.sleep(100 * time.Millisecond) |
| Pick a random number | math/rand/v2 | rand.int_n(n) below n, rand.float64() below 1 |
| Write JSON | encoding/json | string(json.marshal(value)) |
| Fetch a URL | net/http, io | http.get(url), then io.read_all(resp.body) |
import go "os"
import go "strings"
os.write_file("cats.txt", to_bytes("Tama\nMike\nKuro\n"), 420)
let names = strings.split(strings.trim_suffix(string(os.read_file("cats.txt")), "\n"), "\n")
print(names) // [Tama, Mike, Kuro]
print(recover(os.read_file("missing.txt"), "no such file")) // no such file
An HTTP reply is a record: its fields are read with a dot, and its body is held
by Go and read with io.read_all.
import go "net/http"
import go "io"
let resp = http.get("https://example.com/")
print(resp.status_code) // 200
let page = string(io.read_all(resp.body))
resp.body.close()
print(len(page) > 0) // true
What a program cannot do
- Read JSON into a value.
json.marshalandjson.validwork, butjson.unmarshalfills a Go value that a program has no way to make, so JSON text cannot be turned into a dict or list. - Use a Go type as a value.
time.Secondis a constant and can be multiplied, buttime.Duration(90)names a type, and is a build error. - Run in the playground. It can load no Go package.
Imports Whisker refuses
An import without go names no package: Whisker has none of its own. Such
an import is an error, and the error says what to write instead:
error: "file" is not a Whisker package; use import go "os"
| A program might try | Write instead |
|---|---|
import "file", import "env" | import go "os" |
import "http" | import go "net/http" |
import "clock" | import go "time" |
import "random" | import go "math/rand/v2" |
import "json" | import go "encoding/json" |
import "testing" | nothing: assert, assert_eq and assert_not need no import |
A library, without a wrapper
A library reached this way needs no wrapper. The AWS SDK, for example, resolves credentials and region through its own default chain — environment variables, shared config files, SSO, instance metadata — so a program authenticates as the AWS CLI does on the same machine:
import go cfg "github.com/aws/aws-sdk-go-v2/config"
import go "github.com/aws/aws-sdk-go-v2/service/sts"
let conf = cfg.load_default_config()
let client = sts.new_from_config(conf)
let me = try(fn() { client.get_caller_identity({}) })
if is_error(me) {
fail("not authenticated:", me)
}
print(me["account"])
print(me["arn"])A Go function whose first parameter is a context.Context is given one that
expires thirty seconds after the call starts, and the function has to check it
to stop early. A Go function without a context parameter has no deadline, so a
call such as http.get can run for as long as Go lets it.