Tern

Command line

tern is the Tern compiler. It checks a program, translates it to C, and has clang build the C into a native binary, a library, or a WebAssembly module. It also runs tests, formats code, fetches packages, and serves editors. This page lists every command and flag, the exit codes, the JSON error format for tools, the targets and the toolchains they need, the environment variables the compiler and compiled programs read, and the commands that run the test suites.

tern run hello.tn            # compile and run
tern hello.tn                # the same: a file name alone means `run`
tern build hello.tn -o hello # make a binary
tern check hello.tn          # type and safety checks only
tern test                    # run the tests in *_test.tn files
tern fmt                     # format every .tn file below this directory

Installing

tern is written in Tern (compiler/). ./install.sh builds it into bin/tern and links it into ~/.local/bin. It builds the compiler with the previous bin/tern; on a fresh checkout (or when bin/tern is too old) it first compiles bootstrap/ternc.c, the compiler emitted as one C file, with cc (see bootstrap/README.md).

tern needs clang to build anything (on macOS, xcode-select --install). Run it from anywhere; it finds the standard library and runtime next to itself. Every target (--target wasm, linux, ios, android, ...) is handled by tern itself; see Targets for the toolchains they need.

Commands

tern <command> <file.tn> [flags] [-- program arguments]
CommandWhat it does
run FILEChecks, compiles, and runs the program, passing it the arguments after --. Exits with the program's exit status.
build FILEChecks and compiles the program to a file (see Build outputs).
check FILEOnly the type and safety checks; prints FILE: ok. Fast: no C compiler runs.
repl [FILE...]An interactive prompt: type an expression to see its value, or statements, fns, structs and imports that later lines use. Each FILE's definitions are loaded first (see REPL).
emit FILEPrints the generated C to standard output.
test [PATH...]Runs the test_* functions in *_test.tn files (see Testing).
fmt [--check] [PATH...]Formats .tn files in place (see Formatting).
new NAME [--template T] [--no-git]Starts a project in the directory NAME from a template: cli (default), roost, or lib (see New projects).
openapi-client SPEC.json -o DIR --name NAME [--tag T]Writes a typed client package for an HTTP API from its OpenAPI 3 document (see Clients for other APIs).
add NAME[@VERSION] [GIT-URL]Adds a package from the package index (or any git repository) to tern.mod at its newest release, and fetches it.
remove NAMETakes a package out of tern.mod, tern.lock, and deps/.
search [WORD...]Lists the packages whose name or description has every word: the standard library, the first-party packages, and the index's.
auditLists the packages in tern.lock that a security advisory names, with the fixed version; exit status 1 if any.
get [NAME URL@VERSION]Fetches the packages listed in tern.mod into deps/ (see Packages).
lspRuns the language server on standard input and output (see Editors).
guide [TOPIC...]Prints the language reference, or only its sections about a topic.
x TASKIn a Tern checkout: its own tasks (tools/x.tn): test [suite], build, bootstrap, docs [--check], llms. See Tests.
`migrate [--db URL] [--dir DIR] updown [N]statusnew NAME`Applies or undoes the migrations in ./migrations on the database from --db or $DATABASE_URL (see migrate).
sqlgen [--db URL] Q.sql... -o OUT.tn [--migrations DIR] [--check]Writes typed functions for the queries in Q.sql (see sqlgen).
version, --versionPrints the version and the directory the runtime and standard library come from.
help, -h, --helpPrints a usage summary with every command and flag.

FILE is the program's main file, which must contain fn main() (unless you build a library). Modules it imports are found from there (see Modules and packages).

guide NAME, when NAME is a standard-library module or a first-party package (guide json, guide web), prints that module's API: the comment at the top of its file. Otherwise guide looks for sections whose title contains the topic (guide strings, guide maps); if none do, it prints the sections whose text contains every word given (guide parallel for). If nothing matches, it lists the section titles and exits with status 1. It is meant for quick lookups from a terminal, and for agents.

tern run wc.tn -- notes.txt todo.txt
tern guide closures
tern emit hello.tn > hello.c

Flags

