Tern

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:12 is 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

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.

Does not compile
limit = 5

fn main():
    print(limit)
Compiler output
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)
Output
5

expected 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.

Does not compile
fn main():
    x = 3
    if x > 0
        print("positive")
Compiler output
3: error: expected `:`, found end of line
fn main():
    x = 3
    if x > 0:
        print("positive")
Output
positive

expected 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.

Does not compile
fn main():
    x = 3
    if x > 0:
    print("positive")
Compiler output
4: error: expected an indented block, found 'print'
fn main():
    x = 3
    if x > 0:
        print("positive")
Output
positive

expected a name, found TOKEN

The parser needed a name (of a variable, function, field, or type) here.

Does not compile
fn main():
    for 1 in [1, 2]:
        pass
Compiler output
2: error: expected a name, found 1
fn main():
    for n in [1, 2]:
        print(n)
Output
1
2

expected end of line, found TOKEN

The statement was complete, but more text followed on the same line. Put one statement on each line.

Does not compile
fn main():
    print(1) print(2)
Compiler output
2: error: expected end of line, found 'print'
fn main():
    print(1)
    print(2)
Output
1
2

expected =, found end of line

A variable is created by giving it a value. x: int alone is not a declaration.

Does not compile
fn main():
    count: int
    count = 3
    print(count)
Compiler output
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)
Output
3

unexpected TOKEN

The parser found a token that can't start or continue an expression here.

Does not compile
fn main():
    total = )
Compiler output
2: error: unexpected ')'
fn main():
    total = 0
    print(total)
Output
0

unexpected 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.

Does not compile
fn main():
    x = 1
        y = 2
    print(x, y)
Compiler output
3: error: unexpected indentation: this line is indented more than the block it is in
fn main():
    x = 1
    y = 2
    print(x, y)
Output
1 2

this 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.

Does not compile
fn main():
    if true:
        x = 1
      print(x)
Compiler output
4: error: this line's indentation doesn't match any enclosing block
fn main():
    x = 0
    if true:
        x = 1
    print(x)
Output
1

unterminated string

A string has no closing " on the same line. Strings are one line; write \n for a line break.

Does not compile
fn main():
    print("hello)
Compiler output
2: error: unterminated string
fn main():
    print("hello")
    print("two\nlines")
Output
hello
two
lines

unterminated 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.

Does not compile
fn main():
    x = 1
    print(f"x = {x")
Compiler output
3: error: unterminated string inside f-string
fn main():
    x = 1
    print(f"x = {x}")
Output
x = 1

f-string has } without an opening { (write }} for a brace)

In an f-string, { and } mark expressions. For a literal brace, double it.

Does not compile
fn main():
    print(f"a } b")
Compiler output
2: error: f-string has `}` without an opening `{` (write `}}` for a brace)
fn main():
    n = 2
    print(f"{{n}} is {n}")
Output
{n} is 2

can'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.

Does not compile
fn main():
    price = 3.14159
    print(f"{price:.2f}")
Compiler output
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)}")
Output
3.14

unexpected character 'C'

The character can't appear in Tern code outside a string. Common ones are ;, ', !, $, and @.

Does not compile
fn main():
    x = 5 $ 3
Compiler output
2: error: unexpected character '$'
fn main():
    x = 5 - 3
    print(x)
Output
2

left 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.

Does not compile
fn first() int:
    return 1

fn main():
    first() = 3
Compiler output
5: error: left side of `=` must be a variable, field, or element
fn first() int:
    return 1

fn main():
    x = first()
    x = 3
    print(x)
Output
3

positional 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.

Does not compile
struct Point:
    x, y: int

fn main():
    p = Point(x=1, 2)
Compiler output
5: error: positional arguments must come before named ones
struct Point:
    x, y: int

fn main():
    p = Point(1, y=2)
    print(p)
Output
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.

Does not compile
fn area(w: int, h: int) int:
    return w * h

fn main():
    a = area(w=2, h=3)
Compiler output
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)
Output
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.

Does not compile
fn inc(n: mut int):
    n += 1

fn main():
    inc(&5)
Compiler output
5: error: `&` needs a variable, field, or element
fn inc(n: mut int):
    n += 1

fn main():
    x = 5
    inc(&x)
    print(x)
Output
6

export goes before fn

Only functions can be exported (for C, JavaScript, or Swift callers). Structs and enums can't.

Does not compile
export struct Point:
    x: int

fn main():
    pass
Compiler output
1: error: `export` goes before `fn`
struct Point:
    x: int

export fn origin_x() int:
    return Point(0).x

fn main():
    print(origin_x())
Output
0

function NAME is defined twice

There is no overloading: each function name in a module is used once. Give the second one another name.

Does not compile
fn show(n: int):
    print(n)

fn show(s: str):
    print(s)

fn main():
    show(1)
Compiler output
4: error: function `show` is defined twice
fn show_int(n: int):
    print(n)

fn show_str(s: str):
    print(s)

fn main():
    show_int(1)
    show_str("a")
Output
1
a

NAME is defined twice

Two enums (or an enum and a struct) have the same name.

Does not compile
enum Color:
    Red

enum Color:
    Blue

fn main():
    pass
Compiler output
4: error: `Color` is defined twice
enum Color:
    Red
    Blue

fn main():
    print(Color.Blue)
Output
Color.Blue

enum NAME has two variants named VARIANT

Each variant of an enum needs its own name.

Does not compile
enum Light:
    Red
    Red

fn main():
    pass
Compiler output
3: error: enum `Light` has two variants named `Red`
enum Light:
    Red
    Green

fn main():
    print(Light.Green)
Output
Light.Green

Habits 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 ))

Does not compile
def add(a, b):
    return a + b

fn main():
    pass
Compiler output
1: 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))
Output
5

there are no classes: declare data with struct Name: (fields only)

Does not compile
class Point:
    x: int

fn main():
    pass
Compiler output
1: 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))
Output
Point{x: 3}

variables are created by assigning: x = 5 (no let/var/const)

Does not compile
fn main():
    let x = 5
Compiler output
2: 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)
Output
5

variables are created with =: x = 5

Does not compile
fn main():
    x := 5
Compiler output
2: error: expected a name, found '='
2: hint: variables are created with `=`: `x = 5`
fn main():
    x = 5
    print(x)
Output
5

write and / write or / write not x

Logic operators are words.

Does not compile
fn main():
    a = true
    b = false
    if a && b:
        print("both")
