Whisker Language Specification

This document defines the syntax and semantics of the Whisker programming language.

Whisker is a small, gradually typed language that reads like Go: a handful of reserved words, fn for every function, type for every type declaration, and no semicolons. Source files use the .wsk extension and are encoded in UTF-8. The whisker command transpiles a program to Go and builds it into a native binary with the Go toolchain; whisker run builds and runs it in one step.

Errors are values that pass through a program until something handles them (see Error Model). An error that nothing handles ends the program with a message such as error: Division by zero.

Notation

This specification uses Extended Backus-Naur Form (EBNF):

Production  = name "=" Expression "." .
Expression  = Term { "|" Term } .
Term        = Factor { Factor } .
Factor      = name | literal | "(" Expression ")" | "[" Expression "]" | "{" Expression "}" .
  • [ ... ] denotes optional (0 or 1).
  • { ... } denotes repetition (0 or more).
  • " ... " denotes terminal symbols.

Source Code Representation

Source code is UTF-8 encoded text in .wsk files. Newlines terminate statements; semicolons are not used. A line that begins with |> continues the expression on the line above (see Pipe Expression). The compiler reads one .wsk file at a time.

Lexical Elements

Comments

LineComment  = "//" { any_char } newline .
BlockComment = "/*" { any_char } "*/" .

A line comment starts with // and runs to the end of the line. A block comment starts with /*, ends with the first */, and may span lines. Block comments do not nest. Comments are treated as whitespace.

# is not a comment in Whisker.

Reserved Words

Exactly these 11 words are reserved. None of them can be used as a name:

keyword = "let" | "fn"    | "return"   | "if"    | "else"   | "for"
        | "break" | "continue" | "match" | "type" | "import" .

let x = 1 binds x; let for = 1 is a syntax error.

Contextual Keywords

These words have a meaning in one position only, and are ordinary names everywhere else:

WordWhere it means somethingMeaning
structafter type Namea struct (or sum) type
interfaceafter type Namean interface type
purebefore fn at the start of a declarationa pure function
requires, ensuresafter a function’s or method’s signature, before its bodya precondition, a postcondition
resultinside an ensures clausethe value the function returns
inafter the loop variables of forthe subject of a loop
godirectly after importthe path names a Go package

let in = 1, let struct = 2, let pure = 3 and let requires = 4 are valid bindings.

Predeclared Identifiers

These names are bound before the program starts. They are not reserved: a program may bind any of them again, and the new binding hides the predeclared one for the rest of its scope.

KindNames
Constantstrue false nil
Functionsprint fail map filter reduce and the other built-in functions
Typesint int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float float32 float64 byte rune bool string error list dict
let print = 1      // valid: print is now an int in this scope
let true = 0       // valid, though unwise

Identifiers

identifier = letter { letter | digit } .
letter     = "a" ... "z" | "A" ... "Z" | "_" .
digit      = "0" ... "9" .

Identifiers name bindings, functions, types, fields and methods. By convention, values and functions use snake_case and types use PascalCase.

Integer Literals

int_lit = digit { digit } .

An integer literal is a sequence of decimal digits. Its value is exact; the type it takes is decided by where it is used (see Integers). A literal may be as large as 18446744073709551615, the largest uint64.

Float Literals

float_lit = digit { digit } "." digit { digit } .

A float literal has a decimal point with digits on both sides, and is a 64-bit IEEE 754 number unless its context gives it float32.

String Literals

string_lit = '"' { char | escape } '"' .
escape     = "\" ( '"' | "\" | "n" | "t" | "r" ) .

Operators and Delimiters

Operators:
  +    -    *    /    %
  =    ==   !=   <    >    <=   >=
  &&   ||   !
  |>   .    ..   =>

Delimiters:
  (    )    {    }    [    ]    ,    :

Operator precedence, from loosest to tightest:

PrecedenceOperators
1||
2&&
3== !=
4< > <= >=
5|>
6+ -
7* / %
8unary ! -
9call (), index [], member .

Types

Whisker is gradually typed. Every value carries its type at run time, so a program whose bindings and lambda parameters carry no annotations still runs, and a wrong operation is an error when it happens. An annotation states a type ahead of time: the checker then refuses a program that contradicts it before it runs, and the compiler generates native Go code for the annotated parts instead of code that handles any value. Where an annotation is left out, the type is inferred when it can be, and is otherwise unknown until the program runs.

Annotations are optional on bindings and lambda parameters, and required on the parameters of a named function and on its result when it returns a value.

Primitive Types

TypeDescription
int64-bit signed integer; the default integer type
int8 int16 int32 int64signed integers of that many bits
uint64-bit unsigned integer
uint8 uint16 uint32 uint64unsigned integers of that many bits
bytealias for uint8
runealias for int32
floatalias for float64
float32 float64IEEE 754 floating point of that many bits
booltrue or false
stringUTF-8 text

An alias and the type it names are the same type: a byte is a uint8.

Other Types

TypeDescription
erroran error value carrying a message (see Error Model)
listordered collection: [1, 2, 3]
dictstring-keyed dictionary: {"key": value}
fn(T1, T2) Ra function type
nilthe absence of a value