Flags go after the command, before or after the file name. Everything after -- is passed to the program by run. An unknown flag is an error that suggests the closest one (unknown flag `--nativ`; did you mean `--native`?), and so is an unknown command.

FlagMeaning
-o PATHOutput file for build (and, for run, where to put the binary).
--jsonWith check, run, or build: report compile errors as JSON on standard output (below).
--symbolsWith check --json: also list every definition and reference (below), for editors.
--target T, --target=TCompile for another platform (see Targets). Default: native.
--libBuild a static library (libNAME.a) and a C header (NAME.h) of the program's export fn functions.
--sharedBuild a shared library (libNAME.dylib on macOS, libNAME.so elsewhere) and a C header.
--portableUse the portable runtime on native too (see below). Libraries always use it.
-g, --debugA debug build: -g -O0, with the C kept next to the output (see Debugging).
--nativeTune the code for this machine's CPU (see Build outputs).
--no-cacheBuild without the build cache.
--stripLeave the symbol table and the function and module names out of the binary (see Build outputs).
--filter TEXT(test) Run only the tests whose name contains TEXT.
-v(test) Also show the output of tests that pass.
-l LIB, -lLIBLink a C library, as with a C compiler. Repeatable.
-L DIR, -LDIRAdd a library search directory. Repeatable.
-I DIR, -IDIRAdd a C header search directory. Repeatable.

-l, -L, and -I are for calling C; libraries and sources named in extern blocks are linked in automatically, so they are only needed for extra ones. run can't be combined with --lib or --shared (a library can't be run).

The portable runtime finds each thread's heap through thread-local storage instead of from the thread's (specially aligned) stack. That lets Tern code run on threads it didn't create, which libraries and callbacks from C need, at a cost of about 20% on allocation-heavy code. Every target except native uses it.

REPL

tern repl reads Tern a line at a time. An expression prints its value (strings quoted); x = 5 makes a variable later lines can use; fn, struct, enum, const and import add to the program, and typing a fn or struct again replaces it. A line ending in : starts a block, ended by an empty line.

$ tern repl
>>> xs = [3, 1, 2]
>>> xs.sorted()
[1, 2, 3]
>>> fn sq(n: int) int:
...     return n * n
...
>>> sq(xs[0])
9

Commands: :show prints the program so far, :undo takes back the last input, :reset starts over, :load FILE adds a file's definitions (not its main), :quit or Ctrl-D ends.

Tern is compiled, so the session is one program that is compiled and run again for each input (about a third of a second for a small one, thanks to the build cache); only the new input's output is shown. Input that doesn't compile, or fails when it runs, isn't kept. Earlier lines run again each time, so their side effects (writing a file, reading the clock, drawing a random number) happen again, and a value such as random.int(0, 9) may differ from the one shown when it was typed.

Exit codes

StatusWhen
0Success. For run, whatever the program returned: 0 when main returns normally.
1Compile errors; the C compiler failed or isn't installed; a target's toolchain is missing; an unknown command or flag; a flag is missing its value; the runtime can't be found; guide found no matching section; a test failed; fmt --check found a file to format; get failed.
2(run only) The program stopped with a runtime error.
64Usage error: no command, no file given, or run --lib. The usage text is printed.
66The file doesn't exist: tern: can't open FILE.

With run, any other status comes from the program itself (os.exit(3) gives 3). Compiled programs use the same convention on their own: 0 on success, 2 after a runtime error, which prints runtime error in <function> (<file>:<line>): <message> to standard error.

Compile errors

Errors go to standard error, one per line, with a hint: line after an error when the code looks like another language's habit (def, let, &&, append, None, ...). All the errors in a program are reported together, followed by a count:

prog.tn:3: error: sqrt() needs a float
prog.tn:3: hint: convert first: `sqrt(float(n))`
prog.tn:4: error: int() needs a float
prog.tn:4: hint: to parse a string, use `s.to_int(default)`, e.g. `"42".to_int(0)`
2 error(s); not compiled.

The compiler errors page explains the common ones.

JSON output