Compiler output
4: error: expected `:`, found '&&'
4: hint: write `and`
fn main():
    a = true
    b = false
    if a and not b:
        print("a only")
Output
a only

write elif cond:

Does not compile
fn main():
    x = 1
    if x > 1:
        print("big")
    else if x > 0:
        print("small")
Compiler output
5: error: expected `:`, found 'if'
5: hint: write `elif cond:`
fn main():
    x = 1
    if x > 1:
        print("big")
    elif x > 0:
        print("small")
Output
small

write x += 1 / x -= 1

There is no ++ or --.

Does not compile
fn main():
    x = 1
    x++
Compiler output
3: error: unexpected '+'
3: hint: write `x += 1` / `x -= 1`
fn main():
    x = 1
    x += 1
    print(x)
Output
2

statements end at the line end; remove the ;

Does not compile
fn main():
    x = 1;
Compiler output
2: error: unexpected character ';'
2: hint: statements end at the line end; remove the `;`
fn main():
    x = 1
    print(x)
Output
1

strings use double quotes: "text" (or text, raw, when it holds double quotes)

Does not compile
fn main():
    name = 'ada'
Compiler output
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)
Output
ada

there is no c ? a : b; write a if c else b

Does not compile
fn main():
    n = 3
    label = n > 2 ? "big" : "small"
Compiler output
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)
Output
big

lambdas are written fn(x) x + 1 (one expression)

Does not compile
fn main():
    inc = lambda x: x + 1
Compiler output
2: 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))
Output
2

a 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.

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = xs.map(fn(x):
        return x * 2)
Compiler output
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))
Output
[2, 4, 6] [2, 4, 6]

there are no comprehensions: xs.map(fn(x) ...) and xs.filter(fn(x) ...)

Does not compile
fn main():
    xs = [1, 2, 3]
    ys = [x * 2 for x in xs]
Compiler output
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)
Output
[2, 4, 6]

write not (x in xs)

There is no not in operator. not binds tighter than in, so the parentheses are needed.

Does not compile
fn main():
    ages = {"ada": 36}
    if "bob" not in ages:
        print("no bob")
Compiler output
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")
Output
no bob

integer 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).

Does not compile
fn main():
    big = 99999999999999999999
Compiler output
2: error: integer literal 99999999999999999999 is too big for an int (the largest is 9223372036854775807)
fn main():
    big = 1_000_000_000
    print(big)
Output
1000000000

parameters are written name: type, e.g. fn f(a: int, b: str)

Does not compile
fn half(n int) int:
    return n / 2

fn main():
    pass
Compiler output
1: 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))
Output
4

there is no self: take the struct as a normal parameter

Does not compile
struct Rect:
    w, h: int

fn area(self) int:
    return self.w * self.h

fn main():
    pass
Compiler output
4: 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())
Output
6

min_max returns int, not (int,int)

A function returns several values as a tuple, and its return type must say so:

Does not compile
fn min_max(xs: [int]) int:
    return 1, 9

fn main():
    pass
Compiler output
2: 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)
Output
1 9

import math, then math.pow(x, y) (floats)

There is no ** operator.

Does not compile
fn main():
    print(2 ** 10)
Compiler output
2: error: unexpected '*'
2: hint: `import math`, then `math.pow(x, y)` (floats)
import math

fn main():
    print(math.pow(2.0, 10.0))
Output
1024.0

/ on two ints already divides without a remainder; comments start with #

There is no // operator. / on two ints truncates toward zero.

Does not compile
fn main():
    print(7 // 2)
Compiler output
2: error: unexpected '/'
2: hint: `/` on two ints already divides without a remainder; comments start with `#`
fn main():
    print(7 / 2)   # integer division
Output
3

there are no exceptions: return a bool or a status enum

Does not compile
fn main():
    try:
        print(1)
Compiler output
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")
Output
not a number

use match value: with one arm per case (_: for the default)

Does not compile
fn main():
    code = 404
    switch code:
        pass
Compiler output
3: 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)
Output
error 404

match arms are Pattern: followed by an indented block

Does not compile
fn main():
    code = 200
    match code:
        200 => print("ok")
Compiler output
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")
        _: pass
Output
ok

import standard modules by their name: import math, import http

Does not compile
import std.math

fn main():
    pass
Compiler output
1: 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))
Output
4.0

array 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

Does not compile
fn total(xs: Vec<int>) int:
    return 0

fn main():
    pass
Compiler output
1: 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 type
fn total(xs: [int]) int:
    t = 0
    for x in xs:
        t += x
    return t

fn main():
    print(total([1, 2, 3]))
Output
6

Blocks 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.

Does not compile
fn main() {
    print(1)
}
Compiler output
2: error: expected `:`, found '('
2: hint: blocks use `:` and indentation, not braces
fn main():
    print(1)
Output
1

Names 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.

Does not compile
fn main():
    total = 0
    for x in [1, 2, 3]:
        total += x
    print(totl)
Compiler output
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)
Output
6

Booleans are lowercase. None exists, as the empty Option, but it needs to know what kind of Option it is:

Does not compile
fn main():
    found = None
Compiler output
2: 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))
Output
None -1

NAME is a module; add import NAME at the top of this file

The code uses a standard module (math, fs, json, ...) without importing it.

Does not compile
fn main():
    print(math.pi())
Compiler output
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())
Output
3.141592653589793

unknown 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.

Does not compile
fn show_name(name: string):
    print(name)

fn main():
    pass
Compiler output
1: error: unknown type `string`
1: hint: write str
fn show_name(name: str):
    print(name)

fn main():
    show_name("ada")
Output
ada

unknown 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.

Does not compile
fn main():
    for i in range(3):
        print(i)
Compiler output
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)
Output
0
1
2

xs.f(...) is a call to a function f(xs, ...), so a missing method is also an unknown function:

Does not compile
fn main():
    xs = [1, 2]
    xs.append(3)
Compiler output
3: error: unknown function `append`
3: hint: arrays grow with `xs.push(value)`
fn main():
    xs = [1, 2]
    xs.push(3)
    print(xs)
