Sn Tin

Reference

The language

Everything Tin has, on one page. Every example here is compiled and run when the docs are built.

Programs

A program is one .tin file. It starts at fn main(). Everything else in the file is a declaration: functions, types, constants and agents. Declarations can appear in any order.

// A line comment.
/* A block comment. */

let GREETING = "Hello"            // a top-level constant

fn greet(name: string): string => "{GREETING}, {name}!"

fn main() {
  print(greet("Tin"))
}
Hello, Tin!

A comment that starts with /// is a doc comment. On a tool fn, its parameters, and the fields of a type, doc comments become the descriptions a model reads (see Agents and tools).

Variables and values

let names a value that never changes. var names one that can be reassigned or changed in place. Types are inferred; write one after the name when it helps.

let name = "Ada"            // string
var count = 0               // int
let ratio: float = 1        // an annotation: the literal becomes a float
count += 1
count = count * 10
print("{name} {count} {ratio}")
Ada 10 1.0
let total = 0
total = total + 1
error: 'total' is immutable
 --> main.tin:2:1
  |
2 | total = total + 1
  | ^^^^^
  = note: declare it with `var total = ...` to allow reassignment
  = fix: declare total with var

A later let with the same name shadows the earlier one. A block { ... } is an expression: its value is its last expression.

let x = 2
let x = "now a string"
let area = {
  let w = 3
  let h = 4
  w * h
}
print("{x}: {area}")
now a string: 12

Arrays and structs are values

Assigning an array or a struct, passing it to a function, or capturing it in a lambda gives the receiver its own copy. Nothing changes behind your back: a function cannot alter its caller's data unless the parameter is marked inout, and then the caller must pass a var and mark it with &, so every call that changes something says so: addZero(&a). A method call on a var (a.push(1), counts.set(k, v)) needs no mark.

fn withZero(xs: int[]): int[] {
  var copy = xs
  copy.push(0)
  copy
}

fn addZero(xs: inout int[]) {
  xs.push(0)                // changes the caller's variable
}

fn main() {
  var a = [1, 2]
  let b = a                 // b is its own array
  a.push(3)
  print("{a} {b}")

  print(withZero(b))
  print(b)                  // unchanged

  addZero(&a)
  print(a)
}
[1, 2, 3] [1, 2]
[1, 2, 0]
[1, 2]
[1, 2, 3, 0]
let fixed = [1, 2]
addZero(&fixed)
error: cannot call 'addZero', which changes its argument: 'fixed' is immutable
 --> main.tin:2:10
  |
2 | addZero(&fixed)
  |          ^^^^^
  = note: declare it with `var fixed = ...` to change it
  = fix: declare fixed with var

Today's cost: the copy is made eagerly whenever a value enters or leaves a var. Passing a value to a function, and binding it in a loop or a match, borrows it instead, so most code copies little. Copy-on-write is a possible later optimisation (DESIGN.md says when); it would not change what programs print.

Types

