Trine language card
One page for writing correct Trine on the first try (people and AI agents). Every trine block below is checked by the test suite, and its output block is compared with a real run.
Shape of a program
# comments start with #; blocks are indented (2 spaces); no semicolons, no braces
type Shape =
| Circle(r: Float)
| Rect(w: Float, h: Float)
fn area(s): # types are inferred; annotations optional: fn area(s: Shape) -> Float
match s:
Circle(r) => 3.0 * r * r
Rect(w, h) => w * h
fn main():
let shapes = [Circle(1.0), Rect(2.0, 3.0)]
var total = 0.0 # `let` is immutable; `var` can be reassigned
for s in shapes:
total = total + area(s)
print(total)
print(format_float(total, 2))
9.0
9.00
Rules that differ from Python
- Ints are 64-bit and never wrap: overflow stops the program with an error.
/on Ints is floor division;%matches it. No implicit Int↔Float: usefloat(i),int(x). - Values, not references:
var b = athenb[0] = 9leavesaunchanged (copy-on-write, so it's free unless both are used). Functions can't change their arguments: return the new value. push(xs, x)returns the new list: writexs = push(xs, x)(in place whenxsis unique).ifandmatchare expressions:let y = if x > 0: 1 else: 2. The last expression of a function is its result (return xalso works).matchmust cover every case (or use_). Nonull: useOption(Some(x)/None);opt ?? defaultunwraps one (get(m, k) ?? 0).- Slices:
s[1:4],xs[:3],xs[2:](Lists and Strs; out of range is an error). Strings:find(s, "x")(an Option),replace(s, a, b),lower,upper(ASCII),trim,split,join. - Sorting:
sort(xs),sort_by(xs, fn((name, age)) => (-age, name))(stable; tuples compare element by element),reverse(xs),xs + ys. - Tuples:
let p = (1, "a"),let (n, s) = p,for (k, v) in pairs:,match p: (0, y) => ...; the type is written(Int, Str). They compare with==and work as map keys. - Loops:
for x in xs,for i in range(n),range(a, b),range(a, b, step),for _ in,for c in s(characters),for (i, x) in enumerate(xs),for (a, b) in zip(xs, ys),while cond.breakleaves the innermost loop,continueskips to its next round. - Comprehensions:
[x * x for x in xs if x > 0],[(i, j) for i in a for j in b],{w: len(w) for w in words}. - Updates:
x += 1(also-= *= /= %=),g[r][c] = v,(a, b) = (b, a + b). No negative indexes: the last element isxs[len(xs) - 1]. - Generators:
fn evens(n) yields Int:withyield i; the type is(Int) -> Gen[Int], consumed lazily byfor x in evens(10)(compiled to a plain loop when it can be). A function that just loops over its parameter takes any iterable:total : (a) -> Int where a: Iter[Int]accepts a List, Map (keys), Set or generator. - Booleans:
and,or,not;if / elif / else. - Indexing is bounds-checked:
xs[i]out of range stops the program with an error.
Types
Int Float Bool Str Unit · List[a] [1, 2] · Map[k, v] {"a": 1} · Set[a] set([1, 2]) · functions fn(x) => x + 1 · Option[a] · Result[a, e] · your own types, generic too: type Box[a] = Box(a). Map keys and set elements must be Int, Bool, Str, Unit, or lists and types made of them (not Float, not functions).
type Point = Point(x: Float, y: Float) # named fields
fn parse_pair(s: Str) -> Option[Point]:
let parts = split(s, ",")
if len(parts) != 2:
None
else:
let x = parse_float(trim(parts[0]))? # `?`: return None (or Err) early
let y = parse_float(trim(parts[1]))?
Some(Point(x: x, y: y))
fn main():
match parse_pair("1.5, 2"):
Some(p) => print(p.with(y: 0.0).x + p.y) # .field reads; .with(f: v) copies with changes
None => print("bad input")
print(parse_pair("oops"))
var counts = {}
for w in split("a b a c a", " "):
counts[w] = if w in counts: counts[w] + 1 else: 1
print(counts)
print(get(counts, "z")) # get(map, key) -> Option
3.5
None
{"a": 3, "b": 1, "c": 1}
None
Traits (shared behaviour)
trait Describe:
fn describe(self) -> Str
impl Describe for Int:
fn describe(self) -> Str: "the number " + str(self)
impl Describe for List[a] where a: Describe:
fn describe(self) -> Str: "a list starting with " + describe(self[0])
fn main():
print(describe([7, 8]))
a list starting with the number 7
Constants
const LIMIT = 10, const TABLE = build_table(LIMIT): UPPER_CASE names, computed once at compile time (any function may be called), used like values.
Modules
import "lib/geometry.tr" as geo (path relative to this file; as optional, default: the file's stem), then geo.area(s), geo.Shape, geo.Circle(1.0), geo.Circle(r) => in patterns. Only names marked pub (pub fn, pub type, pub trait) are visible.
Built-in functions
- Output:
print(x),print(a, b)(joined by spaces),str(x) - Numbers:
abs,min(a, b),max,sqrt,float,int,floor/ceil/round(to Int),pow,exp,log,sin...hypot,PI,TAU,E,format_float(x, digits);sum(xs),min(xs),max(xs)(a non-empty list),sum(xs, 0.0)(any list),sum(n, zero, fn(i) => term)(addstermfor i in 0..n-1) - Lists:
len,push,range(n)/range(a, b),grid(rows, cols, fn(r, c) => v),par_map(f, xs)(=[f(x) for x in xs]; native builds run it on all cores whenfandxshold no capability) - Tasks:
let t = spawn(fn() => work(x))...wait(t): runs alongside, behaves as if run at the spawn (same output order and errors). A task captures data or aNet(net(sys)); aConnmoves into it; never a Sys, Dir or function. It stays in its function (a list of tasks is fine).async fn fetch(n: Net, url: Str) -> ...: each call starts a task;await twaits (let ts = [fetch(n, u) for u in urls], thenawaiteach) - C:
extern fn hypot(x: Float, y: Float) -> Float(libm math always allowed; anything else needs--allow-c).extern "z" fn crc32(crc: Int, buf: List[Int], n: Int) -> Int: another library;Stris a C string,List[Int]bytes,vara buffer C writes (the call assigns the variable). Calls passing pointers go in anunsafe:block (docs/FFI.md) - Python:
py_start(sys)→Result[Py, Str](needs--allow-python);py_import(py, "pandas"),py_get(o, "name"),py_invoke(f, [Json args]),py_method(o, "m", args),py_index(o, key),py_ref(o)(an object as an argument),py_json(o)→Result[Json, Str],py_text(o)(docs/PYTHON.md); a script:python(dir, "helper.py")+py_call(py, "fn", "[json]") - Strings:
len(characters),chars,join(xs, sep),split(s, sep),trim,starts_with,ends_with;s[i]is a one-character string;ord(c)/chr(n)convert a character to and from its code point - Repetition:
"-" * 20,[0] * n - f-strings:
f"x = {x}, avg = {total / n:.2}"(any expression;:.N= Float decimals;{x:>8}/{x:<8}/{x:^8}= width and alignment,{x:>8.2}both;{{}}are braces; write{(e)}ifeitself starts with{) - Parsing:
parse_int(s) -> Option[Int],parse_float(s) -> Option[Float] - Maps and sets:
m[k](an error if the key is missing),get(m, k) -> Option,m[k] = v,keys,values,remove(m, k);set(xs),add(s, x),remove(s, x),union,intersection,difference;x in cfor lists, maps, sets, strings - Placeholder:
todo("what")has any type; reaching it stops with "not implemented: what"
Input and output need permission
There are no global files or environment. main(sys) receives the system capability; a function can only reach what it is passed, and its type says so. Run with grants: trine run app.tr --allow-read=data --allow-env=HOME -- arg1 arg2.
- Sys:
args(sys),env(sys, "NAME"),read_line(sys) -> Option[Str],read_all(sys),now(sys) -> Float(seconds),seed(sys) -> Int(OS entropy) - Random numbers (pure):
s = random(s)advances a generator state;random_below(s, n). Predictable: not for tokens, passwords or keys (CAPABILITIES.md) - Directories:
dir(sys, "path") -> Result[Dir, Str],read_file(d, name),write_file(d, name, text),append_file,read_lines(d, name),list_dir(d),subdir(d, name),readonly(d); big files:for line in each_line(open_lines(d, name)?) - Input lines:
for line in stdin_lines(sys) - Programs (
--allow-run=git):run(sys, ["git", "status"]) -> Result[(status, out, err), Str],run_input(sys, cmd, input); no shell - Network (
--allow-net=host):http_get(sys, url) -> Result[Str, Str](body of a 2xx),http_post(sys, url, body, type),http(sys, method, url, headers, body) -> Result[(status, headers, body), Str]; https:// via curl. TCP:tcp_connect(sys, host, port),tcp_send,tcp_read_line,tcp_read_all,tcp_close - No permission needed:
eprint(x)(standard error),exit(code) - Library (no import): JSON:
parse_json(s) -> Result[Json, Str],to_json,to_json_pretty,json_get(j, k),json_at(j, i),json_str/json_num/json_int/json_bool/json_list(Options);Json=JNull | JBool | JNum(Float) | JStr | JArr | JObj(Map). Time (UTC):format_time(t, "%Y-%m-%d %H:%M:%S"),parse_time(s, fmt) -> Option[Float],time_parts(t),make_time(y, mo, d, h, mi, s),weekday(t)(docs/LIBRARY.md)
All of these return Result/Option: failures are values. Limits for untrusted runs: --max-steps=N (calls + loop iterations, same count in every engine), --max-time=S, --max-mem=64M, --max-output=1M.
Tools
| command | what it does |
|---|---|
trine run f.tr | run (interprets at once, switches to a cached native build) |
trine check f.tr | type-check; prints every function's inferred type |
trine repl | interactive: definitions show their types, expressions their values and types |
trine fix f.tr [--apply] | show fixes for errors; --apply applies the most confident ones |
--json (any command) | errors as JSON lines on stderr: code, line, col, message, fixes (edits with line/col ranges and a confidence: certain, likely, placeholder) |
trine fmt f.tr | canonical layout (--check to verify); never changes meaning |
trine lint f.tr | warnings: unused variables/functions, var never reassigned (fixable with trine fix) |
trine doc f.tr | Markdown reference with every function's inferred type |
trine caps f.tr | which functions can reach the outside world |
trine test [files or dirs] | runs the test "name": blocks (assert(c), assert_eq(a, b) inside); output shown for failures, with the call stack |
trine hints f.tr | where native code borrows, shares, may copy, and still checks bounds |
trine build f.tr -o exe | native executable |
trine bounds f.tr | which index and overflow checks are proven unnecessary |
An agent loop: run trine check f.tr --json; apply a certain or likely fix, or decide on a change when fixes is empty; repeat until {"ok":true,...}.