T Language Reference

Complete syntax reference for both SLN and C notations

T's type system centers on newtypes. A type name simultaneously serves as a field identifier (in tuples), a variant tag (in enums), and a constructor. This unifies what are normally separate concepts. Together with primitives, pointers, and arrays, this minimal system is enough for C-level programming.

Primitive Types

TypeDescription
boolBoolean (true, false)
i8, i16, i32, i64, i128Signed integers (i128: C and Rust backends only; Cranelift, WASM and WGSL refuse it with an error)
u8, u16, u32, u64, u128Unsigned integers (u128: C and Rust backends only; Cranelift, WASM and WGSL refuse it with an error)
isize, usizePlatform-dependent integers (ptrdiff_t, size_t in C)
f32, f64Floating-point

Compound Types

SLNCDescription
(& T) or &T&TShared pointer
(| T) or |T|TMutable pointer
(array T N)[T]NFixed-size array
(vector T N){T}NSIMD vector
(slice T)[T]Slice
(slice-mut T)|[T]Mutable slice
(tuple T1 T2 …)T1 & T2 & …Tuple (product type, & = AND)
(enum T1 T2 …)T1 | T2 | …Enum (sum type, | = OR)
(fn (T1 T2 …) R)fn(T1, T2, …) -> RFunction type

A vector type is also a cast target: ({f32}3: s) in C syntax, (cast s (vector f32 3)) in SLN, broadcasts the scalar s to every lane.

A vector reads its lanes by index (v[0]) or by swizzle: a field name built from 1 to 4 of the letters x, y, z, w. One letter yields the element type, more than one a vector of that length, and letters may repeat (v.yyyy). A swizzle is read-only; assign to a lane by index instead. The C backend lowers a single lane to v[i] and a wider swizzle to __builtin_shufflevector, the WGSL backend passes it through. The Rust backend reads a single lane as an index and a wider swizzle as an array of the selected lanes.

A vector literal concatenates: an element that is itself a vector contributes all of its lanes, so {color.xyz, 1.0} with color: {f32}3 is a {f32}4, and {a.xy, b.xy} is one as well. All elements share the element type, and a number literal adopts it. An array literal is unaffected — there a vector element stays one element. Braces in statement position are a block, so a one-element literal {v} reads as a block whose result is v — at module level as well as inside a function body, since both read {…} the same way. Write the splat form instead: {f32}1: v with no braces around v. From two elements on, the comma settles it and the brace form works.

Declarations

Names

T does not mangle names: every type, function, constant, parameter and local binding keeps its name in the generated code. A name that the target language reserves is therefore rejected rather than renamed, because renaming would break the linkage a pub declaration promises.

For the C backend this means the C keywords are unavailable as T names — double, int, char, long, short, signed, unsigned, struct, union, enum, static, extern, const, volatile, register, restrict, inline, typedef, goto, switch, case, default, do, for, while, break, continue, auto, void, sizeof, and the _-prefixed keywords of C11. The check runs before code generation, so the error names the T source line rather than the generated C.

Newtypes

This example shows primitive newtypes (Byte, Size), constants, explicit downcast via field access (.u64), and sizeof for querying type sizes at compile time.

type Byte u8
type Size u64

const MAX_SIZE Size 1024

print "byte =" 42
print "MAX_SIZE =" MAX_SIZE.u64
print "sizeof(i32) =" (sizeof i32)
print "sizeof(f64) =" (sizeof f64)
type Byte = u8;
type Size = u64;

const MAX_SIZE: Size = 1024;

print("byte =", 42);
print("MAX_SIZE =", MAX_SIZE.u64);
print("sizeof(i32) =", sizeof(i32));
print("sizeof(f64) =", sizeof(f64));

Casts

Three forms sit behind what other languages call a cast, and they do different things.

Numbers never convert with as. u32: n is the conversion, and the compiler says so when as is used on a number.

type meters f32
type feet f32

fn as_bits (number) (|f32) u32
    let bits (as number |u32)
    bits@0

let distance (meters 1.5)
print "meters =" distance.f32

let converted (feet (* distance.f32 3.28084))
print "feet =" converted.f32

