Tenon reference
Idioms. Hashes/requirements. Install.
Programs
Root file has fn main() or
fn main(cli: Cli) -> result<unit, CliError>
(any parameter name); see E0310.
.tn files dual-read UTF-8 or compact
~1 (LF, prefix records); tenon fmt
preserves each surface (--migrate-utf8 converts
~1 to UTF-8);
tenon compact/explain inspect compact
forms. Identifiers: ASCII letters, digits, _ (no
leading digit). Keywords:
fn struct enum type interface impl match with let var if else while for break continue return true false dyn.
Single-file #! scripts
(#!/usr/bin/env tenon) take optional top
//! edition, //! capabilities, and
//! deps headers; manifests, derives, and binaries
cache offline in $TENON_CACHE_DIR/scripts/ with zero
local files (E1230–E1236).
test name { … } uses
assert(cond)/assert_eq(l, r) (equality
types). Never pub/imported; check
checks, builds strip.
tenon test <dir> [--filter SUB] runs C+interp
(application-tests).
Modules
Files are modules: import a.b { f, T } loads
a/b.tn. Imports first; only pub items
import. Aliases: f as local (as is
contextual). import a.b or
import a.b as m binds b/m
for m.f(x), m.T, m.E.v; one
import per module per file. Public signatures cannot expose
private types (newtype reprs excepted). Impls are global; methods
need local interfaces or bounds. Newtype ctor/.value
are file-private. derive G for T materializes
implicitly in cache (generators).
Packages/[embed.m]: details.
Values and types
Integer literals: decimal/hex (0xFF), no suffixes,
≤18446744073709551615; must fit expected/other operand integer
type, default i64. Negated/literal-only arithmetic
(-1, 1 + 2) takes context on either
side.
Strings: \n \t \r \\ \" \0. Compact text blocks:
`N; + N raw | lines joined by LF (no
escapes/interpolation).
| Type | Values | Notes |
|---|---|---|
i64, i32 |
signed 64/32-bit ints | overflow traps |
u8, u32, u64 |
unsigned 8/32/64-bit ints | overflow traps |
f64 |
IEEE 754 binary64 | 1.5, 2.0e-3; floats |
bool |
true, false |
|
str |
immutable UTF-8 | literals, interpolation, + |
bytes |
immutable raw bytes | s.bytes(), slices, + |
vec<T> |
immutable sequence | [a, b,]; [] needs element type |
unit |
no useful value | omitted return annotation |
Bindings infer initializer types; annotations
(let n: i64 = 1) must match. Assignments, arguments,
operands, and returns require exact types; no implicit
conversions. Invalid types suppress dependent mismatches (E0307;
E0600/E0601 generic arity).
i64(x)..u64(x) convert integers with
range checks (i64(x) truncates f64;
f64(n) converts); x.wrapping_u8() etc.
truncate. Numeric names are reserved as types/fns, legal as
locals. Int methods: wrapping_{add,sub,mul,neg},
bit_{and,or,xor,not}, shl,
shr, rotl, rotr (shift
counts i64 in 0..bits; signed
shr is arithmetic). Builtins beat interface
methods.
Records
Records (struct Point { x: i64, y: i64 }) are
nominal, immutable values. Need ≥1 unique field; fields allow
@key("v")/@flag for
std.reflect; forward uses work. By-value cycles are
E0410; cycles via
vec/map/fn/dyn
are allowed (ADR-0270). Literals require every field once,
evaluated as written. Read p.x; with
updates ≥1 non-overlapping field paths including compound ops
(s with { pane.scroll: 0, stats.hits += 1 }, base
once, replacements L-to-R; overlaps E0415). On var
locals, s.a.b = v / s.a.b += 1 desugars
to s = s with { … } (let is E0204,
non-local target E0406). Last-use
with/set updates (including across
calls/returns) reuse container storage
(--report=copies). Type/fn namespaces are separate.
Ident { is a literal only before
Ident :.
Newtypes (type UserId = new i64) end at newline,
;, or EOF (new is contextual). In-module
use UserId(42) and id.value; equality
requires same type; no arithmetic or with. Erased in
IR. Type aliases/generic newtypes: E0420/E0421.
Unions and match
Example:
enum Shape { Circle(i64), Rect(i64, i64), Empty }.
Enums are closed nominal values with positional payloads:
Shape.Circle(3), Shape.Empty. Nullary
ctors/patterns omit () (E0516). Named payloads use
records; same cycle rule as records (E0410). match
evaluates its scrutinee once and runs one statement or block arm.
Arms end at newline, ,, or } (including
in calls); extra commas are E0514. Flat union patterns take
variant names (optional scrutinee qualifier, else E0515), with
payload names or _.
A(x, y) | B(y, x) => x needs identical binder
names/types; newlines may follow |. One final
unqualified _ arm (no binders/alternatives) covers
remaining variants; malformed/redundant wildcards are E0503,
duplicate variants E0504. Otherwise all variants are required.
Nested/literal union patterns and guards are unsupported. Binders
follow local scope rules. Used matches need equal types in
reaching arms; divergent arms supply no value; discarded tails run
for effects.
Bindings
Int matches take literals, half-open ranges
(48..58), | alternatives, and one final
_ default. Bounds must fit scrutinee type; first
match wins (including overlaps); scrutinee runs once (details). String matches
take literal str patterns and |, then
one final unqualified _ (no binders); first
byte-equal match wins (including NUL); escapes and escaped braces
work; interpolation patterns are E0513. Invalid patterns/defaults:
E0517; missing defaults: E0518.
let limit = 10 is immutable;
var total = 0 allows
total = total + limit, numeric
+= -= *= /= %=, and += concat on
str/bytes/vec<T>
(desugared to x = x op (rhs)).
Bindings are block-scoped; initializers precede binding. Only
var locals reassign. Redeclaration: E0208; shadowing:
E0209. Sibling blocks may reuse names. Locals/fns have separate
namespaces (let twice = 2; twice(twice) calls the
fn), except fn-typed locals cannot share a visible fn
name (E0708). Member receivers resolve locals before
type/interface qualifiers, including cli.
Functions
Parameters require types; returns default to unit.
Non-unit fns/methods/closures return on every path via explicit
return or implicit tail expression (plain expr,
if/else, match);
single-expression fns/methods also allow = expr
(fn double(x: i64) -> i64 = x * 2).
unit allows bare return/fallthrough;
result<unit, E> fallthrough returns
ok. Names must exist and be unique; arity must match.
Global print/println are reserved
(E0800). Forward calls/recursion work.
Contextual requires <bool> and
ensures <res> => <bool> clauses on
fn signatures typecheck in param/result scope
(E1270/E1271), trap on failure (exit 101), and appear in
doc --card.
Function types fn(A, B) -> R (unit
fn(A)) hold named fns (generic with context) or
closures { x, y -> body } /
{ -> body }. Closures need expected
fn type (E0706), snapshot-capture outer bindings (no
outer var writes E0707; no escaping
return/break/continue
E0703; ? targets the closure). Call f(x)
or (r.f)(x) (E0666/E0709).
checkfree fn fails build (E0720) if a value check remains in
its body; callees may trap (use
check --assert-total <fn> for transitive
totality).
checkfree fn at(v: vec<i64>, i: i64) -> i64 {
if i < 0 || i >= v.len() { return 0 }
v[i]
}
fn main() {}
Generics
Example: struct Box<T> { value: T } and
fn id<T>(x: T) -> T = x allow
let b: Box<i64> = Box { value: id(1) }.
Functions, structs, and enums take <T>.
Box<i64> is type-only; calls/ctors infer from
context, then args/fields L-to-R. Unsolved params need annotations
(E0602); write id(42), Box { … }. Opaque
params allow equality; arithmetic/printing need concrete types.
Both backends specialize reached instances (limits).
Interfaces
Example:
interface Area { fn area(self) -> i64 }
implemented by
impl Area for i64 { fn area(self) -> i64 = self * self }.
Methods/signatures end at newlines. Only first
self may omit type; Self is the exact
receiver in params/returns. One impl per (interface, concrete
type). Unique bounds <T: A + B> enable methods;
inferred/forwarded calls require all bounds. x.area()
searches impls/bounds; ambiguity E0659: qualify via local
interface (Area.area(x)). Direct dispatch, receiver
first. Bare interfaces aren't types (E0663); dyn I
wraps any impl via dyn I(x) when every method takes
self first and uses Self nowhere else
(E0667), and implements I itself. Impl targets:
builtins, newtypes, or instantiated generics (not
fn/dyn, E0665). Bounds on functions only
(E0607). No generic interfaces/impls, inherent impls, or default
methods (restrictions).
Option and result
Seeded unions option<T>
(some(T), none),
result<T, E> (ok(T),
err(E)) use ordinary match/equality. Annotations need
all args; some(1), none,
ok(1), err("bad") need solved context.
Non-option none is a type mismatch. All six names are
reserved top-level types/fns (E0203), legal locals. Bare
some/ok/err require locals
(E0201); ctors use fn namespace and ().
option<T>: unwrap_or(T) -> T,
is_some(), is_none().
result<T, E>:
unwrap_or(T) -> T, is_ok(),
is_err(). unwrap_or default has exact
type T and is eager (receiver then default, each
once). Builtins beat interface methods.
Postfix ? unwraps or returns early:
result<T, E> needs
result<U, F> return with F =
E or an enum with one V(E) variant
(wraps); option<T> needs
option<U>. Else
r.map_err { e -> … }. Unit main
cannot use ? (E0521). Lazy right-associative
opt ?? fallback unwraps option<T>
and evaluates fallback only on none.
let <pat> = <expr> else { <diverging> }
unwraps option<T>,
result<T, E>, or enum variants into immutable
locals (E1200 if else does not diverge;
E1201 for non-variant patterns).
fn twice(x: result<i64, str>) -> result<i64, str> = ok(x? * 2)
fn main() {}
Control flow
if/else, while,
for, break, continue,
return, and typed holes todo() /
todo("msg"). Conditions require bool
(E0304). for x in v iterates vec or
bytes (u8); for i in a..b
iterates half-open i64 ranges. Heads run once L-to-R;
binders are immutable. str requires
s.chars() or s.bytes(). for
is a keyword; in is contextual.
while tests before each iteration (including after
continue). break exits innermost loop;
continue skips body (for advances
first). Loop heads sit outside body scope: control targets an
enclosing loop. return exits the fn.
todo(...) diverges to any type, traps at runtime
(exit 101), lists via tenon holes [--json], and fails
release builds (E1265).
if is an expression:
let n = if flag { 1 } else { 0 }. Used values need
else and matching branch types. A block's value is
its last expression (even with ;), else
unit. Divergent branches supply no value. Statement
if discards branch values. Only the selected branch
runs.
Operators
Precedence (low to high): ?? (right-assoc, lazy),
||, &&, == !=,
< <= > >=, + -,
* / %, unary - !, postfix
., [], ?,
with. Other binary ops are left-associative;
comparisons don't chain
(a < b && b < c). Evaluation is
strictly L-to-R.
&&/|| short-circuit.
/ truncates toward zero; % takes
dividend's sign. INT64_MIN % -1 is 0;
INT64_MIN / -1 traps (ADR-0012).
+ also concatenates str or
bytes. Negation needs signed int or f64.
Ordering accepts matching ints, f64 (IEEE), or
str (UTF-8 bytes). Logical ops need
bool. Equality accepts matching types (not
fn/dyn, E0664; no derives/FFI, E0665):
records in order, unions by tag/payload, sequences by contents
including NULs.
break/continue require
while/for; max nesting 256 (each match
counts once; arm blocks add block nesting). Lone |
outside patterns is E0005 (||). No ++
(E0111): write x += 1.
Strings and sequences
Slices s[a..b], s[a..],
s[..b], s[..] are O(1) same-type views
of str, bytes, or vec using
half-open i64 offsets (bytes for
str/bytes, elements for
vec; defaults 0 and len).
Bounds must be ordered and in range; str endpoints
must be UTF-8 scalar boundaries (else trap). Views keep parent
storage alive across returns/loops. Indexing str is
E0712; assigning slices is E0710. bytes slicing
allows invalid UTF-8. .. also forms int match ranges
and for heads.
Methods need () unless followed by a block
({ Ident (, Ident)* ->). Bare { … }
isn't a value (E0700); fns cannot take trailing blocks (E0701).
str/bytes: len() (bytes),
is_empty(). s.bytes() is a view;
b.to_str() validates to
option<str> without copying.
vec<u8>.to_bytes() -> bytes copies.
s.byte(i) and b[i] read raw
u8 (including UTF-8 continuation bytes); out-of-range
i64 traps even when discarded.
str: contains(s),
starts_with(s), ends_with(s),
find(s) (option<i64> byte offset),
trim() (Unicode White_Space view),
parse_i64() (strict ASCII decimal, optional sign;
invalid/overflow → none), parse_f64(),
words(), count(s), chars(),
split(sep), lines() (last three return
vec<str> views). Ints never coerce to
str; interpolate "{n}". Discarding
trim() is E0711 (text = text.trim()). Text details.
Vectors: len(), is_empty(),
contains(x), set(i, x),
push(x), concat(v); get(i),
first(), last() →
option<T>;
vec<str>.join(sep) → str (complexity).
v[i] traps OOB; updates preserve snapshots; unused
results are E0711. v = v.push(x) is amortized O(1) in
locals, fields, and helpers (ADR-0041).
Blocks: v.map { x -> x * 2 } →
vec<U>;
filter { x -> x > 0 } and stable
sort_by { a, b -> a < b } need
bool, keep vec<T> (sort: O(n)
workspace; right first only if before(right, left)).
fold(init) { acc, x -> acc + x } yields
init's type. Last expr is value; statement tail is
unit. Params are immutable, cannot shadow locals.
Captures allow var writes except in parallel blocks
(captured var write E0721; capturing/returning
non-Fs caps E0722; Fs is read-only in
workers; see cli
DOCS). return/?/outer
break/continue: E0703; inner loops allow
local control. Vector blocks lower to loops.
Interpolation makes str:
"x = {x + 1}"; full/nested exprs L-to-R; printable
parts; escape {{/}}, \" (details).
Scratch arenas reset per fn/iteration; escapes outlive via
older storage or copies. Carry is outer var in a
loop. Replacements last until region end; tip appends preserve
snapshots (budget; runtime).
Platform: cli
Agent platform (experimental): agent
DOCS. Root [package] platform defaults to
"cli" (details).
cli.stdout/stderr:
print/println (int, bool, str),
write(bytes), flush() →
unit. println adds LF; str
preserves NUL. Direct output interpolation allocates nothing.
Stderr is unbuffered (doesn't flush stdout); stdout is
TTY-line-buffered else lazy 64 KiB; normal exit/traps flush.
Capabilities (Cli, Clock,
Stdin, Stdout, Stderr,
Env, Fs, Net,
Process, File, Listener,
Conn) can be passed/stored, not constructed outside
platforms or concretely compared (opaque generic equality
allowed). Broken pipes exit 141 (output failures). Main
err prints error: <payload>\n and
exits 1; ok exits 0. CliError:
NotFound(str), Denied(str),
IsDirectory(str), Io(str),
Failed(str); ok() needs
unit (E0808).
cli.stdin/File: lines()
(str; bad UTF-8 traps), byte_lines(),
chunks(n) (n < 1 traps, E0901),
read_some(n) (single bounded read; empty at EOF),
byte_lines_max(n) →
result<vec<bytes>, CliError>
(for x in r.byte_lines_max(n)?; oversize →
Failed),
read_all()/read_text(). First three and
byte_lines_max(n)? are for heads (E0900
on bare reader; stream
details).
cli.fs: open(p) → File,
read(p) → bytes,
read_text(p) → str,
write(p, bytes) → unit,
list(p)/walk(p)/walk_pruned(p, skip)
→ vec<path>,
stat(p)/lstat(p) →
FileStat { kind: str, size: i64, mtime_ms: i64 }
(never opens FIFOs), mkdir(p) → unit
(0700) — all result except exists(p) →
bool. Ignoring fallible results is E0902.
f.close() is repeatable; later reads trap
file closed (mmap). bytes also
has
contains find starts_with ends_with count split lines words trim parse_i64.
Capabilities.
Fs.restrict(p) narrows roots →
result; read_only() denies writes; no_follow():
cwd snapshot, no links/empty paths, exact prefixes.
Net.restrict(hosts) narrows; none()
removes.
POSIX TCP:
net.listen(addr)/connect(addr) →
Listener/Conn results (TCP). HTTP/1.1: http
plugin.
cli.args: vec<str> /
raw_args: vec<bytes> omit program name (bad
UTF-8 traps at args).
cli.clock.now_ms() -> i64: monotonic ms.
cli.env.get(str) / get_bytes(str) →
option (static views). cli.exit(i64)
flushes stdout and diverges (outside 0..255 traps).
e.message() gets CliError text.
fn main(cli: Cli) -> result<unit, CliError> {
let p = path("out.txt")
cli.fs.write(p, "hi\n".bytes())?
cli.stdout.print(cli.fs.restrict(path("."))?.read_text(p)?)
}
hi
L2 path(str_or_bytes) wraps POSIX bytes: byte
equality, no +/printing (join, lossy
display); to_bytes is a view;
to_str, parent, file_name,
extension → option;
components → vec<path>;
is_absolute → bool. Absolute join RHS
replaces; no I/O or normalization (details).
Maps: map() creates map<K,V>
(keys: ints, bool, str, bytes, path, newtypes). get →
option<V>, get_or →
V, contains, len,
is_empty, keys/values →
vec.
set/update(k, init) { v -> … }
(L-to-R: map, key, init, block)/remove preserve
snapshots (set/update keep overwrite
order). Iteration uses frozen insertion-ordered snapshot; equality
ignores order. No indexing/printing. Last-use updates reuse
storage, else O(n) (details).
fn main(cli: Cli) -> result<unit, CliError> {
var seen: map<str, i64> = map()
seen = seen.set("a", 1)
cli.stdout.println(seen.get_or("b", 0))
}
0
cli.process.run(str, vec<str>) /
run_input(str, vec<str>, bytes) →
result<Output, CliError>
(Output { status: i64, stdout: bytes, stderr: bytes };
run uses /dev/null stdin).
stream(str, vec<str>) →
result<i64, CliError> flushes stdout, inherits
stdio. No shell; PATH lookup; default child SIGPIPE; status = code
or 128+signal. cwd(p), clear_env(),
env(k, v) configure child;
sandbox(fs, net) and
sandbox_roots(primary, extra_ro, net) restrict
children (policy).
limit(max_output, timeout_ms) caps output/timeout on
run/run_input (min-stacks
across sandbox; breach kills group and reaps).
call_plugin(name, bytes) uses exec_hash
(--dev allows PATH, W0995).
Toolchain
run compiles C and inherits stdio/exit;
run/interp/profile forward
args after --.
profile [--dev] [path] [--json] emits timing, arena
stats, hotspots, and copy/check reports.
build [-o <out>] writes an executable (default:
local stem). emit-c prints C
(-I runtime); emit-ir prints typed IR.
check [--assert-pure <fn>] [--assert-total <fn>]
checks syntax/types, purity (E1250), and transitive totality
(E1251). Uses $CC, else
cc/gcc.
build/run --debug|--profile: DWARF (debugging).
interp [--fuel N] [--record-caps <f> | --replay-caps <f>]
runs without C (except FFI; SQLite vendored
unless TENON_SQLITE=system) and records/replays caps
offline (E1255/E1256). Generator limits fixed (JSON traps).
eval runs pure exprs.
parse --dump <file.tn>: AST. Exits: 1
diagnostics, 2 usage/tool, 3 C/compiler bug.
gen [path] [--print|--write|--check]
inspects/writes/verifies derives (generators);
holes [path] [--json] lists todo(...).
plugins/plugin: details; script plugins.
version/help. VC.
fmt [--migrate-utf8] <path> formats in
place; fmt --check verifies canonical UTF-8 or
~1 (rules).
--diagnostics=json/--json emits JSON
diagnostics (registry).
test <dir> [--filter SUB] [--timeout-ms N],
--report=authority [--json], explain,
outline, edit replace-fn,
context <root.tn> 'path#fn name' --budget <bytes>:
tools.
Runtime traps
Bounds/slice/UTF-8 errors, overflow, div-by-zero, bad
shift/float casts, fuel/deadline expiry, todo(...),
and contract violations trap
(trap: <kind> at <file>:<line>:<col>
on stderr, exit 101 after stdout flush).
cli.traps: Traps (ceiling traps)
isolates traps via
traps.contain(job) -> result<J, Trapped> for
J: Contained (fn run(self) -> Self)
and traps.limit(fuel, deadline_ms). Unwinding
reclaims domain memory, closes domain files/sockets, and
kills+reaps child groups; cli.exit bypasses domains
(kinds &
domains).
Absent: exceptions, null, implicit conversions, global mutable
state, macros, reflection, tuples, char literals,
/* */, 1_000.
Agent workspaces: explicit vc policy uses trusted
TENON_VC_BIN. Ws.fork() and
Ws.commit(provenance, message) return results
(structured ownership: ADR-0169).