Output
[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.

Does not compile
fn main():
    ratio: float = 1
Compiler output
2: error: `ratio` is declared as float but the value is int
fn main():
    ratio: float = 1.0
    print(ratio)
Output
1.0

can'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.

Does not compile
fn main():
    count = 3
    count = "three"
Compiler output
3: error: can't assign str to `count` of type int
fn main():
    count = 3
    label = str(count)
    print(label)
Output
3

can'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.

Does not compile
fn main():
    names = []
    print(len(names))
Compiler output
2: error: can't tell what `names` holds; add a type, e.g. `names: [int] = []`
fn main():
    names: [str] = []
    print(len(names))
Output
0

can'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.

Does not compile
fn main():
    print([])
Compiler output
2: error: can't tell the type of an empty array; add a type, e.g. `xs: [int] = []`
fn main():
    empty: [int] = []
    print(empty)
Output
[]

can't tell the type of an empty map; add a type, e.g. m: {str: int} = {}

The same, for an empty map literal.

Does not compile
fn main():
    print({})
Compiler output
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)
Output
{}

this expression has no value

A function with no return type was used as a value.

Does not compile
fn log(msg: str):
    print(msg)

fn main():
    x = log("hi")
Compiler output
5: error: this expression has no value
fn log(msg: str):
    print(msg)

fn main():
    log("hi")
Output
hi

map 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.

Does not compile
fn main():
    prices: {float: str} = {}
Compiler output
2: error: map keys must be int, str, bool, or arrays, structs, enums, or tuples of those (no floats or functions), not float
fn main():
    prices: {int: str} = {}
    prices[150] = "cheap"          # 1.50 in cents
    print(prices)
Output
{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.

Does not compile
extern "stdlib.h":
    fn abs(n: int) int

fn main():
    print(abs(-7))
Compiler output
2: error: `abs` is a builtin, so an extern or exported function can't have that name
extern "stdlib.h":
    fn c_abs(n: int) int = "labs"

fn main():
    print(c_abs(-7))
Output
7

no 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.

Does not compile
fn helper() int:
    return 1
Compiler output
1: 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())
Output
1

Operators 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(...).

Does not compile
fn main():
    level: byte = 300
    print(level)
Compiler output
2: error: 300 doesn't fit in a byte (0 to 255); byte(300) keeps its low 8 bits
fn main():
    level: byte = 255
    print(level, byte(300))
Output
255 44

can'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.)

Does not compile
fn main():
    b: byte = 200
    n = 100
    b = b + n
    print(b)
Compiler output
4: error: can't assign int to `b` of type byte: convert with byte(...), which keeps the low 8 bits
fn main():
    b: byte = 200
    n = 100
    b = byte(b + n)
    c: byte = 200
    c += n
    print(b, c)
Output
44 44

OP 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.

Does not compile
fn main():
    n = 3
    avg = 10.0 / n
Compiler output
3: 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)
Output
3.3333333333333335

For str + int the parenthetical advice doesn't apply: convert the number with str(), or use an f-string, as the hint says.

Does not compile
fn main():
    n = 3
    print("n=" + n)
Compiler output
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}")
Output
n=3 n=3

OP needs numbers, not TYPE

Arithmetic works on int and float only (and + on strings).

Does not compile
fn main():
    print(true + false)
Compiler output
2: error: `+` needs numbers, not bool
fn main():
    a = true
    b = false
    count = 0
    if a:
        count += 1
    if b:
        count += 1
    print(count)
Output
1

% needs ints

The remainder operator works on ints only. For floats, use x - math.floor(x / y) * y.

Does not compile
fn main():
    print(7.5 % 2.0)
Compiler output
2: error: `%` needs ints
import math

fn main():
    x = 7.5
    y = 2.0
    print(7 % 2, x - math.floor(x / y) * y)
Output
1 1.5

OP doesn't work on strings (use + to join them)

Strings support + (join) and * (repeat), not - or /. To remove text, use replace.

Does not compile
fn main():
    print("report.txt" - ".txt")
Compiler output
2: error: `-` doesn't work on strings (use + to join them)
fn main():
    print("report.txt".replace(".txt", ""))
Output
report

OP needs bools

and and or work on bool values only. There is no truthiness: compare explicitly.

Does not compile
fn main():
    n = 3
    m = 0
    if n and m:
        print("both")
Compiler output
4: error: `and` needs bools
fn main():
    n = 3
    m = 0
    if n != 0 and m != 0:
        print("both")
    else:
        print("not both")
Output
not both

not 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 !=.

Does not compile
fn main():
    x = 1
    if not x == 2:
        print(x)
Compiler output
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)
Output
1

can't negate TYPE

Unary - works on int and float only.

Does not compile
fn main():
    s = "5"
    print(-s)
Compiler output
3: error: can't negate str
fn main():
    s = "5"
    print(-s.to_int(0))
Output
-5

OP 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:

Does not compile
struct Button:
    label: str
    on_click: fn(int) int

fn main():
    a = Button("ok", fn(x) x)
    print(a == a)
Compiler output
7: error: `==` can't compare Button: functions, channels, tasks, and shared cells have no equality
struct Button:
    label: str
    on_click: fn(int) int

fn main():
    a = Button("ok", fn(x) x)
    print(a.label == "ok", [1, 2] == [1, 2])
Output
true true

OP needs numbers or strings, not TYPE

<, <=, >, and >= work on int, float, and str (strings compare by bytes).

Does not compile
fn main():
    print(true < false)
Compiler output
2: error: `<` needs numbers or strings, not bool
fn main():
    print(1 < 2, "apple" < "banana")
Output
true true

condition must be a bool

if, elif, and while need a bool. There is no truthiness for numbers, strings, or arrays.

Does not compile
fn main():
    xs = [1]
    if len(xs):
        print("not empty")
Compiler output
3: error: condition must be a bool
fn main():
    xs = [1]
    if len(xs) > 0:
        print("not empty")
Output
not empty

in a str looks for a substring, not TYPE

x in s on a string checks for a substring, so x must be a str.

Does not compile
fn main():
    print(1 in "a1b")
Compiler output
2: error: `in` a str looks for a substring, not int
fn main():
    print("1" in "a1b", str(1) in "a1b")
Output
true true

in needs an element of TYPE

x in xs on an array checks for an element, so x must have the element type.

Does not compile
fn main():
    ids = [1, 2, 3]
    print("2" in ids)
Compiler output
3: error: `in` needs an element of [int]
fn main():
    ids = [1, 2, 3]
    print(2 in ids)
Output
true

in needs a key of TYPE

k in m on a map checks for a key, so k must have the key type.

Does not compile
fn main():
    ages = {"ada": 36}
    print(36 in ages)
Compiler output
3: error: `in` needs a key of {str:int}
fn main():
    ages = {"ada": 36}
    print("ada" in ages, 36 in ages.values())
