Skip to content

@value types: Vector/Color/Ray/Intersection as values; ray tracer 2.7-4.7x faster - #684

Merged
ASDAlexander77 merged 28 commits into
mainfrom
value-types
Oct 24, 2026
Merged

ASDAlexander77 merged 28 commits into
mainfrom
value-types

Conversation

@ASDAlexander77

Copy link
Copy Markdown
Owner

Adds an opt-in @value marker for classes and interfaces. A @value type is a value object: its fields are readonly, it has no identity, it is stored by value (no heap allocation), and it behaves exactly as the same TypeScript would. Anything that cannot be compiled that way is an error that names the reason.

The ray tracer benchmark marks Vector, Color, Ray and Intersection and leaves its object literals as they are. Medians of two bench.ps1 runs:

Model Before @value vs Rust idiomatic (55 ms)
own 444 ms 148 ms 2.7x
none 434 ms 165 ms 3.0x
rc 630 ms 172 ms 3.1x
gc 1199 ms 255 ms 4.7x

Every model prints checksum 38837369. The goal of about 60 ms is not reached. tslang/benchmarks/raytrace/README.md ("Results 2026-10-24: @value") says where the rest goes. Measured variants that remove the addLight closure's capture cells, the | null result and the virtual calls bring none and own to 58 ms.

What @value does

  • One MLIR type, !ts.value<@Name, !ts.tuple<...>>, for both classes and interfaces. It lowers to the LLVM struct of its tuple, and a cast to or from that tuple is free. Conversion into a @value class is nominal; conversion into a @value interface is structural.
  • @value classes: new fills a stack slot, methods take this by value, statics are globals, and there is no vtable. No extends, implements, type parameters, setters, abstract, @final or @cpp.
  • Readonly as TS2540: a field can only be assigned as this.f = ... directly in the class's own constructor.
  • Inside a @value constructor or a field initializer, this cannot be used as a whole value (const self = this, f(this), readonly f = mk(this)). A copy taken there would miss the fields assigned after it.
  • A closure that captures a @value constructor's this may only be called directly in that constructor.
  • === between values, instanceof, and a type that contains itself are errors that name the reason. "Contains itself" includes a path through another value's fields ('b.a') or the type arguments of a generic class (Box<L>), in either declaration order.
  • A @value field is never typed as an unspecialized generic: a generic whose argument is declared later is retried, and an unknown argument is an error. (Before, Box<K> with K declared later silently got the bare Box layout.)
  • Missing values: T | null, T | undefined, v?: T and f?: T share one three-state encoding. Reading a field of a missing value throws, the same way a member access on a null interface does. ?. skips the rest of the chain.
  • Values holding references work under gc, rc and own, through generics and closures.
  • Under -mm=own, a tuple that borrows and owns nothing is an unboxed record (own spec §36).
  • -shared export and import, including nested and optional values.

Design: tslang/docs/superpowers/specs/2026-10-24-value-types-design.md. Plan: tslang/docs/superpowers/plans/2026-10-24-value-types.md.

Changes for code without @value

  • ?. now skips the whole rest of the chain once it meets null or undefined, as TypeScript does. Before, t?.a.b on a missing type-literal object read 0, and the same chain through a null class object crashed at run time. Chains used in &&/|| now print the existing "casting from optional (undefined) value" warning, because the chain is correctly typed T | undefined.
  • -shared: __decls imports now go through the same retry loop as import-as-source, so an interface that refers to a type declared after it imports instead of failing with "can't find type by name".
  • -mm=own: §36 also applies to plain type-literal tuples, so own accepts more programs. 00spread now compiles under own. own_err_record_literal_let_field still fails, at 12:5 instead of 10:11. recordRetainOf looks through all views, fieldOnlyRead/fieldTakersOf return early for fields that hold no block, and non-escaping closures accept more frame storage. Nothing that compiled before is rejected.

