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
| Type | Description |
|---|---|
bool | Boolean (true, false) |
i8, i16, i32, i64, i128 | Signed integers (i128: C and Rust backends only; Cranelift, WASM and WGSL refuse it with an error) |
u8, u16, u32, u64, u128 | Unsigned integers (u128: C and Rust backends only; Cranelift, WASM and WGSL refuse it with an error) |
isize, usize | Platform-dependent integers (ptrdiff_t, size_t in C) |
f32, f64 | Floating-point |
Compound Types
| SLN | C | Description |
|---|---|---|
(& T) or &T | &T | Shared pointer |
(| T) or |T | |T | Mutable pointer |
(array T N) | [T]N | Fixed-size array |
(vector T N) | {T}N | SIMD 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, …) -> R | Function 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
- Primitive newtypes wrap a single type:
type meters = f32; - Newtypes can wrap other newtypes (stacking):
type direction = point; - Tuple newtypes combine multiple newtypes:
type point = x & y; - Fields are identified by their type name — the type is the field identifier
- Tuple rules (follow from type-based identification): all fields must be newtypes (no primitives — they have no name to identify by), no duplicates (would be ambiguous), minimum 2 fields
- Implicit downcast (newtype → base), explicit upcast (base → newtype)
- Explicit downcast via field access:
d.f64extracts the base type — works through newtype stacking - Upcast syntax:
TypeName: value(C) /(TypeName value)orTypeName:value(SLN) - SLN
:is right-associative:speed:meters:42.0→(speed (meters 42.0)) - C-syntax supports comma shorthand:
type x, y = f32;
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.
TypeName: value(C) /(TypeName value)(SLN) constructs a newtype from its base type. It is safe and checked: the value must have the base type.value.TypeNameunwraps a newtype down to a type it is built on, through any number of stacking steps.distance.f32reads thef32insidemeters.value as Typereinterprets a pointer as a pointer to another type. It checks nothing, which is why it exists only for pointers — no numeric conversion uses it.
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)
- Enums are sum types: a value is one of several variant types
- C-syntax:
type result = ok | err;— SLN:type result (enum ok err) - Same rules as tuples: all variants must be newtypes, no duplicates, minimum 2 variants
- Construction:
result: ok: 42(C) /(result ok:42)(SLN) — chain of upcasts - Match:
ok(value) => ...(C) /(ok value) ...(SLN) — binds the inner value - Compiled to C as tagged unions:
struct { uint8_t tag; union { ... } value; }
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
- Void functions omit the return type
- The last expression in the body is the return value
- Types and functions share a namespace — a name cannot be both a type and a function
- Arguments are matched by type, not by position. If parameters have distinct types, the caller can pass them in any order — the compiler reorders them automatically. Parameters with the same type keep positional order.
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
| Keyword | Effect | C equivalent |
|---|---|---|
| (none) | Internal linkage (default) | static |
pub | External linkage | no static |
extern | External declaration | function prototype |
import | File import / C header inclusion | #include (for .h) or source expansion (for .c.t/.sln.t) |
pubapplies tofn,const, andtype- A string directly after
pubdocuments the item:pub "Returns twice the input." fn twice(n: i32) -> i32 { n * 2 }. A public item without one is a lint warning;mainis exempt because the compiler publishes it itself pubfunctions cannot use anonymous tuple or enum types — T has no name manglingmainis always publicexternandimportare the opposite: importing external declarationsimport "file.c.t"expands the imported file's declarations into the current file (source-level)import "header.h"for C headers becomes#include "header.h"import "lib.th"imports a.thheader (syntax-independent, works from both C and SLN files)t header file.c.tgenerates a.thheader frompubdeclarations andextern fn- Circular imports are handled (each file is included at most once)
- Standard library files in
std/(next to the compiler binary) are searched as fallback - Available stdlib modules:
math.th,memory.th,string.th,file.th,process.th,convert.th
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:
| Item | Documentation |
|---|---|
type meters = f64 | A distance in meters. |
const ZERO: meters = meters: 0.0 | The zero distance. |
fn twice(meters) -> meters | Returns the sum of a distance with itself. |
Bindings
| Binding | Internal Type | Addressable | Mutable | Auto-deref |
|---|---|---|---|---|
let | T | no | no | no |
ref | &T | yes | no | yes |
var | |T | yes | yes | yes |
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
| SLN | C | Type |
|---|---|---|
42 | 42 | i32 |
0xFF | 0xFF | i32 (hex) |
0o77 | 0o77 | i32 (octal) |
0b1010 | 0b1010 | i32 (binary) |
3.14 | 3.14 | f64 |
0x14.8 | 0x14.8 | f64 (hex float = 20.5) |
1e300, 1.5e-5 | 1e300, 1.5e-5 | f64 (exponent) |
true, false | true, false | bool |
"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
| SLN | C | Description |
|---|---|---|
(+ a b) | a + b | Addition |
(- a b) | a - b | Subtraction |
(* a b) | a * b | Multiplication |
(/ a b) | a / b | Division |
(% a b) | a % b | Modulo |
(- a) | -a | Negation |
Comparison
| SLN | C | Description |
|---|---|---|
(== a b) | a == b | Equal |
(!= a b) | a != b | Not equal |
(< a b) | a < b | Less than |
(<= a b) | a <= b | Less or equal |
(> a b) | a > b | Greater than |
(>= a b) | a >= b | Greater or equal |
Logical
| SLN | C | Description |
|---|---|---|
(and a b) | a && b | Logical AND |
(or a b) | a || b | Logical OR |
(not a) | !a | Logical NOT |
Bitwise
| SLN | C | Description |
|---|---|---|
(& a b) | a & b | AND |
(| a b) | a | b | OR |
(^ a b) | a ^ b | XOR |
(~ a) | ~a | NOT |
(<< a n) | a << n | Left shift |
(>> a n) | a >> n | Right 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
- Integer match:
match value { 0 => ..., 1 => ..., _ => ... }(C) /match value (0 ...) (1 ...) (_ ...)(SLN) - Enum match:
match r { ok(v) => ..., err(c) => ... }(C) /match r (ok v) ... (err c) ...(SLN) - Variant patterns bind the inner value:
ok(v)extracts theokvariant and names itv _is the wildcard pattern (matches anything)- Match is an expression — the result of each arm becomes the value
- Compiled to C
switch— integer match on values, enum match on the tag
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 valuetype 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
- C-syntax:
target := value;— SLN:(set target value) - Works like
std::mem::replace— assigns new value and returns the old one - Left side must be a mutable pointer (
|T).varvariables are|T, sox := 20works directly - Multi-assignment (simultaneous, all RHS evaluated first):
- C:
x, y := y, x;— SLN:(set x y y x)— swap - C:
a, b, c := c, a, b;— rotation
- C:
- Capture old values:
let prev = current := get_next();—prevgets the old value - Mixed multi:
let a, b = x, y := y, x;— swap + capture old values in new bindings - Multi-let (shorthand for multiple declarations):
- C:
let x, y = 1, 2;— SLN:(let x 1 y 2) - Works with all binding modes:
var a, b = 1, 2;,ref r, s = a, b;
- C:
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
- Types inferred from initial values, or explicit:
p1: Type1 = init1(C) /(p1 p2) (Type1 Type2) (init1 init2)(SLN) - Arguments are evaluated in parallel before assignment
- Used for loops and forward jumps (skipping code)
- Labels can have zero parameters:
label skip();/label skip
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
- C-syntax:
defer statement;— SLN:(defer statement) - Deferred statements execute at the end of the enclosing function, and before every
return - Multiple defers execute in LIFO order (last deferred runs first)
- Useful for cleanup: closing files, freeing memory, restoring state
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
- C-syntax:
call(f, x)— SLN:(call f x) - First argument is the callable, rest are arguments
- Direct function calls use normal syntax:
twice(5)/(twice 5)
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
- A slice is a fat pointer:
{ data: *T, length: usize } - Full slice: C:
arr[]— SLN:(@ arr)— converts an entire array to a slice - Sub-slice: C:
arr[start, end]— SLN:(@ arr start end)— slice fromstarttoend(exclusive) - Element access unchanged: C:
arr[i]— SLN:(@ arr i)orarr@i - Slice elements are accessed the same way:
s[i]/(@ s i) - Slice type:
[T](C) /(slice T)(SLN). A mutable slice, whose elements can be written through:|[T](C) /(slice-mut T)(SLN).&[T]is the shared slice and means the same as[T] - Compiled to C as a struct with
datapointer andlengthfield - A slice over a
vararray can be written through (s[0] := 99reaches the array); over aletarray it is read-only. Passing it where[T]is expected works either way
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 slotsimport "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 syntax | Result |
|---|---|
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 counterimport "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.