The Trine language, version 1.0
Frozen (M9, 2026-12-04). This is the language Trine 1.0 compiles. From here on it changes only by adding (new built-ins, new library functions, new syntax that was an error before) or through a new edition (§6) that a package opts into, with an automatic migration. What is stable, and what isn't, is in COMPATIBILITY.md.
This is the reference: what is a program, what is well-typed, what a program means. The card (CARD.md) teaches; this document decides. Where the implementation and this text disagree, that is a bug in one of them; tests/golden.rs (spec_lists_every_keyword_and_builtin) checks that every keyword, operator and built-in function the compiler knows is defined here.
Two editions exist: 0.9 (the language before 1.0; the default for a file whose package names none) and 1.0 (§6). They differ only in §1.4.
Notation: EBNF. x? optional, x* repetition, x+ one or more, 'tok' a literal token, NEWLINE INDENT DEDENT layout tokens (§1.3).
1. Lexical structure
1.1 Characters and comments
Source is UTF-8. # starts a comment to the end of the line (outside strings). Tabs are not allowed in indentation. Lines end at \n (a \r before it is dropped).
1.2 Tokens
int = digit (digit | '_')* -- '_' separators ignored; must fit in 64 bits
float = digit (digit | '_')* ('.' digit (digit | '_')*)? exp? -- needs '.' or exp; `1.` is Int then '.'
exp = ('e' | 'E') ('+' | '-')? digit+ -- 1e9, 2.5e-3 (always a Float)
string = '"' (char | escape)* '"' -- escape: \n \t \r \" \\ ; no newline inside
fstring = 'f"' (char | escape | '{{' | '}}' | '{' expr (':' spec)? '}')* '"'
spec = ('<' | '>' | '^')? digit* ('.' digit+)? -- align, width, decimals: {x:>8.2}
ident = (letter | '_') (letter | digit | '_')*
Keywords: fn let var if elif else while for in return break continue match type trait impl where true false and or not, and _. Contextual words (identifiers except in these positions): import, as, pub, const, extern, yields, yield, with.
Operators and punctuation: ( ) [ ] { } , : -> => = == != < <= > >= + - * / % | . ?, and the updates += -= *= /= %=.
1.3 Layout
Indentation is significant, as in Python. At the start of each non-blank, non-comment line outside brackets, the lexer compares its indentation with a stack of open widths: deeper pushes and emits INDENT; shallower pops, emitting one DEDENT per level, and must land exactly on an open width ("inconsistent indentation" otherwise). Each logical line ends with NEWLINE. Inside ( [ { newlines and indentation are ignored. At the end of input all open levels are closed.
The canonical token stream is printed by trine tokens FILE; selfhost/lexer.tr is a second, independent implementation of this section and is tested to agree byte for byte.
1.4 Contextual and reserved words
async, await, test and unsafe start their constructs only where they can: async before fn, await before a name or (, test at the start of a line before a string, unsafe at the start of a statement before :. In edition 0.9 they are ordinary names everywhere else. In edition 1.0 they are reserved: as the name of a variable, parameter, function or type they are a syntax error ("test is a keyword in edition 1.0"). They stay allowed after . (a field, or a function of a module, which may be of another edition) and as a field name before : in a constructor call, a type's fields or .with(...), since field names show when a value prints.
2. Grammar
2.1 Programs and items
program = (item | NEWLINE)*
item = 'pub'? (fndef | typedef | traitdef | constdef | externdef)
| impldef | import | testdef
testdef = 'test' string ':' block -- run by `trine test`, never called
import = 'import' string ('as' ident)? NEWLINE
fndef = 'fn' ident params ('->' type)? ('yields' type)? where? ':' block
params = '(' (param (',' param)*)? ')'
param = ident (':' type)?
where = 'where' ident ':' name (',' ident ':' name)*
typedef = 'type' ident ('[' ident (',' ident)* ']')? '=' variants
variants = '|'? variant ('|' variant)*
| NEWLINE INDENT ('|' variant NEWLINE)+ DEDENT
variant = Ident ('(' fields? ')')?
fields = field (',' field)* -- all named or none
field = (ident ':')? type
traitdef = 'trait' Ident ':' NEWLINE INDENT (sig NEWLINE)+ DEDENT
sig = 'fn' ident '(' 'self' (',' param)* ')' ('->' type)?
impldef = 'impl' name 'for' type where? ':' NEWLINE INDENT fndef+ DEDENT
constdef = 'const' UPPER (':' type)? '=' expr NEWLINE
externdef = 'extern' string? 'fn' ident '(' (xparam (',' xparam)*)? ')' ('->' type)? NEWLINE
xparam = ident ':' 'var'? type -- string: the C library ("z"); see docs/FFI.md
unsafe = 'unsafe' ':' block -- a statement: may call externs that take pointers
type = name ('[' type (',' type)* ']')?
| '(' (type (',' type)*)? ')' '->' type
name = ident ('.' ident)? -- `mod.Name` for an imported module's names
2.2 Blocks and statements
block = expr | target '=' expr -- on the same line
| 'break' | 'continue' | 'return' expr? -- on the same line too: `if x < 0: break`
| NEWLINE INDENT stmt+ DEDENT
stmt = ('let' | 'var') ident (':' type)? '=' expr NEWLINE
| ('let' | 'var') tuplepat '=' expr NEWLINE -- destructuring (§3.10)
| target '=' expr NEWLINE -- target: ident ('[' expr ']')* | tuple of targets
| target ('+=' | '-=' | '*=' | '/=' | '%=') expr NEWLINE -- `t += e` is `t = t + e`
| 'while' expr ':' block
| 'for' (ident | '_' | tuplepat) 'in' expr ':' block -- a List, Map, Set, Str (its characters) or generator
| 'return' expr? NEWLINE
| 'break' NEWLINE -- only inside a loop (§4)
| 'continue' NEWLINE
| 'yield' expr NEWLINE -- only in a generator (§3.7)
| expr NEWLINE
2.3 Expressions (lowest precedence first)
expr = or
or = and ('or' and)*
and = not ('and' not)*
not = 'not' not | cmp
cmp = coalesce (('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in') coalesce)? -- no chaining
coalesce = add ('??' coalesce)? -- `opt ?? default`, grouped to the right
add = mul (('+' | '-') mul)*
mul = unary (('*' | '/' | '%') unary)*
unary = '-' unary | postfix
postfix = primary ( '(' args? ')' | '[' expr ']' | '[' expr? ':' expr? ']' | '.' ident
| '.' 'with' '(' named ')' | '?' )* -- '[a:b]': a slice (§4)
args = expr (',' expr)* (',' ident ':' expr)* | ident ':' expr (',' ident ':' expr)*
primary = int | float | string | fstring | 'true' | 'false' | ident
| '(' ')' | '(' expr ')'
| '(' expr (',' expr)+ ','? ')' -- a tuple
| '[' (expr (',' expr)*)? ']'
| '[' expr comp+ ']' -- list comprehension
| '{' (expr ':' expr (',' expr ':' expr)*)? '}'
| '{' expr ':' expr comp+ '}' -- map comprehension
| 'fn' params '=>' expr -- lambda
| 'if' expr ':' block ('elif' expr ':' block)* ('else' ':' block)?
| 'match' expr ':' NEWLINE INDENT (pattern '=>' (expr | block) NEWLINE?)+ DEDENT
pattern = '_' | '-'? int | string | 'true' | 'false' | ident | '(' ')'
| Name ('(' pattern (',' pattern)* (',' ident ':' pattern)* ')')?
| '(' pattern (',' pattern)+ ')' -- a tuple
tuplepat = '(' tp (',' tp)+ ')' tp = ident | '_' | tuplepat
comp = 'for' (ident | '_' | tuplepat) 'in' expr | 'if' expr
An identifier starting with an uppercase letter in a pattern is a constructor; lowercase binds. elif/else may start the next line at the same indentation. Operator chains and nesting are bounded (resource limits of the parser; the error says so).
Desugarings (done by the parser, so later stages never see them): f-strings become + of str(...) / format_float(x, N) (padded by #pad for a width); const becomes a literal; extern fn becomes a function whose body calls #extern; yield e becomes #yield(e); trait methods get dispatchers. A comprehension [e for x in xs if c] becomes a loop that pushes onto a hidden list (clauses nest left to right, as in Python), inside a block expression, so ? and return in e act on the enclosing function; {k: v for ...} assigns m[k] = v instead. opt ?? d becomes match opt: Some(v) => v; None => d (d is evaluated only for None; opt must be an Option). The pattern () matches the unit value. t op= e becomes t = t op e (the target, indexes included, is read, then written). g[i][j] = v evaluates v, then the indexes left to right, then takes row g[i] out, assigns into it and puts it back (in place when g is unique). print(a, b, ...) prints the parts' str joined by spaces (print() prints an empty line). sum(xs), sum(xs, start), min(xs) and max(xs) become loops at the call site: sum(xs) and min/max start from the first element (an empty list is an error: sum(xs, 0.0) gives a start value).
3. Static semantics
3.1 Types
Base types Int Float Bool Str Unit; List[a], Map[k, v], Set[a]; function types (a, b) -> c; Option[a] (Some(x), None) and Result[a, e] (Ok(x), Err(e)) from the prelude; user types from type; tuples (a, b, ...) (§3.10); capabilities Sys, Dir, Py (§3.6); generators Gen[a]. There is no null, no subtyping and no implicit conversion (float(i), int(x), str(x)).
3.2 Inference
Hindley–Milner with let-polymorphism at top-level functions: every function gets the most general type its body allows (trine check prints it). Annotations are optional and only ever restrict. Lambdas, let and var are monomorphic. Mutually recursive functions are typed together (strongly connected components of the call graph).
3.3 Operators
+ is defined on Int, Float, Str and List (concatenation); - * / % on Int and Float (both sides the same type); s * n and xs * n (a Str or List known to be one where the * is checked, times an Int) repeat it n times ("-" * 20, [0] * n; n <= 0 gives an empty one); comparisons < <= > >= on Int, Float, Str; == != on any type except functions and capabilities (structural); in tests membership in List, Map (keys), Set, and Str (substring); and or not on Bool. x? on Option/Result returns early from the enclosing function with the None/Err; the function's own result must be the same kind.
3.4 Traits
trait T: declares methods whose first parameter is self; impl T for Type: provides them. A function using a method on a type variable gets a where a: T requirement, inferred or written. Built-in traits: Num (Int, Float), Add (Int, Float, Str, List), Ord (Int, Float, Str, and tuples of comparable elements, compared element by element), Sized (len), Seq (List or Str: slices), Key (map keys / set elements: no functions, capabilities or Floats), Iter[e] (what for x in c needs of a c whose type isn't known: List[e], Set[e], Gen[e], or Map[e, v], which loops over its keys; inferred only, not written). Capabilities can't implement traits. Calls are specialized when the type is known (no dispatch at run time).
3.5 Values, records and ownership
All values are immutable values (copy-on-write): assignment and argument passing never create aliasing visible to the program. var rebinds a name; xs[i] = v and push produce the new value (in place when not shared). Records are single-variant types with named fields: p.x reads, p.with(x: 1.0) copies with changes. Pattern matching must be exhaustive.
3.6 Capabilities
main(sys) receives the only Sys; no expression can create one. Outside-world operations take a capability: args env read_line read_all now seed dir run run_input net tcp_connect http py_start (net(sys) gives a Net: http and tcp_connect take a Sys or a Net) take Sys; read_file write_file append_file list_dir subdir readonly open_lines python take a Dir; next_line takes the Lines that open_lines gives; tcp_send tcp_read_line tcp_read_all tcp_close take the Conn that tcp_connect gives; py_call takes a Py. Sys Dir Lines Conn Py are the capability types: they can't be compared, hashed or given trait impls. A function whose parameters' types can't contain a capability or a function can't affect the outside world; trine caps reports this per function and per module. Grants (--allow-read, --allow-write, --allow-env, --allow-run, --allow-net, --allow-python, --allow-c) decide at run time which capabilities can be obtained and what they can reach (docs/CAPABILITIES.md). print, eprint (standard error) and exit need no capability.
3.7 Generators
fn f(...) yields T: has type (...) -> Gen[T]; its body has type Unit and may use yield e with e : T. yield anywhere else (including lambdas) is an error. for x in g accepts Gen[T] with x : T.
Dynamically: calling a generator runs nothing and returns the generator value (one step, as a call). for x in g runs g's body from the start; each yield v runs the loop body with x = v (one step), then the generator continues. A return in the loop body leaves the loop's function; a return in the generator ends the loop. A continue in the loop body ends that round (the generator goes on to its next yield); a break stops the generator there, and the program carries on after the loop. Generators can't be compared with ==.
3.8 Tasks
spawn(f) with f : () -> T returns a Task[T]; wait(t) returns the T. The argument is a lambda or the name of a function without parameters. Rules, checked statically:
- Isolation (what a task may hold, so tasks can't race): a lambda passed to
spawncan capture data, aNet(shared freely), or aConn/Lines(or a value holding one), which moves into the task: the function can't use it after thespawn, and aspawninside a loop can't take one bound outside the loop. It can't capture aSys, aDir, aPy, a function value or a task. - A task stays in the function that spawned it:
Taskcan't appear in a function's parameter or result types, inside another type other than a list (List[Task[T]]is allowed; anOption[Task[T]]is not), or among a lambda's captures.
async fn f(params) -> T: body declares an ordinary function whose calls start tasks: f(a, b) evaluates the arguments, then is spawn(fn() => f(a', b')) (so the arguments follow the isolation rules) and has type Task[T]. await e is wait(e). An async function can't be used as a value, can't be a generator, and main can't be async.
Dynamically, a program with tasks behaves exactly as if each task ran to completion at its spawn: same output in the same order, same error (and nothing the program did after a failed spawn is visible), exit(n) included. Native code runs tasks on their own threads; a task that hasn't been waited for is joined when it is dropped, at the latest when its function returns. Tasks can't be compared with ==. One relaxation: network operations (through a Net or a moved Conn) in a task may happen while earlier tasks are still running, so a server can see requests in a different order, and requests of later tasks may have been sent when an earlier task fails; what the program prints, and the error it reports, are still exactly the sequential ones.
3.9 Modules
import "path.tr" as m makes the module's pub names available as m.name (functions, types, constructors, traits). A module has no authority of its own. Import cycles are errors.
3.10 Tuples
(e1, e2, ...) (two or more elements) has type (T1, T2, ...); the same syntax is the type in annotations (fn f(p: (Int, Str)) -> (Int, Int)); (T) is just T and () is Unit. A tuple is a data value like a one-constructor type: ==, map keys and set elements work when its elements do, and match can take it apart ((0, y) => ...); a match on a tuple needs a catch-all arm unless one arm matches everything. It prints as it is written: (1, "a").
A parameter may be a tuple too: fn((name, age)) => age, fn area((w, h)): w * h.
let (a, (b, _)) = e and var (a, b) = e bind each name to its part (var makes each one mutable); for (k, v) in xs: takes each element apart. Only names, _ and nested tuples may appear there (other patterns could fail to match: use match). The parser rewrites them to one let per name.
3.11 C functions
extern fn name(params) -> T declares a function of the C library or libm; extern "lib" fn one of another library. A parameter is Int (int64_t), Float (double), Bool (int), Str (a NUL-terminated copy), List[Int] (bytes, each 0 to 255), var List[Int] (bytes C writes) or var Int (an int64_t C writes); the result is one of Int Float Bool Unit, Str (copied; NULL is a runtime error) or Option[Str] (NULL is None). A call passes var arguments as variables, which it assigns afterwards. A call to an extern whose signature has a Str, a byte list or a var (or a string result) must be inside an unsafe: block, and such a function can't be used as a value. A buffer that C writes past (into the 256 guard bytes after it) is a runtime error. Calling any C function but the pure math ones needs --allow-c (FFI.md).
3.12 Tests
test "name": block declares a test: type-checked with the file, never called by the program; trine test runs each one on its own (TESTING.md). Two tests in a file can't share a name.
4. Dynamic semantics
- Evaluation is strict, left to right (arguments, operands, list/map literals, fields).
- Int is 64-bit two's complement and never wraps: overflow is a run-time error.
/on Ints is floor division and%its matching remainder (sign of the divisor); dividing by zero is an error. Float is IEEE-754 double; comparing NaN with< <= > >=is an error. - Slices:
x[a:b]is a new List or Str holding elements (characters)atob - 1ofx;x[:b]starts at 0 andx[a:]runs to the end. They need0 <= a <= b <= len(x): anything else is an error (slice [2:9] is out of bounds for a string of length 5), as an index out of range is. A slice of a Map or Set is a type error. - Indexing is bounds-checked; out of range is an error (the native compiler removes checks it proves unnecessary, never changing behavior).
print(x)writesstr(x)and a newline. Strings are sequences of Unicode characters:len(s)counts characters,s[i]is a one-character string.- Maps and sets iterate in insertion order.
forover a Map yields its keys, over a Str its characters. - There are no negative indexes:
xs[-1]is out of bounds (the message says so). breakleaves the innermostwhileorforaround it;continuegoes on to its next round (the next test of awhile, the next element of afor). Both must be inside a loop of the same function: a lambda's body is a function of its own. Likereturn, they produce no value, solet x = if c: break else: 1is fine. After abreak, aforloop does not make its final "no more elements" test (one step fewer than a loop that runs out).- A program's observable behavior (output, errors, exit status) is the same on every engine: the interpreter, the VM and native code (the conformance suite enforces this).
- A runtime error is reported with its call stack under it (
inf`, thencalled fromgat file:line:col` for each call in progress, a run of the same call counted, at most 12 lines): the same on the interpreter, the VM and native debug builds. Release native builds leave the stack out (recording it costs optimizations). assert(c),assert(c, why)andassert_eq(a, b)check at the call: a failure is a runtime error there (assertion failed: 3 != 4). A program may define its ownassert.- Resource limits (
--max-steps,--max-mem,--max-time,--max-output) stop a run with an error; a step is a call or a loop test, counted identically by every engine.
5. Built-in functions
Output and conversion: print str float int format_float. Numbers: abs min max sqrt sum (min(a, b), max(a, b); sum(n, zero, f) adds f(i) for i in 0..n; over a list, sum(xs), sum(xs, start), min(xs), max(xs), §2.3). Math on Float: floor ceil round (to Int), pow exp log log2 log10 sin cos tan asin acos atan atan2 hypot; pow(a, b) on Ints is exact (an overflow is an error; a negative exponent is an error). Constants PI TAU E are Floats (a program's own definition of the name wins). Lists: len push range grid par_map sort sort_by reverse enumerate zip: range(n), range(a, b), range(a, b, step) (a step of 0 is an error); enumerate(xs) is [(0, x0), (1, x1), ...] and zip(xs, ys) pairs elements up to the shorter length (both are library functions written in Trine, added when a program uses them and doesn't define them itself); sort(xs) orders the elements ascending; sort_by(xs, key) orders them by key(x), calling key once per element, left to right (a tuple key sorts by several things: sort_by(people, fn((name, age)) => (-age, name))). Both are stable (equal elements keep their order) and need comparable elements or keys (a NaN is an error, as for <). reverse(xs) is the list backwards; xs + ys is a new list, xs then ys. Strings: chars join split trim starts_with ends_with ord chr parse_int parse_float find replace lower upper: find(s, sub) is Some(index) of the first sub in characters, or None; replace(s, old, new) replaces every old, left to right (an empty old is an error); lower and upper change the ASCII letters A-Z / a-z only (the same everywhere: no locale or Unicode case tables). Collections: get keys values remove add set union intersection difference. Tasks: spawn wait (§3.8). Capabilities: args env read_line read_all now seed dir read_file write_file append_file list_dir subdir readonly open_lines next_line run run_input tcp_connect tcp_send tcp_read_line tcp_read_all tcp_close http python py_call (§3.6; types and messages in docs/CAPABILITIES.md). run(sys, [prog, args...]) and run_input(sys, cmd, input) give (status, output, errors); http(sys, method, url, headers, body) gives (status, headers, body) with header names in lower case. Output: eprint(x) prints to standard error; exit(code) ends the program with status code (0 to 255). Randomness: random random_below (pure SplitMix64 on a seed; not cryptographically secure). Placeholders: todo(msg) type-checks as anything and fails when run.
5.1 The library
Some functions are written in Trine and added to a program that uses one of their names (docs/LIBRARY.md): enumerate, zip; JSON (Json, parse_json, to_json, to_json_pretty, json_get json_at json_str json_num json_int json_bool json_list); time in UTC (time_parts, make_time, weekday, format_time, parse_time); files, input and HTTP (read_lines, each_line, stdin_lines, http_get, http_post). A group is added whole, so a program that uses a group and also defines one of its names is an error (rename yours); a program that defines every name it uses from a group keeps its own (its own enumerate wins). Messages in library code name its file, <library>/json.tr.
6. Editions
A package declares its edition in trine.toml ([package] edition = "1.0"); every file in the package is read by that edition's rules. A file outside any package, or in one that names no edition, is read as 0.9 unless --edition says otherwise. Packages of different editions work together: an edition only changes how a file is read, never what a definition means, so a definition's hash (HASHING.md) is the same in every edition.
trine migrate [path] [--to EDITION] [--check] moves a package to an edition: it rewrites every file (for 1.0: reserved words used as names get a _ suffix, avoiding names already in the package), loads each file before and after, and writes nothing unless every definition has the same hash afterwards, under its old name or its new one. Then it sets edition.
| edition | differences from the one before |
|---|---|
0.9 | (the first) |
1.0 | async await test unsafe are reserved (§1.4) |