--json prints the result as JSON on standard output instead, for editors, scripts, and agents. The exit status is the same as without it. On success (check only):

{"ok": true, "file": "prog.tn"}

With errors:

{
 "ok": false,
 "errors": [
  {
   "file": "prog.tn",
   "line": 3,
   "message": "sqrt() needs a float",
   "hint": "convert first: `sqrt(float(n))`",
   "source": "a = sqrt(n)"
  }
 ]
}
FieldTypeMeaning
okbooltrue if the program compiled
filestring(success) the file that was checked
errors[].filestringthe file the error is in (an imported module can be the one at fault), relative to the current directory when it's below it
errors[].lineintline number, from 1
errors[].messagestringthe error, as in the text output
errors[].hintstring or nulla suggested fix, or null
errors[].sourcestringthe offending line, trimmed

Only compile errors are JSON. Usage errors, a missing file, and C compiler failures are still printed as text on standard error. run --json and build --json print nothing on success except the program's own output.

check --json --symbols adds a "symbols" field, whether or not there are errors: every definition in the program and every reference to one, for editors (go to definition, hover, find references, rename):

"symbols": {
  "defs": [{"id": "field:Point.x", "kind": "field", "name": "x", "qualified": "Point.x",
            "file": "prog.tn", "line": 2, "col": 5, "end_col": 6,
            "type": "int", "signature": "x: int"}, ...],
  "refs": [{"file": "prog.tn", "line": 9, "col": 14, "end_col": 15, "def": "field:Point.x"}, ...]
}
  • kind is fn, struct, enum, variant, field, param, local, or builtin.
  • col and end_col are 1-based byte offsets in the line (end_col is one past the name).
  • A reference's def is a definition's id. Builtins are builtin:NAME, with a definition that carries only a signature.
  • Method calls (p.area()), fields, and module-qualified names (http.Request) point at what they mean. Generic functions' bodies are covered through their first use.
  • The standard library contributes its functions and types as definitions (so an editor can jump into it), not the references inside it.

Build outputs

build writes into the current directory unless -o says otherwise. For prog.tn:

CommandWrites
build prog.tnprog (an executable)
build --target wasm prog.tnprog.wasm (a WASI program)
build --lib prog.tnlibprog.a and prog.h
build --shared prog.tnlibprog.dylib or libprog.so, and prog.h
build --lib --target wasm prog.tnprog.wasm, prog.mjs (a JavaScript loader), and prog.d.ts (TypeScript types)
build --lib --target wasm-threads prog.tnthe same three; the loader also starts the worker threads

The header goes in the same directory as the library, named after it without the lib prefix: -o out/libgame.a writes out/game.h. Missing directories in -o are created. run builds into a new temporary directory (or to -o) and runs from there.

The generated C and the object files go into a temporary directory. If clang fails, tern says so and where the generated C is (the generated C is at /tmp/.../prog.c), which is useful when reporting a compiler bug. If clang isn't installed at all, it says that instead.

Native builds use -O3 and a baseline CPU, so a binary runs on any machine of the same kind: -mcpu=apple-m1 on Apple silicon (any M-series Mac), -march=armv8.2-a on arm64 Linux, and -march=x86-64-v2 on x86-64 (any x86-64 CPU from about 2009 on). --native tunes for the building machine instead (-mcpu=native / -march=native); on the benchmarks in bench/ the difference is within noise (M4 Pro: fib +1.6%, nbody +0.4%, sieve -0.6%, tasks -1.0%, trees -8.4%, baseline time vs native), so the portable default costs nothing measurable there.

A binary names its functions and modules in runtime errors (runtime error in pricing.total (pricing.tn:8): ...), so those names are in the executable, as in Go and in an unstripped Rust binary. --strip leaves them out, along with the symbol table: errors then give only the line (runtime error (line 8): ...), and a reader of the binary sees no function names. String literals are still there as written, and the machine code can still be disassembled; keep secrets out of programs you hand to others.

A copied tern binary finds the runtime and standard library by walking up from where it is; if it can't, it says can't find the Tern runtime and asks for TERN_ROOT.

Build cache