Output
true true

in works on str, arrays, and maps, not TYPE

Does not compile
fn main():
    n = 12
    print(1 in n)
Compiler output
3: error: `in` works on str, arrays, and maps, not int
fn main():
    n = 12
    print("1" in str(n))
Output
true

f-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.

Does not compile
fn main():
    xs = [1, 2]
    print(f"xs = {xs}")
Compiler output
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)}")
Output
xs = [1, 2]
xs = [1,2]

str() converts int, float, bool, or str, not TYPE

Does not compile
fn main():
    xs = [1, 2]
    label = str(xs)
Compiler output
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)
Output
[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.)

Does not compile
fn main():
    n = int("42")
Compiler output
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)
Output
42 2

sqrt() needs a float

Does not compile
fn main():
    n = 16
    print(sqrt(n))
Compiler output
3: error: sqrt() needs a float
3: hint: convert first: `sqrt(float(n))`
fn main():
    n = 16
    print(sqrt(float(n)))
Output
4.0

abs() needs a number

Does not compile
fn main():
    print(abs("-3"))
Compiler output
2: error: abs() needs a number
fn main():
    print(abs(-3), abs(-2.5))
Output
3 2.5

min() 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.

Does not compile
fn main():
    print(min(1, 2.5))
Compiler output
2: error: min() needs two numbers of the same type
fn 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)
Output
1 2.5
1

chr() needs an int (a byte value 0-255)

Does not compile
fn main():
    print(chr("A"))
Compiler output
2: error: chr() needs an int (a byte value 0-255)
fn main():
    print(chr(65), "A".byte(0))
Output
A 65

Functions 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.

Does not compile
fn sign(n: int) int:
    if n > 0:
        return 1
    elif n < 0:
        return -1

fn main():
    pass
Compiler output
1: 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))
Output
-1

NAME must return a TYPE

A bare return in a function that has a return type.

Does not compile
fn first_even(xs: [int]) int:
    for x in xs:
        if x % 2 == 0:
            return
    return -1

fn main():
    pass
Compiler output
4: error: `first_even` must return a int
fn first_even(xs: [int]) int:
    for x in xs:
        if x % 2 == 0:
            return x
    return -1

fn main():
    print(first_even([3, 4]))
Output
4

NAME doesn't return a value

return value in a function without a return type. Add the return type after the ).

Does not compile
fn double(n: int):
    return n * 2

fn main():
    pass
Compiler output
2: error: `double` doesn't return a value
fn double(n: int) int:
    return n * 2

fn main():
    print(double(4))
Output
8

NAME returns TYPE, not TYPE

The returned value doesn't match the declared return type.

Does not compile
fn label(n: int) str:
    return n

fn main():
    pass
Compiler output
2: error: `label` returns str, not int
fn label(n: int) str:
    return str(n)

fn main():
    print(label(4))
Output
4

NAME takes N argument(s), got N

There are no default values or variadic parameters. Pass every argument.

Does not compile
fn area(w: int, h: int) int:
    return w * h

fn main():
    print(area(3))
Compiler output
5: error: `area` takes 2 argument(s), got 1
fn area(w: int, h: int) int:
    return w * h

fn main():
    print(area(3, 3))
Output
9

argument N of NAME should be TYPE, not TYPE

The argument has the wrong type.

Does not compile
fn repeat_word(w: str, n: int) str:
    return w * n

fn main():
    print(repeat_word("ab", "3"))
Compiler output
5: error: argument 2 of `repeat_word` should be int, not str
fn repeat_word(w: str, n: int) str:
    return w * n

fn main():
    print(repeat_word("ab", "3".to_int(1)))
Output
ababab

NAME is a TYPE, not a function

Something that isn't a function was called. Often a variable shadows a function name.

Does not compile
fn main():
    total = 5
    print(total(3))
Compiler output
3: error: `total` is an int, not a function
fn main():
    total = 5
    print(total * 3)
Output
15

Structs

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.

Does not compile
struct Node:
    value: int
    next: Node

fn main():
    pass
Compiler output
1: 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)
Output
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.

Does not compile
struct Point:
    x, y: int

fn main():
    p = Point(1, 2, 3)
Compiler output
5: error: Point has 2 fields, got 3 values
struct Point:
    x, y: int

fn main():
    p = Point(1, 2)
    print(p)
Output
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.

Does not compile
struct User:
    name: str
    admin: bool

fn main():
    u = User("ada")
Compiler output
6: error: missing field `admin` in User
struct User:
    name: str
    admin: bool

fn new_user(name: str) User:
    return User(name, false)

fn main():
    print(new_user("ada"))
Output
User{name: "ada", admin: false}

field FIELD given twice

The same field was given by position and by name, or twice by name.

Does not compile
struct Point:
    x, y: int

fn main():
    p = Point(1, x=2)
Compiler output
5: error: field `x` given twice
5: error: missing field `y` in Point

x 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)
Output
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().

Does not compile
struct User:
    name: str

fn main():
    u = User("ada")
    print(u.nmae)
Compiler output
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)
Output
ada
Does not compile
fn main():
    xs = [1, 2]
    print(xs.length)
Compiler output
3: error: [int] has no field `length`
3: hint: use `len(x)`
fn main():
    xs = [1, 2]
    print(len(xs))
Output
2

field FIELD is TYPE, not TYPE

A value in a struct constructor has the wrong type for its field.

Does not compile
struct Item:
    name: str
    qty: int

fn main():
    it = Item("pen", "2")
Compiler output
6: error: field `qty` is int, not str
struct Item:
    name: str
    qty: int

fn main():
    it = Item("pen", 2)
    print(it)
Output
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 (...).)

Does not compile
enum Color:
    Red
    Green

fn main():
    c = Color()
Compiler output
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)
Output
Color.Green

ENUM 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.

Does not compile
enum Color:
    Red
    Green

fn main():
    c = Color.Blue
Compiler output
6: error: Color has no variant `Blue` (it has Red, Green)
enum Color:
    Red
    Green
    Blue

fn main():
    c = Color.Blue
    print(c)
Output
Color.Blue

ENUM.VARIANT takes N value(s), got N

The variant was built with the wrong number of values.

Does not compile
enum Shape:
    Circle(radius: float)

fn main():
    s = Shape.Circle(1.0, 2.0)
Compiler output
5: error: Shape.Circle takes 1 value(s), got 2
enum Shape:
    Circle(radius: float)