TypeWhat it isExample
int32-bit signed integer. Overflow is an error, never a silent wrap.42, -7, 0xff, 1_000_000
i6464-bit signed integer, checked the same way. Convert with i64(x) and int(x) (which panics if the value doesn't fit). A model sees it as a decimal string, so it stays exact; JavaScript gets a BigInt.let ns: i64 = 1_731_660_000_000_000_000
float64-bit floating point.3.14, 1e-9
booltrue or false.true
stringImmutable UTF-8 text."hi {name}"
DurationA length of time. Not a number.250ms, 1.5s, 2min
T[]A growable array of T.[1, 2, 3]
(A, B)A tuple: items read as t.0, t.1, or bound with let (a, b) = t.(1, "one")
(A, B) => CA function value.(x: int) => x + 1
Option<T>A value that may be missing.Some(3), None
Result<T, E>Success or failure.Ok(3), Err("no")
Map<K, V>An insertion-ordered map. m[k] reads (panics if k is missing; m.get(k) gives an Option), m[k] = v sets, for k, v in m walks it. A hash map; its storage is hidden.newMap(), mapOf([("a", 1)])
Set<T>Distinct values in insertion order: add, has, remove, for x in s.newSet(), setOf([1, 2])
Task<T>A running task that will produce a T.spawn work()
AgentAn agent value.agent { ... }
voidNo value. Only used as a return type.

You declare your own types with type: structs and sum types. Type names start with an uppercase letter.

Numbers

Tin never converts between int and float for you. Convert with float(x) and int(x) (which truncates toward zero). The one convenience: an integer literal next to a float is read as a float.

let n = 7
let half = float(n) / 2        // 2 is a literal, so it adapts
print(half)
print(int(half))
print(7 / 2)                   // integer division
print(7 % 2)
print(2.0 * 3)
3.5
3
3
1
6.0
let n = 7
print(n * 1.5)
error: '*' needs both sides to have the same type, found int and float
 --> main.tin:2:7
  |
2 | print(n * 1.5)
  |       ^^^^^^^
  = note: Tin never converts numbers silently: use float(x) or int(x)
  = fix: wrap it in float(...)

Integer +, - and * are checked. Overflow in constants is a compile error; at run time it is a panic. Dividing by zero is a runtime error.

var big = 2147483647
print(big + 1)
panic: integer overflow
Operators, loosest firstWorks on
|>a value and a function: x |> f(y) is f(x, y)
||bool; the right side runs only if needed
&&bool; the right side runs only if needed
== != < > <= >=numbers, strings, durations and frequencies; == and != also on bool and, structurally, on arrays, structs and enums (equal when their parts are)
& | ^, x.shl(n), x.shr(n)bitwise, on int and i64; they bind tighter than comparisons, and a shift count outside the type's bits panics
+ -numbers, durations; + joins strings
* / %numbers (% is int only)
-x !x await spawnprefix
f(x) a[i] a.b x?postfix

Strings

Anything inside { } in a string is an expression, converted with the same rules as print. Every type can be printed, including your own structs and sum types.

let p = Point { x: 1, y: 2 }
print("p is {p}, twice x is {p.x * 2}, and {if p.y > 1 { "y is big" } else { "y is small" }}")
print("a literal brace: \{ and a tab:\tdone")
print("len counts bytes: {"héllo".len}")
p is Point { x: 1, y: 2 }, twice x is 2, and y is big
a literal brace: { and a tab:	done
len counts bytes: 6

Escapes are \n, \t, \r, \0, \\, \", \{, \} and \u{e9} (a Unicode code point in hex). Positions and len count bytes: s.chars() gives the characters as a char[], and s.charAt(i) gives the character that starts at byte i, as a string. Strings are compared with == and ordered with < byte by byte. The string functions are in the standard library.

Formatting

A hole can end with a format spec after a colon: "{x:spec}". The spec is [[fill]align][0][width][.precision][type], as in Python and Rust. .2 rounds a float to 2 decimals (and cuts a string to 2 characters); a width pads to that many characters, numbers to the right and everything else to the left unless <, > or ^ says otherwise; a character before the alignment is the fill; 0 pads a number with zeros after its sign; ? shows the value as it appears inside an array (strings quoted); x, X and b write an int in hex, upper-case hex or binary. A colon inside brackets, a lambda or a string in the hole is not a spec.

let pi = 3.14159
print("{pi:.2} [{42:>6}] [{42:06}] [{"ab":^6}] [{7:*<4}] {255:x} {5:b} {"tin":?}")
for row in [("arm", 0.923), ("rover", 0.4)] {
  print("{row.0:<8}|{row.1:>6.2}")
}
3.14 [    42] [000042] [  ab  ] [7***] ff 101 "tin"
arm     |  0.92
rover   |  0.40
print("{3:.2}")
error: precision (.2) is for floats and strings, found int
 --> main.tin:1:11
  |
1 | print("{3:.2}")
  |           ^^
  = note: an int has no decimals: {n} or {float(n):.2}

Characters

A char is one Unicode character, written in single quotes: 'a', 'é', '\n', '\'', '\u{1F600}'. It is not a number and not a string: int(c) is its code point, char(n) turns a code point back (and panics for one that is not a character), str(c) or "{c}" makes text, and fromChars(cs) joins a char[]. Chars compare with == and < by code point, can be matched, and work as Map keys and in Sets. isDigit, isLetter, isSpace, isUpper, isLower, upper and lower are ASCII-based.

let cs = "héllo".chars()
print(cs.len)
print(cs[1])
print(cs.filter((c) => c != 'l'))
print(fromChars(cs.map((c) => c.upper())))
print(int('A') + 1)
5
é
['h', 'é', 'o']
HéLLO
66
let c = 'x'
print(c == "x")
error: '==' compares a char with a string
 --> main.tin:2:7
  |
2 | print(c == "x")
  |       ^^^^^^^^
  = note: a char is written in single quotes: 'a'; or turn the char into text with str(c)
  = fix: use the char 'x'

Durations

A number with a unit is a Duration: us, ms, s, min or h. Units are part of the type, so a duration only combines with numbers in ways that keep the unit meaningful.

let tick = 250ms
print(tick + 1s)          // Duration + Duration
print(tick * 4)           // Duration * number
print(1s / tick)          // Duration / Duration is a plain float
let n = 3
print(n * 1ms)            // a number becomes a Duration by multiplying with a unit
print(now() < 1h)
1.25s
1s
4.0
3ms
true
print(250ms + 3)
error: '+' cannot combine Duration and int
 --> main.tin:1:7
  |
1 | print(250ms + 3)
  |       ^^^^^^^^^
  = note: a bare number has no unit: write 3ms or 3s, or `3 * 1ms` to convert a number

Functions

Parameters always have types. A body is either a block, whose last expression is the result, or => and a single expression. Without a return type, a block-bodied function returns nothing.

fn square(x: int): int => x * x

fn describe(n: int): string {
  if n < 0 { return "negative" }      // return leaves early
  let kind = if n % 2 == 0 { "even" } else { "odd" }
  "{n} is {kind}"                      // the last expression is the result
}

fn log(message: string) {
  print("[log] {message}")
}

fn main() {
  log(describe(square(3)))
}
[log] 9 is odd

Methods

fn Type.name(...) declares a method. Calling x.name(y) passes x as the first argument. The same syntax works for any function whose first parameter fits, so xs.map(f) and map(xs, f) are the same call.

type Circle = { r: float }

fn Circle.area(c: Circle): float => PI * c.r * c.r
fn string.shout(s: string): string => s.upper() + "!"

fn main() {
  let c = Circle { r: 2.0 }
  print(c.area().fixed(2))
  print("tin".shout())
  print(Circle.area(c) == c.area())
}
12.57
TIN!
true

Pipelines

x |> f(y) means f(x, y), and x |> f means f(x). Long chains read top to bottom.

let total = [1, 2, 3, 4, 5, 6]
  |> filter(n => n % 2 == 0)
  |> map(n => n * n)
  |> sum
print(total)
56

Lambdas and closures

A lambda is (params) => expression, or x => expression for one parameter. Parameter types come from where the lambda is used, or from an annotation. A lambda captures the variables it mentions by value, at the moment it is created. For that reason it can capture a let or a parameter, but not a var.

fn adder(n: int): (int) => int => x => x + n

fn main() {
  let add5 = adder(5)
  let ops = [add5, adder(100), x => x * x]
  print(ops.map(f => f(7)))

  let twice = (f: (int) => int) => (x: int) => f(f(x))
  print(twice(add5)(0))
}
[12, 107, 49]
10
var counter = 0
let bump = () => counter + 1
error: closures capture by value, and 'counter' is a `var`
 --> main.tin:2:18
  |
2 | let bump = () => counter + 1
  |                  ^^^^^^^
  = note: copy it first: `let counterNow = counter`, or pass it as a parameter

A named function is a value too: pass square wherever a (int) => int is expected.

Control flow

if is an expression when it has an else. Conditions are bool; there is no truthiness.

for n in [3, 30, 300] {
  let size = if n < 10 { "small" } else if n < 100 { "medium" } else { "large" }
  print("{n}: {size}")
}
3: small
30: medium
300: large

while loops on a condition. for walks a half-open range from..to or the items of an array; for i, x in xs also gives the index. loop { ... } runs until a break or return. break and continue work in all of them. for k, v in m walks a Map and for x in s a Set. for also walks your own types: an iterator has fn T.next(it: inout T): Option<Item> (the loop calls it on its own copy until None), and a collection has fn T.iter(x: T): ... returning anything for walks. A struct literal in the loop head needs parentheses: for x in (Countdown { n: 3 }).

var i = 0
while i < 3 {
  i += 1
}

var evens: int[] = []
for n in 0..10 {
  if n % 2 == 1 { continue }
  if n > 6 { break }
  evens.push(n)
}
print("{i} {evens}")

for i, name in ["base", "elbow"] {
  print("{i}: {name}")
}
var tries = 0
loop {
  tries += 1
  if tries == 3 { break }
}
3 [0, 2, 4, 6]
0: base
1: elbow

Structs

A struct groups named fields. Build one by naming the type and every field; when a variable has the field's name, { x, y } is enough. Fields of a var can be assigned.

type Point = { x: float, y: float }
type Line = { from: Point, to: Point, label: string }

fn main() {
  let x = 3.0
  let y = 4.0
  var line = Line { from: Point { x: 0.0, y: 0.0 }, to: Point { x, y }, label: "diagonal" }
  line.to.x += 1
  line.label = "moved"
  print(line)
}
Line { from: Point { x: 0.0, y: 0.0 }, to: Point { x: 4.0, y: 4.0 }, label: "moved" }

Sum types and match

A sum type lists every shape a value can take. A variant can carry named fields, positional values, or nothing. Variant names start with an uppercase letter and are used directly.

type Shape =
  | Circle { r: float }
  | Rect { w: float, h: float }
  | Dot

type Token = | Number(int) | Operator(string) | End

fn area(s: Shape): float => match s {
  Circle { r } => PI * r * r
  Rect { w, h: height } => w * height      // bind a field under another name
  Dot => 0.0
}

fn main() {
  print([Circle { r: 1.0 }, Rect { w: 2.0, h: 3.0 }, Dot].map(area))
  for t in [Number(4), Operator("+"), End] {
    print(match t {
      Number(n) => "number {n}"
      Operator(sym) => "operator {sym}"
      End => "end"
    })
  }
}
[3.141592653589793, 6.0, 0.0]
number 4
operator +
end

match must cover every case. Forget one and the compiler names it and offers the missing arm as a fix. An arm can add a guard, Temp(c) if c > 80.0 => ...: it matches only when the guard holds, so it does not count toward covering that case.

let l = Red
print(match l { Red => "stop", Green => "go" })
error: match is not exhaustive: missing Amber
 --> main.tin:2:7
  |
2 | print(match l { Red => "stop", Green => "go" })
  |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: add the missing arms, or a catch-all `_ => ...`
  = fix: add an arm for Amber
PatternMatches
Circle { r }that variant, binding the named fields you list
Number(n)that variant, binding its positional values; _ skips one
Dota variant without values
0, "yes", truethat exact int, string or bool
otheranything, bound to the name
_anything
Err(Low), Rect { h: 0, w }, Some(Ok(_))patterns inside patterns, at any depth

Inside a pattern, an uppercase name is a variant of the value's type, never a new binding: Err(Low) matches only that error, and a misspelt variant is a compile error. Coverage is checked through nesting, so a match that handles Err(Low) but not Err(High) is rejected and the message names Err(High). An arm that earlier arms already cover is an error too. Matching on an int or a string needs a final _ or name arm. Sum types can refer to themselves, which is how trees and expression types are written.

let checks: Result<int, Level>[] = [Ok(3), Err(Low), Err(High)]
for c in checks {
  print(match c { Ok(n) => "ok {n}", Err(Low) => "too low", Err(High) => "too high" })
}
for s in [Rect { w: 4, h: 0 }, Rect { w: 2, h: 3 }, Circle { r: 1 }] {
  print(match s { Rect { h: 0, w } => "a line {w} long", Rect { w, h } => "{w}x{h}", Circle { r } => "r={r}" })
}
ok 3
too low
too high
a line 4 long
2x3
r=1
let c: Result<int, Level> = Err(High)
match c { Ok(n) => print(n), Err(Low) => print("low") }
error: match is not exhaustive: missing Err(High)
 --> main.tin:2:1
  |
2 | match c { Ok(n) => print(n), Err(Low) => print("low") }
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  = note: add the missing arms, or a catch-all `_ => ...`
  = fix: add an arm for Err(High)

Option, Result and ?

Tin has no null and no exceptions. A value that may be absent is an Option<T>: Some(x) or None. An operation that may fail returns a Result<T, E>: Ok(x) or Err(e). Both are ordinary sum types, so you match on them.

After a call, ? unwraps the good case. Otherwise it returns the Err or None from the enclosing function, which must return the same kind.

fn parsePort(text: string): Result<int, string> {
  match parseInt(text) {
    Some(n) => if n > 0 && n < 65536 { Ok(n) } else { Err("port {n} is out of range") }
    None => Err("'{text}' is not a number")
  }
}

fn address(host: string, port: string): Result<string, string> {
  let p = parsePort(port)?           // on Err, address returns that Err
  Ok("{host}:{p}")
}

fn main() {
  print(address("localhost", "8080"))
  print(address("localhost", "http"))
  print(parseInt("12").or(0) + parseInt("x").or(0))
}
Ok("localhost:8080")
Err("'http' is not a number")
12

A panic("message") stops the program. It is for bugs, not for expected failures.

Arrays

An array literal is [a, b, c]. An empty one needs a type from its surroundings. Indexing is checked: reading or writing outside the array is a panic that names the index. push and pop change an array in place, so they need a var.

var xs = [10, 20, 30]
xs.push(40)
xs[0] = 11
let last = xs.pop()
var names: string[] = []
names.push("ada")
print("{xs} {xs.len} {last} {names}")
[11, 20, 30] 3 40 ["ada"]
let xs = [1, 2, 3]
var i = 7
print(xs[i])
panic: index 7 is out of bounds for an array of length 3

Generics

Functions and types take type parameters in < >. You never write the type arguments at a call: they are inferred from the arguments, or from the type the result is assigned to. Each distinct use is compiled to its own specialised code, so generic code runs as fast as code written by hand for that type.

type Pair<A, B> = { first: A, second: B }

fn swap<A, B>(p: Pair<A, B>): Pair<B, A> => Pair { first: p.second, second: p.first }

fn largest<T>(xs: T[]): Option<T> {
  if xs.len == 0 { return None }
  var best = xs[0]
  for x in xs {
    if x > best { best = x }
  }
  Some(best)
}

fn main() {
  print(swap(Pair { first: 1, second: "one" }))
  print(largest([3, 9, 4]))
  print(largest(["pear", "apple"]))
  let nothing: Option<float> = largest([])     // the annotation supplies T
  print(nothing)
}
Pair { first: "one", second: 1 }
Some(9)
Some("pear")
None

A generic function is checked against each type it is used with. If largest were called with an array of structs, the error would point at x > best and say which type it was being compiled for. To get the error at the call instead, say what the type parameter needs with a trait.

Traits

A trait names the methods a generic function needs. A type satisfies a trait when it has those methods with those types; there is no impl block, because a method is already a function named Type.method. In a trait, Self is the type that satisfies it, and each method takes it first.

trait Shape {
  fn area(s: Self): float
  fn name(s: Self): string
}

type Circle = { r: float }
type Square = { side: float }

fn Circle.area(c: Circle): float => PI * c.r * c.r
fn Circle.name(c: Circle): string => "circle"
fn Square.area(s: Square): float => s.side * s.side
fn Square.name(s: Square): string => "square"

fn describe<T: Shape>(x: T): string => "{x.name()}: {x.area().fixed(2)}"

fn main() {
  print(describe(Circle { r: 1.0 }))
  print(describe(Square { side: 2.0 }))
}
circle: 3.14
square: 4.00

A bound is checked where the function is called. The error points at the argument, lists the methods the type lacks, and its fix (tin fix) writes them as stubs that compile and panic until you fill them in:

trait Shape {
  fn area(s: Self): float
}
type Tri = { b: float, h: float }

fn twice<T: Shape>(x: T): float => 2.0 * x.area()

fn main() {
  print(twice(Tri { b: 1.0, h: 2.0 }))
}
error: Tri does not satisfy Shape: it has no method 'area'
 --> main.tin:9:15
  |
9 |   print(twice(Tri { b: 1.0, h: 2.0 }))
  |               ^^^^^^^^^^^^^^^^^^^^^^
  = note: twice<T: Shape> needs it; a type satisfies a trait by having its methods:
  = note:   fn Tri.area(s: Tri): float
  = fix: add the method

Several bounds are joined with +: fn f<T: Shape + Show, U: Show>(...). Built-in types satisfy traits the same way: fn int.name(n: int): string makes int satisfy a trait asking for name. A parameter marked inout in the trait must be inout in the method too.

A function with bounds is also checked once where it is written. There its type parameters have only the methods of their bounds, so a mistake in a generic library is found in the library, not in the program that calls it. < needs T: Ord and == needs T: Eq; the fix adds the bound:

fn has<T: Show>(xs: T[], y: T): bool {
  for x in xs {
    if x == y { return true }
  }
  false
}
error: functions are declared at the top level; use a lambda here: `let f = (x: int) => x + 1`
 --> main.tin:1:1
  |
1 | fn has<T: Show>(xs: T[], y: T): bool {
  | ^^

A generic function with no bounds at all is still checked per use, as under Generics.

Ord, Show and Eq

The standard library declares three traits and uses them itself:

  • Ord: fn compare(a: Self, b: Self): int, negative when a comes first, 0 when equal, positive after. A struct or enum with compare gets < > <= >=, and sort, min and max (bounded T: Ord) accept it. Numbers, strings, i64, Duration and Frequency have compare already. The order is total: for floats NaN equals NaN and comes after every number, so sort puts NaNs last, min(NaN, 1.0) is 1.0 and max(NaN, 1.0) is NaN. The operators keep IEEE meaning: NaN < 1.0 and 1.0 < NaN are both false.
  • Show: fn show(x: Self): string. Every type has a derived one (what print shows). A struct or enum's own show replaces it everywhere: in print, "{x}", str(x), and inside arrays, options and other structs. Inside its own show, "{p}" means the derived text.
  • Eq: fn equals(a: Self, b: Self): bool. Every type without functions, agents or tasks in it has a derived one (what == does). A struct or enum's own equals replaces it for ==, !=, contains, indexOf and the fields of other structs.
type Version = { major: int, minor: int }

fn Version.compare(a: Version, b: Version): int {
  if a.major != b.major { a.major - b.major } else { a.minor - b.minor }
}
fn Version.show(v: Version): string => "v{v.major}.{v.minor}"

fn main() {
  let vs = [Version { major: 1, minor: 4 }, Version { major: 0, minor: 9 }]
  print(sort(vs))
  print(vs[0] > vs[1])
  print(max(vs[0], vs[1]))
}
[v0.9, v1.4]
true
v1.4

Without compare, < on a struct is an error whose fix adds the method:

type P = { x: int }
print(P { x: 1 } < P { x: 2 })
error: unexpected 'type'
 --> main.tin:1:1
  |
1 | type P = { x: int }
  | ^^^^

A trait is a compile-time contract, not a type. fn f(x: Shape) is an error: there are no trait objects, and every generic call is compiled for its concrete type, so calls through a trait cost the same as direct calls. A trait has no default method bodies and no type parameters, and only functions take bounds (type Box<T: Shape> is an error).

Concurrency

There is no async keyword and no coloured functions. Any function may pause, as sleep does, and its callers do not have to know. spawn starts a call as a task and gives back a Task<T>; await waits for its result. Tasks take turns on one thread, switching only where one pauses, so there are no data races.

fn fetchScore(player: string, wait: Duration): int {
  sleep(wait)                     // pauses this task; others keep running
  player.len * 10
}

fn main() {
  let started = now()
  let a = spawn fetchScore("ada", 200ms)
  let b = spawn fetchScore("grace", 200ms)
  print(await a + await b)
  print(now() - started < 350ms)   // both waits overlapped
}
80
true

The arguments of a spawned call are evaluated before the task starts. A program ends when main and every task have finished. A panic in any task stops the program.

Tasks have owners

A task cannot outlive the task that spawned it. await t returns only when t and everything t started have finished, so a function that spawns helpers and returns early does not leave work running behind your back.

fn save(what: string) {
  sleep(20ms)
  print("saved {what}")
}

fn checkout(): string {
  spawn save("order")          // checkout returns before this finishes...
  spawn save("receipt")
  "checkout returned"
}

fn main() {
  let t = spawn checkout()
  print(await t)               // ...but nobody sees it as done until both saves are
}
saved order
saved receipt
checkout returned

Stopping and time limits

t.stop() stops a task and everything beneath it. A stopped task ends at its next pause: a sleep, await, fetch or agent call it is waiting in is abandoned at once, and nothing after it runs. within waits a limited time for a task and gives Some(result), or stops the task and gives None.

fn crunch(name: string, time: Duration): string {
  sleep(time)
  "{name} finished"
}

fn main() {
  print(spawn crunch("quick", 5ms) |> within(1s))
  print(spawn crunch("endless", 1h) |> within(20ms))

  let t = spawn crunch("background", 1h)
  t.stop()
  print("done: {t.done()}, stopped: {t.stopped()}")
}
Some("quick finished")
None
done: true, stopped: true
On a Task<T>Meaning
await tits result, once it and its tasks have finished; a panic if it was stopped
within(t, limit)Some(result) if it finishes in time; otherwise stops it and gives None
t.stop()stops it and every task beneath it
t.done()whether it has finished or been stopped
t.stopped()whether it was stopped

spawn takes everything written after it, so spawn f().stop() would spawn the result of f().stop(). Write spawn f() |> within(1s), or put the spawn in parentheses or a variable first. The compiler points this out.

Agents and tools

Three declarations make agents part of the language. A tool fn is a function the compiler also describes to a model. An agent binds a model, a system prompt and tools, and is called like a function. A guarded tool fn needs a person's approval before it runs. The full rules are on the Agents and tools page.

/// Add two integers.
tool fn add(a: int, b: int): int => a + b

agent Calculator {
  model: "mock"                    // an offline stand-in; use a Claude model name for the real thing
  system: "Use the tools for arithmetic."
  tools: [add]
}

type Order = { item: string, quantity: int }

agent Clerk { model: "mock" }

fn main() {
  print(Calculator("please add 19 and 23"))
  let order: Order = Clerk("2 of the 'oat latte', please")     // a typed reply
  print(order.quantity * 450)
}
mock: 42
900

Files and JavaScript

import "./other.tin" brings another Tin file into the program (with tin run; the playground is one file). Every file shares one namespace, as if it were one file, and each is read once however often it is imported. Errors point at the file and line they are in.

// kinematics.tin
fn reach(a: float, b: float): float => a + b

// main.tin
import "./kinematics.tin"
fn main() { print(reach(0.3, 0.25)) }

import "./arm.tin" as arm keeps the file's names in their own namespace: its types, functions, constants and agents are arm.Joint, arm.overLimit, arm.REACH, arm.Planner. Inside arm.tin they are used without the prefix, and two modules may define the same names. Methods follow their type (joint.over() works on an arm.Joint).

import "./arm.tin" as arm
import "./base.tin" as base       // base.tin has its own Joint and overLimit

fn main() {
  let j = arm.Joint { name: "elbow", angle: -2.4, limit: 2.1 }
  let wheels: base.Joint[] = [base.Joint { name: "left", turns: 5 }]
  print(arm.overLimit([j]))
  print(base.overLimit(wheels))
  print(arm.Planner("can you reach 0.4 m?"))
}

Three things stay global: variant names of sum types (match on them without a prefix), extern fns, and methods on built-in types such as fn string.shout. A tool's name, as a model sees it, has no dot: arm.canReach is offered as arm_canReach. A file is imported one way, with a name or without; the module name is lowercase. examples/namespaces/ has the whole program.

Packages

A package is a git repository or a folder of .tin files. tin add puts it in the project's tin.toml, fetches it, and pins the exact commit in tin.lock:

$ tin add https://github.com/you/geometry.git
created tin.toml
  geometry 3f9c2a1b7d0e https://github.com/you/geometry.git (new)
added geometry: import "geometry/<file>" (its <file>.tin), or import "geometry" (its lib.tin)

$ cat tin.toml
[package]
name = "app"
version = "0.1.0"

[dependencies]
geometry = { git = "https://github.com/you/geometry.git" }

import "geometry/vec" is the package's vec.tin (or src/vec.tin), named vec; import "geometry" is its lib.tin, named geometry. Use as for another name. A package's names are always behind its module name, like a file imported as one.

import "geometry/vec"

fn main() {
  print(vec.len(vec.Vec { x: 3.0, y: 4.0 }))
}
  • tin add <url> --rev v1.2 follows a tag, branch or commit; tin add ../units uses a folder in place. Any URL git can clone works, including a local path.
  • tin install fetches everything at the commits in tin.lock. --frozen refuses to change the lock, for CI. Each package also has a sha256 checksum of its .tin files in the lock, and a changed file is an error: tin run refuses an edited git package, and tin install fetches the pinned commit again.
  • A package's own tin.toml dependencies are installed too. Each name has one source for the whole program: two packages asking for units from different places is an error that names both.
  • Git packages are cloned into .tin/pkgs/, which tin add adds to .gitignore. Commit tin.toml and tin.lock.

There is no registry and no version solving: a dependency is a URL or a folder, and the lock says which commit. examples/packages/ has a package and a program that uses it; Package docs shows what tin doc makes of the package.

import js "spec" names a JavaScript module: a file, a Node built-in ("node:os") or an installed package. Each extern fn is a function that module exports. Values cross as plain data, checked against the Tin types, and an async function just works. An extern declared to return Result<T, string> turns a JavaScript throw into Err(message).

A flat extern fn is answered by the one imported module that exports that name. If none does, or two do, the program does not start and says which. A block binds externs to its module:

import js "./geometry.mjs"
import js "node:path" {
  extern fn basename(path: string): string
  extern fn extname(path: string): string
}
extern fn hypot(a: float, b: float): float     // from geometry.mjs

fn main() {
  print(basename("/robots/arm/pose.tin"))
  print(hypot(3.0, 4.0))
}

JavaScript can do anything on the machine, so an extern is the capability js in tin caps, and a tool a model may call freely cannot reach one: it has to be a guarded tool fn. An i64 crosses as a BigInt.

Where values cross into Tin, the check is exact for code and forgiving for models:

value arrives asdeclaredfrom an extern fn (js, mcp, py)a tool's input (a model, an MCP client)
"5"int, floaterror5
"true"boolerrortrue
5, truestringerror"5", "true"
"123", a BigInt, a safe integeri64accepted (the schema asks for a decimal string)accepted
a Buffer / Uint8Arraystringdecoded as UTF-8–
2.5, out of rangeinterrorerror

A model writes "5" for a number often enough that refusing it would only cost a retry; code that returns the wrong type has a bug, and Tin says where (count: expected an integer, got "5").

MCP servers

import mcp "command" starts an MCP server (any stdio server: the command is split into words, no shell, run from the file's folder) and answers each extern fn in its block with the server's tool of that name (a tool spelled with - or . is matched by _). Before main runs, every extern is checked against the server's tool list: a missing tool, a missing required argument or an argument of the wrong JSON type stops the program with a message that names both sides. Arguments go by name; the result is the tool's structured content, or its text (parsed as JSON unless the extern returns string), checked against the declared type. A tool error stops the program, or becomes Err(text) when the extern returns Result<T, string>.

import mcp "npx -y @modelcontextprotocol/server-everything" {
  extern fn add(a: int, b: int): int
  extern fn echo(message: string): string
}

fn main() {
  print(add(2, 40))
  print(echo("hi"))
}

An MCP server is outside code too: tin caps and the compiler treat it like JavaScript, so an agent gets an MCP tool through a guarded tool fn that wraps the extern, and a person approves each call (examples/mcp/). The other way round, tin mcp file.tin serves a program's tool fns as an MCP server.

Python

import py "module" names a Python module: a .py file next to the program, the standard library, or anything installed for the interpreter ($PYTHON, else a .venv next to the file, else python3). Its block lists the functions the program uses. Before main runs, each one is checked against the real function: the module must import, the name must be a function, and its parameters must match by name. Arguments go by name (functions that take *args, like math.gcd, get them in the declared order).

import py "statistics" {
  extern fn median(data: float[]): float
}
import py "math" {
  extern fn gcd(a: int, b: int): int
}

fn main() {
  print(median([3.0, 1.0, 2.0]))
  print(gcd(84, 36))
}

Values cross as plain data, shaped by the Tin types: a Tin float is a Python float even when it is 2.0, an i64 stays exact, a struct is a dict, and a dataclass, tuple or numpy array coming back becomes a struct or array. The result is checked against the declared type. A Python exception becomes Err("ValueError: ...") for an extern that returns Result<T, string> and stops the program otherwise. Python's print goes to standard error. Python runs in one child process per program, so a call is a round trip (about 20 µs) and only data crosses, never a handle to a Python object. Like JavaScript, Python is outside code for tin caps: a free tool cannot reach it. examples/py/ has a complete program.

Tests

A test "name" { ... } block sits next to the code it tests. tin test file.tin runs every block, each in a fresh instance of the program, and a test fails if it panics. assertEq compares any two values of the same type; assert takes a condition and an optional message (without one, the condition's source is the message). Agents can be tested offline with the mock model or a replay tape.

fn discount(total: int, percent: int): Result<int, string> {
  if percent < 0 || percent > 100 { return Err("percent must be between 0 and 100") }
  Ok(total - total * percent / 100)
}

test "a quarter off" {
  assertEq(discount(1000, 25), Ok(750))
}

test "silly percentages are refused" {
  assert(discount(1000, 150).isErr(), "150% should be refused")
}

fn main() {
  print(discount(1000, 25))
}

tin run ignores the test blocks but still type-checks them, so tests cannot rot unnoticed. A file with only tests needs no main.

Lines and semicolons

A statement ends at the end of its line. Semicolons are optional and only needed to put two statements on one line. An expression continues onto the next line when that line starts with an operator such as |>, ., + or &&. Three tokens never continue a line, because they so often start a new statement: (, [ and -.

let a = 1; let b = 2
let sum = a
  + b
let text = "  padded  "
  .trim()
  .upper()
print("{sum} {text}")
3 PADDED

What Tin does not have

Tin is at version 0.1. Some of these are planned, some are decisions for now; DESIGN.md says which, and why:

  • A package registry or version solving. Packages come from git URLs or folders, pinned by commit in tin.lock; one source and one commit per name, no semver ranges.
  • A garbage collector, or copy-on-write. There is no collector: the compiler frees values deterministically (owned locals at the end of their block or on reassignment, closures by reference count). Copies are eager, not copy-on-write.
  • A 64-bit int. int is 32-bit and overflow panics; use i64 where that is too small. Measured: a 64-bit int doubles int arrays (+34% peak memory on a 2M-int sort) for no gain in arithmetic speed (bench/experiments/int-width).
  • Trait objects, default methods or generic traits. A trait is a bound on a generic function's type parameter, satisfied by having its methods. You cannot store "any Shape" in an array (use an enum), and a trait cannot supply method bodies (only the standard library's Show and Eq are derived). There is no Hash trait: Map hashes keys structurally, and a type with its own equals should also define fn T.hash(x: T): int.
  • Unicode-aware case and classes. char.upper(), isDigit() and the rest are ASCII-based ('é'.upper() is 'é'), and string positions count bytes, not characters.
  • C interop, or Python objects. import py calls Python functions in a child process with plain data; there is no import c, and no handle to a Python object crosses.
  • Agents, tasks and fetch outside a JavaScript host. tin build --target wasi makes a .wasm that runs under wasmtime with no JavaScript, but only for programs without agents, spawn, fetch, approve or import js/mcp/py (tin build --target wasi); the same holds for tin build --native executables.
  • Type arguments at a call. newMap<string, int>() does not parse: write the type where the result goes (var m: Map<string, int> = newMap()), or build from values (mapOf([("a", 1)])).
  • Lazy iterator adapters. for walks your own iterators, but map, filter and friends work on arrays only; collect an iterator into an array first.