T → Rust Interop Guide
How T maps to unsafe Rust — the second compilation target
Besides C, T compiles to Rust. The output is unsafe Rust: T has raw pointers and no borrow checker, so its pointer semantics map to *const T / *mut T rather than to references. As with the C backend there is no name mangling — every T identifier appears as-is in the generated code.
Generating Rust
t code --rust file.c.t # print the generated Rust t build --rust file.c.t # compile to a binary through rustc t run --rust file.c.t # compile and run
The flag overrides the default backend, which is C. Setting T_BACKEND=rust makes Rust the default, so plain t build goes through rustc.
Type Mapping
Primitive Types
T's primitives are Rust's primitives — bool, i8…i128, u8…u128, isize, usize, f32, f64 all keep their names. The diverging type never becomes !.
Pointers
| T | Rust | Notes |
|---|---|---|
&T | *const T | Shared (read-only) pointer |
|T | *mut T | Mutable pointer |
[T]N | [T; N] | Fixed-size array |
[T] | &[T] | Shared slice, carries its length |
|[T] | &mut [T] | Mutable slice, writes reach the array |
{T}N | [T; N] | SIMD vector, see below |
fn(A) -> B | fn(A) -> B | Function pointer |
null | std::ptr::null() / null_mut() | Chosen by the pointer's mutability |
Indexing a pointer becomes pointer arithmetic: data[i] with data: &i32 emits *data.add(i as usize). Indexing an array stays an index expression.
Newtypes
| T | Rust |
|---|---|
type meters = f64; | type meters = f64; |
type point = x & y; | struct point { pub x: x, pub y: y } |
type result = ok | err; | enum result { ok(ok), err(err) } |
Primitive newtypes become type aliases, not Rust newtype structs. That keeps T's cast system free: meters: 42.0 (construction) and d.f64 (downcast) are both no-ops in the generated code, and arithmetic on a newtype needs no operator impls. The distinctness of the type is enforced by T's own type checker before emission, so nothing is lost.
Tuple newtypes become structs whose fields are named after their member types, so p.x in T is p.x in Rust. Enum newtypes become real Rust enums, and match arms map to variant patterns: ok(value) => becomes result::ok(value) =>.
Why Unsafe
Every function is declared unsafe fn and its body is wrapped in an unsafe block. T has raw pointers, no lifetimes and no aliasing rules, so dereferences, pointer arithmetic and extern calls all need unsafe — wrapping the whole body avoids sprinkling the output with per-expression blocks, and marking the function itself keeps the obligation visible at every call site. Function pointer types follow suit: |fn(i32) -> i32 becomes unsafe fn(i32) -> i32. Only main stays safe, because Rust requires it.
This is the honest mapping: T is a C-level language, and the generated Rust carries exactly the same obligations the generated C does. If you want safe Rust with references and generics, compile Ty to Rust instead.
Bindings
| T | Rust |
|---|---|
let x = 5; | let x = 5; |
var v = 5; | let mut v = 5; |
x := 20 | std::mem::replace(&mut x, 20) |
x, y := y, x | temporaries, then assignment (parallel semantics) |
ref and var bindings are pointers in T's AST but plain locals in the output: they are auto-dereferenced in value contexts and auto-referenced where a pointer is expected. Passing a var to a |i32 parameter emits &raw mut v, and inside such a function the parameter is dereferenced on use, so pointer += 1 becomes *pointer += 1.
Entry Point
A main that returns a value becomes a Rust main returning ExitCode, so the exit status is the same one the C output would produce:
fn main() -> std::process::ExitCode {
fn exit_code() -> i32 { println!("{}", 1); 3 }
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 — including the implicit one around top-level statements — emits a plain fn main().
Control Flow
Rust has no goto, so label/jump is lowered structurally, depending on the direction of the jumps:
| T | Rust |
|---|---|
| backward jump (loop) | 'label_x: loop { … continue 'label_x; } |
| forward jump (skip) | 'label_x: { … break 'label_x; } |
| both directions | 'label_x: loop { if entry_pending_x { … } … } |
The third form is a loop whose body starts with the code that precedes the label, guarded by a flag that is cleared on the first pass. A forward jump breaks out of that guarded block and lands at the label; a backward jump continues the loop and skips the entry code, exactly as falling into the label does in C.
Label parameters become mutable locals declared before the loop or block; a jump assigns its arguments into temporaries first, then into the parameters, preserving T's parallel-assignment semantics. This T program
label loop(i = 0);
if i >= 3 { return; }
print("i =", i);
jump loop(i + 1);
becomes
let mut i: i32 = 0;
'label_loop: loop {
if i >= 3 { return; };
println!("{} {}", "i =", i);
{ let jump_value_0 = i.wrapping_add(1); i = jump_value_0; continue 'label_loop; }
}
What remains rejected is a jump that crosses a block boundary — a label declared inside an if and jumped to from outside it. Rust's labels are lexically scoped, C's goto is not, and there is no structural form for that case; it would need a state machine, which would cost every well-behaved label its readable output. No existing T program hits it.
Defer
Rust has no defer. Deferred statements are emitted at the end of the enclosing block in reverse order, and again before every return in that block. The observable behaviour matches the C backend.
Extern Functions
extern fn printf(format: &u8, ...) -> i32; becomes
unsafe extern "C" {
pub fn printf(_0: *const u8, ...) -> i32;
}
Parameter names of extern declarations are not kept by T's AST, so they appear as _0, _1, … in both backends. This is cosmetic: the call site passes arguments positionally.
A name declared extern more than once is rejected with Rust has no overloading: 'name' is declared more than once. Rust resolves an extern "C" name through the linker just like C does, and T does not mangle it.
Variadic C functions work, since Rust supports variadics in extern declarations. String literals become C string literals in pointer position (c"…".as_ptr().cast::<u8>()), so passing them to C functions is nul-terminated as expected. In print they stay ordinary Rust string literals.
Printing Floats
print formats floats the way C's %g does, because that is the defined behaviour of T's print and both backends have to agree. Rust's own Display for f64 prints the shortest representation that round-trips, which is a different — and for large values much longer — string: 599584916 where C prints 5.99585e+08.
The rule is six significant digits, scientific notation when the exponent is below -4 or at least 6, trailing zeros and a trailing decimal point removed. The generated code carries a small t_format_float helper for this, emitted only into modules that actually print a float.
This costs precision, exactly as the C backend does: 1.0 / 3.0 prints as 0.333333. T has no way to select a format yet.
Using the Output
The generated file is a standalone Rust program (or module) with no dependencies — only std. Three ways to use T code from a Cargo project, from most to least automatic.
From a build script, with tyre-build as a build dependency. This is the way to go for sources that use import, because the build script runs the real t compiler and gets import expansion for free:
fn main() -> Result<(), String> {
tyre_build::compile_t("src/shapes.c.t")?;
Ok(())
}
include!(concat!(env!("OUT_DIR"), "/shapes.rs"));
let doubled = unsafe { shapes::twice(21) };
The generated file declares pub mod shapes itself, named after the source file, so no wrapping module is needed at the include site. Changing the source triggers a rebuild. Set T_BIN if the t compiler is not on the PATH.
Embedded in Rust source, with the tyre-macro dependency. Good for short snippets; the macros do not expand import:
tyre_macro::t!(shapes, r#"
pub fn twice(n: i32) -> i32 { n * 2 }
"#);
tyre_macro::include_t!(counter, "src/counter.c.t");
Both take the module name first. include_t! resolves its path against the crate root and picks C or SLN syntax from the extension.
By hand: t code --rust lib.c.t > src/generated.rs, then mod generated; — the emitted #![allow(…)] attributes are inner attributes of the file, so this works as a module.
In all three cases T's pub becomes Rust's pub and everything else stays private to the module. Since there is no mangling, a T function keeps its exact name.
SIMD Vectors
A vector type {T}N becomes the array [T; N], and the operators become generated helper functions — a + b emits t_vector_add_i32_4(a, b), a loop over the lanes. Only the helpers a program actually uses are emitted. Indexing and vector literals need no help: they are already array syntax in Rust.
Rust has no stable portable SIMD type (std::simd is nightly-only), so this is the mapping that keeps the generated code buildable on stable. Whether the lane loop turns back into a SIMD instruction is left to LLVM's auto-vectorization, where the C backend states it in the source through GCC's vector extensions.
Arithmetic (+ - * / %), the bitwise operators (& | ^ << >>) and negation work; integer lanes wrap, matching the scalar case. Comparisons on vectors are rejected — in C they produce a mask vector, which has no counterpart here. The C backend does not currently emit working code for them either.
Unsupported
Almost everything T can express compiles. One case does not, and it is a borrow-checker rule rather than a gap: a slice over a var array is a mutable view, so it becomes &mut numbers[..]. Two such slices over the same array at the same time are legal T and rejected Rust — "cannot borrow numbers as mutable more than once". Over a let array both slices are shared views and any number of them coexist.