fn main():
    s = Shape.Circle(1.0)
    print(s)
Output
Shape.Circle(radius: 1.0)

ENUM.VARIANT has no field NAME

A named value doesn't match any of the variant's fields.

Does not compile
enum Shape:
    Circle(radius: float)

fn main():
    s = Shape.Circle(r=1.0)
Compiler output
5: error: Shape.Circle has no field `r`
5: error: missing `radius` in Shape.Circle

The 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)
Output
Shape.Circle(radius: 1.0)

missing FIELD in ENUM.VARIANT

Every value of a variant must be given.

Does not compile
enum Shape:
    Rect(w: float, h: float)

fn main():
    s = Shape.Rect(w=2.0)
Compiler output
5: error: missing `h` in Shape.Rect
enum Shape:
    Rect(w: float, h: float)

fn main():
    s = Shape.Rect(w=2.0, h=3.0)
    print(s)
Output
Shape.Rect(w: 2.0, h: 3.0)

FIELD is TYPE, not TYPE

A value given to an enum variant has the wrong type.

Does not compile
enum Shape:
    Circle(radius: float)

fn main():
    s = Shape.Circle(1)
Compiler output
5: error: `radius` is float, not int
enum Shape:
    Circle(radius: float)

fn main():
    s = Shape.Circle(1.0)
    print(s)
Output
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.

Does not compile
enum Shape:
    Circle(radius: float)
    Square(side: float)

fn main():
    s = Shape.Circle(2.0)
    print(s.radius)
Compiler output
7: error: Shape is an enum: use `match` to get at its values
enum Shape:
    Circle(radius: float)
    Square(side: float)

fn main():
    s = Shape.Circle(2.0)
    match s:
        Circle(r):
            print(r)
        Square(side):
            print(side)
Output
2.0

match works on enums, int, str, and bool, not TYPE

match can't compare floats, arrays, maps, or structs. Use if/elif for those.

Does not compile
fn main():
    x = 1.5
    match x:
        _:
            print(x)
Compiler output
3: error: match works on enums, int, str, and bool, not float
fn main():
    x = 1.5
    if x < 1.0:
        print("small")
    else:
        print("large")
Output
large

ENUM 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.

Does not compile
enum Level:
    Low
    High

fn main():
    lv = Level.Low
    match lv:
        0:
            print("low")
        _:
            print("high")
Compiler output
8: error: Level is an enum: match its variants, not int values
enum Level:
    Low
    High

fn main():
    lv = Level.Low
    match lv:
        Low:
            print("low")
        High:
            print("high")
Output
low

this pattern is TYPE, but the value being matched is TYPE

The literal in a pattern has a different type from the value being matched.

Does not compile
fn main():
    code = 404
    match code:
        "404":
            print("not found")
Compiler output
4: error: this pattern is str, but the value being matched is int
fn main():
    code = 404
    match code:
        404:
            print("not found")
        _:
            print("something else")
Output
not found

NAME 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 _.

Does not compile
fn main():
    n = 7
    match n:
        other:
            print(n)
Compiler output
4: error: `other` is a variant pattern, but the value being matched is int
fn main():
    n = 7
    match n:
        _:
            print(n)
Output
7

ENUM.VARIANT doesn't match a TYPE

A qualified pattern names a variant of a different enum.

Does not compile
enum Light:
    Red
    Green

enum Alert:
    Red

fn main():
    l = Light.Red
    match l:
        Alert.Red:
            print("stop")
        _:
            print("go")
Compiler output
11: error: `Alert.Red` doesn't match a Light
enum Light:
    Red
    Green

enum Alert:
    Red

fn main():
    l = Light.Red
    match l:
        Light.Red:
            print("stop")
        _:
            print("go")
Output
stop

VARIANT is already handled above

A variant appears in two arms; the second could never run.

Does not compile
enum Light:
    Red
    Green

fn main():
    l = Light.Red
    match l:
        Red:
            print("stop")
        Red:
            print("halt")
        Green:
            print("go")
Compiler output
10: error: `Red` is already handled above
enum Light:
    Red
    Green

fn main():
    l = Light.Red
    match l:
        Red:
            print("stop")
        Green:
            print("go")
Output
stop

ENUM.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.

Does not compile
enum Shape:
    Rect(w: float, h: float)

fn main():
    s = Shape.Rect(2.0, 3.0)
    match s:
        Rect(w):
            print(w)
Compiler output
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)
Output
2.0

match 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.

Does not compile
enum Light:
    Red
    Yellow
    Green

fn main():
    l = Light.Red
    match l:
        Red:
            print("stop")
Compiler output
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")
Output
stop

can'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.

Does not compile
enum State:
    Loading(progress: int)
    Done

fn main():
    s = State.Loading(100)
    match s:
        Loading(p):
            if p == 100:
                s = State.Done
        Done:
            pass
Compiler output
10: error: can't change `s` inside a `match` on it (its values are in use); change it after the match
enum 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)
Output
State.Done

Arrays, maps, and strings

can't index into TYPE

Only arrays (xs[i]), maps (m[k]), and strings (s[i]) can be indexed.

Does not compile
fn main():
    n = 1234
    print(n[0])
Compiler output
3: error: can't index into int
fn main():
    n = 1234
    print(str(n)[0])
Output
1

array index must be an int

Does not compile
fn main():
    xs = [10, 20]
    print(xs["0"])
Compiler output
3: error: array index must be an int
fn main():
    xs = [10, 20]
    print(xs[0])
Output
10

this map's keys are TYPE

The index has a different type from the map's keys.

Does not compile
fn main():
    ages = {"ada": 36}
    print(ages[0])
Compiler output
3: error: this map's keys are str
fn main():
    ages = {"ada": 36}
    print(ages["ada"])
Output
36

can only slice a str or an array, not TYPE

Does not compile
fn main():
    ages = {"ada": 36, "bob": 25}
    print(ages[..1])
Compiler output
3: error: can only slice a str or an array, not {str:int}
fn main():
    ages = {"ada": 36, "bob": 25}
    print(ages.keys()[..1])
Output
["ada"]

slice bounds must be ints

Does not compile
fn main():
    s = "hello"
    print(s[1.0..])
Compiler output
3: error: slice bounds must be ints
fn main():
    s = "hello"
    print(s[1..])
Output
ello

[value] * n: n must be an int

Does not compile
fn main():
    zeros = [0] * 3.0
Compiler output
2: error: `[value] * n`: n must be an int
fn main():
    zeros = [0] * 3
    print(zeros)