var value (cast 1.0 f32)
print "bits =" (as_bits value)
type meters = f32;
type feet = f32;

fn as_bits(number: |f32) -> u32 {
    let bits = number as |u32;
    bits[0]
}

let distance = meters: 1.5;
print("meters =", distance.f32);

let converted = feet: distance.f32 * 3.28084;
print("feet =", converted.f32);

var value = f32: 1.0;
print("bits =", as_bits(value));

Enums (Sum Types)

This example declares an enum with two variants and matches on them. The variant type name acts as both the tag and the constructor — types are simultaneously enum tags and field names.

type ok i32
type err i32
type result (enum ok err)

fn describe (result) (result)
    match result
        (ok value) (print "ok:" value)
        (err code) (print "err:" code)

describe (result ok:42)
describe (result err:-1)
type ok = i32;
type err = i32;
type result = ok | err;

fn describe(result) {
    match result {
        ok(value) => print("ok:", value),
        err(code) => print("err:", code),
    }
}

describe(result: ok: 42);
describe(result: err: -1);

Functions

Example: fn make(xv: x, yv: y) can be called as make(y: 2.0, x: 1.0) — the compiler matches x: 1.0 to xv: x and y: 2.0 to yv: y, regardless of argument order. This is consistent with tuple fields being identified by type.

Visibility

KeywordEffectC equivalent
(none)Internal linkage (default)static
pubExternal linkageno static
externExternal declarationfunction prototype
importFile import / C header inclusion#include (for .h) or source expansion (for .c.t/.sln.t)

Overloaded extern Declarations

The same extern fn name may be declared more than once, as long as the parameter types differ. A call picks the declaration whose parameter types fit its arguments; a number literal adopts the parameter type, so pick(1.0, 2.0) selects the f32 form and pick(1, 2) the i32 form. If no declaration fits, or more than one does, the error names the candidates. Two declarations with identical parameter types are rejected.

extern fn pick(a: f32, b: f32) -> f32;
extern fn pick(a: i32, b: i32) -> i32;

Overloading is a property of the target language, and T does not mangle names, because extern names are what the linker sees. WGSL overloads its builtins, so the WGSL backend accepts overloaded declarations; std/wgsl.th declares the scalar and vector forms of length, dot, mix, max and the rest that way. The C and Rust backends reject an overloaded extern, because neither language can express it.

import math.th

print (sqrt 2.0)
print PI
import "math.th";

print(sqrt(2.0));
print(PI);
pub "A distance in meters." type meters f64
pub "The zero distance." const ZERO meters meters:0.0
pub "Returns the sum of a distance with itself." fn twice (meters) (meters) meters
    (+ meters meters)
print (twice ZERO)
pub "A distance in meters." type meters = f64;
pub "The zero distance." const ZERO: meters = meters: 0.0;
pub "Returns the sum of a distance with itself." fn twice(meters) -> meters {
    meters + meters
}
print(twice(ZERO));

The documentation strings of a file's public items form its reference:

ItemDocumentation
type meters = f64A distance in meters.
const ZERO: meters = meters: 0.0The zero distance.
fn twice(meters) -> metersReturns the sum of a distance with itself.

Bindings

BindingInternal TypeAddressableMutableAuto-deref
letTnonono
ref&Tyesnoyes
var|Tyesyesyes

Multiple bindings in one statement: let x, y = 1, 2; (C) / (let x 1 y 2) (SLN).

Auto-deref applies in: operators, conditions, return, print, assignment values (right side of :=), let initializers, label/jump arguments.

Assignment targets (left side of :=): shared pointers (&) are automatically dereferenced to reach a mutable pointer (|T). For example, &|T := y derefs through & and assigns through the |T. If no |T is reachable, it is an error.

Auto-deref does not apply in: function arguments to pointer parameters (auto-ref instead), field access (. preserves pointer state), index target.

Shader Attributes

Attributes carry declaration metadata that a backend needs and the language itself does not interpret. So far only the WGSL backend reads them; the C and Rust backends ignore or reject them. An attribute is @name or @name(argument, …) and may sit before a function, before a parameter, and after -> in front of the return type.

