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))area: 12.57from 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])) 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
| Module | What it's for |
|---|---|
| fmt | Fixed decimals, padding, digit grouping, money (f-strings have no format specs) |
| math | Square roots, rounding, logarithms, powers, trigonometry, pi |
| random | Fast pseudo-random ints and floats (not for cryptography) |
| time | Clocks, sleeping, RFC 3339 and strftime formatting and parsing, dates, durations |
| os | Arguments, environment, exit codes, stdin / stderr, subprocesses, signals |
| fs | Files and directories: whole-file and line-by-line reading, stat, rename, errors |
| json | Encoding any value to JSON, and decoding JSON into typed values |
| re | Regular expressions in linear time: search, groups, validate, replace, split |
| log | Leveled, structured logs (logfmt, JSON or text) on stderr |
| crypto | SHA-2, HMAC, Argon2id password hashing, PBKDF2, secure random, base64, hex, UUIDs |
| term | The terminal: is it one, its size, colors that switch off when piped, tables, progress, password prompts |
| flag | Command-line flags into a struct: types from the fields, defaults from its values, --help written for you |
| heap | A heap of ints, floats or strings: smallest (or largest) first |
| pqueue | A priority queue of any values: Dijkstra, schedulers, event loops |
| deque | A double-ended queue: O(1) at both ends (BFS, sliding windows) |
| bitset | A set of small ints, one bit each: sieves, visited sets, flags |
| url | URLs: parse, build, resolve links, query pairs, escaping (Go's net/url rules) |
| toml | TOML 1.0 config files into a struct or a json.Value, and structs back to TOML |
| binary | Binary formats: big- and little-endian integers and floats, varints (protobuf / LEB128), a Writer and a checked Reader |
| path | File paths as text: join, clean, dir / base / ext, relative paths, shell patterns and ** globs |
| sql | Rows from a database driver straight into structs (like Go's database/sql), and the row format drivers share |
| csv | Reading and writing CSV (RFC 4180, like Go's encoding/csv): rows, records by column, one record at a time |
| compress | zstd, gzip, zlib and deflate of any bytes, with size limits for untrusted input |
| html | HTML escaping and templates that escape by default |
| http | HTTP servers (a one-line serve, and the engine with routes, WebSockets, SSE and HTTPS), a client, request and response helpers |
| tls | TLS 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_nullThey 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", []))[{"body": "same call"}]Platform availability
Most modules work everywhere Tern runs. The exceptions depend on the operating system (sockets, SQLite, OpenSSL):
| Module | macOS / Linux | iOS | Android | WebAssembly |
|---|---|---|---|---|
| fmt, math, random, time, json, re, log, crypto, compress, html, csv, sql, path, flag, url, toml, binary, heap, pqueue, deque, bitset, term | yes | yes | yes | yes |
| os, fs | yes | yes | yes | yes, inside the directories the host grants |
| sqlite | yes | yes (SQLite from the SDK) | no (the NDK has no SQLite) | no |
| migrate | yes | yes | no (uses sqlite) | no |
| sqlgen | yes | yes | no (uses sqlite) | no |
| http | yes | yes | yes | http.serve no; the helpers yes |
| web, pg, redis, auth, sentry | yes | yes | yes | no (no sockets) |
| tls | yes (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).