A list written out with one kind of element in it is a list of that kind, and one written with several holds anything: [1, 2, 3] holds ints, [1, "a"] holds whatever it holds. Nothing is refused for being mixed; what changes is only how much is known about an element before the program runs.

The program declares further types with type: aliases, new types, structs, sum types and interfaces (see Type Declarations).

Type Expressions

TypeExpr     = identifier | FuncTypeExpr .
FuncTypeExpr = "fn" "(" [ TypeExpr { "," TypeExpr } ] ")" [ TypeExpr ] .

A type name is an identifier: a predeclared type, or one the program declared with type.

A function type is written the way a function’s head is: fn, the parameter types in parentheses, and the result type. It can stand anywhere a type can, so a higher-order function can say what it takes and what it gives:

type Pred = fn(int) bool

fn twice(f fn(int) int, x int) int { f(f(x)) }
fn adder(n int) fn(int) int { fn(x int) { x + n } }

print(twice(adder(3), 1))       // 7

The result type may be left out (fn(string)), and is then unknown, as a lambda’s is. A function type is satisfied by any function of the same number of parameters whose known types agree with it; a type left unknown on either side agrees with anything, so fn(x) { x + 1 } is a fine fn(int) int. A value whose type is known and is not a function cannot be called.

Integers

Default type

An integer literal whose type nothing decides is an int:

let n = 42          // int
let b uint8 = 42    // uint8: the annotation decides

A literal used with a value of a known integer type takes that type, as an untyped constant does in Go:

let x uint8 = 200
let y = x + 1       // the 1 is a uint8; y is a uint8

Mixing types is an error

Arithmetic and comparison need both operands to have the same numeric type. Mixing two different integer types — signed with unsigned, or two sizes — is a compile error. Convert one of them explicitly.

let a int = 1
let b uint = 2
a + b               // error: mismatched types int and uint
a + int(b)          // 3

int and float do not mix either: 1 + 2.5 is refused with Cannot add int and float, and 1 < 2.5 with Cannot compare int and float. Write float(1) + 2.5. When the types are known only at run time, the same operation is an error then (Cannot add Int and Float). The sized types (int8 … uint64, float32) mix with nothing but themselves.

Out-of-range literals are an error

A literal that does not fit the type it takes is a compile error:

let b uint8 = 300   // error: 300 overflows uint8
let u uint = -1     // error: -1 overflows uint

Overflow wraps around

Arithmetic that leaves the range of its type at run time wraps around, as it does in Go:

let x uint8 = 255
print(x + 1)        // 0

let y int8 = 127
print(y + 1)        // -128

Conversions

A type’s name called with one argument converts the argument to that type: int(v), float(v), string(v), uint8(v), int64(v), float32(v). This is the only way to convert.

string(v) gives any value as it prints, except a non-empty list of bytes from to_bytes, which it turns back into the text. A numeric type takes a number or a string, and int also takes a bool, as 1 or 0. The names are function values too, and map(xs, int) takes the same inputs as int(x). A string is read as a number of that type, ignoring space around it. Text that is not one, or one outside the type’s range, is an error:

print(string(42) + "!")   // 42!
print(int("42") + 1)      // 43
print(float(" 3.5 "))     // 3.5
print(recover(uint8("300"), 0)) // 0

Between numbers, converting an integer to a smaller integer type keeps the low bits; converting between signed and unsigned of the same size reinterprets the bits. Converting a float to an integer truncates toward zero.

let big = 300
print(uint8(big))   // 44
let n = 200
print(int8(n))      // -56
print(int(3.9))     // 3

Converting an integer literal that does not fit the target type is a compile error, as it is in Go: uint8(300) written with the literal itself is refused; uint8(big) with a value known only at run time wraps.

Division by zero

Integer division or remainder by zero does not stop the program. It is an error, which recover catches like any other:

let z uint = 0
print(recover(1 / z, 0))  // 0
print(1 / z)              // error: Division by zero

Values without an annotation

A sized integer keeps its type wherever it goes, including through bindings, parameters and lists that carry no annotation. print shows its value in full:

let max uint64 = 18446744073709551615
let copy = max
print(copy)         // 18446744073709551615

Expressions

Literals and Names

ListLit  = "[" [ Expr { "," Expr } [ "," ] ] "]" .
DictLit  = "{" [ DictEntry { "," DictEntry } [ "," ] ] "}" .
DictEntry = string_lit ":" Expr .

true, false and nil are the predeclared constants. A name evaluates to the value it is bound to. A dict’s keys are string literals.

print(nil) prints nil, and an error prints its message, such as error: Division by zero. A struct prints as Point{x: 1, y: 2}, a new type as UserId{value: 42}, and a variant of a sum type the way it is written, Circle(1.5).

Unary and Binary Expressions

UnaryExpr  = ( "!" | "-" ) Expr .
BinaryExpr = Expr binary_op Expr .
binary_op  = "+" | "-" | "*" | "/" | "%" | "==" | "!=" | "<" | ">" | "<=" | ">="
           | "&&" | "||" .
  • - negates a number. ! negates a bool, and accepts a value of any other type too, inverting its truthiness: !0 is true.
  • Arithmetic (+, -, *, /, %) needs operands of the same type (see Integers). + also joins strings.
  • Ordering (<, >, <=, >=) works on numbers of the same type.
  • Equality (==, !=) needs operands of the same type: 1 == "one" is an error. There are two exceptions. Either side may be nil whatever the other is, since “is this missing?” may be asked of any value; nil equals only nil. And any two values of new types may be compared: two of the same type compare their underlying values, and two of different types are never equal. Two different struct types are not excepted.
  • && and || need bool operands wherever the checker can tell their types (see Truthiness for the operands whose type is known only at run time), and evaluate the right side only when the left does not decide the answer.
let m = {"a": "A"}
print(m["missing"] == nil)                     // true

type Temperature int
type Humidity int
print(Temperature(72) == Temperature(72))      // true
print(Temperature(72) == Humidity(72))         // false

Call Expression

CallExpr = Expr "(" [ Expr { "," Expr } ] ")" .

A call applies a function, a lambda, a method, a built-in, or a type’s constructor, to its arguments.

Arity. Calling a function with fewer arguments than it takes is a partial application: add(5) is a function waiting for the rest. Calling it with more is an error. A built-in called with the wrong number of arguments is refused before the program runs, with the position of the call:

fn add(a int, b int) int { a + b }
let add5 = add(5)
print(add5(3))                  // 8

print(lower())                  // error: lower requires 1 argument(s), got 0
print(3.14159 |> round)         // error: round requires 2 argument(s), got 1

A pipe’s left side is one of the arguments counted.

Functions are values. A function named rather than called is the function itself, and can be bound, piped into, or passed along like any other value. A built-in named rather than called is the built-in itself; the number of arguments it takes travels with it, so one called through a binding with the wrong number answers with an error:

fn double(n int) int { n * 2 }
let twice = double
print(twice(21))                // 42
print(map([1, 2, 3], double))   // [2, 4, 6]

let f = upper
print(f("hi"))                  // HI
let g = lower
print(recover(g(), "wrong count"))  // wrong count

Names. Which declaration a name reaches is settled where it is written. A binding takes the name over for as long as it is in scope, whatever it holds, and this covers a built-in and a type’s constructor as well as a function:

let upper = fn(s) { "shadowed:" + s }
print(upper("hi"))              // shadowed:hi

A parameter and a loop variable are bindings too. whisker lint warns where a binding hides a built-in.

Errors as arguments. Calling a function value — a lambda, or a function held in a binding — with an error among its arguments does not run it: the call answers with that error. A named function whose parameter is typed error receives it.

Recursion. A compiled program recurses as deep as Go’s stack allows; the playground, which runs programs without a Go toolchain, bounds the depth, and a call nested deeper than its limit is an error. A self tail call takes no depth at all: when a top-level function’s return calls that same function with every argument, the function starts over with the new arguments instead of nesting a call, and runs in constant space however deep it goes:

fn count(n int, acc int) int {
  if n == 0 { return acc }
  return count(n - 1, acc + 1)    // a tail call
}
print(count(10000000, 0))         // 10000000

The arguments are worked out before the next turn begins. Only a call of the function to itself counts: a call inside a lambda or a nested function, one written as a pipe, and a method calling itself are ordinary calls, and so is any call in a function with a contract.

Lambda Expression

LambdaExpr = "fn" "(" [ ParamList ] ")" Block .

A lambda is fn without a name, and declares no result type: its result type is inferred. A body that is one expression yields that expression. A longer body yields what return hands back, or, when it ends with an expression statement, that expression’s value; a body that does neither yields nil. return in a lambda returns from the lambda, not from the function around it.

let double = fn(x) { x * 2 }
let add = fn(a int, b int) { return a + b }
let twice = fn(x) {
  let y = x * 2
  y                  // the result
}

A lambda may read the bindings in scope where it is written.

Index and Member Expressions

IndexExpr  = Expr "[" Expr "]" .
MemberExpr = Expr "." identifier .

An index reaches a list element by zero-based position, or the value stored under a key of a dict. A position outside the list is an error; a key that is not in the dict gives nil.

A member reaches a field of a struct, the value inside a new type (.value), a method, or a member of an imported Go package. A member read rather than called is a value of its own: a field is what it holds, and a method is that method bound to what it was reached through, a function like any other:

type User struct { name string }
fn (u User) hi() string { "hi " + u.name }

let u = User("mike")
let say = u.hi
print(say())                    // hi mike

When the value a member is reached through is an error, the member is that error too, and so is a call of it: an error passes along a chain untouched until something handles it.

Chains

A call, an index and a member are postfix forms, and each can follow any operand: a name, a literal, a parenthesized expression, or another postfix form. They chain in any order and read left to right:

type Point struct { x int, y int }
fn (p Point) show() string { string(p.x) + "," + string(p.y) }
fn adder(n int) fn(int) int { fn(x int) { x + n } }
let points = [Point(1, 2)]
let handlers = [fn(x) { x * 2 }]

print(adder(1)(2))              // 3: a call of what a call returned
print(handlers[0](3))           // 6: a call through an index
print(points[0].show())         // 1,2: a method of an indexed element
print(fn(x) { x * 2 }(5))       // 10: a lambda called where it is written
print((5 |> Point(6)).x)        // 5: a member of a parenthesized expression