A global variable declares a binding that lives outside any function body. It is written var<class> name: Type;, where the storage class is uniform, storage, storage, mut or workgroup. A global is read like a value; it is not a pointer binding.

The fields of a tuple newtype carry attributes too, each one in front of its field: type vertex_out = @builtin(position) clip & @location(0) uv;. The WGSL backend turns that newtype into a struct and writes the attributes back in front of its members, which is how a vertex stage hands an interpolator to a fragment stage. Attributes belong to the declaration, not to the type: two tuples that differ only in their attributes are still the same type, and an anonymous tuple never carries any.

import wgsl.th

type clip (vector f32 4)
type uv (vector f32 2)
type vertex_out (tuple (clip (attributes (@ builtin position))) (uv (attributes (@ location 0))))

(attributes (@ vertex)) fn vertex_main ((corner (attributes (@ builtin vertex_index)))) (u32) vertex_out
    var x (cast -1.0 f32)
    var y (cast -1.0 f32)
    (if (== corner 1)
        (do (set x 3.0)))
    (if (== corner 2)
        (do (set y 3.0)))
    (vertex_out (vector x y 0.0 1.0) (vector (+ (* x 0.5) 0.5) (+ (* y 0.5) 0.5)))

(attributes (@ fragment)) fn fragment_main (vertex_out) (vertex_out) (attributes (@ location 0)) (vector f32 4)
    let texture vertex_out.uv
    (vector texture.x texture.y 0.5 1.0)
import "wgsl.th";

type clip = {f32}4;
type uv = {f32}2;
type vertex_out = @builtin(position) clip & @location(0) uv;

@vertex fn vertex_main(@builtin(vertex_index) corner: u32) -> vertex_out {
    var x = f32: -1.0;
    var y = f32: -1.0;
    if corner == 1 {
        x := 3.0;
    }
    if corner == 2 {
        y := 3.0;
    }
    vertex_out {
        clip: {x, y, 0.0, 1.0},
        uv: {x * 0.5 + 0.5, y * 0.5 + 0.5}
    }
}

@fragment fn fragment_main(vertex_out) -> @location(0) {f32}4 {
    let texture = vertex_out.uv;
    {texture.x, texture.y, 0.5, 1.0}
}
import wgsl.th

(attributes (@ group 0) (@ binding 0)) global uniform tint (vector f32 4)

(attributes (@ group 0) (@ binding 1)) global storage-mut samples (array f32 4)

fn brightness (color) ((vector f32 4)) f32
    (length color)

(attributes (@ vertex)) fn vertex_main ((position (attributes (@ location 0)))) ((vector f32 4)) (attributes (@ builtin position)) (vector f32 4)
    (+ position tint)

(attributes (@ fragment)) fn fragment_main () () (attributes (@ location 0)) (vector f32 4)
    (* tint (brightness tint))
import "wgsl.th";

@group(0) @binding(0) var<uniform> tint: {f32}4;

@group(0) @binding(1) var<storage, mut> samples: [f32]4;

fn brightness(shade: {f32}4) -> f32 {
    length(shade)
}

@vertex fn vertex_main(@location(0) position: {f32}4) -> @builtin(position) {f32}4 {
    position + tint
}

@fragment fn fragment_main() -> @location(0) {f32}4 {
    tint * brightness(tint)
}

In the SLN syntax the attribute group is the first element of the declaration's own list, so it has to stand on the same line as the fn or global that it belongs to. A declaration without attributes keeps its plain form — an empty group is never written.

Expressions

Literals

SLNCType
4242i32
0xFF0xFFi32 (hex)
0o770o77i32 (octal)
0b10100b1010i32 (binary)
3.143.14f64
0x14.80x14.8f64 (hex float = 20.5)
1e300, 1.5e-51e300, 1.5e-5f64 (exponent)
true, falsetrue, falsebool
"hello""hello"&u8
(array 1 2 3)[1, 2, 3][T]N
(vector 1.0 2.0 3.0){1.0, 2.0, 3.0}{T}N

The types above are what a number literal falls back to when nothing else determines it. A literal standing where a type is already known takes that type instead: the argument in take(1) is a u64 if that is what take declares, and the elements of [1, 2, 3] are u64 in a [u64]3 binding. This is the only direction type information travels in T — from a known type down to a literal, never from an expression up to its surroundings.