Output
[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.

Does not compile
fn main():
    xs = [1, 2.5]
Compiler output
2: error: array mixes int and float
fn main():
    xs = [1.0, 2.5]
    print(xs)
Output
[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.

Does not compile
fn main():
    config = {"port": 8080, "host": "localhost"}
Compiler output
2: error: map mixes str: int with str: str
struct Config:
    port: int
    host: str

fn main():
    config = Config(8080, "localhost")
    print(config)
Output
Config{port: 8080, host: "localhost"}

len() needs a str, array, map, or channel, not TYPE

Does not compile
fn main():
    n = 1234
    print(len(n))
Compiler output
3: error: len() needs a str, array, map, or channel, not int
fn main():
    n = 1234
    print(len(str(n)))
Output
4

push() needs an array, not TYPE

push adds to the end of an array. Maps grow with m[k] = v; strings with +=.

Does not compile
fn main():
    s = "ab"
    s.push("c")
Compiler output
3: error: push() needs an array, not str
fn main():
    s = "ab"
    s += "c"
    print(s)
Output
abc

argument 2 of push should be TYPE, not TYPE

The pushed value doesn't match the array's element type.

Does not compile
fn main():
    xs = [1, 2]
    xs.push("3")
Compiler output
3: error: argument 2 of `push` should be int, not str
fn main():
    xs = [1, 2]
    xs.push("3".to_int(0))
    print(xs)
Output
[1, 2, 3]

pop() needs an array, not TYPE

Does not compile
fn main():
    s = "abc"
    last = s.pop()
Compiler output
3: error: pop() needs an array, not str
fn main():
    s = "abc"
    last = s[len(s) - 1]
    s = s[..len(s) - 1]
    print(last, s)
Output
c ab

NAME() 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.

Does not compile
fn main():
    xs = [5, 6, 7]
    xs.remove(1)
Compiler output
3: error: remove() works on maps, not [int]
fn main():
    xs = [5, 6, 7]
    xs = xs.filter(fn(x) x != 6)
    print(xs)
Output
[5, 7]

get(): the key should be TYPE, not TYPE

Does not compile
fn main():
    ages = {"ada": 36}
    print(ages.get(0, -1))
Compiler output
3: error: get(): the key should be str, not int
fn main():
    ages = {"ada": 36}
    print(ages.get("zed", -1))
Output
-1

get(): the default should be TYPE, not TYPE

The default is returned when the key is missing, so it must have the value type.

Does not compile
fn main():
    ages = {"ada": 36}
    print(ages.get("zed", "unknown"))
Compiler output
3: error: get(): the default should be int, not str
fn main():
    ages = {"ada": 36}
    print(ages.get("zed", -1))
Output
-1

strings 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.

Does not compile
fn main():
    s = "cat"
    s[0] = "b"
Compiler output
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)
Output
bat

NAME 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.

Does not compile
fn main():
    print([1, 2, 3].pop())
Compiler output
2: error: `pop` modifies its receiver, so it needs a variable, field, or element
2: error: can only modify a variable, field, or element
fn main():
    xs = [1, 2, 3]
    print(xs.pop(), xs)
Output
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".

Does not compile
fn main():
    xs = [1, 2]
    print(xs.map(2))
Compiler output
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 int
fn main():
    xs = [1, 2]
    print(xs.map(fn(x) x * 2))
Output
[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.

Does not compile
fn shout(s: str) str:
    return s.upper()

fn main():
    xs = [1, 2]
    print(xs.map(shout))
Compiler output
6: error: argument 2 of `map` should be fn(int)?, not fn(str)str
6: error: map(): the function should take one int
fn shout(s: str) str:
    return s.upper()

fn main():
    xs = ["a", "b"]
    print(xs.map(shout))
Output
["A", "B"]

map(): the function must return a value

Does not compile
fn show(x: int):
    print(x)

fn main():
    xs = [1, 2]
    ys = xs.map(show)
Compiler output
6: error: map(): the function must return a value
fn main():
    xs = [1, 2]
    for x in xs:
        print(x)
Output
1
2

filter(): the function should return bool, not TYPE

For a lambda, the same mistake is reported as this function should return bool, not TYPE.

Does not compile
fn double(x: int) int:
    return x * 2

fn main():
    xs = [1, 2, 3]
    print(xs.filter(double))
Compiler output
6: error: argument 2 of `filter` should be fn(int)bool, not fn(int)int
6: error: filter(): the function should return bool, not int
fn is_even(x: int) bool:
    return x % 2 == 0

fn main():
    xs = [1, 2, 3]
    print(xs.filter(is_even))
Output
[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.

Does not compile
fn main():
    words = ["pear", "fig"]
    print(words.sort_by(fn(w) len(w) > 3))
Compiler output
3: error: sort_by(): the function should return an int, float, f32, or str to sort by, not bool
fn main():
    words = ["pear", "fig"]
    print(words.sort_by(fn(w) len(w)))
Output
["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.

Does not compile
fn add_tax(price: float) float:
    price = price * 1.2
    return price

fn main():
    pass
Compiler output
2: 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)
Output
12.0
12.0

This includes push, pop, and field assignment on a parameter:

Does not compile
fn add_default(tags: [str]):
    tags.push("new")

fn main():
    pass
Compiler output
2: 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)
Output
["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.

Does not compile
fn main():
    prices = [10, 20]
    for p in prices:
        p = p * 2
Compiler output
4: 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)
Output
[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.

Does not compile
fn items() [int]:
    return [1, 2]

fn main():
    items()[0] = 5
Compiler output
5: error: can only modify a variable, field, or element
fn items() [int]:
    return [1, 2]

fn main():
    xs = items()
    xs[0] = 5
    print(xs)
Output
[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.

Does not compile
fn reset(n: mut int):
    n = 0

fn main():
    count = 5
    reset(count)
Compiler output
6: error: argument 1 of `reset` is `mut`: write `&count` so the change is visible here
fn reset(n: mut int):
    n = 0

fn main():
    count = 5
    reset(&count)
    print(count)
Output
0

argument 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.

Does not compile
fn show(n: int):
    print(n)

fn main():
    count = 5
    show(&count)
Compiler output
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)
Output
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.

Does not compile
fn main():
    x = 1
    y = &x
Compiler output
3: error: `&` is only for passing an argument to a `mut` parameter
fn main():
    x = 1
    y = x              # a copy
    y += 1
    print(x, y)
Output
1 2

can'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.)

Does not compile
fn main():
    fn limit() int:
        return 5
    limit = 10
Compiler output
4: 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)
Output
10

Aliasing

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.

Does not compile
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)
Compiler output
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)
Output
[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.

Does not compile
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))
Compiler output
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))
Output
[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.

Does not compile
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)
Compiler output
10: error: `c.on_tick` would see the same value twice: `&c` can be changed, but `c.on_tick` is the function being called
struct 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)
Output
1