Known gaps (follow-ups)

  • -mm=own rejects some TS-valid @value shapes cleanly: a record converted to an ordinary interface, reading an element of an array of @value values (const a = recs[0]), owning literals pushed into arrays (-mm=own: a tuple of owned values, and a record a call returns, are values #679), and closures nested in @value methods.
  • A @value type that refers to itself through an array or a generic class (next: L[], box: Box<L>) is rejected; that needs a recursive value type.
  • ""?.x treats the empty string as missing (pre-existing in single-link ?.; the chain short-circuit now shares that test).
  • indexOf/includes on values report the identity error inside lib.generics.ts, not at the user's call.
  • An own export of a borrowing return without @lends gets a generic message.
  • Benchmark: the closure capture cells, the 88-byte | null result (its tag test is a strcmp), and the virtual calls.

Tests

The full suite passes 5744 of 5744 on Windows. New tests are under tslang/test/tester/value/, plus own tests (own_value_*, own_err_value_*) and the -shared pairs export_value_types/import_value_types and the forward-reference pair. Not run on Linux locally.

🤖 Generated with Claude Code

ASDAlexander77 and others added 28 commits October 24, 2026 10:20
ProcessHeapPass marked __tslang_heap_malloc/calloc/aligned_alloc as
writing other memory and gave their result no `noalias`. So every
allocation clobbered whatever the program had just stored: a field
written into a fresh object was loaded back from the heap after the
next `new` instead of reused, and the object could never be deleted.
In the ray tracer every vector of `Vector.plus(Vector.times(k, d), p)`
stayed on the heap although LLVM had inlined the helpers.

An allocation now touches only the allocator's state
(`memory(inaccessiblemem: readwrite)`) and returns a `noalias` block,
as LLVM's own malloc does. Writing the allocator's state still keeps two
equal allocations from merging (the GC_malloc case in GCPass).

Ray tracer, 512x512, median of 7: own 597 -> 444 ms, none 642 -> 434 ms,
gc unchanged (its own allocator), rc 606 -> 630 ms. The benchmark README
records the numbers and what is left between own and Rust.

Test: 00fresh_objects_folded.ts runs, and fresh-objects-folded.cmake
checks that the optimized IR of `keep` loads no field back under none,
rc and own (it fails before this change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A marked class or interface is a value of its readonly fields: no heap
object, no identity, copied on assign, pass and return. Aimed at the ray
tracer's Vector/Color/Ray/Intersection allocations; the benchmark keeps
its object literals as written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…minal conversion

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…is an error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… intersection members too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ll ternary

A @value interface's type is taken only once all its fields are resolved
(getValueTypeOfInterfaceIfLaidOut, as getValueTypeOfClassIfLaidOut does for a
class): `Hit { thing: Thing }` declared before `Thing { intersect(): Hit | null }`
gave Thing's method the Hit of the first discovery pass (fields resolved so
far), and the class implementing Thing the complete one, so the signatures did
not match. Its fields are also laid out in declaration order, not in the order
the passes resolved them.

An object literal received as a @value type that may be missing (`T | null`)
is built as the T, so `c ? { d: 1 } : null` is the missing type of T and null
rather than a cast of `null | {d}` to T.

Tests: value_iface_cycle (gc rc none), value_ternary_null (gc rc none own),
AOT and JIT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tuple that holds borrows and owns nothing - a @value record such as the
ray tracer's Intersection, or a type literal - is a borrowing record with no
box (own spec 36): its uses are bounded by what it borrows, as a boxed
record's are, and nothing of it is counted or released.

Signature pass:
- classifyUnboxedRecord: an object literal's local whose read is never boxed,
  read whole, whose block-holding fields all borrow (this, a parameter, a place
  read, a borrowing call's result, a let's value, a captured variable's, an
  immortal value; a fresh value only in a temporary given to calls that do not
  keep it). Never a handle, a string, or a generator state's field. Marked
  __own_record_unboxed_fields (+ __own_record_temporary); its reads are records.
- Facts.unboxed / __own_result_record_unboxed beside __own_result_record; boxes
  and unboxed records in one value or on two return paths give no facts; an
  exported @Lends @record function returning one is an error.
- The type walkers read a @value type as its storage tuple (asStorageTuple):
  castMakesInterface(value, tuple) opened Thing, so S.intersect's facts were
  "reached through an interface".

Inference pass:
- classifyRecords takes the unboxed records; walkRecord follows a field taken
  out of the tuple (ExtractProperty) and a field read in place out of the local
  that holds it (PropertyRef of the local or of its storage-tuple cast), whose
  write is a keep; a temporary's fresh field is bounded by its own release.
  The flow and release walks look through that cast too (slotVariableOf,
  valuesStoredInto).
- unboxedRecordFlow: such a value has no owner check, its retains go, and
  dropUnboxedRecordCounts erases every retain/release of it and of locals that
  hold only such values (edge releases too); a local or merge mixing one with
  an owning value is an error.
- isView: a cast between a @value type and its storage tuple is the same value.
- recordRetainOf follows the literal's read through its views.
- fieldTakersOf / fieldOnlyRead: a field that holds no block takes nothing
  (print(h.dist) made the record's number field a taker).
- A non-escaping closure capturing frame or parameter storage that holds no
  block (this of a @value constructor with number fields) needs no owner.

Tests: own_value_record, own_value_loop, own_value_temporaries (own, rc, gc,
none, AOT+JIT; no counting under own), value_iface_cycle under own; negatives
own_err_value_record_{place_dropped,stored,let_reassigned,mixed_local,
field_written,param_field_kept}; own_err_record_literal_let_field now rejected at the push.
value_interface stays off under own (nested owning literal; record converted
to an ordinary interface); value_refs is not registered under own (its copies
outlive the originals' Nodes: correct rejections). The marked ray tracer
compiles under own (13 errors before) and prints 38837369. Corpus 542 -> 543.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- own negatives for the exits of a record that borrows a `let`:
  own_err_value_record_{returned,captured,field_stored,global}, and
  own_err_value_refs_copy (a copy out of an array read after the element is
  overwritten; own rejects the read even without the overwrite, an
  over-rejection that predates spec 36).
- own_value_record prints a record's number field straight; own_value_temporaries
  prints one of a value that owns its vector (the owner check's fieldTakersOf /
  fieldOnlyRead number-field fix; without it, "used here after its value was
  moved").
- value_interface runs under own; its two own gaps (a nested owning literal,
  #679; a record converted to an ordinary interface) move to
  value_interface_own_gaps, which runs under gc, rc and none and stays off
  under own.
- own spec 36: the new tests, and a constant-index call on a const array
  outside a loop (records boxed or not) in "Not here".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A library's @value class and interfaces reach an importer through __decls,
which prints them in source order. An interface naming one declared after
it (`Hit { ray: Ray }` before `Ray`) failed to import with "can't find type
by name: Ray", @value or not: the importer read the declarations in one
pass. It now tries each that failed again once the others are in, as a
module's own statements are, and drops what the failed tries reported.

The pair builds V and R, Hit and Ray (nested, Hit first) on both sides,
gives them back, reads Hit | null after narrowing and through ?., under
gc, rc and own, compiled and JIT. An object literal for the imported V is
the nominal conversion error, and own's export of a @value that only
borrows its argument names why it cannot be told to another module.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A plain pair, no @value: the library's exported interface A holds a B
declared after it, and the importer reads a.b.k and a.n of the A a
library function returns, under gc, rc and own, compiled and JIT. A
library whose exported interface holds a type it does not export still
fails to import, with "can't find type by name".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In a @value class's constructor `this` is the slot `new` is filling. Read
whole (`const self = this`, `f(this)`, `arr.push(this)`, `[this]`,
`{ v: this }`, `() => this`) it was a copy of the fields stored so far, so
a later `this.a = 1` did not reach it (`self.a` read 0 where TypeScript
reads 1). Such a use is now an error; `this.f`, `this.f = x`, `this.m()`
and `this["f"]` stay allowed, in the constructor and in arrow functions
inside it.

value_class.ts's Q passed `this` to a function; it now reads the fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A @value type is the tuple of its fields held in place, so one that holds
itself (`next: L | null`, or `A.b: B | null` with `B.a: A`) can never be
laid out: each discovery pass found the other type not laid out yet and
the end result was "can't find type by name: L". While a @value type's
field is typed, a @value type it needs that is not laid out yet is now
recorded as one it waits for; a type that waits, through the types it
waits for, for itself is reported:

  @value type 'L' contains itself through 'next'; a value cannot hold itself
  @value type 'A' contains itself through 'b.a'; ...

and "can't find type by name" for it is left out. `next: L[]` did not
compile before either and now gets the same error. A reference through
an ordinary class (`box: Box`, `Box.l: L | null`) still works.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TypeScript skips the whole rest of a chain once a `?.` in it meets null or
undefined. Each link read only the link before it, so in `g?.ray.dir.x`
`.dir` read `g?.ray`'s undefined: a missing @value type threw there, a
missing type literal read 0.

A chain link that is not a `?.` itself (`.c`, `[i]`, `.m()`, `!`) and has
one below it is now made whole: the `?.`'s object is read once and tested
as the `?.` tests it, and the chain - generated as before, on the value
read - runs only when it is there, as an optional; undefined otherwise. A
chain ending in a void call moves into an `if` with no result.

Code without @value changes too: such a chain on a missing object is
undefined instead of reading on (a type literal gave 0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`T | null` of a @value type is an optional holding a tagged union:
isMissingValueUnion makes isUnionTypeNeedsTag answer yes, so it is a packed
`<{ ptr tag, payload }>` (the tag points at a type descriptor's name,
`object` or `null`) inside `{ ..., i1 }`. The spec now says what is emitted,
what undefined, null and a value look like, and how the comparisons test
them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`{ ...this }` in a @value constructor failed in the discovery run with
"Spread in an object literal is not supported for type: V" before the check,
which ran only in the real run, could say why. The check is AST-only, so it
now runs in both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An instance field's initializer runs in the constructor (in the one made
for it when none is written), where `this` is the slot being filled:
`readonly f = mk(this)` captured a copy taken before `this.a = 7` (f()
gave 0, TypeScript 7), and `readonly b = show(this)` read a = 0. The
constructor's check now walks the class's instance field initializers
too; `this.a` in one stays allowed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`box: Box<L>` in a @value type L: while L's fields were typed, L was not
laid out, so instantiating Box<L> failed and the unspecialized generic
`Box` became the field's type for good. Box<L> was later made from that
L, a literal of L with a Box<L> converted between two class types, and
the compiler crashed (0xC0000005, already at --emit=mlir).

A generic whose instantiation waited for a @value type that is not laid
out yet now fails the field instead, so it is typed again in the next pass
(`box: Box<K>` with K declared later works). For L's own type that wait is
a cycle, reported as

  @value type 'L' reaches itself through 'box' in the type arguments of
  'Box<L>'; a @value type cannot hold a generic type made from it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ffd2996 failed a @value field's generic only when its instantiation had
waited for a @value type. With the generic declared before the @value
types, the type argument (`Box<B>`, B declared after A) was not even
registered on the first pass: no wait, so the unspecialized `Box` still
became the field's type. `A.p: Box<B>` with `B.a: A` crashed again at a
literal of A, `box: Box<K>` read `.l` as "Can't resolve property", and
`Box<Nope>` compiled.

While a @value type's field is typed, a failed instantiation now always
fails the field, which is typed again in the next pass; the generic's own
declaration, specialized meanwhile, is not the field
(suspendValueLayoutFrames). The cycle is reported, `Box<K>` works in either
declaration order, and `Box<Nope>` is "can't find type by name: Nope".
Fields of other types keep the fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ASDAlexander77
ASDAlexander77 merged commit c2c8077 into main Oct 24, 2026
2 checks passed
@ASDAlexander77
ASDAlexander77 deleted the value-types branch October 24, 2026 18:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant