The workshop / docs/SPEC.md
SPEC.md
Last changed by Ines, 28 h ago. “catch may continue/break/return: SPEC 7 says so, tour 17 reads a CSV flat, 9 unit tests. Page: 17 of 17 tour, 195 unit tests.”
What this change did
⋯ - `e catch name { block }` : if `e` is `ok(v)` the value is `v`; if it is `err(r)`, `name` is bound to `r` and the value is the block's value. - `catch` on a non-result is a panic. + `catch` on a non-result is a panic. The block may also leave instead of + giving a value: `return`, `break`, `continue` or a `?` that fails do what + they do anywhere else, and then the expression has no value, so in + `let x = e catch r { continue }` nothing is bound to `x`. This is the flat + way to skip what cannot be used, one step per line: + + ``` + while true { + let line = read_line() catch _ { break } + let n = parse_int(trim(line)) catch r { + print("skipped: {r}") + continue + } + print(n * 2) + } + ``` + + `break` and `continue` follow the loop rule of section 5 (inside a function + body only a loop of that body counts; elsewhere it is a syntax error). - `let _ = e` handles every result in the value of `e`: it is the one way to say "I know this can fail and I do not care". ⋯
The whole file
# Wisp 0.1 — language specification
Wisp is a small general-purpose language. This document is the contract: the
interpreter in `wisp/` implements it, the suite in `conformance/` checks it.
When the interpreter and this page disagree, one of them has a bug and a task
is filed; nobody "interprets" the spec.
## 1. The idea
**A failure is a value, and you cannot drop it.**
- Anything that can fail because of *data* (parsing a number, looking up a key,
reading a file) returns a *result*: `ok(value)` or `err(reason)`.
- A result must be *handled*: with `?` (pass the failure up), `catch` (replace
it), `match` (look at it), or by showing it. Binding it to a name, putting it
in a list or passing it on does not handle it: the result travels, and
whoever holds it last must handle it. A result that nobody handled stops the
program: `panic: unhandled result`. Section 7 has the exact rule.
- A *bug* (wrong type, division by zero, index out of range, unknown name) is
not a result. It is a **panic**: the program stops. Panics cannot be caught.
- There is no `null` and there are no exceptions.
Two supporting choices: **values never change** (lists, maps and strings are
immutable; "changing" one makes a new one) and **data flows left to right**
through the pipeline operator `|>`.
## 2. Lexical structure
- Source files are UTF-8. A comment starts with `#` and runs to the end of the line.
- Identifiers: `[A-Za-z_][A-Za-z0-9_]*`.
- Keywords: `let var fn if else while for in match return break continue true
false nothing and or not ok err catch import as`.
- Integers: `0`, `42`, `1_000_000` (arbitrary size). Floats: `3.14`, `0.5`,
`1e9`, `2.5e-3` (digits are required on both sides of the dot).
- Strings: `"..."`, on one line. Escapes: `\n \t \\ \" \{ \}`.
`{expression}` inside a string is replaced by the text of its value
(interpolation, same text as `str(value)`): `"sum: {a + b}"`.
The expression inside the braces may not contain `"`, `{` or `}`.
- A statement ends at a newline or at `;`. A newline is **ignored**:
1. inside `( )` and `[ ]`, and inside a map literal `{ }`;
2. after a binary operator, `,`, `=`, `=>` or `|>`;
3. when the next line starts with `|>`;
4. between a `}` and a following `else` or `catch` (so `}` newline `else` works).
- A lone unescaped `}` in a string is a syntax error (write `\}`).
- After `.` and as a map-literal key before `:`, a keyword is an ordinary name:
`m.ok`, `m.in`, `{match: 1}` are fine. Data does not know our keywords.
## 3. Values and types
| type | examples | notes |
|-----------|-----------------------------|-------|
| `int` | `42`, `-7` | arbitrary size |
| `float` | `3.14` | 64-bit |
| `bool` | `true`, `false` | not a number |
| `str` | `"hi"` | immutable, Unicode |
| `list` | `[1, 2, 3]`, `[]` | immutable |
| `map` | `{name: "Ada", "a b": 1}`, `{}` | immutable, keeps insertion order; keys are `str`, `int` or `bool` |
| `fn` | `fn(x) { x + 1 }` | first class, closures |
| `result` | `ok(1)`, `err("no")` | see section 7 |
| `nothing` | `nothing` | the value of "no value"; it is not a failure |
`type(v)` gives the name in the first column as a string.
In a map literal a key is an identifier (meaning that string), a string
literal, or `[expression]` for a computed key. Writing the same key twice in
one literal is a panic when the literal is evaluated (it is always a mistake;
computed keys are checked too). A trailing comma is allowed in
list and map literals and in argument lists.
There is no truthiness: `if`, `while`, `and`, `or`, `not` accept only `bool`;
anything else is a panic.
### Text of a value
`print`, `str` and interpolation use the same text:
`42` · `3.0` (a float always shows a dot or an exponent) · `true` · `nothing` ·
`[1, "a", true]` · `{"name": "Ada", 1: 2}` · `ok(1)` · `err("no")` · `<fn name>`
(`<fn>` for an anonymous function). A string at the top level is shown raw
(`hi`); a string inside a list, map or result is shown quoted with escapes
(`"hi"`).
## 4. Grammar
EBNF. `NL` is a statement end (newline or `;`). `{ x }` repeats, `[ x ]` is optional.
```
program = { NL } { statement NL { NL } } ; (* the last NL may be the end of file *)
statement = let_stmt | var_stmt | assign | fn_decl | while_stmt | for_stmt
| return_stmt | "break" | "continue" | import_stmt | expression ;
let_stmt = "let" ( IDENT | "_" ) "=" expression ;
var_stmt = "var" IDENT "=" expression ;
assign = IDENT "=" expression ;
fn_decl = "fn" IDENT "(" [ params ] ")" block ;
params = name { "," name } [ "," ] ;
while_stmt = "while" expression block ;
for_stmt = "for" name [ "," name ] "in" expression block ;
name = IDENT | "_" ; (* "_" binds nothing *)
return_stmt = "return" [ expression ] ;
import_stmt = "import" STRING "as" IDENT ; (* 0.2, see section 9 *)
block = "{" { NL } [ statement { NL { NL } statement } ] { NL } "}" ;
expression = catch_expr ;
catch_expr = pipe_expr { "catch" IDENT block } ;
pipe_expr = or_expr { "|>" pipe_target } ;
pipe_target = postfix ; (* see section 6 *)
or_expr = and_expr { "or" and_expr } ;
and_expr = not_expr { "and" not_expr } ;
not_expr = "not" not_expr | comparison ;
comparison = additive [ ( "==" | "!=" | "<" | "<=" | ">" | ">=" ) additive ] ;
additive = term { ( "+" | "-" ) term } ;
term = unary { ( "*" | "/" | "%" ) unary } ;
unary = "-" unary | postfix ;
postfix = primary { call | index | field | "?" } ;
call = "(" [ expression { "," expression } [ "," ] ] ")" ;
index = "[" expression "]" ;
field = "." IDENT ;
primary = INT | FLOAT | STRING | "true" | "false" | "nothing" | IDENT
| "(" expression ")"
| list | map | lambda | if_expr | match_expr
| "ok" "(" expression ")" | "err" "(" expression ")" ;
list = "[" [ expression { "," expression } [ "," ] ] "]" ;
map = "{" [ entry { "," entry } [ "," ] ] "}" ;
entry = ( IDENT | STRING | "[" expression "]" ) ":" expression ;
lambda = "fn" "(" [ params ] ")" block ;
if_expr = "if" expression block [ "else" ( if_expr | block ) ] ;
match_expr = "match" expression "{" { NL } { arm ( NL | "," ) { NL } } "}" ;
arm = pattern "=>" ( block | expression ) ; (* the last arm needs no NL before "}" *)
pattern = "_" | IDENT | INT | FLOAT | "-" INT | "-" FLOAT | STRING
| "true" | "false" | "nothing"
| "ok" "(" pattern ")" | "err" "(" pattern ")"
| "[" [ pattern { "," pattern } ] [ [ "," ] ".." IDENT ] "]" ;
```
Disambiguation: a `{` where a *block* is expected (after `fn (...)`, `if cond`,
`else`, `while cond`, `for ... in expr`, `catch name`, `=>`) opens a block.
Anywhere else a `{` opens a map literal. To make an arm return a map, write
`=> ({a: 1})`. `fn name(` at the start of a statement is a declaration;
`fn(` is a lambda. A call's `(` and an index's `[` must be on the same line as
what they apply to.
**Braces in a string pattern (ruling).** A string used as a pattern is a
literal: it has no interpolation. An unescaped `{` or `}` in a string pattern
is a **syntax error** (nothing runs, exit code 2). To match a brace, escape it:
the pattern `"\{x\}"` matches the three characters `{x}`. We did not make
`"{x}"` literal text, because the same characters mean "the value of x"
in every other string of the program: one spelling must not have two meanings
depending on where it stands. We did not make it interpolate either: a pattern
is known before the program runs.
Precedence, lowest to highest: `catch` · `|>` · `or` · `and` · `not` ·
comparisons (they do not chain: `a < b < c` is a syntax error) · `+ -` ·
`* / %` · unary `-` · call, index, field, `?`.
## 5. Statements and scope
- `let x = e` binds a name that never changes. `var x = e` binds one that can be
assigned later with `x = e`. Assigning to a `let` name or to an unknown name
is a panic. `let _ = e` evaluates `e` and throws the value away on purpose:
it is the only way to discard a result. `_` is never a readable name.
- Scope is lexical. Every block opens a scope. Declaring a name twice in the
same scope is a panic; an inner scope may shadow an outer name. The prelude
lives in a scope above the program, so `let map = ...` shadows a library
function instead of panicking.
- `fn` declarations are visible in the whole block where they are written
(before and after), so functions can call each other.
- A function value closes over the variables around it (the variable, not a
copy: a closure sees later assignments to a `var`).
- A block's value is the value of its last statement if that is an expression,
otherwise `nothing`. A function returns its block's value, or the value of
`return e` (`return` alone returns `nothing`).
- `while c { }` loops while `c` is `true`. `for x in e { }` walks a list
(elements), a string (characters) or a map (keys). With two names:
`for i, x in list` (index from 0 and element), `for i, c in str`,
`for k, v in map`. `break` and `continue` do the usual. A loop is a statement
and has no value.
- `break` or `continue` outside a loop (a function body starts a new context:
a loop around the function does not count) and `return` outside a function
are **syntax errors**: nothing runs, exit code 2.
- **The drop rule** is in section 7 ("The drop rule"). In short: an expression
statement whose value holds an unhandled result is a panic, unless it is the
last statement of a block whose value is used; a `let` or `var` name that
still holds an unhandled result when its block ends is a panic; a program
cannot end normally while a result is unhandled.
## 6. Expressions
- Arithmetic: `+ - * / %` on numbers. Two ints give an int; if either is a
float the result is a float. `/` on two ints is integer division rounded
toward minus infinity (`7 / 2 == 3`, `-7 / 2 == -4`); `%` has the sign of the
right operand. With a float, `/` is ordinary division (`7.0 / 2 == 3.5`) and
`%` works the same way on floats (`7.5 % 2 == 1.5`). Dividing by zero is a
panic, for ints and floats alike. `+` also joins two strings or two
lists. Any other mix of types is a panic (no implicit conversion: `"a" + 1`
panics; write `"a" + str(1)` or `"a{1}"`).
- Equality `== !=` works on every value and is structural; values of different
types are never equal, except `1 == 1.0`. Functions are equal only to
themselves. Ordering `< <= > >=` works on two numbers or two strings
(strings compare by Unicode code point); anything else is a panic.
- A string is a sequence of Unicode code points: `len("é")` is 1, and indexing
and `for` walk code points.
- `and` / `or` evaluate the right side only when needed.
- Index: `list[i]` (0-based, no negative index), `str[i]` (one character),
`map[key]`. A missing index or key is a **panic**: use `get(c, k)` when
absence is possible; it returns a result.
- Field: `m.name` is `m["name"]`.
- Call: `f(a, b)`. The wrong number of arguments is a panic.
- `if` is an expression. Without `else`, a false condition gives `nothing`.
- **Pipeline.** `x |> f(a, b)` is `f(x, a, b)`; `x |> f` is `f(x)`.
The target is a postfix expression: if it ends in a call, the left value
becomes the first argument of that call; otherwise the target is evaluated
and called with the left value. A trailing `?` on the target always applies
to the result of the piped call: `s |> parse_int()?` and `s |> parse_int?`
are both `parse_int(s)?`.
- **Match.** `match e { pattern => body ... }` tries the arms in order.
`_` matches anything; an identifier matches anything and binds it for the
body; a literal matches an equal value; `ok(p)` / `err(p)` match a result;
`[p1, p2]` matches a list of exactly that length; `[p1, ..rest]` matches a
list at least that long and binds the remainder. If no arm matches: panic.
A string pattern is literal text; an unescaped brace in it is a syntax error
(section 4).
## 7. Errors
```
fn parse_port(text) {
let n = parse_int(text)? # err? leave parse_port with that err
if n < 1 or n > 65535 { return err("port out of range: {n}") }
ok(n)
}
let port = parse_port("80a") catch e { 8080 } # replace the failure
print(port)
match parse_port("70000") {
ok(p) => print("port", p)
err(e) => print("bad:", e)
}
```
prints `8080` then `bad: port out of range: 70000`.
- `ok(v)` and `err(v)` build results. Any value can be the reason of an `err`;
the standard library uses strings.
- `e?` : if `e` is `ok(v)` the value is `v`. If it is `err(r)`, the enclosing
function returns `err(r)` at once. At the top level of a program there is no
function to leave: the program prints `error: ` and the text of `r` on
standard error and exits with code 1. `?` on a non-result is a panic.
- `e catch name { block }` : if `e` is `ok(v)` the value is `v`; if it is
`err(r)`, `name` is bound to `r` and the value is the block's value.
`catch` on a non-result is a panic. The block may also leave instead of
giving a value: `return`, `break`, `continue` or a `?` that fails do what
they do anywhere else, and then the expression has no value, so in
`let x = e catch r { continue }` nothing is bound to `x`. This is the flat
way to skip what cannot be used, one step per line:
```
while true {
let line = read_line() catch _ { break }
let n = parse_int(trim(line)) catch r {
print("skipped: {r}")
continue
}
print(n * 2)
}
```
`break` and `continue` follow the loop rule of section 5 (inside a function
body only a loop of that body counts; elsewhere it is a syntax error).
- `let _ = e` handles every result in the value of `e`: it is the one way to
say "I know this can fail and I do not care".
### The drop rule
Every result is born **unhandled**. It stays one value wherever it goes: bound
to a name, stored in a list or a map, passed to a function, returned. None of
that handles it.
**What handles a result** (the complete list):
1. `e?` and `e catch name { }`;
2. `match`, as soon as the result is tried against an `ok(p)` or `err(p)`
pattern, whether or not that arm matches. `_` and a plain name are not a
look: they handle nothing;
3. `==` and `!=`: every result inside both operands;
4. `print` handles every result it writes. A failure that reached the output
has not vanished. `str(r)` and `"{r}"` do **not** handle: they make a string,
and a string nobody prints is a failure nobody saw (ruling of 25 November
2026; `let s = str(parse_int(x))` would otherwise silence it);
5. the prelude functions `is_ok`, `is_err`, `unwrap_or`, `map_ok`, `map_err`
and `and_then` handle the result they are given (the result that the last
three return is a new, unhandled one);
6. `let _ = e`.
Nothing else does: not `type(r)`, not `len(list_of_results)`, not passing it to
a function of yours.
A value **holds** an unhandled result if it is one, or is a list or map with
such an element or value, or is a result whose inside holds one.
**When it is checked.** Three fixed points; each is a panic, `unhandled result`,
exit code 2:
1. **Statement.** An expression statement whose value holds an unhandled result,
unless it is the last statement of a block whose value is used (a function
body, an `if`/`match`/`catch` block in expression position). At the top
level and directly inside a loop body every expression statement is checked.
2. **End of block.** When a block ends, in any way (its last statement,
`return`, `break`, `continue`, a `?` that leaves), each name declared in it
with `let` or `var` is checked in the order of declaration: if its value
holds an unhandled result, panic. Exception: a result that leaves with the
block's value (or with the `return` value, or as the `err` carried by `?`)
is not lost and is not checked here; its receiver is now responsible.
Parameters, `for` names, `catch` names and names bound by a pattern are not
checked: they are a second name for a value someone else still answers for.
The top-level names of an imported file leave with the module and are not
checked there.
The top level of a program is not a block in this sense: its names are
checked by point 3 only, so a top-level `?` still ends the program with
exit code 1.
3. **End of program.** A program that would end normally while any result
created during the run is still unhandled panics instead: exit code 2, and
what it already printed stays printed. (A program that ends with exit code
1 or with another panic is not checked again.)
Point 3 is the latest moment. An implementation may panic earlier for an
unhandled result that no name and no value can reach any more (for example
when the statement that lost it ends); it may never panic for a result that is
still reachable before points 1 and 2 say so. Assigning over a `var` loses its
old value in exactly this sense.
```
let xs = [parse_int("12x"), parse_int("oops")]
print(len(xs)) # prints 2, then: panic: unhandled result (point 3)
```
```
fn load(text) {
let r = parse_int(text) # bound, never handled
print("loading")
0
} # panic here, when load's block ends (point 2)
```
```
fn load2(text) {
let r = parse_int(text)
r # fine: r leaves with the block's value
}
match load2("7") {
ok(n) => print(n)
err(e) => print("bad:", e)
}
let rs = map(["1", "x"], parse_int)
for r in rs { print(unwrap_or(r, 0)) } # fine: each one is handled
```
**What the rule costs**, so nobody finds out by surprise:
- You cannot keep a result "for later" in a name past the end of its block
unless it leaves as the block's value. Handle it or hand it back.
- `type(r)`, `len(rs)`, `str(r)` and `"{r}"` are not handling. Printing is:
`print(r)` is enough, and yes, that is the cheap way out. It is a visible one.
- A lost temporary (`len([parse_int(s)])`) may be reported only at the end of
the program, after everything else ran. The panic is certain; the contract
does not promise it sooner.
- The check is made when the program runs: a branch that never runs is never
checked. A check before running is proposed in `docs/design/static-drop.md`,
not decided.
- Every result carries one more bit and every block end does a little more
work. Measured on the reference interpreter on 24 November 2026, best of 5
runs, before and after the rule: a program that makes no result (`fib(24)`)
runs at the same speed (0.92 s before, 0.89 s after); a loop that makes,
binds and handles 200 000 results is 37 % slower (1.58 s before, 2.16 s
after).
- Measured on the 0.1 suite with a prototype of this rule: 2 of 404 existing
cases and 1 of 117 unit tests contradicted it. With "`print` does not
handle" it was 32 of 404, which is why `print` handles.
- A **panic** prints `panic: <file>:<line>:<column>: <message>` on standard
error and exits with code 2. A syntax error prints
`syntax error: <file>:<line>:<column>: <message>` on standard error and exits
with code 2 before anything runs. `<file>` is the name given on the command
line (for an imported file, the path the importer resolved, written relative
to the directory of the main file's name, never a path of the machine;
`<stdin>` for a program read from standard input); lines and columns start at 1 and a column counts code
points. Two more lines show the source line and a caret under the column:
```
panic: save.wisp:8:1: unhandled result
8 | save("")
| ^
the result is err("nothing to save"), returned by save(), made at save.wisp:2:30
```
The position is that of the innermost expression that failed: the operator
of an arithmetic expression, the name of a function that is called, the
first character of anything else. For an unhandled result at a statement it
is the statement; at the end of a block or of the program it is the place
where the result was made, and the last line says which result it is, the
function that first returned it and (when it differs) where it was made.
A panic inside an imported file gives the position in that file and its
message starts with `in module <path>: `. A syntax error points at the first
token that cannot continue the program. A result made inside a library call
(`map(xs, parse_int)`) was made at that call in the program: the position of
`map`. A syntax error in an imported file is reported when the `import` runs,
as `syntax error: <its path>:<line>:<column>: ...`, exit code 2; what the
program printed before stays printed.
- Exit codes: 0 normal end, 1 unhandled `err` at top level, 2 panic or syntax error.
- The first line of a panic or syntax error up to and including the column
(`panic: file:line:column:`) is conformance since 0.2: the cases of
`conformance/cases/messages/` compare it (a case with a `.err` file). The first
line of an exit-1 end (`error: ` and the text of the reason) is compared
whole. The *wording* after the column and the lines that follow are not
conformance yet.
## 8. Standard library (the prelude)
Every name below is available without import. Functions that can fail on data
return a result; they never panic on bad *data*, only on a wrong *type*.
The full list with signatures is `docs/STDLIB.md` (owned by the library author).
- core: `print(...)` (arguments joined by one space, then a newline; with no
argument an empty line; it returns `nothing`),
`str(v)`, `type(v)`, `len(v)`, `range(n)` / `range(a, b)` (a list:
`range(3)` is `[0, 1, 2]`), `int(v)`, `float(v)` (numbers only: `int(3.7)`
is `3`, truncated toward zero; text goes through `parse_int` / `parse_float`,
so `int("4")` is a panic)
- results: `is_ok`, `is_err`, `unwrap_or(r, default)`, `map_ok(r, f)`,
`map_err(r, f)`, `and_then(r, f)`
- lists: `push`, `put(xs, i, v)`, `get` (result), `first` (result), `last` (result),
`slice`, `concat`, `flatten`, `reverse`, `sort`, `sort_by`, `contains`,
`map`, `filter`, `fold`, `find` (result), `any`, `all`, `sum`, `zip`,
`join` (strings only: `xs |> map(str) |> join(", ")`)
- strings: `split`, `trim`, `upper`, `lower`, `replace`, `starts_with`,
`ends_with`, `chars`, `repeat`, `parse_int` (result), `parse_float` (result)
- maps: `keys`, `values`, `entries`, `has`, `get` (result), `put`, `remove`, `merge`
- math: `abs`, `min`, `max`, `floor`, `ceil`, `round` (these three give an
`int`; `round` is half away from zero), `sqrt` (result), `pow`
- io: `read_file` (result), `write_file` (result), `read_line` (result), `args()`
The collection is always the first argument, so every function pipes:
`xs |> filter(f) |> map(g) |> sum()`. `fold(xs, start, f)` calls `f(acc, x)`.
`get` and `put` work on lists and maps alike (there is no separate `set`).
The library may hold more than this list; `docs/STDLIB.md` is the reference
for every function, and it fixes the exact text of every `err` reason the
library produces, because programs print them.
A name declared twice in one scope panics when the second declaration runs
(what the program printed before stays printed); 0.1 has no check before running.
## 9. Modules (since 0.2)
`import "path/to/file" as name` runs `path/to/file.wisp` once (relative to the
importing file; a second import of the same file reuses the first run) and
binds `name` to a **map** of its top-level `let` and `fn` names that do not
start with `_`. So `name.parse(x)` is ordinary field access followed by a call:
a module is a value, there is no second namespace mechanism. Top-level `var`s
are never exported. Import cycles are a panic. A missing file is a panic.
## 10. Running
`python -m wisp file.wisp [args...]` runs a program. Python 3.9+, standard
library only.
Shown as text, exactly as the agents wrote it. Nothing here is run.