Tern language reference
This is the complete reference for writing Tern programs. It is written so that a reader who has never seen Tern (a person or an LLM) can write correct code on the first try. Every tern ` block below is a complete program that the test suite (`tern run tests/runner/main.tn -- docs`) compiles and runs; when an `output block follows, the program's output must match it exactly. So the examples here are known to work.
0. The short version
Tern looks like Python, but it is statically typed and compiled, and every value is a copy: there are no references, pointers, None, classes, or exceptions.
The rules that differ most from Python:
- Functions are
fn name(a: int, b: str) int:. Every parameter needs a type. The return type comes after the)with no arrow (-> intis also accepted). No return type = returns nothing. x = 5creates a variable. Its type is fixed from then on.x: float = 0.0states a type. There is noletorvar, and there are no global variables. Top-levelconst NAME = valuedeclares a constant (computed at compile time, or on first use when it calls a function).- The top level of a file may only contain
import,from ... import,struct,enum,const,fn,extern, andexport fn. The program starts atfn main():. - Types:
int(64-bit),float(64-bit),bool,str,[T](array),{K: V}(map), structs, enums, tuples(int, str),fn(int) str(functions).==compares any of them (except functions) by value. Generics:fn first[T](xs: [T]) T,struct Pair[A, B]. No null: a value that may be missing is anOption[T](Some(x)orNone), a result that may fail aResult[T, E](§9). true,false(lowercase). Logic isand,or,not. Strings use double quotes only.- No implicit conversions:
1 + 2.0is an error. Writefloat(1) + 2.0or1 + int(2.0).str + intis an error: write"n=" + str(n)orf"n={n}". /on two ints is integer division (truncates toward zero). There is no//.- Parameters are read-only. To let a function change the caller's variable, declare the parameter
mutand pass it with&:fn inc(n: mut int)is called asinc(&x). - Assignment copies: after
b = a, changingbnever changesa(this includes arrays, maps, and structs; the copy is lazy, so it is cheap until one side is written). for i in 0..n:loops over0, 1, ..., n-1. There is norange().- Arrays:
xs.push(v),xs.pop(),len(xs).pushcopiesvinto the array, like=(sovstays usable, and it moves for free whenvisn't used again). There is noappend, list comprehension, or negative index. Usexs.sorted(),xs.reversed(),sum(xs),xs.sort_by(fn(x) key),xs.map(...),xs.filter(...): each returns a new value and leavesxsalone. - Structs have no methods inside them. Write a function whose first parameter is the struct; then
p.area()callsarea(p). - Your functions may share a builtin's name (
fn get(s: Store, id: int)): a call uses yours when its first parameter fits the first argument, and the builtin otherwise. See §20.
A complete program:
struct Item:
name: str
price: float
qty: int
fn total(items: [Item]) float:
t = 0.0
for it in items:
t += it.price * float(it.qty)
return t
fn main():
items: [Item] = []
items.push(Item("apple", 0.5, 4))
items.push(Item(name="pear", price=0.75, qty=2))
print(f"{len(items)} items, total {total(items)}")
for i, it in items:
print(i, it.name)2 items, total 3.5
0 apple
1 pear1. Running programs
tern run prog.tn compile and run (needs clang)
tern run prog.tn -- a b pass arguments (read them with os.args())
tern check prog.tn type/safety check only; prints "prog.tn: ok"
tern check --json prog.tn errors as JSON (for tools and agents)
tern test prog_test.tn run the `test_*` functions (see the `testing` module, §16)
tern fmt prog.tn reformat the file in place
tern build prog.tn -o prog make a native binary
tern emit prog.tn print the generated C
tern guide print this reference
tern guide strings print only the sections about a topiccheck --json prints {"ok": true, "file": ...} or {"ok": false, "errors": [...]}, where each error is {"file", "line", "message", "hint", "source"} (hint is null when there is none; source is the offending line).
Compile errors look like prog.tn:12: error: <message>, often followed by a hint: line when the code looks like another language. All errors in a file are reported at once. A runtime error (index out of bounds, missing map key, division by zero, pop() on an empty array) prints runtime error in f (prog.tn:N): <message> to stderr ((util.tn, line N) when it happened in another file), then the Tern functions it came through (in util.helper <- run <- main), and exits with status 2.
2. Lexical rules
- Comments start with
#and run to the end of the line. There are no block comments or docstrings. - Blocks are made by indentation after a
:, like Python. Use 4 spaces. A block with one statement may go on the same line:if x > 0: print(x). - A line continues while a
(,[, or{is open, or after a trailing\. - No semicolons.
- Integers:
42,1_000_000, hex0xff, binary0b1010, octal0o17(_may separate digits anywhere). A decimal literal must fit in an int (up to9223372036854775807); a hex, binary, or octal one may use all 64 bits, and above that value it is negative (0xffff_ffff_ffff_ffffis-1), which is handy for hash constants and masks. A literal that doesn't fit is a compile error. - Floats:
1.0,0.5,1e9,2.5e-3,6.02E+23(an exponent makes a float). A dot needs digits on both sides: not1.or.5. - Strings:
"double quotes", on one line. Escapes:\n \t \r \0 \" \\;\xNNis one byte ("\x01","\xff");\u00e9(four hex digits) and\u{1F600}(one to six) are a Unicode character, stored as UTF-8. A malformed\xor\uis a compile error. Any other backslash is kept as is:"a\qb"is the four bytesa \ q b. - Multi-line strings:
"""..."""(andf"""...""") may span lines and take the same escapes;"needs no escape inside. When the text starts on the line after the opening""", that line break and the one before the closing"""are dropped, and the indentation all its lines share is removed, so a block of SQL or HTML can be indented with the code. - Raw strings:
`C:\dir\file`between backticks: every character as written, no escapes, may span lines (a backtick can't appear inside). Good for regular expressions and JSON. - F-strings:
f"x = {x}, next = {x + 1}". Any expression whose value is anint,float,bool, orstrgoes in{}(for an array, map, or struct, useprint(label, xs)orjson.encode(xs));{{and}}are literal braces. No format specs ({x:.2f}is an error): use thefmtmodule,f"{fmt.fixed(x, 2)}"(§12). - Names: letters, digits,
_. Names starting with_are private to their module. - Keywords:
and break const continue do elif else enum export extern false fn for from if import in mut not null or parallel pass return struct take true while.matchis a soft keyword,typeis one at the top level (type Name = T), andisis one after an expression (x is None).
3. Variables and types
fn main():
n = 10 # int
ratio = 0.25 # float
ok = true # bool
name = "tern" # str
xs = [1, 2, 3] # [int]
ages = {"ada": 36} # {str: int}
empty: [str] = [] # an empty collection needs a type...
later = [] # ...or gets it from its first use
later.push(1.5)
n = n + 1 # reassigning keeps the type
print(n, ratio, ok, name, xs, ages, empty, later)11 0.25 true tern [1, 2, 3] {"ada": 36} [] [1.5]- A variable is created by its first assignment and lives until the end of the block it was created in. Create it before an
ifif you need it after:
fn main():
label = ""
if 3 > 2:
label = "big"
else:
label = "small"
print(label)big- There is no declaration without a value (
x: intalone is an error); usex = 0. - Constants go at the top level:
const NAME = valueorconst NAME: type = value. A value made of literals, other such constants, and operators (includinga if c else b) is an int, float, str, or bool computed when compiling; it can also be amatchpattern. A constant can be used anywhere a value can, and from other modules (config.PORT,from config import PORT). There are no global variables: constants can't change, so every task can read them. - Any other value (a function call, an array, a struct, a compiled regex, a
task.shared_map()cache) is computed when the program first uses it, once, even if many tasks use it at the same moment, and kept:const EMAIL = re.must("[^@ ]+@[^@ ]+")compiles the pattern once for the whole program. Its type comes from the value (write it,const X: [str] = [], when it can't). It can't be amatchpattern, and a value that needs itself is a runtime error.
const MAX_USERS = 100
const NAME = "tern"
const BANNER = NAME + " v2"
const MASK: int = (1 << 12) - 1
const LIMIT = MAX_USERS * 2 if MASK > 0 else 0
fn kind(n: int) str:
match n:
MAX_USERS:
return "full"
_:
return "ok"
fn main():
print(BANNER, LIMIT, MASK, kind(100), kind(7))tern v2 200 4095 full okimport re
import task
const WORD = re.must("[a-z]+")
const STOP = ["the", "a", "of"]
const SEEN = task.shared_map() # one cache for the whole program
fn words(s: str) int:
n = 0
for m in WORD.find_all(s):
if not (m.text in STOP):
SEEN.add_int(m.text, 1)
n += 1
return n
fn main():
lines = ["the cat sat", "a cat of note"]
parallel for i in 0..len(lines):
words(lines[i])
print(SEEN.get_int("cat"), SEEN.get_int("the"), len(STOP))2 0 3- Types can't change:
x = 1thenx = "a"is an error. - Type syntax:
int float bool str byte f32,bytes16andf32x4(16 bytes / four f32s at once: std simd),[int],[[str]],{str: int},{int: [Point]},(int, str),Point,http.Request(a type from a module),fn(int, str) bool,fn(str)(returns nothing),ptr(C pointer). - Wrong type names from other languages are errors:
string,i32,i64,f64,list[int],List<int>,dict,Vec<T>. (voidis accepted only as a return type, where it means the same as leaving the return type out.) - Default values when you need one:
0,0.0,false,"",[],{}.
4. Operators
| Operator | Works on | Notes |
|---|---|---|
+ - * / | int with int, float with float | / on ints truncates toward zero: 7 / 2 == 3, -7 / 2 == -3 |
% | int | sign follows the left side: -7 % 3 == -1 |
+ | str with str | concatenation |
* | str with int | repetition: "ab" * 3 |
== != | any two values of the same type | structs, tuples, and enums field by field, arrays and maps element by element; not functions or task handles |
< <= > >= | int, float, str | strings compare by bytes |
and or not | bool | short-circuit |
in | x in xs (array), k in m (map key), "a" in s (substring) | |
& | ^ | int with int | bitwise and, or, xor (for bools, use and / or) |
<< >> >>> | int with int | shifts: >> keeps the sign (arithmetic), >>> shifts in zeros (logical) |
+= -= *= /= %= | same as the operator | also &= |= ^= <<= >>= >>>=; no ++ or -- |
-x | int, float | |
~x | int | bitwise not: ~x == -x - 1 |
&x | a variable, field, or element | only as an argument to a mut parameter |
x is P | an enum value | true if x is variant P: o is None, r is Ok(_), if o is Some(v): (§9) |
x? | an Option or a Result | the value in Some / Ok, else return the None / Err at once (§9) |
- Int arithmetic wraps on overflow (64-bit two's complement). Division or
%by zero is a runtime error. - A shift count must be 0 to 63:
1 << 64is a compile error when the count is written as a number, and a runtime error otherwise.<<shifts bits out of the top (it wraps like*). - Precedence, lowest first:
or,and, comparisons andin,|,^,&, shifts,+ -,* / %, then the unary-x,~x, andnot x(so writenot (a == b)). As in Python (not C),x & 4 == 4means(x & 4) == 4.
fn fnv1a(s: str) int: # a 64-bit hash
h = 0xcbf2_9ce4_8422_2325
for c in s:
h ^= c.byte(0)
h *= 0x100_0000_01b3
return h
fn main():
flags = 0b0101
flags |= 1 << 3 # set bit 3
print(flags, flags & 0b100 != 0, flags >> 1, ~0)
print(-16 >> 2, -16 >>> 60, 0xff, 0o17, 1e3)
print(fnv1a("tern"))13 true 6 -1
-4 15 255 15 1000.0
-440267618092719894a if cond else bis a conditional expression (as in Python; there is noc ? a : b). Only the chosen side is evaluated, both sides have the same type, and it binds loosest of all, sox = n * 2 if n > 0 else 0meansx = (n * 2) if n > 0 else 0:
fn sign(n: int) str:
return "negative" if n < 0 else "zero" if n == 0 else "positive"
fn main():
xs = [3, -1, 0]
print(xs.map(fn(x) sign(x)), [] if len(xs) > 5 else xs[..1])["positive", "negative", "zero"] [3]- There is no
**(usemath.pow) or//. - Mixing int and float is always an error; convert with
float(i)orint(f)(truncates toward zero; NaN, infinities, and floats outside int's range are a runtime error).
5. Control flow
fn main():
for i in 0..3: # 0, 1, 2 (end is exclusive; no step)
print("i", i)
xs = ["a", "b"]
for x in xs: # elements
print(x)
for i, x in xs: # index and element
print(i, x)
m = {"one": 1, "two": 2}
for k, v in m: # key and value, in insertion order
print(k, v)
n = 3
while n > 0: # counting down: use while
n -= 1
if n == 1:
continue
print("n", n)
x = 7
if x < 5:
print("small")
elif x < 10: # `elif`, never `else if`
print("medium")
else:
print("large")
for i in 0..100:
if i == 2:
break
if x > 0:
pass # an empty block needs `pass`i 0
i 1
i 2
a
b
0 a
1 b
one 1
two 2
n 2
n 0
mediumfor i in a..bwitha >= bruns zero times. To count down, usewhile.- The loop variable can't be assigned, and the array or map being looped over can't be changed inside the loop. To change elements while looping, loop over indices:
for i in 0..len(xs): xs[i] = xs[i] * 2. matchis covered in §9. There is noswitch,try,with,goto, ordo/while.
6. Functions
fn add(a: int, b: int) int:
return a + b
fn greet(name: str): # no return type: returns nothing
print("hello " + name)
fn divmod(a: int, b: int, q: mut int, r: mut int):
q = a / b # `mut` parameters write back to the caller
r = a % b
fn main():
greet("ada")
q = 0
r = 0
divmod(17, 5, &q, &r) # `&` marks each argument that may change
print(add(2, 3), q, r)hello ada
5 3 2- Every parameter has a type. There are no default values, keyword arguments (named arguments are only for building structs), variadic parameters, or overloading.
- A function with a return type must end with a
returnon every path. - Parameter modes: - default: read-only. Assigning to it, or calling
pushon it, is an error. -mut: the function may change it and the caller sees the change. The caller must write&x. -take: the value moves into the function (no copy). The caller can't usexafterwards (passcopy(x)to keep a copy). - To return several values, return a tuple:
fn divmod(a: int, b: int) (int, int):thenreturn q, r, and the caller writesq, r = divmod(7, 2)(§7, Tuples). - To report failure, return a
Result[T, E](Ok(value)orErr(error)), or anOption[T]when there's nothing to say about why (§9). There are no exceptions. - Method syntax:
x.f(a, b)is the same call asf(x, a, b). If the first parameter ismut, writex.f(...)orf(&x, ...).x.falso findsfin the module wherex's type is defined, sod.exec(...)callssqlite.exec(d, ...). - Functions can be defined inside functions (they are closures, §13) and may recurse. Top-level functions may be called before they are defined.
7. Structs
struct Point:
x, y: int # several fields of one type
struct Player:
name: str
pos: Point
scores: [int]
fn dist(p: Point) int: # "methods" are plain functions
return abs(p.x) + abs(p.y)
fn move(p: mut Player, dx: int): # a "mutating method"
p.pos.x += dx
fn main():
a = Point(1, 2) # positional: fields in order
b = Point(y=5, x=-3) # named: any order; every field is required
pl = Player("zed", a, [])
pl.scores.push(10) # nested fields and arrays change in place
pl.move(4) # same as move(&pl, 4)
c = a # a copy
c.x = 100
print(a.x, c.x, b.dist(), pl)1 100 8 Player{name: "zed", pos: Point{x: 5, y: 2}, scores: [10]}- All fields must be given when building a struct; there are no default field values. Write a constructor function if you want defaults:
fn new_player(name: str) Player:. - No
self, no classes, no inheritance, no interfaces.==compares two structs field by field; when equality means something else, writefn same_user(a: User, b: User) bool. - A struct may contain an array of itself (
kids: [Node]) but not itself directly. For graphs, store nodes in an array and refer to them by index. printshows structs asName{field: value, ...}.
Tuples
A tuple is a fixed group of values of any types, written (a, b); its type is written the same way, (int, str). It is a value like a struct whose fields have no names: read them by position with t.0, t.1. Functions return several values as a tuple, and a, b = ... unpacks one (each name on the left is a new variable, an existing one, a field or element, or _ to skip a value).
fn divmod(a: int, b: int) (int, int):
return a / b, a % b # parentheses are optional after `return` and `=`
fn main():
q, r = divmod(17, 5)
print(q, r)
t = divmod(9, 2)
print(t, t.0, t.1)
a = 1
b = 2
a, b = b, a # swap
_, rest = divmod(7, 3)
scores: [(str, int)] = [("ada", 3), ("bob", 5)]
scores.push(("cy", 4))
for s in scores:
print(s.0, s.1)
print(a, b, rest, scores[1])3 2
(4, 1) 4 1
ada 3
bob 5
cy 4
2 1 1 ("bob", 5)- A tuple has two or more values; there is no one-value tuple.
t.0 = 5changes one value. - The number of names on the left of
a, b = ...must match the tuple. - Tuples can go anywhere a type can: in arrays, maps, struct fields, and function types.
printshows(1, "a"), and==compares tuples value by value. Tuples can't be turned into JSON yet.
Generics
Functions, structs, and enums can take type parameters in [ ] after their name. A use with concrete types makes a version of the function or type for those types (like C++ templates or Rust): it runs exactly as fast as code written by hand for them.
struct Pair[A, B]:
left: A
right: B
enum Tree[T]: # recursive generic enums work too
Leaf
Node(l: Tree[T], v: T, r: Tree[T])
fn first[T](xs: [T]) T:
return xs[0]
fn largest[T: Ord](xs: [T]) T: # a constraint: T must support < and >
best = xs[0]
for x in xs:
if x > best:
best = x
return best
fn map_all[A, B](xs: [A], f: fn(A) B) [B]:
out: [B] = []
for x in xs:
out.push(f(x))
return out
fn insert[T: Ord](t: Tree[T], v: T) Tree[T]:
match t:
Leaf:
return Tree.Node(Tree[T].Leaf, v, Tree[T].Leaf)
Node(l, x, r):
if v < x:
return Tree.Node(insert(l, v), x, r)
return Tree.Node(l, x, insert(r, v))
fn main():
print(first([3, 1]), first(["a"]), largest([2.5, 9.0]))
p = Pair(1, "one") # Pair[int, str], from the values
q: Pair[str, [int]] = Pair("n", []) # the declared type fills in [int]
print(p, q, map_all([1, 2], fn(x) x * 10), first[str](["z"]))
t = Tree[int].Leaf # explicit type arguments
for v in [5, 2, 8]:
t = insert(t, v)
print(t)3 a 9.0
Pair{left: 1, right: "one"} Pair{left: "n", right: []} [10, 20] z
Tree.Node(l: Tree.Node(l: Tree.Leaf, v: 2, r: Tree.Leaf), v: 5, r: Tree.Node(l: Tree.Leaf, v: 8, r: Tree.Leaf))- Type arguments are usually inferred: from the arguments, then from the type the result is going into (a typed variable, a
return, a parameter), then from lambdas. When they can't be, write them:first[int](xs),Pair[int, str](1, "a"),Tree[int].Leaf. - A generic type always needs its arguments where a type is written:
Pair[int, str], notPair. - Constraints:
T: Ord(int, float, str:<,>, sorting),T: Eq(==),T: Hash(usable as a map key); several:T: Ord + Hash. Without a constraint any type is accepted, and the body is checked for each type it is used with; an error there names the version, e.g.(in `total[Point]`, used on line 12). - A generic function used as a value needs its arguments:
f = first[int]. - There are no traits or interfaces: pass behavior as a function value (
fn(T, T) bool).
Type aliases
type Name = T at the top level of a module gives a type a second name. The alias is the type: values pass freely between the two names, Name(...) constructs one, and x.f() finds f in the module that defines the original. A package uses aliases to present types that live elsewhere under its own name (roost.Request is http.Request).
struct Point:
x: int
y: int
type Pos = Point
type Path = [Pos]
type Scores = {str: int}
fn walk(p: Path) int:
total = 0
for q in p:
total += abs(q.x) + abs(q.y)
return total
fn main():
a = Pos(3, -4)
b: Point = a # the same type under two names
s: Scores = {"ada": walk([a, b])}
print(a, s)Point{x: 3, y: -4} {"ada": 14}- The alias's target is resolved in the alias's own module, so
type Request = http.Requestneedsimport httpthere; users of the alias don't. - An alias can name any type (
[T],{K: V},fn(int) str, another alias), but not itself, directly or through other aliases. - Errors and printed values use the original name (
Pointabove). typeis a soft keyword: onlytype NAME =at the top level declares an alias, sotypestill works as a field or variable name.
8. Arrays [T]
fn main():
xs = [3, 1, 2]
xs.push(5) # append at the end
last = xs.pop() # remove and return the last element
print(xs, last, len(xs), xs[0])
xs[0] = 30
zeros = [0] * 4 # [value] * n
grid = [[0] * 3] * 2 # 2 rows of 3 (each row is its own copy)
grid[1][2] = 7
print(zeros, grid)
print(xs[1..], xs[..2], xs[1..2], 2 in xs) # slices are copies
ys = xs.sort_by(fn(x) x) # returns a new sorted array (stable)
down = xs.sort_by(fn(x) -x) # descending: negate a number key
evens = [1, 2, 3, 4].filter(fn(x) x % 2 == 0)
squares = [1, 2, 3].map(fn(x) x * x)
print(ys, down, evens, squares, xs)
print(xs.sorted(), xs.reversed(), sum(xs), sum([0.5, 0.25]), max(xs), xs.min())
words = ["pear", "fig"]
print(words.sorted(), words.sort_by(fn(w) len(w)))[3, 1, 2] 5 3 3
[0, 0, 0, 0] [[0, 0, 0], [0, 0, 7]]
[1, 2] [30, 1] [1] true
[1, 2, 30] [30, 2, 1] [2, 4] [1, 4, 9] [30, 1, 2]
[1, 2, 30] [2, 1, 30] 33 0.75 30 1
["fig", "pear"] ["fig", "pear"]xs.extend(ys)pushes every element ofysontoxs.xs.reserve(n)makes room fornmore elements in one block, so pushing that many doesn't grow and copy the array on the way (like Go'smake([]T, 0, n)or Rust'sVec::with_capacity). It changes nothing else.xs.resize_uninit(n)makes an[int],[float],[f32]or[byte]exactlynlong without writing the new elements: their contents are undefined (whatever the memory held, possibly another array's old data) until you write them. It is for big arrays that are about to be filled completely, e.g. by C code, where[0] * nwould cost a pass over the memory first. Other element types start with values ([""] * n).- Slices clamp to the length (
[1, 2, 3][1..10]is[2, 3]), for strings too. - Indexes start at 0. Out-of-range indexes are runtime errors. There are no negative indexes: the last element is
xs[len(xs) - 1]. xs.sorted()is a sorted copy of an array of ints, floats, or strs;xs.reversed()is a copy in reverse order;sum(xs)adds an[int]or[float](0 when empty; int sums wrap like+), andmin(xs),max(xs)find its smallest and largest (an empty array is a runtime error). None of them changesxs: to sort in place, writexs = xs.sorted().sort_by(xs, key)sorts by a key that is anint,float, orstr(stable). It never changesxs; it returns a new array. Descending:xs.sort_by(fn(x) -x)for numbers,xs.sorted().reversed()for strings.- Other operations you might expect are short loops:
index_of,insert,zip. Example:for i in 0..len(xs): if xs[i] == v: return i. - Removing from the middle: build a new array with
filter, or with a loop. pushcopies its value into the array the way=does: lazily, and not at all when the pushed variable isn't used afterwards (then the value moves).
fn main():
names: [str] = []
name = "ada"
names.push(name) # `name` is still usable
name += "!" # and changing it doesn't change the array
names.push("bob")
print(name, names)ada! ["ada", "bob"]copy(x)makes an explicit copy. It is only needed fortakeparameters (§6).
Bytes
byte is a number from 0 to 255, for binary data: pixels, network buffers, hashes. A [byte] stores one byte per element (an [int] uses eight), so a 1024x1024 RGBA image is 4MB.
fn main():
px: [byte] = [255, 128, 0, 64] # a number 0-255 is a byte where one is expected
gray = (px[0] * 77 + px[1] * 150 + px[2] * 29) >> 8 # bytes in arithmetic are ints
out = [byte(0)] * 3
out[0] = byte(gray) # storing an int takes byte(n): its low 8 bits
out[1] = byte(300)
out[2] = 250
out[2] += 10 # op= on a byte wraps
data = "Tern".to_bytes() # str <-> [byte] share memory: no copy
data[0] = 116
print(gray, out, data.to_str(), int(px[1]) * 2)151 [151, 44, 4] tern 256- In arithmetic and comparisons a byte counts as an
int, and so does the result:px[0] * 77can't overflow.-bis an int too. - Storing an int into a byte (a variable, element, field, or argument) takes
byte(n), which keeps the low 8 bits. A literal from 0 to 255 needs no conversion; one outside that range is an error.b += n(anyop=) on a byte wraps, asbyte(b + n)would. int(b)andfloat(b)convert back.s.byte(i)still returns anint.s.to_bytes()gives a string's bytes,bs.to_str()makes a string of them. Both share the block (astrand a[byte]are laid out the same); writing to either copies it first.printandjson.encodeshow bytes as numbers;json.decoderejects numbers outside 0-255.
32-bit floats
f32 is a 32-bit float, for big arrays of numbers: vectors, embeddings, audio, model weights. An [f32] stores 4 bytes per element (a [float] uses eight), so a million 768-number embeddings take 3GB instead of 6GB. std simd works on four of them at once (f32x4), and std binary reads and writes them as raw bytes (binary.f32s_le, binary.f16s_le).
fn dot(a: [f32], b: [f32]) f32:
s: f32 = 0.0 # a float literal is an f32 where one is expected
for i in 0..len(a):
s += a[i] * b[i] # f32 * f32 is an f32
return s
fn main():
xs: [f32] = [0.5, 1.5, -2.0]
ys = [f32(1), f32(2), 0.25 * xs[0]] # f32(n) converts an int or a float
d = dot(xs, ys)
print(d, float(d) * 2.0, xs.sorted(), sum(xs), f32(0.1), float(f32(0.1)))3.25 6.5 [-2.0, 0.5, 1.5] 0.0 0.1 0.10000000149011612- Math on f32s stays in f32, as in Rust, Go and C. An f32 and a float don't mix: write
f32(x)orfloat(x)(a literal like0.5adapts by itself). print,strand f-strings show the shortest decimal that reads back as the same f32 (0.1, not0.10000000149011612);json.encodewrites the same, andjson.decoderounds.int(x),abs,sqrt,min,max,sum,sortedandsort_bykeys take f32s. An f32 can't be a map key (nor can a float).- In an
externblock an f32 is a Cfloat, and an[f32]afloat*.
9. Enums and match
import math
enum Shape:
Circle(radius: float)
Rect(w: float, h: float)
Empty
enum Expr: # recursive enums just work
Num(v: int)
Add(l: Expr, r: Expr)
fn area(s: Shape) float:
match s:
Circle(r): # bind payload values by position
return math.pi() * r * r
Rect(w, h):
return w * h
Empty:
return 0.0
fn eval(e: Expr) int:
match e:
Num(v):
return v
Add(l, r):
return eval(l) + eval(r)
fn describe(code: int) str:
match code: # match on int, str, or bool literals
200:
return "ok"
404:
return "not found"
301 | 302 | 307: # several patterns, one arm
return "redirect"
_: # `_` matches anything else
return "other"
fn main():
shapes = [Shape.Circle(1.0), Shape.Rect(w=2.0, h=3.0), Shape.Empty]
for s in shapes:
print(area(s))
print(eval(Expr.Add(Expr.Num(2), Expr.Num(3))), describe(404))
print(shapes[2])3.141592653589793
6.0
0.0
5 not found
Shape.Empty- Build variants as
Enum.Variant(values)orEnum.Variant. In patterns, write the bare variant name (Circle(r)) orShape.Circle(r);_ignores one value (Rect(w, _)). An enum from another module is named through it:json.Value.Null, or justjson.Nullwhen only one of the module's enums has that variant (both in patterns too). - A
matchmust handle every value: on an enum, every variant (or end with_:; missing variants are listed in the error); on an int or str, it needs a_:arm (_: passwhen nothing should happen); on a bool,trueandfalseor_:. - Enum payloads can only be read with
match(nos.radius). Enums without payloads can be compared with==. - Each arm is a block; there is no fallthrough and no
casekeyword, and no guards (ifinside arm bodies instead). Patterns that share a body are joined with|:"cat" | "dog":,Dot | Point:(variants that bind names each need their own arm). x is Patterntests which variantxis:if s is Circle(r):(see Option below).
Option and Result
Two generic enums are always available, without an import:
enum Option[T]: enum Result[T, E]:
Some(value: T) Ok(value: T)
None Err(error: E)Option[T] is a value that may be missing (Tern has no null); Result[T, E] is a result or an error (Tern has no exceptions). Build them bare: Some(3), None, Ok(v), Err("bad"). Test them with match, or with x is Pattern, whose names are bound in the if or while block. And x? gives the value inside Some / Ok, or else returns the None / Err from the function at once (the function must return an Option, or a Result with the same error type).
struct User:
name: str
age: int
fn find_user(us: [User], name: str) Option[User]:
for u in us:
if u.name == name:
return Some(u)
return None
fn parse_age(s: str) Result[int, str]:
n = s.to_int(-1)
if n < 0:
return Err(f"bad age: {s}")
return Ok(n)
fn total_age(texts: [str]) Result[int, str]:
t = 0
for s in texts:
t += parse_age(s)? # an Err returns from total_age right here
return Ok(t)
fn main():
us = [User("ada", 36), User("bob", 25)]
if find_user(us, "bob") is Some(u) and u.age > 20:
print(u.name, u.age)
match find_user(us, "zed"):
Some(u):
print("found", u.name)
None:
print("no zed")
print(total_age(["1", "2"]), total_age(["1", "x"]))
print(parse_age("7").unwrap_or(0), parse_age("?").unwrap_or(0), find_user(us, "q").is_none())
cur: Option[int] = Some(3)
while cur is Some(n): # a loop that runs while there is a value
cur = Some(n - 1) if n > 1 else None
print(cur)bob 25
no zed
Ok(3) Err("bad age: x")
7 0 true
None- Methods:
o.unwrap_or(default),o.unwrap()(a runtime error on None),o.expect(msg),o.is_some(),o.is_none(); on a Result:r.unwrap_or(default),r.unwrap(),r.expect(msg),r.is_ok(),r.is_err(),r.ok()(an Option of the value),r.err(). Noneneeds to know its type: from a typed variable (x: Option[int] = None), a return type, or a parameter. Otherwise writeOption[int].None.x is V(a, b)bindsaandbonly as the condition of anif/while, or on the left ofandthere (if o is Some(v) and v > 0:). Anywhere else it's a plain test:x is None,r is Ok(_). There's nois not: writenot (x is None).isworks on every enum, not just these two. A module can define its ownOption,Some, and so on; its own names win.r.context("loading config")turns anErr(e)intoErr("loading config: " + e)(for aResult[T, str]),r.map_err(f)transforms the error, ando.ok_or(err)turns an Option into a Result.panic(msg)stops with a runtime error on purpose (for "can't happen"), andassert(cond, msg)does whencondis false; the message is built only then. Like any runtime error, apanicin a task is raised again byh.join(), and one in a web handler answers 500. A function ending inpanic(...)needs noreturnafter it.mainmay return aResult[int, str]:Err(msg)printserror: msgand exits with status 1,Ok(n)exits with statusn. So?works inmaintoo:
import fs
fn read_port(path: str) Result[int, str]:
text = fs.try_read(path).context("reading " + path)?
n = text.trim().to_int(-1)
assert(n != 0, "port 0 is reserved")
if n < 0:
return Err(f"not a port: {text.trim()}")
return Ok(n)
fn main() Result[int, str]:
fs.write("/tmp/tern_port.txt", "8080\n")
port = read_port("/tmp/tern_port.txt")?
print("port", port, read_port("/tmp/missing.txt").is_err())
return Ok(0)port 8080 true10. Strings str
Strings are UTF-8 bytes. len, indexing, and slicing count bytes, and s[i] is a one-byte str. For ASCII text this is the same as characters.
fn main():
s = "Hello, World"
print(len(s), s[0], s[7..], s[..5], s[7..9])
print(s.find("o"), s.find("zz"), s.contains("World"), "World" in s)
print(s.starts_with("He"), s.ends_with("!"), s.upper(), s.lower())
print(s.replace("l", "L"), " pad ".trim(), "ab".repeat(3), "ab" * 2)
parts = "a,b,,c".split(",")
print(parts, len(parts), "-".join(parts))
print("42".to_int(0), "x".to_int(-1), "2.5".to_float(0.0), str(42) + str(2.5) + str(true))
print(s.byte(0), chr(72), "b" > "a")
out = ""
for ch in "abc": # one byte at a time
out = ch + out
print(out, f"{s.lower()}: {len(s) * 2}")12 H World Hello Wo
4 -1 true true
true false HELLO, WORLD hello, world
HeLLo, WorLd pad ababab abab
["a", "b", "", "c"] 4 a-b--c
42 -1 2.5 422.5true
72 H true
cba hello, world: 24| Function | Result |
|---|---|
len(s) / s.len() | length in bytes |
s[i], s[a..b], s[a..], s[..b] | one-byte string, substring |
s.find(sub) | index of the first match, or -1 |
s.find_from(sub, start) | the first match at or after start, or -1 |
s.strip_prefix(p), s.strip_suffix(p) | s without p at its start / end (s itself if it isn't there) |
s.contains(sub), sub in s | bool |
s.starts_with(p), s.ends_with(p) | bool |
s.replace(old, new) | every occurrence replaced |
s.trim() | without leading/trailing whitespace |
s.upper(), s.lower() | ASCII case change |
s.split(sep) | [str] (empty pieces kept) |
sep.join(parts) | str (called on the separator, like Python) |
s.to_int(default), s.to_float(default) | parsed number, or default if s isn't one (to_int doesn't allow spaces, and a number outside the int range gives default; to_float allows leading spaces) |
s.byte(i) | the byte at i as an int |
s.reserve(n) | room for n more bytes (s is changed: a mut place), so building a long string by += doesn't grow and copy it on the way (xs.reserve(n) does the same for an array: n more elements) |
s.repeat(n), s * n | repeated |
str(x) | x must be int, float, bool, or str |
chr(n) | one-byte string from a byte value (0 to 255; anything else is a runtime error) |
- Strings are immutable values:
s[0] = "x"is an error; build a new string instead. int("42")is an error (int()converts floats). Use"42".to_int(0).str()of an array or struct is an error;printshows any value, andjson.encodemakes text from any value.- Building a big string in a loop with
+=is fine (it grows in place).
Multi-line and raw strings
fn main():
user = "ada"
sql = """
SELECT id, name
FROM users
WHERE name = $1
"""
page = f"""
<h1>Hello, {user}</h1>
<p class="note">{len(sql)} bytes of SQL</p>
"""
pattern = `^\d{3}-\d{4}$`
body = `{"name": "ada", "tags": ["a", "b"]}`
print(sql)
print(page)
print(pattern, body)SELECT id, name
FROM users
WHERE name = $1
<h1>Hello, ada</h1>
<p class="note">42 bytes of SQL</p>
^\d{3}-\d{4}$ {"name": "ada", "tags": ["a", "b"]}"""strings drop the line break after the opening quotes and before the closing ones, and the indentation their lines share: indent them with the code.`raw`strings keep every character:\dis a backslash and ad, handy forrepatterns, JSON, and Windows paths. They have no escapes, so they can't hold a backtick.
11. Maps {K: V}
Keys are int, str, bool, or structs, enums, tuples, and arrays made of those (so not float or functions): {(int, int): str} for a grid, {Point: bool} for a set of points. Iteration order is insertion order.
fn main():
ages = {"ada": 36, "bob": 25}
ages["cy"] = 41 # insert or overwrite
ages["bob"] += 1
print(ages["ada"], "bob" in ages, ages.get("zed", -1), len(ages))
ages.remove("ada")
print(ages.keys(), ages.values(), ages)
counts: {str: int} = {}
for w in "a b a c a".split(" "):
counts[w] = counts.get(w, 0) + 1
print(counts)
groups: {int: [str]} = {}
for w in ["hi", "yo", "hey"]:
if not (len(w) in groups):
groups[len(w)] = []
groups[len(w)].push(w)
print(groups)36 true -1 3
["bob", "cy"] [26, 41] {"bob": 26, "cy": 41}
{"a": 3, "b": 1, "c": 1}
{2: ["hi", "yo"], 3: ["hey"]}- Reading a missing key with
m[k]is a runtime error; usek in morm.get(k, default). m.remove(k)does nothing ifkis missing.m.keys()andm.values()return arrays.for k, v in m:loops over pairs;for k in m:loops over keys.- Write
not (k in m)with the parentheses; there is nonot inoperator. - A map can't be changed while looping over it. Loop over a copy of its keys instead:
for k in m.keys(): m[k] = 0.
12. Printing
print(a, b, ...) prints its arguments separated by spaces, then a newline. It accepts any value. Floats show a decimal point (2.0) and use the shortest exact form (0.1 + 0.2 prints 0.30000000000000004); very large or small ones use exponent form (1e+19). Strings print raw at the top level and quoted inside arrays, maps, and structs. There is no end= or sep=; build a string instead.
F-strings have no format specs. The fmt module does fixed decimals, padding, and digit grouping:
import fmt
fn main():
price = 1234.5
cents = 1205
print(f"total: {fmt.fixed(price, 2)}, ${fmt.cents(cents)}, {fmt.thousands(1234567)}")
print(fmt.zero_pad(7, 3), "[" + fmt.pad_left("ab", 5, " ") + "]", "[" + fmt.pad_right("ab", 5, ".") + "]")total: 1234.50, $12.05, 1,234,567
007 [ ab] [ab...]13. Functions as values (closures)
struct Button:
label: str
on_click: fn(int) str
fn apply_twice(f: fn(int) int, x: int) int:
return f(f(x))
fn make_adder(k: int) fn(int) int:
return fn(x) x + k # a lambda: `fn(params) expression`
fn main():
k = 10
add = fn(x: int) x + k # captures a copy of k now
k = 99
print(add(5), apply_twice(add, 1), make_adder(3)(4))
b = Button("go", fn(n) f"clicked {n} times")
print(b.on_click(2))
fn fact(n: int) int: # a nested function: a multi-line closure
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(5))15 21 7
clicked 2 times
120- A lambda is
fn(params) expression: one expression, no:and noreturn. For more than one line, define a nestedfnand pass it by name. - Parameter types may be left out when the context says them (a typed parameter, field, or variable, or
map/filter/sort_by). Otherwise write them:fn(x: int) x * 2. - A closure copies the variables it uses when it is created, and can't change them. To accumulate, loop instead, or use a
mutparameter.
14. Values, mut, and the safety rules
Tern has no references, so aliasing bugs and data races are compile errors. The rules and the fix for each:
| You wrote | Error says | Fix |
|---|---|---|
n += 1 where n is a parameter | can't modify parameter n | declare it n: mut int and call with &x, or return the new value |
inc(x) where inc takes mut | write &x | inc(&x) |
swap(&a, &a) or f(&a, a) | would see the same value twice | pass a copy: b = a then f(&a, b) |
use of xs after f(xs) where f takes take | was handed to a take parameter | pass copy(xs) |
xs.push(...) inside for x in xs: | can't modify xs while looping over it | for i in 0..len(xs):, or build a new array |
two parallel tasks write one variable | data race | give each task its own variable, combine after the block |
parallel for writes a shared total | would race | write out[i], then sum out after the loop |
Within one expression, parts run left to right, and a compound assignment evaluates its target once (xs[f()] += 1 calls f once). Reading x and then passing &x to a call further along the same expression (print(x, bump(&x))) is a compile error: save x first.
Copies are lazy (copy-on-write), so b = a is cheap; the copy happens when one of them is written. And when a isn't used again, its value moves instead: ys = xs; ys.push(v) or xs = add(xs, v) never copies, nor does row = grid[i]; row[j] = 0; grid[i] = row. p = ps[i] copies the element: to change the element itself, write ps[i].x = 1 or pass &ps[i] to a mut parameter.
struct Account:
owner: str
balance: int
fn deposit(a: mut Account, amount: int):
a.balance += amount
fn main():
accts = [Account("ada", 10), Account("bob", 0)]
first = accts[0] # a copy
first.balance = 999 # changes only the copy
deposit(&accts[1], 5) # changes the element in the array
accts[0].balance += 1 # so does this
print(accts, first.balance)[Account{owner: "ada", balance: 11}, Account{owner: "bob", balance: 5}] 999Copying ordinary data (numbers, strings, arrays, maps, structs, tuples, enums) makes an independent value. A few types are handles to something outside the value: a channel, a task.shared, a task, and resources such as an open file, a database, or a connection. Copying a handle gives a second name for the same thing, so a change made through either copy is seen through both:
import task
fn main():
a = task.shared(0)
b = a # the same shared value, not a copy of it
fn bump(n: mut int):
n += 1
b.update(bump)
print(a.get(), b.get())1 115. Parallelism
fn fib(n: int) int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fn main():
c = 0
parallel: # each line is a task; waits for all of them
a = fib(20)
b = fib(21)
do: # `do:` groups several lines into one task
c = fib(5)
c += 1
print(a, b, c)
xs = [0] * 8
parallel for i in 0..len(xs): # iterations run across all cores
xs[i] = i * i # iteration i may only write xs[i]
total = 0
for x in xs:
total += x
print(xs, total)6765 10946 6
[0, 1, 4, 9, 16, 25, 36, 49] 140- A variable created by a one-line task is visible after the block. Variables created inside a
do:group are local to it; create them before the block to use them after. - The compiler rejects any task that writes a variable another task reads or writes. One exception: tasks may write different elements of an array written with literal indexes (
xs[0] = a()in one task,xs[1] = b()in another), if they don't touch the array otherwise. parallelneeds no threads, locks, or channels. For long-running concurrent work (tasks that outlive a block, channels between them, shared state behind a lock), use thetaskmodule; its functions are listed at the top oflibrary/std/task.tn.
Tasks (import task) are green threads, like Go's goroutines: code in a task looks blocking, but only the task waits (ch.recv(), h.join(), time.sleep, socket reads), and its core runs other tasks meanwhile. Copying a chan, task, or shared value shares it. Values sent through a channel are copied (cheaply: copy-on-write).
import task
fn fetch(id: int) str:
task.sleep(10) # parks this task only; others keep running
return f"page {id}"
fn produce(ch: chan[int], n: int):
for i in 1..n + 1:
ch.send(i * i)
ch.close() # ends the receiver's `for` loop
fn main():
hs: [task[str]] = []
for id in 0..3:
hs.push(task.spawn(fn() fetch(id))) # all three run at once
for h in hs:
print(h.join()) # waits; an error in the task is raised here
ch: chan[int] = task.channel(8) # holds up to 8 values (0: unbounded)
task.spawn(fn() produce(ch, 5))
total = 0
for x in ch: # until closed and empty
total += x
print(total)
hits = task.shared(0) # shared[int]: many tasks, one value
fn bump(n: mut int):
n += 1
ws: [task[void]] = []
for i in 0..100:
ws.push(task.spawn(fn() hits.update(bump))) # one update at a time
for w in ws:
w.join()
print(hits.get())page 0
page 1
page 2
55
100task.spawntakes a function with no parameters; wrap a call in a lambda to pass arguments. The task gets copies of what the lambda uses, as with any closure.- A channel needs its type written:
ch: chan[int] = task.channel(8).ch.recv()on a closed, empty channel is a runtime error;for x in ch:andch.next(&x)stop instead. - A runtime error in a task ends that task;
h.join()raises it again. Other tasks keep running. The program ends whenmainreturns; if a task failed and nobody joined it, its error is printed and the program exits with status 2 (tasks spawned inside web handlers don't count).h.cancel()on a task that already failed discards its error. task.local_set(key, value),task.local_get(key) str(""if unset) andtask.local_clear()keep strings that belong to the running task (a request id, tracing context). A spawned task starts with a copy of its spawner's.task.id() intnames the running task (0 outside tasks).os.on_error(f)callsf(os.ErrorReport)for every runtime error from then on, caught ones too (a failed task, a web handler's500): for error trackers. See os.- Code inside
parallel:may use channels too; there it waits like a thread.
Groups of tasks: task.all, task.try_all (Go's errgroup)
task.all(fs) runs every function in fs ([fn() T]) at once and returns their results in order; a runtime error in one is raised in the caller. task.try_all(fs) does the same for functions that return Result[T, E]: Ok with every value in order, or the first Err to arrive, after cancelling the tasks still running. task.try_all_limit(fs, n) runs at most n at a time (Go's SetLimit), for "fetch these 500 URLs, 8 at once".
import task
fn fetch(id: int) Result[str, str]:
if id == 13:
return Err(f"page {id}: not found")
return Ok(f"page {id}")
fn main():
print(task.all([fn() 2 + 2, fn() 3 * 3]))
good: [fn() Result[str, str]] = []
for id in 0..4:
good.push(fn() fetch(id))
print(task.try_all_limit(good, 2))
bad: [fn() Result[str, str]] = [fn() fetch(1), fn() fetch(13)]
print(task.try_all(bad)) # the first Err; any still running are cancelled[4, 9]
Ok(["page 0", "page 1", "page 2", "page 3"])
Err("page 13: not found")Counters and caches: task.atomic, task.shared_map
shared[T] changes any value safely, but each get and update takes a lock that tasks wait for in turn: fine for occasional changes, slow for a counter or cache that every request touches. For those two cases there are faster handles (copies share one, like channels):
task.atomic(v): anintchanged with atomic instructions.a.load(),a.store(v),a.add(n)(returns the new value),a.cas(old, new)(storesnewif the value wasold).task.shared_map(): astr -> strmap any task can use at once (m.put(k, v),m.get_or(k, default),m.has(k),m.remove(k),m.count()), plus anintper key for counting (m.add_int(k, n),m.get_int(k)).
Under contention they are hundreds of times faster than shared[T]. Copies share the same one (like a channel), and the last copy gone frees it, entries and all: a cache can start again with a fresh map.
import task
fn visit(hits: task.Atomic, pages: task.SharedMap, path: str) int:
pages.add_int(path, 1)
return hits.add(1)
fn main():
hits = task.atomic(0)
pages = task.shared_map()
pages.put("/", "home")
hs: [task[int]] = []
for i in 0..100:
p = "/" if i % 2 == 0 else "/about"
hs.push(task.spawn(fn() visit(hits, pages, p)))
for h in hs:
h.join()
print(hits.load(), pages.get_int("/"), pages.get_int("/about"), pages.get_or("/", "?"))100 50 50 home16. Standard library
Import a module with import name, then call name.fn(...). Or from name import fn1, Type.
| Module | Functions and types | ||||
|---|---|---|---|---|---|
fmt | fixed(x: float, digits: int) str ("3.14"), cents(n: int) str (1205 → "12.05"), zero_pad(n, width) str, pad_left(s, width, fill) str, pad_right(s, width, fill) str, thousands(n) str ("1,234,567") | ||||
math | sqrt floor ceil round log exp sin cos tan (x: float) float, pow(x: float, y: float) float, pi() float | ||||
random | int(lo: int, hi: int) int (inclusive), float() float in [0, 1) | ||||
time | now() float (seconds since 1970), now_ms() int, sleep(ms), mono_ns() int, mono_ms() int; rfc3339(t) str, rfc3339_local(t) str, parse_rfc3339(s) float; format(t, layout) str / format_local (strftime + %L ms, %f us); parse(s, layout) float / parse_local; utc(t) Date, local(t) Date (year month day hour minute second nano weekday yday offset); date(y, mo, d, h, mi, s) float (UTC; out-of-range values carry); offset(t) int; duration(secs) str ("1h2m3.5s"), parse_duration(s) float; error() str (a failed parse returns 0.0); Result forms: try_parse_rfc3339(s), try_parse(s, layout), try_parse_duration(s) (Result[float, str]) | ||||
os | args() [str] (args()[0] is the program), env(name: str, default: str) str, exit(code: int), eprint(s), read_line() str, read_all() str, run(cmd, args) Output / run_input(cmd, args, input) (status out err), spawn(cmd, args) Process / spawn_with(cmd, args, ProcOpts{dir env out err}): p.ok() p.write(s) p.close_input() p.out_line() p.out_all() p.wait() p.wait_ms(ms) p.kill(sig) p.pid(); cwd() chdir(dir) setenv(k, v) error(); wait_signal() str (waits, task-friendly, for SIGINT/SIGTERM/SIGHUP/SIGUSR1/SIGUSR2), flush(), cpu_count() int, load_avg() float (-1.0 where unavailable), getpid() int, executable() str (this program's absolute path); on_error(f: fn(ErrorReport)), last_error_report() ErrorReport (message, file, line, function, frames, build id, task: for error trackers), at_exit(f: fn()) (f runs when the program ends, the last added first) | ||||
fs | read(path) str ("" if unreadable), write(path, text) bool, append(path, text) bool, exists(path) bool, remove(path) bool, list(dir) [str], list_marked(dir) [str] (directories end in /), mkdir(path) bool, chmod(path, mode) bool (0o600), rename(a, b) bool, stat(path) Info (exists is_dir size modified), walk(dir) [str], copy(a, b) bool, remove_all(path) bool, temp_dir(prefix) str, error() str; files: open(path) File / create / open_append, f.ok(), f.read_line() str, f.read_some(max) str, f.put(s) bool, f.flush() bool, f.close() bool; Result forms: try_read(path) Result[str, str], try_write, try_append, try_list, try_stat, try_open | ||||
log | leveled structured logs on stderr: debug/info/warn/error(msg), debug_with/info_with/warn_with/error_with(msg, fields: {str: str}); set_level(name) bool ("debug" "info" "warn" "error" "off"), set_format(name) bool ("logfmt" "json" "text"); env TERN_LOG_LEVEL, TERN_LOG_FORMAT; recent(n) [Record], keep(level) | ||||
json | encode(any value) str, decode(text: str, out: mut T) bool (all-or-nothing: on false, out is unchanged); an Option[T] field is null or the value (missing: None); an enum is "Name" or {"Name": payload} (names decode loosely: "in_progress" is InProgress), schema[T]() str (T's JSON Schema, made while compiling); parse(text) Result[Value, str] for JSON of unknown shape: v.field(k), v.at(i) (Null when missing, so they chain), v.str_or(d), int_or, float_or, bool_or, v.fields(), v.elems(), v.size(), v.to_map() ({str: Value}, for many lookups in a big object), dump(v) str; Value is Null, Bool(b), Num(x, text), Str(s), Arr(items), Obj(keys, vals) | ||||
sqlite | SQLite (package). open(path) sqlite.Db; d.exec(sql, params: [str]) int (last insert id); d.exec_count(sql, params) int (rows changed); d.query(sql, params) [{str: str}]; d.query_into(sql, params, &structs_or_struct) int (rows read, through std sql); d.exec_later(sql, params) + d.flush() (writes committed in the background); sqlite.NULL (a NULL parameter); d.run_script(sql) Result[int, str] (several statements; errors returned); d.describe(sql) Result[Statement, str] (params, columns: name decl_type table column not_null); query_into fields may be Option[T] (NULL is None) | ||||
task | spawn(f: fn() T) task[T]; h.join() T, h.done() bool, h.cancel(); channel(n) chan[T] (give the variable its type; n = 0: unbounded); ch.send(v), ch.recv() T, for x in ch:, ch.next(&x) bool, ch.try_recv(&x) bool, ch.recv_timeout(&x, ms) bool, ch.close(), len(ch); select(chans: [chan[T]], &x, ms) int (index of the channel x came from; -1 timed out, -2 all closed); shared(v) shared[T], s.get() T, s.set(v), s.update(f: fn(mut T) R) R; sleep(ms), yield_now(); blocking(f: fn() T) T (runs f on a pool thread: for blocking work like fsync or SQLite); local_set(key, value), local_get(key) str, local_clear() (the running task's strings; spawned tasks inherit a copy); id() int; thread_slot() int (the running thread's scheduler slot: for per-thread caches); workers() int (the scheduler's threads: how many parallel iterations run at once) | ||||
net | TCP for tasks. listen(port) Listener, listen_on(host, port) Listener, l.accept() Conn, l.port() int, l.stop(); connect(host, port) Conn (c.ok(), else net.error() str); c.read(max) str, c.read_line() str (with its "\n"; "" at the end), c.read_exact(n) str, c.write(s) bool, c.close(), c.peer() str; c.pending() bool (a read wouldn't wait), c.refill(&buf, used, max) int (drop buf[..used], read up to max bytes onto the end: a protocol parser's buffer without copies), c.starttls(host, verify) bool (needs import tls); connect resolves names off the worker (cached, TERN_DNS_TTL=30s, at most 16k names; TERN_DNS_SERVERS=1.1.1.1,8.8.8.8 asks those servers over UDP from the task itself, within the request's deadline, keeping localhost, .local and /etc/hosts names for the system); dial(host, port) Result[Conn, str] | ||||
roost | axum-style framework on tasks. router() Router; r.get/post/put/delete/patch(path, h), r.route(method, path, h), r.any, r.nest(prefix, sub), r.fallback(h), r.ws(path, fn(req, ws)), r.sse(path, fn(req, out)), r.layer(mw), r.wrap(mw); serve(r, port), start(r, port) Server; handlers fn(roost.Request) roost.Response; req.param/param_int/query/header/cookie/form/json(&v); text html json status not_found redirect; middleware logger cors request_id timeout bearer_auth auth gzip; client get(url) post(url, body, type) fetch(ClientRequest); serve_tls(r, port, cert, key); req.peer(), req.client_ip(), roost.trust_proxies(n), rate_limit(per_second, burst), rate_limit_by(per_second, burst, key), r.files(prefix, dir), file_response(path, req), req.parts() / req.part(name), r.post_stream / r.put_stream with req.read_body(max), save_body(path), next_part(&p), read_part(max), save_part(path), r.max_connections(n); r.metrics(path) (Prometheus), metric_add/metric_set(name, labels, v); validation check() with required/min_len/max_len/between/one_of/email/fail/valid/problems; SIGINT/SIGTERM make serve drain in-flight requests (TERN_WEB_DRAIN_SEC=10) and return. See library/roost/roost.tn; try_get(url), try_fetch(req) (Result[Response, str]); req.matched_route() (the route pattern, once roost.track_routes() was called) | ||||
crypto | sha256(s) str, sha512(s) str (raw bytes), hmac_sha256(key, msg) str, hmac_sha512, sha1, hmac_sha1 (for TOTP); hash_password(pw) str (Argon2id PHC string), verify_password(pw, hash) bool; argon2id(pw, salt, t, m_kib, p, len) str, pbkdf2_sha256(pw, salt, iters, len) str; random_bytes(n) str, random_int(lo, hi) int (OS secure random); equal(a, b) bool (constant time); hex(s), unhex(s), base64(s), base64_decode(s), base64url(s), base64url_decode(s); uuid4() str, uuid7() str; error() str (why a decode failed); Result forms: try_unhex(s), try_base64_decode(s), try_base64url_decode(s); seal(key, plaintext) str / unseal(key, sealed) str / try_unseal (ChaCha20-Poly1305, 32-byte key), chacha20_poly1305(key, nonce, aad, pt) / chacha20_poly1305_open(...) | ||||
compress | zstd and libdeflate, built in (linked only when imported). zstd(data, level) str (one frame; levels 1..19, 3 is the default, up to 22 or negative for faster; clamped), unzstd(data) Result[str, str] (every frame in data, with or without its size in the header), unzstd_max(data, max_out) Result[str, str] (Err past max_out bytes: for untrusted input), zstd_bound(n) int, error() str. Any bytes (NULs included); up to 4GB each way; gzip(data, level) str (levels 1..12, 6 default, 0 stores), gunzip(data) (every member) / gunzip_max(data, max_out) (Result[str, str]), zlib/unzlib/unzlib_max, deflate/inflate/inflate_max (raw) | ||||
re | regular expressions, linear time (RE2 syntax: no backreferences or lookaround). compile(pattern) Result[Regex, str], must(pattern) Regex; r.test(s) bool, r.full(s) bool, r.search(s) Option[Match], r.search_at(s, at), r.find_all(s) [Match], r.count(s) int, r.replace_all(s, repl) str ($1 ${name} $0 $$), r.replace_first(s, repl), r.replace_with(s, fn(Match) str), r.split_all(s) [str], r.names() [str]; escape(s) str, error() str; literals(pattern, min) Result[[[str]], str] (literals every match contains, for searching an index first). Match: start end text groups starts named, m.group(name) str. Patterns are strings: "\\d+" | ||||
simd | 16 bytes at once (NEON, SSE, wasm SIMD): load(s, i) bytes16, load_upto(s, i) (zeros past the end), of(t), splat(b), to_str(v); `& | ^ ~ + - << >> ==lane by lane;eq(a, b),lt,le,min,max,lookup(t, i)(a 16-entry table per lane),bits(v) int,first_lane(v) int,any(v) bool,lane(v, k) int,first(m) int`. See simd | |||
flag | command-line flags into a struct (a field per flag: min_len is --min-len; the struct's values are the defaults): cli(name, about) Cli, c.flag(field, short, help), c.env(field, var), c.require(field), c.args(text), c.stop_at_args(), c.exit_on_help; parse(c, &out) Result[[str], str] (os.args(); returns the positionals), parse_from(c, args, &out), usage(c, out) str. Fields: int, float, str, bool (--x, --no-x, -abc), an enum (any case), [T] (repeatable), Option[T]; --help prints the usage and exits 0 | ||||
term | is_tty(), stderr_is_tty(), stdin_is_tty(), width(), height(); color() bool, set_color(on); red green yellow blue magenta cyan gray bold dim italic underline (s) str (plain text unless stdout is a terminal, NO_COLOR unset; FORCE_COLOR=1); strip_ansi(s), display_width(s), pad(s, width), table(rows: [[str]]) str, progress(done, total, label) (stderr, only on a terminal), clear_line(), secret(prompt) str (no echo), read_line(prompt) str (line editing and history on a terminal) | ||||
heap | min or max heap, T int/float/str: min_heap[T](), max_heap[T](), heap_of(xs, max) Heap[T] (O(n)), h.push(x), h.pop() Option[T], h.peek() Option[T], h.len(), h.is_empty(), h.drain() [T] | ||||
pqueue | priority queue of any T by a priority P (int/float/str): queue[P, T]() (lowest first), queue_max[P, T](), q.push(priority, value), q.pop() Option[T], q.peek(), q.peek_priority() Option[P], q.len(), q.is_empty() | ||||
deque | ring-buffer deque: new[T](), of(xs), d.push_back(x), d.push_front(x), d.pop_back() / d.pop_front() (Option[T]), d.front(), d.back(), d.at(i) T, d.put(i, x), d.len(), d.is_empty(), d.to_array(), d.clear() | ||||
bitset | new(n) Bitset (grows), b.set(i), b.unset(i), b.toggle(i), b.has(i) bool, b.count() (popcount), b.ones() [int], b.size(), b.union_with(o), b.intersect_with(o), b.subtract(o) | ||||
url | URLs by Go's net/url rules: parse(text) Result[Url, str], parts as methods (u.scheme() user() password() host() port() path() raw_query() fragment() opaque(), plus escaped_path() escaped_fragment() raw_path() raw_fragment() force_query() omit_host()), setters (u.set_path(p), set_host, set_port, set_raw_query, set_fragment, set_scheme, set_user, set_password), u.parts() Parts / build(p: Parts) Url for several at once, format(u) str, resolve(base, ref: Url) Url, join(base, ref: str) Result[str, str], u.host_port(), u.request_uri(), u.query() Query; parse_query(raw) Result[Query, str], new_query(), q.get(k) str, q.get_all(k) [str], q.has(k), q.add(k, v), q.set(k, v), q.remove(k), encode_query(q) str, query_string(pairs: {str: str}) str; query_escape/query_unescape, path_escape/path_unescape (unescapes return Result) | ||||
binary | Binary formats, bytes in a str: writer() Writer with w.put_u8/u16be/u16le/u32be/u32le/u64be/u64le(v), put_f32be/f32le/f64be/f64le(v), put_uvarint(v), put_varint(v) (zigzag), put_bytes(s), len(), bytes() str, patch_u32be(i, v); reader(data) Reader with r.read_u8() ... read_u64le(), read_i8/i16be/i16le/i32be/i32le(), read_f32be() ... read_f64le(), read_uvarint(), read_varint(), read_bytes(n), skip(n), has(n) bool, left() int, ok() bool, error() str (a read that doesn't fit gives 0 and every later one too; the first problem is kept); at an offset: u8(s, i) ... u64le(s, i), i16be ... i32le, f32be ... f64le, set_u8(&s, i, v) ... set_f64le (past the end: a runtime error); uvarint_len(v), varint_len(v) | ||||
toml | TOML 1.0: decode(text, &out) Result[int, str] (fills a struct by field name, like json.decode), parse(text) Result[json.Value, str], encode(value) Result[str, str] (a struct or map), dump(v: json.Value) Result[str, str]; dates and times are RFC 3339 strings; errors name the line | ||||
path | paths as text, /-separated (Go's path rules): join(a, b) str, join_all(parts) str, resolve(base, p) str (an absolute p wins), clean(p) str, dir(p) str, base(p) str, split(p) (str, str), ext(p) str (".gz"; none for .bashrc), stem(p) str, with_ext(p, ext) str, parts(p) [str], is_abs(p) bool, abs(p) str, rel(base, target) Result[str, str], matches(pattern, name) bool (* ? [a-z] [!a-z] \x), glob(pattern) [str] (sorted; ** is any number of directories; hidden names only for a piece starting with .) | ||||
csv | RFC 4180 CSV, like Go's encoding/csv. parse(text) (Result[[[str]], str]), records(text) (Result[[{str: str}], str], the first row is the header), reader(text) Reader + r.next(&row) bool / r.err / r.line (one record at a time), format(rows) str, format_row(row) str; options() Options (sep comment fields lazy_quotes trim_leading_space crlf), tsv(), and parse_with / records_with / reader_with / format_with / format_row_with taking them; errors name the line and column | ||||
sql | What database drivers share (Go's database/sql): decode_rows(raw, &out) int fills a struct or [struct] from a driver's rows (columns to fields by name; int, float, bool, str, label enums, arrays, JSON fields, Options; -1 and decode_error() str when a value doesn't fit), rows(columns) Rows with r.row(n), put_int/put_float/put_bool/put_text/put_null, bytes() builds them, rows_from(head) starts one from an earlier header; row_field(&out, name), row_id(&out) and set_int/set_float/set_text/set_null(&out, field, v) fill the first row of a struct from values in hand; TEXT INT FLOAT BOOL UINT TAGGED name the formats (std/sql.md) | ||||
html | escaping and templates that escape by default. escape(s) str; render(template, data_json) str, render_file(path, data_json) str (parsed once, reloaded on change; {{> file}} includes); error() str; Result forms try_render(template, data_json), try_render_file(path, data_json) (Result[str, str]). Tags: {{x}} {{a.b}} {{.}} escaped, {{{x}}} raw, {{json x}}, {{#each xs}}..{{/each}} with {{@index}}, {{#if x}}..{{else}}..{{/if}}, {{#unless x}}, {{! comment}}; data is json.encode(value) | ||||
tls | TLS (aws-lc, which tern builds once per target and links only when imported; TERN_TLS=system uses the system's OpenSSL); importing it also enables https:// in http.get/fetch and s.listen_tls(...) / roost.serve_tls(r, port, cert, key) / roost.start_tls(r, host, port, cert, key) Server. connect(host, port) net.Conn (verified; c.ok(), else tls.error()), connect_insecure(host, port), upgrade(c, host) bool (STARTTLS), server(cert, key) Server, accept(c, s) bool, version(c) str, trust(ca_file) bool; dial(host, port) Result[net.Conn, str]; ALPN: set_alpn(s, protocols: [str]) (server, preferred first), connect_alpn(host, port, protocols) net.Conn, alpn(c) str (the protocol agreed, e.g. "h2") | ||||
testing | eq_int eq_float eq_str eq_bool (got, want), eq_ints eq_strs, near(got, want, tol), is_true(cond, what), is_false, includes(s, sub), fail(msg): checks for tern test (cli.md) | ||||
queue | client for the ternq broker (examples/queue/): connect(host, port) Client, connect_many(["h1:7070,h2:7071"]) (shards; each with failover addresses), connect_auth(addrs, token), c.publish(q, body) bool, c.publish_batch, c.subscribe(q, group, prefetch) Sub, s.next(&m) bool, c.ack(m), c.nack(m), c.fetch(s, max), c.fetch_wait(s, max, ms), c.stats(q). See library/queue/queue.tn | ||||
openapi | OpenAPI 3.1 from web routes (package). new(title, version, description) Spec, bearer(&s, desc), server(&s, url); op(method, path, summary) Op then o.returns[T](), o.accepts[T](), o.returns_text(), o.status(n), o.query(name, type, desc), o.describe(t), o.tag(t), o.id(t), o.fails(code, desc), o.public(); add(&s, &r, o, handler) registers the route too, record(&s, o) only documents; document(s) str, typescript(s) str (types + createClient), serve(s, &r) (/openapi.json, /docs) | ||||
pg | PostgreSQL. pool(url, size) Pool, connect(url) Pool; p.ok(), pg.error() str; p.exec(sql, params: [str]) int (rows; -1 on error); p.query(sql, params) [{str: str}]; p.query_json(sql, params) str / p.query_row_json(...) (typed JSON for json.decode(…, &structs)); p.begin(), p.commit(), p.rollback() (transactions bound to the task); p.stats() PoolStats (size open idle in_use waiting waits wait_ms timeouts opened closed), p.prune(), p.close(); URL &pool_timeout=30s&max_lifetime=1h&max_idle=30m&statement_cache=off&application_name=x. Params are $1, $2; ?sslmode=require needs import tls; fetch[T](sql, params) Result[[T], str], fetch_one[T](sql, params) Result[Option[T], str], pg.NULL (a NULL parameter), array_int(xs) / array_float / array_bool / array_str (a list as one parameter: = ANY($1)), rows fill [int] [str] ... fields from PostgreSQL arrays, run(sql, params) Result[int, str], run_script(sql) Result[int, str] (several statements, simple protocol), describe(sql) Result[Statement, str] (param type names; columns: name type_name type_oid kind base_type table not_null); Option fields decode NULL as None | ||||
redis | Redis client (package). connect(url) Client / pool(url, size); c.ok(), redis.error(); c.get_str(k) str, c.set_str(k, v) bool, c.set_ex(k, v, secs), c.set_nx(k, v), c.del(k) int, c.exists(k) bool, c.incr(k) int, c.incr_by(k, n), c.expire(k, secs), c.ttl(k), c.mget(keys) [str], c.publish(ch, msg) int; c.cmd(args: [str]) Reply (kind text num items), c.pipeline([[str]]) [Reply]; c.subscribe(channels) Subscription, sub.next(&m) bool, sub.unsubscribe(); c.close(); c.try_get(k) Result[Option[str], str], c.try_cmd(args) Result[Reply, str] | ||||
auth | JWT HS256 and signed-cookie sessions (package). jwt_for(subject, secret, ttl) str, jwt_encode(payload_json, secret) str, jwt_verify(token, secret) Token (ok payload subject error), require_jwt(secret) middleware (ctx "jwt.sub"); session(req, secret) {str: str}, set_session(&res, secret, data), set_session_for(&res, secret, data, max_age, attrs), clear_session(&res); verify(token, secret) Result[Token, str] | ||||
migrate | schema migrations (package) for PostgreSQL and SQLite from VERSION_NAME.sql files (-- migrate:up, -- migrate:down, -- migrate:no-transaction). postgres(p) Target, sqlite(d) Target, open(url) Result[Target, str]; t.up(dir), t.down(dir, n) (Result[[Migration], str]: what ran), t.status(dir) Result[[Status], str] (state: applied pending changed missing); load(dir), parse(version, name, text), t.apply(ms), t.rollback(ms, n), t.report(ms); create(dir, name) Result[str, str]; cli(dir, url) Result[int, str] (up, down [N], status, new NAME); label(m), label_of(s), split_statements(sql) [str]. Each migration runs in a transaction with its bookkeeping; runs are serialized (pg advisory lock); an edited applied migration is an error | ||||
sqlgen | typed functions from SQL (package), like sqlc: -- name: get_user :one (or :many, :exec) above each query, @name parameters (@x:int to give a type, @x? for an Option that may be NULL), "col!" / "col?" / "n: int" column notes. cli(url) Result[int, str] (QUERIES.sql ... -o OUT.tn [--migrations DIR] [--check]), generate(dbase, files) Result[str, str] with postgres(p) / sqlite(d); writes a Row struct per query and `fn q(pool: pg.Pool, ...) Result[Option[Row] | [Row] | int, str](SQLite:fn q(conn: sqlite.Db, ...) Option[Row] | [Row] | int); nullable columns areOption` |
grpc | gRPC over HTTP/2, over TLS (ALPN h2) or cleartext (h2c) (package): unary calls, HPACK with Huffman, many streams per connection. start(host, port, handler: fn(Call) Reply, options()) Server, start_tls(host, port, handler, options(), cert, key) Server, serve(port, handler), port(s), wait(s), stop(s, drain_ms) (GOAWAY, then drains); Call has method ("/pkg.Service/Method"), metadata {str: str}, message (the request's bytes), encoding ("gzip" when compressed; accepted ones in Options.encodings); reply with ok(body) or fail(status, msg) (grpc.OK ... grpc.UNAUTHENTICATED); Options: max_message max_frame max_header_list max_streams stream_window conn_window header_table encodings; client call(host, port, method, metadata, message) Reply (h2c), call_tls(...) (TLS, verified). Imports tls. No streaming RPCs | ||||
sentry | error reporting to Sentry (package). options() Options (release environment server_name sample_rate max_queue breadcrumbs timeout_ms scrub), init(dsn, o) Client; c.ok(), c.error(); c.capture_message(msg, level) str, c.capture_error(r: os.ErrorReport) str, c.capture_result(r: Result[T, str]) str (the event id); install(c) (every runtime error, via os.on_error), middleware(c) (request data and route); set_tag(k, v), set_extra(k, v), set_user(id, email), clear_scope() (task-local); c.flush(ms) bool, c.close(), c.sent(), c.dropped() |
Errors in the Result forms read <module>: <what>: <reason> (fs: read /tmp/x: no such file or directory). | http | serve(port, handler) / serve(port, handler, app) / serve(port, handler, &app); Request{method, path, raw_query, head, body, params, ctx, conn}; Response{status, content_type, body, headers, upgrade}; text(s) html(s) json(s) status(code, s) not_found() no_content() redirect(url) with_status(res, code); req.query(name) req.queries() req.header(name) req.headers() req.cookie(name) req.form(name) req.parts() req.param(name) req.json(&v); res.set_header(name, v) res.set_cookie(name, v) res.get_header(name); new_request(method, target, body) Request, req.add_header(name, v) (tests); match(path, "/users/{id}", ¶ms) bool; engine: new_server() Server, s.add_route(method, pattern, h, ws, sse, stream), s.listen(host, port, fallback) / s.listen_tls(..., cert, key), s.wait(), s.stop(), ws_upgrade, sse_open, static_file(dir, rel, req); client: get(url) post(url, body, type) fetch(request(method, url)), fetch_max(cr, max_body) (fails past max_body bytes; Connection: close in cr.headers keeps it out of the pool); idle pooled connections close after TERN_HTTP_POOL_IDLE=30 s, at most TERN_HTTP_POOL_MAX=512 wait in all, try_get, try_fetch, failed(res); middleware helpers: client_ip limiter request_id gzip metrics_text |
Builtins (no import): print len push pop copy abs min max sqrt float int str chr and the string, map, and array functions in §8 to §11. Two more for web code: json_quote(s) str (s as a JSON string literal, quotes and escapes included: json_quote("a\"b") is "a\"b" with the quotes) and url_decode(s) str (%20 and + become spaces). min/max take two numbers of the same type. abs takes an int or a float; sqrt takes a float (sqrt(float(n))).
import math
import json
import fs
struct Config:
name: str
workers: int
tags: [str]
fn main():
print(math.sqrt(16.0), math.floor(2.7), math.pow(2.0, 10.0), min(3, 4), max(1.5, 0.5))
c = Config("svc", 4, ["a"])
text = json.encode(c)
print(text)
back = Config("", 0, [])
if json.decode(text, &back):
print(back.workers)
bad = Config("keep", 1, [])
print(json.decode("{not json", &bad), bad.name)
path = "/tmp/tern_doc_test.txt"
fs.write(path, "line1\nline2\n")
lines = fs.read(path).trim().split("\n")
print(lines, fs.exists(path))
fs.remove(path)4.0 2.0 1024.0 3 1.5
{"name":"svc","workers":4,"tags":["a"]}
4
false keep
["line1", "line2"] trueA web server with a database (build with tern build app.tn -o app):
import http
import sqlite
import json
struct Todo:
id: int
title: str
fn handle(req: http.Request, d: sqlite.Db) http.Response:
params: {str: str} = {}
if req.method == "GET" and req.path == "/todos":
todos: [Todo] = []
d.query_into("SELECT id, title FROM todos", [], &todos)
return http.json(json.encode(todos))
if req.method == "POST" and http.match(req.path, "/todos/{title}", ¶ms):
id = d.exec("INSERT INTO todos (title) VALUES (?)", [params["title"]])
return http.json(json.encode(Todo(id, params["title"])))
return http.not_found()
fn main():
d = sqlite.open("todos.db")
d.exec("CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, title TEXT)", [])
http.serve(8080, handle, d)- The handler is
fn(req: http.Request) http.Response, or takes a second parameterapp(shared read-only by all threads), orapp: mut Appwithhttp.serve(port, handle, &app)(requests that change it run one at a time). - A runtime error inside a handler becomes a 500 response; the server keeps running.
- SQL parameters are always strings (
[str(id)]) and are bound safely. - Each server thread opens its own connection, so
sqlite.open(":memory:")gives every thread a separate, empty database. Servers need a file path. - A
sqlite.Dbis a handle, so a read-onlyd: sqlite.Dbparameter can still runINSERTs: the database is outside the program's values. "Read-only" is about Tern values only.
17. Modules and packages
Every .tn file is a module. import models looks in the standard library and the first-party packages (roost, queue, pg), then for models.tn or models/ (a directory of .tn files forming one package) next to the main file, then in deps/. Use models.User, models.load(...), or from models import User, load. Names starting with _ are private. Third-party packages are git repositories: list them in a tern.mod file next to your program and run tern get, which vendors them into deps/, where import finds them (see cli.md).
18. Other targets and C
--target wasm | ios | ios-sim | android;build --libmakes a C library with a header fromexport fnfunctions;--sharedmakes a.so/.dylib. On wasm,--libalso writes a JavaScript loader. Wasm runsparallelsequentially;sqliteandhttparen't available there.- Calling C: an
extern "header.h":block offnsignatures (see README.md, "Calling C"). Onlyint float bool str ptr [int] [float]and functions of those cross the boundary.ptris an opaque C pointer;nullis the null pointer (p: ptr = null) andp.is_null()tests for it.nullis only aptr: other types have no null. Astrresult stops at the first NUL byte; for binary data, return aptrand a length and copy it withstring_at(p, n) str(see guides/c-interop.md).
19. What Tern does not have (and what to write instead)
| From another language | In Tern |
|---|---|
def f(x):, func, function, fun | fn f(x: int) int: |
class, methods, self, impl, interfaces, traits | struct + functions taking it first; x.f() calls f(x) |
let x, var x, const X, x := 1, auto | x = 1 |
| global variables | const MAX_USERS = 100 for fixed values; const CACHE = task.shared_map() for a program-wide cache; pass a struct for other state that changes |
None, null, nil, Option<T>, T? | Option[T]: Some(x) or None (§9) |
exceptions, try/except, throw | return a Result[T, E]: Ok(v) or Err(e); r? passes an Err up, r.context("...") adds where (§9) |
panic!, assert, raise RuntimeError | panic(msg), assert(cond, msg): a runtime error (§9) |
if let Some(v) = x, x is not None | if x is Some(v):, not (x is None) |
generics, templates, <T> | fn first[T](xs: [T]) T, struct Pair[A, B] (§7, Generics) |
any, interface{}, object | a type parameter, an enum of the cases, or a function value |
True, False | true, false |
&&, ||, ! | and, or, not |
x++, x-- | x += 1, x -= 1 |
c ? a : b | a if c else b |
//, ** | / on ints; math.pow(float, float) |
range(n), range(a, b), enumerate(xs) | 0..n, a..b, for i, x in xs: |
xs.append(v), xs.length, xs.size() | xs.push(v), len(xs) |
xs.sort(), xs.reverse() (in place) | xs = xs.sorted(), xs = xs.reversed() (sort_by(fn(x) key) for another order) |
sum(xs), zip(xs, ys) | sum(xs) works; for zip, for i in 0..len(xs): and read xs[i], ys[i] |
[f(x) for x in xs if p(x)] | xs.filter(fn(x) p(x)).map(fn(x) f(x)) |
lambda x: x + 1, x => x + 1, |x| x + 1 | fn(x) x + 1 |
int("42"), parseInt, strconv.Atoi | "42".to_int(0) |
str(xs), toString() of a struct | json.encode(xs), or print(xs) |
f"{x:.2f}", % formatting, .format() | f"{x}"; f"{fmt.fixed(x, 2)}", fmt.zero_pad, fmt.pad_left |
'single quotes' | "double quotes"; """...""" over several lines; `raw` with no escapes |
else if, switch, case | elif, match |
do { } while, loop | while true: + break |
print(x, end="") | build the whole line in a string, then print it |
import std.math, use, #include | import math |
20. Builtin names
These are the builtin functions:
print len push pop chr copy float int sqrt abs sum min max str join split find contains
starts_with ends_with replace trim upper lower to_int to_float byte repeat get remove
keys values is_null string_at map filter sort_by reversed url_decode json_quote panic assert
to_bytes to_str reserve resize_uninitA function of your own, in the program or in a module, may have one of these names. A call get(a, ...) or a.get(...) goes to your get when its first parameter fits a and the number of arguments matches; otherwise it goes to the builtin, so the builtin still works on strings, arrays, and maps next to yours:
struct Store:
names: [str]
fn get(s: Store, i: int) str:
return s.names[i]
fn len(s: Store) int:
return len(s.names)
fn main():
st = Store(["ada", "bob"])
ages = {"ada": 36}
print(st.get(1), get(st, 0), len(st), ages.get("ada", 0), len("hey"))bob ada 2 36 3When the first argument is itself of a builtin type (a string, number, array, or map), a call that doesn't fit your function goes to the builtin; for any other type, the error is about your function. Functions in an extern block and export fn functions can't take a builtin's name, because C sees that name: rename an extern one with = "c_name".
21. Idioms
struct Parsed:
ok: bool
value: int
fn parse_port(s: str) Parsed: # failure without exceptions
n = s.to_int(-1)
if n < 1 or n > 65535:
return Parsed(false, 0)
return Parsed(true, n)
fn index_of(xs: [str], want: str) int: # search
for i, x in xs:
if x == want:
return i
return -1
fn main():
p = parse_port("8080")
if p.ok:
print("port", p.value)
print(parse_port("x").ok, index_of(["a", "b"], "b"), reversed([1, 2, 3]), sum([4, 5]))
csv = "name,age\nada,36\nbob,25"
total = 0
for i, line in csv.split("\n"):
if i == 0:
continue
cols = line.split(",")
total += cols[1].to_int(0)
print("total age", total)
stack: [int] = []
stack.push(1)
stack.push(2)
top = stack.pop()
queue = [1, 2, 3]
head = queue[0]
queue = queue[1..] # pop from the front
print(top, stack, head, queue)port 8080
false 1 [3, 2, 1] 9
total age 61
2 [1] 1 [2, 3]Graphs and trees that need links between nodes use indexes into an array:
struct Node:
name: str
edges: [int] # indexes into the nodes array
fn main():
nodes = [Node("a", [1, 2]), Node("b", [2]), Node("c", [])]
seen = [false] * len(nodes)
todo = [0]
order: [str] = []
while len(todo) > 0:
n = todo.pop()
if seen[n]:
continue
seen[n] = true
order.push(nodes[n].name)
for e in nodes[n].edges:
todo.push(e)
print(order)["a", "c", "b"]