Records (roadmap #16)
type Vec2 = Vec2(x: Float, y: Float)
type Particle = Particle(pos: Vec2, vel: Vec2, alive: Bool)
let o = Vec2(y: 0.0, x: 0.0) # named arguments, any order
o.x # field access
fn fall(p, dt):
p.with(vel: p.vel.with(y: p.vel.y - 9.8 * dt)) # copy with changes: in place when unique
match s:
Circle(r: r) => ... # named patterns; other fields are `_`
What exists
- Named fields on any constructor: either all of a constructor's fields are named, or none are. A record is just a data type whose constructors have named fields. Multi-variant types can share fields (
Circle(name: Str, r: Float) | Rect(name: Str, ...)), and a shared field must have the same type in every variant that has it. - Construction works by position or by name, with the named arguments in any order. The errors cover a missing field, an unknown field, a field given twice, and named arguments passed to an ordinary function.
- **
r.freads a field.** It is only allowed when every variant ofr's type hasf, so a field read can never fail at run time. Otherwise the error says which variant lacks the field and suggestsmatch. The record's type is inferred from the field name. When several types share the name, the decision waits until the type is known, or the checker asks for an annotation. - **
r.with(f: v, ...)** gives a copy with some fields replaced, and type-checks each new value against its field. - Named patterns:
Circle(r: radius). Fields that aren't mentioned are wildcards. - Inference and hashing. No annotations are needed, as in
step : (Particle, Float) -> Particle. Field names are part of a type's meaning in the hash store, like constructor names.
How it is implemented: no engine changes
- At parse time, named arguments and named patterns become positional (
src/records.rs). - After type checking,
r.fandr.with(..)become ordinarymatchexpressions, using the record type the checker resolved for each one. The interpreter, VM, native backend, bounds prover and fuzzer all just see matches. - A chain likep.pos.xbecomes one match with nested patterns, so no intermediate record is copied. The exhaustiveness checker now treats single-constructor patterns as always matching. - The lowered program must type-check again; if it doesn't, that is a hard internal error. This check caught a real gap, an exhaustiveness false positive on nested patterns. Before it existed, the VM would have quietly lost type information.
Value semantics that run in place
A record update never changes what anyone else sees. Yet the particle simulation in examples/records.tr allocates only its initial objects:
| pipeline | allocations | reused in place | refcount overhead removed |
|---|---|---|---|
| borrowing only | 30,205 | 0 | 60.5% |
| borrowing + drop-reuse (default) | 627 | 150,000 | 100% |
That run is 200 particles × 150 steps, with each step updating the particle and two nested Vec2s. Three mechanisms make it work:
- Rebuilds reuse their own cell. In
r.with(..), the new values are computed before the record is taken apart, as in Rust'sS { f: e, ..r }. The record is therefore dead when it is rebuilt, and drop-reuse rebuilds it in the same memory. - Nested updates are taken apart first. In
p.with(vel: p.vel.with(...)),pis a variable that the new values use only through its fields. Sopis taken apart first andp.velreads the field directly. Both levels are then unique, and both are rebuilt in place. - List elements are taken out, not copied (new
takereads). Withps[i] = step(ps[i]), the old read copied the element, so it was shared andstephad to allocate. Now, when nothing touches the list between the read and the write, and nothing in between can leave early, a unique list gives up the element (leaving a placeholder that the write replaces). This works in the VM and natively (rt_index_take). Shared lists still copy:let ys = xs; xs[0] = xs[0].with(...)leavesysuntouched, and that case is tested.
Speed. The new particles benchmark updates 1,000 particles for 300 steps with .with(...). It takes 4.0 ms natively, against 67.7 ms for idiomatic mutable Python dataclasses (17× faster), with identical output.
Evidence
- Golden program
examples/records.tr. It produces identical output in the interpreter, 4 VM strategies and native code, with 0 leaked objects. The testrecords_update_in_placechecks the inferred types, at least 90,000 reuses and fewer than 1,000 allocations. - Six error tests: - a field that doesn't exist; - a field only some variants have; - a missing constructor argument; - an update with the wrong type; - named arguments to a function; - a field name shared by two types, with nothing to tell them apart.
- Fuzzer coverage. Generated programs include a two-variant record type with shared fields. They exercise construction by name in any order, reads,
withwith one or two fields, named patterns, and in-place element updates of record lists with shared elements. - 70,000 program cases ran clean (interpreter vs 5 VM strategies). - 2,600 native cases and 30,000 syntax mutations ran clean. - No regressions: all 24 tests pass, and the benchmark suite shows no slowdowns.
Honest notes
- Printing still shows positions,
Vec2(1.0, 2.0), notVec2(x: 1.0, y: 2.0). Showing names would need field-name tables in all three engines. - **
==and<on records** are structural or unavailable, as before. User impls of the operator traits remain a follow-up from #19. - Updates evaluate the new values before the record. This only matters if both have side effects, such as
printinside an update value. - Named arguments work for constructors only. Applying them to functions would need scope analysis, because a local could shadow a function's name.
- Element takes need a straight line between the read and the write, with no loops and no early exits in between.
for p in ps:-style updates of records would need a mutable loop variable, which is roadmap work.