Everything else keeps the type it computes. 0 - 1 is an i32, whatever it is passed to, and passing it where a u64 belongs is an error rather than a silent conversion. Write the conversion where it happens:

take(u64: 0 - 1);

The same holds for widths within one signedness: an i32 does not become an i64 by being used as one.

Arithmetic

SLNCDescription
(+ a b)a + bAddition
(- a b)a - bSubtraction
(* a b)a * bMultiplication
(/ a b)a / bDivision
(% a b)a % bModulo
(- a)-aNegation

Comparison

SLNCDescription
(== a b)a == bEqual
(!= a b)a != bNot equal
(< a b)a < bLess than
(<= a b)a <= bLess or equal
(> a b)a > bGreater than
(>= a b)a >= bGreater or equal

Logical

SLNCDescription
(and a b)a && bLogical AND
(or a b)a || bLogical OR
(not a)!aLogical NOT

Bitwise

SLNCDescription
(& a b)a & bAND
(| a b)a | bOR
(^ a b)a ^ bXOR
(~ a)~aNOT
(<< a n)a << nLeft shift
(>> a n)a >> nRight shift

This example combines bitwise operations with extern (C interop) to call printf directly, and implements a popcount function using the bit-clearing trick n & (n - 1) in a label/jump loop.

extern printf (&u8 ...) i32

fn popcount (n) (u32) i32
    label loop (bits count) (n 0)
    if (== bits 0)
        return count
    jump loop (& bits (- bits 1)) (+ count 1)

let a (cast 170 u32)
let b (cast 92 u32)
printf "a       = %u (0x%X)\n" a a
printf "b       = %u (0x%X)\n" b b
printf "a & b   = %u\n" (& a b)
printf "a | b   = %u\n" (| a b)
printf "a ^ b   = %u\n" (^ a b)
printf "~a      = %u\n" (~ a)
printf "a << 2  = %u\n" (<< a 2)
printf "a >> 2  = %u\n" (>> a 2)
printf "popcount(a) = %d\n" (popcount a)
printf "popcount(b) = %d\n" (popcount b)
extern fn printf(format: &u8, ...) -> i32;

fn popcount(n: u32) -> i32 {
    label l(bits = n, count = 0);
    if bits == 0 { return count; }
    jump l(bits & (bits - 1), count + 1);
}

let a = u32: 170;
let b = u32: 92;
printf("a       = %u (0x%X)\n", a, a);
printf("b       = %u (0x%X)\n", b, b);
printf("a & b   = %u\n", a & b);
printf("a | b   = %u\n", a | b);
printf("a ^ b   = %u\n", a ^ b);
printf("~a      = %u\n", ~a);
printf("a << 2  = %u\n", a << 2);
printf("a >> 2  = %u\n", a >> 2);
printf("popcount(a) = %d\n", popcount(a));
printf("popcount(b) = %d\n", popcount(b));

Match

type ok i32
type err i32
type result (enum ok err)

let r (result ok:42)

let value
    match r
        (ok v) v
        (err c) (* c -1)
print value
type ok, err = i32;
type result = ok | err;

let r = result: ok: 42;

let value = match r {
    ok(v) => v,
    err(c) => c * -1,
};
print(value);

Assignment

var x 1
var y 2
set x y y x
print x y
var x = 1;
var y = 2;
x, y := y, x;
print(x, y);

var current = 10;
fn get_next() -> i32 { 42 }
let previous = current := get_next();
print(previous, current);

Label / Jump

This factorial implementation shows label/jump as a loop: loop carries an accumulator and counter, jumping back until counter > n. Arguments are evaluated in parallel, so result * counter uses the current values before the jump updates them.

fn factorial (n) (i64) i64
    label loop (result counter) (i64 i64) (1 2)
    if (> counter n)
        return result
    jump loop (* result counter) (+ counter 1)

print "factorial(5) =" (factorial 5)
print "factorial(10) =" (factorial 10)
print "factorial(20) =" (factorial 20)
fn factorial(n: i64) -> i64 {
    label loop(i: i64 = 1, result: i64 = 1);
    if i > n { return result; }
    jump loop(i + 1, result * i);
}