A finished build is kept in ~/.cache/tern ($XDG_CACHE_HOME/tern if that is set), named by a hash of everything that went into it: the generated C, the compiler and its flags, the C sources and headers from extern blocks, and the libraries in -L directories (by size and time). Building an unchanged program again copies the result instead of running clang: rebuilding the compiler itself (tern build compiler/main.tn) takes 0.2 s instead of 36 s. The cache keeps the 1000 most recently used builds.

tern run and tern test run the cached program itself (through a hard link) rather than a copy: macOS checks a program's code signature the first time each file runs, which takes a second or two, so an unchanged program starts at once every run after the first.

tern run and tern test also keep the runtime as a separate object, compiled once for each set of features a program uses (tasks, the web server, SQLite, ...) and then shared by every program that uses the same set, so after an edit only the program's own code goes through clang. A web server's rebuild takes about 0.55 s instead of 1.2 s. The finished program runs just as fast: the runtime's hot paths are inline functions that every program still compiles in. tern build compiles everything as one unit.

A program over 200 KB of generated C (a web app; not a small script or a benchmark) is compiled as units of about 100 KB, as many at once as there are cores, and each unit is cached by its contents. The declarations every unit shares are compiled once, as a precompiled header (kept in the cache too). A function goes to the unit its name picks, and generated names are numbered within each function, so an edit changes only the units holding the functions it touched: after a one-line change to a 7 MB server (strata), tern run recompiles one unit of 72 and the build takes about 1.1 s (tern build, with ThinLTO: 3.5 s; both 13 s before). tern build links the units with ThinLTO (cross-unit inlining, as fast as one unit), and on macOS keeps the link's per-unit code in the cache too; tern run and tern test link without it. A release build never reuses a tern run / tern test binary.

--no-cache skips it for one build, TERN_CACHE=off turns it off, and TERN_CACHE=DIR moves it. Debug builds aren't cached. The cache doesn't notice a change in a system library or the C compiler itself; delete the directory after upgrading clang. If the directory can't be written (a sandbox that only allows the workspace and the temp directory), the cache moves to $TMPDIR/tern-cache-$USER for that build, with no messages.

Debugging

tern build -g prog.tn (or --debug) builds with -g -O0, keeps the generated C next to the output as prog.tern.c, and puts #line directives in it, so a debugger shows and steps through the .tn source:

tern build -g prog.tn -o prog
lldb ./prog
(lldb) breakpoint set --file prog.tn --line 12
(lldb) run
(lldb) next
(lldb) frame variable

Breakpoints by file.tn:line, stepping, and backtraces use Tern lines; stepping into the runtime shows the C. Variables have their C names: a parameter n is n_p, and a local total is total_2 (a number is added to keep names unique). gdb works the same way on Linux.

Testing

tern test runs tests: functions named test_... with no parameters, in files whose names end in _test.tn.

# math_test.tn
import testing

fn add(a: int, b: int) int:
    return a + b

fn test_add():
    testing.eq_int(add(2, 2), 4)

fn test_split():
    testing.eq_strs("a,b".split(","), ["a", "b"])