A postfix form binds tighter than any operator: a - b.c subtracts b.c, and -f(1) negates the call. A postfix form continues the expression only on the line it is written on: a line that opens with ( or [ starts an expression of its own.

Pipe Expression

PipeExpr = Expr "|>" Expr .

Passes the left value as the first argument of the right side:

x |> f(y)       // f(x, y)
x |> f          // f(x)

A line that begins with |> continues the expression on the line directly above it:

[1, 2, 3, 4]
  |> filter(fn(x) { x % 2 == 0 })
  |> map(fn(x) { x * x })
  |> print

The continuation reaches exactly one token past the newline, so a blank line or a comment between two stages ends the statement. A |> that opens a statement is an error.

Recover

RecoverExpr = "recover" "(" Expr "," Expr ")"
            | Expr "|>" "recover" "(" Expr ")" .

recover(x, fallback) is x, unless x fails; then it is fallback. A function as the fallback receives the error. x |> recover(fallback) is the same, written at the end of a pipe.

fn risky() int {
  fail("no luck")
  return 1
}
fn parse(n int) int { n * 2 }

print(recover(risky(), 0))                          // 0
print(recover(risky(), fn(err error) { -1 }))       // -1
print(risky() |> parse() |> recover(0))             // 0

recover looks like a call but is not one: x is watched while it is worked out, so a failure anywhere inside it is caught, including one raised in a typed function. A program that declares a function or type named recover anywhere, or binds the name in scope, calls its own instead.

Match Expression

MatchExpr = "match" Expr "{" { MatchArm } "}" .
MatchArm  = Pattern [ "if" Expr ] "=>" Expr [ "," ] .
Pattern   = CtorPattern | LitPattern | RangePattern | "_" .
CtorPattern  = Constructor "(" [ SubPattern { "," SubPattern } ] ")" .
SubPattern   = identifier | Pattern .   (* a lower-case identifier binds the field *)
RangePattern = PrimaryExpr ".." PrimaryExpr .
LitPattern   = PrimaryExpr .

match works out its subject and tests it against each pattern in order. Its value is the body of the first arm whose pattern matches and whose guard, if it has one, holds. If no arm matches, the value is nil; in a function whose result type is a native type such as int or string, that is an error. Put a _ arm last to be sure of a value.

A literal pattern is a primary expression: a literal, a name, a - followed by a number, a parenthesized expression, or one of these followed by a member, call or index. It is not an arbitrary binary expression: write (k * 2) => ..., not k * 2 => .... A name in a literal pattern is compared with the subject, not bound to it. A range pattern lo..hi is inclusive, and its bounds are worked out when the match runs, so they may be negative or names; a bound or subject that is not a number never matches. _ matches anything.

let size = fn(n) {
  match n {
    0 => "zero",
    1..10 => "low",
    _ => "other"
  }
}
print(size(0), size(5), size(11))   // zero low other

Constructor Patterns

A capitalized name followed by parentheses is a constructor pattern. It matches a value built by that constructor — a variant of a sum type, a struct, or a new type — and matches each field, in declaration order, against the pattern in its position. Inside the parentheses a lower-case name binds the field: taking the value apart is what the parentheses are for. _ ignores a field, a literal compares it, and constructor patterns nest.

type Option struct {
  Some(value)
  None
}

let describe = fn(found) {
  match found {
    Some(0) => "zero",
    Some(Some(x)) => "nested " + string(x),
    Some(x) => "got " + string(x),
    None => "nothing"
  }
}
print(describe(Some(Some(2))))   // nested 2
print(describe(None))            // nothing

A name bound by a pattern is visible in that arm’s guard and body only, and may be bound once per pattern. The case of the name is what separates Some(x), which takes a value apart, from limit(x), which calls a function and compares the subject with its result. A constructor written alone, as None is above, is a literal pattern.

Guards

if after a pattern adds a guard: a bool condition tested once the pattern has matched, with its bindings in scope. When the guard does not hold, matching continues with the next arm.

type Option struct {
  Some(value)
  None
}

let reading = fn(r) {
  match r {
    Some(t) if t > 30 => "hot",
    Some(t) => "fine",
    None => "no reading"
  }
}
print(reading(Some(35)))   // hot

Exhaustiveness

A match that takes apart a sum type — because its subject is known to be one, or because an arm names one of its variants — must cover every variant. One that leaves a value out is a compile error that names it:

type Option struct {
  Some(value)
  None
}

let a = fn(found) { match found { Some(x) => x } }
// error: match does not cover None; add an arm for it or a _ arm
let b = fn(found) { match found { Some(x) if x > 0 => x, None => 0 } }
// error: match does not cover Some(_); add an arm for it or a _ arm

An arm with a guard covers nothing for certain, since its guard may fail, and a literal in a field position covers only that value, except that true and false together cover a bool. An arm of _ covers everything. Every variant an arm names must belong to the same sum type. A match that takes apart only structs and new types need not cover every value.

Statements

Binding

LetStmt = "let" identifier [ TypeExpr ] "=" Expr newline
        | identifier "=" Expr newline .

let binds a name to a value. x = 1 without let declares x just as let x = 1 does. A binding cannot be rebound: writing x = ... for a name already bound in the same scope is a compile error, not an assignment.

A binding at the top level of the program belongs to the whole program, so a function can read it even when the function is written above it. Its value exists only once its line has run, though, and a function called before then fails:

fn greet() string { return label }
let label = "tama"
print(greet())                  // tama

fn early() string { return later }
print(early())                  // error: later is used before it is bound
let later = "too late"

That failure is an error like any other, which recover catches. A name bound nowhere at all is refused before the program runs.

Function Declaration

FuncStmt  = [ "pure" ] "fn" identifier "(" [ ParamList ] ")" [ TypeExpr ]
            { Contract } Block .
Contract  = ( "requires" | "ensures" ) Expr .
ParamList = Param { "," Param } .
Param     = identifier [ TypeExpr ] .
Block     = "{" { Stmt } "}" .

Every parameter of a named function needs a type, and a function that returns a value needs a result type. Grouped parameters share the type that follows them: in fn add(a, b int), both are int. A function without a result type returns nil.

A function that declares a result type and whose body is exactly one expression statement returns that expression, as a lambda does: return may be left out. What counts is one expression, not one line, so a pipe that spans lines qualifies. A body of more than one statement still needs return on every path, and a function without a result type returns nothing, whatever its body ends with. The same holds for methods.

fn greet(name string) string {
  return "Hello, " + name + "!"
}

pure fn square(x int) int { x * x }   // the same as { return x * x }

fn total(xs list) int {
  xs
    |> filter(fn(x) { x > 0 })
    |> reduce(0, fn(a, x) { a + x })
}

Nested Functions

A function may be declared inside another. It is visible only within the block it is written in (an if or for body has its own scope), it may read the enclosing scope, and it hides a top-level function of the same name. A nested function may call itself, and a sibling written after it; calling one before its declaration has run is an error.

fn outer(x int) int {
  fn inner(y int) int { x + y }
  return inner(10)
}
print(outer(5))     // 15

Pure Functions

A pure fn may call only other pure functions and side-effect-free builtins: the operators, the conversions, len, is_error, head, tail, append, map, filter, reduce, sort, reverse, round, and the string builtins. Calling print, fail, try, a Go package member, or a function that is not pure from one is a compile error. Lambda bodies are checked too, so an impure lambda handed to map is refused, and so is naming an impure function as a value — binding it, passing it, or returning it.

The rule is about the declaration a name reaches, not the name: a pure body may bind a name of its own that happens to be the name of an impure function.

Contracts

Between the signature and the body, any number of contract clauses may be written: requires <expr> is a precondition, ensures <expr> a postcondition, and inside an ensures clause result is the returned value. The clauses keep the order they were written in, may share the signature’s line or sit on lines of their own, and are allowed on named functions and methods, not on a lambda. whisker fmt writes each clause on its own line, indented two spaces, with the opening brace on a line of its own.

pure fn abs(x int) int
  requires x > -9223372036854775807
  ensures result >= 0
{
  if x < 0 { return -x }
  return x
}

Every clause is checked each time the function runs, under whisker run, whisker build and whisker test alike: the requires clauses on the way in, in order, and the ensures clauses on the value about to be returned, whichever return it comes from. A violation is an error carrying error: abs: requires x > 0 was violated or error: abs: ensures result >= 0 was violated (result = -3), which recover catches. Only the clause that failed is named.

A clause must be a bool, may call only pure functions and side-effect-free builtins (a function need not be pure to carry a contract, but its clauses always are), and sees the parameters and the top-level bindings but not the locals of the body. result exists only in ensures, in a function that returns a value, and a parameter called result clashes with it. A clause with no expression, a contract on a lambda, and result outside an ensures are syntax errors.

Three tools use contracts:

  • whisker test tries the contract of each pure fn in the file under test (foo.wsk for foo_test.wsk) that has an ensures and whose parameters are all annotated with a type that can be generated (int, float, bool, string, list). It runs the function on 100 generated inputs (-prop-count, -seed), throwing away those that do not satisfy a requires, and reports PASS: contract of abs (100 cases) or FAIL: contract of abs with the smallest input found and the seed. When 90% or more of the inputs fail a requires, the function is reported as SKIP.
  • whisker verify proves a contract for every input; see Verify.
  • whisker export lean <file> writes each pure function as a Lean 4 definition and each ensures as a theorem, with its requires as hypotheses and sorry for its proof, to be proved in Lean.

Verify

whisker verify <files...> hands each pure fn that has a contract to the z3 solver, which must be on the PATH, and asks whether some input satisfies every requires and still breaks an ensures. Integers are bit vectors of their own width, so overflow wraps around as it does in the program. A division adds the question whether its divisor can be zero. A call of another pure function is not expanded: its requires is proved at the call and its ensures is assumed of the value it returns, so each function is proved once, against its own contract. A function whose proof relies on the contract of a callee that is not itself proved is reported as unknown, and so is a counterexample that depends on what a callee promises rather than on what it does.

ReportMeaningExit status
proved: fno input breaks the contract0
counterexample: f (x = -9223372036854775808)this input does; the clause it breaks follows1
unknown: f (reason)z3 did not decide in time (-timeout, default 10s per obligation)1
skipped: f (reason)outside what is translated: a loop, recursion, a float, a string, a list or a dict0

Without the requires clause, the abs above is disproved:

counterexample: abs (x = -9223372036854775808)
  breaks: ensures result >= 0

since -x wraps around for the smallest int. A file with no pure function that has a contract says so and exits 0. Without z3 on the PATH the command says how to install it and exits 1.

Return Statement

ReturnStmt = "return" [ Expr ] newline .

Returns from the innermost function or lambda, with the value if one is given.

If Statement

IfStmt = "if" Expr Block [ "else" ( IfStmt | Block ) ] .

The condition is written without parentheses and must be a bool: if 5 { … } is refused with Condition must be bool, got int. A condition whose type is known only at run time is tested by its truthiness.

let n = 9
if n % 15 == 0 {
  print("FizzBuzz")
} else if n % 3 == 0 {
  print("Fizz")
} else {
  print(n)
}
// Fizz

For Statement

ForStmt   = "for" [ Expr ] Block
          | "for" identifier [ "," identifier ] "in" RangeExpr Block .
RangeExpr = Expr [ ".." Expr ] .
BreakStmt    = "break" .
ContinueStmt = "continue" .
FormMeaning
for cond { … }repeat while cond holds, tested before each turn
for { … }repeat until break
for x in xs { … }each element of a list, or each key of a dict
for i, x in xs { … }index and element (key and value for a dict)
for i in a..b { … }a to b, inclusive
for i in n { … }0 to n - 1

break leaves the nearest loop; continue starts its next turn. Both belong to the nearest enclosing for, and neither may be written outside one, including inside a lambda or a function declared in a loop body, since those run when they are called rather than as part of the turn.

for x in [1, 2, 3, 4] {
  if x == 4 { break }       // stop here
  if x == 2 { continue }    // skip this one
  print(x)                  // 1, 3
}
for k, v in {"b": 2, "a": 1} {
  print(k + string(v))      // a1, b2
}

The condition of for cond must be a bool. Because bindings cannot be rebound, such a loop cannot count its own way to a stopping point: its condition is about something the loop does not change, and it usually ends with break once the body has what it came for. A condition that is already false means the body never runs.

A dict is walked in sorted key order, so a program’s output does not change from run to run.

The count and element forms are written the same way, so which one a loop means depends on its subject: a list is walked element by element, a dict by key, and anything else is read as a count. When the subject’s type is known ahead of time the choice is made while compiling; otherwise it is made when the loop runs, with the same answer.

Import Statement

ImportStmt = "import" [ "go" ] [ identifier ] string_lit newline .

import go "github.com/x/y" brings in a Go package. A name before the path renames the package: import go yml "gopkg.in/yaml.v3". Whisker has no packages of its own, so an import without go is an error, and the error says what to write instead, as import go "os" for import "file"; the standard library reference lists them.

Importing a Go package

With go, the string is a Go import path, and any Go package can be named. Nothing has to be written for it first: the call is made through a bridge, which reads what Whisker has a shape for and holds what it has not.

import go "strings"
import go u "net/url"

print(strings.to_upper("whisker"))       // WHISKER

let parsed = u.parse("https://example.com/a/b")
print(parsed.host)                       // example.com

Names. The package is called by the last element of its path — url for "net/url" — except that a major-version element belongs to the module, so "github.com/x/y/v2" is y. When that leaves a name a program cannot write, such as one that is a reserved word or holds a -, a name before the path gives it one. Go names are spelled the way Whisker writes names: strings.to_upper is strings.ToUpper, and sts.new_from_config is sts.NewFromConfig. A name holding an initialism cannot be spelled this way, so it is written as Go writes it: strings.ToValidUTF8. A wrong spelling is a build error naming the spelling that exists. A Go method String() is written .string().

Results. What comes back is read if Whisker has a shape for it and held if not. A record becomes a dict, under the names a Whisker program writes, and a field is read with a dot as well as by key: p.host and p["host"] are the same, and so is Go’s own spelling, resp.StatusCode for resp.status_code. Only a Go struct has fields read this way, and a method the name spells exactly is the method even when a field has the same name in lower case; that field is then read by key. A time.Time becomes its text; a trailing error becomes a Whisker error, which recover catches. A client, a connection, a handle — anything with methods and nothing to read — is held whole, and the next call is made on it:

import go "regexp"

let re = regexp.must_compile("[0-9]+")
print(re.find_string("abc 123 def"))     // 123

What is read also remembers what it was read out of, so it can still be called on and handed to the next call as itself:

import go u "net/url"
import go "time"

let p = u.parse("https://example.com/a/b?x=1")
print(p.host)                            // example.com
print(p.hostname())                      // example.com

let d = time.ParseDuration("90m")
print(d)                                 // 5400000000000
print(d.minutes())                       // 90

A method is found by the spelling Go gives it, or by one differing only in its capitals when that names exactly one method. A method that wants a pointer can be called on a record held by value: it is called on a copy. A dict the program wrote itself remembers nothing, and is built into the Go record a call asks for.

What was read is a reading, taken when it was taken. A Whisker value cannot be changed once made, and the Go value behind it can be, by a call or a method; after such a call the two say different things. A method with nothing of its own to return gives back a fresh reading of what it was called on, so the change has somewhere to show:

import go u "net/url"

let q = u.ParseQuery("x=1&y=2")
print(q.set("z", "9"))                   // {x: [1], y: [2], z: [9]}
print(q)                                 // {x: [1], y: [2]}

A method with nothing to say is not the same as one whose answer is nothing: a search that found nothing answers nil, and a method that failed answers with an error.

Some things are held where they would otherwise be read wrongly: a whole number past what an int can say, which shows as <uint64 18446744073709551615> and goes back into a call exactly as it came; a record with no field to read and methods to call, which shows as what it says of itself; a record met again while it is being read, and anything more than 64 levels down. A pointer to a plain number or text is read as that value, and .deref() reads it again.

Arguments. A function taking an empty interface — fmt.Sprintf, json.Marshal — gets the plain Go value behind the Whisker one: what was read out of Go arrives as the Go value it was, and what the program wrote itself arrives as a plain one, a list as a slice and a dict as a map. A list of bytes from to_bytes arrives as a []byte. An interface with methods can be satisfied only by something held from Go. A function that takes a context is given one that lasts thirty seconds from the call.

import go "fmt"
import go j "encoding/json"

print(fmt.sprintf("%s has %d", "whisker", 4))     // whisker has 4
print(string(j.marshal({"name": "whisker"})))     // {"name":"whisker"}

Versions and side effects. The version is the toolchain’s choice unless the path names one with @: import go "github.com/aws/aws-sdk-go-v2/aws/arn@v1.32.0". A package imported and never called is still imported, for what its init does, as Go’s import _ is: import go "image/png" registers the format.

Generics, channels, and functions taking functions are not reached this way. A Go package is also out of reach in the playground, which has no Go toolchain.

Type Declarations

TypeDecl      = "type" identifier ( AliasDecl | NewTypeDecl | StructDecl | InterfaceDecl ) .
AliasDecl     = "=" TypeExpr newline .
NewTypeDecl   = TypeExpr newline .
StructDecl    = "struct" "{" ( { Field [ "," ] newline } | { Variant [ "," ] newline } ) "}" .
Field         = identifier TypeExpr .
Variant       = identifier [ "(" [ VariantField { "," VariantField } ] ")" ] .
VariantField  = identifier [ TypeExpr ] .
InterfaceDecl = "interface" "{" { MethodSig } "}" .
MethodSig     = identifier "(" [ ParamList ] ")" [ TypeExpr ] newline .
FormMeaning
type A = intA is another name for int
type A intA is a new type, distinct from int
type P struct { x int }a struct
type S struct { Circle(r float), Dot }a sum type
type S interface { area() float }an interface

An alias is the same type as what it names, interchangeable with it everywhere, and leaves no trace in the generated code:

type Nickname = string
let name Nickname = "Tama"
print(name + " chan")           // Tama chan

A new type is not interchangeable with the type it is made from: passing an Age where an int is wanted is a compile error. Age(3) makes one, and .value reads the value inside. Two new types made from the same type are still different types (see equality).

type UserId int
let id = UserId(42)
print(id.value)                 // 42
print(id)                       // UserId{value: 42}

A struct makes a constructor of the same name that takes the fields in order:

type Point struct {
  x int
  y int
}

let p = Point(3, 7)
print(p.x)          // 3

Sum Types

A struct body whose first entry is a name without a type lists variants, and the type is a sum type: each value is exactly one of the variants. Each variant is a constructor of its own, taking its fields in parentheses; a variant with no fields is a value rather than a function. The sum type’s own name is a type, which can annotate a parameter or a result, but not a constructor. A variant’s field may leave its type out, as a lambda parameter may.

type Shape struct {
  Circle(radius float)
  Rect(w float, h float)
  Dot
}

fn area(s Shape) float {
  match s {
    Circle(r) => 3.0 * r * r,
    Rect(w, h) => w * h,
    Dot => 0.0
  }
}

print(area(Rect(2.0, 3.0)))   // 6
print(Circle(1.5))            // Circle(1.5)

A variant prints the way it is written and compares by value; two variants of the same sum type are always comparable, and different variants are unequal. A variant’s name shares the namespace of types. Constructor patterns reach what a variant carries; a field may also be read with . when every variant has it. A method declared for a sum type belongs to every variant.

Interfaces

An interface is a named set of method signatures. A struct, sum type or new type satisfies it when its methods include every one the interface names, with the same parameter and result types; nothing declares that it does. An interface’s name is a type, and may annotate a parameter, a result or a binding. A value of a type that does not satisfy it is refused:

type Showable interface {
  show() string
}

type Cat struct { name string, age int }
fn (c Cat) show() string { c.name + " (age " + string(c.age) + ")" }

fn display(s Showable) string { s.show() }
print(display(Cat("tama", 2)))   // tama (age 2)

Passing a type without a show method is refused with Rock does not satisfy Showable: missing method show. An interface is checked before the program runs, and generates no code of its own.

Methods

MethodDecl = "fn" "(" identifier identifier ")" identifier "(" [ ParamList ] ")" [ TypeExpr ] Block .

A method names its receiver before the method name. In the body, the receiver name is the value the method was called on.

type User struct { name string, age int }

fn (u User) show() string {
  return u.name + " (age " + string(u.age) + ")"
}

type Age int
fn (a Age) next() Age { Age(a.value + 1) }

Methods may be declared for a struct, a sum type or a new type. A method read rather than called is bound to its receiver (see Index and Member Expressions).

Expression Statement

Any expression can stand as a statement. Its value is discarded; an error it holds is not, and is raised where the statement is written, so it fails the enclosing function and ends the program unless something catches it. An error already handled — the one try hands back — is an ordinary value, and a statement holding it carries on.

fn at_nine(xs list) int {
  xs[9]                  // an error, raised here
  print("not reached")
  return 0
}

print(recover(string(at_nine([1, 2])), "caught"))   // caught

Built-in Functions

Built-ins are predeclared identifiers and can be rebound. The standard library reference describes each one.

FunctionPurpose
print(args...)print values
fail(args...)raise an error
try(fn)call fn, turning a failure into an error value
is_error(v)whether v is an error
exit([status])end the program
len(v)length of a string, list or dict
head(list), tail(list)first element; everything after it
append(list, value)a new list with value at the end
map(list, fn)transform each element
filter(list, fn)keep the elements fn accepts
reduce(list, init, fn)fold a list into one value
sort(list), reverse(list)a sorted copy; a reversed copy
upper(s), lower(s), trim(s)change case; strip whitespace
replace(s, old, new), pad(s, width)replace text; pad with spaces
contains(s, sub)whether s contains sub
index_of(s, sub)character offset of sub in s, or -1
split(s, sep)split s around sep
join(list, sep)join strings with sep
slice(s, start, end)substring by character position
int(v) float(v) string(v) …conversion by the type’s name
to_bytes(s), to_runes(s)the bytes, or the characters, of a string
round(x, places)round to decimal places
assert(cond [, msg])test assertion
assert_eq(got, want [, msg])test assertion
assert_not(cond [, msg])test assertion
seed(values...)an example input for a property or fuzz test

The members of an imported Go package are named after the package: strings.to_upper, os.read_file, http.get, …

Property tests

In a *_test.wsk file, a function named prop_* is a property. whisker test runs it on generated inputs and reports the first that makes it fail.

  • Every parameter needs a type annotation, and there must be at least one. The types that can be generated are int, float, bool, string and list (of ints); a sized integer type is generated over its whole range.
  • An input passes when the body returns with no unhandled error. An error that recover catches is not a failure; a panic is.
  • It runs on 100 inputs, or -prop-count <n> (1 or more). Edge values come first. A generated string or list has 0 to 20 elements.
  • -seed <n> fixes the inputs; a failure always prints the seed.
  • A failing input is shrunk, each argument on its own, in at most 1,000 attempts. The report shows the shrunk input, the original and the seed.
  • seed(values...) as a statement of the body adds an example that runs first and is not counted. It is worked out before the generated inputs and before the body, so its values may not use a parameter or a name the body binds at its top level; a top-level name of the file may be used.

Error Model

  1. Raising. fail(args...) raises an error whose message is its arguments joined with spaces. Built-ins and the runtime raise errors of their own, such as Division by zero or Index 5 out of range.

  2. Error values. An error is a value of type error carrying its message. It passes through the program: an operation, a call of a function value, or a member reached through an error answers with that error, and an expression statement holding one fails the enclosing function.

  3. Catching. recover(x, fallback) (or x |> recover(fallback)) is fallback when x fails; a function as the fallback receives the error. try(fn) calls fn and answers with the error instead of failing. An error caught this way is handled: an ordinary value, which can be printed, passed and stored.

  4. Checking. is_error(v) is true when v is an error.

  5. Reporting. An error nothing catches ends the program with exit status 1, and is written to standard error after the position of the statement that was running, in the same file:line:column form the compiler’s own errors use:

    probe.wsk:12:3: error: Cannot read "x" as an Int
    

    The position is on the report only. An error caught with recover or try carries its message alone, and prints as error: followed by it.

fn divide(a int, b int) int {
  if b == 0 {
    fail("division by zero")
  }
  return a / b
}

print(recover(divide(10, 0), 0))     // 0
let result = try(fn() { divide(10, 0) })
print(is_error(result))              // true
print(result)                        // error: division by zero

Truthiness

Conditions — of if, of for cond, and of a guard — and the operands of && and || must be bool wherever the checker can tell their type: if 5, 1 && 2 and for "" are refused, so write the comparison out (n != 0, len(s) > 0). Only where a value’s type is known only at run time, such as an unannotated lambda parameter, is it tested by its truthiness instead. ! accepts any value, and inverts the truthiness of one that is not a bool. && and || on such values answer with one of their operands: && with the left one if it is falsy and the right one otherwise, || with the left one if it is truthy and the right one otherwise.

ValueTruthy?
trueyes
falseno
nilno
0, 0.0no
any other numberyes
""no
any other stringyes
[], {}no
a non-empty list or dictyes
a struct, a functionyes
an errorno

Program Structure

A Whisker program is a single .wsk file holding a sequence of top-level statements: imports, type declarations, functions, methods, bindings and expression statements. There is no main function: the top-level statements run in order, from the top of the file. Functions and types may be used above the line that declares them; a top-level binding may be read by a function above it, but has its value only once its line has run (see Binding).

The whisker command transpiles the program to a Go package main: functions and types become Go declarations, and the top-level statements become the body of Go’s main. whisker transpile shows that Go source, and whisker build compiles it into a native binary.

A file named foo_test.wsk is a test file; whisker test reads foo.wsk alongside it, and runs its test_*, catwalk_*, prop_* and fuzz_* functions (see the standard library reference).