Ty Language Reference
Complete syntax and semantics for Ty
Ty extends T with generics, callable types, and impl blocks. All T syntax (newtypes, tuples, enums, pointers, arrays, control flow) works unchanged in Ty. This reference covers what Ty adds.
Types
Ty inherits all T types and adds generic parameters.
Generics
Type and function parameters are declared in square brackets:
fn identity[T] T -> T { it }
type x;
type y;
type Point[T] = x[T] & y[T];
let p = Point[f64] { x: 1.5, y: 2.5 };
print(p.x.f64, p.y.f64);
print(identity(42));Output:
1.5 2.5 42
| Feature | Syntax | Example |
|---|---|---|
| Generic function | fn name[T] ParamType -> R | fn identity[T] T -> T { it } |
| Generic type | type name[T] = inner; | type x; (shorthand for type x[T] = T;) |
| Explicit specialization | Name[ConcreteType] | Point[f64] { x: 1.5, y: 2.5 } |
| Inferred specialization | (automatic from arguments) | identity(42) infers T = i32 |
Generic types used in tuple fields are monomorphized transitively: Point[f64] also monomorphizes x[f64] and y[f64]. Field values are accessed using dot-type syntax: p.x returns the value as type x[f64], and p.x.f64 unwraps it to a plain f64.
Const Generics
Parameters with a type annotation are compile-time constants:
type N = u64; type Buffer[T]N = [T]N; let b = Buffer[i32]4: [1, 2, 3, 4]; print(b[0], b[3]);
Output:
1 4
Const parameters are declared as a suffix after ]. The parameter name must be a previously declared type. For example, type N = u64; declares N as a const-generic parameter name, then Buffer[T]N uses it. Const parameters are substituted during monomorphization: Buffer[i32]4 instantiates T = i32 and N = 4.
Const parameters support arithmetic in type positions (+, -, *, /):
type N = u64; type Pair[T]N = [T](N * 2); let p = Pair[i32]3: [1, 2, 3, 4, 5, 6]; print(p[0], p[5]);
Output:
1 6
Functions take const parameters the same way. A function that needs a const parameter but no type parameter writes an empty bracket pair before the suffix: fn dot[]N. Inside the body the parameter is an ordinary value, so it can drive a loop:
type N = u64;
type factor = f64;
type MV[T]N = [T]N;
type left[]N = MV[f64]N;
type right[]N = MV[f64]N;
fn dot[]N left[]N & right[]N -> f64 {
var total = f64: 0.0;
var i = u64: 0;
while i < N {
total += left[i] * right[i];
i += 1;
}
total
}
fn scale[]N left[]N & factor -> MV[f64]N {
var out = MV[f64]N: [0.0]N;
var i = u64: 0;
while i < N {
out[i] := left[i] * factor.f64;
i += 1;
}
out
}
fn main -> i32 {
let a = MV[f64]3: [1.0, 2.0, 3.0];
let b = MV[f64]3: [4.0, 5.0, 6.0];
print(dot[]3(a, b));
let right = scale[]3(a, factor: 2.0);
print(right[0], right[1], right[2]);
0
}Output:
32 2 4 6
Each call site fixes the length: dot[]3(a, b) instantiates N = 3, and the loop bound i < N becomes a constant after monomorphization. left and right are const-generic newtypes over MV[f64]N, which is what lets the two parameters of dot be told apart by type.
Arrays and Repeat Literals
Arrays use bracket-suffix syntax for their size:
| Syntax | Description | Example |
|---|---|---|
[T]N | Array of N elements | [i32]3 — three integers |
[T](expr) | Computed-size array | [f64](popcount(Blades)) |
[T] | Slice — pointer and length | [i32] — a run of integers of any length |
Array literals can use a repeat syntax: [value]count repeats the value count times:
let zeros: [f64]4 = [0.0]4; // same as [0.0, 0.0, 0.0, 0.0] let ones: [i32]3 = [1]3; // same as [1, 1, 1]
SIMD Vectors
A vector type is written with braces instead of brackets: {f64}4 is four lanes of f64. It indexes like an array, but arithmetic applies to all lanes at once, and the backend maps it onto the target's vector registers:
let a: {f64}4 = {1.0, 2.0, 3.0, 4.0};
let b: {f64}4 = {10.0, 20.0, 30.0, 40.0};
let sum: {f64}4 = a + b; // {11.0, 22.0, 33.0, 44.0}A vector literal needs at least one comma, because {x} is a block. A trailing comma is enough, so a single-lane vector is {x,} — which is also the form a macro must emit when it splices the lanes in: qq({$...(lanes),}).
The conversion form Type: value broadcasts a scalar into every lane. It builds a vector from the lane type and the lane count alone, so it works where a literal cannot: inside a function whose lane count is a const parameter, no vector of that type exists yet to copy from.
type MV[T]Blades = {T}(popcount(Blades));
fn spread[]Blades() -> f64 {
let lanes: MV[f64]Blades = MV[f64]Blades: 1.5;
lanes[0] + lanes[1]
}The lane count is a const expression, so vectors compose with const generics the same way arrays do. A vector wider than the target's registers is legal — the backend splits it:
type N = u64;
const fn twice(n: u64) -> u64 { n * 2 }
type Pack[T]N = {T}twice(N);
type left[]N = Pack[f64]N;
type right[]N = Pack[f64]N;
fn added[]N left[]N & right[]N -> Pack[f64]N {
left + right
}
fn main -> i32 {
let a = Pack[f64]2: {1.0, 2.0, 3.0, 4.0};
let b = Pack[f64]2: {10.0, 20.0, 30.0, 40.0};
let wide = Pack[f64]4: {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
let sum = added[]2(a, b);
let doubled = added[]4(wide, wide);
print(sum[0], sum[3], doubled[7]);
0
}Output:
11 44 2
Slices
An array has its length in its type, so a function that takes [i32]5 accepts arrays of exactly five elements. A slice drops the length from the type and carries it as a value instead: [T] is a pointer to the first element plus a count, which lets one function serve arrays of any size. The count is available as .length.
Two forms produce a slice from an array. numbers[] covers the whole array, numbers[start, end] covers the half-open range from start to end:
fn total(values: [i32]) -> i32 {
var sum = 0;
var i = usize: 0;
while i < values.length {
sum += values[i];
i += 1;
}
sum
}
fn main -> i32 {
let numbers = [1, 2, 3, 4, 5];
print(total(numbers[]));
print(total(numbers[1, 4]));
0
}Output:
15 9
The sub-slice numbers[1, 4] holds the three elements at indices 1, 2 and 3, so its .length is 3 while the full slice reports 5. A slice borrows the array it points into; it does not copy the elements, and it stays valid only as long as that array does.
In SLN a slice type is (slice T), and the two slicing forms are (@ numbers) and (@ numbers 1 4). Since a slice type has no name to bind the parameter to, the parameter is named explicitly: (param values (slice i32)).
Explicit Type Arguments
When the compiler cannot infer generic arguments, provide them explicitly:
fn identity[T] T -> T { it }
print(identity[f64](3.14));
print(identity[i32](42));Output:
3.14 42
identity[f64](3.14) explicitly specializes T to f64. This is required when the type cannot be inferred from the arguments alone.
Borrow Checking
A ref or var binding to an existing variable, and a slice taken from an array, are views: they name memory that belongs to something else. Ty checks that such a view never outlives what it points into, and it does so without lifetime annotations — the compiler infers what each value depends on and reads the lifetime of a borrow from its last use.
A view may not leave the scope that owns the memory. Returning one from a function is rejected:
fn leak() -> &i32 {
let x: i32 = 5;
ref r = x;
r
}reference to local 'x' outlives the scope it was created in
The same rule applies to a block, since a block that yields a slice of one of its own arrays leaves the slice pointing at memory that is already gone:
let escaped = {
let numbers: [i32]3 = [1, 2, 3];
numbers[]
};reference to local 'numbers' outlives the scope it was created in
While a borrow is alive, the memory behind it may not be written through another name. A borrow is alive from where it is created up to its last use, so the check depends on where a variable is read, not on where its block ends:
ref r = x; var m = x; m := 5; r
cannot write to 'x' through 'm' while 'r' still borrows it
Moving the last use of r above the second binding makes the same code legal — the borrow has ended by the time m is created. A let binding copies instead of borrowing and is never a view, so it never keeps anything alive and never blocks a write.
Ownership and Drop
A type is owning when it is declared with type, has an impl directly on itself, and its inner type names no fields — a pointer, an integer, a float, but not a tuple and not another newtype. Box[T] from the standard library is the example. That impl is its destructor; there is no reserved name and no trait. Types that fn desugars to, and newtypes over a tuple such as type add = a & b, are callables, not owning types.
For a value of an owning type the checker tracks moves. A value is moved when it is returned, bound to another let, passed to its own destructor, or passed to a parameter that consumes it (see Library Handles). A later use is an error, and the message says which of these happened:
import "box.c.ty";
fn main -> i32 {
let cell = make_box[i32](boxed[i32]: 7);
Box[i32](cell);
print(box_value[i32](cell));
0
}Borrow error: box_destroy.c.ty:6:26: use of 'cell' after it was destroyed on line 5
With free_box[i32](cell); on line 5 instead, the error reads use of 'cell' after it was consumed by 'free_box' on line 5: free_box passes its argument on to free, so calling it consumes the box.
A let-bound local of an owning type that is not moved anywhere in its block is dropped automatically at the end of that block: the compiler inserts a defer calling the destructor, after monomorphization, so Box[i32] and Box[f64] each get their own. Locals are dropped in reverse order of declaration. A local that was consumed, for example by free_box, is not dropped again.
Limits Function parameters are never dropped automatically. A local that is moved in any branch is not dropped on the other branches either, so it leaks there — never a double free. Collections owning many elements have no drop yet. Which newtypes count as owning is a rule of thumb, not a marker: a hand-written callable over a single primitive, such as type triple = i32; impl triple -> i32 { it * 3 }, is an owning type too, and a let-bound triple has its impl called when its block ends.
Library Handles
A library hands out objects that depend on each other: a device creates buffers, a buffer creates views, and a buffer must not outlive its device. Ty attaches these lifetimes to the values, not to reference types, so no pointer or reference has to appear in the signatures and nothing has to be annotated. An integer handle, such as an OpenGL name, works as well as a pointer:
type Device = i32;
type Buffer = i32;
type View = i32;
fn open_device(id: i32) -> Device { Device: id }
fn create_buffer(ref device: Device, size: i32) -> Buffer { Buffer: size }
fn create_view(ref buffer: Buffer) -> View { View: buffer.i32 }
fn view_size(ref view: View) -> i32 { view.i32 }
impl Device { print(10, it); 0 }
impl Buffer { print(20, it); 0 }
impl View { print(30, it); 0 }
fn main -> i32 {
let device = open_device(7);
let buffer = create_buffer(device, 64);
let view = create_view(buffer);
print(view_size(view));
0
}64 30 64 20 64 10 7
Each destructor prints its tag. The view is dropped first, then the buffer, then the device. Declare the constructors before the impl of the type they build: written after the impl, Device: id calls the destructor instead of converting.
A result depends on its arguments. The result of a call depends on every argument that is an owning value or depends on one, unless the result type is plain: no pointer, reference, slice, function or owning type, followed through newtypes. So buffer depends on device, view depends on buffer and through it on device, and view_size(view) is an i32 that depends on nothing. Only the signature is read, so the rule is the same for a function with a body and for an extern fn. Destroying the device while the view is still used is rejected:
let device = open_device(7);
let buffer = create_buffer(device, 64);
let view = create_view(buffer);
Device(device);
print(view_size(view));Borrow error: handles_early.c.ty:19:21: 'view' depends on 'device' (created from it on line 16), but 'device' was destroyed on line 18 Borrow error: handles_early.c.ty:16:5: 'buffer' depends on 'device' (created from it on line 16), but 'device' was destroyed on line 18, before 'buffer' is dropped at the end of its block
The second error is about the automatic drop: buffer would be destroyed at the end of main, after the device it belongs to. A dependency lasts until the dependent's last use, so destroying both by hand in the right order is accepted:
let device = open_device(7);
let buffer = create_buffer(device, 64);
print(buffer_size(buffer));
Buffer(buffer);
Device(device);
print(5);64 20 64 10 7 5
A dependency follows its value through a rename: after let moved = device;, destroying moved ends buffer as well, and the message says 'device' was moved into 'moved' on line … and destroyed on line …. A function may not return a value that depends on one of its own locals:
fn make_buffer() -> Buffer {
let device = open_device(7);
create_buffer(device, 64)
}Borrow error: escape.c.ty:12:5: the result of 'make_buffer' depends on local 'device' (declared on line 11), which is dropped when 'make_buffer' returns
A call consumes what it keeps. For a function with a body, the compiler infers whether a parameter is consumed: it is when the body destroys it, returns it, renames it, or passes it on to a consuming parameter. A close_device(device: Device) { Device(device); } therefore consumes its argument, and a later use reads use of 'device' after it was consumed by 'close_device' on line 13. An extern fn has no body to read, so its declaration says it: a parameter of an owning type, or of a mutable pointer, consumes the argument unless it is written ref. Passing a projection such as handle.|u8 to a consuming mutable-pointer parameter consumes handle itself; this is how a function that calls free becomes a consumer.
type Device = |u8;
type Buffer = |u8;
extern fn lib_create_device() -> Device;
extern fn lib_create_buffer(ref device: Device) -> Buffer;
extern fn lib_destroy_device(device: Device);
extern fn lib_release_buffer(buffer: Buffer);
extern fn lib_buffer_size(ref buffer: Buffer) -> u64;
impl Device { lib_destroy_device(it); 0 }
impl Buffer { lib_release_buffer(it); 0 }
fn main -> i32 {
let device = lib_create_device();
let buffer = lib_create_buffer(device);
lib_destroy_device(device);
print(lib_buffer_size(buffer));
0
}Borrow error: binding.c.ty:17:27: 'buffer' depends on 'device' (created from it on line 15), but 'device' was consumed by 'lib_destroy_device' on line 16
Without the lib_destroy_device(device); line the program checks, and the generated C ends main with impl_Buffer(buffer); before impl_Device(device);. Without ref on lib_create_buffer, creating the buffer consumes the device, and any later use of device reads use of 'device' after it was consumed by 'lib_create_buffer' on line 15.
ref Parameters
ref in front of a parameter means the function only borrows the argument. It is a checking mode only: the C and Rust backends emit the same by-value parameter with or without it. Both syntaxes accept it — fn f(ref device: Device) or the shorthand fn f(ref Device) in C syntax, (ref (param device Device)) or (ref Device) in SLN, and ((ref Device) Device) as the parameter list of an SLN extern — and ty fmt keeps it. On an extern fn, ref is the only way to say that a call does not consume. On a function with a body, the compiler checks that the body keeps its promise:
fn peek(ref device: Device) -> i32 { Device(device); 1 }Borrow error: ref_destroyed.c.ty:7:45: 'device' is a ref parameter of 'peek' and must not be destroyed on line 7
ref applies only where there is something to borrow. On a plain type it is an error:
extern fn abs(ref value: i32) -> i32;
Borrow error: ref parameter '_0' of 'abs' has the plain type 'i32'; ref applies only to owning values, values depending on them, and pointers
Limits The dependency rule over-approximates: a result depends on every owning or dependent argument, so a clone_buffer(ref device: Device, ref source: Buffer) -> Buffer makes the clone depend on the source too, and there is no way yet to opt out. A destructor has only it, so a release that needs the parent (vkDestroyBuffer(device, buffer)) is written as an ordinary consuming function. ref on a generic parameter is not checked for a plain type, because the type is unknown before monomorphization.
While Loops
while loops execute a block as long as a condition is true:
var i = 0;
var sum = 0;
while i < 5 {
sum += i;
i += 1;
}
print(sum);Output:
10
while is lowered to T's label/jump mechanism during compilation.
Impl Blocks
An impl block makes a type callable. Each type has at most one impl block.
type celsius = f64;
type to_fahrenheit = celsius;
impl to_fahrenheit -> f64 { celsius.f64 * 9.0 / 5.0 + 32.0 }
print(to_fahrenheit(celsius: 100.0));Output:
212
The impl body accesses the wrapped value using dot-type syntax: celsius.f64 unwraps the celsius newtype to its underlying f64.
| Syntax | Description |
|---|---|
impl Type -> R { body } | Callable impl on a concrete type |
impl[T] Type[T] -> R { body } | Generic callable impl |
Blanket Impls
A generic impl whose target is a structure, rather than a single named type, applies to every type that fits it. Ty has no traits, so there is no bound on T: any T that provides what the body uses compiles, and any other fails at compile time at the call that instantiates it.
// A blanket impl in Ty: `impl[T] describe[T] { ... }` is a generic impl whose target is a
// structure (`describe[T] = tag & T`), matching every `T` the way `impl[T] print & (string &
// T)` would in the owner's original shape (Ty has no traits, so there is no bound on `T`; any
// `T` that provides what the body calls on it compiles, any other fails at compile time — see
// `type_missing_field.c.ty`). `describe` is a user-declared operation, not `print`
// (`type print;` cannot be declared, `print` stays a hardcoded keyword).
type tag = i32;
type celsius = i32;
type inches = i32;
type describe[T] = tag & T;
impl[T] describe[T] {
print(it.tag.i32);
print(it.T);
}
fn main() -> i32 {
// Same blanket impl, two different `T`, two different outputs — proves the generic body
// actually depends on the bound type rather than always producing one value.
describe[celsius](1, celsius: 20);
describe[inches](2, inches: 12);
0
}Output:
1 20 2 12
Implicit Fields
Inside an impl block, tuple fields are available as implicit variables. No need to write it.field:
type x = f32;
type y = f32;
type Point = x & y;
impl Point -> f32 {
let x2 = x.f32 * x.f32;
let y2 = y.f32 * y.f32;
x2 + y2
}
print(Point { x: x: 3.0, y: y: 4.0 }!);Output:
25
x and y refer to the corresponding fields of the tuple. This works because each field becomes a function parameter named after its type.
Array Index Syntax
For array-based types, @N is shorthand for it[N]:
type add = [i32]2;
impl add -> i32 { @0 + @1 }
print(add(3, 7));Output:
10
it Keyword
it refers to the entire value inside an impl block. Use it when you need to pass the whole value to another function, rather than accessing individual fields:
type x = i32;
type y = i32;
type point = x & y;
fn total(p: point) -> i32 { p.x.i32 + p.y.i32 }
impl point -> i32 { total(it) } // pass the whole value
fn main -> i32 {
let q = point { x: 3, y: 4 };
print(q!); // prints 7
0
}Fields stay reachable through it as well: it.x.i32 + it.y.i32.
Callable Types
A type with an impl block is callable. Constructing it with () triggers evaluation:
type n = i32;
type twice = n;
impl twice -> i32 { n * 2 }
twice(5) // constructs twice { n: 5 }, evaluates → 10Arguments are matched to fields by type. For tuples with multiple fields, each argument matches the field whose type it satisfies.
Construction vs Evaluation
| Syntax | Semantics | Lisp analogy |
|---|---|---|
Name(args) | Construct + evaluate | (eval (list ...)) |
Name { fields } | Construct as data (never evaluates) | (quote ...) |
Name { fields }! | Construct + evaluate | (eval (list ...)) |
! Eval
! is the postfix eval operator. It evaluates a constructed value through its impl.
Type { fields }always constructs data without evaluation — even if the type has animplblock.Type { fields }!constructs and then evaluates (equivalent toType(args)).Type(args)is shorthand for constructing and evaluating in one step.data!evaluates an already-constructed value through its impl.
type a = i32;
type b = i32;
type pair = a & b;
let data = pair { a: 3, b: 7 };
print(data.a.i32, data.b.i32);
type add = a & b;
impl add -> i32 { it.a.i32 + it.b.i32 }
print(add(3, 7));Output:
3 7 10
add { a: 3, b: 7 } constructs the tuple without calling the impl. data! evaluates it afterwards. add(3, 7) combines both steps.
Functions
fn declares a callable type. The parameter types follow the name directly — no parentheses:
type n = i32;
fn twice n -> i32 { n.i32 * 2 }
type a = i32;
type b = i32;
fn max a & b -> i32 { if a.i32 > b.i32 { a.i32 } else { b.i32 } }Generic functions declare type parameters in square brackets:
fn identity[T] T -> T { it }
fn first[T & U] T & U -> T { it.T }const fn uses the traditional (name: type) syntax for compile-time functions:
const fn square(n: u64) -> u64 { n * n }fn Desugaring
Every fn is syntactic sugar for a type definition plus an impl block:
type n = i32;
fn twice n -> i32 { n.i32 * 2 }
// is equivalent to:
type twice = n;
impl twice -> i32 { n.i32 * 2 }This equivalence is the core of Ty's design: functions are callable types. Parameter types must be previously declared newtypes — duplicate parameter types are rejected.
Uniform Function Call Syntax
Any function or callable type can be called with dot syntax. x.f(y) is sugar for f(x, y):
type n = i32;
fn twice n -> i32 { n.i32 * 2 }
fn inc n -> i32 { n.i32 + 1 }
print(5.twice());
print(5.twice().inc());Output:
10 11
Since Ty matches arguments by type (not position), x.f(y) and y.f(x) are both valid. UFCS enables left-to-right chaining.
Monomorphization
Generic functions and types are monomorphized: each concrete instantiation produces a separate copy. identity[T] called with i32 and bool produces identity$i32 and identity$bool. The $ separator prevents collisions with user-defined names.
Monomorphization is transitive. Point[f64] also monomorphizes its fields x[f64] and y[f64]. Generic impl blocks are instantiated for each type the target is specialized with.
The monomorphized Ty code is then lowered to T (resolving impl blocks to functions, callable constructions to function calls) and compiled through T's C backend.
Const Functions
Functions marked const fn can be evaluated at compile time. They are used in type-level computations, such as computing array sizes from const-generic parameters. The multivector type type Blades = u64; type MV[T]Blades = [T]popcount(Blades); uses a const-generic Blades bitmask to determine how many elements to allocate.
const fn popcount(n: u64) -> u64 {
var count = u64: 0;
var remaining = n;
while remaining > 0 {
count += remaining & 1;
remaining := remaining >> 1;
}
count
}
const fn grade(blade: u64) -> u64 {
popcount(blade)
}
type Blades = u64;
type MV[T]Blades = [T](popcount(Blades));
type Vec3 = MV[f64]0b1110;
fn main() -> i32 {
let v = Vec3: [1.0, 2.0, 3.0];
print(v[0], v[1], v[2]);
print(grade(0b1110));
0
}Const functions support integer and float arithmetic, bitwise operations, comparisons, loops, conditionals, arrays, and casts. They can call other const functions. Const functions are also available at runtime as normal functions.
Named constants in types
Named constants declared with const are substituted in type-level expressions before monomorphization:
const FULL_3D: u64 = 0b1111_1111;
type Multivector3 = MV[f64]FULL_3D;
Compile-time type construction
Const functions can be used in generic type arguments to compute types at compile time. This enables patterns like grade-filtered multivector types:
const fn grade_filter(blades: u64, target_grade: u64) -> u64 {
var result: u64 = 0;
var bit: u64 = 0;
while bit < 64 {
if (blades >> bit & 1) > 0 {
if popcount(bit) == target_grade {
result := result | (1 << bit);
}
}
bit := bit + 1;
}
return result;
}
const FULL_3D: u64 = 0b1111_1111;
type Scalar3 = MV[f64](grade_filter(FULL_3D, 0)); // 1 element
type Vector3 = MV[f64](grade_filter(FULL_3D, 1)); // 3 elements
type Bivector3 = MV[f64](grade_filter(FULL_3D, 2)); // 3 elements
Compile-time field access
Array indices can be computed at compile time using const functions. This enables blade-indexed access on multivectors:
const fn blade_index(blades: u64, target_bit: u64) -> u64 {
var index: u64 = 0;
var bit: u64 = 0;
while bit < target_bit {
if (blades >> bit & 1) > 0 { index := index + 1; }
bit := bit + 1;
}
return index;
}
const VEC3: u64 = 0b1110;
const E1: u64 = 1;
let v: Vec3 = [1.0, 2.0, 3.0];
print(v[blade_index(VEC3, E1)]); // prints 1
Modules
A module is a named namespace. It is written as a block, or as a line that loads the module from a file next to the current one:
mod ga { ... } // the block form
mod ga; // loads ga.c.ty, or ga/mod.c.ty
Names inside a module are reached through a path with ::, and use binds a path, or every public name of a module, into the current scope:
use ga::length_squared;
use ga::*;
mod ga {
pub "The horizontal coordinate." type x = f64;
pub "The vertical coordinate." type y = f64;
pub "A point in the plane." type point = x & y;
pub "Returns the squared distance from the origin." fn length_squared point -> f64 {
let dx = point.x.f64;
let dy = point.y.f64;
dx * dx + dy * dy
}
}
use ga::*;
fn main() -> i32 {
let p = point { x: 3.0, y: 4.0 };
print(length_squared(p));
print(ga::length_squared(p));
0
}A string directly after pub documents the item, as in pub "A point in the plane." type point = x & y;. A public item without one is a lint warning. Together, those strings are the reference of a file:
| Item | Documentation |
|---|---|
type x = f64 | The horizontal coordinate. |
type y = f64 | The vertical coordinate. |
type point = x & y | A point in the plane. |
fn length_squared point -> f64 | Returns the squared distance from the origin. |
pub makes a declaration reachable from outside its module. Without it, a declaration is visible only in its own module and in that module's submodules; naming it from anywhere else is an error that says the path is not pub.
An unqualified name is looked up in the current module first, then in the modules around it, out to the file itself. The first match wins. Ty has no super:: or crate::, because a file is compiled as a whole and there is nothing to import across.
T has no modules, so ga::length_squared is lowered to ga_length_squared. If that name is also declared by hand, the compiler stops and names both declarations.
Imports
Ty supports two kinds of imports:
Ty imports
Import other .c.ty files. The imported file's source is expanded inline before parsing, so all types and functions become available:
type x = f32;
type y = f32;
type point = x & y;
fn distance point -> f32 {
let dx = point.x.f32;
let dy = point.y.f32;
dx * dx + dy * dy
}import "import_lib.c.ty";
fn main() -> i32 {
let p = point { x: 3.0, y: 4.0 };
print(distance(p));
0
}T imports
Import T files (.c.t) to use T functions and types. The T file is parsed separately and its declarations are merged into the compiled module:
import "math.c.t";
This gives access to all extern fn declarations and types defined in the T file. T's standard library modules can be imported by name:
import "math.c.t"; // sin, cos, sqrt, PI, ...
import "memory.c.t"; // malloc, free, memcpy, ...
import "string.c.t"; // strlen, strcmp, ...
import "file.c.t"; // fopen, fread, fwrite, ...
import "process.c.t"; // exit, system, getenv
import "convert.c.t"; // atoi, atof, strtol, ...
Import paths are resolved relative to the importing file. If not found, the compiler falls back to the standard library directory next to the binary.
Standard Library
Ty provides standard library modules in ty/std/. These import T's standard library and add Ty-specific types:
| Module | Contents |
|---|---|
math.c.ty | All of T's math (sin, cos, sqrt, PI, ...) plus radians/degrees newtypes with to_radians/to_degrees |
memory.c.ty | malloc, free, memcpy, ... |
string.c.ty | strlen, strcmp, strcpy, ... |
file.c.ty | fopen, fread, fwrite, ... |
process.c.ty | exit, system, getenv |
convert.c.ty | atoi, atof, strtol, ... |
option.c.ty | Option[T] with variants some[T]/none, plus is_some, unwrap_or and map_some |
result.c.ty | Result[T & E] with variants ok[T]/error[E], plus is_ok, is_error, unwrap_ok_or and map_ok; value.try propagates the error (see docs/ty-error-propagation.md) |
transform.c.ty | transform[T & U], the function type map_ok/map_some take |
box.c.ty | Box[T], a single heap cell, with make_box, box_value, set_box, free_box |
array.c.ty | Array[T], a growing heap buffer, with make_array, push, as_slice, array_get, array_set, array_length, free_array |
Box[T] is a newtype over |T, so it is a pointer with a name rather than a value with a header. make_box allocates one cell and stores the initial value in it. Box[T] has an impl directly on itself that frees the cell, which makes it an owning type (see Ownership and Drop): the cell below is freed automatically when main ends, without a call to free_box:
import "box.c.ty";
fn main -> i32 {
let cell = make_box[i32](boxed[i32]: 7);
print(box_value[i32](cell));
set_box[i32](cell, boxed[i32]: 9);
print(box_value[i32](cell));
0
}Output:
7 9
Array[T] is a tuple of a pointer, a length and a capacity. push returns the grown array instead of mutating its argument, because the buffer can move when it runs out of room and the caller has to learn the new address. as_slice hands the whole buffer out as a slice, so the ordinary slicing and indexing forms work on a heap array:
import "array.c.ty";
fn main -> i32 {
let one = make_array[i32](capacity: 1);
let two = push[i32](one, element[i32]: 10);
let three = push[i32](two, element[i32]: 20);
let numbers = push[i32](three, element[i32]: 30);
print(array_length[i32](numbers).usize);
print(array_get[i32](numbers, index: 2));
array_set[i32](numbers, index: 0, element[i32]: 7);
print(array_get[i32](numbers, index: 0));
let view = as_slice[i32](numbers);
print(view.length);
print(view[0]);
print(view[2]);
free_array[i32](numbers);
0
}Output:
3 30 7 3 7 30
The first three lines come from the Array[T] accessors; the last three are the slice view: length 3, first element, last element. A slice borrows the array's buffer, so it stays valid only until the array is freed or grown past its capacity.
Option and Result are ordinary generic enums — no compiler support behind them. Construction goes through the enum and the variant, both named: Option[i32]: some[i32]: 42. A match arm binds the payload by naming the variant, and an arm that ignores it uses _:
type some[T] = T;
type none = u8;
type Option[T] = some[T] | none;
type ok[T] = T;
type error[E] = E;
type Result[T & E] = ok[T] | error[E];
fn describe[T & E] Result[T & E] {
match Result {
ok(value) => print("ok", value),
error(cause) => print("error", cause),
}
}
fn main -> i32 {
let found = Option[i32]: some[i32]: 42;
let missing = Option[i32]: none: 0;
match found {
some(value) => print("found", value),
_ => print("missing"),
}
match missing {
some(value) => print("found", value),
_ => print("missing"),
}
describe(Result[i32 & u8]: ok[i32]: 7);
describe(Result[i32 & u8]: error[u8]: 3);
0
}Output:
found 42 missing ok 7 error 3
Each instantiation is monomorphized: Option[i32] becomes a tagged union whose variants are some$i32 and none. Since the parameter of a generic function is named after its type, the body of describe matches on Result, not on it.
Error Propagation: .try
Postfix .try unwraps a Result or returns its error from the enclosing function early. In SLN it is (try expression). Ty has no ? operator.
import "result.c.ty";
type numerator = i32;
type denominator = i32;
type limit = i32;
type value = i32;
fn divide numerator & denominator -> Result[i32 & u8] {
if denominator.i32 == 0 {
Result[i32 & u8]: error[u8]: 1
} else {
Result[i32 & u8]: ok[i32]: (numerator.i32 / denominator.i32)
}
}
fn check_below value & limit -> Result[i32 & u8] {
if value.i32 < limit.i32 {
Result[i32 & u8]: ok[i32]: value.i32
} else {
Result[i32 & u8]: error[u8]: 2
}
}
fn scaled_share numerator & denominator -> Result[i32 & u8] {
let share = divide(numerator.i32, denominator.i32).try;
Result[i32 & u8]: ok[i32]: (10 * check_below(share, 50).try)
}
fn report(outcome: Result[i32 & u8]) {
match outcome {
ok(amount) => print("ok", amount),
error(code) => print("error", code),
}
}
fn main -> i32 {
report(scaled_share(100, 4));
report(scaled_share(100, 0));
report(scaled_share(100, 1));
print(unwrap_ok_or[i32 & u8](scaled_share(100, 0), -1));
0
}Output:
ok 250 error 1 error 2 -1
The rules, each reported as a compile error at the .try:
- The enclosing function needs a declared return type, because the early return is built while its body is parsed.
- No conversion happens: the operand's error variant must be identical to the function's (
error[u8]intoerror[u8]). The success payload is free. .tryon anOptionreturnsnoneearly, inside a function returning anOption. MixingOptionandResultis refused.- Recognition is structural: any two-variant enum of
ok[…]/error[…], or ofsome[…]/none, counts, not only the standard library's.
Usage:
import "math.c.ty";
fn main() -> i32 {
let angle: degrees = degrees: 90.0;
print(sin(to_radians(angle).f64));
return 0;
}
You can also import T's stdlib directly with import "math.th" if you don't need Ty's wrapper types.
Operator Overloading
Operators on custom types are dispatched through callable tuples. The compiler matches binary operations to impl targets by convention:
| Operator | Wrapper type name |
|---|---|
+ | add |
- | sub |
* | mul |
/ | div |
% | rem |
== | equal |
!= | not_equal |
< | less |
> | greater |
<= | less_equal |
>= | greater_equal |
Define the wrapper type with type add; (shorthand for type add[T] = T;), then write the impl directly on the tuple add[T] & T:
import "operators.c.ty";
type x = f64;
type y = f64;
type vec2 = x & y;
impl add[vec2] & vec2 -> vec2 {
let a = it.add.vec2;
let b = it.vec2;
vec2 { x: (a.x.f64 + b.x.f64), y: (a.y.f64 + b.y.f64) }
}
impl sub[vec2] & vec2 -> vec2 {
let a = it.sub.vec2;
let b = it.vec2;
vec2 { x: (a.x.f64 - b.x.f64), y: (a.y.f64 - b.y.f64) }
}
fn main() -> i32 {
let a = vec2 { x: 10.0, y: 20.0 };
let b = vec2 { x: 3.0, y: 5.0 };
let sum = a + b;
let diff = a - b;
print(sum.x.f64, sum.y.f64);
print(diff.x.f64, diff.y.f64);
0
}The wrapper (add, sub) marks the left operand. In the impl body, it.add.vec2 unwraps it to vec2, and it.vec2 accesses the right operand directly.
Operator overloading only applies to named types (newtypes), not to primitives like i32 or f64. Inside an operator's own impl body, the same operator uses the built-in version to avoid infinite recursion.
Full example:
import "operators.c.ty";
type x = f64;
type y = f64;
type vec2 = x & y;
impl add[vec2] & vec2 -> vec2 {
let a = it.add.vec2;
let b = it.vec2;
vec2 { x: (a.x.f64 + b.x.f64), y: (a.y.f64 + b.y.f64) }
}
fn main() -> i32 {
let a = vec2 { x: 1.0, y: 2.0 };
let b = vec2 { x: 3.0, y: 4.0 };
let c = a + b;
print(c.x.f64, c.y.f64);
0
}Type construction
const fn popcount(n: u64) -> u64 {
var count = u64: 0;
var remaining = n;
while remaining > 0 {
count += remaining & 1;
remaining := remaining >> 1;
}
count
}
type blade_set_a = u64;
type blade_set_b = u64;
const fn xor_blades(a: blade_set_a, b: blade_set_b) -> u64 {
a ^ b
}
const fn union_blades(a: blade_set_a, b: blade_set_b) -> u64 {
a | b
}
type Blades = u64;
type MV[T]Blades = [T](popcount(Blades));
type Vec3 = MV[f64]0b1110;
type Rotor3 = MV[f64]0b0100_1001;
type Test1 = MV[f64](xor_blades(0b1010, 0b0110));
type Test2 = MV[f64](union_blades(0b1010, 0b0110));
fn main() -> i32 {
let v = Vec3: [1.0, 2.0, 3.0];
let r = Rotor3: [1.0, 2.0, 3.0];
let t1 = Test1: [10.0, 20.0];
let t2 = Test2: [10.0, 20.0, 30.0];
print(v[0], v[1], v[2]);
print(r[0], r[1], r[2]);
print(t1[0], t1[1]);
print(t2[0], t2[1], t2[2]);
print(popcount(xor_blades(0b1010, 0b0110)));
print(popcount(union_blades(0b1010, 0b0110)));
0
}Blade access
const fn popcount(n: u64) -> u64 {
var count = u64: 0;
var remaining = n;
while remaining > 0 {
count += remaining & 1;
remaining := remaining >> 1;
}
count
}
type blade_set = u64;
type blade_bit = u64;
const fn blade_index(blades: blade_set, target_bit: blade_bit) -> u64 {
var index = u64: 0;
var bit = u64: 0;
while bit < target_bit.u64 {
if (blades.u64 >> bit & 1) > 0 {
index += 1;
}
bit += 1;
}
index
}
type Blades = u64;
type MV[T]Blades = [T](popcount(Blades));
const VEC3_BLADES: u64 = 0b1110;
type Vec3 = MV[f64]VEC3_BLADES;
const E1: u64 = 1;
const E2: u64 = 2;
const E3: u64 = 3;
fn get_e1 Vec3 -> f64 { Vec3[blade_index(blade_set: VEC3_BLADES, blade_bit: E1)] }
fn get_e2 Vec3 -> f64 { Vec3[blade_index(blade_set: VEC3_BLADES, blade_bit: E2)] }
fn get_e3 Vec3 -> f64 { Vec3[blade_index(blade_set: VEC3_BLADES, blade_bit: E3)] }
fn main() -> i32 {
let v = Vec3: [1.0, 2.0, 3.0];
print(get_e1(v), get_e2(v), get_e3(v));
print(blade_index(blade_set: VEC3_BLADES, blade_bit: E1));
print(blade_index(blade_set: VEC3_BLADES, blade_bit: E2));
print(blade_index(blade_set: VEC3_BLADES, blade_bit: E3));
0
}Type casting
const fn popcount(n: u64) -> u64 {
var count = u64: 0;
var remaining = n;
while remaining > 0 {
count += remaining & 1;
remaining := remaining >> 1;
}
count
}
type blade_set = u64;
type blade_bit = u64;
const fn blade_index(blades: blade_set, target_bit: blade_bit) -> u64 {
var index = u64: 0;
var bit = u64: 0;
while bit < target_bit.u64 {
if (blades.u64 >> bit & 1) > 0 {
index += 1;
}
bit += 1;
}
index
}
const fn has_blade(blades: blade_set, bit: blade_bit) -> u64 {
(blades.u64 >> bit.u64) & 1
}
type Blades = u64;
type MV[T]Blades = [T](popcount(Blades));
const VEC3: u64 = 0b1110;
const FULL3: u64 = 0b1111_1111;
type Vec3 = MV[f64]VEC3;
type Full3 = MV[f64]FULL3;
fn vec3_to_full Vec3 -> Full3 {
var result = Full3: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
var bit = u64: 0;
while bit < 8 {
if has_blade(blade_set: VEC3, blade_bit: bit) > 0 {
let src = blade_index(blade_set: VEC3, blade_bit: bit);
let dst = blade_index(blade_set: FULL3, blade_bit: bit);
result[dst] := Vec3[src];
}
bit += 1;
}
result
}
fn main() -> i32 {
let v = Vec3: [1.0, 2.0, 3.0];
let full = vec3_to_full(v);
print(full[0], full[1], full[2], full[3]);
print(full[4], full[5], full[6], full[7]);
0
}Grade-filtered types
const fn popcount(n: u64) -> u64 {
var count = u64: 0;
var remaining = n;
while remaining > 0 {
count += remaining & 1;
remaining := remaining >> 1;
}
count
}
const fn grade(blade: u64) -> u64 {
popcount(blade)
}
type blade_set = u64;
type blade_grade = u64;
const fn grade_filter(blades: blade_set, target_grade: blade_grade) -> u64 {
var result = u64: 0;
var bit = u64: 0;
while bit < 64 {
if (blades >> bit & 1) > 0 {
if grade(bit) == target_grade {
result := result | (1 << bit);
}
}
bit += 1;
}
result
}
type Blades = u64;
type MV[T]Blades = [T](popcount(Blades));
const FULL_3D: u64 = 0b1111_1111;
type Multivector3 = MV[f64]FULL_3D;
type Scalar3 = MV[f64](grade_filter(FULL_3D, 0));
type Vector3 = MV[f64](grade_filter(FULL_3D, 1));
type Bivector3 = MV[f64](grade_filter(FULL_3D, 2));
type Trivector3 = MV[f64](grade_filter(FULL_3D, 3));
fn main() -> i32 {
let s = Scalar3: [1.0];
let v = Vector3: [1.0, 2.0, 3.0];
let b = Bivector3: [4.0, 5.0, 6.0];
let t = Trivector3: [7.0];
let mv = Multivector3: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
print(s[0]);
print(v[0], v[1], v[2]);
print(b[0], b[1], b[2]);
print(t[0]);
print(mv[0], mv[1], mv[2], mv[3], mv[4], mv[5], mv[6], mv[7]);
0
}Macros
Macros are expanded before parsing and are therefore the same in Ty and in T, in both syntaxes. They are documented separately in Macros.