can'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).

Does not compile
fn bump(n: mut int) int:
    n += 1
    return n

fn main():
    x = 0
    print(x, bump(&x))
Compiler output
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 before
fn bump(n: mut int) int:
    n += 1
    return n

fn main():
    x = 0
    before = x
    print(before, bump(&x), x)
Output
0 1 1

Reads 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)

Does not compile
fn consume(xs: take [int]) int:
    return len(xs)

fn main():
    xs = [1, 2]
    print(consume(xs))
    print(len(xs))
Compiler output
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))
Output
2
2

NAME 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.

Does not compile
fn consume(xs: take [int]) int:
    return len(xs)

fn main():
    xs = [1, 2]
    print(consume(xs))
    xs.push(3)
Compiler output
7: error: `xs` was handed to a `take` parameter earlier and is gone
fn consume(xs: take [int]) int:
    return len(xs)

fn main():
    xs = [1, 2]
    print(consume(xs))
    xs = [3]
    print(xs)
Output
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.

Does not compile
fn keep(row: take [int]) int:
    return len(row)

fn main():
    row = [0, 0]
    for i in 0..3:
        print(keep(row))
Compiler output
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)))
Output
2
2
2

can'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.

Does not compile
fn keep(xs: take [int]) int:
    return len(xs)

fn process(xs: mut [int]):
    print(keep(xs))

fn main():
    pass
Compiler output
5: 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)
Output
2

Loops

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.

Does not compile
fn main():
    n = 3
    for i in n:
        print(i)
Compiler output
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)
Output
0
1
2

range bounds must be int

Ranges count integers. For float steps, loop over ints and convert.

Does not compile
fn main():
    for x in 0..2.5:
        print(x)
Compiler output
2: error: range bounds must be int
fn main():
    for i in 0..5:
        print(float(i) * 0.5)
Output
0.0
0.5
1.0
1.5
2.0

break is only allowed inside a loop

The same message is used for continue.

Does not compile
fn main():
    x = 1
    if x > 0:
        break
Compiler output
4: error: `break` is only allowed inside a loop
fn main():
    for x in [1, -1, 2]:
        if x < 0:
            break
        print(x)
Output
1

can'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.

Does not compile
fn main():
    names = ["a", "b"]
    for n in names:
        names.push(n + "2")
Compiler output
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)
Output
["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:

Does not compile
fn main():
    stock = {"pen": 3, "ink": 0}
    for k, v in stock:
        stock[k] = v + 10
Compiler output
4: 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)
Output
{"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".

Does not compile
fn count(xs: [int]) int:
    return len(xs)

fn main():
    total = 0
    parallel:
        total += count([1, 2])
        total += count([3])
    print(total)
Compiler output
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 block
fn count(xs: [int]) int:
    return len(xs)

fn main():
    parallel:
        a = count([1, 2])
        b = count([3])
    print(a + b)
Output
3

iterations 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.

Does not compile
fn main():
    total = 0
    parallel for i in 0..100:
        total += i * i
Compiler output
4: 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 loop
fn main():
    squares = [0] * 100
    parallel for i in 0..100:
        squares[i] = i * i
    total = 0
    for s in squares:
        total += s
    print(total)
Output
328350

For an array, the message says write onlyNAME[i]``: each iteration may write only the element at its own index.

Does not compile
fn main():
    xs = [0] * 10
    parallel for i in 0..10:
        xs[0] = i
Compiler output
4: 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 loop
fn main():
    xs = [0] * 10
    parallel for i in 0..10:
        xs[i] = i
    print(xs)
Output
[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.

Does not compile
fn main():
    xs = [1, 2, 3, 4]
    parallel for i in 0..3:
        xs[i] = xs[i + 1]
Compiler output
4: error: each iteration writes `xs[i]`, so reading any other part of `xs` inside the loop would race
fn main():
    xs = [1, 2, 3, 4]
    old = xs
    parallel for i in 0..3:
        xs[i] = old[i + 1]
    print(xs)
Output
[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.

Does not compile
fn main():
    squares: {int: int} = {}
    parallel for i in 0..10:
        squares[i] = i * i
Compiler output
3: error: `squares` is not an array
fn 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])
Output
81

can't tell the type of NAME

A one-line task that creates a variable must give it a value whose type is known.

Does not compile
fn main():
    parallel:
        names = []
        n = 5
    print(names, n)
Compiler output
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)
Output
["a"] 5

do: groups several statements into one task, so it only works directly inside parallel:

Does not compile
fn main():
    do:
        print(1)
Compiler output
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)
Output
2 5

return isn't allowed inside parallel; assign the result to a variable and return after the block

Does not compile
fn fib(n: int) int:
    if n < 2:
        return n
    parallel:
        return fib(n - 1) + fib(n - 2)
    return 0

fn main():
    pass
Compiler output
5: error: `return` 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:
        a = fib(n - 1)
        b = fib(n - 2)
    return a + b

fn main():
    print(fib(15))
Output
610

Closures

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.

Does not compile
fn main():
    count = 0
    fn bump():
        count += 1
    bump()
Compiler output
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)
Output
2

can'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).

Does not compile
fn main():
    double = fn(x) x * 2
Compiler output
2: 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))
Output
4 6

this 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.

Does not compile
fn main():
    add: fn(int) int = fn(a, b) a + b
Compiler output
2: 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))
Output
5

parameter NAME should be TYPE here

A lambda parameter's written type differs from the one the context expects.

Does not compile
fn main():
    xs = [1, 2]
    ys = xs.filter(fn(x: str) len(x) > 0)
Compiler output
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 int
fn main():
    xs = [1, 2]
    ys = xs.filter(fn(x: int) x > 1)
    print(ys)
Output
[2]

this function should return TYPE, not TYPE

The lambda's expression has a different type from the expected return type.

Does not compile
fn main():
    label: fn(int) str = fn(n) n * 2
Compiler output
2: error: this function should return str, not int
fn main():
    label: fn(int) str = fn(n) str(n * 2)
    print(label(4))