print("factorial(5) =", factorial(i64: 5));
print("factorial(10) =", factorial(i64: 10));
print("factorial(20) =", factorial(i64: 20));

Defer

fn test (x) (i32) i32
    defer (print "cleanup")
    if (< x 0)
        return -1
    (* x 2)

print (call test 5)
print (call test -3)
fn test(x: i32) -> i32 {
    defer print("cleanup");
    if x < 0 {
        return -1;
    }
    x * 2
}

print(test(5));
print(test(-3));

Function Pointer Calls

apply takes a function pointer f: fn(i32) -> i32 and invokes it via call. This separates function pointer invocation from direct calls, avoiding ambiguity with type construction in SLN.

fn twice (n) (i32) i32
    (* n 2)

fn thrice (n) (i32) i32
    (* n 3)

fn apply (f x) ((fn (i32) i32) i32) i32
    (call f x)

print "twice(5) =" (apply twice 5)
print "thrice(5) =" (apply thrice 5)
fn twice(n: i32) -> i32 {
    n * 2
}

fn thrice(n: i32) -> i32 {
    n * 3
}

fn apply(f: fn(i32) -> i32, x: i32) -> i32 {
    call(f, x)
}

print("twice(5) =", apply(twice, 5));
print("thrice(5) =", apply(thrice, 5));

Printing

print writes one line per call and picks the format from each argument's type. Floats go through %g, which shows six significant digits — enough for a readable number, not enough to tell two f64 values apart. print(0.1 + 0.2) prints 0.3.

For the exact value, declare the C function and choose the format yourself:

extern fn printf(format: &u8, ...) -> i32;

let sum = 0.1 + 0.2;
printf("%.17g\n", sum);
printf("%a\n", sum);

That prints 0.30000000000000004 and 0x1.3333333333334p-2.

Both backends call the same C library here, so the output is identical down to the last digit — which a reimplementation on each side would not be, since C's %.17g and Rust's shortest round-trip form disagree on how many digits to show.

Arguments at a variadic position are passed as written; the auto-dereference that applies to pointer parameters elsewhere does not happen there. Write *x where the value is meant.

Slices

Threads and Atomics

T has no thread syntax of its own. Threads come from the platform through import "thread.th", a header in T's standard library that declares pthread_create, pthread_join and the pthread_mutex_* functions as ordinary extern functions. A thread body is a plain function of type fn(|u8) -> |u8, passed by name:

import thread.th
import memory.th

# Starts two threads, each writing its own value into its own 4-byte slot
# of a shared 8-byte buffer, joins both, then prints both values. Which
# thread the OS scheduler runs first does not matter: the two threads never
# touch the same memory, so the printed output is the same on every run.

fn worker_a (arg) (|u8) |u8
    let slot (cast arg |i32)
    (set slot@0 111)
    null

fn worker_b (arg) (|u8) |u8
    let slot (cast arg |i32)
    (set slot@0 222)
    null

fn main () ()
    let slots (malloc 8)
    var thread_a (cast 0 u64)
    var thread_b (cast 0 u64)
    pthread_create thread_a null worker_a slots
    pthread_create thread_b null worker_b (+ slots 4)
    pthread_join thread_a null
    pthread_join thread_b null
    let values (cast slots |i32)
    print values@0
    print values@1
    free slots
import "thread.th";
import "memory.th";

// Starts two threads, each writing its own value into its own 4-byte slot
// of a shared 8-byte buffer, joins both, then prints both values. Which
// thread the OS scheduler runs first does not matter: the two threads never
// touch the same memory, so the printed output is the same on every run —
// not "thread ran before the other one", but "each wrote where only it
// writes".

fn worker_a(arg: |u8) -> |u8 {
    let slot = arg as |i32;
    slot[0] := 111;
    null
}

fn worker_b(arg: |u8) -> |u8 {
    let slot = arg as |i32;
    slot[0] := 222;
    null
}

fn main() {
    let slots = malloc(8);
    var thread_a = u64: 0;
    var thread_b = u64: 0;
    pthread_create(thread_a, null, worker_a, slots);
    pthread_create(thread_b, null, worker_b, slots + 4);
    pthread_join(thread_a, null);
    pthread_join(thread_b, null);
    let values = slots as |i32;
    print(values[0]);
    print(values[1]);
    free(slots);
}

