Ty → Rust Interop Guide
How Ty maps to safe Rust — without going through T
Ty has two backends. The C backend lowers Ty to T first, which monomorphizes generics and erases impl blocks. The Rust backend skips that path and emits Rust directly from the Ty AST, because Rust already has the features T lacks: generics, references, and a borrow checker.
Both backends run the whole example corpus today. A few C-level constructs still have no Rust form — see Current Limits.
ty code --rust file.c.ty # print the generated Rust ty build --rust file.c.ty # compile to a binary through rustc ty run --rust file.c.ty # compile and run
TY_BACKEND=rust makes Rust the default, so plain ty build goes through rustc.
Generics
Ty generics become Rust generics — one function, not one copy per instantiation. This program
fn identity[T] T -> T { it }
print(identity(42));
print(identity(true));
becomes
pub fn identity<T>(it: T) -> T { it }
fn main() { println!("{} {}", identity(42), identity(true)); }
Through the C backend the same source produces two mangled functions, identity$i32 and identity$bool. Rust monomorphizes at its own level, so the T-level mangling is unnecessary — and the emitted code stays readable.
A const generic parameter is emitted as const N: usize regardless of the integer type it carries in Ty, because that is the only type Rust accepts for an array length; where the parameter is used as a value, the original type is cast back in.
A length computed from a const parameter — type MV[T]Blades = [T](popcount(Blades)) — cannot appear in a Rust signature as written: stable Rust rejects "generic parameters in const operations". Such an alias is not emitted at all; each use site is expanded with its arguments substituted, so MV[f64]0b1110 becomes [f64; popcount(14) as usize], which rustc folds at compile time. Rust type aliases are transparent anyway, so nothing is lost by not declaring them.
Where the arguments are not concrete — a function that stays generic over Blades — the length is lifted into a const parameter of its own. This
fn zero[]Blades(MV[f64]Blades) -> MV[f64]Blades { … }
becomes
pub fn zero<const Blades: usize, const LENGTH0: usize>(MV: [f64; LENGTH0]) -> [f64; LENGTH0] { … }
and every call gets the length as a further argument: zero::<{ SET }, { popcount(SET) as usize }>(v), or the caller's own LENGTH0 where the call is itself generic. One LENGTHn parameter is added per distinct computed length in the signature, in order of first appearance, and the same numbering applies to structs. The original parameter stays because the body still needs the value — popcount(Blades) as an ordinary expression is fine, it is only the type position stable Rust closes off.
This keeps the library generic instead of monomorphizing it, which is what makes a Ty geometric-algebra layer usable from Rust with one copy of each function rather than one per blade set.
Callable Types
A Ty impl block on a type makes that type callable. In Rust it becomes a plain function named after the type:
type n = i32;
type twice = n;
impl twice -> i32 { n.i32 * 2 }
emits pub fn twice(_n: n) -> i32 { (_n * 2) }. The implicit it parameter is named after the field type; where the field name would shadow its own type name, the parameter is prefixed with an underscore. Calls in Ty (twice(5)) need no translation, they are already Rust calls.
Operator Overloading
An impl add[vec2] & vec2 -> vec2 makes + work on vec2. In Rust the impl stays a plain function and the operator becomes a call to it:
let c: vec2 = a + b;
let c: vec2 = _t_add_vec2(a, b);
No impl std::ops::Add is synthesized. Ty's semantics are a function call, and a call is what the operator means — wrapping it in a trait would add a layer that nothing reads back.
The operand types are matched through their aliases, so an impl written against MV[f64]Blades is found for an operand typed left[]Blades. Where the impl is generic, its arguments are recovered from the operand types and emitted as a turbofish — mul_mv::<{ Blades }, { LENGTH0 }>(left, right) — because a const parameter that only appears inside a computed length cannot be inferred.
An operator used on a generic parameter is a different case: there the backend infers a trait bound from the body, so impl[T] add[T] -> T { @0 + @1 } emits pub fn add<T: std::ops::Add<Output = T>>(_0: T, _1: T) -> T. Printing a generic value likewise adds std::fmt::Display.
Enums
A Ty sum type becomes a Rust enum, one variant per member type:
type Option[T] = some[T] | none; let found: Option[i32] = Option[i32]: some[i32]: 42;
enum Option<T> { some(some<T>), none(none) }
let found: Option<i32> = Option::<i32>::some(42);
Matching maps directly: some(value) => … becomes Option::some(value) => …. Through the C backend the same type becomes a tagged union with one monomorphized copy per instantiation; in Rust it stays generic.
References
Ty's pointer syntax maps to Rust references rather than raw pointers, which is what makes the output safe: &T becomes &T, |T becomes &mut T. The only unsafe that appears is around a call to an extern fn, where Rust requires it — abs(value) becomes unsafe { abs(value) }. Ty code without a C binding contains none.
For the C-level language, the corresponding mapping is raw pointers inside unsafe — see the T → Rust Interop Guide.
Shared with T
Everything Ty inherits from T maps as it does in the T backend: primitive newtypes become type aliases (so Type: value and .Type casts are no-ops), tuple newtypes become structs with fields named after their member types, print becomes println!, and blocks, if/else, match and while map one-to-one.
Entry Point and const fn
A Ty main that returns a value becomes a Rust main returning ExitCode, so the exit code survives the translation:
fn main() -> i32 { print(total(a)); 0 }
fn main() -> std::process::ExitCode {
fn exit_code() -> i32 { println!("{}", total(a)); 0 }
std::process::ExitCode::from(exit_code() as u8)
}
The inner function is what lets return inside main keep its own type. A main without a return type emits a plain fn main().
const fn carries over to Rust's const fn, which is what makes a constant computed by a function usable as an array length. Loops are allowed there, so the usual bit-counting helpers translate unchanged.
Using the Output
Ty code can be pulled into a Cargo project the same three ways T code can, and the result is safe Rust — the caller needs no unsafe.
From a build script, with tyre-build as a build dependency. This is the only way that expands import, since it runs the real ty compiler:
fn main() -> Result<(), String> {
tyre_build::compile_ty("src/measure.c.ty")?;
Ok(())
}
include!(concat!(env!("OUT_DIR"), "/measure.rs"));
let doubled = measure::twice(21);
The generated file declares pub mod measure itself, named after the source file. Changing the source triggers a rebuild. Set TY_BIN if the ty compiler is not on the PATH.
Embedded in Rust source, with the tyre-macro dependency:
tyre_macro::ty!(measure, r#"
type n = i32;
fn twice n -> i32 { n.i32 * 2 }
"#);
tyre_macro::include_ty!(scale, "src/scale.sln.ty");
Both take the module name first. include_ty! resolves its path against the crate root and picks C or SLN syntax from the extension. The macros do not expand import.
By hand: ty code --rust file.c.ty > src/generated.rs, then mod generated;.
Current Limits
Every example shipped in examples/ty/ compiles through this backend and prints what the C backend prints — a test in ty-backend_rust/tests/corpus.rs compiles each one both ways and compares the output. The geometric-algebra library and the SDF renderer that uses it compile as well, which is what the const-parameter and operator work above was measured against. What is still missing:
- Raw
label/jumpcontrol flow — Rust labels are lexically scoped, Cgotois not. Usewhile. - Defer — no equivalent is emitted; the C backend remains the way to run one.
- Variadic extern functions — Rust has no stable syntax for calling them safely.
- Const field access and const tuple construction in type-level expressions.
- SIMD vectors — a
{T}Nvector maps to[T; N], but arithmetic on a whole vector is not lowered to per-lane operations the way the T backend does it.
Everything unsupported reports an error instead of silently producing wrong code. The C backend remains the reference implementation; use ty build without a flag when in doubt.
Both backends run the same borrow check on the Ty source before emitting anything, so a program that lets a view outlive what it points into, or that writes through one name while another still borrows it, is rejected with a Ty error and a Ty line number rather than with an rustc error pointing at generated code. The rules are described under Borrow Checking.