On this page

Tenon idioms

One way per common job; LANGUAGE.md is the reference. Examples are complete UTF-8 Tenon programs; tenon fmt --migrate-utf8 converts legacy ~1 files.

Read lines

Stream stdin with for; it reads line by line and copies retained lines.

fn main(cli: Cli) -> result<unit, CliError> {
    var count = 0
    for line in cli.stdin.lines() {
        count += 1
        cli.stdout.println("{count}: {line}")
    }
}
1: a
2: b

Parse arguments

cli.args omits the program name. Print bad usage to stderr and exit nonzero.

fn main(cli: Cli) -> result<unit, CliError> {
    let args = cli.args
    if args.len() != 1 {
        cli.stderr.println("usage: double N")
        cli.exit(1)
    }
    let some(n) = args[0].parse_i64() else {
        cli.stderr.println("usage: double N")
        cli.exit(1)
    }
    cli.stdout.println(n * 2)
}
40

Count with a map

Reassign set; get_or supplies zero. Iteration follows first insertion. Last-use with/set updates reuse storage (--report=copies).

fn main(cli: Cli) -> result<unit, CliError> {
    var counts: map<str, i64> = map()
    for line in cli.stdin.lines() {
        for word in line.words() {
            counts = counts.set(word, counts.get_or(word, 0) + 1)
        }
    }
    for word, n in counts {
        cli.stdout.println("{word} {n}")
    }
}
a 2
b 1

Handle errors

Return result<T, CliError> and propagate with ?. Returning err from main prints error: <message> to stderr and exits 1.

fn parse(text: str) -> result<i64, CliError> {
    match text.parse_i64() {
        some(n) => ok(n),
        none => err(CliError.Failed("bad number: {text}")),
    }
}

fn main(cli: Cli) -> result<unit, CliError> {
    cli.stdout.println(parse("12")?)
    cli.stdout.println(parse("x")?)
}
12

Write output

Interpolate mixed values in println (zero allocation). Results go to stdout, messages to stderr, raw bytes via write. Normal exit, cli.exit, and traps flush stdout.

fn main(cli: Cli) -> result<unit, CliError> {
    let name = "total"
    cli.stdout.println("{name}: {1 + 2}")
    cli.stderr.println("done")
    cli.stdout.write("raw\n".bytes())
}
total: 3
raw

Sandbox a process

A host list fails closed; print the error kind, not platform text.

fn main(cli: Cli) -> result<unit, CliError> {
    let net = cli.net.restrict(["example.com"])?
    let child = cli.process.sandbox(cli.fs.read_only(), net)
    match child.run("/bin/true", []) {
        ok(_) => cli.stdout.println("unexpected success"),
        err(e) => match e {
            Denied(_) => cli.stdout.println("Denied"),
            NotFound(_) | IsDirectory(_) | Io(_) | Failed(_) => cli.stdout.println("other error"),
        },
    }
}
Denied

Read a file

Validate arguments, open path, and stream.

fn main(cli: Cli) -> result<unit, CliError> {
    if cli.args.len() != 1 {
        cli.stderr.println("usage: count FILE")
        cli.exit(1)
    }
    let file = cli.fs.open(path(cli.args[0]))?
    var count = 0
    for line in file.lines() {
        count += 1
    }
    file.close()
    cli.stdout.println(count)
}
2

Split fields

split keeps empty fields as views. Check field count before indexing; return errors for bad lines or numbers.

fn main(cli: Cli) -> result<unit, CliError> {
    var total = 0
    for line in cli.stdin.lines() {
        let fields = line.split(",")
        if fields.len() != 2 {
            return err(CliError.Failed("bad line: {line}"))
        }
        let some(n) = fields[1].parse_i64() else {
            return err(CliError.Failed("bad number: {fields[1]}"))
        }
        total += n
    }
    cli.stdout.println(total)
}
3

Write prompts and schemas

Use interpolated strings ("{var}", escaping {{/}}) or [embed.m] asset files for multi-line prompts, JSON schemas, and HTML.

Serve web pages

Use web: notes, deploy.

Organize modules

One file per module (import ids { UserId, user_id } loads ids.tn); export with pub. For opaque IDs, declare pub type UserId = new i64 with pub fn user_id(n: i64) -> UserId; .value stays file-private.

Callbacks and dyn dispatch

Use <T: I> for static dispatch, fn(…) for callbacks, and vec<dyn I> / map<str, dyn I> for heterogeneous registries.

Bridge packages

A third package can impl another package's interface for a second package's type (import bridge loads it). Coherence is global; duplicate versions are E0939 (ADR-0027, ADR-0077).

Packages a, b, c expose lib (import a { Area } selects a.lib):

deps/a/lib.tn:

pub interface Area {
    fn area(self) -> i64
}

deps/b/lib.tn:

pub struct Square { side: i64 }

deps/c/lib.tn:

import a.lib { Area }
import b.lib { Square }

impl Area for Square {
    fn area(self) -> i64 = self.side * self.side
}

app/main.tn:

import a.lib { Area }
import b.lib { Square }
import c

fn main(cli: Cli) -> result<unit, CliError> {
    let square = Square { side: 4 }
    cli.stdout.println(square.area())
}

Derive codecs

Discover plugins with tenon plugins index [dir] and tenon plugins docs main.tn.

Declare codec = { edition = "2026" } under [dependencies] in tenon.toml (105 bundled plugins) or //! deps = ["codec"] in a #! script. Run tenon fetch once in packages to lock offline sources. Opt in each named type (and nested children) in main.tn:

import codec.json { Json }
import codec.binary { Binary }

struct Point { x: i64, y: i64 }
derive Json for Point
derive Binary for Point

fn main() {}
tenon check main.tn
tenon gen --print main.tn

Derives materialize implicitly in cache on check/test/run/build; inspect with tenon gen --print or tenon view --generated, or write committed gen/ companions with tenon gen --write (--check verifies). Encode with point_to_json(p) / point_to_binary(p); decode with point_from_json(text.bytes()) / point_from_binary(data). Match codec errors explicitly. See wire rules.

Write a plugin

Scaffold and validate a generator or library:

tenon plugin new generator my_gen
cd my_gen
tenon plugin check