Tern

Standard library

Tern ships a standard library for the programs people write most: formatting, math, time, files and processes, JSON, logging, cryptography, SQLite, and web services with TLS, PostgreSQL and Redis. This page explains how to import modules, lists what each one is for, shows which functions need no import at all, and says which modules work on which platforms.

Importing a module

import name makes a module's functions and types available as name.thing:

import fmt
import math

fn main():
    area = math.pi() * 2.0 * 2.0
    print("area:", fmt.fixed(area, 2))
Output
area: 12.57

from name import a, b brings chosen names in so you can use them without the prefix. You can mix both forms:

import json
from fmt import thousands, pad_left
from http import Request, new_request

fn page_of(req: Request) int:
    return req.query("page").to_int(1)

fn main():
    page = page_of(new_request("GET", "/search?q=tern&page=2", ""))
    print(pad_left(thousands(page * 1500), 8, " "), json.encode([page]))
Output
   3,000 [2]

Imports go at the top level of a file, usually first. A module that is never imported costs nothing: SQLite, for example, is linked only into programs that import sqlite.

The standard library is ordinary Tern modules in the std/ directory of the compiler, so import models looks in std/ before it looks next to your program. Don't name your own modules after the standard ones. See Modules and packages for how your own modules work.

The modules

ModuleWhat it's for
fmtFixed decimals, padding, digit grouping, money (f-strings have no format specs)
mathSquare roots, rounding, logarithms, powers, trigonometry, pi
randomFast pseudo-random ints and floats (not for cryptography)
timeClocks, sleeping, RFC 3339 and strftime formatting and parsing, dates, durations
osArguments, environment, exit codes, stdin / stderr, subprocesses, signals
fsFiles and directories: whole-file and line-by-line reading, stat, rename, errors
jsonEncoding any value to JSON, and decoding JSON into typed values
reRegular expressions in linear time: search, groups, validate, replace, split
logLeveled, structured logs (logfmt, JSON or text) on stderr
cryptoSHA-2, HMAC, Argon2id password hashing, PBKDF2, secure random, base64, hex, UUIDs
termThe terminal: is it one, its size, colors that switch off when piped, tables, progress, password prompts
flagCommand-line flags into a struct: types from the fields, defaults from its values, --help written for you
heapA heap of ints, floats or strings: smallest (or largest) first
pqueueA priority queue of any values: Dijkstra, schedulers, event loops
dequeA double-ended queue: O(1) at both ends (BFS, sliding windows)
bitsetA set of small ints, one bit each: sieves, visited sets, flags
urlURLs: parse, build, resolve links, query pairs, escaping (Go's net/url rules)
tomlTOML 1.0 config files into a struct or a json.Value, and structs back to TOML
binaryBinary formats: big- and little-endian integers and floats, varints (protobuf / LEB128), a Writer and a checked Reader
pathFile paths as text: join, clean, dir / base / ext, relative paths, shell patterns and ** globs
sqlRows from a database driver straight into structs (like Go's database/sql), and the row format drivers share
csvReading and writing CSV (RFC 4180, like Go's encoding/csv): rows, records by column, one record at a time
compresszstd, gzip, zlib and deflate of any bytes, with size limits for untrusted input
htmlHTML escaping and templates that escape by default
httpHTTP servers (a one-line serve, and the engine with routes, WebSockets, SSE and HTTPS), a client, request and response helpers
tlsTLS connections, https:// in the HTTP client, HTTPS servers

First-party packages (roost, sqlite, pg, redis, auth, ...) are imported the same way but aren't part of the standard library: see Packages.

Each page lists every function with its signature, what it does at the edges (empty input, missing files, bad JSON), and a tested example.

Builtins: no import needed

Some functions are part of the language, not a module. They need no import. Your own functions may share their names; see builtin names:

print len push pop copy abs min max sqrt float int str chr
find contains starts_with ends_with replace trim upper lower split join
to_int to_float byte repeat
get remove keys values
map filter sort_by
json_quote url_decode is_null

They are documented on the builtin functions page. Like any function, they can be called with method syntax: s.upper() is upper(s), and xs.push(v) is push(&xs, v).

The same rule works for module functions whose first parameter has a module type: d.exec(sql, params) calls sqlite.exec(d, sql, params), because d is a sqlite.Db.

import sqlite

fn main():
    d = sqlite.open(":memory:")
    d.exec("CREATE TABLE notes (body TEXT)", [])
    sqlite.exec(d, "INSERT INTO notes (body) VALUES (?)", ["same call"])
    print(d.query("SELECT body FROM notes", []))
Output
[{"body": "same call"}]

Platform availability

Most modules work everywhere Tern runs. The exceptions depend on the operating system (sockets, SQLite, OpenSSL):

ModulemacOS / LinuxiOSAndroidWebAssembly
fmt, math, random, time, json, re, log, crypto, compress, html, csv, sql, path, flag, url, toml, binary, heap, pqueue, deque, bitset, termyesyesyesyes
os, fsyesyesyesyes, inside the directories the host grants
sqliteyesyes (SQLite from the SDK)no (the NDK has no SQLite)no
migrateyesyesno (uses sqlite)no
sqlgenyesyesno (uses sqlite)no
httpyesyesyeshttp.serve no; the helpers yes
web, pg, redis, auth, sentryyesyesyesno (no sockets)
tlsyes (aws-lc, built in)yes (aws-lc, built in)yes (aws-lc, built in)no

Using sqlite or http.serve on a target that lacks it is a compile error, not a runtime surprise:

$ tern build --target wasm app.tn
app.tn:1: error: `import sqlite` is not available on wasm
1 error(s); not compiled.

On wasm, the http module's plain functions (http.text, http.match, req.query, ...) still work, so request-handling code can be shared and tested; only the server itself is missing. A wasm program can only reach the directories its host grants: tern run --target wasm grants the current directory and /tmp; with wasmtime, pass --dir. See the WebAssembly guide and iOS and Android for details.

What is not in the standard library

There is no MySQL client yet. For those, call a C library directly (see Calling C).

Source: docs/std/index.md. Every example on this page is compiled and run by tern x test docs.