Output
8

Modules

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.

Does not compile
import modles

fn main():
    pass
1: 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.

Does not compile
import fmt

fn main():
    print(fmt._scaled(5, 2))
Compiler output
4: error: `_scaled` is private to module `fmt`
import fmt

fn main():
    print(fmt.cents(500))
Output
5.00

module 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.

Does not compile
import fmt

fn main():
    print(fmt.fixd(3.14159, 2))
Compiler output
4: error: module `fmt` has no `fixd`
import fmt

fn main():
    print(fmt.fixed(3.14159, 2))
Output
3.14

NAME 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.)

Does not compile
fn describe(req: http.Request) str:
    return req.path

fn main():
    pass
Compiler output
1: error: `http` isn't an imported module (add `import http`)
Compiles (not run here)
import http

fn describe(req: http.Request) str:
    return req.path

fn main():
    pass

import 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].

Does not compile
struct Point:
    x, y: float

extern "math.h":
    fn hypot(p: Point) float

fn main():
    pass
Compiler output
5: 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))
Output
5.0

TYPE 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.

Does not compile
extern "names.h":
    fn fill_name(out: mut str)

fn main():
    pass
Compiler output
2: error: `str` can't cross the C boundary (a `mut` parameter can be int, float, bool, ptr, [int], [float], or [byte])
Compiles (not run here)
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)

Does not compile
extern "string.h":
    fn strlen(s: take str) int

fn main():
    pass
Compiler output
2: 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"))
Output
5

NAME 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.

Does not compile
extern "stats.h":
    fn histogram() [int]

fn main():
    pass
Compiler output
2: error: `histogram` returns [int], which can't cross the C boundary (C functions return int, float, bool, str, ptr, or an extern struct)
Compiles (not run here)
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.

Does not compile
extern "stdlib.h":
    fn labs(n: int) int

fn main():
    f = labs
Compiler output
5: error: `labs` is a C function; wrap it in a Tern function to use it as a value
extern "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))
Output
[2, 3]

an extern block holds fn signatures (no bodies)

Does not compile
extern "stdlib.h":
    limit = 5

fn main():
    pass
Compiler output
2: error: an `extern` block holds `fn` signatures (no bodies) and `struct`s
extern "stdlib.h":
    fn labs(n: int) int

fn main():
    print(labs(-5))
Output
5

after =, write the C function name in quotes: = "c_name"

= "name" gives a Tern name to a C function with a different name.

Does not compile
extern "stdlib.h":
    fn long_abs(n: int) int = labs

fn main():
    pass
Compiler output
2: 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))
Output
5

WORD 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.

Does not compile
extern "math.h" link m:
    fn cbrt(x: float) float

fn main():
    pass
Compiler output
1: error: `link` needs a quoted file or library name
extern "math.h" link "m":
    fn cbrt(x: float) float

fn main():
    print(cbrt(27.0))
Output
3.0

exported 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.

Does not compile
export fn double_all(xs: mut [int]):
    for i in 0..len(xs):
        xs[i] *= 2

fn main():
    pass
Compiler output
1: 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))
Output
42

TYPE can't cross the C boundary (exported functions take int, float, bool, str, or ptr)

Does not compile
struct Point:
    x, y: int

export fn norm1(p: Point) int:
    return abs(p.x) + abs(p.y)

fn main():
    pass
Compiler output
4: 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))
Output
7

exported 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.

Does not compile
export fn primes() [int]:
    return [2, 3, 5]

fn main():
    pass
Compiler output
1: 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())
Output
[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.

Does not compile
fn main():
    name = ""
    print(name.is_null())
Compiler output
3: error: is_null() needs a ptr, not str
fn main():
    name = ""
    print(len(name) == 0)
Output
true

Web, 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.

Does not compile
import http

fn main():
    http.serve(8080)
Compiler output
4: error: http.serve(port, handler) or http.serve(port, handler, app)
Compiles (not run here)
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

Does not compile
import http

fn handle(req: http.Request) http.Response:
    return http.text("hello")

fn main():
    http.serve("8080", handle)
Compiler output
7: error: serve(): the port must be an int
Compiles (not run here)
import 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.

Does not compile
import http

fn main():
    http.serve(8080, fn(req: http.Request) http.text("hello"))
Compiler output
4: error: serve(): the second argument must be the name of a handler function
Compiles (not run here)
import 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).

Does not compile
import http

fn handle(path: str) str:
    return "hello " + path

fn main():
    http.serve(8080, handle)
Compiler output
7: error: serve(): `handle` must look like `fn handler(req: http.Request) http.Response`
Compiles (not run here)
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.

Does not compile
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)
Compiler output
12: error: `handle` changes the app state, so pass it with `&`; requests then run one at a time
Compiles (not run here)
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)

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 &.

Does not compile
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)
Compiler output
11: error: `handle` only reads the app state, so pass it without `&`
Compiles (not run here)
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.

Does not compile
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")
Compiler output
10: error: serve(): the app state should be App, not str
Compiles (not run here)
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, 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.

Does not compile
import json

struct Button:
    label: str
    on_click: fn(int) str

fn main():
    b = Button("go", fn(n) "clicked")
    print(json.encode(b))
Compiler output
9: error: json.encode can't handle Button
import json

struct Button:
    label: str
    on_click: fn(int) str

fn main():
    b = Button("go", fn(n) "clicked")
    print(json.encode(b.label))
Output
"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.

Does not compile
import json

fn main():
    pair = (1, "a")
    ok = json.decode(`[2, "b"]`, &pair)
Compiler output
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)
Output
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])
Output
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"])
Output
-1

runtime 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 zero

Check the divisor:

fn main():
    total = 10
    count = 0
    avg = 0
    if count != 0:
        avg = total / count
    print(avg)
Output
0

runtime 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 array

Check the length first:

fn main():
    stack = [1, 2]
    while len(stack) > 0:
        print(stack.pop())
Output
2
1

runtime error: negative array length

[value] * n with a negative n. The line number is reported as 0.

fn main():
    n = -1
    zeros = [0] * n
runtime error: negative array length

Use max(n, 0) if n may be negative:

fn main():
    n = -1
    zeros = [0] * max(n, 0)
    print(zeros)
Output
[]

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)
Output
true

runtime 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 channel

Usually 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:

MessageMeaning
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 seta function value was called before any function was stored in it
Source: docs/errors.md. Every example on this page is compiled and run by tern x test docs.