$ tern test
PASS  test_add (4 ms)
PASS  test_split (3 ms)
ok    math_test.tn: 2 passed, 0 failed (9 ms)
  • tern test searches the current directory and the directories below it (skipping deps/, build/, and names starting with .); tern test DIR searches DIR, and tern test FILE runs the tests in any one file.
  • Each test runs in its own process, so a runtime error or a crash fails that test and the others still run. A test's output is shown only when it fails (-v shows it always).
  • --filter TEXT runs only the tests whose name contains TEXT.
  • The exit status is 1 if any test failed or a test file didn't compile.
  • A test file can use everything a program can, including its own helper functions and imports of the modules next to it. It must not have a fn main().
  • A test file inside a package (a directory of .tn files none of which has fn main(), such as a package directory or the top of a package's own repository) is part of that package, as in Go: it calls the package's functions and uses its types by their plain names, _private ones included, without importing it. A test that imports a neighbouring file by name (import greet beside greet.tn) treats it as a separate module instead.

The testing module has the checks. Each one that fails prints FAIL: ... with the values and ends the test:

FunctionFails unless
testing.eq_int(got, want), eq_float, eq_str, eq_boolgot == want
testing.eq_ints(got, want), eq_strsthe arrays have the same elements
testing.near(got, want, tolerance)abs(got - want) <= tolerance (floats)
testing.is_true(cond, what), is_falsecond is true (false)
testing.includes(s, sub)s contains sub
testing.fail(msg)never: always fails

Formatting

tern fmt rewrites .tn files in the standard layout: 4-space indentation, one space around binary operators and after commas and colons, none inside brackets, at most one blank line in a row, one blank line before a top-level fn/struct/enum that follows a block, no trailing whitespace, and one newline at the end. Comments are kept, and an end-of-line comment keeps its column when it fits. Only whitespace changes: the tokens are the same before and after. Formatting a formatted file changes nothing.

tern fmt                     # every .tn file below the current directory
tern fmt src/ main.tn        # these files and directories
tern fmt --check             # list the files that would change; exit status 1 if any would
tern fmt - < in.tn           # standard input to standard output

A file that doesn't parse is left alone and reported. Long lines aren't wrapped.

New projects

tern new wc                      # a command-line tool (the default template)
tern new notes --template web    # a web app: JSON API on SQLite, accounts, a page, migrations
tern new slugs --template lib    # a package other projects import as `slugs`
tern new --list                  # the templates

tern new creates the directory (it must not exist, or be empty), copies the template from templates/ in the Tern checkout with its name filled in, and runs git init (not with --no-git). Every project it makes passes tern test as it is, has a README saying how to run it, a tern.mod for packages, and an AGENTS.md (plus a CLAUDE.md pointing to it) that tells coding agents how to write Tern and where things go in that project. A lib name must be a valid module name (lowercase letters, digits, _).

Packages

tern search csv              # what exists: std, first-party (built in), and the index
tern add csv                 # the newest vX.Y.Z tag of the indexed repository; or csv@v1.2.0
tern add geo https://github.com/someone/geo    # any git repository, not only indexed ones
tern remove csv

tern add looks the name up in the package index (index/packages/NAME.txt in the Tern checkout, or $TERN_INDEX: a directory or a git URL; see index/README.md), picks the newest release tag (the default branch's commit if there are none), and runs tern get for it. A name that is already built in (roost, pg, json, ...) needs no adding, and tern add says so. A package's *_test.tn files are never part of it.

A project lists the packages it uses in a tern.mod file at its root, one per line:

# name = git-url@version   (a tag, branch, or commit)
csv = https://github.com/someone/tern-csv@v1.2.0

tern get clones each one at that version into deps/NAME/ (without its .git) and records the exact commits, a hash of each package's files, and what each package's code can reach (network, files, processes, C code) in tern.lock, which later tern get runs reuse and check, so every checkout gets the same, verified code. A package whose files no longer match the lock is an error, and so is an update that can reach something new (the network, say) until you accept it: tern get --accept NAME. tern audit lists the locked packages with a security advisory. Fetching and building never run a package's code. See design/packages.md, "Security", for the details and TERN_PROXY / TERN_PRIVATE. tern get NAME URL@VERSION adds or changes a line in tern.mod first. A package's own tern.mod is followed too; all packages share one deps/ directory, and your tern.mod decides when two want different versions.

import csv then finds deps/csv/ (after the standard library and the program's own directory), from any file in the project. Commit tern.mod and tern.lock; deps/ can be committed (vendored) or recreated with tern get. The design is in design/packages.md.

Editors

editor/vscode/ is a VS Code extension: syntax highlighting, comment and bracket handling, indentation after :, and the language server. See its README to install it.

tern lsp is a language server (the Language Server Protocol on standard input and output) for any editor that speaks it:

  • errors and hints as you type (it runs tern check --json --symbols on the file; unsaved text is checked from a hidden temporary copy next to the file, so imports still resolve);
  • go to definition, hover (the signature or type, and the comment above the definition), find references, and rename, for every name the checker resolves: functions (also when called as x.f()), types, fields, variants, parameters, and locals;
  • completion (after x.: the fields of x's type and the functions that take it first; after mod.: that module's functions and types; elsewhere: keywords, builtins, imported modules, and the file's own names), and signature help in calls;
  • formatting (the same as tern fmt), an outline of the file, and a search of the names in the workspace.

While the file has a syntax error, the server keeps the names from its last check that parsed; where those no longer match the text, definition and hover fall back to looking up fn, struct, and enum lines by name.

Targets

--targetBuilds forNeedsNotes
nativethis machineclangthe default; the fast runtime
macos-x86_64Intel Macsclangruns under Rosetta 2 on Apple silicon
linux, linux-arm64Linux arm64Dockerbuilt and run in a container (image built on first use)
linux-x86_64Linux x86-64Dockerthrough Docker's emulation
linux-static, linux-static-x86_64any Linux (fully static, musl)Dockerone self-contained executable: runs on any distribution, even in a FROM scratch image
wasmWebAssembly (WASI)brew install llvm lld wasi-libc wasi-runtimes, or a wasi-sdk (WASI_SDK_PATH)one thread: parallel runs sequentially; no sqlite, no http.serve. run uses wasmtime, or Node.js 18+
wasm-threadsWebAssembly with shared memoryas wasm, plus Node.js 18+parallel runs in parallel on Web Workers (Node's worker_threads). run uses Node; in a browser, load the library from a Worker on a cross-origin-isolated page
iosiPhone and iPad (arm64)Xcodecan't be run here; link the --lib library into an app
ios-simthe iOS SimulatorXcoderun boots a simulator if none is running
android, android-arm64Android arm64Android NDKno sqlite (no SQLite in the NDK). run uses adb and a connected device or emulator
android-x86_64Android x86-64Android NDKemulators on Intel machines

Using import sqlite or http.serve on a target that doesn't have it is a compile error (`import sqlite` is not available on wasm). See the WebAssembly and iOS and Android guides.

When run runs a program in Docker, on a simulator, or on a device, it passes along the environment variables whose names start with TERN_, and DBPATH. Under wasm-threads, Node passes the whole environment (TERN_THREADS sets the number of threads; the default is the number of cores).

Environment variables

Read by the compiler

VariableEffect
TERN_STATS=1Build the program with memory counters (below). Read when compiling, not when running.
CCThe C compiler for native and macos-x86_64 builds (default clang).
TERN_ROOTThe Tern checkout holding runtime/, library/, and docs/ (default: found by walking up from the tern executable).
TERN_CACHEoff turns the build cache off; a directory moves it.
TERN_SPLIT0 compiles tern run / tern test programs as one unit; 1 uses the separate runtime object for tern build too (see build cache).
TERN_UNIT_BYTESA program whose generated C is over twice this (default 100000 bytes; programs over 200 KB) compiles as units of about this size (at most 128), cached one by one, linked with ThinLTO by tern build when the C compiler is clang (see build cache). TERN_SPLIT=0 turns it off; TERN_UNIT_LTO=0 links without ThinLTO.
TERN_PCH0 compiles a split program's units without the precompiled header of what they share.
TERN_DCE0 generates every function of every imported module; by default only the functions the program can reach (from main, a library's export fns, or the tests) are compiled.
WASI_SDK_PATHA wasi-sdk install to use for wasm (otherwise /opt/wasi-sdk, then Homebrew's packages).
TERN_WASM_SIMD0 builds wasm targets without wasm SIMD, for hosts that reject it (some blockchain VMs). Browsers, Node, and wasmtime all support it; it is on by default.
ANDROID_NDK_HOME, ANDROID_NDK_ROOTThe Android NDK (otherwise the newest under $ANDROID_HOME/ndk/, default ~/Library/Android/sdk).
ANDROID_HOMEThe Android SDK, used to find the NDK and adb.
TERN_IOS_DEVICEThe simulator to boot for ios-sim when none is running (a UDID).

Read by compiled programs

VariableDefaultEffect
TERN_THREADSnumber of coresWorker threads for parallel (1 to 256).
TERN_HTTP_THREADSTERN_THREADSThreads serving HTTP requests.
TERN_HTTP_MAX_BODY_MB16Largest request body accepted (larger: 413).
TERN_HTTP_IDLE_SEC60Seconds before an idle keep-alive connection is closed.
TERN_HTTP_HEADER_SEC10Seconds a client may take to finish sending a request.
TERN_INDEXthe checkout's index/the package index for tern add / search / audit: a directory, or a git URL.
TERN_PROXY(none: git directly)a package mirror for tern get (see design/packages.md, "Security"); off for git directly.
TERN_PRIVATE(none)comma-separated URL prefixes (github.com/mycorp/) fetched with git directly, never through the mirror.

The http variables are described on the http page.

TERN_STATS

A program compiled with TERN_STATS=1 counts its heap allocations and prints a summary to standard error when it ends normally:

TERN_STATS=1 tern run examples/01_values.tn
-- memory: 4 allocations, 4 freed, 0 leaked, 2 copy-on-write copies; no GC
  • allocations and freed: heap blocks created and released.
  • leaked: blocks never released, not counting the ones that live for the whole run (string literals and one-byte strings, which WebAssembly makes at start-up: that is why "freed" can be far below "allocations" there with nothing leaked). It should always be 0; the test suites fail on any leak.
  • copy-on-write copies: times a shared array, map, or string had to be copied because one holder changed it. A high number in a hot loop is worth a look (see Performance tips).

The line isn't printed when the program ends with os.exit or a runtime error. Without TERN_STATS, the counters are compiled out and cost nothing. A library built with it exports tern_stats() to print the same line on demand.

Tests

The test suites are a Tern program, tests/runner/. From the repository root:

tern run tests/runner/main.tn -- run                      # the main suite: tests/run, tests/reject, tests/embed
tern run tests/runner/main.tn -- run --update             # rewrite the expected .out / .err files from current results
tern run tests/runner/main.tn -- run --flags="--portable" # pass extra compiler flags to the run tests
tern run tests/runner/main.tn -- run --target=wasm        # run the run tests on another target (skips unsupported ones)
tern run tests/runner/main.tn -- run --mobile             # also the Swift (iOS Simulator) and JNI (Android) demos
tern run tests/runner/main.tn -- docs                     # every example in docs/, README.md, and AGENTS.md
tern run tests/runner/main.tn -- docs docs/std/json.md    # only these files
tern run tests/runner/main.tn -- docs -v                  # also print each example's output
tern run tests/runner/main.tn -- docs --update docs/x.md  # rewrite the ```output / ```error blocks that differ
tern run tests/runner/main.tn -- hints                    # the hints for habits from other languages
tern run tests/runner/main.tn -- cli                      # the tern command itself (test, fmt, get, lsp, cache, -g)
tern run tests/runner/main.tn -- bootstrap                # stage 0 builds the compiler; it reaches a fixed point
tern run tests/runner/main.tn -- all                      # every suite
tern run tools/site/main.tn -- --check                    # no broken links between doc pages

The suites test $TERN if it is set, else bin/tern.

  • run compiles each program in tests/run/ with TERN_STATS=1, runs it, compares its output with the .out file next to it, and fails on any leak. Each program in tests/reject/ must fail to compile with exactly the errors in its .err file. tests/embed/ runs C, JavaScript, and Python host programs that call Tern libraries.
  • docs compiles and runs every tern ` block in the documentation and compares it with the `output block after it. tern check ` blocks are only compiled, and `tern error blocks must fail with exactly the errors in the `error block that follows. Run over everything, it also checks that llms-full.txt is up to date (tern run tools/llms.tn regenerates it).
  • hints feeds common mistakes from other languages to check --json and checks that each gets a helpful hint.
  • bootstrap builds stage 0 from bootstrap/ternc.c, has it build the compiler (stage 1), has that build itself (stage 2), and checks that stages 1 and 2 emit identical C.

Each prints one line per test and a summary, and exits with status 1 if anything failed.

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