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

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

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.

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

commandwhat it does
trine run f.trrun (interprets at once, switches to a cached native build)
trine check f.trtype-check; prints every function's inferred type
trine replinteractive: 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.trcanonical layout (--check to verify); never changes meaning
trine lint f.trwarnings: unused variables/functions, var never reassigned (fixable with trine fix)
trine doc f.trMarkdown reference with every function's inferred type
trine caps f.trwhich 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.trwhere native code borrows, shares, may copy, and still checks bounds
trine build f.tr -o exenative executable
trine bounds f.trwhich 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,...}.