Atomic memory operations are built into the language, one form per operation:

C syntaxResult
atomic_load(pointer, ordering)the loaded value
atomic_store(pointer, value, ordering)nothing
atomic_rmw(operator, pointer, value, ordering)the value before the operation
atomic_cas(pointer, expected, new, success, failure)the value before the attempt; the swap happened when it equals expected
atomic_fence(ordering)nothing

SLN writes the same forms as lists: atomic_rmw add counter 1 seq_cst. The read-modify-write operators are add, sub, and, nand, or, xor and xchg; the orderings are relaxed, acquire, release, acq_rel and seq_cst. A compare-and-swap's failure ordering may be neither release nor acq_rel, since a failed attempt stores nothing, and may not be stronger than its success ordering — both are compile errors. Four threads incrementing one counter:

import thread.th
import memory.th

# A contended counter: 4 threads each increment a shared i32 counter 100000
# times through atomic_rmw(add, ..., seq_cst). The exact total (400000) is
# the only thing this program prints. See examples/reference/atomics.c.t for
# the full rationale (iteration count, non-atomic control).

fn worker (arg) (|u8) |u8
    let counter (cast arg |i32)
    label loop (i) (i32) (0)
    if (>= i 100000)
        return null
    atomic_rmw add counter 1 seq_cst
    jump loop (+ i 1)

fn main () ()
    let counter (malloc 4)
    let counter_i32 (cast counter |i32)
    atomic_store counter_i32 0 seq_cst
    var thread_a (cast 0 u64)
    var thread_b (cast 0 u64)
    var thread_c (cast 0 u64)
    var thread_d (cast 0 u64)
    pthread_create thread_a null worker counter
    pthread_create thread_b null worker counter
    pthread_create thread_c null worker counter
    pthread_create thread_d null worker counter
    pthread_join thread_a null
    pthread_join thread_b null
    pthread_join thread_c null
    pthread_join thread_d null
    print (atomic_load counter_i32 seq_cst)
    free counter
import "thread.th";
import "memory.th";

// A contended counter: 4 threads each increment a shared i32 counter 100000
// times through atomic_rmw(add, ..., seq_cst). The exact total (400000) is
// the only thing this program prints — a single number that is either the
// contended fixed point or it is not, no smoothing possible.
//
// Why 100000 and not fewer: docs/t-threads.md measured that a non-atomic
// increment on this machine can still land on the right total by luck at
// low contention — the race window (read, add, write) is short enough that
// four threads often do not collide within a few thousand iterations. The
// counter's non-atomic control (t/tests/atomics_contended.rs) raises the
// iteration count until collisions are observed and reports the number of
// wrong runs out of a fixed number of trials.

fn worker(arg: |u8) -> |u8 {
    let counter = arg as |i32;
    label loop(i: i32 = 0);
    if i >= 100000 {
        return null;
    }
    atomic_rmw(add, counter, 1, seq_cst);
    jump loop(i + 1);
}

fn main() {
    let counter = malloc(4);
    let counter_i32 = counter as |i32;
    atomic_store(counter_i32, 0, seq_cst);

    var thread_a = u64: 0;
    var thread_b = u64: 0;
    var thread_c = u64: 0;
    var thread_d = u64: 0;
    pthread_create(thread_a, null, worker, counter);
    pthread_create(thread_b, null, worker, counter);
    pthread_create(thread_c, null, worker, counter);
    pthread_create(thread_d, null, worker, counter);
    pthread_join(thread_a, null);
    pthread_join(thread_b, null);
    pthread_join(thread_c, null);
    pthread_join(thread_d, null);

    print(atomic_load(counter_i32, seq_cst));
    free(counter);
}

Output: 400000, every run. Backend support: C, Rust and Cranelift compile threads and atomics; WebAssembly compiles atomics but has no nand read-modify-write and refuses it; WGSL has no pointers and refuses both.

Macros

Macros are expanded before parsing and are therefore the same in T and in Ty, in both syntaxes. They are documented separately in Macros.