Compiler errors
This page lists the errors the Tern compiler reports, with what each one means and how to fix it. Search the page for the text of your error: each heading is an error message, with the parts that change (names, types, counts) written in capitals, like NAME, TYPE, or N. Every entry has a short program that produces the error, the exact output of the compiler, and a fixed program. The last section covers runtime errors, which happen while a program runs.
How to read an error
The compiler checks the whole file before it builds anything. Each problem is one line:
prog.tn:12: error: can't modify parameter `n`: parameters are read-only unless declared `mut`
prog.tn:12: hint: to change only a local copy, copy it first (`n2 = n`) and change `n2`; ...
1 error(s); not compiled.prog.tn:12is the file and line.error:says what is wrong. Type and safety errors are all reported at once; a syntax error (the file can't be read as Tern at all) stops at the first one.hint:appears when the compiler recognizes a habit from another language or a likely typo, and says what to write instead. Not every error has one.
In the examples below the file name is left out, so 5: error: ... means line 5.
For tools and agents, check --json prints the same information as JSON on stdout:
tern check --json prog.tn{"ok": false, "errors": [{"file": "prog.tn", "line": 2,
"message": "can't modify parameter `n`: parameters are read-only unless declared `mut`",
"hint": "to change only a local copy, ...", "source": "n += 1"}]}hint is null when there is none, and source is the offending line. A clean file gives {"ok": true, "file": ...}. The --json flag also works with run and build.
Contents
- Syntax
- Habits from other languages
- Names and types
- Operators and conversions
- Functions and calls
- Structs
- Enums
- Arrays, maps, and strings
- Mutation,
mut, and& - Aliasing
takeand moved values- Loops
- Parallelism and races
- Closures
- Modules
- C interop and
export - Web, database, and JSON
Syntax
Syntax errors come from reading the file, before any types are checked. Only the first one is reported. Many of them come with a hint when the line looks like another language; those are listed in Habits from other languages.
expected fn, struct, enum, type, const, or extern at the top level
The top level of a file may only hold import, from ... import, struct, enum, const, fn, extern, and export fn. Statements and variables live inside functions. There are no global variables; a value that never changes can be a const.
limit = 5
fn main():
print(limit)1: error: expected `fn`, `struct`, `enum`, `type`, `const`, or `extern` at the top level
1: hint: there are no global variables; for a value that never changes, write `const LIMIT = 5` (a variable that changes belongs in a function, or in a struct you pass around)Make it a constant (or, if it changes, a variable inside a function that you pass around):
const LIMIT = 5
fn main():
print(LIMIT)5expected TOKEN, found TOKEN
The parser needed a particular token and saw something else. The most common case is a missing : at the end of an if, for, while, fn, struct, or match line.
fn main():
x = 3
if x > 0
print("positive")3: error: expected `:`, found end of linefn main():
x = 3
if x > 0:
print("positive")positiveexpected an indented block, found TOKEN
A line that ends in : must be followed by an indented block (or a single statement on the same line). For an empty block, write pass.
fn main():
x = 3
if x > 0:
print("positive")4: error: expected an indented block, found 'print'fn main():
x = 3
if x > 0:
print("positive")positiveexpected a name, found TOKEN
The parser needed a name (of a variable, function, field, or type) here.
fn main():
for 1 in [1, 2]:
pass2: error: expected a name, found 1fn main():
for n in [1, 2]:
print(n)1
2expected end of line, found TOKEN
The statement was complete, but more text followed on the same line. Put one statement on each line.
fn main():
print(1) print(2)2: error: expected end of line, found 'print'fn main():
print(1)
print(2)1
2expected =, found end of line
A variable is created by giving it a value. x: int alone is not a declaration.
fn main():
count: int
count = 3
print(count)2: error: expected `=`, found end of line
2: hint: a variable needs a value when it is created: `x: int = 0`fn main():
count: int = 0
count = 3
print(count)3unexpected TOKEN
The parser found a token that can't start or continue an expression here.
fn main():
total = )2: error: unexpected ')'fn main():
total = 0
print(total)0unexpected indentation: this line is indented more than the block it is in
A line is indented more than the line before it, but the line before doesn't end in :. Only a block after : may be indented further.
fn main():
x = 1
y = 2
print(x, y)3: error: unexpected indentation: this line is indented more than the block it is infn main():
x = 1
y = 2
print(x, y)1 2this line's indentation doesn't match any enclosing block
When a block ends, the next line must line up with one of the blocks around it. Here line 4 is indented 6 spaces, but the blocks are at 4 and 8. Use 4 spaces per level.
fn main():
if true:
x = 1
print(x)4: error: this line's indentation doesn't match any enclosing blockfn main():
x = 0
if true:
x = 1
print(x)1unterminated string
A string has no closing " on the same line. Strings are one line; write \n for a line break.
fn main():
print("hello)2: error: unterminated stringfn main():
print("hello")
print("two\nlines")hello
two
linesunterminated string inside f-string
This usually means a { in an f-string has no closing }. The compiler keeps reading the expression inside the braces, takes the f-string's closing " as the start of a new string, and reaches the end of the line.
fn main():
x = 1
print(f"x = {x")3: error: unterminated string inside f-stringfn main():
x = 1
print(f"x = {x}")x = 1f-string has } without an opening { (write }} for a brace)
In an f-string, { and } mark expressions. For a literal brace, double it.
fn main():
print(f"a } b")2: error: f-string has `}` without an opening `{` (write `}}` for a brace)fn main():
n = 2
print(f"{{n}} is {n}"){n} is 2can't read TEXT inside the f-string
The text between { and } isn't an expression. The usual cause is a format spec such as {x:.2f}: f-strings have none. Use the fmt module instead.
fn main():
price = 3.14159
print(f"{price:.2f}")3: error: can't read `price:.2f` inside the f-string
3: hint: f-strings have no format specs: `import fmt`, then `{fmt.fixed(x, 2)}` (2 decimals), `fmt.zero_pad(n, 3)`, `fmt.pad_left(s, width, " ")`import fmt
fn main():
price = 3.14159
print(f"{fmt.fixed(price, 2)}")3.14unexpected character 'C'
The character can't appear in Tern code outside a string. Common ones are ;, ', !, $, and @.
fn main():
x = 5 $ 32: error: unexpected character '$'fn main():
x = 5 - 3
print(x)2left side of = must be a variable, field, or element
Only a variable (x), a field (p.x), or an element (xs[i], m[k]) can be assigned to.
fn first() int:
return 1
fn main():
first() = 35: error: left side of `=` must be a variable, field, or elementfn first() int:
return 1
fn main():
x = first()
x = 3
print(x)3positional arguments must come before named ones
When building a struct you may give fields by position, by name, or both, but the positional ones come first.
struct Point:
x, y: int
fn main():
p = Point(x=1, 2)5: error: positional arguments must come before named onesstruct Point:
x, y: int
fn main():
p = Point(1, y=2)
print(p)Point{x: 1, y: 2}named arguments are only for building structs
Functions take positional arguments only. name=value works only in a struct or enum variant constructor. print has no end= or sep=; build the line as a string first.
fn area(w: int, h: int) int:
return w * h
fn main():
a = area(w=2, h=3)5: error: named arguments are only for building structs
5: hint: functions take positional arguments only: `f(1, 2)`fn area(w: int, h: int) int:
return w * h
fn main():
a = area(2, 3)
print(a)6& needs a variable, field, or element
&x passes a place that a mut parameter can change. A literal or a computed value has no place to change.
fn inc(n: mut int):
n += 1
fn main():
inc(&5)5: error: `&` needs a variable, field, or elementfn inc(n: mut int):
n += 1
fn main():
x = 5
inc(&x)
print(x)6export goes before fn
Only functions can be exported (for C, JavaScript, or Swift callers). Structs and enums can't.
export struct Point:
x: int
fn main():
pass1: error: `export` goes before `fn`struct Point:
x: int
export fn origin_x() int:
return Point(0).x
fn main():
print(origin_x())0function NAME is defined twice
There is no overloading: each function name in a module is used once. Give the second one another name.
fn show(n: int):
print(n)
fn show(s: str):
print(s)
fn main():
show(1)4: error: function `show` is defined twicefn show_int(n: int):
print(n)
fn show_str(s: str):
print(s)
fn main():
show_int(1)
show_str("a")1
aNAME is defined twice
Two enums (or an enum and a struct) have the same name.
enum Color:
Red
enum Color:
Blue
fn main():
pass4: error: `Color` is defined twiceenum Color:
Red
Blue
fn main():
print(Color.Blue)Color.Blueenum NAME has two variants named VARIANT
Each variant of an enum needs its own name.
enum Light:
Red
Red
fn main():
pass3: error: enum `Light` has two variants named `Red`enum Light:
Red
Green
fn main():
print(Light.Green)Light.GreenHabits from other languages
These are syntax or name errors whose hint recognizes a habit from Python, JavaScript, Go, Rust, or C. The headings here are the hint text, since the error itself (expected ... or unexpected ...) says little on its own.
functions are written fn name(x: int, y: str) int: (return type after the ))
def add(a, b):
return a + b
fn main():
pass1: error: expected `fn`, `struct`, `enum`, `type`, `const`, or `extern` at the top level
1: hint: functions are written `fn name(x: int, y: str) int:` (return type after the `)`)fn add(a: int, b: int) int:
return a + b
fn main():
print(add(2, 3))5there are no classes: declare data with struct Name: (fields only)
class Point:
x: int
fn main():
pass1: error: expected `fn`, `struct`, `enum`, `type`, `const`, or `extern` at the top level
1: hint: there are no classes: declare data with `struct Name:` (fields only) and write functions that take it first; `p.f()` calls `f(p)`struct Point:
x: int
fn shifted(p: Point, dx: int) Point:
return Point(p.x + dx)
fn main():
p = Point(1)
print(p.shifted(2))Point{x: 3}variables are created by assigning: x = 5 (no let/var/const)
fn main():
let x = 52: error: expected end of line, found 'x'
2: hint: variables are created by assigning: `x = 5` (no let/var/const)fn main():
x = 5
print(x)5variables are created with =: x = 5
fn main():
x := 52: error: expected a name, found '='
2: hint: variables are created with `=`: `x = 5`fn main():
x = 5
print(x)5write and / write or / write not x
Logic operators are words.
fn main():
a = true
b = false
if a && b:
print("both")4: error: expected `:`, found '&&'
4: hint: write `and`fn main():
a = true
b = false
if a and not b:
print("a only")a onlywrite elif cond:
fn main():
x = 1
if x > 1:
print("big")
else if x > 0:
print("small")5: error: expected `:`, found 'if'
5: hint: write `elif cond:`fn main():
x = 1
if x > 1:
print("big")
elif x > 0:
print("small")smallwrite x += 1 / x -= 1
There is no ++ or --.
fn main():
x = 1
x++3: error: unexpected '+'
3: hint: write `x += 1` / `x -= 1`fn main():
x = 1
x += 1
print(x)2statements end at the line end; remove the ;
fn main():
x = 1;2: error: unexpected character ';'
2: hint: statements end at the line end; remove the `;`fn main():
x = 1
print(x)1strings use double quotes: "text" (or text, raw, when it holds double quotes)
fn main():
name = 'ada'2: error: unexpected character "'"
2: hint: strings use double quotes: "text" (or `text`, raw, when it holds double quotes)fn main():
name = "ada"
print(name)adathere is no c ? a : b; write a if c else b
fn main():
n = 3
label = n > 2 ? "big" : "small"3: error: expected end of line, found 'big'
3: hint: there is no `c ? a : b`; write `a if c else b`fn main():
n = 3
label = "big" if n > 2 else "small"
print(label)biglambdas are written fn(x) x + 1 (one expression)
fn main():
inc = lambda x: x + 12: error: expected end of line, found 'x'
2: hint: lambdas are written `fn(x) x + 1` (one expression)fn main():
inc = fn(x: int) x + 1
print(inc(1))2a lambda is one expression with no colon: fn(x) x * 2
A lambda can't hold statements. For more than one line, define a nested fn and pass it by name.
fn main():
xs = [1, 2, 3]
ys = xs.map(fn(x):
return x * 2)3: error: unexpected ':'
3: hint: a lambda is one expression with no colon: `fn(x) x * 2`; for more lines, define a nested `fn name(...)` and pass `name`fn main():
xs = [1, 2, 3]
fn double(x: int) int:
y = x * 2
return y
print(xs.map(double), xs.map(fn(x) x * 2))[2, 4, 6] [2, 4, 6]there are no comprehensions: xs.map(fn(x) ...) and xs.filter(fn(x) ...)
fn main():
xs = [1, 2, 3]
ys = [x * 2 for x in xs]3: error: expected `,`, found 'for'
3: hint: there are no comprehensions: `xs.map(fn(x) ...)` and `xs.filter(fn(x) ...)`, or a loop with `push`fn main():
xs = [1, 2, 3]
ys = xs.map(fn(x) x * 2)
print(ys)[2, 4, 6]write not (x in xs)
There is no not in operator. not binds tighter than in, so the parentheses are needed.
fn main():
ages = {"ada": 36}
if "bob" not in ages:
print("no bob")3: error: expected `:`, found 'not'
3: hint: write `not (x in xs)`fn main():
ages = {"ada": 36}
if not ("bob" in ages):
print("no bob")no bobinteger literal ... is too big for an int
An int is 64 bits: decimal literals go up to 9223372036854775807. For bigger numbers use a float (1e20); for bit patterns, a hex literal may use all 64 bits (0xffff_ffff_ffff_ffff).
fn main():
big = 999999999999999999992: error: integer literal 99999999999999999999 is too big for an int (the largest is 9223372036854775807)fn main():
big = 1_000_000_000
print(big)1000000000parameters are written name: type, e.g. fn f(a: int, b: str)
fn half(n int) int:
return n / 2
fn main():
pass1: error: expected `:`, found 'int'
1: hint: parameters are written `name: type`, e.g. `fn f(a: int, b: str)`fn half(n: int) int:
return n / 2
fn main():
print(half(9))4there is no self: take the struct as a normal parameter
struct Rect:
w, h: int
fn area(self) int:
return self.w * self.h
fn main():
pass4: error: expected `:`, found ')'
4: hint: there is no `self`: take the struct as a normal parameter, `fn area(r: Rect) float:`struct Rect:
w, h: int
fn area(r: Rect) int:
return r.w * r.h
fn main():
r = Rect(2, 3)
print(r.area())6min_max returns int, not (int,int)
A function returns several values as a tuple, and its return type must say so:
fn min_max(xs: [int]) int:
return 1, 9
fn main():
pass2: error: `min_max` returns int, not (int,int)fn min_max(xs: [int]) (int, int):
lo = xs[0]
hi = xs[0]
for x in xs:
lo = min(lo, x)
hi = max(hi, x)
return lo, hi
fn main():
lo, hi = min_max([4, 1, 9])
print(lo, hi)1 9import math, then math.pow(x, y) (floats)
There is no ** operator.
fn main():
print(2 ** 10)2: error: unexpected '*'
2: hint: `import math`, then `math.pow(x, y)` (floats)import math
fn main():
print(math.pow(2.0, 10.0))1024.0/ on two ints already divides without a remainder; comments start with #
There is no // operator. / on two ints truncates toward zero.
fn main():
print(7 // 2)2: error: unexpected '/'
2: hint: `/` on two ints already divides without a remainder; comments start with `#`fn main():
print(7 / 2) # integer division3there are no exceptions: return a bool or a status enum
fn main():
try:
print(1)2: error: expected a name, found end of line
2: hint: there are no exceptions: return a bool or a status enum, and handle it with `if` or `match`struct Parsed:
ok: bool
value: int
fn parse_age(s: str) Parsed:
n = s.to_int(-1)
if n < 0:
return Parsed(false, 0)
return Parsed(true, n)
fn main():
p = parse_age("x")
if not p.ok:
print("not a number")not a numberuse match value: with one arm per case (_: for the default)
fn main():
code = 404
switch code:
pass3: error: expected end of line, found 'code'
3: hint: use `match value:` with one arm per case (`_:` for the default)fn main():
code = 404
match code:
200:
print("ok")
_:
print("error", code)error 404match arms are Pattern: followed by an indented block
fn main():
code = 200
match code:
200 => print("ok")4: error: expected `:`, found '='
4: hint: match arms are `Pattern:` followed by an indented block (or `Pattern: stmt` on one line); lambdas are `fn(x) x + 1`fn main():
code = 200
match code:
200: print("ok")
_: passokimport standard modules by their name: import math, import http
import std.math
fn main():
pass1: error: expected end of line, found '.'
1: hint: import standard modules by their name: `import math`, `import http`import math
fn main():
print(math.sqrt(16.0))4.0array types are [int], map types {str: int}, tuple types (int, str), and a generic type's arguments go in [ ] (Pair[int, str]); there are no set or Option types
fn total(xs: Vec<int>) int:
return 0
fn main():
pass1: error: expected `,`, found '<'
1: hint: array types are `[int]`, map types `{str: int}`, tuple types `(int, str)`, and a generic type's arguments go in `[ ]` (`Pair[int, str]`, `Option[int]`); there is no set typefn total(xs: [int]) int:
t = 0
for x in xs:
t += x
return t
fn main():
print(total([1, 2, 3]))6Blocks written with braces
Braces don't make blocks, and there is no hint for this yet: { opens a map literal, so the error is reported on a later line and can be confusing. Use : and indentation.
fn main() {
print(1)
}2: error: expected `:`, found '('
2: hint: blocks use `:` and indentation, not bracesfn main():
print(1)1Names and types
unknown variable NAME
The name isn't a variable in scope. Usually it is a typo (the hint suggests a close name), a variable created inside a block and used after it, or a name from another language (True, None, self). A variable lives until the end of the block that created it, so create it before the if or loop if you need it after.
fn main():
total = 0
for x in [1, 2, 3]:
total += x
print(totl)5: error: unknown variable `totl`
5: hint: did you mean `total`?fn main():
total = 0
for x in [1, 2, 3]:
total += x
print(total)6Booleans are lowercase. None exists, as the empty Option, but it needs to know what kind of Option it is:
fn main():
found = None2: error: can't tell what kind of `None` this is; give it a type, e.g. `x: Option[int] = ...`, or write `Option[int].None`fn main():
found: Option[int] = None
print(found, found.unwrap_or(-1))None -1NAME is a module; add import NAME at the top of this file
The code uses a standard module (math, fs, json, ...) without importing it.
fn main():
print(math.pi())2: error: `math` is a module; add `import math` at the top of this file
2: error: unknown function `pi`
2: hint: `x.f(...)` calls a function `f(x, ...)`; there is no such function (see `tern guide`)The first error is the one to fix; the second goes away with it. Note that for math.sqrt, math.floor, and the other names that are also builtins, a missing import can instead show up as a wrong argument count.
import math
fn main():
print(math.pi())3.141592653589793unknown type NAME
The type doesn't exist. Tern's types are int, float, bool, str, [T], {K: V}, fn(...), ptr, and your structs and enums; names from other languages (string, i32, f64, list, dict, Vec) get a hint.
fn show_name(name: string):
print(name)
fn main():
pass1: error: unknown type `string`
1: hint: write strfn show_name(name: str):
print(name)
fn main():
show_name("ada")adaunknown function NAME
No function, builtin, or local function value has this name. The hint covers common names from other languages (range, append, sort, input, enumerate, strip, ...) and close spellings.
fn main():
for i in range(3):
print(i)2: error: unknown function `range`
2: hint: there is no range(): write `for i in 0..n:` (or `for i in a..b:`; the end is exclusive)fn main():
for i in 0..3:
print(i)0
1
2xs.f(...) is a call to a function f(xs, ...), so a missing method is also an unknown function:
fn main():
xs = [1, 2]
xs.append(3)3: error: unknown function `append`
3: hint: arrays grow with `xs.push(value)`fn main():
xs = [1, 2]
xs.push(3)
print(xs)[1, 2, 3]NAME is declared as TYPE but the value is TYPE
A variable with a stated type (x: int = ...) was given a value of another type. There are no implicit conversions.
fn main():
ratio: float = 12: error: `ratio` is declared as float but the value is intfn main():
ratio: float = 1.0
print(ratio)1.0can't assign TYPE to NAME of type TYPE
A variable's type is fixed by its first assignment. Use a new variable for a value of another type, or convert.
fn main():
count = 3
count = "three"3: error: can't assign str to `count` of type intfn main():
count = 3
label = str(count)
print(label)3can't tell what NAME holds; add a type, e.g. NAME: [int] = []
An empty [] or {} gets its type from how it is used later (for example the first push). If nothing ever says what goes in it, the type must be written.
fn main():
names = []
print(len(names))2: error: can't tell what `names` holds; add a type, e.g. `names: [int] = []`fn main():
names: [str] = []
print(len(names))0can't tell the type of an empty array; add a type, e.g. xs: [int] = []
An empty array literal appears where nothing says its element type, such as a direct argument to print.
fn main():
print([])2: error: can't tell the type of an empty array; add a type, e.g. `xs: [int] = []`fn main():
empty: [int] = []
print(empty)[]can't tell the type of an empty map; add a type, e.g. m: {str: int} = {}
The same, for an empty map literal.
fn main():
print({})2: error: can't tell the type of an empty map; add a type, e.g. `m: {str: int} = {}`fn main():
empty: {str: int} = {}
print(empty){}this expression has no value
A function with no return type was used as a value.
fn log(msg: str):
print(msg)
fn main():
x = log("hi")5: error: this expression has no valuefn log(msg: str):
print(msg)
fn main():
log("hi")himap keys must be int, str, bool, or arrays, structs, enums, or tuples of those (no floats or functions), not TYPE
A map key must hash and compare exactly, so floats (where 0.1 + 0.2 != 0.3) and functions can't be keys, nor structs that hold them. For a float key, scale it to an int.
fn main():
prices: {float: str} = {}2: error: map keys must be int, str, bool, or arrays, structs, enums, or tuples of those (no floats or functions), not floatfn main():
prices: {int: str} = {}
prices[150] = "cheap" # 1.50 in cents
print(prices){150: "cheap"}NAME is a builtin, so an extern or exported function can't have that name
Your own functions may share a builtin's name (builtin names), but a function in an extern block or an export fn can't: C sees its name. Rename an extern function with = "c_name", and pick another name for an exported one.
extern "stdlib.h":
fn abs(n: int) int
fn main():
print(abs(-7))2: error: `abs` is a builtin, so an extern or exported function can't have that nameextern "stdlib.h":
fn c_abs(n: int) int = "labs"
fn main():
print(c_abs(-7))7no fn main() found (a test file? name it *_test.tn and run tern test; a library? tern build --lib)
A program starts at fn main():. A file with only helper functions can be imported by another file, or built as a C library with build --lib (its export fn functions become the library's API). Test files (*_test.tn) have no main: tern test runs them, and tern check checks them without one.
fn helper() int:
return 11: error: no `fn main()` found (a test file? name it *_test.tn and run `tern test`; a library? `tern build --lib`)fn helper() int:
return 1
fn main():
print(helper())1Operators and conversions
NUMBER doesn't fit in a byte (0 to 255); byte(NUMBER) keeps its low 8 bits
A literal where a byte is expected must be from 0 to 255. To wrap a bigger number around on purpose, convert it with byte(...).
fn main():
level: byte = 300
print(level)2: error: 300 doesn't fit in a byte (0 to 255); byte(300) keeps its low 8 bitsfn main():
level: byte = 255
print(level, byte(300))255 44can't assign int to NAME of type byte: convert with byte(...), which keeps the low 8 bits
Arithmetic on bytes gives an int, so storing the result back into a byte takes byte(...). (b += n and the other op= forms wrap on their own.)
fn main():
b: byte = 200
n = 100
b = b + n
print(b)4: error: can't assign int to `b` of type byte: convert with byte(...), which keeps the low 8 bitsfn main():
b: byte = 200
n = 100
b = byte(b + n)
c: byte = 200
c += n
print(b, c)44 44OP with mismatched types TYPE and TYPE (use float()/int() to convert)
Both sides of an arithmetic or comparison operator must have the same type. Ints and floats never mix.
fn main():
n = 3
avg = 10.0 / n3: error: `/` with mismatched types float and int (use float()/int() to convert)
3: hint: ints and floats never mix: `float(i) * x` or `i * int(x)`fn main():
n = 3
avg = 10.0 / float(n)
print(avg)3.3333333333333335For str + int the parenthetical advice doesn't apply: convert the number with str(), or use an f-string, as the hint says.
fn main():
n = 3
print("n=" + n)3: error: `+` with mismatched types str and int (use float()/int() to convert)
3: hint: convert with `str(n)` ("n=" + str(n)) or use an f-string: f"n={n}"fn main():
n = 3
print("n=" + str(n), f"n={n}")n=3 n=3OP needs numbers, not TYPE
Arithmetic works on int and float only (and + on strings).
fn main():
print(true + false)2: error: `+` needs numbers, not boolfn main():
a = true
b = false
count = 0
if a:
count += 1
if b:
count += 1
print(count)1% needs ints
The remainder operator works on ints only. For floats, use x - math.floor(x / y) * y.
fn main():
print(7.5 % 2.0)2: error: `%` needs intsimport math
fn main():
x = 7.5
y = 2.0
print(7 % 2, x - math.floor(x / y) * y)1 1.5OP doesn't work on strings (use + to join them)
Strings support + (join) and * (repeat), not - or /. To remove text, use replace.
fn main():
print("report.txt" - ".txt")2: error: `-` doesn't work on strings (use + to join them)fn main():
print("report.txt".replace(".txt", ""))reportOP needs bools
and and or work on bool values only. There is no truthiness: compare explicitly.
fn main():
n = 3
m = 0
if n and m:
print("both")4: error: `and` needs boolsfn main():
n = 3
m = 0
if n != 0 and m != 0:
print("both")
else:
print("not both")not bothnot needs a bool
not applies to a bool. It binds tighter than == and in, so not x == 2 means (not x) == 2. Add parentheses, or use !=.
fn main():
x = 1
if not x == 2:
print(x)3: error: `not` needs a bool
3: hint: `not` binds tighter than comparisons and `in`: write `not (a == b)`, `not (k in m)`, or use `!=`
3: error: `==` with mismatched types bool and int (use float()/int() to convert)fn main():
x = 1
if x != 2:
print(x)1can't negate TYPE
Unary - works on int and float only.
fn main():
s = "5"
print(-s)3: error: can't negate strfn main():
s = "5"
print(-s.to_int(0))-5OP can't compare TYPE: functions, channels, tasks, and shared cells have no equality
== and != compare any values field by field and element by element (structs, arrays, maps, tuples, enums), except those holding a function or a task handle. Compare the other fields yourself:
struct Button:
label: str
on_click: fn(int) int
fn main():
a = Button("ok", fn(x) x)
print(a == a)7: error: `==` can't compare Button: functions, channels, tasks, and shared cells have no equalitystruct Button:
label: str
on_click: fn(int) int
fn main():
a = Button("ok", fn(x) x)
print(a.label == "ok", [1, 2] == [1, 2])true trueOP needs numbers or strings, not TYPE
<, <=, >, and >= work on int, float, and str (strings compare by bytes).
fn main():
print(true < false)2: error: `<` needs numbers or strings, not boolfn main():
print(1 < 2, "apple" < "banana")true truecondition must be a bool
if, elif, and while need a bool. There is no truthiness for numbers, strings, or arrays.
fn main():
xs = [1]
if len(xs):
print("not empty")3: error: condition must be a boolfn main():
xs = [1]
if len(xs) > 0:
print("not empty")not emptyin a str looks for a substring, not TYPE
x in s on a string checks for a substring, so x must be a str.
fn main():
print(1 in "a1b")2: error: `in` a str looks for a substring, not intfn main():
print("1" in "a1b", str(1) in "a1b")true truein needs an element of TYPE
x in xs on an array checks for an element, so x must have the element type.
fn main():
ids = [1, 2, 3]
print("2" in ids)3: error: `in` needs an element of [int]fn main():
ids = [1, 2, 3]
print(2 in ids)truein needs a key of TYPE
k in m on a map checks for a key, so k must have the key type.
fn main():
ages = {"ada": 36}
print(36 in ages)3: error: `in` needs a key of {str:int}fn main():
ages = {"ada": 36}
print("ada" in ages, 36 in ages.values())true truein works on str, arrays, and maps, not TYPE
fn main():
n = 12
print(1 in n)3: error: `in` works on str, arrays, and maps, not intfn main():
n = 12
print("1" in str(n))truef-strings can show int, float, bool, or str values, not TYPE
An f-string {...} takes a number, bool, or string. For arrays, maps, and structs, pass the value to print separately, or turn it into text with json.encode.
fn main():
xs = [1, 2]
print(f"xs = {xs}")3: error: f-strings can show int, float, bool, or str values, not [int]
3: hint: pass it to print separately, `print("xs =", xs)`, or `import json` and use `{json.encode(xs)}`import json
fn main():
xs = [1, 2]
print("xs =", xs)
print(f"xs = {json.encode(xs)}")xs = [1, 2]
xs = [1,2]str() converts int, float, bool, or str, not TYPE
fn main():
xs = [1, 2]
label = str(xs)3: error: str() converts int, float, bool, or str, not [int]
3: hint: `print` shows any value; for text, `import json` and use `json.encode(x)`import json
fn main():
xs = [1, 2]
label = json.encode(xs)
print(label)[1,2]int() needs a float
int() converts a float to an int (truncating). It doesn't parse strings: use s.to_int(default). (The hint about parsing strings is also shown for int(true); for a bool, use an if.)
fn main():
n = int("42")2: error: int() needs a float
2: hint: to parse a string, use `s.to_int(default)`, e.g. `"42".to_int(0)`fn main():
n = "42".to_int(0)
m = int(2.9)
print(n, m)42 2sqrt() needs a float
fn main():
n = 16
print(sqrt(n))3: error: sqrt() needs a float
3: hint: convert first: `sqrt(float(n))`fn main():
n = 16
print(sqrt(float(n)))4.0abs() needs a number
fn main():
print(abs("-3"))2: error: abs() needs a numberfn main():
print(abs(-3), abs(-2.5))3 2.5min() needs two numbers of the same type
min and max take exactly two numbers of one type. For the smallest element of an array, loop.
fn main():
print(min(1, 2.5))2: error: min() needs two numbers of the same typefn main():
print(min(1, 2), max(1.0, 2.5))
xs = [4, 1, 9]
lo = xs[0]
for x in xs:
lo = min(lo, x)
print(lo)1 2.5
1chr() needs an int (a byte value 0-255)
fn main():
print(chr("A"))2: error: chr() needs an int (a byte value 0-255)fn main():
print(chr(65), "A".byte(0))A 65Functions and calls
function NAME must end with a return
A function with a return type must return on every path. The compiler doesn't reason about which conditions are possible, so an if/elif chain without a final else or return is not enough.
fn sign(n: int) int:
if n > 0:
return 1
elif n < 0:
return -1
fn main():
pass1: error: function `sign` must end with a `return`fn sign(n: int) int:
if n > 0:
return 1
elif n < 0:
return -1
return 0
fn main():
print(sign(-5))-1NAME must return a TYPE
A bare return in a function that has a return type.
fn first_even(xs: [int]) int:
for x in xs:
if x % 2 == 0:
return
return -1
fn main():
pass4: error: `first_even` must return a intfn first_even(xs: [int]) int:
for x in xs:
if x % 2 == 0:
return x
return -1
fn main():
print(first_even([3, 4]))4NAME doesn't return a value
return value in a function without a return type. Add the return type after the ).
fn double(n: int):
return n * 2
fn main():
pass2: error: `double` doesn't return a valuefn double(n: int) int:
return n * 2
fn main():
print(double(4))8NAME returns TYPE, not TYPE
The returned value doesn't match the declared return type.
fn label(n: int) str:
return n
fn main():
pass2: error: `label` returns str, not intfn label(n: int) str:
return str(n)
fn main():
print(label(4))4NAME takes N argument(s), got N
There are no default values or variadic parameters. Pass every argument.
fn area(w: int, h: int) int:
return w * h
fn main():
print(area(3))5: error: `area` takes 2 argument(s), got 1fn area(w: int, h: int) int:
return w * h
fn main():
print(area(3, 3))9argument N of NAME should be TYPE, not TYPE
The argument has the wrong type.
fn repeat_word(w: str, n: int) str:
return w * n
fn main():
print(repeat_word("ab", "3"))5: error: argument 2 of `repeat_word` should be int, not strfn repeat_word(w: str, n: int) str:
return w * n
fn main():
print(repeat_word("ab", "3".to_int(1)))abababNAME is a TYPE, not a function
Something that isn't a function was called. Often a variable shadows a function name.
fn main():
total = 5
print(total(3))3: error: `total` is an int, not a functionfn main():
total = 5
print(total * 3)15Structs
struct NAME contains itself by value (values can't be infinite; use an enum with a variant for "none", or an array)
Every value is stored inline, so a struct holding itself would be infinitely large. An array of itself is fine (it may be empty), and so is a recursive enum.
struct Node:
value: int
next: Node
fn main():
pass1: error: struct `Node` contains itself by value (values can't be infinite; use an enum with a variant for "none", or an array)struct Node:
value: int
children: [Node]
fn main():
leaf = Node(2, [])
root = Node(1, [leaf])
print(root)Node{value: 1, children: [Node{value: 2, children: []}]}STRUCT has N fields, got N values
A struct is built with every field, in order (or by name). Too many values were given.
struct Point:
x, y: int
fn main():
p = Point(1, 2, 3)5: error: Point has 2 fields, got 3 valuesstruct Point:
x, y: int
fn main():
p = Point(1, 2)
print(p)Point{x: 1, y: 2}missing field FIELD in STRUCT
Every field must be given; there are no default field values. Write a constructor function if you want defaults.
struct User:
name: str
admin: bool
fn main():
u = User("ada")6: error: missing field `admin` in Userstruct User:
name: str
admin: bool
fn new_user(name: str) User:
return User(name, false)
fn main():
print(new_user("ada"))User{name: "ada", admin: false}field FIELD given twice
The same field was given by position and by name, or twice by name.
struct Point:
x, y: int
fn main():
p = Point(1, x=2)5: error: field `x` given twice
5: error: missing field `y` in Pointx was given by position and again by name, so y was never given; both are reported.
struct Point:
x, y: int
fn main():
p = Point(1, y=3)
print(p)Point{x: 1, y: 3}TYPE has no field FIELD
The struct has no field with this name, either in a constructor or in value.field. The hint suggests a close name. Arrays, maps, and strings have no fields at all: use len(x) and functions like s.upper().
struct User:
name: str
fn main():
u = User("ada")
print(u.nmae)6: error: User has no field `nmae`
6: hint: did you mean `name`?struct User:
name: str
fn main():
u = User("ada")
print(u.name)adafn main():
xs = [1, 2]
print(xs.length)3: error: [int] has no field `length`
3: hint: use `len(x)`fn main():
xs = [1, 2]
print(len(xs))2field FIELD is TYPE, not TYPE
A value in a struct constructor has the wrong type for its field.
struct Item:
name: str
qty: int
fn main():
it = Item("pen", "2")6: error: field `qty` is int, not strstruct Item:
name: str
qty: int
fn main():
it = Item("pen", 2)
print(it)Item{name: "pen", qty: 2}Enums
ENUM is an enum: build one of its variants, e.g. ENUM.VARIANT(...)
An enum value is always one of its variants. Name the variant. (For a variant without values, leave off the parentheses, even though the message shows (...).)
enum Color:
Red
Green
fn main():
c = Color()6: error: Color is an enum: build one of its variants, e.g. `Color.Red(...)`enum Color:
Red
Green
fn main():
c = Color.Green
print(c)Color.GreenENUM has no variant VARIANT (it has VARIANT, VARIANT, ...)
The variant name is misspelled or missing from the enum. The message lists the ones that exist. This error also appears for a pattern in match.
enum Color:
Red
Green
fn main():
c = Color.Blue6: error: Color has no variant `Blue` (it has Red, Green)enum Color:
Red
Green
Blue
fn main():
c = Color.Blue
print(c)Color.BlueENUM.VARIANT takes N value(s), got N
The variant was built with the wrong number of values.
enum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(1.0, 2.0)5: error: Shape.Circle takes 1 value(s), got 2enum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(1.0)
print(s)Shape.Circle(radius: 1.0)ENUM.VARIANT has no field NAME
A named value doesn't match any of the variant's fields.
enum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(r=1.0)5: error: Shape.Circle has no field `r`
5: error: missing `radius` in Shape.CircleThe compiler also reports missingradiusin Shape.Circle, since the real field was not given.
enum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(radius=1.0)
print(s)Shape.Circle(radius: 1.0)missing FIELD in ENUM.VARIANT
Every value of a variant must be given.
enum Shape:
Rect(w: float, h: float)
fn main():
s = Shape.Rect(w=2.0)5: error: missing `h` in Shape.Rectenum Shape:
Rect(w: float, h: float)
fn main():
s = Shape.Rect(w=2.0, h=3.0)
print(s)Shape.Rect(w: 2.0, h: 3.0)FIELD is TYPE, not TYPE
A value given to an enum variant has the wrong type.
enum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(1)5: error: `radius` is float, not intenum Shape:
Circle(radius: float)
fn main():
s = Shape.Circle(1.0)
print(s)Shape.Circle(radius: 1.0)ENUM is an enum: use match to get at its values
A variant's values can only be read with match, because the compiler can't know which variant a value holds until it checks.
enum Shape:
Circle(radius: float)
Square(side: float)
fn main():
s = Shape.Circle(2.0)
print(s.radius)7: error: Shape is an enum: use `match` to get at its valuesenum Shape:
Circle(radius: float)
Square(side: float)
fn main():
s = Shape.Circle(2.0)
match s:
Circle(r):
print(r)
Square(side):
print(side)2.0match works on enums, int, str, and bool, not TYPE
match can't compare floats, arrays, maps, or structs. Use if/elif for those.
fn main():
x = 1.5
match x:
_:
print(x)3: error: match works on enums, int, str, and bool, not floatfn main():
x = 1.5
if x < 1.0:
print("small")
else:
print("large")largeENUM is an enum: match its variants, not TYPE values
A literal pattern (a number, string, or bool) was used in a match on an enum.
enum Level:
Low
High
fn main():
lv = Level.Low
match lv:
0:
print("low")
_:
print("high")8: error: Level is an enum: match its variants, not int valuesenum Level:
Low
High
fn main():
lv = Level.Low
match lv:
Low:
print("low")
High:
print("high")lowthis pattern is TYPE, but the value being matched is TYPE
The literal in a pattern has a different type from the value being matched.
fn main():
code = 404
match code:
"404":
print("not found")4: error: this pattern is str, but the value being matched is intfn main():
code = 404
match code:
404:
print("not found")
_:
print("something else")not foundNAME is a variant pattern, but the value being matched is TYPE
A bare name in a pattern means an enum variant. Here the value is an int, str, or bool, so there are no variants. To match anything, use _.
fn main():
n = 7
match n:
other:
print(n)4: error: `other` is a variant pattern, but the value being matched is intfn main():
n = 7
match n:
_:
print(n)7ENUM.VARIANT doesn't match a TYPE
A qualified pattern names a variant of a different enum.
enum Light:
Red
Green
enum Alert:
Red
fn main():
l = Light.Red
match l:
Alert.Red:
print("stop")
_:
print("go")11: error: `Alert.Red` doesn't match a Lightenum Light:
Red
Green
enum Alert:
Red
fn main():
l = Light.Red
match l:
Light.Red:
print("stop")
_:
print("go")stopVARIANT is already handled above
A variant appears in two arms; the second could never run.
enum Light:
Red
Green
fn main():
l = Light.Red
match l:
Red:
print("stop")
Red:
print("halt")
Green:
print("go")10: error: `Red` is already handled aboveenum Light:
Red
Green
fn main():
l = Light.Red
match l:
Red:
print("stop")
Green:
print("go")stopENUM.VARIANT has N value(s): write VARIANT(a, b)
A pattern must bind every value of the variant, by position. Use _ for values you don't need.
enum Shape:
Rect(w: float, h: float)
fn main():
s = Shape.Rect(2.0, 3.0)
match s:
Rect(w):
print(w)7: error: Shape.Rect has 2 value(s): write `Rect(w, h)`enum Shape:
Rect(w: float, h: float)
fn main():
s = Shape.Rect(2.0, 3.0)
match s:
Rect(w, _):
print(w)2.0match on ENUM doesn't handle VARIANT, ... (add them, or a _: arm)
A match on an enum must cover every variant, so adding a variant later shows every place that needs to handle it. A match on int, str, or bool doesn't have to be complete.
enum Light:
Red
Yellow
Green
fn main():
l = Light.Red
match l:
Red:
print("stop")8: error: match on Light doesn't handle Yellow, Green (add them, or a `_:` arm)enum Light:
Red
Yellow
Green
fn main():
l = Light.Red
match l:
Red:
print("stop")
_:
print("go")stopcan't change NAME inside a match on it (its values are in use); change it after the match
The arm's bound values come from the value being matched, so it can't be replaced while the arm runs. Record what to do, and change it after the match.
enum State:
Loading(progress: int)
Done
fn main():
s = State.Loading(100)
match s:
Loading(p):
if p == 100:
s = State.Done
Done:
pass10: error: can't change `s` inside a `match` on it (its values are in use); change it after the matchenum State:
Loading(progress: int)
Done
fn main():
s = State.Loading(100)
finished = false
match s:
Loading(p):
finished = p == 100
Done:
pass
if finished:
s = State.Done
print(s)State.DoneArrays, maps, and strings
can't index into TYPE
Only arrays (xs[i]), maps (m[k]), and strings (s[i]) can be indexed.
fn main():
n = 1234
print(n[0])3: error: can't index into intfn main():
n = 1234
print(str(n)[0])1array index must be an int
fn main():
xs = [10, 20]
print(xs["0"])3: error: array index must be an intfn main():
xs = [10, 20]
print(xs[0])10this map's keys are TYPE
The index has a different type from the map's keys.
fn main():
ages = {"ada": 36}
print(ages[0])3: error: this map's keys are strfn main():
ages = {"ada": 36}
print(ages["ada"])36can only slice a str or an array, not TYPE
fn main():
ages = {"ada": 36, "bob": 25}
print(ages[..1])3: error: can only slice a str or an array, not {str:int}fn main():
ages = {"ada": 36, "bob": 25}
print(ages.keys()[..1])["ada"]slice bounds must be ints
fn main():
s = "hello"
print(s[1.0..])3: error: slice bounds must be intsfn main():
s = "hello"
print(s[1..])ello[value] * n: n must be an int
fn main():
zeros = [0] * 3.02: error: `[value] * n`: n must be an intfn main():
zeros = [0] * 3
print(zeros)[0, 0, 0]array mixes TYPE and TYPE
All elements of an array have one type. Ints and floats don't mix; for different kinds of values, use a struct or an enum.
fn main():
xs = [1, 2.5]2: error: array mixes int and floatfn main():
xs = [1.0, 2.5]
print(xs)[1.0, 2.5]map mixes TYPE: TYPE with TYPE: TYPE
All keys of a map have one type, and all values have one type.
fn main():
config = {"port": 8080, "host": "localhost"}2: error: map mixes str: int with str: strstruct Config:
port: int
host: str
fn main():
config = Config(8080, "localhost")
print(config)Config{port: 8080, host: "localhost"}len() needs a str, array, map, or channel, not TYPE
fn main():
n = 1234
print(len(n))3: error: len() needs a str, array, map, or channel, not intfn main():
n = 1234
print(len(str(n)))4push() needs an array, not TYPE
push adds to the end of an array. Maps grow with m[k] = v; strings with +=.
fn main():
s = "ab"
s.push("c")3: error: push() needs an array, not strfn main():
s = "ab"
s += "c"
print(s)abcargument 2 of push should be TYPE, not TYPE
The pushed value doesn't match the array's element type.
fn main():
xs = [1, 2]
xs.push("3")3: error: argument 2 of `push` should be int, not strfn main():
xs = [1, 2]
xs.push("3".to_int(0))
print(xs)[1, 2, 3]pop() needs an array, not TYPE
fn main():
s = "abc"
last = s.pop()3: error: pop() needs an array, not strfn main():
s = "abc"
last = s[len(s) - 1]
s = s[..len(s) - 1]
print(last, s)c abNAME() works on maps, not TYPE
get, remove, keys, and values are map functions. To remove from an array, build a new one with filter or a loop.
fn main():
xs = [5, 6, 7]
xs.remove(1)3: error: remove() works on maps, not [int]fn main():
xs = [5, 6, 7]
xs = xs.filter(fn(x) x != 6)
print(xs)[5, 7]get(): the key should be TYPE, not TYPE
fn main():
ages = {"ada": 36}
print(ages.get(0, -1))3: error: get(): the key should be str, not intfn main():
ages = {"ada": 36}
print(ages.get("zed", -1))-1get(): the default should be TYPE, not TYPE
The default is returned when the key is missing, so it must have the value type.
fn main():
ages = {"ada": 36}
print(ages.get("zed", "unknown"))3: error: get(): the default should be int, not strfn main():
ages = {"ada": 36}
print(ages.get("zed", -1))-1strings can't be changed in place; build a new one, e.g. s = s[..i] + x + s[i + 1..]
Strings are immutable values. Build a new string and assign it.
fn main():
s = "cat"
s[0] = "b"3: error: strings can't be changed in place; build a new one, e.g. `s = s[..i] + x + s[i + 1..]`fn main():
s = "cat"
s = "b" + s[1..]
print(s)batNAME modifies its receiver, so it needs a variable, field, or element
xs.push(v) and xs.pop() change xs, so xs must be something that can be changed, not a literal or a function result. The compiler also reports can only modify a variable, field, or element on the same line.
fn main():
print([1, 2, 3].pop())2: error: `pop` modifies its receiver, so it needs a variable, field, or element
2: error: can only modify a variable, field, or elementfn main():
xs = [1, 2, 3]
print(xs.pop(), xs)3 [1, 2]map(xs, f) needs an array and a function, not TYPE and TYPE
map, filter, and sort_by take an array and a function. The message may be preceded by an argument error that mentions a type like fn(int)?; the ? there means "any return type".
fn main():
xs = [1, 2]
print(xs.map(2))3: error: argument 2 of `map` should be fn(int)?, not int
3: error: map(xs, f) needs an array and a function, not [int] and intfn main():
xs = [1, 2]
print(xs.map(fn(x) x * 2))[2, 4]NAME(): the function should take one TYPE
The function passed to map, filter, or sort_by must take one value of the array's element type.
fn shout(s: str) str:
return s.upper()
fn main():
xs = [1, 2]
print(xs.map(shout))6: error: argument 2 of `map` should be fn(int)?, not fn(str)str
6: error: map(): the function should take one intfn shout(s: str) str:
return s.upper()
fn main():
xs = ["a", "b"]
print(xs.map(shout))["A", "B"]map(): the function must return a value
fn show(x: int):
print(x)
fn main():
xs = [1, 2]
ys = xs.map(show)6: error: map(): the function must return a valuefn main():
xs = [1, 2]
for x in xs:
print(x)1
2filter(): the function should return bool, not TYPE
For a lambda, the same mistake is reported as this function should return bool, not TYPE.
fn double(x: int) int:
return x * 2
fn main():
xs = [1, 2, 3]
print(xs.filter(double))6: error: argument 2 of `filter` should be fn(int)bool, not fn(int)int
6: error: filter(): the function should return bool, not intfn is_even(x: int) bool:
return x % 2 == 0
fn main():
xs = [1, 2, 3]
print(xs.filter(is_even))[2]sort_by(): the function should return an int, float, f32, or str to sort by, not TYPE
sort_by takes a key function. It can't sort by a bool, array, or struct directly; turn it into a number or string.
fn main():
words = ["pear", "fig"]
print(words.sort_by(fn(w) len(w) > 3))3: error: sort_by(): the function should return an int, float, f32, or str to sort by, not boolfn main():
words = ["pear", "fig"]
print(words.sort_by(fn(w) len(w)))["fig", "pear"]Mutation, mut, and &
Tern has no references: every value is a copy, and a function can change a caller's variable only through a mut parameter, marked with & at the call. These errors enforce that. See Values, mut, and &.
can't modify parameter NAME: parameters are read-only unless declared mut
A parameter is the caller's value, lent to the function. Changing it would either change the caller's variable behind its back or silently change only a copy, so it is refused. Copy it to a local variable, return the new value, or declare it mut.
fn add_tax(price: float) float:
price = price * 1.2
return price
fn main():
pass2: error: can't modify parameter `price`: parameters are read-only unless declared `mut`
2: hint: to change only a local copy, copy it first (`price2 = price`) and change `price2`; to change the caller's value, declare `price: mut T` and call with `f(&x)` or `x.f()`fn with_tax(price: float) float:
return price * 1.2
fn add_tax(price: mut float):
price = price * 1.2
fn main():
p = 10.0
print(with_tax(p))
add_tax(&p)
print(p)12.0
12.0This includes push, pop, and field assignment on a parameter:
fn add_default(tags: [str]):
tags.push("new")
fn main():
pass2: error: can't modify parameter `tags`: parameters are read-only unless declared `mut`
2: hint: to change only a local copy, copy it first (`tags2 = tags`) and change `tags2`; to change the caller's value, declare `tags: mut T` and call with `f(&x)` or `x.f()`fn add_default(tags: mut [str]):
tags.push("new")
fn main():
tags = ["a"]
tags.add_default()
print(tags)["a", "new"]can't modify loop variable NAME
The loop variable is a copy of the current element (or index). Assigning to it would not change the array, so it is refused. To change elements, loop over indices.
fn main():
prices = [10, 20]
for p in prices:
p = p * 24: error: can't modify loop variable `p`fn main():
prices = [10, 20]
for i in 0..len(prices):
prices[i] = prices[i] * 2
print(prices)[20, 40]can only modify a variable, field, or element
A mut argument or a changing method call needs a place to write to. A function result or literal isn't one.
fn items() [int]:
return [1, 2]
fn main():
items()[0] = 55: error: can only modify a variable, field, or elementfn items() [int]:
return [1, 2]
fn main():
xs = items()
xs[0] = 5
print(xs)[5, 2]argument N of NAME is mut: write &x so the change is visible here
A mut parameter changes the caller's variable, and Tern requires the caller to say so with &, so every change is visible at the call.
fn reset(n: mut int):
n = 0
fn main():
count = 5
reset(count)6: error: argument 1 of `reset` is `mut`: write `&count` so the change is visible herefn reset(n: mut int):
n = 0
fn main():
count = 5
reset(&count)
print(count)0argument N of NAME isn't mut, so don't pass it with &
& promises that the function may change the argument. This parameter is read-only, so the & would be misleading.
fn show(n: int):
print(n)
fn main():
count = 5
show(&count)6: error: argument 1 of `show` isn't `mut`, so don't pass it with `&`fn show(n: int):
print(n)
fn main():
count = 5
show(count)5& is only for passing an argument to a mut parameter
There are no references or pointers to Tern values. &x only appears as an argument.
fn main():
x = 1
y = &x3: error: `&` is only for passing an argument to a `mut` parameterfn main():
x = 1
y = x # a copy
y += 1
print(x, y)1 2can't assign to function NAME
A nested function's name refers to the function; it isn't a variable. (It is reported together with a type error.)
fn main():
fn limit() int:
return 5
limit = 104: error: can't assign int to `limit` of type fn()int
4: error: can't assign to function `limit`fn main():
fn limit() int:
return 5
max_items = limit()
max_items = 10
print(max_items)10Aliasing
NAME would see the same value twice: &PLACE can be changed, but PLACE is also passed (argument N)
A function that takes a mut parameter may assume nothing else it can see changes at the same time. Passing the same variable twice breaks that (in transfer(&a, &a, 30) the second write would undo the first). Tern refuses the call. For array elements it can't prove two indices differ, so f(&xs[i], &xs[j]) is refused too.
struct Account:
balance: int
fn transfer(src: mut Account, dst: mut Account, amount: int):
src.balance -= amount
dst.balance += amount
fn main():
a = Account(100)
transfer(&a, &a, 30)10: error: `transfer` would see the same value twice: `&a` can be changed, but `a` is also passed (argument 2)If you do need the function to read a value while changing it, pass a copy:
fn add_all(xs: mut [int], ys: [int]):
for y in ys:
xs.push(y)
fn main():
xs = [1, 2]
snapshot = xs
add_all(&xs, snapshot)
print(xs)[1, 2, 1, 2]NAME would see the same value twice: PLACE is given away, but PLACE is also passed (argument N)
A value handed to a take parameter is moved, so it can't also be passed as another argument.
fn merge(xs: take [int], ys: [int]) [int]:
for y in ys:
xs.push(y)
return xs
fn main():
xs = [1]
print(merge(xs, xs))8: error: `merge` would see the same value twice: `xs` is given away, but `xs` is also passed (argument 2)fn merge(xs: take [int], ys: [int]) [int]:
for y in ys:
xs.push(y)
return xs
fn main():
xs = [1]
print(merge(copy(xs), xs))[1, 1]NAME would see the same value twice: &PLACE can be changed, but NAME is the function being called
The function being called is stored in the value that is also passed mut, so the call could change the function while it runs.
struct Counter:
n: int
on_tick: fn(mut Counter)
fn bump(c: mut Counter):
c.n += 1
fn main():
c = Counter(0, bump)
c.on_tick(&c)10: error: `c.on_tick` would see the same value twice: `&c` can be changed, but `c.on_tick` is the function being calledstruct Counter:
n: int
on_tick: fn(mut Counter)
fn bump(c: mut Counter):
c.n += 1
fn main():
c = Counter(0, bump)
tick = c.on_tick
tick(&c)
print(c.n)1can't read NAME here: a call later in this expression changes it with &NAME, and that call runs first. Read NAME into a variable on the line before
Calls inside an expression run before the plain reads around them: each call's result is computed first. So when one part of an expression reads x and a call further along changes x through &x, the read would see the new value, which isn't what the code says. Tern refuses it instead of picking an order silently (Rust refuses it too).
fn bump(n: mut int) int:
n += 1
return n
fn main():
x = 0
print(x, bump(&x))7: error: can't read `x` here: a call later in this expression changes it with `&x`, and that call runs first. Read `x` into a variable on the line beforefn bump(n: mut int) int:
n += 1
return n
fn main():
x = 0
before = x
print(before, bump(&x), x)0 1 1Reads after the call are fine (bump(&x) + x reads the new x, as written), and so are and / or, which run their right side only after the left.
take and moved values
A take parameter moves the value into the function instead of copying it. The caller's variable is gone afterwards.
NAME was handed to a take parameter earlier and is gone (pass copy(NAME) to keep it)
fn consume(xs: take [int]) int:
return len(xs)
fn main():
xs = [1, 2]
print(consume(xs))
print(len(xs))7: error: `xs` was handed to a `take` parameter earlier and is gone (pass `copy(xs)` to keep it)fn consume(xs: take [int]) int:
return len(xs)
fn main():
xs = [1, 2]
print(consume(copy(xs)))
print(len(xs))2
2NAME was handed to a take parameter earlier and is gone
The same, when the moved variable is changed afterwards. Assigning a whole new value (xs = [...]) is allowed and brings the variable back.
fn consume(xs: take [int]) int:
return len(xs)
fn main():
xs = [1, 2]
print(consume(xs))
xs.push(3)7: error: `xs` was handed to a `take` parameter earlier and is gonefn consume(xs: take [int]) int:
return len(xs)
fn main():
xs = [1, 2]
print(consume(xs))
xs = [3]
print(xs)2
[3]NAME is handed over inside this loop, so the next pass would use it after it's gone (pass copy(NAME))
A variable from outside a loop is moved inside it. The second pass would use it after the first moved it.
fn keep(row: take [int]) int:
return len(row)
fn main():
row = [0, 0]
for i in 0..3:
print(keep(row))6: error: `row` is handed over inside this loop, so the next pass would use it after it's gone (pass `copy(row)`)fn keep(row: take [int]) int:
return len(row)
fn main():
row = [0, 0]
for i in 0..3:
print(keep(copy(row)))2
2
2can't give away mut parameter NAME (it belongs to the caller); pass copy(NAME)
A mut parameter is the caller's variable. Moving it would leave the caller with nothing.
fn keep(xs: take [int]) int:
return len(xs)
fn process(xs: mut [int]):
print(keep(xs))
fn main():
pass5: error: can't give away `mut` parameter `xs` (it belongs to the caller); pass `copy(xs)`fn keep(xs: take [int]) int:
return len(xs)
fn process(xs: mut [int]):
print(keep(copy(xs)))
fn main():
xs = [1, 2]
process(&xs)2Loops
can only loop over an array, a str, a map, or a channel, not TYPE (for a range, write for i in 0..n:)
for x in n with a number is an error; write a range.
fn main():
n = 3
for i in n:
print(i)3: error: can only loop over an array, a str, a map, or a channel, not int (for a range, write `for i in 0..n:`)fn main():
n = 3
for i in 0..n:
print(i)0
1
2range bounds must be int
Ranges count integers. For float steps, loop over ints and convert.
fn main():
for x in 0..2.5:
print(x)2: error: range bounds must be intfn main():
for i in 0..5:
print(float(i) * 0.5)0.0
0.5
1.0
1.5
2.0break is only allowed inside a loop
The same message is used for continue.
fn main():
x = 1
if x > 0:
break4: error: `break` is only allowed inside a loopfn main():
for x in [1, -1, 2]:
if x < 0:
break
print(x)1can't modify NAME while looping over it; loop over indices instead: for i in 0..len(NAME):
Changing an array while a for loop walks it would change what the loop sees, so it is refused. To change elements in place, loop over indices; to add or remove elements, build a new array.
fn main():
names = ["a", "b"]
for n in names:
names.push(n + "2")4: error: can't modify `names` while looping over it; loop over indices instead: `for i in 0..len(names):`
4: hint: or build a new array: `out: [T] = []`, push into `out` in the loop, then `names = out`fn main():
names = ["a", "b"]
out: [str] = []
for n in names:
out.push(n)
out.push(n + "2")
names = out
print(names)["a", "a2", "b", "b2"]can't modify NAME while looping over it; loop over a copy of its keys instead: for k in NAME.keys():
The same rule for a map. keys() returns a copy of the keys, so the loop can change the map:
fn main():
stock = {"pen": 3, "ink": 0}
for k, v in stock:
stock[k] = v + 104: error: can't modify `stock` while looping over it; loop over a copy of its keys instead: `for k in stock.keys():`fn main():
stock = {"pen": 3, "ink": 0}
for k in stock.keys():
stock[k] = stock[k] + 10
print(stock){"pen": 13, "ink": 10}Parallelism and races
Tasks in a parallel: block, and iterations of a parallel for, run at the same time. The compiler refuses any program where one of them writes a variable another one reads or writes. See Parallelism.
data race on NAME: the task on line N writes it while the task on line N reads it at the same time
The full message ends with: "Give each task its own variable and combine them after the block".
fn count(xs: [int]) int:
return len(xs)
fn main():
total = 0
parallel:
total += count([1, 2])
total += count([3])
print(total)8: error: data race on `total`: the task on line 7 writes it while the task on line 8 writes it at the same time. Give each task its own variable and combine them after the blockfn count(xs: [int]) int:
return len(xs)
fn main():
parallel:
a = count([1, 2])
b = count([3])
print(a + b)3iterations of parallel for run at the same time, so writing NAME from every iteration would race
Every iteration writes the same variable. Store each iteration's result in its own array slot, then combine after the loop.
fn main():
total = 0
parallel for i in 0..100:
total += i * i4: error: iterations of `parallel for` run at the same time, so writing `total` from every iteration would race; store per-iteration results in an array indexed by `i`, or combine results after the loopfn main():
squares = [0] * 100
parallel for i in 0..100:
squares[i] = i * i
total = 0
for s in squares:
total += s
print(total)328350For an array, the message says write onlyNAME[i]``: each iteration may write only the element at its own index.
fn main():
xs = [0] * 10
parallel for i in 0..10:
xs[0] = i4: error: iterations of `parallel for` run at the same time, so writing `xs` from every iteration would race; write only `xs[i]`, or combine results after the loopfn main():
xs = [0] * 10
parallel for i in 0..10:
xs[i] = i
print(xs)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]each iteration writes NAME[i], so reading any other part of NAME inside the loop would race
Another iteration may be writing the element being read. Read from a copy made before the loop.
fn main():
xs = [1, 2, 3, 4]
parallel for i in 0..3:
xs[i] = xs[i + 1]4: error: each iteration writes `xs[i]`, so reading any other part of `xs` inside the loop would racefn main():
xs = [1, 2, 3, 4]
old = xs
parallel for i in 0..3:
xs[i] = old[i + 1]
print(xs)[2, 3, 4, 4]NAME is not an array
A parallel for iteration may write NAME[i] only when NAME is an array. Maps can't be written from parallel iterations; fill an array, then build the map after the loop.
fn main():
squares: {int: int} = {}
parallel for i in 0..10:
squares[i] = i * i3: error: `squares` is not an arrayfn main():
parts = [0] * 10
parallel for i in 0..10:
parts[i] = i * i
squares: {int: int} = {}
for i, v in parts:
squares[i] = v
print(squares[9])81can't tell the type of NAME
A one-line task that creates a variable must give it a value whose type is known.
fn main():
parallel:
names = []
n = 5
print(names, n)2: error: can't tell the type of `names`
3: error: can't tell the type of an empty array; add a type, e.g. `xs: [int] = []`fn main():
names: [str] = []
parallel:
names = ["a"]
n = 5
print(names, n)["a"] 5do: groups several statements into one task, so it only works directly inside parallel:
fn main():
do:
print(1)2: error: `do:` groups several statements into one task, so it only works directly inside `parallel:`fn main():
total = 0
parallel:
do:
total = 1
total += 1
other = 5
print(total, other)2 5return isn't allowed inside parallel; assign the result to a variable and return after the block
fn fib(n: int) int:
if n < 2:
return n
parallel:
return fib(n - 1) + fib(n - 2)
return 0
fn main():
pass5: error: `return` isn't allowed inside `parallel`; assign the result to a variable and return after the blockfn fib(n: int) int:
if n < 2:
return n
parallel:
a = fib(n - 1)
b = fib(n - 2)
return a + b
fn main():
print(fib(15))610Closures
A closure (a lambda fn(x) ... or a nested fn) copies the variables it uses when it is created. See Functions as values.
can't modify NAME here: this function has its own copy of it, made when the function was created (return a new value, or take it as a mut parameter)
Because the closure holds a copy, changing it would not change the outer variable, so it is refused.
fn main():
count = 0
fn bump():
count += 1
bump()4: error: can't modify `count` here: this function has its own copy of it, made when the function was created (return a new value, or take it as a `mut` parameter)fn main():
count = 0
fn bump(n: mut int):
n += 1
bump(&count)
bump(&count)
print(count)2can't tell the type of parameter NAME; write fn(NAME: int) ..., or give the variable a type, e.g. f: fn(int) int = ...
A lambda's parameter types can be left out only when the context gives them (a typed variable, parameter, or field, or map/filter/sort_by).
fn main():
double = fn(x) x * 22: error: can't tell the type of parameter `x`; write `fn(x: int) ...`, or give the variable a type, e.g. `f: fn(int) int = ...`fn main():
double = fn(x: int) x * 2
triple: fn(int) int = fn(x) x * 3
print(double(2), triple(2))4 6this function takes N parameter(s), but it should take N here (TYPE)
The lambda has a different number of parameters from the function type expected here.
fn main():
add: fn(int) int = fn(a, b) a + b2: error: this function takes 2 parameter(s), but it should take 1 here (fn(int)int)fn main():
add: fn(int, int) int = fn(a, b) a + b
print(add(2, 3))5parameter NAME should be TYPE here
A lambda parameter's written type differs from the one the context expects.
fn main():
xs = [1, 2]
ys = xs.filter(fn(x: str) len(x) > 0)3: error: parameter `x` should be int here
3: error: argument 2 of `filter` should be fn(int)bool, not fn(str)bool
3: error: filter(): the function should take one intfn main():
xs = [1, 2]
ys = xs.filter(fn(x: int) x > 1)
print(ys)[2]this function should return TYPE, not TYPE
The lambda's expression has a different type from the expected return type.
fn main():
label: fn(int) str = fn(n) n * 22: error: this function should return str, not intfn main():
label: fn(int) str = fn(n) str(n * 2)
print(label(4))8Modules
See Modules and packages for how imports are found.
can't find module NAME (looked in the standard library and DIR)
import name looks in the standard library and the first-party packages, then for name.tn or a directory name/ next to the main file, then in deps/ when the project has a tern.mod (the message then also names ROOT/deps). Check the spelling and where the file is.
import modles
fn main():
pass1: error: can't find module `modles` (looked in the standard library and /home/ada/project)NAME is private to module MODULE
Names that start with _ can only be used inside their own module.
import fmt
fn main():
print(fmt._scaled(5, 2))4: error: `_scaled` is private to module `fmt`import fmt
fn main():
print(fmt.cents(500))5.00module MODULE has no NAME
The module exists but has no function, struct, or enum with that name. The same error appears for from MODULE import NAME.
import fmt
fn main():
print(fmt.fixd(3.14159, 2))4: error: module `fmt` has no `fixd`import fmt
fn main():
print(fmt.fixed(3.14159, 2))3.14NAME isn't an imported module (add import NAME)
A type like http.Request names a module that this file doesn't import. (For a function call such as math.pi(), the message is NAME is a module; add import NAME.)
fn describe(req: http.Request) str:
return req.path
fn main():
pass1: error: `http` isn't an imported module (add `import http`)import http
fn describe(req: http.Request) str:
return req.path
fn main():
passimport cycle: MODULE -> MODULE -> MODULE
Two modules import each other, directly or through others. Move the shared code into a third module that both import. With main.tn importing a, and a.tn and b.tn importing each other:
a.tn:1: error: import cycle: main -> a -> b -> a(main is the program's main file.)
NAME is defined twice in module MODULE
A package is a directory of .tn files that form one module, so their top-level names must be distinct across all the files. With shapes/one.tn and shapes/two.tn both defining fn area():
shapes/two.tn:1: error: `area` is defined twice in module `shapes`only the main program can export functions (MODULE.NAME)
export fn makes a function callable from C, JavaScript, or Swift. Only the file you build can export; an imported module can't. Put an export fn wrapper in the main file that calls the module's function. With lib.tn containing export fn add(...) and the main file importing lib:
lib.tn:1: error: only the main program can export functions (`lib.add`)C interop and export
These are about extern blocks (calling C) and export fn (being called from C or JavaScript). See Calling C, and Tern as a library.
TYPE can't cross the C boundary (use int, float, bool, str, ptr, [int], [float], [byte], or a function of int/float/bool/ptr values)
A C function's parameters must have a C form. Structs, maps, enums, and arrays of other types don't. Pass the fields one by one, or use [int] / [float].
struct Point:
x, y: float
extern "math.h":
fn hypot(p: Point) float
fn main():
pass5: error: `Point` can't cross the C boundary (use int, float, bool, str, ptr, [int], [float], [byte], or a function of int/float/bool/ptr values)extern "math.h":
fn hypot(x: float, y: float) float
fn main():
print(hypot(3.0, 4.0))5.0TYPE can't cross the C boundary (a mut parameter can be int, float, bool, ptr, [int], [float], or [byte])
C can write back into numbers and number arrays, not into a str. Have the C function return a string instead.
extern "names.h":
fn fill_name(out: mut str)
fn main():
pass2: error: `str` can't cross the C boundary (a `mut` parameter can be int, float, bool, ptr, [int], [float], or [byte])extern "names.h":
fn make_name() str
fn main():
print(make_name())NAME is a C function; take doesn't mean anything to C (drop it)
extern "string.h":
fn strlen(s: take str) int
fn main():
pass2: error: `strlen` is a C function; `take` doesn't mean anything to C (drop it)extern "string.h":
fn strlen(s: str) int
fn main():
print(strlen("hello"))5NAME returns TYPE, which can't cross the C boundary (C functions return int, float, bool, str, or ptr)
A C function can't return an array. Pass a mut [int] or mut [float] for it to fill.
extern "stats.h":
fn histogram() [int]
fn main():
pass2: error: `histogram` returns [int], which can't cross the C boundary (C functions return int, float, bool, str, ptr, or an extern struct)extern "stats.h":
fn histogram(out: mut [int])
fn main():
counts = [0] * 10
histogram(&counts)
print(counts)NAME is a C function; wrap it in a Tern function to use it as a value
A C function can't be stored in a variable or passed as a function value. Wrap it.
extern "stdlib.h":
fn labs(n: int) int
fn main():
f = labs5: error: `labs` is a C function; wrap it in a Tern function to use it as a valueextern "stdlib.h":
fn labs(n: int) int
fn c_abs(n: int) int:
return labs(n)
fn main():
f = c_abs
print([-2, 3].map(f))[2, 3]an extern block holds fn signatures (no bodies)
extern "stdlib.h":
limit = 5
fn main():
pass2: error: an `extern` block holds `fn` signatures (no bodies) and `struct`sextern "stdlib.h":
fn labs(n: int) int
fn main():
print(labs(-5))5after =, write the C function name in quotes: = "c_name"
= "name" gives a Tern name to a C function with a different name.
extern "stdlib.h":
fn long_abs(n: int) int = labs
fn main():
pass2: error: after `=`, write the C function name in quotes: `= "c_name"`extern "stdlib.h":
fn long_abs(n: int) int = "labs"
fn main():
print(long_abs(-5))5WORD needs a quoted file or library name
After the header, an extern line may name C files to compile (source "impl.c") and libraries to link (link "m"), each in quotes.
extern "math.h" link m:
fn cbrt(x: float) float
fn main():
pass1: error: `link` needs a quoted file or library nameextern "math.h" link "m":
fn cbrt(x: float) float
fn main():
print(cbrt(27.0))3.0exported NAME can't take mut or take parameters (C passes plain values)
An exported function is called from C or JavaScript, which pass plain values in and get one value out. Return the result instead.
export fn double_all(xs: mut [int]):
for i in 0..len(xs):
xs[i] *= 2
fn main():
pass1: error: exported `double_all` can't take `mut` or `take` parameters (C passes plain values)export fn double(n: int) int:
return n * 2
fn main():
print(double(21))42TYPE can't cross the C boundary (exported functions take int, float, bool, str, or ptr)
struct Point:
x, y: int
export fn norm1(p: Point) int:
return abs(p.x) + abs(p.y)
fn main():
pass4: error: `Point` can't cross the C boundary (exported functions take int, float, bool, str, or ptr)export fn norm1(x: int, y: int) int:
return abs(x) + abs(y)
fn main():
print(norm1(3, -4))7exported NAME returns TYPE, which can't cross the C boundary (return int, float, bool, str, or ptr)
To hand structured data to the caller, return it as JSON text.
export fn primes() [int]:
return [2, 3, 5]
fn main():
pass1: error: exported `primes` returns [int], which can't cross the C boundary (return int, float, bool, str, or ptr)import json
export fn primes() str:
return json.encode([2, 3, 5])
fn main():
print(primes())[2,3,5]is_null() needs a ptr, not TYPE
null and is_null() are only for ptr, the opaque C pointer type. Other types have no null.
fn main():
name = ""
print(name.is_null())3: error: is_null() needs a ptr, not strfn main():
name = ""
print(len(name) == 0)trueWeb, database, and JSON
See Building web apps, json, and sqlite.
http.serve(port, handler) or http.serve(port, handler, app)
http.serve takes a port, a handler function, and optionally the app state.
import http
fn main():
http.serve(8080)4: error: http.serve(port, handler) or http.serve(port, handler, app)import http
fn handle(req: http.Request) http.Response:
return http.text("hello")
fn main():
http.serve(8080, handle)serve(): the port must be an int
import http
fn handle(req: http.Request) http.Response:
return http.text("hello")
fn main():
http.serve("8080", handle)7: error: serve(): the port must be an intimport http
fn handle(req: http.Request) http.Response:
return http.text("hello")
fn main():
http.serve(8080, handle)serve(): the second argument must be the name of a handler function
The handler must be a top-level function named directly, not a lambda or a variable.
import http
fn main():
http.serve(8080, fn(req: http.Request) http.text("hello"))4: error: serve(): the second argument must be the name of a handler functionimport http
fn hello(req: http.Request) http.Response:
return http.text("hello")
fn main():
http.serve(8080, hello)serve(): NAME must look like fn handler(req: http.Request) http.Response
The handler takes the request (and the app state, when there is one) and returns a response. With app state the shape is fn handler(req: http.Request, app: App) http.Response (or app: mut App).
import http
fn handle(path: str) str:
return "hello " + path
fn main():
http.serve(8080, handle)7: error: serve(): `handle` must look like `fn handler(req: http.Request) http.Response`import http
fn handle(req: http.Request) http.Response:
return http.text("hello " + req.path)
fn main():
http.serve(8080, handle)NAME changes the app state, so pass it with &; requests then run one at a time
The handler takes app: mut App, so the call must pass &app. Requests that can change the state run one at a time, so they never race.
import http
struct App:
hits: int
fn handle(req: http.Request, app: mut App) http.Response:
app.hits += 1
return http.text(str(app.hits))
fn main():
app = App(0)
http.serve(8080, handle, app)12: error: `handle` changes the app state, so pass it with `&`; requests then run one at a timeimport http
struct App:
hits: int
fn handle(req: http.Request, app: mut App) http.Response:
app.hits += 1
return http.text(str(app.hits))
fn main():
app = App(0)
http.serve(8080, handle, &app)NAME only reads the app state, so pass it without &
The handler takes the state read-only, so all requests can share it in parallel. Drop the &.
import http
struct App:
name: str
fn handle(req: http.Request, app: App) http.Response:
return http.text(app.name)
fn main():
app = App("demo")
http.serve(8080, handle, &app)11: error: `handle` only reads the app state, so pass it without `&`import http
struct App:
name: str
fn handle(req: http.Request, app: App) http.Response:
return http.text(app.name)
fn main():
app = App("demo")
http.serve(8080, handle, app)serve(): the app state should be TYPE, not TYPE
The third argument must have the type of the handler's second parameter.
import http
struct App:
name: str
fn handle(req: http.Request, app: App) http.Response:
return http.text(app.name)
fn main():
http.serve(8080, handle, "demo")10: error: serve(): the app state should be App, not strimport http
struct App:
name: str
fn handle(req: http.Request, app: App) http.Response:
return http.text(app.name)
fn main():
http.serve(8080, handle, App("demo"))json.encode can't handle TYPE
JSON holds numbers, bools, strings, arrays, maps, structs, and enums made of those (Option[T] is null or the value). Functions, tuples, ptr values, and recursive enums have no JSON form; encode the parts that do.
import json
struct Button:
label: str
on_click: fn(int) str
fn main():
b = Button("go", fn(n) "clicked")
print(json.encode(b))9: error: json.encode can't handle Buttonimport json
struct Button:
label: str
on_click: fn(int) str
fn main():
b = Button("go", fn(n) "clicked")
print(json.encode(b.label))"go"json.decode can't fill a TYPE
json.decode(text, &value) fills a value of a JSON-compatible type. The same limits as json.encode apply.
import json
fn main():
pair = (1, "a")
ok = json.decode(`[2, "b"]`, &pair)5: error: json.decode can't fill a (int,str)import json
struct Pair:
n: int
s: str
fn main():
pair = Pair(1, "a")
ok = json.decode(`{"n": 2, "s": "b"}`, &pair)
print(ok, pair)true Pair{n: 2, s: "b"}runtime error in F (FILE:N): index N out of bounds (length N)
An array or string index is negative or not less than the length. There are no negative indexes: the last element is xs[len(xs) - 1]. This program:
fn main():
xs = [10, 20, 30]
print(xs[3])stops with:
runtime error in main (prog.tn:3): index 3 out of bounds (length 3)Check the index first, or loop over the array directly. (Slices don't fail: xs[1..10] stops at the end of the array.)
fn main():
xs = [10, 20, 30]
i = 3
if i < len(xs):
print(xs[i])
else:
print("no element", i)
print(xs[len(xs) - 1], xs[1..10])no element 3
30 [20, 30]runtime error in F (FILE:N): key not found (use m.get(key, default) or key in m)
m[k] reads a key that isn't in the map. This program:
fn main():
ages = {"ada": 36}
print(ages["bob"])stops with:
runtime error in main (prog.tn:3): key not found (use m.get(key, default) or `key in m`)Use get with a default, or test with in:
fn main():
ages = {"ada": 36}
print(ages.get("bob", -1))
if "bob" in ages:
print(ages["bob"])-1runtime error in F (FILE:N): division by zero
Integer / or % by zero. (Float division by 0.0 doesn't fail; it gives inf or nan.) This program:
fn main():
total = 10
count = 0
print(total / count)stops with:
runtime error in main (prog.tn:4): division by zeroCheck the divisor:
fn main():
total = 10
count = 0
avg = 0
if count != 0:
avg = total / count
print(avg)0runtime error in F (FILE:N): pop() from an empty array
This program:
fn main():
stack: [int] = []
top = stack.pop()stops with:
runtime error in main (prog.tn:3): pop() from an empty arrayCheck the length first:
fn main():
stack = [1, 2]
while len(stack) > 0:
print(stack.pop())2
1runtime error: negative array length
[value] * n with a negative n. The line number is reported as 0.
fn main():
n = -1
zeros = [0] * nruntime error: negative array lengthUse max(n, 0) if n may be negative:
fn main():
n = -1
zeros = [0] * max(n, 0)
print(zeros)[]runtime error: random.int: hi < lo
random.int(lo, hi) returns a number from lo to hi inclusive, so hi must not be less than lo.
import random
fn main():
n = random.int(1, 6)
print(n >= 1 and n <= 6)trueruntime error: stack overflow (recursion too deep)
A function recursed so deeply that the thread's stack (64MB) ran out, on the main thread, inside parallel:, or in a task (stack overflow in a task). The program ends with status 2. Recursion a few hundred thousand calls deep is fine; unbounded recursion (a missing base case) is the usual cause. Turn deep recursion over long inputs into a loop.
runtime error in F (FILE:N): can't convert inf to int
int(x) of a float with no integer value: inf, -inf, nan, or a value outside int's range (can't convert 1e+20 to int (out of range)). Check first with x == x and x < 9_000_000_000_000_000_000.0 and x > -9_000_000_000_000_000_000.0.
runtime error in F (FILE:N): chr(N): the byte value must be 0 to 255
chr(n) makes a one-byte string, so n must be a byte value.
runtime error: all tasks are blocked (deadlock)
Every task, main included, waits on a channel, a join, or a shared value with no timeout, so nothing can ever wake them. The message says what main and the other tasks wait for:
runtime error: all tasks are blocked (deadlock): main is waiting for a task to finish; 2 tasks are waiting to receive from a channelUsually a value is never sent, or two tasks each wait for the other. Waits on sockets, timers (task.sleep, recv_timeout), and task.blocking aren't counted, so a server waiting for connections is never reported.
runtime error in F (FILE:N): a shared value was used inside its own update
The function passed to s.update(f) called s.get(), s.set(v), or s.update(g) on the same shared value. The update holds the value until f returns, so that would wait forever. Use the value f is given instead.
task failed: MESSAGE
A task hit a runtime error and nothing joined it (h.join() raises the error again). The error is printed, and when main returns the program exits with status 2. Join the task, or call h.cancel() on it if its failure is expected.
Other runtime errors
These are rare:
| Message | Meaning |
|---|---|
array too large (over 4 billion elements) | an array outgrew the size limit |
string too long (over 4GB) | a string outgrew the size limit |
called a function value that was never set | a function value was called before any function was stored in it |