diff --git a/tslang/benchmarks/raytrace/README.md b/tslang/benchmarks/raytrace/README.md index c07fd02bc..3ab1c781c 100644 --- a/tslang/benchmarks/raytrace/README.md +++ b/tslang/benchmarks/raytrace/README.md @@ -1,9 +1,9 @@ # Ray tracer: memory models vs Rust and C++ `rtbench.ts` is `test/tester/tests/raytrace.ts` at 512x512 with a pixel checksum (see its header). -`rtbench_own.ts` is the same program for `-mm=own`, with two source edits: the surfaces, which every -thing shares, are `Shared` handles, and `Plane.normal` returns a fresh vector instead of -its own field. +`rtbench_own.ts` is the same program for `-mm=own`, with one source edit: the surfaces, which every +thing shares, are `Shared` handles. In both files `Vector` and `Color` are `@value` classes +and `Ray` and `Intersection` `@value` interfaces (see "Results 2026-10-24: `@value`"). `rust/` and `cpp/` each hold two ports of the same algorithm: - `rust/src/bin/idiomatic.rs`, `cpp/idiomatic.cpp`: `Vector`/`Color` are plain values, things are @@ -26,6 +26,108 @@ pwsh tslang/benchmarks/raytrace/bench.ps1 - Rust: `opt-level=3`, `lto="fat"`, `codegen-units=1`, `panic="abort"` - C++: `clang++ -std=c++20 -O3`, and `cl /std:c++20 /O2 /EHsc /MT` +## Results 2026-10-24: `@value` + +Release, Windows 11 x64, the same machine and toolchains as below; branch `value-types` (98ec37ff, +stacked on the "allocator as malloc" change). Two runs of `bench.ps1`, median of 7 runs after a +warm-up each; the table gives the mean of the two medians. For the tslang builds in the table the +two medians were within 1.5 ms of each other; for the C++ `shared_ptr` rows within 6 ms, and for +the `--no-stack-promotion` builds within 7 ms (gc: 256.2 and 249.4). Every build prints the same +checksum. + +`rtbench.ts` and `rtbench_own.ts` mark `Vector` and `Color` as `@value` classes (constructor +parameters `public readonly`) and `Ray` and `Intersection` as `@value` interfaces (fields +`readonly`). Their values are structs passed and returned by value, not heap objects. A `@value` +type has no null of its own, so `intersect` returns `Intersection | null` and `closestInter` is +`Intersection | undefined`. No object literal changed. `rtbench_own.ts`'s `Plane.normal` returns +`this.norm` again, since returning a value copies it. + +| Build | allocator as malloc | `@value` | vs Rust idiomatic | +|---|---|---|---| +| tslang gc | 1199 ms | 255 ms | 4.7x | +| tslang rc | 630 ms | 172 ms | 3.1x | +| tslang none | 434 ms | 165 ms | 3.0x | +| tslang own | 444 ms | 148 ms | 2.7x | +| Rust idiomatic | 54 ms | 55 ms | 1x | +| Rust Rc-boxed | 490 ms | 492 ms | 9.0x | +| C++ idiomatic (clang) | 50 ms | 50 ms | 0.9x | +| C++ idiomatic (MSVC) | 68 ms | 68 ms | 1.2x | +| C++ shared_ptr (clang) | 829 ms | 903 ms | 16.5x | +| C++ shared_ptr (MSVC) | 896 ms | 977 ms | 18x | + +The "allocator as malloc" column is the earlier run below; its Rust and C++ values are that run's +(its "main" column, since those ports do not use tslang's allocator). The Rust and C++ ports did +not change; their `@value` column is this run, for comparison. "vs Rust idiomatic" divides the +`@value` column by this run's Rust idiomatic (54.6 ms). The goal was 1.1x of Rust idiomatic, about 60 ms. own is 2.7x, about 90 ms short of it. + +`--no-stack-promotion` changes gc, rc and own by 2% or less; none takes 180 ms without it (9% +slower). This run does not explain the difference for none. + +Stack promotion: `--emit=mlir-affine --stack-promotion-report` under rc keeps 17 allocations on +the heap and none of them is a `Vector`, `Color`, `Ray` or `Intersection`. They are the four +closures that capture (`addLight`, `getPoint`, `recenterX`, `recenterY`: "counted-capture") and +the scene built once in `defaultScene` and `exec` (the things, the lights, the camera, the scene +literal, the `RayTracer`). In the optimized LLVM IR, `render` allocates nothing per pixel under +none (LLVM inlines `getPoint` and its two closures and deletes their cells; rc allocates two cells +once per `render`). The one allocation left on the hot path is `addLight`'s: `getNaturalColor` +puts each of the six variables the closure captures in a heap cell (rc adds a seventh block), on +every call. + +Where the time goes. A 512x512 render calls `intersections` 2.24 million times (9 million +`Thing.intersect` calls through the interface), `shade` 397 thousand times and `testRay` 1.59 +million times. Each row below edits a scratch copy of the benchmark (`rtbench.ts` for none and +rc, `rtbench_own.ts` for own) to remove one cost and keeps the checksum; none of these edits is in +the benchmark. The edits: + +- A: `getNaturalColor` does not build `addLight` and call `scene.lights.reduce(addLight, + Color.defaultColor)`; it starts from `let col = Color.defaultColor`, runs `addLight`'s body in a + `for (const light of scene.lights)` loop (a light in shadow is skipped, otherwise + `col = Color.plus(col, ...)`), and returns `col`. +- B: `intersect` returns `Intersection` in `Thing`, `Sphere` and `Plane`; a miss returns + `{ thing: this, ray: ray, dist: 0 }` instead of `null`. `closestInter` is an `Intersection` that + starts as `{ thing: scene.things[0], ray: ray, dist: 0 }`, and the tests `inter != null`, + `isect != null` (`testRay`) and `isect === undefined` (`traceRay`) test `dist` against 0. +- F: `@final` before `class RayTracer`, so calls to its methods are direct. + +Median of 7 runs, ms: + +| Variant | none | own | rc | +|---|---|---|---| +| the benchmark | 165 | 148 | 171 | +| A: `addLight` written as a loop over the lights, no closure | 89 | 89 | 108 | +| B: `intersect` returns `dist: 0` for a miss, no `\| null` | 148 | 131 | 177 | +| F: `@final class RayTracer` | 147 | 129 | 161 | +| A and B | 73 | 72 | 117 | +| A, B and F | 58 | 58 | 107 | + +- A: the `addLight` closure costs 59-76 ms (A alone: 76 ms under none, 59 under own; the same + after B). The IR shows where: 2.4 million cell allocations per render (six per `shade`), which + none never frees and own and rc free again. Closures are a non-goal of `@value`. +- B: `Intersection | null` costs 16-17 ms under none and own (B alone, and B after A). The IR shows + two likely parts, not measured separately: the result is an optional holding a union, 88 bytes, + returned from every `Thing.intersect` call; and every test for null compares the union's type + tag with the string `"null"` (`strcmp`), once per `intersect` result, per `traceRay` and per + `testRay`. Under rc B is 5 ms slower, probably because the miss now carries a `thing` that is + retained and released (not measured separately). +- F: the virtual `RayTracer` methods cost 18-19 ms alone and 14-15 ms after A and B (none and + own). `traceRay` and `testRay` call `intersections` and `shade` through the vtable, so LLVM + inlines none of them and the 88-byte result goes through memory. `@final` makes the calls + direct. The `Thing` and `Surface` calls stay indirect, as in Rust. +- With all three removed, none and own run in 58 ms, 1.06x Rust: these three account for the + whole gap. rc stays at 107 ms. The IR shows that copying an `Intersection` retains and releases + its `thing` through the type's retain and release functions, which are indirect calls; that + this is what keeps rc at 107 ms is a reading of the IR, not measured. +- Checks for a missing value: of the three narrowed reads looked at in the optimized IR, one has + no check left and two keep one. In `RayTracer.intersections` under none, `inter.dist` after + `inter != null` reads the field with no check. In `RayTracer.traceRay` (none and rc), + `isect === undefined` rules out only `undefined` (null and undefined are one encoding), so + passing `isect` to `shade`, which takes a plain `Intersection`, keeps a test for null and its + throw ("a @value value is null or undefined"). Under rc, the `inter.dist` read in + `intersections` keeps one too, because the retain and release calls of `closestInter = inter` + come between the test and the read. Only `traceRay`'s check was measured: writing + `isect == null` there, which folds it, gives the same times. The rc `intersections` re-check was + not isolated. + ## Results 2026-10-24 Release, Windows 11 x64, the same machine and toolchains as below; median of 7 runs after a diff --git a/tslang/benchmarks/raytrace/rtbench.ts b/tslang/benchmarks/raytrace/rtbench.ts index 038398113..5876c87e6 100644 --- a/tslang/benchmarks/raytrace/rtbench.ts +++ b/tslang/benchmarks/raytrace/rtbench.ts @@ -3,6 +3,9 @@ // every pixel's drawing color into a checksum (38837369), so the render cannot be optimized away // and every build, including the Rust ports in rust/, can be checked against the others. // print() shows the sum with 6 significant digits, so the low digits are printed separately. +// Vector and Color are @value classes and Ray and Intersection @value interfaces: their values are +// structs copied on the stack, not heap objects. A missing intersection is spelled +// `Intersection | null` (or `| undefined`), since a @value type has no null of its own. declare function sqrt(v: number): number; declare function floor(v: number): number; declare function pow(v: number, s: number): number; @@ -32,10 +35,11 @@ class Math { } } +@value class Vector { - constructor(public x: number, - public y: number, - public z: number) { + constructor(public readonly x: number, + public readonly y: number, + public readonly z: number) { } static times(k: number, v: Vector) { return new Vector(k * v.x, k * v.y, k * v.z); } static minus(v1: Vector, v2: Vector) { return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } @@ -54,10 +58,11 @@ class Vector { } } +@value class Color { - constructor(public r: number, - public g: number, - public b: number) { + constructor(public readonly r: number, + public readonly g: number, + public readonly b: number) { } static scale(k: number, v: Color) { return new Color(k * v.r, k * v.g, k * v.b); } static plus(v1: Color, v2: Color) { return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b); } @@ -90,15 +95,17 @@ class Camera { } } +@value interface Ray { - start: Vector; - dir: Vector; + readonly start: Vector; + readonly dir: Vector; } +@value interface Intersection { - thing: Thing; - ray: Ray; - dist: number; + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; } interface Surface { @@ -109,7 +116,7 @@ interface Surface { } interface Thing { - intersect(ray: Ray): Intersection; + intersect(ray: Ray): Intersection | null; normal(pos: Vector): Vector; surface: Surface; } @@ -132,7 +139,7 @@ class Sphere implements Thing { this.radius2 = radius * radius; } normal(pos: Vector): Vector { return Vector.norm(Vector.minus(pos, this.center)); } - intersect(ray: Ray): Intersection { + intersect(ray: Ray): Intersection | null { let eo = Vector.minus(this.center, ray.start); let v = Vector.dot(eo, ray.dir); let dist = 0.0; @@ -154,7 +161,7 @@ class Plane implements Thing { constructor(public norm: Vector, public offset: number, public surface: Surface) { } public normal(pos: Vector): Vector { return this.norm; } - public intersect(ray: Ray): Intersection { + public intersect(ray: Ray): Intersection | null { let denom = Vector.dot(this.norm, ray.dir); if (denom > 0) { return null; @@ -198,7 +205,7 @@ class RayTracer { private intersections(ray: Ray, scene: Scene) { let closest = +Infinity; - let closestInter: Intersection = undefined; + let closestInter: Intersection | undefined = undefined; for (let i in scene.things) { let inter = scene.things[i].intersect(ray); if (inter != null && inter.dist < closest) { diff --git a/tslang/benchmarks/raytrace/rtbench_own.ts b/tslang/benchmarks/raytrace/rtbench_own.ts index e22da49d7..7bae0f043 100644 --- a/tslang/benchmarks/raytrace/rtbench_own.ts +++ b/tslang/benchmarks/raytrace/rtbench_own.ts @@ -1,8 +1,12 @@ // @strict-null false -// rtbench.ts for -mm=own, with its two source edits: the surfaces, which every thing shares, are -// `Shared` handles, and `Plane.normal` returns a fresh vector, as `Sphere.normal` does, -// instead of its own field. Otherwise the same program and the same checksum (38837369). +// rtbench.ts for -mm=own, with one source edit: the surfaces, which every thing shares, are +// `Shared` handles. Otherwise the same program and the same checksum (38837369). +// (`Plane.normal` used to return a fresh vector here; with Vector a @value class, returning its +// own field returns a copy, as in rtbench.ts.) // print() shows the sum with 6 significant digits, so the low digits are printed separately. +// Vector and Color are @value classes and Ray and Intersection @value interfaces: their values are +// structs copied on the stack, not heap objects. A missing intersection is spelled +// `Intersection | null` (or `| undefined`), since a @value type has no null of its own. declare function sqrt(v: number): number; declare function floor(v: number): number; declare function pow(v: number, s: number): number; @@ -32,10 +36,11 @@ class Math { } } +@value class Vector { - constructor(public x: number, - public y: number, - public z: number) { + constructor(public readonly x: number, + public readonly y: number, + public readonly z: number) { } static times(k: number, v: Vector) { return new Vector(k * v.x, k * v.y, k * v.z); } static minus(v1: Vector, v2: Vector) { return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); } @@ -54,10 +59,11 @@ class Vector { } } +@value class Color { - constructor(public r: number, - public g: number, - public b: number) { + constructor(public readonly r: number, + public readonly g: number, + public readonly b: number) { } static scale(k: number, v: Color) { return new Color(k * v.r, k * v.g, k * v.b); } static plus(v1: Color, v2: Color) { return new Color(v1.r + v2.r, v1.g + v2.g, v1.b + v2.b); } @@ -90,15 +96,17 @@ class Camera { } } +@value interface Ray { - start: Vector; - dir: Vector; + readonly start: Vector; + readonly dir: Vector; } +@value interface Intersection { - thing: Thing; - ray: Ray; - dist: number; + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; } interface Surface { @@ -109,7 +117,7 @@ interface Surface { } interface Thing { - intersect(ray: Ray): Intersection; + intersect(ray: Ray): Intersection | null; normal(pos: Vector): Vector; surface: Shared; } @@ -132,7 +140,7 @@ class Sphere implements Thing { this.radius2 = radius * radius; } normal(pos: Vector): Vector { return Vector.norm(Vector.minus(pos, this.center)); } - intersect(ray: Ray): Intersection { + intersect(ray: Ray): Intersection | null { let eo = Vector.minus(this.center, ray.start); let v = Vector.dot(eo, ray.dir); let dist = 0.0; @@ -153,8 +161,8 @@ class Sphere implements Thing { class Plane implements Thing { constructor(public norm: Vector, public offset: number, public surface: Shared) { } - public normal(pos: Vector): Vector { return new Vector(this.norm.x, this.norm.y, this.norm.z); } - public intersect(ray: Ray): Intersection { + public normal(pos: Vector): Vector { return this.norm; } + public intersect(ray: Ray): Intersection | null { let denom = Vector.dot(this.norm, ray.dir); if (denom > 0) { return null; @@ -198,7 +206,7 @@ class RayTracer { private intersections(ray: Ray, scene: Scene) { let closest = +Infinity; - let closestInter: Intersection = undefined; + let closestInter: Intersection | undefined = undefined; for (let i in scene.things) { let inter = scene.things[i].intersect(ray); if (inter != null && inter.dist < closest) { diff --git a/tslang/docs/superpowers/plans/2026-10-24-value-types.md b/tslang/docs/superpowers/plans/2026-10-24-value-types.md new file mode 100644 index 000000000..8c55cd827 --- /dev/null +++ b/tslang/docs/superpowers/plans/2026-10-24-value-types.md @@ -0,0 +1,364 @@ +# `@value` Classes and Interfaces Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** A `@value` class or interface is a value of its readonly fields, not a heap object, so the ray tracer's `Vector`/`Color`/`Ray`/`Intersection` temporaries stop allocating, under every memory model, with the benchmark's object literals unchanged. + +**Architecture:** One new dialect type, `!ts.value<@Name, !ts.tuple<...>>` (`mlir_ts::ValueType`), names a `@value` declaration and carries its fields as a tuple. It lowers to that tuple's LLVM struct. MLIRGen reaches the fields through a `ts.Cast` to the storage tuple, which lowers to nothing, so the existing tuple ops and lowerings do the work. Every type walker sees a `ValueType` as its storage tuple through one helper. The rules that make a value invisible as a copy (readonly, no `===`, no null in a plain slot, no identity conversions) are MLIRGen errors keyed on `ValueType`. + +**Tech Stack:** C++17, MLIR (ts dialect, TableGen types), CMake/CTest, gtest (`unittests/MLIRGen`), the tslang test-runner, PowerShell (`bench.ps1`). + +**Spec:** `tslang/docs/superpowers/specs/2026-10-24-value-types-design.md` + +## Global Constraints + +- Branch `value-types`, stacked on `process-heap-malloc-attrs` (PR #683). The design commit is a98a9b7e. When #683 merges, merge `origin/main` into `value-types`. Never rebase, never force-push. +- The sources use CRLF. Edit them with the Edit tool or a Python script that writes `newline=''`. Never use `sed -i`, which rewrites the file to LF. +- Never bypass commit signing. On `gpg: signing failed: Timeout`: retry, run `gpg-connect-agent "scd killscd" /bye` and retry, then leave the change staged and hand the exact command to the user. +- Build: `cmake --build I:/TypeScriptCompiler/__build/tslang/windows-msbuild-2026-release --config Release --target tslang --parallel 8`. Reconfigure (`cmake .` in that folder) after adding tests. Tests: `ctest -C Release -j 16 --timeout 300` there. Without `-C Release` nothing runs. Full suite before this work: 5525 passed. +- Code without `@value` compiles exactly as before. That includes plain tuples and type literals, so the `return null` tuple bug in the spec's "Found on the way" stays as it is. +- `@value` is never a hint. A marked type is always a value, and anything that can't be compiled as one is an error naming the reason. +- Error texts, pinned by the tests (`X`, `V`, `R`, `f`, `T` stand for the names in each case): + - `class 'V' cannot be both @value and @cpp` (also `abstract`, `@final`) + - `@value class 'V' cannot extend 'B'` + - `class 'X' cannot extend 'V': it is @value` + - `@value class 'V' cannot implement an interface` + - `@value class 'V' cannot have type parameters` + - `field 'f' of @value class 'V' must be readonly` + - `@value class 'V' cannot have a setter` + - `field 'f' of @value interface 'R' must be readonly` + - `field 'f' of @value interface 'R' cannot be optional` + - `@value interface 'R' can only have fields` + - `@value interface 'R' cannot extend 'I': it is not @value` + - `instanceof can't be used with the @value class 'V': its values have no type information` + - `a @value type has no identity; compare its fields` + - `a @value type has no null; write 'T | null'` + - `the @value class 'V' cannot be converted to 'T'` +- Benchmark checksum: 38837369, under gc, rc, none and own. + +## Review Focus + +- A closure that captures a `@value` local reads the variable, not a snapshot. `let v = new V(1); const f = () => v.x; v = new V(2);` then `f() == 2`, as in TypeScript, because the capture is of the binding. Pinned in Task 5's `value_refs.ts`. +- A `@value` value passed through a generic (`[a, b].reduce((acc, x) => V.plus(acc, x), V.zero)`, the benchmark's `lights.reduce` shape) is copied correctly. Pinned in Task 5. +- A literal whose fields are written in a different order from the interface, nested two levels (`{ ray: { dir: d, start: s }, dist: 1, thing: t }`), lands each field in the right slot. Pinned in Task 2. +- A `@value` value stored in a field of an ordinary class (`Camera.pos`) and then read after the class's other fields change keeps its own fields. Pinned in Task 3. +- An optional parameter of a `@value` type (`f(v?: V)`), called with no argument and with one, and `x?.dist` on `T | null`. Pinned in Task 4. + +--- + +### Task 1: `@value` is parsed, stored, enforced and printed + +**Files:** +- Modify: `tslang/include/TypeScript/Defines.h` (beside `#define FINAL_DECORATOR "final"`, about line 327) +- Modify: `tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h` (`InterfaceInfo` about 283-315, `ClassInfo` about 753-820, and their initializer lists) +- Modify: `tslang/lib/TypeScript/MLIRGenClasses.cpp` (decorator loop about 382-420; the combination checks beside the `@final` ones about line 101; the `ExtendsKeyword`/`ImplementsKeyword` heritage branches) +- Modify: `tslang/lib/TypeScript/MLIRGenInterfaces.cpp` (`mlirGenInterfaceInfo` about 1118-1160, and the interface member and heritage loops) +- Modify: `tslang/lib/TypeScript/DeclarationPrinter.cpp` (class printer about 484-491, and the interface printer) +- Test: `tslang/unittests/MLIRGen/DeclarationPrinter.cpp` +- Test: `tslang/test/tester/value/*.ts` (one file per error case below) +- Modify: `tslang/test/tester/CMakeLists.txt` (a `value_error_cases` block after `final_error_cases`, about line 3040, in the same shape) + +**Interfaces:** +- Produces: + - `#define VALUE_DECORATOR "value"` + - `bool ClassInfo::isValue` and `bool InterfaceInfo::isValue`, default `false`, set for definitions and `declare` declarations alike + - `DeclarationPrinter` writes `@value` on its own line before a `@value` class or interface + +- [ ] **Step 1: Write the failing printer unit tests.** Next to `final_class_prints_final_decorator`, add: + - `value_class_prints_value_decorator` (`ci->isValue = true`; `HasSubstr("@value")`) + - `value_interface_prints_value_decorator` (the same for an `InterfaceInfo`) + - `plain_interface_has_no_value_decorator` (`Not(HasSubstr("@value"))`) +- [ ] **Step 2: Write the error-case files** in `test/tester/value/`. Each has one offence and nothing else that fails: + - `value_cpp.ts` (`@value @cpp declare class V { m(): int; }`) + - `value_abstract.ts` + - `value_final.ts` + - `value_extends.ts` (`class B {}` and `@value class V extends B {}`) + - `extends_value.ts` (`@value class V { constructor(public readonly x: number) {} }` and `class X extends V {}`) + - `value_implements.ts` + - `value_generic.ts` + - `value_iface_extends.ts` (`interface I { readonly a: number; }` and `@value interface R extends I { readonly b: number; }`) +- [ ] **Step 3: Register them** as `value_error_cases` `"name|message"` entries with the messages from Global Constraints. Each runs `tslang --emit=obj --no-default-lib -mm=none` and has `PASS_REGULAR_EXPRESSION` set to the message and `FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed"`. Test names are `test-compile-value-`. +- [ ] **Step 4: Confirm they fail.** Reconfigure and build `tslang` and `MLIRTypeScriptUnitTests`, then run `ctest -C Release -R "value-|unittest-MLIRGen"`. Expected: the new tests fail. +- [ ] **Step 5: Implement.** + - Read the decorator into `isValue` in both loops. Interfaces get their own `iterateDecorators` call. + - Emit the combination and heritage errors at the declaration (or `extends`/`implements`) location and fail the declaration, as `@final`'s do. + - `extends_value` is checked where `@final`'s `extends` check is. + - Print the decorator. +- [ ] **Step 6: Run the tests.** `ctest -C Release -R "value-|final-|unittest-MLIRGen"` should all pass. Then the full suite: 0 failed. +- [ ] **Step 7: Commit.** `@value: parse, store, reject invalid combinations, print`. + +### Task 2: `ValueType`, and `@value` interfaces + +**Files:** +- Modify: `tslang/include/TypeScript/TypeScriptTypes.td` (a `TypeScript_Value` def after `TypeScript_Class`, about line 682) +- Modify: `tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h`: + - the new helper + - `isValueType` (about 206) + - `ownsHeapMemory` (body about 3952) + - `getOwnershipFieldTypes` (about 2271) + - type equality and assignability helpers that switch on `TupleType` +- Modify: `tslang/lib/TypeScript/LowerToLLVM.cpp` (the `TupleType` conversion at about 8173; `CastOp` lowering for `ValueType` to and from its storage tuple) +- Modify: `tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h` (`buildRetainBody` about 1309, `buildBody` about 1109) +- Modify: `tslang/lib/TypeScript/StackEscapeFacts.h` (where it classifies tuple values) +- Modify: `tslang/lib/TypeScript/MLIRGenVariables.cpp` (`resolveTypeByNameInNamespace`, interface branch at about 1316) +- Modify: `tslang/lib/TypeScript/MLIRGenExpressions.cpp` (`mlirGen(ObjectLiteralExpression)` about 1891-2124) +- Modify: `tslang/lib/TypeScript/MLIRGenAccessCall.cpp` (the member-access `TypeSwitch` at about 203-384: a `Case`) +- Modify: `tslang/lib/TypeScript/MLIRGenCast.cpp` (`cast` about 691, `castToInterfaceSpecialCases` about 1010) +- Modify: `tslang/lib/TypeScript/MLIRGenImpl.h` (the binary-operator path for `===`/`!==`/`==`/`!=`) +- Test: `tslang/test/tester/value/value_interface.ts` +- Test: `tslang/test/tester/value/value_no_alloc.ts`, `tslang/test/tester/value-no-alloc.cmake` +- Test: error files `value_iface_mutable.ts`, `value_iface_optional.ts`, `value_iface_method.ts`, `value_iface_identity.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` + +**Interfaces:** +- Consumes: `InterfaceInfo::isValue` (Task 1). +- Produces: + - `mlir_ts::ValueType`, mnemonic `value`, parameters `(FlatSymbolRefAttr name, Type storageType)`, builder `ValueType::get(name, storageType)`. `storageType` is always a `mlir_ts::TupleType`. + - `mlir::Type MLIRTypeHelper::stripValueType(mlir::Type)` returns the storage tuple of a `ValueType` and anything else unchanged. Every type walker that must treat a value as its fields calls it. + - `mlir_ts::ValueType MLIRGenImpl::getValueTypeOfInterface(InterfaceInfo::TypePtr)` gives the fields in declaration order. + - `mlir::Value MLIRGenImpl::valueStorage(mlir::Location, mlir::Value)` emits the `ts.Cast` from a `ValueType` value to its tuple. + - In the IR, `ts.Cast` between a `ValueType` and its exact storage tuple, in either direction, lowers to nothing. + +- [ ] **Step 1: Write `value_interface.ts`.** It runs, asserts, and ends with `print("done.")`, like the `final/` tests: + - `class Vec { constructor(public x: number, public y: number) {} }`, `interface Thing { id(): int; }`, `class T1 implements Thing { id(): int { return 7; } }` + - `@value interface Ray { readonly start: Vec; readonly dir: Vec; }` + - `@value interface Hit { readonly thing: Thing; readonly ray: Ray; readonly dist: number; }` + - `function mk(s: Vec, d: Vec): Ray { return { start: s, dir: d }; }` + - `function hit(t: Thing, r: Ray, d: number): Hit { return { dist: d, ray: r, thing: t }; }` (fields out of order) + - `function len(r: Ray) { return r.start.x + r.dir.y; }` + - `interface HasStart { start: Vec; }` + + Asserts: + - `len({ start: new Vec(1, 2), dir: new Vec(3, 4) }) == 5` + - `const h = hit(new T1(), mk(new Vec(1, 0), new Vec(0, 2)), 9); h.dist == 9 && h.thing.id() == 7 && h.ray.dir.y == 2` + - the nested literal `{ ray: { dir: new Vec(0, 3), start: new Vec(5, 0) }, dist: 1, thing: new T1() }` typed `Hit`: `.ray.start.x == 5 && .ray.dir.y == 3` + - `const a: any = mk(new Vec(8, 0), new Vec(0, 0)); a.start.x == 8` + - `const s: HasStart = mk(new Vec(6, 0), new Vec(0, 0)); s.start.x == 6` + - `const tl: { start: Vec; dir: Vec } = mk(...)` and back to `Ray`: fields equal + - `typeof mk(new Vec(0, 0), new Vec(0, 0)) == "object"` + - a loop of 10000 `len(mk(...))` summing to an exact total +- [ ] **Step 2: Write the no-allocation IR check.** + - `value_no_alloc.ts` declares `@value interface Vec { readonly x: number; readonly y: number; }` and a `@value interface Ray` of two `Vec`s. It exports `function len2(a: number, b: number): number`, which builds `{ start: { x: a, y: 0 }, dir: { x: 0, y: b } }`, passes it to a non-exported `len` and returns the result. + - `value-no-alloc.cmake` is modelled on `fresh-objects-folded.cmake`. For each of `gc rc none own`, it compiles with `--emit=llvm --opt --opt_level=3 --no-default-lib` and fails if the body of `@len2(` matches `[mc]alloc|GC_malloc|__tslang_heap`. The pattern deliberately doesn't match `alloca`: a stack slot is fine. `malloc`/`calloc` still catch Linux, where ProcessHeapPass doesn't rename them. +- [ ] **Step 3: Write the error files.** + - `value_iface_mutable.ts`: a field without `readonly`. + - `value_iface_optional.ts`: `readonly f?: number`. + - `value_iface_method.ts`: `m(): int;`. + - `value_iface_identity.ts`: `r1 === r2` on two `Ray` values. +- [ ] **Step 4: Register.** + - `value_interface` runs AOT and JIT in `foreach(value_mm gc rc none own)`, as `final_dispatch` does: `test-compile-value-interface-${mm}`, `test-jit-value-interface-${mm}`. + - `test-value-no-alloc` uses `add_test(... -P value-no-alloc.cmake)`, as `test-fresh-objects-folded` does. + - The four error files are added to `value_error_cases`. +- [ ] **Step 5: Confirm they fail.** `ctest -C Release -R "value-"`. Expected: the new tests fail (no `@value` interface semantics yet). +- [ ] **Step 6: Implement `ValueType`.** Add the TableGen def and the `stripValueType` helper, and lower `ValueType` to the converted storage tuple. Then sort every `mlir_ts::TupleType` hit in `MLIRTypeHelper.h`, `LowerToLLVM/*.h`, `StackEscapeFacts.h`, the `Ownership*Pass.cpp` files and `MLIRGen*.cpp` into two lists: + - **Walkers that descend into fields: apply `stripValueType`.** These are `isValueType`, `ownsHeapMemory`, `getOwnershipFieldTypes`, `buildRetainBody`/`buildBody`, `StackEscapeFacts.h`, type equality and assignability, and the LLVM type converter. Any other hit that reads the fields' types or sizes belongs here too. + - **Sites that key on "this is a tuple" to box or re-represent it: do NOT apply.** A `ValueType` must not reach them. They are: + - the tuple branches of `castToInterfaceSpecialCases` (`MLIRGenCast.cpp` about 1068-1076, into `castTupleToInterface`); + - `NewClassInstance`'s `isValueType` → `ValueRefType` heap box (`MLIRGenAccessCall.cpp` about 2388-2391); + - the object literal's `BoxAsObject` path; + - `isNullAbsorbingType`; + - the tuple-is-a-value-type branch of `getUnionTypeMergeTypes` (about 3456-3460) that makes `UnionType{tuple, null}`. + + A `ValueType` reaches the boxing paths only through an explicit `valueStorage` cast at a conversion the spec allows (Step 7). +- [ ] **Step 7: Implement `@value` interfaces in MLIRGen.** + - The interface name resolves to `getValueTypeOfInterface`. + - Declaration rules give the three member errors. + - An object literal whose contextual type is a `ValueType` is built as its storage tuple (the existing receiver-order path) and cast to the `ValueType`. There is no `castTupleToInterface`. + - Member access on a `ValueType` goes to `cl.Tuple` on `valueStorage(...)`. + - `cast` converts: + - between a `ValueType` interface and a tuple, type literal or another `ValueType` interface with the same field names, by field copy in the target's order; + - a `ValueType` interface to `any`, `Object` or a non-`@value` interface by casting it to its storage tuple and taking the existing tuple paths. + - `===`/`!==`/`==`/`!=` with a `ValueType` on both sides is the identity error. With `null`/`undefined` on one side it is left to Task 4. +- [ ] **Step 8: Run.** `ctest -C Release -R "value-"` should all pass. Then the full suite: 0 failed (no change without `@value`). +- [ ] **Step 9: Commit.** `@value interfaces: a literal of a @value interface type is a value`. + +### Task 3: `@value` classes + +**Files:** +- Modify: `tslang/lib/TypeScript/MLIRGenClasses.cpp` (class storage creation: no vtable field and no `.instanceOf`/`..new`/vtable global for a `@value` class; field and accessor rules) +- Modify: `tslang/lib/TypeScript/MLIRGenVariables.cpp` (`resolveTypeByNameInNamespace`, class branch at about 1297) +- Modify: `tslang/lib/TypeScript/MLIRGenAccessCall.cpp`: + - `NewClassInstance` about 2377, `NewClassInstanceLogicAsOp` about 2503 + - the `ValueType` case added in Task 2: method and getter lookup through the class +- Modify: `tslang/lib/TypeScript/MLIRGenImpl.h` (`instanceof`, about 6226; `this` in methods and constructors of a `@value` class) +- Modify: where a method's function type and its `this` parameter are built (member generation in `MLIRGenClasses.cpp`, and `MLIRGenFunctions.cpp`). For instance members of a `@value` class only, `this` is the `ValueType` rather than `classInfo->classType`; statics are unchanged. +- Modify: `tslang/lib/TypeScript/MLIRGenCast.cpp` (conversion errors) +- Test: `tslang/test/tester/value/value_class.ts` +- Test: error files `value_mutable_field.ts`, `value_setter.ts`, `value_instanceof.ts`, `value_to_any.ts`, `value_identity.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` + +**Interfaces:** +- Consumes: `ValueType`, `stripValueType`, `valueStorage`, the `ValueType` member-access case and the identity error (Task 2); `ClassInfo::isValue` (Task 1). +- Produces: + - `mlir_ts::ValueType MLIRGenImpl::getValueTypeOfClass(ClassInfo::TypePtr)`, with instance fields (parameter properties included) in declaration order. + - The class's name used as a type resolves to it. Used as a value (`V.plus`, `V.white`), it still resolves to the class, so static access is unchanged. + - Instance methods and getters take `this` as the class's `ValueType`. The plan picks by value (the spec leaves value or pointer-to-copy to the builder); LLVM's ABI lowering decides registers or memory. + - In the constructor, `this` is a `!ts.ref` to a stack slot. `new V(...)` makes the slot, calls the constructor and loads the value. + +- [ ] **Step 1: Write `value_class.ts`.** It runs, asserts and prints `done.`: + - `@value class V { constructor(public readonly x: number, public readonly y: number, public readonly z: number) {} static plus(a: V, b: V) { return new V(a.x + b.x, a.y + b.y, a.z + b.z); } static zero = new V(0, 0, 0); dot(o: V) { return this.x * o.x + this.y * o.y + this.z * o.z; } get len2() { return this.dot(this); } }` + - `@value class P { readonly a: number; readonly b: number; constructor(a: number) { this.a = a; this.b = a * 2; } }` (fields assigned in the constructor) + - `class Cam { pos: V; n = 0; constructor(p: V) { this.pos = p; } }` + + Asserts: + - `V.plus(new V(1, 2, 3), new V(4, 5, 6)).y == 7` + - `new V(1, 2, 2).len2 == 9` + - `V.zero.x == 0` + - `new P(3).b == 6` + - `const c = new Cam(new V(1, 1, 1)); c.n = 5; c.pos = V.plus(c.pos, c.pos); c.pos.x == 2` + - `const arr: V[] = [new V(1, 0, 0), new V(2, 0, 0)]; arr[1].x == 2` + - `let v = new V(1, 0, 0); const w = v; v = new V(9, 0, 0); w.x == 1` + - a 10000-step loop `acc = V.plus(acc, new V(1, 0, 0))` ending at `acc.x == 10000` +- [ ] **Step 2: Write the error files.** + - `value_mutable_field.ts`: `@value class V { x: number = 0; }`. + - `value_setter.ts`. + - `value_instanceof.ts`. + - `value_to_any.ts`: `const a: any = new V(...)`. Expect `the @value class 'V' cannot be converted to 'any'`. + - `value_identity.ts`: `new V(...) === new V(...)`. +- [ ] **Step 3: Register.** + - `value_class` runs AOT and JIT under `gc rc none own`, as in Task 2. + - The error files are added to `value_error_cases`. + - Extend `value_no_alloc.ts` with `export function plus2(a: number): number { return V.plus(new V(a, 0, 0), new V(a, 0, 0)).x; }`, using a `@value class V`. + - `value-no-alloc.cmake` also checks `@plus2(`. +- [ ] **Step 4: Confirm they fail.** `ctest -C Release -R "value-"`. +- [ ] **Step 5: Implement.** + - The `@value` class type is `getValueTypeOfClass`. + - Class creation: + - skips the vtable, `.instanceOf`, `..new` and the RTTI global; + - applies the readonly-field and setter errors. + - `new` and constructors follow the Interfaces block. In `NewClassInstance`, the `ValueType` branch (stack slot, constructor, load) comes before the existing `isValueType` check, which would otherwise box the value as a heap `ValueRefType`. `value-no-alloc` catches a box. + - Method and getter calls on a `ValueType` of a class are direct calls with the value as `this`. + - The conversion error covers `any`, `unknown`, `Object`, unions with non-value members and non-`@value` interfaces. + - `instanceof` with a `@value` class on the right is the error. +- [ ] **Step 6: Run.** `ctest -C Release -R "value-"` should all pass, then the full suite: 0 failed. +- [ ] **Step 7: Commit.** `@value classes: new makes a value, methods take this by value`. + +### Task 4: missing values + +**Files:** +- Modify: `tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h` (`getUnionTypeMergeTypes` about 3445-3515). `ValueType | null` becomes `OptionalType`, through a rule placed before the tuple-is-a-value-type branch (about 3456-3460). `ValueType | undefined` already becomes an optional the way a tuple's does. + - Probed on main under `// @strict-null false`: for `type R = { a: number }`, `R | null` stays `!ts.union>` all the way to MLIR, and `R | undefined` is `!ts.optional>`. Both compare correctly. So the pragma does not strip the union, and the null rule belongs in `getUnionTypeMergeTypes`. +- Modify: `tslang/lib/TypeScript/MLIRGenCast.cpp` (`null`/`undefined` into a plain `ValueType` is the error; into `OptionalType` it is the empty optional) +- Modify: `tslang/include/TypeScript/LowerToLLVM/OptionalLogicHelper.h` only if a comparison shape is missing +- Test: `tslang/test/tester/value/value_missing.ts`, error file `value_null_plain.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` + +**Interfaces:** +- Consumes: Tasks 2-3. +- Produces: + - `T | null` and `T | undefined` for a `ValueType` `T` are `OptionalType`, and so is a `f?: T` parameter or field. + - `T | null | undefined` is a `UnionType` of `T`, `null` and `undefined` (the existing tagged union). So `x === undefined` is false when `x` holds `null`. This is the plan's call on the spec's open encoding: it reuses what exists. + +- [ ] **Step 1: Write `value_missing.ts`.** It has `// @strict-null false` at the top, as the benchmark does, and: + - `@value interface Hit { readonly dist: number; }` + - `function find(d: number): Hit | null { if (d < 0) return null; return { dist: d }; }` + - `function first(xs: number[]): Hit | undefined { let best: Hit | undefined = undefined; for (const x of xs) { const h = find(x); if (h != null && (best === undefined || h.dist < best.dist)) best = h; } return best; }` + - `function opt(v?: Hit) { return v === undefined ? -1 : v.dist; }` + + Asserts: + - `find(-1) === null`, `find(-1) != null` is false, `find(2).dist == 2` + - `first([3, -1, 2]).dist == 2`, `first([-1]) === undefined` + - `find(5)?.dist == 5`, `find(-5)?.dist === undefined` + - `opt() == -1`, `opt({ dist: 4 }) == 4` + - `let u: Hit | null | undefined = null; u === undefined` is false and `u === null` is true +- [ ] **Step 2: Write `value_null_plain.ts`:** `@value interface Hit { readonly dist: number; } function f(): Hit { return null; }`. Expect `a @value type has no null; write 'Hit | null'`. Add it to `value_error_cases`. +- [ ] **Step 3: Register** `value_missing` under `gc rc none own`, AOT and JIT. Confirm it fails. +- [ ] **Step 4: Implement** the union merge, the casts and the error. Check that `x.dist` on an `OptionalType` after a `!= null` test reads the field (the `OptionalType` member-access case at `MLIRGenAccessCall.cpp` about 371). +- [ ] **Step 5: Run.** `ctest -C Release -R "value-"` should all pass, then the full suite: 0 failed. +- [ ] **Step 6: Commit.** `@value: T | null is an optional value; null into a plain @value type is an error`. + +### Task 5: values holding references, generics and closures (gc, rc, none) + +**Files:** +- Modify only where the tests fail: the ownership routines and walkers touched in Task 2, and capture/closure code in MLIRGen (`mlirGenRetainCaptured`, capture analysis) +- Test: `tslang/test/tester/value/value_refs.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` + +**Interfaces:** +- Consumes: Tasks 2-4. + +- [ ] **Step 1: Write `value_refs.ts`.** It runs, asserts and prints `done.`: + - `class Node { constructor(public n: int) {} }` + - `@value interface Rec { readonly node: Node; readonly w: number; }` + - `@value class V { constructor(public readonly x: number) {} static plus(a: V, b: V) { return new V(a.x + b.x); } }` + - `function churn() { let s = 0; for (let i = 0; i < 64; i++) { const t = new Node(i); s += t.n; } return s; }` (same-size objects reuse freed blocks: the rc use-after-free rule) + + Asserts: + - Build 1000 `Rec`s from fresh `Node`s into an array. Copy each into a local twice, drop the array's reference by overwriting the slot with a new `Rec`, `churn()`, then read `copy.node.n`. Sum the reads and assert the exact total. + - `[new V(1), new V(2), new V(3)].reduce((acc, x) => V.plus(acc, x), new V(0)).x == 6` + - `let v = new V(1); const f = () => v.x; v = new V(2); f() == 2` (the capture is of the binding) + - A closure that captures a `Rec` and is called after the original's `Node` was overwritten elsewhere still reads its own `node.n`. +- [ ] **Step 2: Register** under `gc rc none` (own is Task 6), AOT and JIT, and also run with `--verify-ownership` under rc, as the corpus verifier does. Run it. +- [ ] **Step 3: Fix what fails.** + - A retain or release missing for a reference field of a value goes in the routine that handles tuples, through `stripValueType`, not a value-only path. + - A closure that copies instead of capturing the binding is a capture-analysis bug: the capture must box the variable as it does for any other local. +- [ ] **Step 4: Run.** `ctest -C Release -R "value-"` should all pass, then the full suite: 0 failed. +- [ ] **Step 5: Commit.** `@value: values holding references, through generics and closures`. + +### Task 6: own + +**Files:** +- Test: `tslang/test/tester/own/own_value_record.ts`, `tslang/test/tester/own/own_value_loop.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` (append to the `foreach(own_test ...)` list at about line 3613; add `value_refs` under own) +- Modify, only as Step 3 finds: `tslang/lib/TypeScript/OwnershipInferencePass.cpp`, `OwnershipSignaturePass.cpp`, `OwnedReturnConsumptionPass.cpp`, `OwnershipFacts.h` + +**Interfaces:** +- Consumes: Tasks 2-5. Background: own spec 32 (borrowing records), #679 (a tuple of owned values is a value), rulings 10 and 32 in `.superpowers/own-raytrace-rulings.md`. + +- [ ] **Step 1: Write the own tests.** These are the benchmark's shapes, each with `churn()` and exact totals. + - `own_value_record.ts`: `interface Thing { hit(r: Ray): Hit | null; id(): int; }`, `@value interface Ray { ... }`, `@value interface Hit { readonly thing: Thing; readonly ray: Ray; readonly dist: number; }`. `class S implements Thing { hit(r: Ray): Hit | null { return r.dir.x > 0 ? { thing: this, ray: r, dist: r.dir.x } : null; } }`. The caller reads `h.thing.id()` and `h.dist` through the `Thing` interface. + - `own_value_loop.ts`: the `intersections` loop. `let closest: Hit | undefined = undefined;` over an array of `Thing`s, reassigned from `t.hit(ray)` inside the loop when nearer. Then the result is used after the loop, and passed to a function that reads `thing` and calls through it. +- [ ] **Step 2: Run them** with `test-runner -mm=own` and `-jit -mm=own`. Also run `value_interface`, `value_class`, `value_missing` and `value_refs` under own. +- [ ] **Step 3: Handle each rejection or crash.** Reduce it to a minimal `--no-default-lib` repro, find the cause in the pass, and decide: + - **Real imprecision:** fix it properly, and add a positive own test, plus an `own_err_*` case if the fix narrows an error. + - **Correct error** (the code really is unsafe): stop and report it with the repro. The spec says the benchmark change for it is decided separately. + + Never special-case `ValueType` inside an ownership pass to get a shape through. A value is a tuple to the passes. +- [ ] **Step 4: Run.** `ctest -C Release -R "own|value-"` should all pass, then the full suite: 0 failed. +- [ ] **Step 5: Commit.** `-mm=own: @value records` (plus each fix, described in the message). + +### Task 7: `@value` across a module boundary + +**Files:** +- Test: `tslang/test/tester/tests/export_value_types.ts`, `tests/import_value_types.ts` +- Modify: `tslang/test/tester/CMakeLists.txt` (beside `test-compile-shared-export-import-final-class`) + +**Interfaces:** +- Consumes: Tasks 1-4. `__decls` carries `@value` because the printer prints it. + +- [ ] **Step 1: Write the pair.** + - `export_value_types.ts`: `@value export class V { constructor(public readonly x: number) {} static plus(a: V, b: V) { return new V(a.x + b.x); } get twice() { return this.x * 2; } }`, `@value export interface R { readonly a: V; readonly n: number; }`, and `export function mkR(n: number): R { return { a: new V(n), n: n }; }`. + - `import_value_types.ts` sums `V.plus(mkR(i).a, new V(1)).twice` over 1000 iterations, asserts the exact total, builds an `R` literal locally and passes it back, then prints `done.`. +- [ ] **Step 2: Register.** + - `test-compile-shared-export-import-value-types` (`test-runner -shared`) and `test-jit-shared-export-import-value-types` (`-jit -shared`), for `gc rc` through `foreach(mm gc rc)`. + - The same two under `own`, registered the way `import_own_record` is. own is the primary target. +- [ ] **Step 3: Run, full suite, commit.** `@value: -shared import`. + +### Task 8: the benchmark + +**Files:** +- Modify: `tslang/benchmarks/raytrace/rtbench.ts`, `rtbench_own.ts` (header comments and the edits below) +- Modify: `tslang/benchmarks/raytrace/README.md` (a new results section above "Results 2026-10-24") +- Modify: `C:\Users\duzha\.claude\projects\I--TypeScriptCompiler\memory\raytrace-alloc-spike-2026-10-24.md` and `MEMORY.md` + +**Interfaces:** +- Consumes: everything above. + +- [ ] **Step 1: Edit both benchmark files** exactly as the spec's "Benchmark edits" lists. Leave every object literal unchanged. + - `@value class Vector`, `@value class Color`, with constructor parameters `public readonly` + - `@value interface Ray`, `@value interface Intersection`, with fields `readonly` + - `intersect(...)`: `Intersection | null` in `Thing`, `Sphere` and `Plane` + - `let closestInter: Intersection | undefined = undefined;` + - `rtbench_own.ts`: `Plane.normal` returns `this.norm` + + Check that `git diff` shows no change to any `{ ... }` literal line. +- [ ] **Step 2: Check the checksum.** For each model, compile and run as `bench.ps1` does (`--emit=exe --opt --opt_level=3 --no-default-lib --mm=`; own builds `rtbench_own.ts`). Each prints 38837369. A difference is a bug in Tasks 2-6: go back there with a reduced test. +- [ ] **Step 3: Check that the hot path is allocation-free.** Run `--emit=mlir-affine --stack-promotion-report` under rc on `rtbench.ts`. No remaining heap site may be a `Vector`, `Color`, `Ray` or `Intersection`. Record which heap sites remain (expected: the `addLight` closure and setup-time objects). +- [ ] **Step 4: Measure.** Run `pwsh tslang/benchmarks/raytrace/bench.ps1` twice and take the medians. +- [ ] **Step 5: Write the README section** "Results : `@value`". It needs: + - the table: every row of the 2026-10-24 table, with a `@value` column; + - the same machine notes; + - the stack-promotion finding; + - "Where the time goes" for what is left, if own and none are above about 60 ms (1.1x of Rust's 54 ms). The spec makes that a report, not more work in this project. +- [ ] **Step 6: Update memory.** Record the numbers, the branch and its state in `raytrace-alloc-spike-2026-10-24.md`, and its `MEMORY.md` line. +- [ ] **Step 7: Full suite, commit.** `Ray tracer: Vector/Color/Ray/Intersection are @value; results`. diff --git a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md index 3bf6cecc5..7e0e2fd31 100644 --- a/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md +++ b/tslang/docs/superpowers/specs/2026-09-24-own-memory-model-design.md @@ -4392,3 +4392,119 @@ Not here: are not values `movesOf` checks, so `each`'s `ts.RetainSlot` is still `merged from several branches` (and `moved inside a loop`). A `const each` of the same reads compiled before this section and still does. + +## 36. Records with no box: tuples that hold borrows (`@value` records), 2026-10-24 + +With `@value` (docs/superpowers/specs/2026-10-24-value-types-design.md) the ray tracer's +`Intersection` is a tuple, not a box: `{ thing: this, ray: ray, dist: dist }` returned as +`Intersection | null` through the interface `Thing`, and `closestInter` given the nearer one inside +`intersections`' loop. Section 32's records are boxes, found where `ts.New` is filled from the +literal's local; a tuple has none, so the store of `this` into the literal's field was a keep, the +facts were lost (`'S.intersect' could return a borrow or keep a parameter, but it is reached through +an interface`), and every use downstream was an error. The same held for a type literal (`type Hit = +{ thing: Thing; d: number }`). The marked benchmark had 13 own errors. + +**The rule.** A tuple that holds borrows and owns nothing is a borrowing record with no box: Rust's +`struct Hit<'a> { thing: &'a Th, .. }` passed by value. What it borrows bounds every use of it, as in +section 32; there is nothing to give back, so no copy of it is counted and no release of it, or of a +local that holds only such records, frees anything. + +- **Which literals** (OwnershipSignatureRecords, `classifyUnboxedRecord`, in every round of the facts + fixpoint beside `classifyRecordBoxes`). An object literal's local (`isConstantRecordLocal`) whose + read is never boxed (`recordBoxOfLocal`), read whole (a literal whose fields are read one by one, to + be re-made as another tuple, is not one), where every field that holds a block borrows it - `this` or + a parameter, a read out of a place, a call's result that borrows, an owning local's value, a + captured variable's, an immortal value - and at least one does. A fresh value counts only in a + *temporary*, a literal whose read is only given to calls that do not keep it and read + (`len({ start: new Vec(1, 2), dir: new Vec(3, 4) })`): the new vectors keep their own releases, and + the record borrows them too. Anywhere else a fresh field is one the tuple would own (an owning tuple, + #679's rules). Never a handle (counted, section 23), a string (copied, section 22), or a field of a + generator's state (whether that read moves the value out is the generator's rule, decided after the + facts: `findYieldedFields`). The local is marked `__own_record_unboxed_fields` (and + `__own_record_temporary`); each read of it is a record in `recordBoxes`. +- **The facts.** A function whose returned values are all such records (through views, merges and + owning locals: `recordParamsOf`) has record facts as in section 32, plus `__own_result_record_unboxed` + on the function and its calls (`Facts.unboxed`). Boxes and unboxed records in one value, or on two + return paths, give no facts: their callers release them differently. Families agree on it as on the + rest. A function with `@lends` and `@record` that another module can call and whose body returns an + unboxed record is an error: `@record` tells the importer it owns a box, and it cannot be told this. +- **Where the record is made and where a call returns one** (OwnershipInferenceRecords). The unboxed + record joins `records` (no box; its reads are the starts of `walkRecord`), and a call that returns + one goes through `checkRecordResults` as before. `walkRecord` follows what a tuple adds: a field + taken out of the record (`ts.ExtractProperty`) that may point into a block is the record still - kept, + it is the record kept - and a field read in place out of a local that holds the record + (`ts.PropertyRef` of the local, or of the local seen as its storage tuple) is a read of the record, + whose loaded value is the record's, and a write of that field (`r.s = x`) is a keep. A temporary's + fresh field is bounded by that value's own release. +- **No owner to find.** A value whose sources are only unboxed records and values that hold no block + (`unboxedRecordFlow`: through views, merges and owning locals) has no owner check + (`checkOwnershipOps` skips it: copies are free), its retains go (`decideRetains`), and after the + moves are placed `dropUnboxedRecordCounts` erases every retain and release of it, and every + `ts.RetainSlot` and `ts.ReleaseSlot` of a local that holds only such values - the edge releases of + section 30 included. A local or a merge that holds one beside a value that owns a block is `a value + that borrows what it holds and owns nothing (a tuple that holds a borrow) meets a value that owns a + block here; -mm=own cannot release them alike`. A handle's counts are left alone. A `@value` local + is reached through a cast of its reference to its storage tuple, and every one of these walks + looks through it (`slotVariableOf`, `valuesStoredInto`). + +Fixes on the way, each needed by a test of this section: + +- `isView`: a `ts.Cast` between a `@value` type and its storage tuple is the same value (it lowers to + nothing). The type walkers of the signature pass (`valueInterfaces`, `anyInterfaces`, + `functionValues`, `castMakesInterface`, `holdsFunction`, `storageTupleOf`) read a `@value` type as + its tuple (`asStorageTuple`): `castMakesInterface(value, tuple)` answered yes and opened `Thing`, which + is why the facts above were "reached through an interface". +- `recordRetainOf` follows the record's read through its views (a `@value` literal is read, then cast + to its type, then retained and returned). +- `fieldTakersOf` and `fieldOnlyRead`: a field taken out of a record that holds no block takes nothing + (`print(h.dist)` converted the number to a string, which counted as a taker of the record). +- A closure that does not escape and captures, by reference, storage of this frame or one a parameter + points to that holds no block (`this` of a `@value` constructor whose fields are numbers) needs no + owner: `'this value' is captured by a closure, but -mm=own cannot tell who owns its value here` before. + +Tests: `own_value_record` (the brief's `S` with a ternary and `P` with an `if`, through `Thing`, 1000 +rays with churn), `own_value_loop` (the `intersections` loop: `closest` starts undefined, takes the +nearer `t.hit(ray)`, is returned and shaded through `thing`), `own_value_temporaries` (call-argument +temporaries of a `@value` interface and of a type literal, a `const` record borrowing a `let` twice +read in place, a `@value` constructor's closure), under own (no counting), rc, gc and none, AOT and +JIT; `value_iface_cycle` and `value_ternary_null` under own too. Negatives: +`own_err_value_record_place_dropped` (the record borrows `p.child`, which a call overwrites before +`o.s` is read in place), `_stored` (pushed into an array), `_let_reassigned`, `_mixed_local`, +`_field_written`, `_param_field_kept` (a callee pushes a record parameter's borrowed field), and the +exits of a record that borrows a `let`: `_returned`, `_captured` (by a closure that escapes), +`_field_stored` (a class field), `_global`. `own_err_value_refs_copy` pins `value_refs`' copy +shape (a copy out of an array read after the element is overwritten); own rejects it at the read +even without the overwrite, an over-rejection that predates this section. `value_interface` runs +under own; its two gaps (below) are in `value_interface_own_gaps`, which every other model runs. `own_err_record_literal_let_field` now reads `borrows ... and cannot be stored` at +the push (the literal borrows the `let`); `own_err_shared_place_literal` pins the handle exclusion (with +it missing, it compiled and crashed with 0xC0000005). + +Teeth (temporary switches, removed): with `dropUnboxedRecordCounts` off, the AOT builds of +`own_value_record` exit 0xC0000005 and `own_value_loop` and `own_value_temporaries` 0xC0000374; with the +in-place field read of `walkRecord` off, `own_err_value_record_place_dropped` compiles and prints 11 +(gc 5; before the storage cast was followed it printed 77777). + +Corpus (`test/tester/tests/*.ts` under `-mm=own --no-default-lib`, `--emit=obj`, Windows): 542 +before, 543 after: `00spread` compiles and prints what gc prints, AOT and JIT. + +The marked benchmark (`rtbench.ts` with the value-types edits and `rtbench_own.ts`'s `Shared`, +`Plane.normal` returning `this.norm`), `--emit=exe --opt --opt_level=3 -mm=own`: 13 errors before, none +after; it prints the checksum 38837369. + +Not here: +- A literal nested in another whose fields own new values (`{ ray: { dir: new Vec(..), .. }, thing: + new T1() }`), and an owning literal pushed into an array or stored into a field: #679's owning + tuples move only into a local or the result (`value_interface_own_gaps`, off under own). +- An unboxed record converted to an ordinary interface (`const s: HasStart = mk(new Vec(6, 0), ..)`): + the box made from the value would own the fields the record borrows. It needs section 32's box + classification for a box filled from a record value, not from a literal (`value_interface_own_gaps`). +- A closure inside a closure in a `@value` method that captures `this` (`value_refs`' `Box.nested`): + the inner capture of the outer box's copy is a keep. +- `value_refs` as a whole: it copies values that hold owned Nodes out of arrays, fields, a generic and + closures and reads the copies after the originals' Nodes are overwritten. Under single ownership + the copy is a borrow of the original, and those programs read freed blocks; own rejects each one + (`borrows an element and cannot be stored`, `... but is used here after ...`), correctly. +- An exported function returning an unboxed record (see the facts above). +- `const ts: Th[] = [new A(), new B()]; const h = ts[1].hit(ray); print(h.dist)` outside a loop is + `borrows an element but is used here after it may be released or overwritten` for a record with a + box (section 32) as much as for one without; the same call inside a loop over `ts` compiles. diff --git a/tslang/docs/superpowers/specs/2026-10-24-value-types-design.md b/tslang/docs/superpowers/specs/2026-10-24-value-types-design.md new file mode 100644 index 000000000..18c0a8146 --- /dev/null +++ b/tslang/docs/superpowers/specs/2026-10-24-value-types-design.md @@ -0,0 +1,267 @@ +# `@value` classes and interfaces + +Date: 2026-10-24. Status: design, awaiting approval. + +## Why + +The ray tracer benchmark (`benchmarks/raytrace`) runs 8x slower than idiomatic Rust (own 444 ms, +none 434 ms with PR #683, Rust 54 ms). The user's goal is 1.1x of Rust, about 60 ms. Almost all of +the gap is heap allocation of short-lived `Vector`, `Color`, `Ray` and `Intersection` objects: +Rust's port allocating the same objects behind `Rc` takes 490 ms. Stack promotion cannot remove +them: the `Vector`/`Color` results are "returned", and the `Ray`/`Intersection` literals are +"converted" (boxed when they become interface values, `castTupleToInterface`). + +TypeScript has no way to say "this is a plain value". The user's ruling: the benchmark may opt in +with a `@value` marker, and a `@value` type behaves like a value object. Its fields are readonly +and it has no identity, so copying it is invisible, and a program means the same as it does in +ordinary TypeScript. Only speed and memory change. + +## Goals + +- `@value` on a class declaration: the class's instances are values (a struct of its fields), not + heap objects. `new C(...)` makes a value; passing, returning, assigning and storing copy it. +- `@value` on an interface declaration: the interface type is a value of its fields, so an object + literal of that type stays the stack tuple tslang already builds for it, with no box and no + vtable. +- The benchmark keeps its object literals exactly as written. `rtbench.ts` and `rtbench_own.ts` + mark `Vector` and `Color` as `@value` classes and `Ray` and `Intersection` as `@value` + interfaces (see "Benchmark edits"). +- Every memory model (gc, rc, own, none) compiles the marked benchmark and prints the same checksum + (38837369). Own included: if own rejects a `@value` value holding a borrow, fixing the ownership + passes is part of this project (the user's ruling). +- Target: the marked benchmark runs within 1.1x of Rust idiomatic, about 60 ms, under own and + none. rc and gc are measured and reported too. The project is done when `@value` works and is + measured, whether or not it reaches 60 ms: the README then says where the remaining time goes, + and closing the rest is a separate project (the user's ruling). + +## Non-goals + +- Inferring value-ness for unmarked classes or interfaces (escape analysis, stack promotion v2). +- Generic `@value` classes, `@value` classes with `extends` or `implements`, and converting a + `@value` class value to `any`, `unknown`, `Object`, a union with non-value members, or a + non-`@value` interface. Each is a compile error in this version (boxing them is a follow-up). +- Removing the remaining indirect calls: `Thing.intersect`/`normal` through the interface, the + `Surface` function fields, the `addLight` closure and the virtual `RayTracer` methods stay as + they are. The first three are indirect in Rust too. +- Fixing the existing handling of `null` assigned to a plain type-literal tuple (see "Found on the + way"). + +## Anti-goals + +- A program whose output differs from ordinary TypeScript. Where a `@value` value would let the + difference show (identity, mutation, `instanceof`), the compiler rejects the program instead. +- Changing anything for code without `@value`. +- Making `@value` a hint the compiler may ignore. Marked types are always values; anything that + cannot be compiled as a value is an error that names the reason. + +## Design + +### The marker + +- `#define VALUE_DECORATOR "value"` in `Defines.h`, beside `FINAL_DECORATOR`. +- Classes: `ClassInfo` (`MLIRGenStore.h`) gets `bool isValue`, set in the class decorator loop in + `MLIRGenClasses.cpp` (about 382-420, where `@cpp` and `@final` are read), on declarations as + well as definitions. +- Interfaces: `InterfaceInfo` (`MLIRGenStore.h` about 283-315) gets `bool isValue`. Interfaces read + no decorators today; `mlirGenInterfaceInfo` (`MLIRGenInterfaces.cpp` about 1118) reads them with + `iterateDecorators`, as classes do. The parser already accepts decorators on interfaces. +- `DeclarationPrinter` prints `@value` before both, so `-shared` importers (`__decls`) see it. +- `@value` with `@cpp`, `abstract`, `@final` (implied anyway), `extends`, `implements` or type + parameters is an error. + +`@value interface` is not valid TypeScript for `tsc`, which rejects decorators on interfaces. That +is accepted: the benchmark already depends on tslang-only declarations. + +### One marked type for both + +Both kinds of `@value` declaration get one new type, `ValueType` +(`!ts.value<@Name, !ts.tuple<...>>`): the declaration's name and its fields as a tuple in +declaration order. It lowers to the tuple's LLVM struct. The marker is what the rules below key on +(`T | null` as an optional, the `===` error, the declaration printer), so plain tuples and type +literals keep exactly their current behaviour, including the bug under "Found on the way". +*(Designer's call, after the builder check.)* + +- A `@value` class's type is nominal: only that class's values convert to it. +- A `@value` interface's type is structural, as TypeScript says: a tuple, an object literal, a + type-literal value or another `@value` interface value with the same fields converts to it by + copying the fields into its order, and it converts to a type literal with the same fields the + same way. + +### `@value` interfaces + +A `@value` interface value is laid out as its type literal already is: the tuple of its fields in +declaration order (`type Ray = { start: Vector; dir: Vector }` is passed by value today). So: + +- A `@value` interface may have only fields, all `readonly`, none optional (`?`). Methods, index + signatures, call signatures and `extends` of a non-`@value` interface are errors. +- An object literal whose contextual type is a `@value` interface is built as the tuple in the + interface's field order (the existing reordering in `mlirGen(ObjectLiteralExpression)`), with no + `castTupleToInterface`. A literal with extra or missing fields is the usual type error. +- `x.f` is a field of the tuple: `PropertyRef`/`ExtractProperty`, not `InterfaceSymbolRef`. +- Converting to a non-`@value` interface, `any` or `Object` boxes a copy, through the existing + tuple-to-interface and tuple-to-any paths. Readonly fields and no identity make the copy + invisible. +### `@value` classes + +A `@value` class's `ValueType` carries the class's name, for member lookup and type checks, and its +instance fields in declaration order (parameter properties included). A plain `TupleType` is not +enough: two `@value` classes with the same fields would be one type, and a method call on a value +would not know its class. + +- Fields: every instance field is `readonly`; a field without it is an error. Field reads are tuple + field reads. +- `new C(args)` reserves a stack slot for the tuple, runs the constructor with `this` pointing at + the slot, and loads the value. In the constructor `this` may be read and its fields assigned, as + `readonly` allows. `this` there is the slot being filled, not a value yet, so it may only be the + object of a member access: `this.f` reads, `this.f = x` and `this.f++` writes, `this.m()` (the + method sees the fields stored so far), `this["f"]`, in the constructor or in an arrow function + inside it (a closure that captures `this` may only be called there: "a closure that captures + 'this' of the @value class 'V' can only be called inside its constructor"). Any use + of `this` as a whole value - `const self = this`, `let s = this`, `f(this)`, `arr.push(this)`, + `return this`, `[this]`, `{ v: this }`, `...this`, `() => this` - is an error: "'this' of the + @value class 'V' is not a value until its constructor returns; read 'this.f'". A copy taken + there would miss the fields stored after it, where TypeScript's object has them. An instance + field's initializer runs in the constructor (in the one made for it when none is written), so the + same rule holds there: `readonly b = show(this)` is the error, `readonly b = this.a * 2` is not. +- Instance methods and getters take `this` as a value (or a pointer to a caller copy: builder's + choice) and are called directly; there is no vtable and no `.instanceOf`. Setters are an error. +- Static members are unchanged. A static field of the class's own type (`static white = new + Color(...)`) is a global holding the value. +- `instanceof C` is an error (no type information at run time). +- The class may not be extended, and may not extend or implement anything (non-goals). + +### Rules for both + +- `===`, `!==`, `==`, `!=` between two `@value` values is an error ("a @value type has no identity; + compare its fields"). Comparing with `null` or `undefined` is allowed (see "Missing values"). +- `typeof v` is `"object"`. +- Arrays (`Vector[]`) hold the values inline, as arrays of tuples do today. +- A generic function or class instantiated with a `@value` type works on copies, as it does with a + tuple. The benchmark needs this: `scene.lights.reduce(addLight, ...)` instantiates + `__array_reduce` with `R = Color`. Only a `@value` class with type parameters of its own is a + non-goal. +- A `@value` value may hold references (`Intersection.thing: Thing`). Copying it copies them as a + tuple copy does today: rc retains each owning field (`buildRetainBody` falls through to + `retainFields`), gc scans the stack, and none does nothing. Under own, a value holding a borrowed + reference is a record (own spec 32, the tuple rules of #679). Today's own support for the ray + tracer rests on borrowing records that live in a box the caller owns (ruling 32 in + `.superpowers/own-raytrace-rulings.md`); with `@value` there is no box. If own rejects + `{ thing: this, ... }` returned through the `Thing` interface, or `closestInter` reassigned in + the loop (ruling 10), the builder fixes the ownership passes properly, with a minimal repro and + an own test for each imprecision. A workaround that bends a pass only for these shapes is not a + fix. If a rejection turns out to be correct (the code really is unsafe), it is reported and the + benchmark change for it is decided separately. +- Stack promotion and the escape facts need no new reason codes: there is no allocation to + report. +- A `@value` type cannot contain itself, directly or through other `@value` types: it is the tuple + of its fields, held in place, so `next: L | null` (or `A.b: B | null` with `B.a: A`) would make it + infinitely large. The error names the type and the fields from it back to itself: "@value type 'L' + contains itself through 'next'; a value cannot hold itself", "@value type 'A' contains itself + through 'b.a'; ..." (each type of a longer cycle is reported, from its own field). An array of + itself in a field (`next: L[]`) or a function type naming it is the same error: the field's type is + made from the `ValueType` being made, which names its whole tuple, so it cannot refer to itself. + An ordinary class or interface between them (`box: Box` with `Box.l: L | null`) is a reference, + and works. A generic one specialized with the type itself (`box: Box`) is not: the specialized + class's type is made from L's, so it is "@value type 'L' reaches itself through 'box' in the type + arguments of 'Box'; a @value type cannot hold a generic type made from it". (The unspecialized + `Box` was taken in its place before, and the compiler crashed at a literal of L.) The same holds + through another @value type (`A.p: Box` with `B.a: A`). A generic of another @value type + declared later (`box: Box`) is typed once K is laid out, wherever the generic is declared; + while a @value type's field is typed, a failed instantiation is never replaced by the + unspecialized generic, so `Box` is "can't find type by name: Nope". + +### Missing values + +TypeScript lets `null` and `undefined` stand for an `Intersection`. A value has no null pointer. + +- Every way of writing that a `@value` type `T` may be missing - `T | null`, `T | undefined`, + `T | null | undefined`, an optional parameter `v?: T`, an optional field `f?: T` - is one + encoding with three states: `OptionalType>` + (`MLIRTypeHelper::getMissingValueType`). undefined is the empty optional, null is the union's + null member, and a value is the union holding `T`. Converting between the spellings changes + nothing, so null stays null and undefined stays undefined, and converting a plain `T` to one + makes a present value. +- As emitted, that is a tagged union inside an optional. `isUnionTypeNeedsTag` answers yes for + the union (`isMissingValueUnion`: one `ValueType` member and `null`), where merging its members + would give the optional back, so it is laid out as any tagged union is: a packed + `<{ ptr, payload }>`. The tag is a pointer to the member's name in a type-descriptor constant + (`@td__object` for the value, since `typeof` of a value is `"object"`; `@td__null` for + null), pointing past the descriptor's 32-byte header at the name string. The payload is an + array of `i64` as large as the largest member (`<{ [1 x i64] }>` for `{ dist: number }`), and + holds the value's storage tuple. The optional adds its has-value `i1`, so `Hit | null` of + `@value interface Hit { readonly dist: number }` is passed and returned as + `{ <{ ptr, <{ [1 x i64] }> }>, i1 }`. undefined is all zeroes (`i1` false); null is `i1` true + with the `null` descriptor's tag and a zero payload; a value is `i1` true with the + `object` tag and the tuple. `=== undefined` reads the `i1`; `=== null` and `== null` read it and + then compare the tag with the string `"null"` (`strcmp` when the tag is not a null pointer). + This is the cost the benchmark README measures for `Intersection | null`. +- Strict comparisons with `null` and `undefined` are exact, as in TypeScript: `x === undefined` is + false for `null`, and `x === null` false for `undefined`. Loose `x == null` and `x != null` ask + whether `x` holds a value. Comparing one with anything else (another value, a number) is the + identity error above. +- Reading a field of a missing value, calling a method or getter on it, or converting it to a + plain `T` throws at run time, as a method of a null interface does (the same throwing stub, + with its own message). +- Under `// @strict-null false`, a conversion such as `const h: Hit = find(-1)` therefore throws at + the conversion, where TypeScript would throw only at a later read of `h`. This divergence is + accepted (controller's ruling). +- Assigning, returning or initializing `null`/`undefined` into a plain `T` is an error, even in a + `// @strict-null false` file: "a @value type has no null; write `T | null`". This is the user's + ruling: it costs four type annotations in the benchmark and keeps every other `@value` slot free + of a flag. In a non-strict file `T | null` is written out for the compiler's sake; TypeScript + reads it as `T`, so the program means the same. +- The optional storage applies only to `@value` types (`ValueType`). How unions of plain tuples + with `null` are built today (`getUnionTypeMergeTypes`) does not change. + +### Benchmark edits + +Both `rtbench.ts` and `rtbench_own.ts`, comments updated. No object literal changes. + +- `@value class Vector`, `@value class Color`, their constructor parameters `public readonly`. +- `@value interface Ray`, `@value interface Intersection`, fields `readonly`. +- `Thing.intersect`, `Sphere.intersect`, `Plane.intersect`: `Intersection | null`. +- `RayTracer.intersections`: `let closestInter: Intersection | undefined = undefined`. +- `rtbench_own.ts`: `Plane.normal` returns `this.norm` again, since returning a value copies it. +- `Color.toDrawingColor` and `Camera`, `Light`, `Scene` are unchanged. + +The Rust and C++ ports are unchanged. README gains a results section with and without the markers. + +## Testing + +- `test/tester` positive tests, each AOT and JIT, under every model where the suite runs them: + - a `@value` class with a constructor, static helpers, an instance method, a getter and a static + field of its own type; values passed, returned, stored in a class field and an array; + - a `@value` interface built from literals in a different field order, read, passed and nested + in another `@value` interface and in a `@value` class; + - `T | null` / `T | undefined` returned and compared, and a field read after a check; + - a `@value` value holding a class reference, copied many times under rc with a `churn()` of + same-size objects (the use-after-free rule from the rc work); + - a `@value` interface value converted to an ordinary interface and to `any`, then read. +- Error tests: a non-`readonly` field, a setter, `extends`/`implements`, generic, `instanceof`, + `===` between values, `null` into a plain `@value` type, a method or `?` field in a `@value` + interface, `@value @cpp`, converting a `@value` class to `any`. +- An IR check that a function taking and returning `@value` values and building a literal of a + `@value` interface has no allocation call in its optimized LLVM IR (like + `fresh-objects-folded.cmake`). +- A `-shared` pair: an exporting module with a `@value` class and a `@value` interface, used from + an importer. +- The full suite stays green (5525 on Windows Release with PR #683). +- `bench.ps1`: the checksum under all four models, and the timings. + +## Found on the way + +On main, `return null` from a function returning a type-literal tuple compiles with +`warning: invalid cast from '!llvm.ptr' to '!llvm.struct<(ptr, ptr)>'`, and the result compares +`false` with both `null` and `undefined`; a tuple local initialized with `undefined` compares +`false` with `undefined`. That is a bug in plain TypeScript code, separate from this project. + +## Left to the builder + +- How `ValueType` is threaded through MLIRGen: where a class reference resolves to it, and + which class paths (`NewClassInstance`, `ClassMembersAccess`, field access) branch on it. +- Passing `this` to instance methods by value or by pointer to a copy, and how large values are + passed in calls (the LLVM ABI decides registers versus memory). +- The encoding of `T | null | undefined`. +- Error message wording. +- Branch layout: on main, or stacked on `process-heap-malloc-attrs` (PR #683) so the benchmark + numbers include it. diff --git a/tslang/include/TypeScript/DOM.h b/tslang/include/TypeScript/DOM.h index e8cdb0f9f..fcfb9cd0b 100644 --- a/tslang/include/TypeScript/DOM.h +++ b/tslang/include/TypeScript/DOM.h @@ -30,6 +30,7 @@ class VariableDeclarationDOM bool captured; bool ignoreCapturing; bool _using; + bool captureByValue; mlir::Value disposeGuard; // a generator's local narrowed by a test: a view of the local's own storage, read and cast // to this type at each read (addSafeCastStatement) @@ -39,7 +40,8 @@ class VariableDeclarationDOM using TypePtr = std::shared_ptr; VariableDeclarationDOM(StringRef name, mlir::Type type, mlir::Location loc, Expression initValue = undefined) - : name(name), type(type), loc(loc), initValue(initValue), captured(false), ignoreCapturing(false), _using(false), readWrite(false), + : name(name), type(type), loc(loc), initValue(initValue), captured(false), ignoreCapturing(false), _using(false), + captureByValue(false), readWrite(false), atomic(false), ordering(0), syncscope(StringRef()), volatile_(false), nonTemporal(false), invariant(false) { @@ -82,6 +84,19 @@ class VariableDeclarationDOM readWrite = value; } + // A closure captures this read-write variable by value, not its cell: `this` of a @value class's + // method, which nothing assigns and whose value cannot change. A `ref` to a @value type named + // `this` in a capture is then only ever the constructor's slot (MLIRTypeHelper:: + // isValueConstructorThisCapture). + bool getCaptureByReference() const + { + return readWrite && !captureByValue; + } + void setCaptureByValue(bool value = true) + { + captureByValue = value; + } + bool getCaptured() const { return captured; diff --git a/tslang/include/TypeScript/Defines.h b/tslang/include/TypeScript/Defines.h index 4089e5100..29c59e94e 100644 --- a/tslang/include/TypeScript/Defines.h +++ b/tslang/include/TypeScript/Defines.h @@ -325,6 +325,9 @@ // `@final class C`: no class may extend C, so a call on a value of type C is a direct call to the // method C has (docs/superpowers/specs/2026-10-19-final-classes-design.md) #define FINAL_DECORATOR "final" +// `@value class C` / `@value interface R`: a type whose values are copied, not shared - no identity, +// no vtable, no base (docs/superpowers/specs/2026-10-24-value-types-design.md) +#define VALUE_DECORATOR "value" // On a `ts.ThisVirtualSymbolRef` (a method's) or a `ts.VirtualSymbolRef` (an accessor's): the // receiver's class is @final, but defined in another module, so the call still goes through the // vtable. The slot holds the method the reference names, which diff --git a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h index b22809eab..ea8bb7722 100644 --- a/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h +++ b/tslang/include/TypeScript/LowerToLLVM/CastLogicHelper.h @@ -110,6 +110,31 @@ class CastLogicHelper return in; } + // a @value type is its storage tuple: the cast to or from that exact tuple changes nothing + // (MLIRGenImpl::valueStorage, and the cast that makes a tuple a value) + if (auto inValueType = dyn_cast(inType); inValueType && inValueType.getStorageType() == resType) + { + return in; + } + + if (auto resValueType = dyn_cast(resType); resValueType && resValueType.getStorageType() == inType) + { + return in; + } + + // ...and so is its place: a field of a @value value is read in place (GetReferenceFromValue) + if (auto inRefType = dyn_cast(inType)) + { + if (auto resRefType = dyn_cast(resType)) + { + auto inValueType = dyn_cast(inRefType.getElementType()); + if (inValueType && inValueType.getStorageType() == resRefType.getElementType()) + { + return in; + } + } + } + if (auto literalType = dyn_cast(inType)) { return cast(in, literalType.getElementType(), tch.convertType(literalType.getElementType()), resType, resLLVMType); diff --git a/tslang/include/TypeScript/LowerToLLVM/LLVMDebugInfo.h b/tslang/include/TypeScript/LowerToLLVM/LLVMDebugInfo.h index 942f7ace5..a0c6ca93e 100644 --- a/tslang/include/TypeScript/LowerToLLVM/LLVMDebugInfo.h +++ b/tslang/include/TypeScript/LowerToLLVM/LLVMDebugInfo.h @@ -178,6 +178,13 @@ class LLVMDebugInfoHelper return getDITypeWithFields(location, tupleType, to_print(tupleType), false, file, line, scope); } + // a @value value is laid out as its storage tuple + if (auto valueType = dyn_cast(type)) + { + return getDITypeWithFields(location, valueType.getStorageType(), valueType.getName().getValue().str(), false, file, + line, scope); + } + if (auto optionalType = dyn_cast(type)) { return getDITypeWithFields(location, optionalType, to_print(optionalType), false, file, line, scope); diff --git a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h index c43da2872..8eeb1410e 100644 --- a/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h +++ b/tslang/include/TypeScript/LowerToLLVM/OwnershipRoutineLogic.h @@ -1042,6 +1042,7 @@ class OwnershipRoutineLogic auto loc = op->getLoc(); auto ptrTy = th.getPtrType(); auto llvmTupleType = tch.convertType(tupleType); + auto captureTupleType = dyn_cast(tupleType); for (auto [index, fieldType] : llvm::enumerate(getFieldTypes(tupleType))) { @@ -1051,6 +1052,15 @@ class OwnershipRoutineLogic continue; } + // `this` of a @value class's constructor is captured by reference, but its storage is + // the slot `new` made in the caller's frame, not a cell: the box borrows it and gives + // nothing back for it + if (captureTupleType && + MLIRTypeHelper::isValueConstructorThisCapture(captureTupleType.getFields()[index].id, fieldType)) + { + continue; + } + auto fieldPtr = rewriter.create(loc, ptrTy, llvmTupleType, boxPtr, ArrayRef{0, (int32_t)index}); if (refFieldType) @@ -1106,8 +1116,11 @@ class OwnershipRoutineLogic return fields; } - void buildBody(mlir::Type type, mlir::Value slotPtr) + void buildBody(mlir::Type typeIn, mlir::Value slotPtr) { + // a @value value is its storage tuple: released field by field below + auto type = MLIRTypeHelper::stripValueType(typeIn); + TypeHelper th(rewriter); TypeConverterHelper tch(typeConverter); @@ -1306,8 +1319,11 @@ class OwnershipRoutineLogic // duplicate the object's own references to its fields, so retain must not touch them. // Only values held *inline* - tuples, optionals, tagged unions - propagate a retain // inwards, because copying one really does duplicate every reference it holds. - void buildRetainBody(mlir::Type type, mlir::Value slotPtr) + void buildRetainBody(mlir::Type typeIn, mlir::Value slotPtr) { + // a @value value is its storage tuple: retained field by field below + auto type = MLIRTypeHelper::stripValueType(typeIn); + TypeHelper th(rewriter); TypeConverterHelper tch(typeConverter); diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h index de42e8d73..88a980e77 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRCodeLogic.h @@ -145,13 +145,29 @@ class MLIRCodeLogic if (auto nestedRef = GetReferenceFromValue(location, extractPropertyOp.getObject())) { return builder.create( - location, - mlir_ts::RefType::get(extractPropertyOp.getType()), - nestedRef, + location, + mlir_ts::RefType::get(extractPropertyOp.getType()), + nestedRef, extractPropertyOp.getPosition().front()); } } + // A @value value seen as its storage tuple (MLIRGenImpl::valueStorage) read out of a place + // has that place, seen as the tuple's: its fields are read in place, as a tuple's are, which + // is what tells a read of a field from a value of its own (readsField, readsLiteralSlot). + if (auto castOp = object.getDefiningOp()) + { + auto valueType = dyn_cast(castOp.getIn().getType()); + if (valueType && valueType.getStorageType() == castOp.getType()) + { + auto nestedRef = GetReferenceFromValue(location, castOp.getIn()); + if (nestedRef && isa(nestedRef.getType())) + { + return builder.create(location, mlir_ts::RefType::get(castOp.getType()), nestedRef); + } + } + } + return mlir::Value(); } @@ -261,8 +277,8 @@ class MLIRCodeLogic fields.push_back( mlir_ts::FieldInfo{ MLIRHelper::TupleFieldName(value->getName(), context), - value->getReadWriteAccess() - ? mlir_ts::RefType::get(value->getType()) + value->getCaptureByReference() + ? mlir_ts::RefType::get(value->getType()) : value->getType(), false, mlir_ts::AccessLevel::Public diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h index 29b17de72..a39b54b53 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRGenStore.h @@ -310,7 +310,14 @@ struct InterfaceInfo bool hasNew; - InterfaceInfo() : hasNew(false) + // `@value`: its values are copied, not shared (see ClassInfo::isValue) + bool isValue; + + // every member resolved: the fields a @value interface's type is made of are all known (see + // MLIRGenImpl::getValueTypeOfInterfaceIfLaidOut) + bool membersResolved; + + InterfaceInfo() : hasNew(false), isValue(false), membersResolved(false) { } @@ -811,6 +818,9 @@ struct ClassInfo // `@final`: nothing extends it, so a method of a value of this type is called directly. The // vtable stays: interfaces, `instanceof` and calls through a base type use it. bool isFinal; + // `@value`: its values are copied, not shared - no identity, no vtable, no base class, no + // interface, no type parameters. Set for a `declare` declaration too. + bool isValue; // a @cpp class with methods that have bodies: C++ methods implemented here, so C++ can // call them through its objects. It has a vtable (the C++ one's layout: the slots and nothing // else, a slot left to a declared C++ method null), may have a constructor and field @@ -829,7 +839,7 @@ struct ClassInfo ClassInfo() : isDeclaration(false), hasNew(false), hasConstructor(false), constructorAccessLevel(mlir_ts::AccessLevel::Public), hasInitializers(false), hasStaticConstructor(false), hasStaticInitializers(false), hasVirtualTable(false), isAbstract(false), isExport(false), isImport(false), - isPublic(false), isDynamicImport(false), hasRTTI(false), isCppVTable(false), isFinal(false), + isPublic(false), isDynamicImport(false), hasRTTI(false), isCppVTable(false), isFinal(false), isValue(false), processingAtEvaluation(ProcessingStages::NotSet), processing(ProcessingStages::NotSet) { } diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h b/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h index 679a0878e..d75c57036 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRPrinter.h @@ -411,6 +411,10 @@ class MLIRPrinter .template Case([&](auto t) { out << t.getName().getValue().str().c_str(); }) + // a @value class or interface is named as it was declared + .template Case([&](auto t) { + out << t.getName().getValue().str().c_str(); + }) .template Case([&](auto t) { printType(out, t.getElementType()); out << "[]"; diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h index cb8909b81..37a5963fb 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeHelper.h @@ -203,9 +203,114 @@ class MLIRTypeHelper } #endif + // A @value type (ValueType) is laid out as its storage tuple: a walker that looks at the fields + // of a value - their types, sizes, what they own - sees the tuple. Anything else is unchanged. + // Sites that box or re-represent a tuple do not call this: a ValueType reaches them only as the + // tuple it is cast to (MLIRGenImpl::valueStorage), where a conversion of it is allowed. + static mlir::Type stripValueType(mlir::Type type) + { + if (auto valueType = dyn_cast_or_null(type)) + { + return valueType.getStorageType(); + } + + return type; + } + + // `this` of a @value class's constructor captured by a closure: a `ref` to the class's value named + // `this`. Its storage is the slot `new` made in the caller's frame, not a cell, so a capture box + // borrows it: nothing counts it in or out (MLIRGenImpl::mlirGenResolveCapturedVars, + // OwnershipRoutineLogic::releaseCapturedFields), and a closure holding it may only be called + // inside the constructor (MLIRGenImpl::checkValueConstructorClosures). + static bool isValueConstructorThisCapture(mlir::Attribute name, mlir::Type type) + { + auto nameAttr = dyn_cast_or_null(name); + auto refType = dyn_cast_or_null(type); + return nameAttr && nameAttr.getValue() == THIS_NAME && refType && isa(refType.getElementType()); + } + + // A @value type has no null pointer. Each way of writing that one may be missing - `T | null`, + // `T | undefined`, `T | null | undefined`, `v?: T`, `f?: T` - is this one type, an optional of + // `T | null`: undefined is the empty optional, null the union's null member, a value otherwise. + // So converting between the spellings changes nothing, and null stays apart from undefined. + // The union's members are ordered as normalizeUnionType orders them. + static mlir::Type getMissingValueType(mlir_ts::ValueType valueType) + { + mlir::SmallVector members{valueType, mlir_ts::NullType::get(valueType.getContext())}; + std::sort(members.begin(), members.end(), [](auto i, auto j) { return i.getAsOpaquePointer() < j.getAsOpaquePointer(); }); + return mlir_ts::OptionalType::get(mlir_ts::UnionType::get(valueType.getContext(), members)); + } + + // `T | null` of a @value type T, which getMissingValueType wraps in the optional + static bool isMissingValueUnion(mlir_ts::UnionType unionType) + { + auto types = unionType.getTypes(); + return types.size() == 2 && llvm::any_of(types, [](mlir::Type type) { return isa(type); }) + && llvm::any_of(types, [](mlir::Type type) { return isa(type); }); + } + + // The @value type a value that may be missing holds when it holds one: of getMissingValueType, or + // of its `T | null` alone (what is left of it once undefined is ruled out) + static mlir_ts::ValueType getMissingValueElement(mlir::Type type) + { + if (auto optType = dyn_cast_or_null(type)) + { + type = optType.getElementType(); + } + + auto unionType = dyn_cast_or_null(type); + if (!unionType || !isMissingValueUnion(unionType)) + { + return mlir_ts::ValueType(); + } + + for (auto member : unionType.getTypes()) + { + if (auto valueType = dyn_cast(member)) + { + return valueType; + } + } + + return mlir_ts::ValueType(); + } + + // A plain `f: T` field (of a class or a literal) where an interface's optional member of the @value + // type T is: the member is read as the optional value a `f?: T` field stores (getMissingValueType), + // and a T is not laid out as one, so it cannot stand in for it + static mlir_ts::ValueType getPlainValueForOptionalMember(mlir::Type memberType, mlir::Type fieldType) + { + auto valueType = isa_and_nonnull(memberType) ? getMissingValueElement(memberType) : mlir_ts::ValueType(); + return valueType && fieldType == valueType ? valueType : mlir_ts::ValueType(); + } + + static void emitPlainValueForOptionalMemberError(mlir::Location location, mlir::Attribute id, mlir_ts::ValueType valueType, + StringRef interfaceName) + { + auto name = isa(id) ? mlir::cast(id).getValue() : StringRef(); + emitError(location) << "field '" << name << "' must be declared '" << name << "?: " << valueType.getName().getValue() + << "' to implement the optional @" VALUE_DECORATOR " member '" << name << "' of '" << interfaceName << "'"; + } + + // A @value type, or one that may be missing (getMissingValueType) + static bool holdsValueType(mlir::Type type) + { + if (auto optType = dyn_cast_or_null(type)) + { + type = optType.getElementType(); + } + + if (auto unionType = dyn_cast_or_null(type)) + { + return llvm::any_of(unionType.getTypes(), [](mlir::Type member) { return isa(member); }); + } + + return isa_and_nonnull(type); + } + bool isValueType(mlir::Type typeIn) { - auto type = getBaseType(typeIn); + auto type = stripValueType(getBaseType(typeIn)); return type && (type.isIntOrIndexOrFloat() || isa(type) || isa(type) || isa(type) || isa(type) || isa(type) || isa(type)); } @@ -438,8 +543,9 @@ class MLIRTypeHelper // A tuple literal folded to a constant (`[1, [6, 7]]`, `{ items: [1, 2] }`) keeps each array // in it as a static header over constant data (#479): such a tuple has to be rebuilt with // heap copies before anything can change one of its arrays. - static bool constTupleHoldsArray(mlir::Type type) + static bool constTupleHoldsArray(mlir::Type typeIn) { + auto type = stripValueType(typeIn); ArrayRef fields; if (auto constTupleType = dyn_cast(type)) { @@ -1480,6 +1586,12 @@ class MLIRTypeHelper if (!suppressErrors) { + if (auto valueType = getPlainValueForOptionalMember(fieldType, stripLiteralType(foundField.type))) + { + emitPlainValueForOptionalMemberError(location, id, valueType, newInterfacePtr->fullName); + return {emptyFieldInfo, mlir::failure()}; + } + emitError(location) << "field " << id << " not matching type: " << fieldType << " and " << foundField.type << " in interface '" << newInterfacePtr->fullName << "' for object '" << to_print(tupleStorageType) << "'"; @@ -1591,6 +1703,12 @@ class MLIRTypeHelper return true; } + // a @value interface is structural: it converts as its fields do + if (isa(srcType) || isa(destType)) + { + return canCastFromTo(location, stripValueType(srcType), stripValueType(destType)); + } + if (auto constTuple = dyn_cast(srcType)) { if (auto matchConstTuple = dyn_cast(destType)) @@ -1694,8 +1812,9 @@ class MLIRTypeHelper return llvm::any_of(type.getFields(), [&](::mlir::typescript::FieldInfo fi) { return testType(fi.type); }); } - bool hasUndefines(mlir::Type type) + bool hasUndefines(mlir::Type typeIn) { + auto type = stripValueType(typeIn); if (auto constTuple = dyn_cast(type)) { return hasUndefinesLogic(constTuple); @@ -1724,8 +1843,9 @@ class MLIRTypeHelper // class/array/object types, is NOT already pointer-like at the LLVM level -- // so a binding of this type needs real storage (an address) to let mutation // be visible across property accesses / call sites, even when declared `const`. - bool hasBoundMethodField(mlir::Type type) + bool hasBoundMethodField(mlir::Type typeIn) { + auto type = stripValueType(typeIn); if (auto constTuple = dyn_cast(type)) { return hasBoundMethodFieldLogic(constTuple); @@ -2124,13 +2244,15 @@ class MLIRTypeHelper return false; } - bool isSizeEqual(mlir::Type srcType, mlir::Type dstType) + bool isSizeEqual(mlir::Type srcTypeIn, mlir::Type dstTypeIn) { - if (!srcType || !dstType) + if (!srcTypeIn || !dstTypeIn) { return false; } + auto srcType = stripValueType(srcTypeIn); + auto dstType = stripValueType(dstTypeIn); if (srcType == dstType) { return true; @@ -2268,9 +2390,10 @@ class MLIRTypeHelper } // Field types of a record-shaped type, empty for anything else. - llvm::SmallVector getOwnershipFieldTypes(mlir::Type type) + llvm::SmallVector getOwnershipFieldTypes(mlir::Type typeIn) { llvm::SmallVector result; + auto type = stripValueType(typeIn); auto addFields = [&](auto fields) { for (auto &field : fields) @@ -2297,6 +2420,14 @@ class MLIRTypeHelper bool isUnionTypeNeedsTag(mlir::Location location, mlir_ts::UnionType unionType, mlir::Type &baseType) { + // `T | null` of a @value type is a tagged union of its own (getMissingValueType): its members + // merged again would be the optional around it, not it + if (isMissingValueUnion(unionType)) + { + baseType = unionType; + return true; + } + auto storeType = getUnionTypeWithMerge(location, unionType.getTypes(), true, true, true); baseType = storeType; return isa(storeType); @@ -2447,13 +2578,15 @@ class MLIRTypeHelper return mlir_ts::NeverType::get(context); } - mlir::LogicalResult getFields(mlir::Type srcType, llvm::SmallVector &destTupleFields, bool noError = false) + mlir::LogicalResult getFields(mlir::Type srcTypeIn, llvm::SmallVector &destTupleFields, bool noError = false) { - if (!srcType) + if (!srcTypeIn) { return mlir::failure(); } + auto srcType = stripValueType(srcTypeIn); + if (auto constTupleType = dyn_cast(srcType)) { for (auto &fieldInfo : constTupleType.getFields()) @@ -2560,8 +2693,9 @@ class MLIRTypeHelper return mlir::success(); } - int getFieldIndexByFieldName(mlir::Type srcType, mlir::Attribute fieldName) + int getFieldIndexByFieldName(mlir::Type srcTypeIn, mlir::Attribute fieldName) { + auto srcType = stripValueType(srcTypeIn); LLVM_DEBUG(llvm::dbgs() << "!! get index of field '" << fieldName << "' of '" << srcType << "'\n";); if (auto constTupleType = dyn_cast(srcType)) @@ -2577,8 +2711,9 @@ class MLIRTypeHelper return -1; } - mlir::typescript::FieldInfo getFieldInfoByIndex(mlir::Type srcType, int index) + mlir::typescript::FieldInfo getFieldInfoByIndex(mlir::Type srcTypeIn, int index) { + auto srcType = stripValueType(srcTypeIn); LLVM_DEBUG(llvm::dbgs() << "!! get #" << index << " of '" << srcType << "'\n";); if (auto constTupleType = dyn_cast(srcType)) @@ -2598,7 +2733,7 @@ class MLIRTypeHelper { LLVM_DEBUG(llvm::dbgs() << "!! get type of field '" << fieldName << "' of '" << srcType << "'\n";); - srcType = stripLiteralType(srcType); + srcType = stripValueType(stripLiteralType(srcType)); if (auto constTupleType = dyn_cast(srcType)) { @@ -2883,6 +3018,13 @@ class MLIRTypeHelper return appendInferTypeToContext(location, srcType, inferType, typeParamsWithArgs, useTupleWhenMergeTypes); } + // a @value interface is structural: it extends what a type literal of its fields does + if (isa_and_nonnull(srcType) || isa(extendType)) + { + return extendsType(location, stripValueType(srcType), stripValueType(extendType), typeParamsWithArgs, + useTupleWhenMergeTypes); + } + if (auto anyType = dyn_cast_or_null(srcType)) { SmallVector inferTypes; @@ -3449,7 +3591,9 @@ class MLIRTypeHelper for (auto type : unionContext.types) { typesAll.push_back(type); - isAllValueTypes &= isValueType(type); + // a @value type with null is not a union with a null member: how it is stored is its own + // (`T | null`, docs/superpowers/specs/2026-10-24-value-types-design.md "Missing values") + isAllValueTypes &= isValueType(type) && !isa(type); isAllLiteralTypes &= isa(type); } @@ -3463,6 +3607,13 @@ class MLIRTypeHelper { auto resType = typesAll.front(); + // a @value type that may be missing, under strict null checks or not + // (docs/superpowers/specs/2026-10-24-value-types-design.md "Missing values") + if (auto valueType = dyn_cast(resType); valueType && (unionContext.isNullable || unionContext.isUndefined)) + { + return getMissingValueType(valueType); + } + // the null the checker needs goes in before undefined wraps the type: undefined makes it // optional, it must not take the null away - `string | null | undefined` accepts null as // `string | null` does @@ -3623,7 +3774,13 @@ class MLIRTypeHelper if (normalizedTypes.size() == 1) { - return isUndefined ? mlir_ts::OptionalType::get(*normalizedTypes.begin()) : *normalizedTypes.begin(); + auto single = *normalizedTypes.begin(); + if (auto valueType = dyn_cast(single); valueType && isUndefined) + { + return getMissingValueType(valueType); + } + + return isUndefined ? mlir_ts::OptionalType::get(single) : single; } mlir::SmallVector newTypes; @@ -3998,6 +4155,12 @@ class MLIRTypeHelper if (auto unionType = dyn_cast(type)) { + // `T | null` of a @value type holds T or nothing: it owns what T owns + if (isMissingValueUnion(unionType)) + { + return llvm::any_of(unionType.getTypes(), [&](mlir::Type member) { return ownsHeapMemory(location, member, visiting); }); + } + mlir::Type baseType; if (isUnionTypeNeedsTag(location, unionType, baseType)) { diff --git a/tslang/include/TypeScript/MLIRLogic/MLIRTypeIterator.h b/tslang/include/TypeScript/MLIRLogic/MLIRTypeIterator.h index b90afa03a..01d0b39a1 100644 --- a/tslang/include/TypeScript/MLIRLogic/MLIRTypeIterator.h +++ b/tslang/include/TypeScript/MLIRLogic/MLIRTypeIterator.h @@ -255,6 +255,12 @@ class MLIRTypeIterator return true; }) + // a @value value is its storage tuple + .Case([&](auto t) { + if (!iterate(t.getStorageType())) + return false; + return true; + }) .Case([&](auto t) { for (auto subType : t.getTypes()) { diff --git a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h index c93cf40b5..b46f3b6f9 100644 --- a/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h +++ b/tslang/include/TypeScript/MLIRLogic/TypeOfOpHelper.h @@ -215,6 +215,12 @@ class TypeOfOpHelper return "unknown"; } + // a @value class or interface is an object to the program, as in TypeScript + if (isa(type)) + { + return "object"; + } + if (isa(type)) { return "tuple"; diff --git a/tslang/include/TypeScript/TypeScriptTypes.td b/tslang/include/TypeScript/TypeScriptTypes.td index 43e17985e..36e3c0b8f 100644 --- a/tslang/include/TypeScript/TypeScriptTypes.td +++ b/tslang/include/TypeScript/TypeScriptTypes.td @@ -681,6 +681,38 @@ def TypeScript_Class : TypeScript_Type<"Class"> { ]; } +def TypeScript_Value : TypeScript_Type<"Value"> { + let mnemonic = "value"; + + let summary = "A @value class or interface: a struct of its readonly fields, copied, never shared"; + let description = [{ + Syntax: + + ``` + value-type ::= `value<` symbol-ref-id `,` tuple-type `>` + ``` + + The declaration's name and its fields as a tuple in declaration order. A value of this type is + laid out as the tuple; `ts.Cast` between the two, either way, lowers to nothing. The name is + what keeps it apart from a plain tuple or type literal of the same fields. + + Examples: + + ```mlir + !ts.value<@Ray, !ts.tuple<{"start",!ts.number},{"dir",!ts.number}>> + ``` + }]; + let parameters = (ins "FlatSymbolRefAttr":$name, "Type":$storageType); + + let assemblyFormat = "`<` params `>`"; + + let builders = [ + TypeBuilderWithInferredContext<(ins "FlatSymbolRefAttr":$name, "Type":$storageType), [{ + return Base::get(storageType.getContext(), name, storageType); + }]> + ]; +} + def TypeScript_Namespace : TypeScript_Type<"Namespace"> { let mnemonic = "namespace"; diff --git a/tslang/lib/TypeScript/DeclarationPrinter.cpp b/tslang/lib/TypeScript/DeclarationPrinter.cpp index 57d435cc9..9f25ef38e 100644 --- a/tslang/lib/TypeScript/DeclarationPrinter.cpp +++ b/tslang/lib/TypeScript/DeclarationPrinter.cpp @@ -492,6 +492,13 @@ namespace typescript newline(); } + // an importer copies the values of a @value class, and may not extend it + if (classType->isValue) + { + os << "@" VALUE_DECORATOR; + newline(); + } + // `abstract` is layout-relevant, not just semantic: mlirGenClassNew skips // synthesizing the `.new` method for abstract classes, so dropping the // modifier makes the reimporting module insert a `.new` vtable slot the @@ -599,6 +606,11 @@ namespace typescript os << "private "; } + // every field of a @value class is readonly (a parameter property is one of them), and the + // importer checks it again + if (classType->isValue) + os << "readonly "; + printAsFieldName(field.id); if (field.isConditional) os << "?"; @@ -608,6 +620,17 @@ namespace typescript newline(); } + // `this` of an instance method of a @value class is the value (the slot `new` made, in the + // constructor), not the class: it is the first parameter, which the importer adds again + auto thisTypeOf = [&](bool isStatic, ArrayRef params) -> mlir::Type { + if (classType->isValue && !isStatic && !params.empty()) + { + return params.front(); + } + + return classType->classType; + }; + // index signature ([x: T]: U;) - not stored in storageType's fields, // and (unlike accessors) its get/set methods are ordinary named // "get"/"set" methods already covered by the methods loop below; only @@ -628,7 +651,7 @@ namespace typescript accessor.isStatic, "get", accessor.name, accessor.getAccessLevel, accessor.get.funcType.getParams(), accessor.get.funcType.getNumResults() > 0 ? accessor.get.funcType.getResult(0) : mlir::Type(), - classType->classType, + thisTypeOf(accessor.isStatic, accessor.get.funcType.getParams()), accessor.get.dllName); }; @@ -637,7 +660,7 @@ namespace typescript accessor.isStatic, "set", accessor.name, accessor.setAccessLevel, accessor.set.funcType.getParams(), mlir::Type(), - classType->classType, + thisTypeOf(accessor.isStatic, accessor.set.funcType.getParams()), accessor.set.dllName); }; @@ -754,7 +777,7 @@ namespace typescript StringRef(method.name).split(CPP_OVERLOAD_SEPARATOR).first, funcType.getParams(), funcType.getNumResults() > 0 ? funcType.getResult(0) : mlir::Type(), - classType->classType); + thisTypeOf(method.isStatic, funcType.getParams())); newline(); } @@ -818,6 +841,13 @@ namespace typescript printNamespaceBegin(interfaceType->elementNamespace); printBeforeDeclaration(); + // an importer copies the values of a @value interface, and has no vtable to see them by + if (interfaceType->isValue) + { + os << "@" VALUE_DECORATOR; + newline(); + } + os << "interface " << interfaceType->name; if (interfaceType->extends.size() > 0) @@ -847,6 +877,9 @@ namespace typescript continue; os.indent(4); + // every field of a @value interface is readonly, and the importer checks it again + if (interfaceType->isValue) + os << "readonly "; printAsFieldName(field.id); if (field.isConditional) os << "?"; diff --git a/tslang/lib/TypeScript/LowerToLLVM.cpp b/tslang/lib/TypeScript/LowerToLLVM.cpp index c62d8fc07..092fef088 100644 --- a/tslang/lib/TypeScript/LowerToLLVM.cpp +++ b/tslang/lib/TypeScript/LowerToLLVM.cpp @@ -4823,6 +4823,13 @@ struct LoadOpLowering : public TsLlvmPattern isOptional = optType.getElementType() == elementType; } + // an interface's `f?: T` of a @value type is read as the optional it is stored as + // (MLIRTypeHelper::getMissingValueType); a member the object lacks has no address, and reads + // as undefined + auto interfaceSymbolRefOp = loadOp.getReference().getDefiningOp(); + auto isMissingValueMember = resultType == elementType && MLIRTypeHelper::getMissingValueElement(resultType) + && interfaceSymbolRefOp && interfaceSymbolRefOp.getOptional().value_or(false); + mlir::Value loadedValue; auto loadedValueFunc = [&](OpBuilder &builder, Location location) -> mlir::Value { mlir::Value loadedValue; @@ -4909,7 +4916,7 @@ struct LoadOpLowering : public TsLlvmPattern return loadedValue; }; - if (isOptional) + if (isOptional || isMissingValueMember) { auto resultTypeLlvm = tch.convertType(resultType); @@ -4921,6 +4928,11 @@ struct LoadOpLowering : public TsLlvmPattern auto createOptionalFunc = [&](OpBuilder &builder, Location location) -> mlir::Value { auto dataValue = loadedValueFunc(builder, location); + if (isMissingValueMember) + { + return dataValue; + } + mlir::Value val = rewriter.create(loc, resultType, dataValue); mlir::Value valAsLLVMType = builder.create(loc, resultTypeLlvm, val); return valAsLLVMType; @@ -5208,7 +5220,7 @@ struct GlobalOpLowering : public TsLlvmPattern inType = literalType.getElementType(); } - if (isa(castType) || isa(castType)) + if (isa(castType) || isa(MLIRTypeHelper::stripValueType(castType))) { createAsGlobalConstructor = true; } @@ -8180,6 +8192,11 @@ static void populateTypeScriptConversionPatterns(LLVMTypeConverter &converter, m return LLVM::LLVMStructType::getLiteral(type.getContext(), convertedTypes, TUPLE_TYPE_PACKED); }); + // a @value class or interface is laid out as its storage tuple + converter.addConversion([&](mlir_ts::ValueType type) { + return converter.convertType(type.getStorageType()); + }); + converter.addConversion([&](mlir_ts::BoundRefType type) { SmallVector llvmStructType; llvmStructType.push_back(LLVM::LLVMPointerType::get(m.getContext())); diff --git a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp index ce1460f38..2cbae5c0d 100644 --- a/tslang/lib/TypeScript/MLIRGenAccessCall.cpp +++ b/tslang/lib/TypeScript/MLIRGenAccessCall.cpp @@ -121,7 +121,7 @@ namespace mlirgen } auto optValue = isa(value.getType()) - ? value : builder.create(location, getOptionalType(value.getType()), value); + ? value : mlirGenOptionalValueOf(location, value); builder.create(location, mlir::ValueRange{optValue}); // else @@ -205,7 +205,25 @@ namespace mlirgen .Case([&](auto enumType) { return cl.Enum(enumType); }) .Case([&](auto constTupleType) { return cl.Tuple(constTupleType); }) .Case([&](auto tupleType) { return cl.Tuple(tupleType); }) - .Case([&](auto stringType) { + // a field of a @value value is a field of its storage tuple + .Case([&](auto valueType) { + cl.setExpression(valueStorage(location, objectValue)); + auto storageType = mlir::cast(valueType.getStorageType()); + // ...and anything else of a @value class's value is a member of the class + if (auto classInfo = getValueClassInfo(valueType)) + { + auto accessingFromLevel = detectAccessLevel(classInfo->classType, genContext); + if (auto value = cl.TupleNoError(storageType, accessingFromLevel)) + { + return value; + } + + return ValueClassMembersAccess(location, objectValue, classInfo, name, accessingFromLevel, genContext); + } + + return cl.Tuple(storageType); + }) + .Case([&](auto stringType) { if (auto value = cl.String(stringType)) { return value; @@ -368,13 +386,36 @@ namespace mlirgen location, objectValue, interfaceType.getName().getValue(), cl.getAttribute(), argument, genContext); }) - .Case([&](auto optionalType) { + .Case([&](auto optionalType) -> mlir::Value { + // a member of a missing @value value throws + if (MLIRTypeHelper::getMissingValueElement(optionalType)) + { + auto present = mlirGenPresentValue(location, objectValue, genContext); + if (present.failed_or_no_value()) + { + return mlir::Value(); + } + + return mlirGenPropertyAccessExpression(location, V(present), name, false, genContext); + } + // this is needed for conditional access to properties auto elementType = optionalType.getElementType(); auto loadedValue = builder.create(location, elementType, objectValue); return mlirGenPropertyAccessExpression(location, loadedValue, name, false, genContext); }) - .Case([&](auto unionType) { + .Case([&](auto unionType) -> mlir::Value { + if (MLIRTypeHelper::getMissingValueElement(unionType)) + { + auto present = mlirGenPresentValue(location, objectValue, genContext); + if (present.failed_or_no_value()) + { + return mlir::Value(); + } + + return mlirGenPropertyAccessExpression(location, V(present), name, false, genContext); + } + // TODO: when access of property in union is finished use it instead of using first type // all union types must have the same property // 1) cast to first type @@ -1072,6 +1113,83 @@ namespace mlirgen return mlir::Value(); } + // A member of a @value class's value that is not one of its fields: an instance method, called + // directly with the value as its `this` (an extension function of it: no vtable, nothing bound), + // or a getter, called the same way. Anything else is looked up as for any class, which says what + // it can't find. + mlir::Value MLIRGenImpl::ValueClassMembersAccess(mlir::Location location, mlir::Value thisValue, ClassInfo::TypePtr classInfo, + mlir::StringRef name, mlir_ts::AccessLevel accessingFromLevel, + const GenContext &genContext) + { + auto methodIndex = classInfo->getMethodIndex(name); + if (methodIndex >= 0 && !classInfo->methods[methodIndex].isStatic) + { + auto &methodInfo = classInfo->methods[methodIndex]; + if (accessingFromLevel < methodInfo.accessLevel) + { + emitError(location, "Class member '") << methodInfo.name << "' is not accessable"; + return mlir::Value(); + } + + auto funcRef = valueClassFunctionRef(location, classInfo, methodInfo, genContext); + if (!funcRef) + { + return mlir::Value(); + } + + return builder.create( + location, getExtensionFunctionType(methodInfo.funcType), thisValue, funcRef); + } + + auto accessorIndex = classInfo->getAccessorIndex(name); + if (accessorIndex >= 0 && !classInfo->accessors[accessorIndex].isStatic) + { + return ClassAccessorAccess(classInfo, location, thisValue, accessorIndex, false, accessingFromLevel, genContext, + /*finalReceiver=*/true); + } + + return ClassMembersAccess(location, thisValue, classInfo, name, false, mlir::Value(), accessingFromLevel, genContext); + } + + // The function of a method or the constructor of a @value class, to call directly: its symbol, or, + // for a class imported from a DLL loaded at run time, the address the DLL has for it (as + // ClassMethodAccess resolves a dynamic import's member). + mlir::Value MLIRGenImpl::valueClassFunctionRef(mlir::Location location, ClassInfo::TypePtr classInfo, + const MethodInfo &methodInfo, const GenContext &genContext) + { + StringRef funcName = methodInfo.funcName; + auto symbolRef = [&]() -> mlir::Value { + return builder.create(location, methodInfo.funcType, + mlir::FlatSymbolRefAttr::get(builder.getContext(), funcName)); + }; + + if (!classInfo->isDynamicImport) + { + return symbolRef(); + } + + if (auto funcOp = theModule.lookupSymbol(funcName); funcOp && !funcOp.getBody().empty()) + { + return symbolRef(); + } + + if (auto globalFuncVar = resolveFullNameIdentifier(location, funcName, false, genContext)) + { + return globalFuncVar; + } + + auto symbolNameValue = V(mlirGenStringValue(location, methodInfo.dllName.empty() ? funcName.str() : methodInfo.dllName, true)); + auto referenceToFuncOpaque = builder.create(location, getOpaqueType(), symbolNameValue); + auto castResult = cast(location, methodInfo.funcType, referenceToFuncOpaque, genContext); + if (castResult.failed_or_no_value()) + { + emitError(location, "Class member '") << funcName << "' can't be resolved (dynamic import)"; + return mlir::Value(); + } + + return V(castResult); + } + mlir::Value MLIRGenImpl::InterfaceMembers(mlir::Location location, mlir::Value interfaceValue, mlir::StringRef interfaceFullName, mlir::Attribute id, mlir::Value argument, const GenContext &genContext) { @@ -1202,6 +1320,12 @@ namespace mlirgen { return mlirGenElementAccessTuple(location, expression, argumentExpression, tupleType); } + // `v["f"]` of a @value value is a field of its storage tuple + else if (auto valueType = dyn_cast(arrayType)) + { + return mlirGenElementAccessTuple(location, valueStorage(location, expression), argumentExpression, + mlir::cast(valueType.getStorageType())); + } else if (auto constTupleType = dyn_cast(arrayType)) { return mlirGenElementAccessTuple(location, expression, argumentExpression, constTupleType); @@ -1714,7 +1838,7 @@ namespace mlirgen if (value) { auto optValue = - builder.create(location, getOptionalType(value.getType()), value); + mlirGenOptionalValueOf(location, value); builder.create(location, mlir::ValueRange{optValue}); // else @@ -2082,6 +2206,11 @@ namespace mlirgen // `C(...)` and `new C(...)` are one thing: where the object lives is the stack promotion // pass's decision, not the spelling's (docs/superpowers/specs/2026-10-18-stack-promotion-design.md) auto classInfo = getClassInfoByFullName(classType.getName().getValue()); + if (classInfo && classInfo->isValue) + { + return NewValueClassInstance(location, classInfo, operands, genContext); + } + auto newOp = ValueOrLogicalResult(NewClassInstanceAsMethodCallOp(location, classInfo, true, genContext)); EXIT_IF_FAILED_OR_NO_VALUE(newOp) if (mlir::failed(mlirGenCallConstructor(location, classInfo, V(newOp), operands, false, genContext))) @@ -2092,6 +2221,94 @@ namespace mlirgen return V(newOp); } + // `new V(...)` of a @value class: a stack slot for its storage tuple, the constructor run with + // `this` pointing at the slot, and the value loaded from it. Nothing is allocated, and nothing + // keeps the slot: what `new` gives is a copy. + ValueOrLogicalResult MLIRGenImpl::NewValueClassInstance(mlir::Location location, ClassInfo::TypePtr classInfo, + NodeArray arguments, const GenContext &genContext) + { + auto constructorIndex = classInfo->getMethodIndex(CONSTRUCTOR_NAME); + if (genContext.dummyRun || constructorIndex < 0) + { + // discovery (or a constructor not declared yet): the arguments are walked for what they + // capture, as NewClassInstance does, and the value is all the type that is wanted + for (auto argument : arguments) + { + mlirGen(argument, genContext); + } + + SmallVector noOperands; + return NewValueClassInstance(location, classInfo, noOperands, genContext); + } + + auto funcType = classInfo->methods[constructorIndex].funcType; + SmallVector operands; + if (mlir::failed(mlirGenOperands(arguments, operands, funcType, genContext, 1/*this params shift*/))) + { + emitError(location) << "Call constructor: can't resolve values of all parameters"; + return mlir::failure(); + } + + return NewValueClassInstance(location, classInfo, operands, genContext); + } + + ValueOrLogicalResult MLIRGenImpl::NewValueClassInstance(mlir::Location location, ClassInfo::TypePtr classInfo, + SmallVector &operands, const GenContext &genContext) + { + auto valueType = getValueTypeOfClass(classInfo); + auto storageType = valueType.getStorageType(); + + // zeroed, as a new object is: a field the constructor does not set reads as nothing, and a + // store into one has no old value to give back + auto zero = builder.create(location, valueType, builder.create(location, storageType)); + auto slot = builder.create(location, mlir_ts::RefType::get(valueType), zero, + builder.getBoolAttr(false), builder.getIndexAttr(0)); + + // discovery wants the type only; the value is still a load, not a constant: a static field + // initialized with `new V()` is set by the static constructor, not folded (isConstValue) + if (!genContext.dummyRun && classInfo->getHasConstructor()) + { + auto constructorIndex = classInfo->getMethodIndex(CONSTRUCTOR_NAME); + if (constructorIndex < 0) + { + if (!genContext.allowPartialResolve) + { + emitError(location) << "Call Constructor: can't find constructor"; + } + + return mlir::failure(); + } + + auto &constructorInfo = classInfo->methods[constructorIndex]; + if (detectAccessLevel(classInfo->classType, genContext) < classInfo->constructorAccessLevel) + { + emitError(location, "Class constructor is not accessable"); + return mlir::failure(); + } + + auto constructorRef = valueClassFunctionRef(location, classInfo, constructorInfo, genContext); + if (!constructorRef) + { + return mlir::failure(); + } + + auto callResult = mlirGenCallFunction(location, constructorInfo.funcType, constructorRef, slot, operands, genContext); + EXIT_IF_FAILED(callResult) + } + + // The constructor stored into the slot's fields as into an owned local's + // (isValueConstructorSlot): a reference in one is counted for the slot, and the slot is left + // behind. The value arrives owned, as a new instance does: its receiver takes those counts + // over, and where nothing does they are given back at the end of the block (§9.30). + auto value = builder.create(location, valueType, slot); + if (mth.ownsHeapMemory(location, valueType)) + { + value->setAttr(OWNED_RESULT_ATTR_NAME, builder.getUnitAttr()); + } + + return V(value); + } + ValueOrLogicalResult MLIRGenImpl::mlirGenCall(mlir::Location location, mlir::Value funcRefValue, SmallVector &operands, const GenContext &genContext) { @@ -2385,7 +2602,8 @@ namespace mlirgen assert(type); auto resultType = type; - if (mth.isValueType(type)) + // a tuple made by `new` is boxed on the heap; a @value value never is + if (mth.isValueType(type) && !isa(type)) { resultType = getValueRefType(type); } @@ -2409,7 +2627,13 @@ namespace mlirgen } emitError(location) << "Can't find class " << to_print(classType); - return mlir::failure(); + return mlir::failure(); + } + + // a @value class: a value made on the stack, never a heap object (no `..new` either) + if (classInfo->isValue) + { + return NewValueClassInstance(location, classInfo, arguments, genContext); } if (genContext.dummyRun) diff --git a/tslang/lib/TypeScript/MLIRGenCast.cpp b/tslang/lib/TypeScript/MLIRGenCast.cpp index 1f7c396eb..16e63f266 100644 --- a/tslang/lib/TypeScript/MLIRGenCast.cpp +++ b/tslang/lib/TypeScript/MLIRGenCast.cpp @@ -705,6 +705,86 @@ namespace mlirgen LLVM_DEBUG(llvm::dbgs() << "\n!! cast " << valueType << "\n -> " << type << "\n";); + // A @value class is nominal. Its value seen as `any`, `unknown`, `Object` or an ordinary + // interface would be a boxed copy that has lost its class (no vtable to call its methods by); + // seen as another @value type, a value of a class it is not. With null or undefined it is + // itself (`V | null`), and so in a union of @value types. + if (auto valueClassInfo = getValueClassInfo(valueType)) + { + auto isValueMember = [](mlir::Type memberType) { + return isa(memberType); + }; + + auto unionType = dyn_cast(type); + if (isa(type) + || (unionType && !llvm::all_of(unionType.getTypes(), isValueMember))) + { + emitError(location) << "the @" VALUE_DECORATOR " class '" << valueClassInfo->name << "' cannot be converted to '" + << to_print(type) << "'"; + return mlir::failure(); + } + } + + // ...and only its own values are values of it: a literal, a tuple, a @value interface value or + // an object of the same fields is not one (its constructor never ran). With null or undefined + // it is `V | null` (the cases below). + if (auto destClassInfo = getValueClassInfo(type); + destClassInfo && !isa(valueType)) + { + // Discovery sees results not resolved yet - a method calling one declared after it gives + // `void` - and keeps going, as it does for any other cast it cannot make yet. Its IR is + // thrown away; the final pass checks the real conversion. + if (genContext.dummyRun || genContext.allowPartialResolve) + { + return V(builder.create(location, type, value)); + } + + emitError(location) << "type '" << to_print(valueType) << "' cannot be converted to the @" VALUE_DECORATOR " class '" + << destClassInfo->name << "'"; + return mlir::failure(); + } + + // A @value type is laid out as its storage tuple. Converting to one is converting to that + // tuple - a field copy in the target's order - and taking the tuple as the value; converting + // from one is converting its tuple, which boxes a copy for `any`, `Object` or an ordinary + // interface. So a @value value never reaches the tuple paths below as itself. With null, + // undefined, an optional or a union on either side it is the cases below (`T | null`). + if (auto destValueType = dyn_cast(type)) + { + // ...and it has no null pointer: a missing value is written `T | null` (an optional + // value), even where null checks are not strict + if (isa(valueType)) + { + emitError(location) << "a @" VALUE_DECORATOR " type has no null; write '" << to_print(type) << " | null'"; + return mlir::failure(); + } + + // one that may be missing is read as the value it holds, and throws when it holds none + // (under `@strict-null false`, where TypeScript would throw only at a later read) + if (MLIRTypeHelper::getMissingValueElement(valueType)) + { + auto present = mlirGenPresentValue(location, value, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(present) + return cast(location, type, V(present), genContext, disableStrictNullCheck); + } + + if (!isa(valueType)) + { + CAST_A(storage, location, destValueType.getStorageType(), valueStorage(location, value), genContext); + return V(builder.create(location, destValueType, storage)); + } + } + else if (isa(valueType) && !isa(type)) + { + return cast(location, type, valueStorage(location, value), genContext, disableStrictNullCheck); + } + // one that may be missing is true when it holds a value, as an object is + else if (isa(type) && MLIRTypeHelper::getMissingValueElement(valueType)) + { + auto nullValue = builder.create(location, getNullType()); + return mlirGenBinaryValues(location, SyntaxKind::ExclamationEqualsToken, value, nullValue, genContext); + } + // see isCppVTableClass: `any` is unboxed and an interface made by asking the object if ((isa(valueType) && isCppVTableClass(type)) || ((isa(type) || isa(type)) && isCppVTableClass(valueType))) diff --git a/tslang/lib/TypeScript/MLIRGenClasses.cpp b/tslang/lib/TypeScript/MLIRGenClasses.cpp index b3358ea4f..d0cd32fc2 100644 --- a/tslang/lib/TypeScript/MLIRGenClasses.cpp +++ b/tslang/lib/TypeScript/MLIRGenClasses.cpp @@ -84,6 +84,19 @@ namespace mlirgen auto isGenericClass = classDeclarationAST->typeParameters.size() > 0; if (isGenericClass && genContext.typeParamsWithArgs.size() == 0) { + // a value is one layout: each instantiation would be another type to copy + auto isValueClass = false; + iterateDecorators(classDeclarationAST, genContext, [&](StringRef name, SmallVector args) { + isValueClass = isValueClass || name == VALUE_DECORATOR; + }); + if (isValueClass) + { + emitError(loc(classDeclarationAST)) << "@" VALUE_DECORATOR " class '" + << MLIRHelper::getName(classDeclarationAST->name) + << "' cannot have type parameters"; + return {mlir::failure(), ""}; + } + return {registerGenericClass(classDeclarationAST, genContext), ""}; } @@ -103,6 +116,16 @@ namespace mlirgen return {mlir::failure(), ""}; } + // a value has no vtable, so it cannot be abstract, a C++ binding or @final (nothing extends + // a value: saying so twice would suggest it could be) + if (newClassPtr->isValue && (newClassPtr->isAbstract || newClassPtr->isCppVTable || newClassPtr->isFinal)) + { + emitError(loc(classDeclarationAST)) + << "class '" << newClassPtr->name << "' cannot be both @" VALUE_DECORATOR " and " + << (newClassPtr->isAbstract ? "abstract" : newClassPtr->isCppVTable ? "@" CPP_VTABLE : "@" FINAL_DECORATOR); + return {mlir::failure(), ""}; + } + if (isGenericClass && genContext.typeParamsWithArgs.size() > 0) { // a concrete instantiation of a generic class (e.g. Box) reprocesses the @@ -236,9 +259,13 @@ namespace mlirgen mlirGenClassDefaultConstructor(classDeclarationAST, newClassPtr, classGenContext); } + // a @value class has a constructor and nothing an object has: no vtable, no `.instanceOf`, + // no `..new` - `new` makes the value in place (NewValueClassInstance) + auto hasObjectMembers = hasOwnRuntimeMembers && !newClassPtr->isValue; + #ifdef ENABLE_RTTI // no `.instanceOf`: a C++ vtable has only the C++ methods - if (hasOwnRuntimeMembers && !newClassPtr->isCppVTable) + if (hasObjectMembers && !newClassPtr->isCppVTable) { // INFO: .instanceOf must be first element in VTable for Cast Any mlirGenClassInstanceOfMethod(classDeclarationAST, newClassPtr, classGenContext); @@ -247,14 +274,14 @@ namespace mlirgen #if ENABLE_TYPED_GC auto enabledGC = compileOptions.needsGCRuntime(); - if (enabledGC && hasOwnRuntimeMembers) + if (enabledGC && hasObjectMembers) { mlirGenClassTypeBitmap(location, newClassPtr, classGenContext); mlirGenClassTypeDescriptorField(location, newClassPtr, classGenContext); } #endif - if (hasOwnRuntimeMembers) + if (hasObjectMembers) { mlirGenClassNew(classDeclarationAST, newClassPtr, classGenContext); } @@ -314,7 +341,7 @@ namespace mlirgen } } - if (hasOwnRuntimeMembers) + if (hasObjectMembers) { if (mlir::failed(mlirGenClassVirtualTableDefinition(location, newClassPtr, classGenContext))) { @@ -417,6 +444,11 @@ namespace mlirgen { newClassPtr->isFinal = true; } + + if (name == VALUE_DECORATOR) + { + newClassPtr->isValue = true; + } }); getClassesMap().insert({namePtr, newClassPtr}); @@ -1062,9 +1094,9 @@ namespace mlirgen } #if ENABLE_RTTI - if (newClassPtr->isCppVTable) + if (newClassPtr->isCppVTable || newClassPtr->isValue) { - // no RTTI: a C++ object can't answer `instanceof` + // no RTTI: a C++ object can't answer `instanceof`, nor can a value, which has no vtable } else if (newClassPtr->isDynamicImport) { @@ -1258,6 +1290,22 @@ namespace mlirgen fieldInfos.push_back({fieldId, baseClassType.getStorageType(), false, mlir_ts::AccessLevel::Public}); auto classInfo = getClassInfoByFullName(baseName); + // a value has no base layout, and nothing extends one: no vtable to override + // through + if (newClassPtr->isValue) + { + emitError(loc(extendingType)) << "@" VALUE_DECORATOR " class '" << newClassPtr->name + << "' cannot extend '" << (classInfo ? classInfo->name : baseName) << "'"; + return; + } + + if (classInfo && classInfo->isValue) + { + emitError(loc(extendingType)) << "class '" << newClassPtr->name << "' cannot extend '" + << classInfo->name << "': it is @" VALUE_DECORATOR; + return; + } + // calls on a @final class are direct (ClassMethodAccess): an override // would never run if (classInfo && classInfo->isFinal) @@ -1298,6 +1346,14 @@ namespace mlirgen if (heritageClause->token == SyntaxKind::ImplementsKeyword) { + // a value has no vtable to see it through an interface by + if (newClassPtr->isValue) + { + emitError(loc(heritageClause)) << "@" VALUE_DECORATOR " class '" << newClassPtr->name + << "' cannot implement an interface"; + return mlir::failure(); + } + newClassPtr->hasVirtualTable = true; auto &interfaceInfos = newClassPtr->implements; @@ -1518,6 +1574,9 @@ namespace mlirgen } } + // an instance field: a static one is a global, not part of the value + auto layoutField = valueLayoutField(newClassPtr->isValue, newClassPtr->fullName, newClassPtr->name, location, + MLIRHelper::getName(name)); auto [type, init] = mlirGenClassDataFieldType(location, propertyDeclaration, genContext); if (init) { @@ -1716,7 +1775,8 @@ namespace mlirgen return mlir::success(); } - mlir::LogicalResult MLIRGenImpl::mlirGenClassConstructorPublicDataFieldMembers(mlir::Location location, SmallVector &fieldInfos, + mlir::LogicalResult MLIRGenImpl::mlirGenClassConstructorPublicDataFieldMembers(mlir::Location location, ClassInfo::TypePtr newClassPtr, + SmallVector &fieldInfos, ConstructorDeclaration constructorDeclaration, const GenContext &genContext) { for (auto ¶meter : constructorDeclaration->parameters) @@ -1744,6 +1804,8 @@ namespace mlirgen isPrivate |= strAttr.getValue().starts_with("#"); } + auto layoutField = valueLayoutField(newClassPtr->isValue, newClassPtr->fullName, newClassPtr->name, loc(parameter), + MLIRHelper::getName(parameter->name)); auto [type, init, typeProvided] = evaluateTypeAndInit(parameter, genContext); if (mth.isNoneType(type)) @@ -1793,7 +1855,8 @@ namespace mlirgen } } - if (newClassPtr->isStatic) + // a @value class has no vtable: its methods are called directly + if (newClassPtr->isStatic || newClassPtr->isValue) { return mlir::success(); } @@ -1816,6 +1879,47 @@ namespace mlirgen return mlir::success(); } + // An instance member of a @value class: every field `readonly` (a parameter property too), and no + // setter. Statics are as any class's. + mlir::LogicalResult MLIRGenImpl::mlirGenValueClassMemberRules(ClassInfo::TypePtr newClassPtr, ClassElement classMember) + { + auto fieldMustBeReadonly = [&](Node fieldNode, Node nameNode) { + emitError(loc(fieldNode)) << "field '" << MLIRHelper::getName(nameNode) << "' of @" VALUE_DECORATOR " class '" + << newClassPtr->name << "' must be readonly"; + return mlir::failure(); + }; + + if (classMember == SyntaxKind::PropertyDeclaration) + { + auto propertyDeclaration = classMember.as(); + if (!hasModifier(propertyDeclaration, SyntaxKind::ReadonlyKeyword)) + { + return fieldMustBeReadonly(propertyDeclaration, propertyDeclaration->name); + } + } + + if (classMember == SyntaxKind::Constructor) + { + for (auto ¶meter : classMember.as()->parameters) + { + auto isProperty = hasModifier(parameter, SyntaxKind::PublicKeyword) || hasModifier(parameter, SyntaxKind::ProtectedKeyword) + || hasModifier(parameter, SyntaxKind::PrivateKeyword) || hasModifier(parameter, SyntaxKind::ReadonlyKeyword); + if (isProperty && !hasModifier(parameter, SyntaxKind::ReadonlyKeyword)) + { + return fieldMustBeReadonly(parameter, parameter->name); + } + } + } + + if (classMember == SyntaxKind::SetAccessor) + { + emitError(loc(classMember)) << "@" VALUE_DECORATOR " class '" << newClassPtr->name << "' cannot have a setter"; + return mlir::failure(); + } + + return mlir::success(); + } + mlir::LogicalResult MLIRGenImpl::mlirGenClassFieldMember(ClassInfo::TypePtr newClassPtr, ClassElement classMember, SmallVector &fieldInfos, bool staticOnly, const GenContext &genContext) @@ -1830,6 +1934,12 @@ namespace mlirgen mlirGenClassProcessClassPropertyByFieldMember(newClassPtr, classMember); + // the copies of a @value value must not differ: no field it could change, no setter + if (newClassPtr->isValue && !isStatic && mlir::failed(mlirGenValueClassMemberRules(newClassPtr, classMember))) + { + return mlir::failure(); + } + if (classMember == SyntaxKind::PropertyDeclaration) { // property declaration @@ -1860,7 +1970,7 @@ namespace mlirgen if (classMember == SyntaxKind::Constructor && !isStatic) { auto constructorDeclaration = classMember.as(); - if (mlir::failed(mlirGenClassConstructorPublicDataFieldMembers(location, fieldInfos, constructorDeclaration, genContext))) + if (mlir::failed(mlirGenClassConstructorPublicDataFieldMembers(location, newClassPtr, fieldInfos, constructorDeclaration, genContext))) { return mlir::failure(); } @@ -2518,6 +2628,12 @@ genContext); { if (!found && !isConditional || found) { + if (auto valueType = found ? MLIRTypeHelper::getPlainValueForOptionalMember(fieldType, foundField.type) : mlir_ts::ValueType()) + { + MLIRTypeHelper::emitPlainValueForOptionalMemberError(location, id, valueType, newInterfacePtr->fullName); + return {emptyFieldInfo, mlir::failure()}; + } + emitError(location) << "field type not matching for " << id << " for interface '" << newInterfacePtr->fullName << "' in class '" << newClassPtr->fullName << "'"; @@ -3291,6 +3407,17 @@ genContext); funcGenContext.clearScopeVars(); funcGenContext.thisType = newClassPtr->classType; funcGenContext.thisClassType = newClassPtr->classType; + // `this` of a @value class: in the constructor the slot `new` made, whose fields it assigns + // (the variable `this` is that slot: mlirGenFunctionParams); in a method or a getter the value + // itself, a copy. A static member's `this` is the class. + if (newClassPtr->isValue && !classMethodMemberInfo.isStatic) + { + auto valueType = getValueTypeOfClass(newClassPtr); + funcGenContext.thisType = classMethodMemberInfo.isConstructor + ? mlir::Type(mlir_ts::RefType::get(valueType)) + : mlir::Type(valueType); + } + if (classMethodMemberInfo.isConstructor) { if (classMethodMemberInfo.isStatic && !genContext.allowPartialResolve) diff --git a/tslang/lib/TypeScript/MLIRGenExpressions.cpp b/tslang/lib/TypeScript/MLIRGenExpressions.cpp index 2cf17902f..ab66e296c 100644 --- a/tslang/lib/TypeScript/MLIRGenExpressions.cpp +++ b/tslang/lib/TypeScript/MLIRGenExpressions.cpp @@ -14,6 +14,20 @@ namespace mlirgen ValueOrLogicalResult MLIRGenImpl::mlirGen(Expression expressionAST, const GenContext &genContext) { + // the object of a `?.` that the optional chain around it has read and tested + if (!optionalChainObjects.empty()) + { + if (auto known = optionalChainObjects.find(optionalChainKey(expressionAST)); known != optionalChainObjects.end()) + { + return known->second; + } + } + + if (auto questionDotObject = optionalChainObject(expressionAST)) + { + return mlirGenOptionalChain(expressionAST, questionDotObject, genContext); + } + auto kind = (SyntaxKind)expressionAST; if (kind == SyntaxKind::Identifier) { @@ -616,6 +630,12 @@ namespace mlirgen } case SyntaxKind::PlusPlusToken: case SyntaxKind::MinusMinusToken: + // an assignment as well: a field of a @value value is readonly + if (mlir::failed(checkValueFieldAssignment(location, expressionValue))) + { + return mlir::failure(); + } + return V(builder.create(location, expressionValue.getType(), builder.getI32IntegerAttr((int)opCode), expressionValue)); default: @@ -641,6 +661,12 @@ namespace mlirgen { case SyntaxKind::PlusPlusToken: case SyntaxKind::MinusMinusToken: + // an assignment as well: a field of a @value value is readonly + if (mlir::failed(checkValueFieldAssignment(location, expressionValue))) + { + return mlir::failure(); + } + return V(builder.create(location, expressionValue.getType(), builder.getI32IntegerAttr((int)opCode), expressionValue)); default: @@ -905,6 +931,21 @@ namespace mlirgen mlir::Value rightExpressionValue, const GenContext &genContext, bool saveResult) { + // a @value value is copied wherever it goes: two of them have no identity to compare, and + // comparing their fields here would answer differently from the TypeScript program. So also + // when either may be missing (`T | null`), and against anything else: only null and + // undefined are compared with one + auto isNullish = [](mlir::Value value) { return isa(value.getType()); }; + if ((opCode == SyntaxKind::EqualsEqualsEqualsToken || opCode == SyntaxKind::ExclamationEqualsEqualsToken + || opCode == SyntaxKind::EqualsEqualsToken || opCode == SyntaxKind::ExclamationEqualsToken) + && leftExpressionValue && rightExpressionValue + && (MLIRTypeHelper::holdsValueType(leftExpressionValue.getType()) || MLIRTypeHelper::holdsValueType(rightExpressionValue.getType())) + && !isNullish(leftExpressionValue) && !isNullish(rightExpressionValue)) + { + emitError(location) << "a @" VALUE_DECORATOR " type has no identity; compare its fields"; + return mlir::failure(); + } + if (auto folded = foldNullishCompare(location, opCode, leftExpressionValue, rightExpressionValue)) { return *folded; @@ -1059,7 +1100,7 @@ namespace mlirgen auto optValue = isa(value.getType()) ? value - : builder.create(location, getOptionalType(value.getType()), value); + : mlirGenOptionalValueOf(location, value); return ValueOrLogicalResult(optValue); }, [&](mlir::Type trueValueType) { @@ -1556,6 +1597,152 @@ namespace mlirgen return value; } + // `a?.b.c`: once a `?.` meets null or undefined, TypeScript skips the whole rest of its chain, and + // the chain is undefined. A link reads only the link before it, so `.c` read `a?.b`'s undefined: + // `.c` of a missing @value type threw, of a missing type literal read 0. So a link of a chain (`.c`, + // `[i]`, `.m()`, `!`) that is not a `?.` itself and has one below it is made whole here + // (mlirGenOptionalChain): this is the object of the nearest `?.` below it (`a`), or none. + // Made on that object (optionalChainObjects), the chain is a chain as before. + Expression MLIRGenImpl::optionalChainObject(Expression expressionAST) + { + // (an absent expression - `for (;;)` - is made as an empty one) + if (!expressionAST || (expressionAST->flags & NodeFlags::OptionalChain) != NodeFlags::OptionalChain) + { + return undefined; + } + + // whether a link has a `?.`, and its object; a node of any other kind ends the chain + auto linkOf = [](Node link, Expression &object) -> std::optional { + switch ((SyntaxKind)link) + { + case SyntaxKind::PropertyAccessExpression: + object = link.as()->expression; + return !!link.as()->questionDotToken; + case SyntaxKind::ElementAccessExpression: + object = link.as()->expression; + return !!link.as()->questionDotToken; + case SyntaxKind::CallExpression: + object = link.as()->expression; + return !!link.as()->questionDotToken; + case SyntaxKind::NonNullExpression: + object = link.as()->expression; + return false; + default: + return std::nullopt; + } + }; + + Node link = expressionAST; + Expression object; + for (;;) + { + if ((link->flags & NodeFlags::OptionalChain) != NodeFlags::OptionalChain) + { + return undefined; + } + + auto hasQuestionDot = linkOf(link, object); + if (!hasQuestionDot) + { + return undefined; + } + + if (*hasQuestionDot) + { + break; + } + + link = object; + } + + // a `?.` link tests its object itself (mlirGenPropertyAccessExpressionLogic, the element access); + // a call's `?.()` is not tested anywhere, which this does not change; and a chain being made on + // its object already is a chain as before + if (link == expressionAST || link == SyntaxKind::CallExpression || optionalChainObjects.count(optionalChainKey(object))) + { + return undefined; + } + + return object; + } + + // ...made whole: the object of the nearest `?.` is read once and tested as that `?.` tests it, the + // chain is made on the value read only when it is there, as an optional, and is undefined when not; + // a chain that ends in a call of a void function (`c?.m.print()`) is only made when it is there. + // The `?.` tests it again, which is the chain as it was made before. + ValueOrLogicalResult MLIRGenImpl::mlirGenOptionalChain(Expression chainAST, Expression questionDotObject, + const GenContext &genContext) + { + auto location = loc(chainAST); + + auto objectResult = mlirGen(questionDotObject, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(objectResult) + auto objectValue = V(objectResult); + + auto key = optionalChainKey(questionDotObject); + optionalChainObjects[key] = objectValue; + auto forget = llvm::make_scope_exit([&]() { optionalChainObjects.erase(key); }); + + if (!MLIRTypeCore::isNullableOrOptionalType(objectValue.getType())) + { + return mlirGen(chainAST, genContext); + } + + CAST_A(condValue, location, getBooleanType(), objectValue, genContext); + + // the result's type is the chain's, known once it is made + auto ifOp = builder.create(location, builder.getNoneType(), condValue, true); + auto abandon = [&]() { + builder.setInsertionPoint(ifOp); + ifOp.erase(); + return mlir::failure(); + }; + + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + auto chainResult = mlirGen(chainAST, genContext); + if (chainResult.failed()) + { + return abandon(); + } + + if (!chainResult.value) + { + // no value: the chain's ops move to an `if` with none + builder.setInsertionPoint(ifOp); + auto voidIfOp = builder.create(location, condValue, false); + auto &thenBlock = voidIfOp.getThenRegion().front(); + auto at = !thenBlock.empty() && thenBlock.back().hasTrait() + ? mlir::Block::iterator(&thenBlock.back()) : thenBlock.end(); + thenBlock.getOperations().splice(at, ifOp.getThenRegion().front().getOperations()); + ifOp.erase(); + builder.setInsertionPointAfter(voidIfOp); + return mlir::success(); + } + + auto chainValue = V(chainResult); + if (mth.isNoneType(chainValue.getType())) + { + // a discovery pass that could not resolve the chain yet (a call's UndefOp of none) + builder.create(location, mlir::ValueRange{chainValue}); + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + auto noneValue = builder.create(location, builder.getNoneType()); + builder.create(location, mlir::ValueRange{noneValue}); + builder.setInsertionPointAfter(ifOp); + return V(ifOp.getResults().front()); + } + + auto optValue = isa(chainValue.getType()) ? chainValue : mlirGenOptionalValueOf(location, chainValue); + ifOp.getResults().front().setType(optValue.getType()); + builder.create(location, mlir::ValueRange{optValue}); + + builder.setInsertionPointToStart(&ifOp.getElseRegion().front()); + auto undefValue = builder.create(location, optValue.getType()); + builder.create(location, mlir::ValueRange{undefValue}); + + builder.setInsertionPointAfter(ifOp); + return V(ifOp.getResults().front()); + } + ValueOrLogicalResult MLIRGenImpl::mlirGen(OmittedExpression ommitedExpression, const GenContext &genContext) { auto location = loc(ommitedExpression); @@ -1892,6 +2079,28 @@ namespace mlirgen { auto location = loc(objectLiteral); + // A literal of a @value type is built as its storage tuple - its fields reordered to the + // declaration's, as for a type literal - and that tuple is the value. It is never boxed. + // Received as one that may be missing (`T | null`), the literal is the T: so is each branch of + // `c ? { d: 1 } : null`, which then makes the missing type of T and null. + if (genContext.receiverType) + { + auto valueType = dyn_cast(mth.stripOptionalType(genContext.receiverType)); + if (!valueType) + { + valueType = MLIRTypeHelper::getMissingValueElement(genContext.receiverType); + } + + if (valueType) + { + GenContext storageGenContext(genContext); + storageGenContext.receiverType = valueType.getStorageType(); + auto result = mlirGen(objectLiteral, storageGenContext); + EXIT_IF_FAILED_OR_NO_VALUE(result) + return cast(location, valueType, V(result), genContext); + } + } + ObjectLiteralInfo oli{}; oli.objectLiteral = objectLiteral; @@ -2172,7 +2381,7 @@ namespace mlirgen // TODO: error, when we use function_name(index: index) and index value is not provided in call function_name(index), index will be mistakenly tearted // as embeded type "index" - if (!isEmbededType(name) && !circularTypeAliases.contains(name)) + if (!isEmbededType(name) && !circularTypeAliases.contains(name) && !valueTypesHoldingThemselves.contains(name)) emitError(location, "can't resolve name: ") << name; return mlir::failure(); diff --git a/tslang/lib/TypeScript/MLIRGenFunctions.cpp b/tslang/lib/TypeScript/MLIRGenFunctions.cpp index 065c9387a..b9bc5466b 100644 --- a/tslang/lib/TypeScript/MLIRGenFunctions.cpp +++ b/tslang/lib/TypeScript/MLIRGenFunctions.cpp @@ -1431,6 +1431,22 @@ namespace mlirgen LLVM_DEBUG(llvm::dbgs() << "Location for Param: " << location << "\n"); + // `this` of a @value class's constructor is the slot `new` made for the value: the + // variable `this` lives in it, so `this.a = a` writes the value's field and `this.m()` sees + // the fields stored so far; read whole (`f(this)`, `const c = this`) it is an error + // (checkValueConstructorThisUses) + if (param->getName() == THIS_NAME && index == firstIndex) + { + auto refType = dyn_cast(param->getType()); + if (refType && getValueClassInfo(refType.getElementType())) + { + auto thisDecl = std::make_shared(THIS_NAME, refType.getElementType(), location); + thisDecl->setReadWriteAccess(); + DECLARE(thisDecl, arguments[index]); + continue; + } + } + // alloc all args // process optional parameters if (param->hasInitValue()) @@ -1456,6 +1472,14 @@ namespace mlirgen { // redefine variable param->setReadWriteAccess(); + // `this` of a @value class's method is the value, which nothing assigns: a closure + // takes a copy of it, not its cell (so a `ref` named `this` in a capture is the + // constructor's slot alone) + if (param->getName() == THIS_NAME && index == firstIndex && getValueClassInfo(param->getType())) + { + param->setCaptureByValue(); + } + DECLARE(param, paramValue); } } @@ -1732,6 +1756,19 @@ namespace mlirgen loopLabelAliases = std::move(outerLoopLabelAliases); }); + // nor is a @value type a body needs one the field being typed around it waits for (an + // initializer's return type inferred from this body) + auto outerValueLayoutFrames = std::move(valueLayoutFrames); + valueLayoutFrames.clear(); + auto restoreValueLayoutFrames = llvm::make_scope_exit([&]() { valueLayoutFrames = std::move(outerValueLayoutFrames); }); + + // nor are the objects an optional chain around it read (mlirGenOptionalChain) this body's: made + // again inside the chain - a recursive function's result inferred - the chain's nodes are made + // anew + auto outerOptionalChainObjects = std::move(optionalChainObjects); + optionalChainObjects.clear(); + auto restoreOptionalChainObjects = llvm::make_scope_exit([&]() { optionalChainObjects = std::move(outerOptionalChainObjects); }); + auto location = loc(functionLikeDeclarationBaseAST); // Debug Info @@ -1839,6 +1876,38 @@ namespace mlirgen return mlir::failure(); } + // a @value class's constructor reads `this` only through its members - in a discovery run + // too, where a use of `this` whole may fail first with an error of its own (`{ ...this }`) + if (functionLikeDeclarationBaseAST == SyntaxKind::Constructor + && !funcProto->getParams().empty() && funcProto->getParams().front()->getName() == THIS_NAME) + { + auto thisRefType = dyn_cast(funcProto->getParams().front()->getType()); + if (auto classInfo = thisRefType ? getValueClassInfo(thisRefType.getElementType()) : ClassInfo::TypePtr()) + { + auto thisUses = checkValueConstructorThisUses(functionLikeDeclarationBaseAST->body, classInfo->name); + + // ...and so do its instance fields' initializers, which run in it (in the one made + // for them when none is written) + if (classInfo->processingDeclaration) + { + for (auto &member : classInfo->processingDeclaration->members) + { + if (member == SyntaxKind::PropertyDeclaration && !hasModifier(member, SyntaxKind::StaticKeyword) + && member.as()->initializer + && failed(checkValueConstructorThisUses(member.as()->initializer, classInfo->name))) + { + thisUses = mlir::failure(); + } + } + } + + if (failed(thisUses)) + { + return mlir::failure(); + } + } + } + // we need it to skip lexical block functionLikeDeclarationBaseAST->body->parent = functionLikeDeclarationBaseAST->body; if (failed(mlirGenBody(functionLikeDeclarationBaseAST->body, funcGenContext))) @@ -1880,6 +1949,11 @@ namespace mlirgen return mlir::failure(); } + if (!funcGenContext.dummyRun && failed(checkValueConstructorClosures(funcOp))) + { + return mlir::failure(); + } + if (funcGenContext.dummyRun && funcGenContext.cleanUps) { funcGenContext.cleanUps->push_back(blockPtr); @@ -2017,7 +2091,7 @@ namespace mlirgen // reference of its own; retaining the cell instead leaves the value with one owner // fewer than the releases that will run for it, which is what freed the source array // of a generator out from under the generator (§9.50). - auto capturedByRef = item.second && item.second->getReadWriteAccess(); + auto capturedByRef = item.second && item.second->getCaptureByReference(); // review capturing by ref. it should match storage type auto refValue = mcl.GetReferenceFromValue(location, varValue); @@ -2062,6 +2136,12 @@ namespace mlirgen paramOptOp.setCapturedAttr(builder.getBoolAttr(true)); builder.create(location, refValue); } + else if (MLIRTypeHelper::isValueConstructorThisCapture(builder.getStringAttr(item.first()), + refValue.getType())) + { + // `this` of a @value class's constructor, seen in a closure through its box: the + // slot `new` made, which this box borrows as the first one does - not a cell + } else if (isCapturedCellSlot(refValue)) { // A closure inside a closure, capturing the same variable. There is nothing @@ -2076,7 +2156,9 @@ namespace mlirgen { // no retain here: what makes a variable's storage a cell is being marked // captured, and nothing was marked. Retaining a stack slot would write a - // count into the frame word in front of it. + // count into the frame word in front of it. `this` of a @value class's + // constructor lands here by design: its storage is the slot `new` made, which + // the box borrows (OwnershipRoutineLogic::releaseCapturedFields skips it). // TODO: review it. // find out if u need to ensure that data is captured and belong to VariableOp or ParamOp with // captured = true @@ -2097,6 +2179,140 @@ namespace mlirgen return mlir::success(); } + // A use of a closure holding the slot of a @value constructor's `this` other than calling it + // (GetThis/GetMethod) or counting it (Retain/Release); null when there is none. Captured by another + // closure is such a use: inside that one it is a field of a box, which could be stored or returned + // from there unseen. + static mlir::Operation *escapingUseOfValueConstructorClosure(mlir::Value closure) + { + for (auto *user : closure.getUsers()) + { + if (!isa(user)) + { + return user; + } + } + + return nullptr; + } + + // A closure that captures `this` of a @value class's constructor holds the address of the slot + // `new` made, which dies with `new`'s caller (MLIRTypeHelper::isValueConstructorThisCapture). So + // it may only be called, in the function that made it: the constructor, or a closure inside it + // that captures `this` itself. Stored, returned, passed on or captured, it could read a dead slot. + mlir::LogicalResult MLIRGenImpl::checkValueConstructorClosures(mlir_ts::FuncOp funcOp) + { + auto result = mlir::success(); + funcOp.walk([&](mlir_ts::CreateBoundFunctionOp boundFuncOp) { + auto captureOp = boundFuncOp.getThisVal().getDefiningOp(); + auto captureRefType = captureOp ? dyn_cast(captureOp->getResult(0).getType()) : mlir_ts::RefType(); + auto captureTupleType = captureRefType ? dyn_cast(captureRefType.getElementType()) : mlir_ts::TupleType(); + if (!captureTupleType) + { + return; + } + + for (auto &field : captureTupleType.getFields()) + { + if (!MLIRTypeHelper::isValueConstructorThisCapture(field.id, field.type)) + { + continue; + } + + if (auto *use = escapingUseOfValueConstructorClosure(boundFuncOp.getResult())) + { + auto valueType = mlir::cast(field.type).getElementType(); + auto classInfo = getValueClassInfo(valueType); + auto className = classInfo ? classInfo->name.str() : to_print(valueType); + emitError(use->getLoc()) << "a closure that captures 'this' of the @" VALUE_DECORATOR " class '" + << className << "' can only be called inside its constructor"; + result = mlir::failure(); + } + + return; + } + }); + + return result; + } + + // `this` of a @value class's constructor is the slot `new` is filling (mlirGenFunctionParams): the + // value is made when the constructor returns. Read whole before that - `const self = this`, + // `f(this)`, `[this]`, `{ v: this }`, `...this`, `return this`, `() => this` - it would be a copy + // of the fields stored so far, and a later `this.a = 1` would not reach it, where TypeScript's + // object would have it. So `this` may only be the object of a member access (`this.a`, + // `this.a = x`, `this.a++`, `this.m()`, `this["a"]`), read as the slot is at that point, in the + // constructor or in an arrow function inside it, whose `this` is the constructor's. A function, + // method, accessor or class inside it has a `this` of its own. `root` is the constructor's body, or + // an instance field's initializer, which runs in the constructor too (mlirGenFunctionBody). + mlir::LogicalResult MLIRGenImpl::checkValueConstructorThisUses(Node root, StringRef className) + { + auto result = mlir::success(); + + auto isThis = [](Node expression) { + while (expression == SyntaxKind::ParenthesizedExpression) + { + expression = expression.as()->expression; + } + + return expression == SyntaxKind::ThisKeyword; + }; + + ts::FuncT<> visitNode; + ts::ArrayFuncT<> visitArray; + + visitNode = [&](Node node) -> Node { + switch ((SyntaxKind)node) + { + case SyntaxKind::FunctionExpression: + case SyntaxKind::FunctionDeclaration: + case SyntaxKind::MethodDeclaration: + case SyntaxKind::GetAccessor: + case SyntaxKind::SetAccessor: + case SyntaxKind::Constructor: + case SyntaxKind::ClassDeclaration: + case SyntaxKind::ClassExpression: + return undefined; + case SyntaxKind::PropertyAccessExpression: + if (isThis(node.as()->expression)) + { + return undefined; + } + + break; + case SyntaxKind::ElementAccessExpression: + if (auto elementAccess = node.as(); isThis(elementAccess->expression)) + { + return visitNode(elementAccess->argumentExpression); + } + + break; + case SyntaxKind::ThisKeyword: + emitError(loc(node)) << "'this' of the @" VALUE_DECORATOR " class '" << className + << "' is not a value until its constructor returns; read 'this.f'"; + result = mlir::failure(); + return undefined; + default: + break; + } + + ts::forEachChild(node, visitNode, visitArray); + return undefined; + }; + + visitArray = [&](NodeArray array) -> Node { + for (auto node : array) + { + visitNode(node); + } + + return undefined; + }; + + visitNode(root); + return result; + } + ValueOrLogicalResult MLIRGenImpl::mlirGenCreateCapture(mlir::Location location, mlir::Type capturedType, SmallVector capturedValues, const GenContext &genContext) { diff --git a/tslang/lib/TypeScript/MLIRGenGenerics.cpp b/tslang/lib/TypeScript/MLIRGenGenerics.cpp index f9217efab..b7b20202d 100644 --- a/tslang/lib/TypeScript/MLIRGenGenerics.cpp +++ b/tslang/lib/TypeScript/MLIRGenGenerics.cpp @@ -192,6 +192,9 @@ namespace mlirgen concreteType = objectType.getStorageType(); } + // a @value value infers from its fields, as a type literal of them does + concreteType = MLIRTypeHelper::stripValueType(concreteType); + if (auto typeTuple = dyn_cast(concreteType)) { return tryInferTupleFields(location, tempTuple, typeTuple, results, genContext); @@ -1202,6 +1205,7 @@ namespace mlirgen declarationMode = false; // create new instance of interface with TypeArguments + auto ownLayout = suspendValueLayoutFrames(); if (mlir::failed(std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext)))) { return {mlir::failure(), mlir::Type()}; @@ -1284,6 +1288,7 @@ namespace mlirgen MLIRValueGuard declarationModeGuard(declarationMode); declarationMode = false; + auto ownLayout = suspendValueLayoutFrames(); auto res = std::get<0>(mlirGen(genericClassInfo->classDeclaration, genericTypeGenContext)); count--; @@ -1460,6 +1465,7 @@ namespace mlirgen llvm::dbgs() << "\n";); // create new instance of interface with TypeArguments + auto ownLayout = suspendValueLayoutFrames(); if (mlir::failed(mlirGen(genericInterfaceInfo->interfaceDeclaration, genericTypeGenContext))) { // return mlir::Type(); diff --git a/tslang/lib/TypeScript/MLIRGenImpl.h b/tslang/lib/TypeScript/MLIRGenImpl.h index 66c4e06dd..efb65fa60 100644 --- a/tslang/lib/TypeScript/MLIRGenImpl.h +++ b/tslang/lib/TypeScript/MLIRGenImpl.h @@ -54,6 +54,7 @@ #endif #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Debug.h" @@ -1328,7 +1329,74 @@ class MLIRGenImpl return isOwnedLocalSlot(reference) || isCapturedVariableCell(reference) || isCapturedCellSlot(reference) || isOwnedGlobalSlot(location, reference) || isOwnedFieldSlot(location, reference) || isOwnedElementSlot(location, reference) || - isOwnedInterfaceFieldSlot(location, reference) || isOwnedSharedValueSlot(location, reference); + isOwnedInterfaceFieldSlot(location, reference) || isOwnedSharedValueSlot(location, reference) || + isValueConstructorSlot(reference); + } + + // The fields of a @value value are readonly (TypeScript's TS2540): only `this.f = ...` in the class's own + // constructor body assigns one - a store into the slot `new` made, which that body has as its `this` + // parameter (isValueConstructorSlot). A closure inside the constructor sees the slot through its box + // (and its store would go uncounted), a method has a copy of the value, and any other place holds a + // value of its own. + mlir::LogicalResult checkValueFieldAssignment(mlir::Location location, mlir::Value left) + { + mlir_ts::ValueType valueType; + int64_t position = -1; + if (auto loadOp = left.getDefiningOp()) + { + auto propertyRefOp = loadOp.getReference().getDefiningOp(); + auto castOp = propertyRefOp ? propertyRefOp.getObjectRef().getDefiningOp() : mlir_ts::CastOp(); + auto refType = castOp ? dyn_cast(castOp.getIn().getType()) : mlir_ts::RefType(); + valueType = refType ? dyn_cast(refType.getElementType()) : mlir_ts::ValueType(); + if (!valueType || isValueConstructorSlot(castOp.getIn())) + { + return mlir::success(); + } + + position = propertyRefOp.getPosition(); + } + else if (auto extractPropertyOp = left.getDefiningOp()) + { + auto castOp = extractPropertyOp.getObject().getDefiningOp(); + valueType = castOp ? dyn_cast(castOp.getIn().getType()) : mlir_ts::ValueType(); + if (!valueType) + { + return mlir::success(); + } + + position = extractPropertyOp.getPosition().front(); + } + else + { + return mlir::success(); + } + + mlir::StringAttr name; + if (auto storageType = dyn_cast(valueType.getStorageType()); + storageType && position >= 0 && position < (int64_t)storageType.getFields().size()) + { + name = dyn_cast_or_null(storageType.getFields()[position].id); + } + + emitError(location) << "cannot assign to '" << (name ? name.getValue() : StringRef("?")) + << "': the fields of a @" VALUE_DECORATOR " type are readonly"; + return mlir::failure(); + } + + // `this` of a @value class's constructor: the slot `new` made for the value (a `ref` parameter, seen as + // its storage tuple when a field is written). It owns what its fields hold, as an owned local does: + // `new` hands the value it loads out of the slot to its receiver as an owned one + // (NewValueClassInstance), so `this.node = new Node()` hands the count over and `this.node = n` + // takes one. The slot starts zeroed, so there is no old value to give back the first time. + bool isValueConstructorSlot(mlir::Value reference) + { + if (auto castOp = reference.getDefiningOp()) + { + reference = castOp.getIn(); + } + + auto refType = dyn_cast(reference.getType()); + return refType && isa(refType.getElementType()) && isa(reference); } // `s.value` (own spec 23): the payload is owned by the handle's block, as a field by its object @@ -1960,9 +2028,36 @@ class MLIRGenImpl // And a tuple literal built at run time (`const nt = [x, [2, [3, 4]]]`), whose arrays // are born with no count: folded, nothing counted them, and `nt[1][1].push(5)` had no // reference to change the array through (#486). + // A literal of a @value type is the record read out of the literal's slot, made a value by a + // cast that lowers to nothing: the record the two literal checks below look for. + auto initialRecord = initial; + if (auto valueCast = initial ? initial.getDefiningOp() : mlir_ts::CastOp(); + valueCast && isa(valueCast.getType())) + { + initialRecord = valueCast.getIn(); + } + + auto recordType = MLIRTypeHelper::stripValueType(type); + + // And a @value value read out of a place that can be written again - a local, a parameter, + // a field, an element or a global (`const w = v`): its fields are read in place + // (GetReferenceFromValue), so folded, `v = new V(9)` changed what `w.x` read. A copy of its + // own is what a value is. + auto valueReadFromPlace = false; + if (isa(type)) + { + auto read = initial; + while (auto castOp = read ? read.getDefiningOp() : mlir_ts::CastOp()) + { + read = castOp.getIn(); + } + + valueReadFromPlace = read && read.getDefiningOp(); + } + MLIRTypeHelper mth(builder.getContext(), compileOptions); needsIdentityStorage = mth.hasBoundMethodField(type) || isa(type) - || MLIRTypeHelper::isConstTupleHoldingArray(type) + || MLIRTypeHelper::isConstTupleHoldingArray(type) || valueReadFromPlace || ((isa(type) || MLIRTypeHelper::isSharedHandleType(type) || ((readsLocalSlot(initial) || viewsLocalSlot(initial)) && mth.ownsHeapMemory(location, type)) || (compileOptions.isRefCounted() @@ -1970,9 +2065,9 @@ class MLIRGenImpl || readsField(viewedValue(initial)) || readsElement(viewedValue(initial)) || readsGlobal(viewedValue(initial))) && mth.ownsHeapMemory(location, type)) - || (readsLiteralSlot(mth, location, initial) && isa(type) + || (readsLiteralSlot(mth, location, initialRecord) && isa(recordType) && mth.ownsHeapMemory(location, type)) - || (initial && initial.getDefiningOp() && isa(type) + || (initialRecord && initialRecord.getDefiningOp() && isa(recordType) && mth.ownsHeapMemory(location, type))) && !(varClass == VariableType::ConstRef) && !(initial && initial.getDefiningOp())); @@ -3650,7 +3745,7 @@ class MLIRGenImpl auto optValue = isa(value.getType()) ? value - : builder.create(location, getOptionalType(value.getType()), value); + : mlirGenOptionalValueOf(location, value); return ValueOrLogicalResult(optValue); }, [&](mlir::Type trueValueType) { @@ -3777,7 +3872,8 @@ class MLIRGenImpl bool isInterfaceVTableTypeSlot(const VirtualMethodOrFieldInfo &methodOrField); mlir::Value mlirGenInterfaceVTableTypeTag(mlir::Location location, mlir::Type implementerType); mlir::LogicalResult mlirGenThrowingMethodStub(mlir::Location location, StringRef name, StringRef stubName, - mlir_ts::FunctionType funcType, const GenContext &genContext); + mlir_ts::FunctionType funcType, const GenContext &genContext, + StringRef message = "method is abstract"); ValueOrLogicalResult mlirGenNullInterfaceVTable(mlir::Location location, InterfaceInfo::TypePtr newInterfacePtr, const GenContext &genContext); ValueOrLogicalResult mlirGenNullInterfaceVTableCast(mlir::Location location, mlir::Type type, @@ -5175,16 +5271,28 @@ class MLIRGenImpl return mlir::failure(); } - auto switchValueEffective = switchValue; - auto actualCaseType = mth.stripLiteralType(caseValue.getType()); - if (switchValue.getType() != actualCaseType) + // a case compares a @value value as `===` does: two of them have no identity, and + // `case null:` asks whether a `T | null` holds a value + mlir::Value condition; + if (MLIRTypeHelper::holdsValueType(switchValue.getType()) || MLIRTypeHelper::holdsValueType(caseValue.getType())) { - CAST(switchValueEffective, location, actualCaseType, switchValue, genContext); + auto compared = mlirGenBinaryValues(location, SyntaxKind::EqualsEqualsEqualsToken, switchValue, caseValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(compared) + condition = V(compared); } + else + { + auto switchValueEffective = switchValue; + auto actualCaseType = mth.stripLiteralType(caseValue.getType()); + if (switchValue.getType() != actualCaseType) + { + CAST(switchValueEffective, location, actualCaseType, switchValue, genContext); + } - auto condition = builder.create( - location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::EqualsEqualsToken), - switchValueEffective, caseValue); + condition = builder.create( + location, getBooleanType(), builder.getI32IntegerAttr((int)SyntaxKind::EqualsEqualsToken), + switchValueEffective, caseValue); + } CAST_A(conditionI1, location, builder.getI1Type(), condition, genContext); @@ -6227,6 +6335,17 @@ class MLIRGenImpl return mlir::failure(); } + // a value has no vtable, so nothing to ask its class of + if (auto classType = dyn_cast(rightType)) + { + if (auto classInfo = getClassInfoByFullName(classType.getName().getValue()); classInfo && classInfo->isValue) + { + emitError(location) << "instanceof can't be used with the @" VALUE_DECORATOR " class '" << classInfo->name + << "': its values have no type information"; + return mlir::failure(); + } + } + #ifdef ENABLE_RTTI if (auto classType = dyn_cast(rightType)) { @@ -6521,6 +6640,11 @@ class MLIRGenImpl leftExpressionValueBeforeCast = safeCastOp.getValue(); } + if (mlir::failed(checkValueFieldAssignment(location, leftExpressionValueBeforeCast))) + { + return mlir::failure(); + } + // TODO: finish it for field access, review CodeLogicHelper.saveResult if (auto loadOp = leftExpressionValueBeforeCast.getDefiningOp()) { @@ -8511,6 +8635,12 @@ class MLIRGenImpl mlir::StringRef name, bool isSuperClass, mlir::Value argument, mlir_ts::AccessLevel accessingFromLevel, const GenContext &genContext, bool finalReceiver = false); + mlir::Value ValueClassMembersAccess(mlir::Location location, mlir::Value thisValue, ClassInfo::TypePtr classInfo, + mlir::StringRef name, mlir_ts::AccessLevel accessingFromLevel, const GenContext &genContext); + + mlir::Value valueClassFunctionRef(mlir::Location location, ClassInfo::TypePtr classInfo, const MethodInfo &methodInfo, + const GenContext &genContext); + bool classHasField(ClassInfo::TypePtr classInfo, mlir::StringRef name, SmallVector &fieldPath) { auto fieldId = MLIRHelper::TupleFieldName(name, builder.getContext()); @@ -8538,6 +8668,62 @@ class MLIRGenImpl mlir::Value InterfaceMembers(mlir::Location location, mlir::Value interfaceValue, mlir::StringRef interfaceFullName, mlir::Attribute id, mlir::Value argument, const GenContext &genContext); + // The value a @value value that may be missing (MLIRTypeHelper::getMissingValueType) holds. When it + // holds null or undefined the read throws, as a member of a null interface does: through a stub + // made as that one's methods are (mlirGenThrowingMethodStub). The check is a branch with no result, + // so nothing is merged. + ValueOrLogicalResult mlirGenPresentValue(mlir::Location location, mlir::Value value, const GenContext &genContext) + { + auto valueType = MLIRTypeHelper::getMissingValueElement(value.getType()); + assert(valueType); + + auto nullValue = builder.create(location, getNullType()); + auto missing = mlirGenBinaryValues(location, SyntaxKind::EqualsEqualsToken, value, nullValue, genContext); + EXIT_IF_FAILED_OR_NO_VALUE(missing) + + auto stubName = concat(valueType.getName().getValue(), ".missing"); + auto stubType = getFunctionType({getOpaqueType()}, {}, false); + if (mlir::failed(mlirGenThrowingMethodStub(location, ".missing", stubName, stubType, genContext, + "a @" VALUE_DECORATOR " value is null or undefined"))) + { + return mlir::failure(); + } + + { + auto ifOp = builder.create(location, V(missing), false); + mlir::OpBuilder::InsertionGuard guard(builder); + builder.setInsertionPointToStart(&ifOp.getThenRegion().front()); + + auto stubRef = builder.create( + location, stubType, mlir::FlatSymbolRefAttr::get(builder.getContext(), stubName)); + auto nullThis = builder.create(location, getOpaqueType(), + builder.create(location, getNullType())); + builder.create(MLIRHelper::getCallSiteLocation(stubRef, location), stubRef, + mlir::ValueRange{nullThis}); + } + + auto unionValue = value; + if (auto optType = dyn_cast(value.getType())) + { + unionValue = builder.create(location, optType.getElementType(), value); + } + + return V(builder.create(location, valueType, unionValue)); + } + + // `value` as an optional of its type (getOptionalType): a @value value is the present value of + // the one optional every missing value of its type is + mlir::Value mlirGenOptionalValueOf(mlir::Location location, mlir::Value value) + { + auto optType = getOptionalType(value.getType()); + if (isa(value.getType())) + { + value = builder.create(location, mlir::cast(optType).getElementType(), value); + } + + return builder.create(location, optType, value); + } + // vtableOffset is the declaring interface's slot-block position within the root // interface's combined vtable (0 unless fieldInfo was found through an `extends` chain // - see InterfaceInfo::findField's doc comment, MLIRGenStore.h). @@ -9081,6 +9267,12 @@ class MLIRGenImpl ValueOrLogicalResult NewClassInstance(mlir::Location location, mlir_ts::ClassType classType, SmallVector &operands, const GenContext &genContext); + ValueOrLogicalResult NewValueClassInstance(mlir::Location location, ClassInfo::TypePtr classInfo, + NodeArray arguments, const GenContext &genContext); + + ValueOrLogicalResult NewValueClassInstance(mlir::Location location, ClassInfo::TypePtr classInfo, + SmallVector &operands, const GenContext &genContext); + ValueOrLogicalResult mlirGenCall(mlir::Location location, mlir::Value funcRefValue, SmallVector &operands, const GenContext &genContext); @@ -9880,6 +10072,16 @@ class MLIRGenImpl ValueOrLogicalResult mlirGen(NonNullExpression nonNullExpression, const GenContext &genContext); + Expression optionalChainObject(Expression expressionAST); + + ValueOrLogicalResult mlirGenOptionalChain(Expression chainAST, Expression questionDotObject, const GenContext &genContext); + + // an expression node, as optionalChainObjects knows it + static const void *optionalChainKey(Node node) + { + return node.operator->(); + } + ValueOrLogicalResult mlirGen(OmittedExpression ommitedExpression, const GenContext &genContext); ValueOrLogicalResult mlirGen(TemplateLiteralLikeNode templateExpressionAST, const GenContext &genContext); @@ -10950,8 +11152,9 @@ class MLIRGenImpl ValueOrLogicalResult mlirGen(ts::ArrayLiteralExpression arrayLiteral, const GenContext &genContext); // TODO: replace usage of this method with getFields method - mlir::Type getTypeByFieldNameFromReceiverType(mlir::Attribute fieldName, mlir::Type receiverType) + mlir::Type getTypeByFieldNameFromReceiverType(mlir::Attribute fieldName, mlir::Type receiverTypeIn) { + auto receiverType = MLIRTypeHelper::stripValueType(receiverTypeIn); if (auto tupleType = dyn_cast(receiverType)) { auto index = tupleType.getIndex(fieldName); @@ -11665,6 +11868,10 @@ class MLIRGenImpl ValueOrLogicalResult mlirGenCreateCapture(mlir::Location location, mlir::Type capturedType, SmallVector capturedValues, const GenContext &genContext); + mlir::LogicalResult checkValueConstructorClosures(mlir_ts::FuncOp funcOp); + + mlir::LogicalResult checkValueConstructorThisUses(Node root, StringRef className); + mlir::Value resolveFunctionWithCapture(mlir::Location location, StringRef name, mlir_ts::FunctionType funcType, mlir::Value thisValue, bool addGenericAttrFlag, const GenContext &genContext); @@ -12294,11 +12501,14 @@ class MLIRGenImpl mlir::LogicalResult mlirGenClassStaticFieldMemberDynamicImport(mlir::Location location, ClassInfo::TypePtr newClassPtr, PropertyDeclaration propertyDeclaration, const GenContext &genContext); - mlir::LogicalResult mlirGenClassConstructorPublicDataFieldMembers(mlir::Location location, SmallVector &fieldInfos, + mlir::LogicalResult mlirGenClassConstructorPublicDataFieldMembers(mlir::Location location, ClassInfo::TypePtr newClassPtr, + SmallVector &fieldInfos, ConstructorDeclaration constructorDeclaration, const GenContext &genContext); mlir::LogicalResult mlirGenClassProcessClassPropertyByFieldMember(ClassInfo::TypePtr newClassPtr, ClassElement classMember); + mlir::LogicalResult mlirGenValueClassMemberRules(ClassInfo::TypePtr newClassPtr, ClassElement classMember); + mlir::LogicalResult mlirGenClassFieldMember(ClassInfo::TypePtr newClassPtr, ClassElement classMember, SmallVector &fieldInfos, bool staticOnly, const GenContext &genContext); @@ -12773,7 +12983,8 @@ class MLIRGenImpl isImport = newClassPtr->isImport && (isConstructor || accessLevel == mlir_ts::AccessLevel::Public); isForceVirtual = (classMember->internalFlags & InternalFlags::ForceVirtual) == InternalFlags::ForceVirtual; #ifdef ALL_METHODS_VIRTUAL - isForceVirtual |= !isConstructor; + // a @value class has no vtable: its methods are called directly + isForceVirtual |= !isConstructor && !newClassPtr->isValue; #endif isVirtual = isForceVirtual; }; @@ -13173,6 +13384,218 @@ class MLIRGenImpl return mlir::failure(); } + // The type of a @value interface: its name and its fields as a tuple, in declaration order (the + // fields of a @value interface it extends first). + mlir_ts::ValueType getValueTypeOfInterface(InterfaceInfo::TypePtr interfaceInfo) + { + llvm::SmallVector fields; + interfaceInfo->getTupleTypeFields(fields, builder.getContext()); + return mlir_ts::ValueType::get(interfaceInfo->interfaceType.getName(), getTupleType(fields)); + } + + // A @value interface used as a type, once all its fields are known (and those of the @value + // interfaces it extends): a type taken before would keep the fields resolved so far, and a + // declaration that took it (`intersect(): Hit | null` of an interface `Hit.thing` refers to) would + // disagree with one that took it later. Not known yet, the declaration fails and is retried in + // the next discovery pass, as for a @value class (getValueTypeOfClassIfLaidOut). + mlir::Type getValueTypeOfInterfaceIfLaidOut(InterfaceInfo::TypePtr interfaceInfo) + { + llvm::SmallPtrSet visited; + std::function laidOut = [&](InterfaceInfo::TypePtr info) { + return !visited.insert(info.get()).second + || (info->membersResolved + && llvm::all_of(info->extends, [&](auto &extent) { return laidOut(std::get<1>(extent)); })); + }; + + if (!laidOut(interfaceInfo)) + { + noteValueLayoutWait(interfaceInfo->fullName, interfaceInfo->name); + return mlir::Type(); + } + + valueLayoutWaits.erase(interfaceInfo->fullName); + return getValueTypeOfInterface(interfaceInfo); + } + + // The field of a @value type whose type is being resolved, until the result goes out of scope: a + // @value type that type needs and that is not laid out yet is one this type waits for + // (noteValueLayoutWait). Nothing for a type that is not @value. + auto valueLayoutField(bool isValue, StringRef owner, StringRef ownerName, mlir::Location location, StringRef field) + { + if (isValue) + { + valueLayoutFrames.push_back({owner.str(), ownerName.str(), field.str(), location}); + } + + return llvm::make_scope_exit([this, isValue]() { + if (isValue) + { + valueLayoutFrames.pop_back(); + } + }); + } + + // A @value type is the tuple of its fields, held in place, so it cannot hold itself, directly or + // through other @value types (`next: L | null`; `A.b: B | null` and `B.a: A`): it would be + // infinitely large. The field being resolved (valueLayoutFrames) needs `waitedFor`, which is not + // laid out yet, so its type waits for it, and is retried in the next discovery pass; a type that + // waits, through the types it waits for, for itself never is laid out - "can't find type by name" + // said so without the reason. An array of it in a field (`next: L[]`), or a function type that + // names it, is the same here: the field's type is made of the type being made. An ordinary class + // or interface between them (`box: Box`, `Box.l: L | null`) is a reference, which waits for nothing. + void noteValueLayoutWait(StringRef waitedFor, StringRef waitedForName) + { + if (valueLayoutFrames.empty()) + { + return; + } + + auto &frame = valueLayoutFrames.back(); + auto &waits = valueLayoutWaits[frame.owner]; + if (llvm::none_of(waits, [&](const ValueLayoutWait &wait) { return wait.waitedFor == waitedFor && wait.field == frame.field; })) + { + waits.push_back({waitedFor.str(), waitedForName.str(), frame.field}); + } + + // the fields from the one being resolved back to its own type + llvm::SmallVector path; + llvm::StringSet<> visited; + std::function reaches = [&](StringRef from) { + if (from == frame.owner) + { + return true; + } + + auto it = valueLayoutWaits.find(from); + if (!visited.insert(from).second || it == valueLayoutWaits.end()) + { + return false; + } + + for (auto &wait : it->second) + { + path.push_back(&wait); + if (reaches(wait.waitedFor)) + { + return true; + } + + path.pop_back(); + } + + return false; + }; + + if (!reaches(waitedFor)) + { + return; + } + + auto through = frame.field; + valueTypesHoldingThemselves.insert(frame.ownerName); + valueTypesHoldingThemselves.insert(waitedForName); + for (auto *wait : path) + { + through += "."; + through += wait->field; + valueTypesHoldingThemselves.insert(wait->waitedForName); + } + + // `box: Box`: the specialized generic's type is made from L's, so L cannot hold it + if (!frame.generic.empty()) + { + emitError(frame.location) << "@" VALUE_DECORATOR " type '" << frame.ownerName << "' reaches itself through '" << through + << "' in the type arguments of '" << frame.generic + << "'; a @" VALUE_DECORATOR " type cannot hold a generic type made from it"; + return; + } + + emitError(frame.location) << "@" VALUE_DECORATOR " type '" << frame.ownerName << "' contains itself through '" + << through << "'; a value cannot hold itself"; + } + + // A generic's declaration specialized for a field of a @value type (`Box`'s members), until the + // result goes out of scope: its own types are not the field's (resolveGenericTypeInNamespace). + auto suspendValueLayoutFrames() + { + auto outer = std::make_shared>(std::move(valueLayoutFrames)); + valueLayoutFrames.clear(); + return llvm::make_scope_exit([this, outer]() { valueLayoutFrames = std::move(*outer); }); + } + + // The generic a field of a @value type names (`box: Box`), while its type arguments are + // resolved: a @value type they wait for is waited for through it (noteValueLayoutWait). + auto valueLayoutGenericArgs(TypeReferenceNode typeReferenceAST) + { + auto set = !valueLayoutFrames.empty() && valueLayoutFrames.back().generic.empty(); + if (set) + { + valueLayoutFrames.back().generic = print(typeReferenceAST); + } + + return llvm::make_scope_exit([this, set]() { + if (set && !valueLayoutFrames.empty()) + { + valueLayoutFrames.back().generic.clear(); + } + }); + } + + // The type of a @value class: its name and its instance fields as a tuple, in declaration order + // (parameter properties included). It has no vtable field: the class's storage is the tuple. + mlir_ts::ValueType getValueTypeOfClass(ClassInfo::TypePtr classInfo) + { + auto storageType = mlir::cast(classInfo->classType.getStorageType()); + llvm::SmallVector fields(storageType.getFields().begin(), storageType.getFields().end()); + return mlir_ts::ValueType::get(classInfo->classType.getName(), getTupleType(fields)); + } + + // The @value class a value of this type is of; none for anything else (a @value interface too). + ClassInfo::TypePtr getValueClassInfo(mlir::Type type) + { + if (auto valueType = dyn_cast_or_null(type)) + { + if (auto classInfo = getClassInfoByFullName(valueType.getName().getValue()); classInfo && classInfo->isValue) + { + return classInfo; + } + } + + return ClassInfo::TypePtr(); + } + + // A @value class used as a type, once its fields are known: a type taken before they are would + // keep a tuple of none. The fields stay from a discovery pass to the pass after it. + mlir::Type getValueTypeOfClassIfLaidOut(ClassInfo::TypePtr classInfo) + { + // past the storage, or failed after it + auto laidOut = [](ProcessingStages stage) { + return stage >= ProcessingStages::ProcessedStorageClass + || (stage >= ProcessingStages::ErrorInMembers && stage <= ProcessingStages::ErrorInVTable); + }; + + if (!laidOut(classInfo->processing) && !laidOut(classInfo->processingAtEvaluation)) + { + noteValueLayoutWait(classInfo->fullName, classInfo->name); + return mlir::Type(); + } + + valueLayoutWaits.erase(classInfo->fullName); + return getValueTypeOfClass(classInfo); + } + + // A @value value seen as its storage tuple: the cast lowers to nothing. Anything else is returned + // as it is. + mlir::Value valueStorage(mlir::Location location, mlir::Value value) + { + if (auto valueType = dyn_cast(value.getType())) + { + return builder.create(location, valueType.getStorageType(), value); + } + + return value; + } + mlir::LogicalResult mlirGenInterfaceAddFieldMember(InterfaceInfo::TypePtr newInterfacePtr, mlir::Attribute fieldId, mlir::Type typeIn, bool isConditional, int orderWeight, bool declareInterface = true); mlir::LogicalResult addInterfaceMethod(mlir::Location location, InterfaceInfo::TypePtr newInterfacePtr, @@ -15001,7 +15424,10 @@ class MLIRGenImpl return parsePartialStatements(src, emptyContext); } - mlir::LogicalResult parsePartialStatements(string src, const GenContext& genContext, bool useRootNamesapce = true, bool file_d_ts = false) + // `declarations`: src is a library's declarations (__decls), printed in its source order, so one + // may name another declared after it (`interface Hit { ray: Ray }` before `Ray`). Each that fails + // is tried again once the others are in, as a module's own statements are. + mlir::LogicalResult parsePartialStatements(string src, const GenContext& genContext, bool useRootNamesapce = true, bool file_d_ts = false, bool declarations = false) { Parser parser; // .d.ts will mark all variables as external (be careful) @@ -15020,6 +15446,23 @@ class MLIRGenImpl } } + if (declarations) + { + auto messagesBefore = genContext.postponedMessages ? genContext.postponedMessages->size() : 0; + if (mlir::failed(mlirGen(module->statements, genContext))) + { + return mlir::failure(); + } + + // all resolved: what the tries before then reported is not an error + if (genContext.postponedMessages) + { + rollbackPostponedErrorMessages(genContext.postponedMessages, messagesBefore); + } + + return mlir::success(); + } + for (auto statement : module->statements) { if (mlir::failed(mlirGen(statement, genContext))) @@ -15193,6 +15636,34 @@ class MLIRGenImpl std::string circularTypeAliasUnwinding; bool reportingCircularTypeAlias = false; + // The field of a @value type whose type is being resolved (valueLayoutField), innermost last. + struct ValueLayoutFrame + { + std::string owner; + std::string ownerName; + std::string field; + mlir::Location location; + // the generic whose type arguments are being resolved for the field (`Box`), if any + std::string generic; + }; + llvm::SmallVector valueLayoutFrames; + // A @value type not laid out yet that one of its fields' types needs (noteValueLayoutWait). + struct ValueLayoutWait + { + std::string waitedFor; + std::string waitedForName; + std::string field; + }; + // what each @value type, by full name, waits for before it can be laid out + llvm::StringMap> valueLayoutWaits; + // @value types reported as holding themselves, by name: "can't find type" for each mention after + // it would only repeat it + llvm::StringSet<> valueTypesHoldingThemselves; + + // the object of a `?.` its optional chain has read and tested, while the rest of the chain is made + // on it (mlirGenOptionalChain) + llvm::DenseMap optionalChainObjects; + // the declaration (no body) each declared function's full name came from, and the module it was // generated into - discovery's is thrown away, and a library's __decls is parsed again for the // next pass; see mlirGen(FunctionDeclaration) diff --git a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp index 56772fa61..0c83149fd 100644 --- a/tslang/lib/TypeScript/MLIRGenInterfaces.cpp +++ b/tslang/lib/TypeScript/MLIRGenInterfaces.cpp @@ -503,10 +503,12 @@ namespace mlirgen // `(this, ...) { throw new Error("method is abstract"); }`, typed as the interface's // method (`this` opaque): what a null interface's vtable holds for each method - // (mlirGenNullInterfaceVTable). Without the default library there is no `Error`, and the message - // itself is thrown. + // (mlirGenNullInterfaceVTable), and what a read of a missing @value value calls + // (mlirGenPresentValue), with its own message. Without the default library there is no `Error`, + // and the message itself is thrown. mlir::LogicalResult MLIRGenImpl::mlirGenThrowingMethodStub(mlir::Location location, StringRef name, StringRef stubName, - mlir_ts::FunctionType funcType, const GenContext &genContext) + mlir_ts::FunctionType funcType, const GenContext &genContext, + StringRef message) { if (auto existing = theModule.lookupSymbol(stubName)) { @@ -541,7 +543,7 @@ namespace mlirgen location, name, stubName, funcType, [&](mlir::Location location, const GenContext &genContext) -> mlir::LogicalResult { NodeFactory nf(NodeFactoryFlags::None); - Expression thrown = nf.createStringLiteral(S("method is abstract")); + Expression thrown = nf.createStringLiteral(stows(message.str())); if (getClassInfoByFullName("Error")) { NodeArray argumentsArray; @@ -1120,7 +1122,19 @@ namespace mlirgen const GenContext &genContext) { auto name = getNameWithArguments(interfaceDeclarationAST, genContext); - return mlirGenInterfaceInfo(name, declareInterface, genContext); + auto newInterfacePtr = mlirGenInterfaceInfo(name, declareInterface, genContext); + if (newInterfacePtr) + { + // `declare interface` too: the declaration is what an importer reads + iterateDecorators(interfaceDeclarationAST, genContext, [&](StringRef decoratorName, SmallVector args) { + if (decoratorName == VALUE_DECORATOR) + { + newInterfacePtr->isValue = true; + } + }); + } + + return newInterfacePtr; } InterfaceInfo::TypePtr MLIRGenImpl::mlirGenInterfaceInfo(const std::string &name, bool &declareInterface, @@ -1174,8 +1188,32 @@ namespace mlirgen auto result = mlirGen(extendsType, genContext); EXIT_IF_FAILED(result); auto ifaceType = V(result); + + // a @value interface (its type is a ValueType) or an ordinary one + auto baseInterfaceInfo = InterfaceInfo::TypePtr(); + if (auto valueType = dyn_cast(ifaceType.getType())) + { + baseInterfaceInfo = getInterfaceInfoByFullName(valueType.getName().getValue()); + } + else if (auto interfaceType = dyn_cast(ifaceType.getType())) + { + baseInterfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue()); + } + + // a value has no base layout to widen, and an interface that is not a value is seen + // through a vtable: a @value interface extends only another @value interface's fields + if (newInterfacePtr->isValue && !(baseInterfaceInfo && baseInterfaceInfo->isValue)) + { + auto baseName = baseInterfaceInfo ? baseInterfaceInfo->name.str() + : MLIRHelper::getName(extendsType->expression.as()); + emitError(loc(extendsType)) << "@" VALUE_DECORATOR " interface '" << newInterfacePtr->name << "' cannot extend '" + << baseName << "': it is not @" VALUE_DECORATOR; + return mlir::failure(); + } + auto success = false; - mlir::TypeSwitch(ifaceType.getType()) + auto baseType = baseInterfaceInfo ? mlir::Type(baseInterfaceInfo->interfaceType) : ifaceType.getType(); + mlir::TypeSwitch(baseType) .template Case([&](auto interfaceType) { auto interfaceInfo = getInterfaceInfoByFullName(interfaceType.getName().getValue()); if (interfaceInfo) @@ -1246,6 +1284,19 @@ namespace mlirgen // do not proceed for Generic Interfaces for declaration if (interfaceDeclarationAST->typeParameters.size() > 0 && genContext.typeParamsWithArgs.size() == 0) { + // a value is one layout: each instantiation would be another type to copy + auto isValueInterface = false; + iterateDecorators(interfaceDeclarationAST, genContext, [&](StringRef name, SmallVector args) { + isValueInterface = isValueInterface || name == VALUE_DECORATOR; + }); + if (isValueInterface) + { + emitError(loc(interfaceDeclarationAST)) << "@" VALUE_DECORATOR " interface '" + << MLIRHelper::getName(interfaceDeclarationAST->name) + << "' cannot have type parameters"; + return mlir::failure(); + } + return registerGenericInterface(interfaceDeclarationAST, genContext); } @@ -1313,11 +1364,34 @@ namespace mlirgen } while (notResolved > 0); + // a @value interface is laid out in its declaration order, the order its fields are listed in + // whichever pass resolved each: `thing: Thing` resolved a pass after `d` (Thing declared + // later) would come after it here, and before it in a module that saw Thing first + if (newInterfacePtr->isValue) + { + llvm::SmallVector declared; + for (auto &interfaceMember : interfaceDeclarationAST->members) + { + if ((SyntaxKind)interfaceMember == SyntaxKind::PropertySignature) + { + declared.push_back(TupleFieldName(interfaceMember.as()->name, ifaceGenContext)); + } + } + + auto position = [&](const InterfaceFieldInfo &field) { + return std::distance(declared.begin(), llvm::find(declared, field.id)); + }; + std::stable_sort(newInterfacePtr->fields.begin(), newInterfacePtr->fields.end(), + [&](const InterfaceFieldInfo &a, const InterfaceFieldInfo &b) { return position(a) < position(b); }); + } + // fix up vtable slot numbers to the canonical methods-then-fields order now that // all members are known - see assignCanonicalVirtualIndexes() for why this can't // be left to getVirtualTable()'s per-cast assignment alone. newInterfacePtr->assignCanonicalVirtualIndexes(); + newInterfacePtr->membersResolved = true; + // add to export if any if (auto hasExport = getExportModifier(interfaceDeclarationAST)) { @@ -1351,6 +1425,14 @@ namespace mlirgen return mlir::failure(); } + // `f?: T` of a @value type is read as the one optional every missing T is + // (MLIRTypeHelper::getMissingValueType), which is how a class's or a literal's `f?: T` stores it: + // the slot is that field, read as it is, null and undefined apart + if (isConditional && isa(type)) + { + type = getOptionalType(type); + } + auto fieldIndex = newInterfacePtr->getFieldIndex(fieldId); if (fieldIndex == -1) { @@ -1388,6 +1470,15 @@ namespace mlirgen MLIRCodeLogic mcl(builder, compileOptions); SyntaxKind kind = interfaceMember; + + // a @value interface is a value of its fields, with no vtable: a method, an accessor or a + // signature would have nothing to be called through + if (newInterfacePtr->isValue && kind != SyntaxKind::PropertySignature) + { + emitError(location) << "@" VALUE_DECORATOR " interface '" << newInterfacePtr->name << "' can only have fields"; + return mlir::failure(); + } + if (kind == SyntaxKind::PropertySignature) { // property declaration @@ -1396,6 +1487,24 @@ namespace mlirgen fieldId = TupleFieldName(propertySignature->name, genContext); + // a field a @value value could change would make its copies differ + if (newInterfacePtr->isValue && !hasModifier(propertySignature, SyntaxKind::ReadonlyKeyword)) + { + emitError(location) << "field '" << MLIRHelper::getName(propertySignature->name) << "' of @" VALUE_DECORATOR + << " interface '" << newInterfacePtr->name << "' must be readonly"; + return mlir::failure(); + } + + // ...and a field it could leave out has no slot in it + if (newInterfacePtr->isValue && isConditional) + { + emitError(location) << "field '" << MLIRHelper::getName(propertySignature->name) << "' of @" VALUE_DECORATOR + << " interface '" << newInterfacePtr->name << "' cannot be optional"; + return mlir::failure(); + } + + auto layoutField = valueLayoutField(newInterfacePtr->isValue, newInterfacePtr->fullName, newInterfacePtr->name, + location, MLIRHelper::getName(propertySignature->name)); auto [type, init, typeProvided] = getTypeAndInit(propertySignature, genContext); if (!type) { diff --git a/tslang/lib/TypeScript/MLIRGenModule.cpp b/tslang/lib/TypeScript/MLIRGenModule.cpp index c95c71414..0ba0d13c5 100644 --- a/tslang/lib/TypeScript/MLIRGenModule.cpp +++ b/tslang/lib/TypeScript/MLIRGenModule.cpp @@ -1554,7 +1554,7 @@ namespace mlirgen declSymbol.starts_with(std::string(SHARED_LIB_DECLARATIONS_2UNDERSCORE) + "_generic_"); auto importData = convertUTF8toWide(dataPtr); - if (mlir::failed(parsePartialStatements(importData, genContext, false, !isGenericClassDecl))) + if (mlir::failed(parsePartialStatements(importData, genContext, false, !isGenericClassDecl, true))) { //assert(false); return mlir::failure(); diff --git a/tslang/lib/TypeScript/MLIRGenTypes.cpp b/tslang/lib/TypeScript/MLIRGenTypes.cpp index 9f1bff46d..6dc2ec47f 100644 --- a/tslang/lib/TypeScript/MLIRGenTypes.cpp +++ b/tslang/lib/TypeScript/MLIRGenTypes.cpp @@ -682,6 +682,15 @@ namespace mlirgen return expandTypeAlias(location, name, [&]() { return getType(typeNode, genericTypeGenContext); }); } + // A field of a @value type naming a generic whose instantiation fails - a type argument that is a + // @value type not laid out yet (`box: Box`, `box: Box` with K declared later), or not + // declared yet, or not at all (`Box`): the generic type itself, unspecialized, would + // become the field's type - for good, as the value's layout. The field fails instead and is + // typed again in the next pass (noteValueLayoutWait); one that never resolves is reported. The + // generic's own declaration, specialized, is not the field (suspendValueLayoutFrames). + auto inValueLayout = !valueLayoutFrames.empty(); + auto valueLayoutArgs = valueLayoutGenericArgs(typeReferenceAST); + if (auto genericClassTypeInfo = lookupGenericClassesMap(name)) { auto classType = genericClassTypeInfo->classType; @@ -692,7 +701,7 @@ namespace mlirgen return specType; } - return classType; + return inValueLayout ? mlir::Type() : classType; } if (auto genericInterfaceTypeInfo = lookupGenericInterfacesMap(name)) @@ -705,7 +714,7 @@ namespace mlirgen return specType; } - return interfaceType; + return inValueLayout ? mlir::Type() : interfaceType; } return mlir::Type(); @@ -802,7 +811,7 @@ namespace mlirgen } auto argName = MLIRHelper::getName(typeArg.as()->typeName); - return circularTypeAliases.contains(argName); + return circularTypeAliases.contains(argName) || valueTypesHoldingThemselves.contains(argName); }); if (!argumentIsCircular) { @@ -1860,7 +1869,8 @@ namespace mlirgen return mth.getFieldNames(type); } - if (auto tupleType = dyn_cast(type)) + // a @value value's keys are its fields' + if (isa(type)) { return mth.getFieldNames(type); } @@ -2034,7 +2044,7 @@ namespace mlirgen } // TODO: sync it with mth.getFields - if (auto tupleType = dyn_cast(type)) + if (isa(type)) { return mth.getFieldTypeByIndexType(type, indexType); } @@ -3475,7 +3485,11 @@ namespace mlirgen // an intersection type's own `{ ... }` member (e.g. `F1 & F2 & { c: number }`'s `c`), // masked only because getVirtualTable() used to overwrite virtualIndex as a side effect // of every cast - see docs/interface-vtable-simplification-design.md §4. - dest->fields.push_back({item.id, item.type, item.isConditional || conditional, 0, dest->getNextVTableMemberIndex()}); + // an optional member of a @value type is read as the optional value every missing T is + // (mlirGenInterfaceAddFieldMember) + auto isConditional = item.isConditional || conditional; + auto type = isConditional && isa(item.type) ? getOptionalType(item.type) : item.type; + dest->fields.push_back({item.id, type, isConditional, 0, dest->getNextVTableMemberIndex()}); } return mlir::success(); @@ -3537,6 +3551,12 @@ namespace mlirgen return type; } + // `v?: T` of a @value type is the one optional value every missing T is + if (auto valueType = dyn_cast(type)) + { + return mth.getMissingValueType(valueType); + } + return mlir_ts::OptionalType::get(type); } diff --git a/tslang/lib/TypeScript/MLIRGenVariables.cpp b/tslang/lib/TypeScript/MLIRGenVariables.cpp index f7270cdf1..6074cfe84 100644 --- a/tslang/lib/TypeScript/MLIRGenVariables.cpp +++ b/tslang/lib/TypeScript/MLIRGenVariables.cpp @@ -1301,6 +1301,13 @@ namespace mlirgen return mlir::Type(); } + // a @value class is a value of its fields; used as a value (`V.plus`), its name is still + // the class (resolveIdentifier), whose statics are as any class's + if (classInfo->isValue) + { + return getValueTypeOfClassIfLaidOut(classInfo); + } + return classInfo->classType; } @@ -1320,6 +1327,12 @@ namespace mlirgen return mlir::Type(); } + // a @value interface is a value of its fields, not a reference seen through a vtable + if (interfaceInfo->isValue) + { + return getValueTypeOfInterfaceIfLaidOut(interfaceInfo); + } + return interfaceInfo->interfaceType; } @@ -1345,12 +1358,22 @@ namespace mlirgen auto classInfo = getClassInfoByFullName(fullName); if (classInfo) { + if (classInfo->isValue) + { + return getValueTypeOfClassIfLaidOut(classInfo); + } + return classInfo->classType; } auto interfaceInfo = getInterfaceInfoByFullName(fullName); if (interfaceInfo) { + if (interfaceInfo->isValue) + { + return getValueTypeOfInterfaceIfLaidOut(interfaceInfo); + } + return interfaceInfo->interfaceType; } } @@ -1396,7 +1419,7 @@ namespace mlirgen } } - if (!isEmbededType(name) && !circularTypeAliases.contains(name)) + if (!isEmbededType(name) && !circularTypeAliases.contains(name) && !valueTypesHoldingThemselves.contains(name)) emitError(location, "can't find type by name: ") << name; return mlir::Type(); @@ -1470,6 +1493,19 @@ namespace mlirgen } auto type = resolveTypeByNameInNamespace(location, name, genContext); + + // as a value, a @value class's name is the class (`V.plus`, `new V()`), as any class's is - + // before its fields are laid out too, when it has no type yet + if (auto valueClassInfo = getValueClassInfo(type)) + { + type = valueClassInfo->classType; + } + else if (auto classInfo = !type && getClassesMap().count(name) ? getClassesMap().lookup(name) : ClassInfo::TypePtr(); + classInfo && classInfo->isValue && classInfo->classType) + { + type = classInfo->classType; + } + if (type) { if (auto classType = dyn_cast(type)) diff --git a/tslang/lib/TypeScript/OwnershipFacts.h b/tslang/lib/TypeScript/OwnershipFacts.h index 7b461da4c..dcf2b89af 100644 --- a/tslang/lib/TypeScript/OwnershipFacts.h +++ b/tslang/lib/TypeScript/OwnershipFacts.h @@ -43,6 +43,17 @@ namespace mlir_ts = mlir::typescript; // the box's release (its interface's tag, OWN_RECORD_BORROWED_FIELDS_ATTR_NAME) frees only the // fields the record owns. #define OWN_RESULT_RECORD_ATTR_NAME "__own_result_record" +// Beside OWN_RESULT_RECORD_ATTR_NAME: the record is unboxed - a tuple value (`@value` or a type +// literal), not a box - and owns nothing: every field that holds a block borrows it. The caller owns +// nothing it gets back; the record is bounded by the arguments named as a boxed one is, and its +// releases, and those of the locals that hold it, give nothing back (spec 36). +#define OWN_RESULT_RECORD_UNBOXED_ATTR_NAME "__own_result_record_unboxed" +// On the local an object literal of tuple type is built in, when it is an unboxed borrowing record +// (OWN_RESULT_RECORD_UNBOXED_ATTR_NAME): the fields it borrows. +#define OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME "__own_record_unboxed_fields" +// ...beside it, when the record is a temporary (only given to calls that do not keep it, and read): a +// fresh value it holds keeps its own owner, the temporary's release, and the record borrows it too. +#define OWN_RECORD_TEMPORARY_ATTR_NAME "__own_record_temporary" // The callee destroys nothing its caller can reach: no overwrite of a place it did not make, no // assignment of a global, no call that may. #define OWN_NO_DROPS_ATTR_NAME "__own_no_drops" @@ -176,6 +187,13 @@ inline bool isRecordResult(mlir::Operation *op) return op && op->hasAttr(OWN_RESULT_RECORD_ATTR_NAME) && op->hasAttr(OWN_RESULT_BORROWS_ATTR_NAME); } +// A result that is an unboxed borrowing record (OWN_RESULT_RECORD_UNBOXED_ATTR_NAME): a tuple that owns +// nothing, bounded by the arguments it borrows. +inline bool isUnboxedRecordResult(mlir::Operation *op) +{ + return isRecordResult(op) && op->hasAttr(OWN_RESULT_RECORD_UNBOXED_ATTR_NAME); +} + // The argument a call's result is a plain borrow of, or -1: none, or a borrowing record, which the // caller owns (isRecordResult). Kept beside resultBorrowsAll for the plain borrow, which names one. inline int resultBorrows(mlir::Operation *op) @@ -213,6 +231,67 @@ inline bool holdsAsIs(mlir::Type wide, mlir::Type narrow, bool onlyNullable = fa })); } +// A `@value` type is laid out as its storage tuple, and to these passes it is that tuple (the casts +// between the two lower to nothing): the tuple for a value type, the type itself for any other. +inline mlir::Type asStorageTuple(mlir::Type type) +{ + if (auto valueType = mlir::dyn_cast_or_null(type)) + { + return valueType.getStorageType(); + } + + return type; +} + +// A reference to a `@value` value seen as a reference to its storage tuple, or the other way round: +// the same storage (`ts.Cast` of `this`, or of a local, before a field is reached). +inline bool isValueStorageRefCast(mlir::Operation *op) +{ + auto castOp = mlir::dyn_cast_or_null(op); + auto in = castOp ? mlir::dyn_cast(castOp.getIn().getType()) : mlir_ts::RefType(); + auto out = castOp ? mlir::dyn_cast(castOp.getType()) : mlir_ts::RefType(); + return in && out && in != out && asStorageTuple(in.getElementType()) == asStorageTuple(out.getElementType()); +} + +// The local a reference is, seen through a cast of a `@value` local to its storage tuple (or back). +inline mlir_ts::VariableOp slotVariableOf(mlir::Value ref) +{ + if (isValueStorageRefCast(ref.getDefiningOp())) + { + ref = ref.getDefiningOp()->getOperand(0); + } + + return ref.getDefiningOp(); +} + +// The values stored into a local as a whole: through the local, or through it seen as its storage +// tuple (a `@value` local). +inline llvm::SmallVector valuesStoredInto(mlir_ts::VariableOp varOp) +{ + llvm::SmallVector refs{varOp.getResult()}; + for (auto *user : varOp->getUsers()) + { + if (isValueStorageRefCast(user)) + { + refs.push_back(user->getResult(0)); + } + } + + llvm::SmallVector values; + for (auto ref : refs) + { + for (auto *user : ref.getUsers()) + { + if (auto storeOp = mlir::dyn_cast(user); storeOp && storeOp.getReference() == ref) + { + values.push_back(storeOp.getValue()); + } + } + } + + return values; +} + // An op whose result is the very block its operand holds: a class widened to a union or an // optional or narrowed back, a union made from its payload or read back from it, an object seen // through an interface (`{vtable, this}`, released through `this`), and an interface seen as @@ -256,8 +335,15 @@ inline bool isView(mlir::Operation *op) auto out = castOp.getType(); auto isNullableView = (isStringOrArray(in) && holdsAsIs(out, in, false)) || (isStringOrArray(out) && holdsAsIs(in, out, true)); + // a `@value` value seen as the tuple it is laid out as, or a tuple seen as the value: the same + // tuple (the cast lowers to nothing) + auto isValueStorage = [](mlir::Type value, mlir::Type tuple) { + auto valueType = mlir::dyn_cast(value); + return valueType && valueType.getStorageType() == tuple; + }; - return (keeps(in) && keeps(out)) || (isClosure(in) && isClosure(out)) || isMadeObject() || isNullableView; + return (keeps(in) && keeps(out)) || (isClosure(in) && isClosure(out)) || isMadeObject() || isNullableView || + isValueStorage(in, out) || isValueStorage(out, in); } // The block a value is a view of. @@ -1428,14 +1514,32 @@ inline llvm::ArrayRef recordBorrowedFields(mlir::Operation *op) return {}; } +// The fields the unboxed borrowing record built in `varOp` borrows (OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME); +// empty for any other local. +inline llvm::ArrayRef unboxedRecordFields(mlir_ts::VariableOp varOp) +{ + if (auto attr = varOp ? varOp->getAttrOfType(OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME) : nullptr) + { + return attr.asArrayRef(); + } + + return {}; +} + // A store into a field of a borrowing record that the record borrows: it takes nothing. inline bool isBorrowedRecordFieldStore(mlir::Operation *op) { auto storeOp = mlir::dyn_cast(op); auto propertyRefOp = storeOp ? storeOp.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); auto varOp = propertyRefOp ? propertyRefOp.getObjectRef().getDefiningOp() : mlir_ts::VariableOp(); + auto position = propertyRefOp ? static_cast(propertyRefOp.getPosition()) : -1; + if (llvm::is_contained(unboxedRecordFields(varOp), position)) + { + return true; + } + auto boxOp = varOp ? recordBoxOfLocal(varOp) : mlir_ts::NewOp(); - return boxOp && llvm::is_contained(recordBorrowedFields(boxOp), static_cast(propertyRefOp.getPosition())); + return boxOp && llvm::is_contained(recordBorrowedFields(boxOp), position); } // The tuple an object, a reference or a tuple value of this type stores its fields in; null for @@ -1460,7 +1564,7 @@ inline mlir_ts::TupleType storageTupleOf(mlir::MLIRContext *context, mlir::Type type = valueRefType.getElementType(); } - return mlir::dyn_cast(type); + return mlir::dyn_cast(asStorageTuple(type)); } // (tuple type, field) -> the one function an object of that type holds in that field: every diff --git a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp index 36b48de93..33a6a9004 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceClosures.cpp @@ -891,6 +891,20 @@ namespace own_inference } else if (!isLoadedCell(value)) { + // a local of this frame, or storage a parameter refers to (`this` of a @value + // constructor, the slot its `new` made), that holds no block - its fields are + // numbers: the closure, which does not escape, reads storage that lives as + // long as this call, and nothing in it can be freed + auto elementType = mlir::cast(value.getType()).getElementType(); + auto argument = mlir::dyn_cast(value); + auto frameStorage = value.getDefiningOp() || + (argument && argument.getOwner()->isEntryBlock() && + mlir::isa(argument.getOwner()->getParentOp())); + if (frameStorage && !ownsHeap(value.getLoc(), elementType)) + { + continue; + } + reportCaptureNotOwned(fill.second, captured); ok = false; continue; diff --git a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp index f913bbf25..03c2aa91b 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceDiagnostics.cpp @@ -162,7 +162,7 @@ namespace own_inference { id = storageType.getId(position); } - else if (auto tupleType = mlir::dyn_cast(type); tupleType && position < tupleType.size()) + else if (auto tupleType = mlir::dyn_cast(asStorageTuple(type)); tupleType && position < tupleType.size()) { id = tupleType.getId(position); } diff --git a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp index 9f2ce51d6..58ef47d38 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceMoves.cpp @@ -124,65 +124,58 @@ namespace own_inference mlir::Operation *retain = nullptr; auto boxed = false; auto other = false; - for (auto *user : read->getUsers()) - { - if (mlir::isa(user)) + auto bad = false; + // the read and its views (a `@value` value seen as its tuple, or the other way round) + forEachUse(read.getResult(), [&](mlir::Operation *user, mlir::Value used) { + if (bad) { - if (retain) - { - return nullptr; - } + return; + } + if (mlir::isa(user)) + { + bad = retain != nullptr; retain = user; - continue; + return; } // copied into the block it is given in as an object or an interface (spec 27): the box // owns what the record held, and its own check decides where the box goes auto storeOp = mlir::dyn_cast(user); - auto box = storeOp && storeOp.getValue() == read.getResult() ? recordBoxOf(storeOp.getReference()) - : mlir_ts::NewOp(); + auto box = storeOp && storeOp.getValue() == used ? recordBoxOf(storeOp.getReference()) : mlir_ts::NewOp(); if (box && box.getResult() == storeOp.getReference()) { - if (boxed) - { - return nullptr; - } - + bad = boxed; boxed = true; - continue; + return; } other = true; if (mlir::isa(user)) { - continue; + return; } // `let a = { item: new C() }`: the read is what an owning local starts with, and rc's // `ts.RetainSlot` of that local is the record's retain if (auto ownerOp = mlir::dyn_cast(user)) { - auto *slotRetain = ownerOp.getInitializer() == read.getResult() && isOwningVariable(ownerOp) - ? onlyRetainSlotOf(ownerOp) - : nullptr; - if (!slotRetain || retain) - { - return nullptr; - } - + auto *slotRetain = ownerOp.getInitializer() == used && isOwningVariable(ownerOp) ? onlyRetainSlotOf(ownerOp) + : nullptr; + bad = !slotRetain || retain; retain = slotRetain; - continue; + return; } // stored into the result slot, or into an owning local (`a = { item: new C() }`) - auto slot = storeOp && storeOp.getValue() == read.getResult() - ? storeOp.getReference().getDefiningOp() - : mlir_ts::VariableOp(); - if (!slot || !(isResultSlot(slot) || isOwningVariable(slot))) - { - return nullptr; - } + auto slot = storeOp && storeOp.getValue() == used ? storeOp.getReference().getDefiningOp() + : mlir_ts::VariableOp(); + bad = !slot || !(isResultSlot(slot) || isOwningVariable(slot)); + }); + + if (bad) + { + return nullptr; } // a boxed record goes nowhere else: the box is its one owner @@ -696,6 +689,12 @@ namespace own_inference bool OwnershipInferencePass::fieldOnlyRead(mlir::Operation *extract, llvm::SmallVectorImpl &reads) { auto onlyRead = true; + if (holdsNoBlock(extract->getResult(0))) + { + reads.push_back(extract); + return true; + } + forEachUse(extract->getResult(0), [&](mlir::Operation *user, mlir::Value used) { if (mlir::isa(user)) { @@ -717,6 +716,12 @@ namespace own_inference void OwnershipInferencePass::fieldTakersOf(mlir::Operation *extract, llvm::SmallVectorImpl &takers) { + // a number taken out takes nothing of the record: `print(h.dist)` converts it to a string + if (holdsNoBlock(extract->getResult(0))) + { + return; + } + forEachUse(extract->getResult(0), [&](mlir::Operation *user, mlir::Value used) { if (mlir::isa(user)) { diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.cpp b/tslang/lib/TypeScript/OwnershipInferencePass.cpp index e174204f5..2ae1d0824 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.cpp +++ b/tslang/lib/TypeScript/OwnershipInferencePass.cpp @@ -118,6 +118,8 @@ namespace own_inference // a handle's retains and releases are rc's, and stay (spec 23.2) toErase.remove_if([](mlir::Operation *op) { return touchesHandle(op); }); placeEdgeReleases(); + // what owns nothing gives nothing back, wherever the moves put its releases (spec 36) + dropUnboxedRecordCounts(toErase); for (auto *op : toErase) { op->erase(); @@ -274,6 +276,13 @@ namespace own_inference llvm::DenseSet proven; for (auto value : ops.candidates) { + // a tuple that owns nothing has no owner to find: copies of it are free, and what it + // borrows bounds every use of it (spec 36) + if (unboxedRecordFlow(value) == UnboxedFlow::Unboxed) + { + continue; + } + if (checkValueMoves(value, toErase) && isFresh(value)) { proven.insert(value); @@ -331,6 +340,13 @@ namespace own_inference continue; // decided already: a `let` that borrows a field of a record (checkValueMoves) } + // a tuple that owns nothing takes nothing (spec 36) + if (auto value = retainedValue(op); value && unboxedRecordFlow(value) == UnboxedFlow::Unboxed) + { + toErase.insert(op); + continue; + } + // a retain of what holds no block takes nothing: a union's number payload made into // another union is a view of the union it came from, but a number all the way if (auto retainOp = mlir::dyn_cast(op); retainOp && holdsNoBlock(retainOp.getReference())) @@ -465,7 +481,8 @@ namespace own_inference returnedParams.clear(); getFunction().walk([](mlir::Operation *op) { for (auto *name : {OWN_PARAMS_ATTR_NAME, OWN_PARAMS_RELEASED_ATTR_NAME, OWN_RESULT_BORROWS_ATTR_NAME, - OWN_RESULT_RECORD_ATTR_NAME, + OWN_RESULT_RECORD_ATTR_NAME, OWN_RESULT_RECORD_UNBOXED_ATTR_NAME, + OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME, OWN_RECORD_TEMPORARY_ATTR_NAME, OWN_NO_DROPS_ATTR_NAME, OWN_FACTS_LOST_ATTR_NAME, OWN_FRESH_RESULT_ATTR_NAME, OWN_ASSIGNS_CAPTURES_ATTR_NAME, OWN_RESULT_BOUNDED_ATTR_NAME, diff --git a/tslang/lib/TypeScript/OwnershipInferencePass.h b/tslang/lib/TypeScript/OwnershipInferencePass.h index edd683081..9f8724d50 100644 --- a/tslang/lib/TypeScript/OwnershipInferencePass.h +++ b/tslang/lib/TypeScript/OwnershipInferencePass.h @@ -554,9 +554,11 @@ class OwnershipInferencePass struct BorrowingRecord { + // null for an unboxed record (spec 36), whose `reads` of `local` are the record mlir_ts::NewOp box; mlir_ts::VariableOp local; llvm::SmallVector interfaces; + llvm::SmallVector reads; llvm::SmallVector borrowed; RecordWalk walk; }; @@ -602,6 +604,30 @@ class OwnershipInferencePass // its own (checkPlaceRead). void checkBorrowingRecords(); + // ---- Unboxed records (spec 36) ---- + // + // A tuple that holds borrows and owns nothing (OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME where it is made, + // OWN_RESULT_RECORD_UNBOXED_ATTR_NAME on a call that returns one) is a record the way a box is - its + // uses bounded by what it borrows, moved into the locals that hold it - but there is nothing to give + // back: rc's retains and releases of it, and of the locals that hold only such records (or nothing + // at all), are erased, whatever the moves decided. + enum class UnboxedFlow + { + None, // no unboxed record + Unboxed, // unboxed records only, or values that hold no block + Mixed // an unboxed record beside a value that owns a block + }; + + // What `value` is, through its views, merges and the owning locals that hold it. + UnboxedFlow unboxedRecordFlow(mlir::Value value); + + // ...and what an owning local holds: its initializer and every value stored into it. + UnboxedFlow unboxedRecordSlotFlow(mlir_ts::VariableOp varOp); + + // Erases the counting of every unboxed record; a local or a merge that holds one beside a value it + // owns is an error (its release could not tell them apart). + void dropUnboxedRecordCounts(llvm::SetVector &toErase); + // A call whose result is a borrowing record (OWN_RESULT_RECORD_ATTR_NAME, spec 32): the box is // this function's to own - it is fresh, and its own check decides its moves and releases - but // it may hold a borrow of each argument the facts name, as a call's result that borrows them diff --git a/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp b/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp index 51c66ccd6..24130ae57 100644 --- a/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp +++ b/tslang/lib/TypeScript/OwnershipInferenceRecords.cpp @@ -101,6 +101,261 @@ namespace own_inference records.push_back(std::move(record)); }); + + // an unboxed record (spec 36): the tuple read out of the local it is built in is the record, and + // every field of it that holds a block borrows + getFunction().walk([&](mlir_ts::VariableOp varOp) { + auto fields = unboxedRecordFields(varOp); + if (fields.empty() || !isConstantRecordLocal(varOp)) + { + return; + } + + auto record = std::make_shared(); + record->local = varOp; + llvm::SmallVector reads; + for (auto *user : varOp->getUsers()) + { + if (auto loadOp = mlir::dyn_cast(user)) + { + reads.push_back(loadOp.getResult()); + continue; + } + + auto propertyRefOp = mlir::dyn_cast(user); + if (!propertyRefOp) + { + continue; + } + + auto borrows = llvm::is_contained(fields, static_cast(propertyRefOp.getPosition())); + for (auto *fieldUser : propertyRefOp->getUsers()) + { + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != propertyRefOp.getResult()) + { + continue; + } + + auto source = recordFieldSource(storeOp.getValue()); + if (source == RecordFieldSource::NoBlock) + { + continue; + } + + // it owns nothing: a fresh value is a temporary's it borrows (the signature pass + // marked only those), and a field it would own is not what it was marked for + if (source == RecordFieldSource::Unknown || !borrows || + (source == RecordFieldSource::Fresh && !varOp->hasAttr(OWN_RECORD_TEMPORARY_ATTR_NAME))) + { + return; + } + + record->borrowed.push_back({storeOp, source}); + } + } + + record->reads = reads; + llvm::SmallVector kills{varOp.getOperation()}; + walkRecord(reads, kills, record->walk); + for (auto &field : record->borrowed) + { + setAttrTracked(field.store, OWN_CAPTURE_BORROW_ATTR_NAME); + recordStoreUses[field.store.getOperation()] = record.get(); + } + + records.push_back(std::move(record)); + }); + } + + OwnershipInferencePass::UnboxedFlow OwnershipInferencePass::unboxedRecordFlow(mlir::Value value) + { + llvm::SmallVector work{value}; + llvm::SmallPtrSet seen; + llvm::SmallPtrSet slots; + auto unboxed = false; + auto other = false; + while (!work.empty()) + { + auto next = work.pop_back_val(); + auto current = rootOf(next); + if (!seen.insert(current).second || holdsNoBlock(next) || holdsNoBlock(current)) + { + continue; + } + + auto *def = current.getDefiningOp(); + if (def && isCall(def)) + { + (isUnboxedRecordResult(def) ? unboxed : other) = true; + continue; + } + + if (auto argument = mlir::dyn_cast(current)) + { + llvm::SmallVector merged; + if (mergedInto(argument, merged)) + { + work.append(merged.begin(), merged.end()); + continue; + } + + other = true; + continue; + } + + auto loadOp = mlir::dyn_cast_or_null(def); + auto varOp = loadOp ? slotVariableOf(loadOp.getReference()) : mlir_ts::VariableOp(); + if (varOp && !unboxedRecordFields(varOp).empty()) + { + unboxed = true; + continue; + } + + // what an owning local holds: its initializer and every value stored into it + if (varOp && isOwningVariable(varOp) && !varOp.getCaptured().value_or(false)) + { + if (!slots.insert(varOp).second) + { + continue; + } + + if (varOp.getInitializer()) + { + work.push_back(varOp.getInitializer()); + } + + for (auto stored : valuesStoredInto(varOp)) + { + work.push_back(stored); + } + + continue; + } + + other = true; + } + + if (!unboxed) + { + return UnboxedFlow::None; + } + + return other ? UnboxedFlow::Mixed : UnboxedFlow::Unboxed; + } + + OwnershipInferencePass::UnboxedFlow OwnershipInferencePass::unboxedRecordSlotFlow(mlir_ts::VariableOp varOp) + { + if (!isOwningVariable(varOp) || varOp.getCaptured().value_or(false)) + { + return UnboxedFlow::None; + } + + // a read of the local, as unboxedRecordFlow follows one; a local never read is asked through a + // load made for the question + for (auto *user : varOp->getUsers()) + { + if (auto loadOp = mlir::dyn_cast(user)) + { + return unboxedRecordFlow(loadOp.getResult()); + } + } + + llvm::SmallVector values; + if (varOp.getInitializer()) + { + values.push_back(varOp.getInitializer()); + } + + for (auto stored : valuesStoredInto(varOp)) + { + values.push_back(stored); + } + + auto flow = UnboxedFlow::None; + auto other = false; + for (auto stored : values) + { + switch (unboxedRecordFlow(stored)) + { + case UnboxedFlow::Mixed: + return UnboxedFlow::Mixed; + case UnboxedFlow::Unboxed: + flow = UnboxedFlow::Unboxed; + break; + case UnboxedFlow::None: + other = other || !holdsNoBlock(stored); + break; + } + } + + return flow == UnboxedFlow::Unboxed && other ? UnboxedFlow::Mixed : flow; + } + + void OwnershipInferencePass::dropUnboxedRecordCounts(llvm::SetVector &toErase) + { + llvm::SmallPtrSet reported; + auto mixed = [&](mlir::Operation *op, mlir::Operation *at) { + if (reported.insert(at).second && reporting()) + { + op->emitError("a value that borrows what it holds and owns nothing (a tuple that holds a borrow) meets " + "a value that owns a block here; -mm=own cannot release them alike"); + signalPassFailure(); + } + }; + + getFunction().walk([&](mlir::Operation *op) { + // a handle's counts are rc's (spec 23.2) + if (touchesHandle(op)) + { + return; + } + + if (mlir::isa(op)) + { + switch (unboxedRecordFlow(op->getOperand(0))) + { + case UnboxedFlow::Unboxed: + toErase.insert(op); + break; + case UnboxedFlow::Mixed: + mixed(op, rootOf(op->getOperand(0)).getDefiningOp() ? rootOf(op->getOperand(0)).getDefiningOp() : op); + break; + case UnboxedFlow::None: + break; + } + + return; + } + + mlir::Value slot; + if (auto retainSlotOp = mlir::dyn_cast(op)) + { + slot = retainSlotOp.getSlot(); + } + else if (auto releaseSlotOp = mlir::dyn_cast(op)) + { + slot = releaseSlotOp.getSlot(); + } + + auto varOp = slot ? slotVariableOf(slot) : mlir_ts::VariableOp(); + if (!varOp) + { + return; + } + + switch (unboxedRecordSlotFlow(varOp)) + { + case UnboxedFlow::Unboxed: + toErase.insert(op); + break; + case UnboxedFlow::Mixed: + mixed(op, varOp); + break; + case UnboxedFlow::None: + break; + } + }); } void OwnershipInferencePass::walkRecord(llvm::ArrayRef starts, llvm::ArrayRef kills, RecordWalk &walk) @@ -120,19 +375,66 @@ namespace own_inference } }; + auto keep = [&](mlir::Operation *user) { walk.kept = walk.kept ? walk.kept : user; }; + auto followSlot = [&](mlir_ts::VariableOp varOp, bool record) { + // the local, and the local seen as its storage tuple (a `@value` local) + llvm::SmallVector refs{varOp.getResult()}; for (auto *slotUser : varOp->getUsers()) + { + if (isValueStorageRefCast(slotUser)) + { + refs.push_back(slotUser->getResult(0)); + } + } + + llvm::SmallVector slotUsers; + for (auto ref : refs) + { + slotUsers.append(ref.getUsers().begin(), ref.getUsers().end()); + } + + for (auto *slotUser : slotUsers) { // its releases and its other values are the slot's own if (auto loadOp = mlir::dyn_cast(slotUser)) { push(loadOp.getResult(), record); + continue; + } + + // a field of a record that is a tuple, read in place out of the local that holds it + // (spec 36): a read of the record, and what it reads is what the record borrows. A + // write of the field would release what the record borrows. + auto propertyRefOp = mlir::dyn_cast(slotUser); + if (!record || !propertyRefOp || !llvm::is_contained(refs, propertyRefOp.getObjectRef())) + { + continue; + } + + walk.uses.push_back({propertyRefOp, {kills.begin(), kills.end()}}); + for (auto *fieldUser : propertyRefOp->getUsers()) + { + walk.uses.push_back({fieldUser, {kills.begin(), kills.end()}}); + if (auto fieldLoad = mlir::dyn_cast(fieldUser)) + { + push(fieldLoad.getResult(), mayPointInto(fieldLoad.getResult())); + } + else if (mlir::isa(fieldUser)) + { + keep(fieldUser); + } + else + { + for (auto result : fieldUser->getResults()) + { + push(result, false); + } + } } } }; - auto keep = [&](mlir::Operation *user) { walk.kept = walk.kept ? walk.kept : user; }; - for (auto start : starts) { push(start, true); @@ -235,6 +537,14 @@ namespace own_inference continue; } + // a field read out of a record that is a tuple (spec 36): what it borrows, or nothing, + // and its keeps are the record's + if (pending.record && mlir::isa(user)) + { + push(user->getResult(0), mayPointInto(user->getResult(0))); + continue; + } + if (pending.record && !isBorrow(user, value)) { keep(user); @@ -298,6 +608,8 @@ namespace own_inference return quoted(varName(slotLoadOf(value).getReference().getDefiningOp())); case RecordFieldSource::Cell: return "a captured variable"; + case RecordFieldSource::Fresh: + return "a temporary"; default: return "a value it does not own"; } @@ -307,7 +619,10 @@ namespace own_inference { for (auto &record : records) { - auto name = recordName(record->interfaces.empty() ? record->box.getResult() : record->interfaces.front()); + auto name = recordName(!record->interfaces.empty() ? record->interfaces.front() + : record->box ? record->box.getResult() + : !record->reads.empty() ? record->reads.front() + : record->local.getResult()); if (record->walk.kept) { reportPlaceBorrowEscapes(record->walk.kept, name, @@ -359,6 +674,11 @@ namespace own_inference { chain.roots.push_back({rootOf(value), Chain::NotOwned}); } + else if (field.source == RecordFieldSource::Fresh) + { + // a temporary's fresh value an unboxed record borrows (spec 36): its own release + chain.roots.push_back({rootOf(value), Chain::Owned}); + } else { continue; diff --git a/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp b/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp index 39fb5e4a6..2d60b63b5 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureCallbacks.cpp @@ -289,6 +289,7 @@ namespace own_signature { shifted = Facts(); shifted.record = facts.record; + shifted.unboxed = facts.unboxed; for (auto [from, to] : {std::make_pair(&facts.owned, &shifted.owned), std::make_pair(&facts.borrows, &shifted.borrows)}) { for (auto index : *from) @@ -363,6 +364,7 @@ namespace own_signature kept.erase(std::unique(kept.begin(), kept.end()), kept.end()); auto promotable = shiftable && llvm::all_of(seen, [&](const Facts &facts) { return facts.borrows == seen.front().borrows && facts.record == seen.front().record && + facts.unboxed == seen.front().unboxed && llvm::none_of(kept, [&](int32_t index) { return llvm::is_contained(facts.borrows, index); }); }); diff --git a/tslang/lib/TypeScript/OwnershipSignatureClosedWorld.cpp b/tslang/lib/TypeScript/OwnershipSignatureClosedWorld.cpp index 1f94439ee..9170dc91d 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureClosedWorld.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureClosedWorld.cpp @@ -105,7 +105,7 @@ namespace own_signature return llvm::any_of(infos, [&](const mlir_ts::FieldInfo &info) { return holdsFunction(info.type, fields, seen); }); }; - if (auto tupleType = mlir::dyn_cast(type)) + if (auto tupleType = mlir::dyn_cast(asStorageTuple(type))) { return any(tupleType.getFields()); } diff --git a/tslang/lib/TypeScript/OwnershipSignatureInterfaces.cpp b/tslang/lib/TypeScript/OwnershipSignatureInterfaces.cpp index 9d2c1566f..bd5f68adc 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureInterfaces.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureInterfaces.cpp @@ -252,6 +252,7 @@ namespace own_signature } }; + type = asStorageTuple(type); if (auto tupleType = mlir::dyn_cast(type)) { fields(tupleType.getFields()); @@ -336,7 +337,7 @@ namespace own_signature return; } - if (auto tupleType = mlir::dyn_cast(type)) + if (auto tupleType = mlir::dyn_cast(asStorageTuple(type))) { fields(tupleType.getFields()); return; @@ -372,6 +373,7 @@ namespace own_signature } }; + type = asStorageTuple(type); if (auto tupleType = mlir::dyn_cast(type)) { fields(tupleType.getFields()); @@ -579,6 +581,7 @@ namespace own_signature } auto tupleFields = [](mlir::Type type) -> std::optional> { + type = asStorageTuple(type); if (auto tupleType = mlir::dyn_cast(type)) { return tupleType.getFields(); diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp index c86777a50..63427ffc8 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.cpp +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.cpp @@ -446,6 +446,16 @@ namespace own_signature signalPassFailure(); } + else if (!lends.empty() && local.record && local.unboxed && !executable && + (funcOp->hasAttr("export") || funcOp->hasAttr(DLL_EXPORT))) + { + // `@record` tells an importer it owns a box; an unboxed record (spec 36) owns nothing, + // and the importer's release of it would free what it borrows + funcOp.emitError("'") + << funcOp.getSymName() << "' returns a tuple that borrows " << describeParams(funcOp, lends) + << " and owns nothing, which -mm=own cannot tell another module yet"; + signalPassFailure(); + } else if (!lends.empty() && funcOp->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME) != local.record) { // An importer knows the result is a record only from `@record` (spec 32): told a plain @@ -570,6 +580,7 @@ namespace own_signature { auto found = -1; auto record = false; + std::optional unboxed; llvm::SmallVector params; for (auto value : returnedValues(funcOp)) { @@ -584,11 +595,20 @@ namespace own_signature return {}; } - switch (recordParamsOf(value, params)) + auto tuples = false; + switch (recordParamsOf(value, params, &tuples)) { case RecordFlow::Bad: return {}; case RecordFlow::Record: + // a box on one path and a tuple that owns nothing on another: the caller's release of + // the one would be wrong for the other + if (unboxed && *unboxed != tuples) + { + return {}; + } + + unboxed = tuples; record = true; continue; case RecordFlow::None: @@ -613,7 +633,7 @@ namespace own_signature { llvm::sort(params); params.erase(std::unique(params.begin(), params.end()), params.end()); - return {params, true}; + return {params, true, unboxed.value_or(false)}; } if (found >= 0) @@ -806,6 +826,7 @@ namespace own_signature Facts facts; facts.borrows = std::move(result.borrows); facts.record = result.record; + facts.unboxed = result.unboxed; facts.owned = localOwnedParams(entry.second); // what the body takes into something on every path; a parameter it returns on // some paths only is kept too, and released on the others (spec 33) @@ -889,6 +910,7 @@ namespace own_signature said.record = !said.borrows.empty() && (entry.second.isDeclaration() ? entry.second->hasAttr(OWN_DECLARED_RECORD_ATTR_NAME) : local.record && local.borrows == said.borrows); + said.unboxed = said.record && !entry.second.isDeclaration() && local.unboxed; if (factsThroughInterface(entry.second, said)) { continue; @@ -994,6 +1016,7 @@ namespace own_signature auto *context = op->getContext(); op->removeAttr(OWN_RESULT_BORROWS_ATTR_NAME); op->removeAttr(OWN_RESULT_RECORD_ATTR_NAME); + op->removeAttr(OWN_RESULT_RECORD_UNBOXED_ATTR_NAME); op->removeAttr(OWN_PARAMS_ATTR_NAME); if (!facts.borrows.empty()) { @@ -1001,6 +1024,10 @@ namespace own_signature if (facts.record) { op->setAttr(OWN_RESULT_RECORD_ATTR_NAME, mlir::UnitAttr::get(context)); + if (facts.unboxed) + { + op->setAttr(OWN_RESULT_RECORD_UNBOXED_ATTR_NAME, mlir::UnitAttr::get(context)); + } } } diff --git a/tslang/lib/TypeScript/OwnershipSignaturePass.h b/tslang/lib/TypeScript/OwnershipSignaturePass.h index 0139b33e2..d24a5b2c4 100644 --- a/tslang/lib/TypeScript/OwnershipSignaturePass.h +++ b/tslang/lib/TypeScript/OwnershipSignaturePass.h @@ -399,6 +399,8 @@ class OwnershipSignaturePass : public mlir::PassWrapper borrows; llvm::SmallVector owned; bool record = false; + // the record is a tuple that owns nothing (OWN_RESULT_RECORD_UNBOXED_ATTR_NAME) + bool unboxed = false; bool empty() const { @@ -407,7 +409,7 @@ class OwnershipSignaturePass : public mlir::PassWrapper borrows; bool record = false; + bool unboxed = false; }; // What the function's result borrows (spec 2.4, 32): the one parameter every heap value it returns @@ -800,6 +803,8 @@ class OwnershipSignaturePass : public mlir::PassWrapper params; // every borrowed field is a parameter's, `this`'s, a read out of one, or immortal bool returnable = true; + // a tuple built in a local, not boxed, that owns nothing (classifyUnboxedRecord) + bool unboxed = false; }; llvm::DenseMap recordBoxes; @@ -809,6 +814,13 @@ class OwnershipSignaturePass : public mlir::PassWrapper ¶ms); + // arguments are this function's parameters or reads out of them. `unboxed` says whether the + // records are tuples that own nothing (spec 36); boxes and such tuples together are Bad. + RecordFlow recordParamsOf(mlir::Value value, llvm::SmallVectorImpl ¶ms, bool *unboxed = nullptr); // ---- Parameters the callee keeps ---- diff --git a/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp b/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp index 217a1357b..b1eb75dcd 100644 --- a/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp +++ b/tslang/lib/TypeScript/OwnershipSignatureRecords.cpp @@ -26,6 +26,193 @@ namespace own_signature classifyRecordBox(newOp); }); + + getOperation().walk([&](mlir_ts::VariableOp varOp) { + varOp->removeAttr(OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME); + varOp->removeAttr(OWN_RECORD_TEMPORARY_ATTR_NAME); + classifyUnboxedRecord(varOp); + }); + } + + void OwnershipSignaturePass::classifyUnboxedRecord(mlir_ts::VariableOp varOp) + { + // an object literal's local whose read is never boxed: the tuple is the value + if (!isConstantRecordLocal(varOp) || recordBoxOfLocal(varOp)) + { + return; + } + + // the record is its read, the whole tuple; a literal whose fields are read out one by one (to be + // re-made as another tuple) is not one + auto read = false; + for (auto *user : varOp->getUsers()) + { + if (mlir::isa(user)) + { + read = true; + } + else if (llvm::any_of(user->getUsers(), [](mlir::Operation *fieldUser) { + return mlir::isa(fieldUser) && !fieldUser->use_empty(); + })) + { + return; + } + } + + if (!read) + { + return; + } + + // a literal no one takes - its read is only given to calls that do not keep it, and read - is + // a temporary (a call's argument): what it holds keeps its own owner, a fresh value too, whose + // release (the temporary's) bounds the record + auto temporary = true; + for (auto *user : varOp->getUsers()) + { + auto loadOp = mlir::dyn_cast(user); + if (!loadOp) + { + continue; + } + + forEachUse(loadOp.getResult(), [&](mlir::Operation *readUser, mlir::Value used) { + if ((!isCall(readUser) && !mlir::isa(readUser)) || + keeps(readUser, used)) + { + temporary = false; + } + }); + } + + RecordBox info; + info.unboxed = true; + llvm::SmallVector borrowed; + auto mth = typeHelper(&getContext()); + for (auto *user : varOp->getUsers()) + { + auto propertyRefOp = mlir::dyn_cast(user); + if (!propertyRefOp) + { + continue; + } + + auto field = propertyRefOp.getResult(); + auto refType = mlir::dyn_cast(field.getType()); + if (!refType || !mth.ownsHeapMemory(field.getLoc(), refType.getElementType())) + { + continue; + } + + auto borrows = false; + for (auto *fieldUser : field.getUsers()) + { + if (mlir::isa(fieldUser)) + { + continue; + } + + auto storeOp = mlir::dyn_cast(fieldUser); + if (!storeOp || storeOp.getReference() != field) + { + return; + } + + // a handle is counted, never borrowed (spec 23.2) + auto value = storeOp.getValue(); + if (isHandle(value)) + { + return; + } + + // a field of a generator's state, read into the record a yield or `next()` makes: the + // generator's rules decide whether that read moves the value out (findYieldedFields, + // after the facts) or borrows it, not this one + auto stateRead = rootOf(value).getDefiningOp(); + auto stateField = stateRead ? stateRead.getReference().getDefiningOp() : mlir_ts::PropertyRefOp(); + if (auto stateType = stateField ? storageTupleOf(stateField.getObjectRef().getType()) : mlir_ts::TupleType(); + stateType && fieldIndex(stateType, ".step") >= 0) + { + return; + } + + switch (recordFieldSource(value)) + { + case RecordFieldSource::NoBlock: + continue; + // a fresh value the temporary borrows: its own release bounds the record, which + // cannot be returned + case RecordFieldSource::Fresh: + if (!temporary) + { + // a field it would own: the tuple is no borrow (an owning tuple, #679), and + // its release would free the field + return; + } + + info.returnable = false; + borrows = true; + continue; + case RecordFieldSource::Unknown: + return; + case RecordFieldSource::Immortal: + borrows = true; + continue; + case RecordFieldSource::Param: + case RecordFieldSource::Place: + if (auto param = borrowedParam(value); param >= 0) + { + info.params.push_back(param); + } + else + { + info.returnable = false; + } + + borrows = true; + continue; + case RecordFieldSource::Slot: + case RecordFieldSource::Cell: + info.returnable = false; + borrows = true; + continue; + } + } + + // a string is copied, not borrowed (spec 22) + if (borrows && isCopyableString(refType.getElementType())) + { + return; + } + + if (borrows) + { + borrowed.push_back(propertyRefOp.getPosition()); + } + } + + if (borrowed.empty()) + { + return; + } + + llvm::sort(borrowed); + borrowed.erase(std::unique(borrowed.begin(), borrowed.end()), borrowed.end()); + llvm::sort(info.params); + info.params.erase(std::unique(info.params.begin(), info.params.end()), info.params.end()); + + varOp->setAttr(OWN_RECORD_UNBOXED_FIELDS_ATTR_NAME, mlir::DenseI32ArrayAttr::get(&getContext(), borrowed)); + if (temporary) + { + varOp->setAttr(OWN_RECORD_TEMPORARY_ATTR_NAME, mlir::UnitAttr::get(&getContext())); + } + for (auto *user : varOp->getUsers()) + { + if (mlir::isa(user)) + { + recordBoxes[user] = info; + } + } } void OwnershipSignaturePass::classifyRecordBox(mlir_ts::NewOp newOp) @@ -267,12 +454,16 @@ namespace own_signature }); } - OwnershipSignaturePass::RecordFlow OwnershipSignaturePass::recordParamsOf(mlir::Value value, llvm::SmallVectorImpl ¶ms) + OwnershipSignaturePass::RecordFlow OwnershipSignaturePass::recordParamsOf(mlir::Value value, llvm::SmallVectorImpl ¶ms, + bool *unboxed) { llvm::SmallVector work{value}; llvm::SmallPtrSet seen; auto record = false; auto other = false; + // boxes and unboxed records met in one value: their releases differ + auto boxes = false; + auto tuples = false; while (!work.empty()) { // what holds no block, by its own type (a box's `value_ref` owns nothing by type, but @@ -294,11 +485,13 @@ namespace own_signature params.append(found->second.params.begin(), found->second.params.end()); record = true; + (found->second.unboxed ? tuples : boxes) = true; continue; } if (def && isCall(def) && isRecordResult(def)) { + (isUnboxedRecordResult(def) ? tuples : boxes) = true; auto args = callArgs(def); for (auto index : resultBorrowsAll(def)) { @@ -368,7 +561,12 @@ namespace own_signature return RecordFlow::None; } - return other ? RecordFlow::Bad : RecordFlow::Record; + if (unboxed) + { + *unboxed = tuples; + } + + return other || (boxes && tuples) ? RecordFlow::Bad : RecordFlow::Record; } } // namespace own_signature diff --git a/tslang/lib/TypeScript/StackPromotionPass.cpp b/tslang/lib/TypeScript/StackPromotionPass.cpp index 0ff38592c..2a50fc0fe 100644 --- a/tslang/lib/TypeScript/StackPromotionPass.cpp +++ b/tslang/lib/TypeScript/StackPromotionPass.cpp @@ -538,7 +538,8 @@ class StackPromotionPass : public mlir::PassWrapper(type)) + // a @value value is its storage tuple's fields (getOwnershipFieldTypes looks through it) + if (isa(type)) { MLIRTypeHelper mth(&getContext(), compileOptions); bytes = 0; diff --git a/tslang/test/tester/CMakeLists.txt b/tslang/test/tester/CMakeLists.txt index 444b102db..9d2cc70b1 100644 --- a/tslang/test/tester/CMakeLists.txt +++ b/tslang/test/tester/CMakeLists.txt @@ -1589,6 +1589,28 @@ foreach(final_mm gc rc own) tslang_add_test(NAME test-compile-shared-export-import-final-class-${final_mm} COMMAND test-runner -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_final_class.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_final_class.ts") tslang_add_test(NAME test-jit-shared-export-import-final-class-${final_mm} COMMAND test-runner -jit -shared -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_final_class.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_final_class.ts") endforeach() +# @value across the boundary: the importer knows the class and interfaces from __decls (`Hit` +# printed before the `Ray` it holds), builds and reads values of them, and gives them back +foreach(value_mm gc rc own) + tslang_add_test(NAME test-compile-shared-export-import-value-types-${value_mm} COMMAND test-runner -shared -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_value_types.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_value_types.ts") + tslang_add_test(NAME test-jit-shared-export-import-value-types-${value_mm} COMMAND test-runner -jit -shared -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_value_types.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_value_types.ts") +endforeach() +# ...and an imported @value class is nominal: an object literal of its shape is not one +add_test(NAME test-compile-shared-import-value-types-structural + COMMAND test-runner -shared -mm=own "${PROJECT_SOURCE_DIR}/test/tester/tests/import_value_types_structural.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_value_types.ts") +set_tests_properties(test-compile-shared-import-value-types-structural PROPERTIES PASS_REGULAR_EXPRESSION "type '.*' cannot be converted to the @value class 'V'" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +# A forward reference in __decls: an exported interface names one declared after it, and the +# importer reads each declaration again once the others are in +foreach(forward_mm gc rc own) + tslang_add_test(NAME test-compile-shared-export-import-forward-iface-${forward_mm} COMMAND test-runner -shared -mm=${forward_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_forward_iface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_forward_iface.ts") + tslang_add_test(NAME test-jit-shared-export-import-forward-iface-${forward_mm} COMMAND test-runner -jit -shared -mm=${forward_mm} "${PROJECT_SOURCE_DIR}/test/tester/tests/import_forward_iface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_forward_iface.ts") +endforeach() +# ...while a type they name and never declare is still an error +add_test(NAME test-compile-shared-import-unresolved-iface + COMMAND test-runner -shared "${PROJECT_SOURCE_DIR}/test/tester/tests/import_unresolved_iface.ts" "${PROJECT_SOURCE_DIR}/test/tester/tests/export_unresolved_iface.ts") +set_tests_properties(test-compile-shared-import-unresolved-iface PROPERTIES PASS_REGULAR_EXPRESSION "error: can't find type by name: Hidden" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") # @keeps and @borrows across the boundary: the importer reads them from __decls (-mm=own), and the # other models ignore them foreach(markers_mm gc rc own) @@ -3038,6 +3060,195 @@ foreach(final_error_case ${final_error_cases}) PROPERTIES PASS_REGULAR_EXPRESSION "${final_error_message}" FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") endforeach() + +# `@value` (docs/superpowers/specs/2026-10-24-value-types-design.md): a class or interface whose +# values are copied, not shared. Each file in value/ breaks one rule; the test passes when the +# compiler prints the message. +set(value_error_cases + "value_cpp|class 'V' cannot be both @value and @cpp" + "value_abstract|class 'V' cannot be both @value and abstract" + "value_final|class 'V' cannot be both @value and @final" + "value_extends|@value class 'V' cannot extend 'B'" + "extends_value|class 'X' cannot extend 'V': it is @value" + "value_implements|@value class 'V' cannot implement an interface" + "value_generic|@value class 'V' cannot have type parameters" + "value_iface_extends|@value interface 'R' cannot extend 'I': it is not @value" + "value_iface_extends_class|@value interface 'R' cannot extend 'C': it is not @value" + "value_iface_generic|@value interface 'R' cannot have type parameters" + "value_iface_mutable|field 'f' of @value interface 'R' must be readonly" + "value_iface_optional|field 'f' of @value interface 'R' cannot be optional" + "value_iface_method|@value interface 'R' can only have fields" + "value_mutable_field|field 'x' of @value class 'V' must be readonly" + "value_setter|@value class 'V' cannot have a setter" + "value_instanceof|instanceof can't be used with the @value class 'V': its values have no type information" + "value_to_any|the @value class 'V' cannot be converted to 'any'" + "value_from_literal|type '.*' cannot be converted to the @value class 'V'" + "value_from_iface|type 'R' cannot be converted to the @value class 'V'" + "value_from_class|type 'C' cannot be converted to the @value class 'V'" + # `.` matches the message's `;`, which a CMake list cannot hold + "value_identity|a @value type has no identity. compare its fields" + "value_iface_identity|a @value type has no identity. compare its fields" + "value_switch_identity|a @value type has no identity. compare its fields" + "value_missing_identity|a @value type has no identity. compare its fields" + "value_compare_number|a @value type has no identity. compare its fields" + "value_optional_member_plain_field|field 'f' must be declared 'f\\?: Hit' to implement the optional @value member 'f' of 'J'" + "value_optional_member_literal|field 'f' must be declared 'f\\?: Hit' to implement the optional @value member 'f' of 'J'" + "value_null_plain|a @value type has no null. write 'Hit \\| null'" + "value_ctor_closure_escape_global|a closure that captures 'this' of the @value class 'V' can only be called inside its constructor" + "value_ctor_closure_escape_field|a closure that captures 'this' of the @value class 'V' can only be called inside its constructor" + "value_ctor_closure_escape_arg|a closure that captures 'this' of the @value class 'V' can only be called inside its constructor" + "value_ctor_closure_escape_nested_store|a closure that captures 'this' of the @value class 'V' can only be called inside its constructor" + "value_ctor_closure_escape_nested_return|a closure that captures 'this' of the @value class 'V' can only be called inside its constructor" + "value_readonly_nested_ctor|cannot assign to 'node': the fields of a @value type are readonly" + "value_readonly_method|cannot assign to 'node': the fields of a @value type are readonly" + "value_readonly_outside|cannot assign to 'x': the fields of a @value type are readonly" + "value_readonly_outside_iface|cannot assign to 'start': the fields of a @value type are readonly" + "value_readonly_incdec|cannot assign to 'x': the fields of a @value type are readonly" + "value_ctor_this_const|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_closure|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_arg|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_push|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_arrow|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_literal|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_spread|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_self_iface|@value type 'L' contains itself through 'next'. a value cannot hold itself" + "value_self_class|@value type 'N' contains itself through 'next'. a value cannot hold itself" + "value_self_mutual|@value type 'A' contains itself through 'b.a'. a value cannot hold itself" + "value_self_array|@value type 'L' contains itself through 'next'. a value cannot hold itself" + "value_self_generic|@value type 'L' reaches itself through 'box' in the type arguments of 'Box'. a @value type cannot hold a generic type made from it" + "value_self_generic_class|@value type 'L' reaches itself through 'box' in the type arguments of 'Box'. a @value type cannot hold a generic type made from it" + "value_self_generic_mutual|@value type 'A' reaches itself through 'p.a' in the type arguments of 'Box'. a @value type cannot hold a generic type made from it" + "value_self_generic_pair|@value type 'A' reaches itself through 'p.a' in the type arguments of 'Pair'. a @value type cannot hold a generic type made from it" + "value_generic_unknown|can't find type by name: Nope" + "value_ctor_this_init|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'" + "value_ctor_this_init_noctor|'this' of the @value class 'V' is not a value until its constructor returns. read 'this.f'") +foreach(value_error_case ${value_error_cases}) + string(FIND "${value_error_case}" "|" value_error_sep) + string(SUBSTRING "${value_error_case}" 0 ${value_error_sep} value_error_name) + math(EXPR value_error_sep "${value_error_sep} + 1") + string(SUBSTRING "${value_error_case}" ${value_error_sep} -1 value_error_message) + add_test(NAME test-compile-value-${value_error_name} + COMMAND $ --emit=obj --no-default-lib -mm=none + "${PROJECT_SOURCE_DIR}/test/tester/value/${value_error_name}.ts" + -o "${CMAKE_CURRENT_BINARY_DIR}/value-${value_error_name}.obj") + set_tests_properties(test-compile-value-${value_error_name} + PROPERTIES PASS_REGULAR_EXPRESSION "${value_error_message}" + FAIL_REGULAR_EXPRESSION "Stack dump|Assertion failed") +endforeach() + +# A literal of a @value interface is a value: built in the interface's field order, read, passed, +# and converted to `any` and a type literal. +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-interface-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_interface.ts") + tslang_add_test(NAME test-jit-value-interface-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_interface.ts") +endforeach() +# ...nested in another literal, two levels out of order, and converted to an ordinary interface +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-interface-own-gaps-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_interface_own_gaps.ts") + set(value_interface_gaps_x86_twin "${TSLANG_X86_TWIN}") + tslang_add_test(NAME test-jit-value-interface-own-gaps-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_interface_own_gaps.ts") + # own rejects both (spec 36 "Not here"): a literal nested in another holding new vectors (an + # owning tuple moved into a tuple's field, #679's limit), and a record that borrows temporaries + # converted to an ordinary interface (its box would own what the record borrows) + if (value_mm STREQUAL "own") + set_tests_properties(test-compile-value-interface-own-gaps-own test-jit-value-interface-own-gaps-own ${value_interface_gaps_x86_twin} + PROPERTIES DISABLED TRUE) + endif() +endforeach() +# `new` of a @value class makes a value: constructor, static helpers and field, a method and a +# getter taking `this` by value; stored in an ordinary class's field and in an array, and copied. +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-class-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_class.ts") + tslang_add_test(NAME test-jit-value-class-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_class.ts") +endforeach() +# ...and its optimized code allocates nothing for it +add_test(NAME test-value-no-alloc + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/value/value_no_alloc.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/value-no-alloc.cmake") +# `T | null`, `T | undefined` and `v?: T` of a @value type are an optional value: returned, +# compared with null and undefined, switched on, and read after a check or through `?.`. +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-missing-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_missing.ts") + tslang_add_test(NAME test-jit-value-missing-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_missing.ts") +endforeach() +# ...and `g?.ray.dir.x` (and `.len()`) of a missing one skips the rest of the chain: undefined, as is a +# type literal's +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-optional-chain-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_optional_chain.ts") + tslang_add_test(NAME test-jit-value-optional-chain-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_optional_chain.ts") +endforeach() +# ...and a field read, a getter call or a conversion to the plain type of a missing one throws +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-missing-read-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_missing_read.ts") + tslang_add_test(NAME test-jit-value-missing-read-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_missing_read.ts") +endforeach() +# Methods of an ordinary class calling each other before all are declared, returning a @value class: +# discovery's unresolved results are not conversions to report. +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-mutual-methods-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_mutual_methods.ts") + tslang_add_test(NAME test-jit-value-mutual-methods-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_mutual_methods.ts") +endforeach() +# A @value interface holding an interface whose method returns it, declared before it: the interface +# and the class implementing it see the @value type with all its fields. +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-iface-cycle-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_iface_cycle.ts") + tslang_add_test(NAME test-jit-value-iface-cycle-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_iface_cycle.ts") +endforeach() +# A @value interface reaching itself through an ordinary class (it holds itself in place, it is an +# error: value_self_*). Not under own: `l.v` of `const l = b.box.l` after `l !== null` is "borrows a +# field but is used here after it may be released or overwritten", an own rule outside this one. +foreach(value_mm gc rc none) + tslang_add_test(NAME test-compile-value-self-through-class-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_self_through_class.ts") + tslang_add_test(NAME test-jit-value-self-through-class-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_self_through_class.ts") +endforeach() +# ...and one holding a generic of another @value type declared after it, the generic declared last or +# first: typed once that type is laid out, not as the unspecialized generic +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-generic-field-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_generic_field.ts") + tslang_add_test(NAME test-jit-value-generic-field-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_generic_field.ts") + tslang_add_test(NAME test-compile-value-generic-field-first-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_generic_field_first.ts") + tslang_add_test(NAME test-jit-value-generic-field-first-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_generic_field_first.ts") +endforeach() +# `c ? { ... } : null` into `T | null` of a @value type: the literal is built as the T +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-ternary-null-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_ternary_null.ts") + tslang_add_test(NAME test-jit-value-ternary-null-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_ternary_null.ts") +endforeach() +# A @value value holding references copies them as a tuple does (rc retains each one): copies out of +# an array, through a generic and into closures keep their Nodes after the originals are overwritten. +# A closure captures a @value local's binding, `reduce` works on copies, and a closure in a @value +# constructor reads `this`. Not under own: most of it copies a value that holds an owned Node and reads +# the copy after the original's Node is overwritten, which single ownership rejects (spec 36). +foreach(value_mm gc rc none) + tslang_add_test(NAME test-compile-value-refs-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_refs.ts") + tslang_add_test(NAME test-jit-value-refs-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_refs.ts") +endforeach() +# ...every retain of it paired with a release on every path (the ownership verifier) +add_test(NAME test-rc-verify-ownership-value-refs + COMMAND $ --emit=mlir-affine --no-default-lib -mm=rc --verify-ownership + "${PROJECT_SOURCE_DIR}/test/tester/value/value_refs.ts") +set_tests_properties(test-rc-verify-ownership-value-refs PROPERTIES FAIL_REGULAR_EXPRESSION "error|Stack dump") +# ...a field of a value in a class's field, read into a const or a literal, is retained as a type +# literal's is +add_test(NAME test-value-rc-field-retain + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/value/value_rc_field_retain.ts" + -P "${CMAKE_CURRENT_SOURCE_DIR}/value-rc-field-retain.cmake") +# ...and the box of a closure capturing `this` in a @value constructor borrows the slot `new` made +add_test(NAME test-value-ctor-capture + COMMAND ${CMAKE_COMMAND} -DTSLANG=$ + "-DFILE=${PROJECT_SOURCE_DIR}/test/tester/value/value_ctor_capture.ts" + "-DWORK_DIR=${CMAKE_CURRENT_BINARY_DIR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/value-ctor-capture.cmake") +# ...and `this` in a @value constructor read through its members - a method, a closure, `this["a"]` - +# sees the fields stored so far (used whole, it is an error: value_ctor_this_* above) +foreach(value_mm gc rc none own) + tslang_add_test(NAME test-compile-value-ctor-this-method-${value_mm} COMMAND test-runner -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_ctor_this_method.ts") + tslang_add_test(NAME test-jit-value-ctor-this-method-${value_mm} COMMAND test-runner -jit -mm=${value_mm} "${PROJECT_SOURCE_DIR}/test/tester/value/value_ctor_this_method.ts") +endforeach() + # A call on a @final class is direct, and the program runs the same under every model. foreach(final_mm gc rc none own) tslang_add_test(NAME test-compile-final-dispatch-${final_mm} COMMAND test-runner -mm=${final_mm} "${PROJECT_SOURCE_DIR}/test/tester/final/final_dispatch.ts") @@ -3638,7 +3849,7 @@ foreach(own_test own_fresh_string own_fresh_array own_return_new own_try_local o own_interface_facts own_declared_scalar_no_drops own_borrowing_record own_borrowing_record_arg own_reduce own_fresh_call_result own_ternary_outer_loop own_destructure_elements - own_tuple_record_values) + own_tuple_record_values own_value_record own_value_loop own_value_temporaries) tslang_add_test(NAME test-jit-own-${own_test} COMMAND test-runner -jit -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") tslang_add_test(NAME test-compile-own-${own_test} COMMAND test-runner -mm=own "${PROJECT_SOURCE_DIR}/test/tester/own/${own_test}.ts") # The promise: no counting at all in what own emits. @@ -3767,6 +3978,16 @@ foreach(borrowing_record_mm rc gc none) endforeach() endforeach() +# A tuple that holds borrows and owns nothing - a @value record returned through an interface, held +# in a local the loop reassigns, a temporary given to a call - under own (spec 36); the same programs +# under every other model. +foreach(value_record_mm rc gc none) + foreach(value_record_test own_value_record own_value_loop own_value_temporaries) + tslang_add_test(NAME test-jit-${value_record_mm}-${value_record_test} COMMAND test-runner -jit -mm=${value_record_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${value_record_test}.ts") + tslang_add_test(NAME test-compile-${value_record_mm}-${value_record_test} COMMAND test-runner -mm=${value_record_mm} "${PROJECT_SOURCE_DIR}/test/tester/own/${value_record_test}.ts") + endforeach() +endforeach() + # `reduce` takes its accumulator, and a parameter returned on some paths only is kept (spec 33); # the same program under every other model. foreach(reduce_mm rc gc none) @@ -4175,7 +4396,7 @@ set(own_error_cases "own_err_global_from_field|:12:7: error: the initializer of global 'k' reads a value another owner keeps" "own_err_global_kept_typeof|:15:9: error: the value read from 'M[.]w' is kept where its end at an assignment of 'M[.]w' cannot be checked" "own_err_record_literal_nested|:8:24: error: an object literal that holds a value it owns is moved only into a local or returned as it is" - "own_err_record_literal_let_field|:10:11: error: an object literal that holds a value it owns is moved only into a local or returned as it is" + "own_err_record_literal_let_field|:12:5: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" "own_err_captured_returned|:6:9: error: '[^']*' borrows a captured variable and cannot be stored, returned or captured" "own_err_literal_moved_twice|:14:16: error: '[^']*' is used here after its value was moved" "own_err_interface_keeps_literal|is a parameter, kept here, but -mm=own cannot make the callers of 'KS.take' give it up" @@ -4243,6 +4464,17 @@ set(own_error_cases "own_err_shared_place_arg|:29:5: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_shared_place_two_uses|:32:5: error: '[^']*' borrows a field but is used here after it may be released or overwritten" "own_err_shared_place_literal|:31:15: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_value_record_place_dropped|:44:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" + "own_err_value_record_stored|:33:9: error: '[^']*' borrows the result of 'mk' and cannot be stored, returned or captured" + "own_err_value_record_let_reassigned|:35:11: error: '[^']*' borrows the result of 'mk' but is used here after it may be released or overwritten" + "own_err_value_record_mixed_local|:21:5: error: a value that borrows what it holds and owns nothing [(]a tuple that holds a borrow[)] meets a value that owns a block here" + "own_err_value_record_field_written|:20:5: error: '[^']*' borrows the result of 'mk' and cannot be stored, returned or captured" + "own_err_value_record_param_field_kept|:8:37: error: '[^']*' borrows a field and cannot be stored, returned or captured" + "own_err_value_record_returned|:26:22: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" + "own_err_value_record_captured|:28:11: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" + "own_err_value_record_field_stored|:32:5: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" + "own_err_value_record_global|:30:5: error: '[^']*' borrows '[^']*' and cannot be stored, returned or captured" + "own_err_value_refs_copy|:32:11: error: '[^']*' borrows an element and cannot be stored, returned or captured" "own_err_shared_place_tuple|:31:39: error: '[^']*' borrows a field and cannot be stored, returned or captured" "own_err_shared_literal_borrowed|the initializer of global 'b' takes a second reference" "own_err_iface_field_overwritten|:23:11: error: '[^']*' borrows a field but is used here after it may be released or overwritten" @@ -4286,7 +4518,8 @@ set(own_error_cases "own_err_borrowing_record_const_field|:20:11: error: '[^']*' borrows the result of 'hit' but is used here after it may be released or overwritten" "own_err_record_without_lends|:11:1: error: '@record' of 'pairOf' says its result is a borrowing record, but no '@lends' names what it borrows" "own_err_record_not_record|:7:1: error: '@record' of 'first' says its result is a record that borrows 'a', but its body returns a borrow of it as it is" - "own_err_record_exported_unsaid|:12:1: error: 'pairOf' returns a record that borrows 'a', 'b', which another module can learn only from '@record' beside its '@lends'") + "own_err_record_exported_unsaid|:12:1: error: 'pairOf' returns a record that borrows 'a', 'b', which another module can learn only from '@record' beside its '@lends'" + "own_err_value_export_borrowing|:13:1: error: 'wrap' returns a tuple that borrows 'n' and owns nothing, which -mm=own cannot tell another module yet") foreach(own_error_case ${own_error_cases}) string(FIND "${own_error_case}" "|" own_error_sep) string(SUBSTRING "${own_error_case}" 0 ${own_error_sep} own_error_name) diff --git a/tslang/test/tester/own/own_err_record_literal_let_field.ts b/tslang/test/tester/own/own_err_record_literal_let_field.ts index d08f6e292..d5d28461e 100644 --- a/tslang/test/tester/own/own_err_record_literal_let_field.ts +++ b/tslang/test/tester/own/own_err_record_literal_let_field.ts @@ -1,6 +1,6 @@ -// -mm=own rejects (spec 21.2): `r` holds the value of the `let` `v`, which `v` owns, and is not seen as -// an interface (where it would be a borrowing record, spec 32), so it moves only into a local or the -// result, not into the array. +// -mm=own rejects (spec 36): `r` holds the value of the `let` `v`, which `v` owns, and nothing it owns +// itself, so it is a tuple that borrows `v` (an unboxed borrowing record), and a borrow cannot be +// stored into the array. (Before spec 36: an object literal that holds a value it owns, spec 21.2.) class V { constructor(public x: number) {} } diff --git a/tslang/test/tester/own/own_err_value_export_borrowing.ts b/tslang/test/tester/own/own_err_value_export_borrowing.ts new file mode 100644 index 000000000..2e5ab260a --- /dev/null +++ b/tslang/test/tester/own/own_err_value_export_borrowing.ts @@ -0,0 +1,16 @@ +// A library function returning a @value value that borrows its argument and owns nothing: an +// importer cannot be told so yet (own spec 36), and the library says why. +export class Node { + constructor(public v: number) {} +} + +@value +export interface Ref { + readonly node: Node; + readonly k: number; +} + +@lends("n") +export function wrap(n: Node): Ref { + return { node: n, k: 1 }; +} diff --git a/tslang/test/tester/own/own_err_value_record_captured.ts b/tslang/test/tester/own/own_err_value_record_captured.ts new file mode 100644 index 000000000..c0998046a --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_captured.ts @@ -0,0 +1,36 @@ +// -mm=own rejects (spec 36): a closure that escapes `make` captures the record, which borrows the +// `let` `n` that `make` releases. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function make(): () => number { + let n = new Node(5); + const r: Rec = { s: n, k: 1 }; + return (): number => r.s.v; +} + +function main() { + const f = make(); + churn(); + print(f()); +} diff --git a/tslang/test/tester/own/own_err_value_record_field_stored.ts b/tslang/test/tester/own/own_err_value_record_field_stored.ts new file mode 100644 index 000000000..edc4daae0 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_field_stored.ts @@ -0,0 +1,40 @@ +// -mm=own rejects (spec 36): the record borrows the `let` `n`, and a class field that outlives `n` +// cannot hold it. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +class Holder { + r: Rec | null = null; +} + +function fill(h: Holder) { + let n = new Node(5); + h.r = { s: n, k: 1 }; +} + +function main() { + const h = new Holder(); + fill(h); + churn(); + print(h.r.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_field_written.ts b/tslang/test/tester/own/own_err_value_record_field_written.ts new file mode 100644 index 000000000..647bdbb4d --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_field_written.ts @@ -0,0 +1,22 @@ +// -mm=own rejects (spec 36): a field of a record written through the local that holds it would release +// the value the record borrows (the type literal's field is not readonly). +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +type Rec = { s: Node; k: number }; + +function mk(n: Node): Rec { + return { s: n, k: 1 }; +} + +function main() { + const n = new Node(5); + let r = mk(n); + r.s = new Node(9); + print(n.v, r.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_global.ts b/tslang/test/tester/own/own_err_value_record_global.ts new file mode 100644 index 000000000..d256ab159 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_global.ts @@ -0,0 +1,37 @@ +// -mm=own rejects (spec 36): the record borrows the `let` `n`, and a global that outlives `n` cannot +// hold it. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +let g: Rec | null = null; + +function fill() { + let n = new Node(5); + g = { s: n, k: 1 }; +} + +function main() { + fill(); + churn(); + print(g.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_let_reassigned.ts b/tslang/test/tester/own/own_err_value_record_let_reassigned.ts new file mode 100644 index 000000000..201bf37bc --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_let_reassigned.ts @@ -0,0 +1,36 @@ +// -mm=own rejects (spec 36): the record borrows the value of the `let` `n`, which the assignment +// releases before the record is read. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function mk(n: Node): Rec { + return { s: n, k: 1 }; +} + +function main() { + let n = new Node(5); + const r = mk(n); + n = new Node(6); + churn(); + print(r.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_mixed_local.ts b/tslang/test/tester/own/own_err_value_record_mixed_local.ts new file mode 100644 index 000000000..e481e5252 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_mixed_local.ts @@ -0,0 +1,23 @@ +// -mm=own rejects (spec 36): `r` holds a record that borrows `n` and owns nothing, then a tuple that +// owns a new Node; one release of `r` cannot do right by both. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +type Rec = { s: Node; k: number }; + +function mk(n: Node): Rec { + return { s: n, k: 1 }; +} + +function main() { + const n = new Node(5); + let r = mk(n); + print(r.s.v); + r = { s: new Node(7), k: 2 }; + print(r.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_param_field_kept.ts b/tslang/test/tester/own/own_err_value_record_param_field_kept.ts new file mode 100644 index 000000000..bae14ba83 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_param_field_kept.ts @@ -0,0 +1,18 @@ +// -mm=own rejects (spec 36): a callee that pushes the borrowed field of a record parameter into an +// array keeps what the record borrows, which its caller's `s` releases at the end of its block. +interface Thing { id(): int; } +class S implements Thing { constructor(private n: int) {} id(): int { return this.n; } } +@value +interface Hit { readonly thing: Thing; readonly d: number; } +function churn() { const keep: S[] = []; for (let i = 0; i < 1000; i++) keep.push(new S(77777)); return keep.length; } +function keep(h: Hit, g: Thing[]) { g.push(h.thing); } +function mk(t: Thing): Hit { return { thing: t, d: 1 }; } +function main() { + const g: Thing[] = []; + { + const s = new S(5); + keep(mk(s), g); + } + churn(); + print(g[0].id()); +} diff --git a/tslang/test/tester/own/own_err_value_record_place_dropped.ts b/tslang/test/tester/own/own_err_value_record_place_dropped.ts new file mode 100644 index 000000000..a9d85f547 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_place_dropped.ts @@ -0,0 +1,45 @@ +// -mm=own rejects (spec 36): the record `o` borrows `p.child`, which `drop` overwrites before `o.s` is +// read through the local that holds it. Before the read in place was followed, this compiled and +// printed 77777 (gc 5). +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function mk(n: Node): Rec { + return { s: n, k: 1 }; +} + +class P { + child = new Node(5); +} + +function drop(p: P) { + p.child = new Node(6); + churn(); +} + +function main() { + const p = new P(); + const o: Rec = { s: p.child, k: 1 }; + drop(p); + print(o.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_returned.ts b/tslang/test/tester/own/own_err_value_record_returned.ts new file mode 100644 index 000000000..2f9084d78 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_returned.ts @@ -0,0 +1,36 @@ +// -mm=own rejects (spec 36): the record borrows the `let` `n`, which is released when `make` returns, +// so it cannot be returned. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function make(): Rec { + let n = new Node(5); + const r: Rec = { s: n, k: 1 }; + return r; +} + +function main() { + const r = make(); + churn(); + print(r.s.v); +} diff --git a/tslang/test/tester/own/own_err_value_record_stored.ts b/tslang/test/tester/own/own_err_value_record_stored.ts new file mode 100644 index 000000000..bc84eef46 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_record_stored.ts @@ -0,0 +1,38 @@ +// -mm=own rejects (spec 36): a record that borrows `n` cannot be stored into an array that outlives it. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function mk(n: Node): Rec { + return { s: n, k: 1 }; +} + +function main() { + const recs: Rec[] = []; + { + const n = new Node(5); + recs.push(mk(n)); + } + + churn(); + print(recs[0].s.v); +} diff --git a/tslang/test/tester/own/own_err_value_refs_copy.ts b/tslang/test/tester/own/own_err_value_refs_copy.ts new file mode 100644 index 000000000..894125c67 --- /dev/null +++ b/tslang/test/tester/own/own_err_value_refs_copy.ts @@ -0,0 +1,38 @@ +// -mm=own rejects (spec 36): `a` is a copy of a value that holds an owned Node; under single ownership +// the copy is a borrow of `recs[0]`, and overwriting `recs[0]` releases the Node it reads. +class Node { + v = 0; + + constructor(v: number) { + this.v = v; + } +} + +@value +interface Rec { + readonly s: Node; + readonly k: number; +} + +function churn() { + const keep: Node[] = []; + for (let i = 0; i < 1000; i++) { + keep.push(new Node(77777)); + } + + return keep.length; +} + +function main() { + const recs: Rec[] = []; + recs.push(makeRec(5)); + const a = recs[0]; + recs[0] = makeRec(6); + churn(); + print(a.s.v); +} + +function makeRec(v: number): Rec { + const n = new Node(v); + return { s: n, k: 1 }; +} diff --git a/tslang/test/tester/own/own_value_loop.ts b/tslang/test/tester/own/own_value_loop.ts new file mode 100644 index 000000000..af4771b45 --- /dev/null +++ b/tslang/test/tester/own/own_value_loop.ts @@ -0,0 +1,98 @@ +// -mm=own: the ray tracer's `intersections` loop over @value records. `closest` starts undefined +// and is given the nearer of each `t.hit(ray)` inside the loop; after the loop it is returned, and +// the caller passes it to `shade`, which reads `thing` and calls through it. Each record borrows the +// receiver it was made by, an element of the array the caller owns. churn() between the loop and +// each read reuses the blocks a freed `S` would leave. +@value +class Vector { + constructor(public readonly x: number, public readonly y: number) {} +} + +@value +interface Ray { + readonly start: Vector; + readonly dir: Vector; +} + +interface Thing { + hit(r: Ray): Hit | null; + id(): int; +} + +@value +interface Hit { + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; +} + +class S implements Thing { + constructor(private n: int, private at: number) {} + + hit(r: Ray): Hit | null { + const d = this.at - r.start.x; + return d > 0 ? { thing: this, ray: r, dist: d } : null; + } + + id(): int { + return this.n; + } +} + +class Scene { + things: Thing[] = [new S(1, 5), new S(2, 3), new S(3, 8)]; +} + +function churn() { + const keep: S[] = []; + for (let i = 0; i < 64; i++) { + keep.push(new S(77777, 77777)); + } + + return keep.length; +} + +class Tracer { + intersections(ray: Ray, scene: Scene) { + let best = +Infinity; + let closest: Hit | undefined = undefined; + for (let i = 0; i < scene.things.length; i++) { + const inter = scene.things[i].hit(ray); + if (inter != null && inter.dist < best) { + closest = inter; + best = inter.dist; + } + } + + return closest; + } + + shade(h: Hit): number { + return h.thing.id() * 100 + h.dist; + } + + trace(ray: Ray, scene: Scene): number { + const h = this.intersections(ray, scene); + churn(); + if (h === undefined) { + return -1; + } + + return this.shade(h); + } +} + +function main() { + const scene = new Scene(); + const tracer = new Tracer(); + let total: number = 0; + for (let i = 0; i < 1000; i++) { + total += tracer.trace({ start: new Vector(i % 10, 0), dir: new Vector(1, 0) }, scene); + } + + print(total); + // start x 0..2: S2 (at 3) is nearest, dist 3 - x; 3..4: S1 (at 5), dist 5 - x; 5..7: S3 (at 8), + // dist 8 - x; 8..9: none (-1). Per ten: 3*200 + 6 + 2*100 + 3 + 3*300 + 6 - 2 = 1713 + assert(total == 171300); + print("done."); +} diff --git a/tslang/test/tester/own/own_value_record.ts b/tslang/test/tester/own/own_value_record.ts new file mode 100644 index 000000000..5e6cd4452 --- /dev/null +++ b/tslang/test/tester/own/own_value_record.ts @@ -0,0 +1,94 @@ +// -mm=own: a @value record holding a borrow of `this` (the ray tracer's Intersection), returned as +// `Hit | null` by methods reached through the interface `Thing`, from a ternary (`S`) and from an +// `if` (`P`). The record is a value, a tuple: there is no box, and its `thing` borrows the +// receiver, which the caller's array owns. The caller reads `h.thing.id()` through the interface and +// `h.dist` after churn(), which reuses blocks of the size a freed `S` or `P` would leave. +@value +class Vector { + constructor(public readonly x: number, public readonly y: number) {} +} + +@value +interface Ray { + readonly start: Vector; + readonly dir: Vector; +} + +interface Thing { + hit(r: Ray): Hit | null; + id(): int; +} + +@value +interface Hit { + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; +} + +class S implements Thing { + constructor(private n: int) {} + + hit(r: Ray): Hit | null { + return r.dir.x > 0 ? { thing: this, ray: r, dist: r.dir.x } : null; + } + + id(): int { + return this.n; + } +} + +class P implements Thing { + constructor(private n: int) {} + + hit(r: Ray): Hit | null { + if (r.dir.y > 0) { + return { thing: this, ray: r, dist: r.dir.y * 2 }; + } + + return null; + } + + id(): int { + return this.n; + } +} + +function churn() { + const keep: S[] = []; + for (let i = 0; i < 64; i++) { + keep.push(new S(77777)); + } + + return keep.length; +} + +function main() { + const things: Thing[] = [new S(1), new P(2)]; + let total: number = 0; + let missing = 0; + for (let i = 0; i < 1000; i++) { + const ray: Ray = { start: new Vector(0, 0), dir: new Vector((i % 3) - 1, (i % 5) - 2) }; + for (let k = 0; k < things.length; k++) { + const h = things[k].hit(ray); + churn(); + if (h != null) { + // a number field printed straight: converting it to a string takes nothing of the record + if (i < 5) { + print(h.dist); + } + + total += h.thing.id() + h.dist + h.ray.start.x; + } else { + missing++; + } + } + } + + // printed above: 1 (S, i = 2), 2 (P, i = 3), 4 (P, i = 4) + print(total, missing); + // S hits 333 times (id 1, dist 1); P 200 times with dist 2 and 200 with dist 4 (id 2) + assert(total == 2666); + assert(missing == 1267); + print("done."); +} diff --git a/tslang/test/tester/own/own_value_temporaries.ts b/tslang/test/tester/own/own_value_temporaries.ts new file mode 100644 index 000000000..dc07d8fdf --- /dev/null +++ b/tslang/test/tester/own/own_value_temporaries.ts @@ -0,0 +1,84 @@ +// -mm=own: a tuple that holds borrows and owns nothing is a record with no box (spec 36), and so is a +// literal given only to calls as a temporary: `len({ start: new Vec(1, 2), dir: new Vec(3, 4) })` +// borrows the two new vectors, which keep their own release after the call. A `@value` record held +// in a `const` that borrows a `let` twice is read through the local in place. A closure in a `@value` constructor that reads +// `this`, whose fields are numbers, needs no owner. churn() inside the callee and before each read +// reuses the blocks a vector freed too early would leave. +class Vec { + constructor(public x: number, public y: number) {} +} + +@value +interface Ray { + readonly start: Vec; + readonly dir: Vec; +} + +type Pair = { a: Vec; b: Vec }; + +// a value that owns its vector (a fresh one moved in), whose number field is printed straight: +// converting the number to a string takes nothing of the value +@value +interface Owned { + readonly v: Vec; + readonly n: number; +} + +function owned(): Owned { + return { v: new Vec(3, 4), n: 2 }; +} + +@value +class W { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + const f = () => this.a + 1; + this.b = f(); + } +} + +function churn() { + const keep: Vec[] = []; + for (let i = 0; i < 64; i++) { + keep.push(new Vec(77777, 77777)); + } + + return keep.length; +} + +function len(r: Ray) { + churn(); + return r.start.x + r.dir.y; +} + +function sum(p: Pair) { + churn(); + return p.a.x + p.b.y; +} + +function main() { + let total: number = 0; + for (let i = 0; i < 1000; i++) { + total += len({ start: new Vec(i, 0), dir: new Vec(0, 1) }); + total += sum({ a: new Vec(1, 0), b: new Vec(0, i) }); + } + + print(total); + assert(total == 2 * 499500 + 2000); + + let v = new Vec(5, 6); + const r: Ray = { start: v, dir: v }; + churn(); + assert(r.start.x == 5 && r.dir.y == 6); + + assert(new W(4).b == 5); + + const o = owned(); + print(o.n); + churn(); + assert(o.v.x == 3 && o.n == 2); + print("done."); +} diff --git a/tslang/test/tester/tests/export_forward_iface.ts b/tslang/test/tester/tests/export_forward_iface.ts new file mode 100644 index 000000000..5b987661c --- /dev/null +++ b/tslang/test/tester/tests/export_forward_iface.ts @@ -0,0 +1,15 @@ +// The library side of a forward reference across a module boundary: `A` names `B`, declared after +// it, and __decls prints them in that order. The importer reads each declaration again once the +// others are in, as a module reads its own (import_forward_iface.ts). +export interface A { + b: B; + n: number; +} + +export interface B { + k: number; +} + +export function mkA(n: number): A { + return { b: { k: n * 10 }, n: n }; +} diff --git a/tslang/test/tester/tests/export_unresolved_iface.ts b/tslang/test/tester/tests/export_unresolved_iface.ts new file mode 100644 index 000000000..5692b9238 --- /dev/null +++ b/tslang/test/tester/tests/export_unresolved_iface.ts @@ -0,0 +1,14 @@ +// A library whose exported `A` holds a `Hidden` it does not export: __decls prints `h: Hidden` with +// no declaration of `Hidden` (import_unresolved_iface.ts). +interface Hidden { + k: number; +} + +export interface A { + h: Hidden; + n: number; +} + +export function mkA(n: number): A { + return { h: { k: n + 1 }, n: n }; +} diff --git a/tslang/test/tester/tests/export_value_types.ts b/tslang/test/tester/tests/export_value_types.ts new file mode 100644 index 000000000..3fd8a3aff --- /dev/null +++ b/tslang/test/tester/tests/export_value_types.ts @@ -0,0 +1,56 @@ +// The library side of @value across a module boundary: a @value class with a static helper and a +// getter, @value interfaces holding it (`Hit` is declared before the `Ray` it holds, so its fields +// are laid out in declaration order on both sides), functions returning them, one returning +// `Hit | null`, and ones reading every field of a value the importer builds. The importer sees only +// these declarations (__decls), which carry `@value`. See import_value_types.ts. +@value +export class V { + constructor(public readonly x: number) {} + + static plus(a: V, b: V) { + return new V(a.x + b.x); + } + + get twice() { + return this.x * 2; + } +} + +@value +export interface R { + readonly a: V; + readonly n: number; +} + +@value +export interface Hit { + readonly ray: Ray; + readonly dist: number; +} + +@value +export interface Ray { + readonly start: V; + readonly dir: V; +} + +export function mkR(n: number): R { + return { a: new V(n), n: n }; +} + +export function readR(r: R) { + return r.a.x * 10 + r.n; +} + +export function mkHit(n: number): Hit { + return { ray: { start: new V(n), dir: new V(n + 1) }, dist: n * 2 }; +} + +export function readHit(h: Hit) { + return h.ray.start.x + h.ray.dir.x * 10 + h.dist * 100; +} + +export function find(n: number): Hit | null { + if (n < 0) return null; + return mkHit(n); +} diff --git a/tslang/test/tester/tests/import_forward_iface.ts b/tslang/test/tester/tests/import_forward_iface.ts new file mode 100644 index 000000000..92258039f --- /dev/null +++ b/tslang/test/tester/tests/import_forward_iface.ts @@ -0,0 +1,16 @@ +// A forward reference in another module's declarations: `A` is printed before the `B` it holds. +import './export_forward_iface' + +function main() { + let sum: number = 0; + for (let i = 0; i < 100; i++) { + const a = mkA(i); + sum += a.b.k + a.n; + } + + assert(sum == 54450, "a.b.k and a.n of an imported A"); + + const a = mkA(3); + assert(a.b.k == 30 && a.n == 3, "the fields of one A"); + print("done."); +} diff --git a/tslang/test/tester/tests/import_unresolved_iface.ts b/tslang/test/tester/tests/import_unresolved_iface.ts new file mode 100644 index 000000000..732a32bc7 --- /dev/null +++ b/tslang/test/tester/tests/import_unresolved_iface.ts @@ -0,0 +1,8 @@ +// A type another module's declarations name but never declare is an error, though the importer +// tries each declaration again once the others are in. +import './export_unresolved_iface' + +function main() { + const a = mkA(2); + print(a.h.k, a.n); +} diff --git a/tslang/test/tester/tests/import_value_types.ts b/tslang/test/tester/tests/import_value_types.ts new file mode 100644 index 000000000..d10465474 --- /dev/null +++ b/tslang/test/tester/tests/import_value_types.ts @@ -0,0 +1,43 @@ +// @value across a module boundary (export_value_types.ts): the imported class `V` is the exporter's +// type, so `V.plus`, `new V` and the getter work on values from either side. Values come back from +// the library's functions and go into them, built here as literals whose fields are written out of +// declaration order, nested in another; a nested field is read through two levels; a `Hit | null` +// is narrowed and read through `?.`. +import './export_value_types' + +function main() { + let sum: number = 0; + for (let i = 0; i < 1000; i++) { + sum += V.plus(mkR(i).a, new V(1)).twice; + } + + assert(sum == 1001000, "V.plus of an imported value and a local one"); + + const r: R = { n: 3, a: new V(4) }; + assert(readR(r) == 43, "a local R read by the library"); + assert(readR(mkR(5)) == 55, "the library's R given back to it"); + + const h = mkHit(2); + assert(h.ray.dir.x == 3 && h.ray.start.x == 2 && h.dist == 4, "a nested field of an imported Hit"); + + const local: Hit = { dist: 5, ray: { dir: new V(7), start: new V(6) } }; + assert(readHit(local) == 576, "a local Hit, fields out of order, read by the library"); + assert(local.ray.dir.x == 7 && local.ray.start.x == 6 && local.dist == 5, "the local Hit read here"); + + const f = find(3); + if (f) { + assert(f.dist == 6 && f.ray.dir.x == 4, "a found Hit"); + } else { + assert(false, "find(3) found nothing"); + } + + const g = find(-1); + if (g) { + assert(false, "find(-1) found something"); + } + + assert(f?.dist == 6, "?. on a found Hit"); + assert(g?.dist === undefined, "?. on a missing Hit"); + + print("done."); +} diff --git a/tslang/test/tester/tests/import_value_types_structural.ts b/tslang/test/tester/tests/import_value_types_structural.ts new file mode 100644 index 000000000..73e11e6ae --- /dev/null +++ b/tslang/test/tester/tests/import_value_types_structural.ts @@ -0,0 +1,10 @@ +// An imported @value class is nominal, as a local one is: an object literal of its shape is not one. +import './export_value_types' + +function takeV(v: V) { + return v.x; +} + +function main() { + print(takeV({ x: 1 })); +} diff --git a/tslang/test/tester/value-ctor-capture.cmake b/tslang/test/tester/value-ctor-capture.cmake new file mode 100644 index 000000000..b20453c2b --- /dev/null +++ b/tslang/test/tester/value-ctor-capture.cmake @@ -0,0 +1,60 @@ +# A closure in a @value constructor that reads `this` (value/value_ctor_capture.ts) captures the +# address of the slot `new` made for the value. Under rc its box borrows that slot: the box's release +# routine (`tsrelcb_`) frees the box and nothing else. Released as a capture cell, the slot had a +# count read and decremented in the caller's frame and was handed to the allocator's free. +cmake_minimum_required(VERSION 3.17.3) +set(ll "${WORK_DIR}/value_ctor_capture.ll") +execute_process(COMMAND "${TSLANG}" --emit=llvm --no-default-lib -mm=rc "${FILE}" -o "${ll}" + OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) +if(NOT result EQUAL 0) + message(FATAL_ERROR "tslang failed (${result}): +${out}${err}") +endif() +file(READ "${ll}" ir) +# ...and no function of the program's own (not a `ts*` ownership routine or a `__tslang_*` helper) +# counts a block directly: the only one such a count could be on here is the slot, which a nested +# closure's capture took as a cell (RetainCell, a count written into the caller's frame) +set(rest "${ir}") +while(TRUE) + string(FIND "${rest}" " +define " begin) + if(begin EQUAL -1) + break() + endif() + math(EXPR begin "${begin} + 1") + string(SUBSTRING "${rest}" ${begin} -1 rest) + string(FIND "${rest}" " +}" end) + string(SUBSTRING "${rest}" 0 ${end} body) + string(SUBSTRING "${rest}" ${end} -1 rest) + if(body MATCHES "^define [^@]*@(ts|__tslang)") + continue() + endif() + if(body MATCHES "@__tslang_(inc|dec)_ref[(]") + message(FATAL_ERROR "a function counts a block directly: +${body}") + endif() +endwhile() +set(routines 0) +while(TRUE) + string(FIND "${ir}" "define internal void @tsrelcb_" begin) + if(begin EQUAL -1) + break() + endif() + string(SUBSTRING "${ir}" ${begin} -1 ir) + string(FIND "${ir}" " +}" end) + string(SUBSTRING "${ir}" 0 ${end} body) + string(SUBSTRING "${ir}" ${end} -1 ir) + math(EXPR routines "${routines} + 1") + string(REGEX MATCHALL "__tslang_free_block[(]" frees "${body}") + list(LENGTH frees free_count) + if(NOT free_count EQUAL 1) + message(FATAL_ERROR "a capture box's release routine frees ${free_count} blocks, not just the box: +${body}") + endif() +endwhile() +if(routines EQUAL 0) + message(FATAL_ERROR "no capture box release routine in: +${ll}") +endif() diff --git a/tslang/test/tester/value-no-alloc.cmake b/tslang/test/tester/value-no-alloc.cmake new file mode 100644 index 000000000..14ea6c4de --- /dev/null +++ b/tslang/test/tester/value-no-alloc.cmake @@ -0,0 +1,45 @@ +# A @value value is not a heap object (value/value_no_alloc.ts): the optimized LLVM IR of `len2`, +# which builds a nested literal of a @value interface and passes it on, and of `plus2`, which makes +# @value class values with `new` and passes them to a static helper, calls no allocator, under every +# model. `alloca` is a stack slot and is fine; malloc/calloc are listed for Linux, where +# ProcessHeapPass does not rename them. LLVM can fold away the allocation of an object that does not +# escape, so the unoptimized IR of `V.plus`, whose `new V` is returned, is read as well. +cmake_minimum_required(VERSION 3.17.3) +function(check_no_alloc mm ir fn) + string(FIND "${ir}" "@${fn}(" begin) + if(begin EQUAL -1) + message(FATAL_ERROR "-mm=${mm}: no function `${fn}` in: +${ir}") + endif() + string(SUBSTRING "${ir}" ${begin} -1 body) + string(FIND "${body}" " +}" end) + string(SUBSTRING "${body}" 0 ${end} body) + if(body MATCHES "[mc]alloc[(]|GC_malloc|__tslang_heap") + message(FATAL_ERROR "-mm=${mm}: `${fn}` allocates: +${body}") + endif() +endfunction() +foreach(mm gc rc none own) + foreach(opt opt noopt) + set(ll "${WORK_DIR}/value_no_alloc_${mm}_${opt}.ll") + if(opt STREQUAL "opt") + set(opt_args --opt --opt_level=3) + else() + set(opt_args) + endif() + execute_process(COMMAND "${TSLANG}" --emit=llvm ${opt_args} --no-default-lib -mm=${mm} "${FILE}" -o "${ll}" + OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) + if(NOT result EQUAL 0) + message(FATAL_ERROR "-mm=${mm} ${opt}: tslang failed (${result}): +${out}${err}") + endif() + file(READ "${ll}" ir) + if(opt STREQUAL "opt") + check_no_alloc(${mm} "${ir}" len2) + check_no_alloc(${mm} "${ir}" plus2) + else() + check_no_alloc(${mm} "${ir}" V.plus) + endif() + endforeach() +endforeach() diff --git a/tslang/test/tester/value-rc-field-retain.cmake b/tslang/test/tester/value-rc-field-retain.cmake new file mode 100644 index 000000000..017d67daa --- /dev/null +++ b/tslang/test/tester/value-rc-field-retain.cmake @@ -0,0 +1,44 @@ +# Under rc, a field of a @value value in an ordinary class's field, read into a const +# (`const s = h.r.start`) or into a literal of the @value interface (`{ start: h.r.start, dir: +# h.r.dir }`), takes a reference exactly as the same read of a type literal does +# (value/value_rc_field_retain.ts): each pair of functions, @value and type literal, has the same +# ownership operations, and at least one retain. A read that does not see the place it reads from +# (MLIRCodeLogic::GetReferenceFromValue through the value's storage tuple) is taken out of a copy of +# the record and not retained, so the const is freed under it once the field is overwritten. +cmake_minimum_required(VERSION 3.17.3) +function(ownership_ops ir fn out) + string(FIND "${ir}" "ts.Func @${fn} " begin) + if(begin EQUAL -1) + message(FATAL_ERROR "no function `${fn}` in: +${ir}") + endif() + string(SUBSTRING "${ir}" ${begin} -1 body) + string(FIND "${body}" " + }" end) + string(SUBSTRING "${body}" 0 ${end} body) + string(REGEX MATCHALL "\"ts[.](Retain|Release)[A-Za-z]*\"" ops "${body}") + set(${out} "${ops}" PARENT_SCOPE) +endfunction() +execute_process(COMMAND "${TSLANG}" --emit=mlir --no-default-lib -mm=rc "${FILE}" + OUTPUT_VARIABLE out ERROR_VARIABLE err RESULT_VARIABLE result) +if(NOT result EQUAL 0) + message(FATAL_ERROR "tslang failed (${result}): +${out}${err}") +endif() +# the module is printed to stderr +set(ir "${out}${err}") +foreach(pair "rayFromHit|rayTFromHit" "startFromHit|startTFromHit") + string(REPLACE "|" ";" pair "${pair}") + list(GET pair 0 value_fn) + list(GET pair 1 literal_fn) + ownership_ops("${ir}" ${value_fn} value_ops) + ownership_ops("${ir}" ${literal_fn} literal_ops) + if(NOT value_ops STREQUAL literal_ops) + message(FATAL_ERROR "`${value_fn}` (@value) has other ownership operations than `${literal_fn}` (type literal): +${value_fn}: ${value_ops} +${literal_fn}: ${literal_ops}") + endif() + if(NOT value_ops MATCHES "Retain") + message(FATAL_ERROR "no retain in `${value_fn}` or `${literal_fn}`: ${value_ops}") + endif() +endforeach() diff --git a/tslang/test/tester/value/extends_value.ts b/tslang/test/tester/value/extends_value.ts new file mode 100644 index 000000000..3e415eff7 --- /dev/null +++ b/tslang/test/tester/value/extends_value.ts @@ -0,0 +1,10 @@ +// A @value class cannot be extended: a value has no vtable to override through. +@value +class V { + constructor(public readonly x: number) {} +} + +class X extends V {} + +function main() { +} diff --git a/tslang/test/tester/value/value_abstract.ts b/tslang/test/tester/value/value_abstract.ts new file mode 100644 index 000000000..d295dda6f --- /dev/null +++ b/tslang/test/tester/value/value_abstract.ts @@ -0,0 +1,8 @@ +// An abstract class exists to be extended, and a value has no vtable to dispatch through. +@value +abstract class V { + abstract m(): int; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_class.ts b/tslang/test/tester/value/value_class.ts new file mode 100644 index 000000000..d5831ba09 --- /dev/null +++ b/tslang/test/tester/value/value_class.ts @@ -0,0 +1,105 @@ +// `@value class`: `new` makes a value - a struct of the class's readonly fields on the stack, +// with no box and no vtable. Static helpers, an instance method and a getter (both take `this` +// by value), a static field of the class's own type and one of another class; values passed, +// returned, stored in a field of an ordinary class and in an array, and copied. A constructor reads +// `this` through its fields and calls a method on it. +@value +class V { + constructor(public readonly x: number, public readonly y: number, public readonly z: number) {} + + static plus(a: V, b: V) { + return new V(a.x + b.x, a.y + b.y, a.z + b.z); + } + + static white = new V(1, 2, 3); + + dot(o: V) { + return this.x * o.x + this.y * o.y + this.z * o.z; + } + + get len2() { + return this.dot(this); + } +} + +// fields assigned in the constructor +@value +class P { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + this.b = a * 2; + } +} + +// a constructor reading `this` through its fields and calling a method on it +@value +class Q { + readonly a: number; + readonly b: number; + readonly s: number; + readonly t: number; + + constructor(a: number) { + this.a = a; + this.b = a * 2; + this.s = this.a + this.b; + this.t = this.twice(); + } + + twice() { + return this.a * 2; + } +} + +// a static field of an ordinary class holding a value +class K { + static k = new V(9, 0, 0); +} + +// an ordinary class holding a value +class Cam { + pos: V; + n = 0; + + constructor(p: V) { + this.pos = p; + } +} + +function main() { + assert(V.plus(new V(1, 2, 3), new V(4, 5, 6)).y == 7); + assert(new V(1, 2, 2).len2 == 9); + assert(V.white.y == 2); + assert(V.white.x == 1 && V.white.z == 3); + assert(K.k.x == 9); + assert(new Q(3).s == 9); + assert(new Q(3).t == 6); + assert(new P(3).b == 6); + + // the value keeps its own fields after the class's other fields change + const c = new Cam(new V(1, 1, 1)); + c.n = 5; + c.pos = V.plus(c.pos, c.pos); + assert(c.pos.x == 2); + + const arr: V[] = [new V(1, 0, 0), new V(2, 0, 0)]; + assert(arr[1].x == 2); + + // a copy, not a reference + let v = new V(1, 0, 0); + const w = v; + v = new V(9, 0, 0); + assert(w.x == 1); + + let acc = new V(0, 0, 0); + for (let i = 0; i < 10000; i++) { + acc = V.plus(acc, new V(1, 0, 0)); + } + + assert(acc.x == 10000); + + print("done."); +} diff --git a/tslang/test/tester/value/value_compare_number.ts b/tslang/test/tester/value/value_compare_number.ts new file mode 100644 index 000000000..18d95153c --- /dev/null +++ b/tslang/test/tester/value/value_compare_number.ts @@ -0,0 +1,15 @@ +// @strict-null false +// A @value value is compared with null or undefined only: against a number it has no identity to +// compare either. +@value +interface Hit { + readonly dist: number; +} + +function find(d: number): Hit | null { + return { dist: d }; +} + +function main() { + print(find(1) === 1); +} diff --git a/tslang/test/tester/value/value_cpp.ts b/tslang/test/tester/value/value_cpp.ts new file mode 100644 index 000000000..a74592a6a --- /dev/null +++ b/tslang/test/tester/value/value_cpp.ts @@ -0,0 +1,9 @@ +// A C++ binding is dispatched through the C++ vtable, and its layout is C++'s: it cannot be a value. +@value +@cpp +declare class V { + m(): int; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_ctor_capture.ts b/tslang/test/tester/value/value_ctor_capture.ts new file mode 100644 index 000000000..c1616c3a4 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_capture.ts @@ -0,0 +1,51 @@ +// A closure in a @value constructor that reads `this` holds the address of the slot `new` made, +// which the closure's box borrows, as does a closure inside it that reads `this` through the outer +// box: under rc a box's release routine frees the box alone, and no function takes or gives back a +// count of the slot as if it were a cell (value-ctor-capture.cmake). A closure in a method takes a +// copy of `this` (the value), not a cell, so its box frees itself alone too. +@value +class W { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + const f = () => this.a + 1; + this.b = f(); + } +} + +@value +class W2 { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + const f = () => { + const h = () => this.a + 1; + return h(); + }; + this.b = f(); + } +} + +class Node { + constructor(public n: int) {} +} + +@value +class M { + constructor(public readonly node: Node) {} + + reader() { + return () => this.node.n; + } +} + +function main() { + assert(new M(new Node(3)).reader()() == 3); + assert(new W(4).b == 5); + assert(new W2(4).b == 5); + print("done."); +} diff --git a/tslang/test/tester/value/value_ctor_closure_escape_arg.ts b/tslang/test/tester/value/value_ctor_closure_escape_arg.ts new file mode 100644 index 000000000..20cde8e09 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_closure_escape_arg.ts @@ -0,0 +1,21 @@ +// A closure that reads `this` in a @value constructor holds the slot `new` made, which dies with +// `new`'s caller: passed to a function it may be kept beyond the slot. +function call(f: () => number) { + return f(); +} + +@value +class V { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + this.b = call(() => this.a + 1); + } +} + +function main() { + const v = new V(4); + print(v.b); +} diff --git a/tslang/test/tester/value/value_ctor_closure_escape_field.ts b/tslang/test/tester/value/value_ctor_closure_escape_field.ts new file mode 100644 index 000000000..f88edd761 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_closure_escape_field.ts @@ -0,0 +1,17 @@ +// A closure that reads `this` in a @value constructor holds the slot `new` made, which dies with +// `new`'s caller: stored in a field of the value it outlives the slot. +@value +class V { + readonly a: number; + readonly f: () => number; + + constructor(a: number) { + this.a = a; + this.f = () => this.a + 1; + } +} + +function main() { + const v = new V(4); + print(v.f()); +} diff --git a/tslang/test/tester/value/value_ctor_closure_escape_global.ts b/tslang/test/tester/value/value_ctor_closure_escape_global.ts new file mode 100644 index 000000000..6bc0edd2f --- /dev/null +++ b/tslang/test/tester/value/value_ctor_closure_escape_global.ts @@ -0,0 +1,18 @@ +// A closure that reads `this` in a @value constructor holds the slot `new` made, which dies with +// `new`'s caller: stored in a global it outlives the slot. +let g: () => number = (): number => 0; + +@value +class V { + readonly a: number; + + constructor(a: number) { + this.a = a; + g = () => this.a + 1; + } +} + +function main() { + const v = new V(4); + print(v.a, g()); +} diff --git a/tslang/test/tester/value/value_ctor_closure_escape_nested_return.ts b/tslang/test/tester/value/value_ctor_closure_escape_nested_return.ts new file mode 100644 index 000000000..535778426 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_closure_escape_nested_return.ts @@ -0,0 +1,20 @@ +// A closure that reads `this` in a @value constructor may only be called where it was made: captured +// by another closure, it can be returned from there and outlive the slot `new` made. +let g: () => number = (): number => 0; + +@value +class V { + readonly a: number; + + constructor(a: number) { + this.a = a; + const f = () => this.a + 1; + const h = () => f; + g = h(); + } +} + +function main() { + const v = new V(4); + print(v.a, g()); +} diff --git a/tslang/test/tester/value/value_ctor_closure_escape_nested_store.ts b/tslang/test/tester/value/value_ctor_closure_escape_nested_store.ts new file mode 100644 index 000000000..9ebc7c7a3 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_closure_escape_nested_store.ts @@ -0,0 +1,22 @@ +// A closure that reads `this` in a @value constructor may only be called where it was made: captured +// by another closure, it can be stored from there and outlive the slot `new` made. +let g: () => number = (): number => 0; + +@value +class V { + readonly a: number; + + constructor(a: number) { + this.a = a; + const f = () => this.a + 1; + const h = () => { + g = f; + }; + h(); + } +} + +function main() { + const v = new V(4); + print(v.a, g()); +} diff --git a/tslang/test/tester/value/value_ctor_this_arg.ts b/tslang/test/tester/value/value_ctor_this_arg.ts new file mode 100644 index 000000000..7cc9a779b --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_arg.ts @@ -0,0 +1,19 @@ +// ...nor an argument +function show(v: V) { + return v.a; +} + +@value +class V { + readonly a: number; + readonly b: number; + + constructor() { + this.a = 1; + this.b = show(this); + } +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_ctor_this_arrow.ts b/tslang/test/tester/value/value_ctor_this_arrow.ts new file mode 100644 index 000000000..385bac281 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_arrow.ts @@ -0,0 +1,16 @@ +// ...nor what a closure in the constructor gives back +@value +class V { + readonly a: number; + readonly b: number; + + constructor() { + const get = () => this; + this.a = 1; + this.b = get().a + 1; + } +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_ctor_this_closure.ts b/tslang/test/tester/value/value_ctor_this_closure.ts new file mode 100644 index 000000000..681d0f62e --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_closure.ts @@ -0,0 +1,16 @@ +// ...nor a copy a closure reads later: `self.a` read 0, not 7 +@value +class V { + readonly a: number; + readonly f: () => number; + + constructor() { + const self = this; + this.f = () => self.a; + this.a = 7; + } +} + +function main() { + print(new V().f()); +} diff --git a/tslang/test/tester/value/value_ctor_this_const.ts b/tslang/test/tester/value/value_ctor_this_const.ts new file mode 100644 index 000000000..7207ff92a --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_const.ts @@ -0,0 +1,17 @@ +// `this` of a @value constructor is the slot `new` is filling, not a value yet: a copy taken here +// would miss the fields stored after it (`self.a` read 0, not 1). +@value +class V { + readonly a: number; + readonly b: number; + + constructor() { + const self = this; + this.a = 1; + this.b = self.a + 1; + } +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_ctor_this_init.ts b/tslang/test/tester/value/value_ctor_this_init.ts new file mode 100644 index 000000000..3c30bfb75 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_init.ts @@ -0,0 +1,19 @@ +// ...nor in an instance field's initializer, which runs in the constructor: the closure read the copy +// taken before `this.a = 7` (0, not 7) +function mk(v: V) { + return () => v.a; +} + +@value +class V { + readonly f: () => number = mk(this); + readonly a: number; + + constructor() { + this.a = 7; + } +} + +function main() { + print(new V().f()); +} diff --git a/tslang/test/tester/value/value_ctor_this_init_noctor.ts b/tslang/test/tester/value/value_ctor_this_init_noctor.ts new file mode 100644 index 000000000..946000b23 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_init_noctor.ts @@ -0,0 +1,14 @@ +// ...with no constructor written as well (`show(this)` read a = 0, not 7) +function show(v: V) { + return v.a; +} + +@value +class V { + readonly b: number = show(this); + readonly a: number = 7; +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_ctor_this_literal.ts b/tslang/test/tester/value/value_ctor_this_literal.ts new file mode 100644 index 000000000..aedc5577b --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_literal.ts @@ -0,0 +1,16 @@ +// ...nor a field of an object literal +@value +class V { + readonly a: number; + readonly b: number; + + constructor() { + const o = { v: this }; + this.a = 1; + this.b = o.v.a + 1; + } +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_ctor_this_method.ts b/tslang/test/tester/value/value_ctor_this_method.ts new file mode 100644 index 000000000..25d1acde7 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_method.ts @@ -0,0 +1,39 @@ +// `this` of a @value constructor read through its fields and methods is read as it is now: a method +// called after a field is set sees it, as does a closure that reads `this.a` and is called here, and a +// field initializer reading `this.a`. +@value +class W { + readonly a: number; + readonly b: number; + readonly c: number; + readonly d: number; + + constructor() { + this.a = 5; + this.b = this.twiceA(); + const f = () => this.a + this.b; + this.c = f(); + this.d = this["a"] + 1; + } + + twiceA() { + return this.a * 2; + } +} + +// ...and so does a field's initializer +@value +class I { + readonly a: number = 5; + readonly b: number = this.a * 2; +} + +function main() { + const w = new W(); + print(w.b); + assert(w.b == 10); + assert(w.c == 15); + assert(w.d == 6); + assert(new I().b == 10); + print("done."); +} diff --git a/tslang/test/tester/value/value_ctor_this_push.ts b/tslang/test/tester/value/value_ctor_this_push.ts new file mode 100644 index 000000000..ec6ebb0f6 --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_push.ts @@ -0,0 +1,16 @@ +// ...nor an element of an array +@value +class V { + readonly a: number; + + constructor(arr: V[]) { + arr.push(this); + this.a = 1; + } +} + +function main() { + const arr: V[] = []; + const v = new V(arr); + print(arr[0].a, v.a); +} diff --git a/tslang/test/tester/value/value_ctor_this_spread.ts b/tslang/test/tester/value/value_ctor_this_spread.ts new file mode 100644 index 000000000..0061738cd --- /dev/null +++ b/tslang/test/tester/value/value_ctor_this_spread.ts @@ -0,0 +1,16 @@ +// ...nor spread into an object literal (which failed first with an error of its own) +@value +class V { + readonly a: number; + readonly b: number; + + constructor() { + this.a = 1; + const o = { ...this }; + this.b = o.a; + } +} + +function main() { + print(new V().b); +} diff --git a/tslang/test/tester/value/value_extends.ts b/tslang/test/tester/value/value_extends.ts new file mode 100644 index 000000000..aa8e1a938 --- /dev/null +++ b/tslang/test/tester/value/value_extends.ts @@ -0,0 +1,10 @@ +// A @value class has no base: the layout of a value is its own fields. +class B {} + +@value +class V extends B { + constructor(public readonly x: number) {} +} + +function main() { +} diff --git a/tslang/test/tester/value/value_final.ts b/tslang/test/tester/value/value_final.ts new file mode 100644 index 000000000..9b1054a90 --- /dev/null +++ b/tslang/test/tester/value/value_final.ts @@ -0,0 +1,9 @@ +// A @value class is never extended, so @final adds nothing: say it once. +@value +@final +class V { + constructor(public readonly x: number) {} +} + +function main() { +} diff --git a/tslang/test/tester/value/value_from_class.ts b/tslang/test/tester/value/value_from_class.ts new file mode 100644 index 000000000..7792b1a3a --- /dev/null +++ b/tslang/test/tester/value/value_from_class.ts @@ -0,0 +1,15 @@ +// A @value class is nominal: an object of an ordinary class with the same fields is not one of its +// values. +@value +class V { + constructor(public readonly x: number, public readonly y: number) {} +} + +class C { + constructor(public x: number, public y: number) {} +} + +function main() { + const v: V = new C(1, 2); + print(v.x); +} diff --git a/tslang/test/tester/value/value_from_iface.ts b/tslang/test/tester/value/value_from_iface.ts new file mode 100644 index 000000000..d9ffee967 --- /dev/null +++ b/tslang/test/tester/value/value_from_iface.ts @@ -0,0 +1,17 @@ +// A @value class is nominal: a @value interface value of the same fields is not one of its values. +@value +class V { + constructor(public readonly x: number, public readonly y: number) {} +} + +@value +interface R { + readonly x: number; + readonly y: number; +} + +function main() { + const r: R = { x: 1, y: 2 }; + const b: V = r; + print(b.x); +} diff --git a/tslang/test/tester/value/value_from_literal.ts b/tslang/test/tester/value/value_from_literal.ts new file mode 100644 index 000000000..21858ca58 --- /dev/null +++ b/tslang/test/tester/value/value_from_literal.ts @@ -0,0 +1,11 @@ +// A @value class is nominal: a literal of its fields is not one of its values (its constructor never +// ran). +@value +class V { + constructor(public readonly x: number, public readonly y: number) {} +} + +function main() { + const a: V = { x: 1, y: 2 }; + print(a.x); +} diff --git a/tslang/test/tester/value/value_generic.ts b/tslang/test/tester/value/value_generic.ts new file mode 100644 index 000000000..eb5d94a20 --- /dev/null +++ b/tslang/test/tester/value/value_generic.ts @@ -0,0 +1,8 @@ +// A @value class is one layout, so it has no type parameters. +@value +class V { + constructor(public readonly x: number) {} +} + +function main() { +} diff --git a/tslang/test/tester/value/value_generic_field.ts b/tslang/test/tester/value/value_generic_field.ts new file mode 100644 index 000000000..f59300998 --- /dev/null +++ b/tslang/test/tester/value/value_generic_field.ts @@ -0,0 +1,30 @@ +// A field of a @value type whose generic's type argument is another @value type declared after it +// (and before): typed once that type is laid out, never as the unspecialized generic. +@value +interface L { + readonly v: number; + readonly box: Box; +} + +@value +interface K { + readonly v: number; +} + +class Box { + constructor(public l: T | null) {} +} + +@value +interface M { + readonly k: Box; +} + +function main() { + const a: L = { v: 1, box: new Box({ v: 2 }) }; + const m: M = { k: a.box }; + assert(a.v == 1); + const k = m.k.l; + assert(k !== null && k.v == 2); + print("done."); +} diff --git a/tslang/test/tester/value/value_generic_field_first.ts b/tslang/test/tester/value/value_generic_field_first.ts new file mode 100644 index 000000000..e84393c35 --- /dev/null +++ b/tslang/test/tester/value/value_generic_field_first.ts @@ -0,0 +1,32 @@ +// ...and with the generic declared first, before the @value types (on the first pass K is not even +// declared yet when L's field is typed) +class Box { + constructor(public l: T | null) {} +} + +@value +interface L { + readonly v: number; + readonly box: Box; +} + +@value +interface K { + readonly v: number; +} + +@value +interface M { + readonly k: Box; +} + +function main() { + const a: L = { v: 1, box: new Box({ v: 2 }) }; + assert(a.v == 1); + const k = a.box.l; + assert(k !== null && k.v == 2); + const m: M = { k: new Box({ v: 3 }) }; + const mk = m.k.l; + assert(mk !== null && mk.v == 3); + print("done."); +} diff --git a/tslang/test/tester/value/value_generic_unknown.ts b/tslang/test/tester/value/value_generic_unknown.ts new file mode 100644 index 000000000..616609f87 --- /dev/null +++ b/tslang/test/tester/value/value_generic_unknown.ts @@ -0,0 +1,15 @@ +// A @value type's field naming a generic of a type that does not exist is an error naming it (the +// unspecialized Box was taken in silence) +class Box { + constructor(public l: T | null) {} +} + +@value +interface L { + readonly v: number; + readonly box: Box; +} + +function main() { + print(1); +} diff --git a/tslang/test/tester/value/value_identity.ts b/tslang/test/tester/value/value_identity.ts new file mode 100644 index 000000000..775e52b3b --- /dev/null +++ b/tslang/test/tester/value/value_identity.ts @@ -0,0 +1,9 @@ +// Two @value values have no identity to compare: each is a copy. +@value +class V { + constructor(public readonly x: number) {} +} + +function main() { + print(new V(1) === new V(1)); +} diff --git a/tslang/test/tester/value/value_iface_cycle.ts b/tslang/test/tester/value/value_iface_cycle.ts new file mode 100644 index 000000000..d04b8be7c --- /dev/null +++ b/tslang/test/tester/value/value_iface_cycle.ts @@ -0,0 +1,39 @@ +// A @value interface holding an ordinary interface that returns it, declared before it: +// `Hit.thing: Thing` and `Thing.intersect(): Hit | null`. The interface's method and the class's +// both see Hit with all its fields, so the class implements the interface. +@value +interface Hit { + readonly thing: Thing; + readonly d: number; +} + +interface Thing { + intersect(x: number): Hit | null; + id(): int; +} + +class S implements Thing { + constructor(private n: int) {} + + intersect(x: number): Hit | null { + if (x > 0) { + return { thing: this, d: x }; + } + + return null; + } + + id(): int { + return this.n; + } +} + +function main() { + const t: Thing = new S(3); + const h = t.intersect(2); + assert(h != null); + assert(h.thing.id() == 3); + assert(h.d == 2); + assert(t.intersect(-1) === null); + print("done."); +} diff --git a/tslang/test/tester/value/value_iface_extends.ts b/tslang/test/tester/value/value_iface_extends.ts new file mode 100644 index 000000000..bdec45df5 --- /dev/null +++ b/tslang/test/tester/value/value_iface_extends.ts @@ -0,0 +1,12 @@ +// A @value interface extends only another @value interface: a value has no base layout to widen. +interface I { + readonly a: number; +} + +@value +interface R extends I { + readonly b: number; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_iface_extends_class.ts b/tslang/test/tester/value/value_iface_extends_class.ts new file mode 100644 index 000000000..08a0e6ccc --- /dev/null +++ b/tslang/test/tester/value/value_iface_extends_class.ts @@ -0,0 +1,13 @@ +// A @value interface extends only another @value interface: a class's fields are seen through a +// reference, not copied. +class C { + readonly a: number = 1; +} + +@value +interface R extends C { + readonly b: number; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_iface_generic.ts b/tslang/test/tester/value/value_iface_generic.ts new file mode 100644 index 000000000..6bcd1a9e7 --- /dev/null +++ b/tslang/test/tester/value/value_iface_generic.ts @@ -0,0 +1,8 @@ +// A @value interface is one layout, so it has no type parameters. +@value +interface R { + readonly f: T; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_iface_identity.ts b/tslang/test/tester/value/value_iface_identity.ts new file mode 100644 index 000000000..b2b170728 --- /dev/null +++ b/tslang/test/tester/value/value_iface_identity.ts @@ -0,0 +1,12 @@ +// Two @value values have no identity to compare: each is a copy. +@value +interface Ray { + readonly start: number; + readonly dir: number; +} + +function main() { + const r1: Ray = { start: 1, dir: 2 }; + const r2: Ray = { start: 1, dir: 2 }; + print(r1 === r2); +} diff --git a/tslang/test/tester/value/value_iface_method.ts b/tslang/test/tester/value/value_iface_method.ts new file mode 100644 index 000000000..d1e703254 --- /dev/null +++ b/tslang/test/tester/value/value_iface_method.ts @@ -0,0 +1,9 @@ +// A @value interface has only fields: a value has no vtable to call a method through. +@value +interface R { + readonly f: number; + m(): int; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_iface_mutable.ts b/tslang/test/tester/value/value_iface_mutable.ts new file mode 100644 index 000000000..4bb87cefc --- /dev/null +++ b/tslang/test/tester/value/value_iface_mutable.ts @@ -0,0 +1,8 @@ +// A field of a @value interface is readonly: a field that could change would make its copies differ. +@value +interface R { + f: number; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_iface_optional.ts b/tslang/test/tester/value/value_iface_optional.ts new file mode 100644 index 000000000..698371489 --- /dev/null +++ b/tslang/test/tester/value/value_iface_optional.ts @@ -0,0 +1,8 @@ +// A field of a @value interface is always there: an absent field has no slot in the value. +@value +interface R { + readonly f?: number; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_implements.ts b/tslang/test/tester/value/value_implements.ts new file mode 100644 index 000000000..ab2fa9506 --- /dev/null +++ b/tslang/test/tester/value/value_implements.ts @@ -0,0 +1,15 @@ +// A value has no vtable, so it cannot be seen through an interface. +interface I { + m(): number; +} + +@value +class V implements I { + constructor(public readonly x: number) {} + m() { + return this.x; + } +} + +function main() { +} diff --git a/tslang/test/tester/value/value_instanceof.ts b/tslang/test/tester/value/value_instanceof.ts new file mode 100644 index 000000000..f0d6b5442 --- /dev/null +++ b/tslang/test/tester/value/value_instanceof.ts @@ -0,0 +1,10 @@ +// A value carries no type information to test. +@value +class V { + constructor(public readonly x: number) {} +} + +function main() { + const v = new V(1); + print(v instanceof V); +} diff --git a/tslang/test/tester/value/value_interface.ts b/tslang/test/tester/value/value_interface.ts new file mode 100644 index 000000000..915805805 --- /dev/null +++ b/tslang/test/tester/value/value_interface.ts @@ -0,0 +1,70 @@ +// `@value interface`: a literal of the interface's type is a value - a tuple of its fields in +// declaration order, with no box and no vtable. It is read, passed, nested and converted. (A literal +// nested in another, and a conversion to an ordinary interface: value_interface_own_gaps.ts.) +class Vec { + constructor(public x: number, public y: number) {} +} + +interface Thing { + id(): int; +} + +class T1 implements Thing { + id(): int { + return 7; + } +} + +@value +interface Ray { + readonly start: Vec; + readonly dir: Vec; +} + +@value +interface Hit { + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; +} + +function mk(s: Vec, d: Vec): Ray { + return { start: s, dir: d }; +} + +// the fields are written in another order than the interface's +function hit(t: Thing, r: Ray, d: number): Hit { + return { dist: d, ray: r, thing: t }; +} + +function len(r: Ray) { + return r.start.x + r.dir.y; +} + +function main() { + assert(len({ start: new Vec(1, 2), dir: new Vec(3, 4) }) == 5); + + const h = hit(new T1(), mk(new Vec(1, 0), new Vec(0, 2)), 9); + assert(h.dist == 9 && h.thing.id() == 7 && h.ray.dir.y == 2); + + // converted: to `any`, to a type literal and back + // tslang reads no member of an `any`: the value is cast back to read it + const a: any = mk(new Vec(8, 0), new Vec(0, 0)); + assert((a).start.x == 8); + + const tl: { start: Vec; dir: Vec } = mk(new Vec(2, 0), new Vec(0, 4)); + const back: Ray = tl; + assert(back.start.x == tl.start.x && back.dir.y == tl.dir.y); + assert(back.start.x == 2 && back.dir.y == 4); + + assert(typeof mk(new Vec(0, 0), new Vec(0, 0)) == "object"); + + let total: number = 0; + for (let i = 0; i < 10000; i++) { + total += len(mk(new Vec(i, 0), new Vec(0, 1))); + } + + assert(total == 50005000); + + print("done."); +} diff --git a/tslang/test/tester/value/value_interface_own_gaps.ts b/tslang/test/tester/value/value_interface_own_gaps.ts new file mode 100644 index 000000000..94e2d8205 --- /dev/null +++ b/tslang/test/tester/value/value_interface_own_gaps.ts @@ -0,0 +1,50 @@ +// The two checks of value_interface.ts that -mm=own rejects (own spec 36, "Not here"); every other +// model runs them. A literal nested in another, holding new vectors and a new T1, out of order: an +// owning tuple moved into a tuple's field (#679's limit). A record that borrows two temporaries, +// converted to an ordinary interface: the box made of it would own what the record borrows. +class Vec { + constructor(public x: number, public y: number) {} +} + +interface Thing { + id(): int; +} + +class T1 implements Thing { + id(): int { + return 7; + } +} + +@value +interface Ray { + readonly start: Vec; + readonly dir: Vec; +} + +@value +interface Hit { + readonly thing: Thing; + readonly ray: Ray; + readonly dist: number; +} + +interface HasStart { + start: Vec; +} + +function mk(s: Vec, d: Vec): Ray { + return { start: s, dir: d }; +} + +function main() { + // nested two levels, each out of order + const n: Hit = { ray: { dir: new Vec(0, 3), start: new Vec(5, 0) }, dist: 1, thing: new T1() }; + assert(n.ray.start.x == 5 && n.ray.dir.y == 3 && n.thing.id() == 7); + + // converted to an ordinary interface + const s: HasStart = mk(new Vec(6, 0), new Vec(0, 0)); + assert(s.start.x == 6); + + print("done."); +} diff --git a/tslang/test/tester/value/value_missing.ts b/tslang/test/tester/value/value_missing.ts new file mode 100644 index 000000000..9f32d7028 --- /dev/null +++ b/tslang/test/tester/value/value_missing.ts @@ -0,0 +1,162 @@ +// @strict-null false +// A @value type has no null pointer: `T | null`, `T | undefined`, `T | null | undefined`, `v?: T` +// and `f?: T` are one optional value that keeps which of null and undefined it holds, as TypeScript +// does. It is returned, passed, held in a field, converted between those spellings, compared with +// null and undefined, switched on, and read after a check or through `?.`. +@value +interface Hit { + readonly dist: number; +} + +interface Holder { + hit?: Hit; +} + +class Box { + hit?: Hit; +} + +class HitBox implements Holder { + hit?: Hit; +} + +interface Based { + x: number; +} + +// `f` is a member of one side only: of the intersection, an optional one +type Either = Based & ({ f: Hit } | { g: number }); + +function find(d: number): Hit | null { + if (d < 0) return null; + return { dist: d }; +} + +function first(xs: number[]): Hit | undefined { + let best: Hit | undefined = undefined; + for (const x of xs) { + const h = find(x); + if (h != null && (best === undefined || h.dist < best.dist)) best = h; + } + + return best; +} + +function opt(v?: Hit) { + return v === undefined ? -1 : v.dist; +} + +// what an optional parameter was given: nothing, null or a value +function state(v?: Hit) { + return v === undefined ? 0 : v === null ? 1 : 2; +} + +function sw(d: number) { + switch (find(d)) { + case null: + return 1; + default: + return 2; + } +} + +function swu(xs: number[]) { + switch (first(xs)) { + case undefined: + return 1; + default: + return 2; + } +} + +function main() { + assert(find(-1) === null); + assert(!(find(-1) != null)); + assert(find(2).dist == 2); + + assert(first([3, -1, 2]).dist == 2); + assert(first([-1]) === undefined); + + assert(find(5)?.dist == 5); + assert(find(-5)?.dist === undefined); + + assert(opt() == -1); + assert(opt({ dist: 4 }) == 4); + + const none: Holder = {}; + const some: Holder = { hit: { dist: 8 } }; + assert(none.hit === undefined && none.hit?.dist === undefined); + assert(some.hit !== undefined && some.hit.dist == 8); + + const box = new Box(); + assert(box.hit === undefined); + box.hit = find(7); + assert(box.hit.dist == 7); + + // a class's `hit?: Hit` seen through the interface, in each state, and written through it + const hitBox = new HitBox(); + const viaImplements: Holder = hitBox; + assert(viaImplements.hit === undefined && !(viaImplements.hit === null)); + hitBox.hit = null; + assert(viaImplements.hit === null && !(viaImplements.hit === undefined)); + hitBox.hit = find(6); + assert(viaImplements.hit.dist == 6); + viaImplements.hit = find(2); + assert(hitBox.hit.dist == 2); + viaImplements.hit = null; + assert(hitBox.hit === null && !(hitBox.hit === undefined)); + viaImplements.hit = undefined; + assert(hitBox.hit === undefined && !(hitBox.hit === null)); + + // ...and of one that does not say it implements it + const plainBox = new Box(); + const viaShape: Holder = plainBox; + assert(viaShape.hit === undefined && !(viaShape.hit === null)); + plainBox.hit = null; + assert(viaShape.hit === null && !(viaShape.hit === undefined)); + plainBox.hit = find(4); + assert(viaShape.hit.dist == 4); + viaShape.hit = find(3); + assert(plainBox.hit.dist == 3); + viaShape.hit = null; + assert(plainBox.hit === null); + viaShape.hit = undefined; + assert(plainBox.hit === undefined); + + const withF: Either = { x: 1, f: { dist: 9 } }; + assert(withF.f.dist == 9); + const withG: Either = { x: 2, g: 3 }; + assert(withG.f === undefined && !(withG.f === null)); + + let u: Hit | null | undefined = null; + assert(!(u === undefined)); + assert(u === null); + + // null and undefined stay apart, whichever spelling holds them + assert(!(find(-1) === undefined)); + assert(!(first([-1]) === null)); + let n: Hit | null | undefined = find(-1); + assert(n === null && !(n === undefined)); + n = first([-1]); + assert(n === undefined && !(n === null)); + n = find(9); + assert(n !== null && n !== undefined && n.dist == 9); + const asUndefinable: Hit | undefined = find(-1); + assert(asUndefinable === null); + const asNullable: Hit | null = first([-1]); + assert(asNullable === undefined); + const present: Hit | null = first([5]); + assert(present.dist == 5); + assert(find(-1) == null && first([-1]) == null && find(-1) == undefined); + + assert(state() == 0); + assert(state(null) == 1); + assert(state({ dist: 1 }) == 2); + + assert(sw(-1) == 1); + assert(sw(3) == 2); + assert(swu([-1]) == 1); + assert(swu([3]) == 2); + + print("done."); +} diff --git a/tslang/test/tester/value/value_missing_identity.ts b/tslang/test/tester/value/value_missing_identity.ts new file mode 100644 index 000000000..7bb5a6692 --- /dev/null +++ b/tslang/test/tester/value/value_missing_identity.ts @@ -0,0 +1,15 @@ +// @strict-null false +// Two @value values that may be missing have no identity to compare either: only null and +// undefined are compared with one. +@value +interface Hit { + readonly dist: number; +} + +function find(d: number): Hit | null { + return { dist: d }; +} + +function main() { + print(find(1) === find(1)); +} diff --git a/tslang/test/tester/value/value_missing_read.ts b/tslang/test/tester/value/value_missing_read.ts new file mode 100644 index 000000000..3e85cbc79 --- /dev/null +++ b/tslang/test/tester/value/value_missing_read.ts @@ -0,0 +1,70 @@ +// @strict-null false +// A missing @value value has no fields: reading one, calling a member of one, or converting one to +// the plain type throws, as a member of a null object does. +@value +interface Hit { + readonly dist: number; +} + +@value +class V { + constructor(public readonly x: number) {} + + get twice() { + return this.x * 2; + } +} + +function find(d: number): Hit | null { + if (d < 0) return null; + return { dist: d }; +} + +function first(d: number): Hit | undefined { + if (d < 0) return undefined; + return { dist: d }; +} + +function mk(x: number): V | null { + if (x < 0) return null; + return new V(x); +} + +function main() { + let caught = 0; + + try { + print(find(-1).dist); + } catch (e) { + caught++; + } + + try { + print(first(-1).dist); + } catch (e) { + caught++; + } + + try { + print(mk(-1).twice); + } catch (e) { + caught++; + } + + // under `@strict-null false` the conversion to the plain type throws, before any read + try { + const h: Hit = find(-1); + print("not here"); + } catch (e) { + caught++; + } + + assert(caught == 4); + + // a value there is read as it is + assert(find(3).dist == 3 && mk(4).twice == 8); + const h: Hit = find(5); + assert(h.dist == 5); + + print("done."); +} diff --git a/tslang/test/tester/value/value_mutable_field.ts b/tslang/test/tester/value/value_mutable_field.ts new file mode 100644 index 000000000..15c43a9be --- /dev/null +++ b/tslang/test/tester/value/value_mutable_field.ts @@ -0,0 +1,8 @@ +// A field a @value value could change would make its copies differ. +@value +class V { + x: number = 0; +} + +function main() { +} diff --git a/tslang/test/tester/value/value_mutual_methods.ts b/tslang/test/tester/value/value_mutual_methods.ts new file mode 100644 index 000000000..7eca9043f --- /dev/null +++ b/tslang/test/tester/value/value_mutual_methods.ts @@ -0,0 +1,42 @@ +// Methods of an ordinary class that call each other before all of them are declared, returning a +// @value class: while the first is discovered the others' results are not known yet, and that +// unresolved result is not a conversion to report (the ray tracer's traceRay/shade/reflection). +@value +class Color { + constructor(public readonly r: number) {} + + static scale(k: number, v: Color) { + return new Color(k * v.r); + } + + static grey = new Color(0.5); +} + +class RT { + private maxDepth = 5; + + private traceRay(x: number, depth: number): Color { + if (depth > 3) { + return Color.grey; + } + + return this.shade(x, depth); + } + + private shade(x: number, depth: number) { + return depth >= this.maxDepth ? Color.grey : this.reflect(x, depth); + } + + private reflect(x: number, depth: number) { + return Color.scale(x, this.traceRay(x, depth + 1)); + } + + run() { + return this.traceRay(2, 0).r; + } +} + +function main() { + assert(new RT().run() == 8); + print("done."); +} diff --git a/tslang/test/tester/value/value_no_alloc.ts b/tslang/test/tester/value/value_no_alloc.ts new file mode 100644 index 000000000..a5400cba4 --- /dev/null +++ b/tslang/test/tester/value/value_no_alloc.ts @@ -0,0 +1,35 @@ +// A literal of a @value interface is a value: `len2` builds one, nested, and passes it on with no +// allocation in its optimized code (value-no-alloc.cmake reads the IR). So is `new` of a @value +// class: `plus2` makes three and allocates nothing either. +@value +interface Vec { + readonly x: number; + readonly y: number; +} + +@value +interface Ray { + readonly start: Vec; + readonly dir: Vec; +} + +function len(r: Ray) { + return r.start.x + r.dir.y; +} + +export function len2(a: number, b: number): number { + return len({ start: { x: a, y: 0 }, dir: { x: 0, y: b } }); +} + +@value +class V { + constructor(public readonly x: number, public readonly y: number, public readonly z: number) {} + + static plus(a: V, b: V) { + return new V(a.x + b.x, a.y + b.y, a.z + b.z); + } +} + +export function plus2(a: number): number { + return V.plus(new V(a, 0, 0), new V(a, 0, 0)).x; +} diff --git a/tslang/test/tester/value/value_null_plain.ts b/tslang/test/tester/value/value_null_plain.ts new file mode 100644 index 000000000..62ae411a3 --- /dev/null +++ b/tslang/test/tester/value/value_null_plain.ts @@ -0,0 +1,15 @@ +// @strict-null false +// A @value type has no null, even where null checks are not strict: a missing value is written +// `T | null`. +@value +interface Hit { + readonly dist: number; +} + +function f(): Hit { + return null; +} + +function main() { + print(f().dist); +} diff --git a/tslang/test/tester/value/value_optional_chain.ts b/tslang/test/tester/value/value_optional_chain.ts new file mode 100644 index 000000000..f62aa5ca3 --- /dev/null +++ b/tslang/test/tester/value/value_optional_chain.ts @@ -0,0 +1,60 @@ +// `a?.b.c`: once `?.` meets a missing value the rest of the chain is skipped and the result is +// undefined, as in TypeScript - for a @value type (whose missing value threw at `.dir`) and for a type +// literal (which read 0). Present, the chain reads through; a call at its end is skipped too. +@value +class V { + constructor(public readonly x: number, public readonly y: number) {} + + len() { + return this.x + this.y; + } +} + +@value +interface Ray { + readonly start: V; + readonly dir: V; +} + +@value +interface Hit { + readonly ray: Ray; + readonly dist: number; +} + +function find(d: number): Hit | null { + if (d < 0) return null; + return { ray: { start: new V(d, 1), dir: new V(2, d) }, dist: d }; +} + +type TV = { x: number; y: number }; +type TRay = { start: TV; dir: TV }; +type THit = { ray: TRay; dist: number }; + +function findT(d: number): THit | null { + if (d < 0) return null; + return { ray: { start: { x: d, y: 1 }, dir: { x: 2, y: d } }, dist: d }; +} + +function main() { + const g = find(-1); + const r = g?.ray.dir.x; + print("missing", r === undefined ? "undefined" : r); + assert(r === undefined); + assert(g?.ray.dir.len() === undefined); + + const f = find(3); + print("present", f?.ray.dir.y); + assert(f?.ray.dir.y === 3); + assert(f?.ray.dir.len() === 5); + + const tg = findT(-1); + const tr = tg?.ray.dir.x; + print("missing literal", tr === undefined ? "undefined" : tr); + assert(tr === undefined); + + const tf = findT(4); + assert(tf?.ray.dir.y === 4); + + print("done."); +} diff --git a/tslang/test/tester/value/value_optional_member_literal.ts b/tslang/test/tester/value/value_optional_member_literal.ts new file mode 100644 index 000000000..426535884 --- /dev/null +++ b/tslang/test/tester/value/value_optional_member_literal.ts @@ -0,0 +1,18 @@ +// @strict-null false +// An optional member of a @value type is read as the optional value a `f?: T` field stores: a +// literal whose field is a plain T (not typed by the interface) cannot stand in for it. +@value +interface Hit { + readonly dist: number; +} + +interface J { + f?: Hit; +} + +function main() { + const h: Hit = { dist: 1 }; + const lit = { f: h }; + const j: J = lit; + print(j.f.dist); +} diff --git a/tslang/test/tester/value/value_optional_member_plain_field.ts b/tslang/test/tester/value/value_optional_member_plain_field.ts new file mode 100644 index 000000000..431600653 --- /dev/null +++ b/tslang/test/tester/value/value_optional_member_plain_field.ts @@ -0,0 +1,20 @@ +// @strict-null false +// An optional member of a @value type is read as the optional value a `f?: T` field stores: a +// plain `f: T` field cannot stand in for it. +@value +interface Hit { + readonly dist: number; +} + +interface J { + f?: Hit; +} + +class Req implements J { + f: Hit = { dist: 1 }; +} + +function main() { + const j: J = new Req(); + print(j.f.dist); +} diff --git a/tslang/test/tester/value/value_rc_field_retain.ts b/tslang/test/tester/value/value_rc_field_retain.ts new file mode 100644 index 000000000..9ee8e1427 --- /dev/null +++ b/tslang/test/tester/value/value_rc_field_retain.ts @@ -0,0 +1,59 @@ +// Under rc, a field of a @value value held in an ordinary class's field, read into a const or into a +// literal of the @value interface, is retained the way the same read of a type literal is +// (value-rc-field-retain.cmake compares each pair of functions' retains and releases). +class Vec { + constructor(public x: number) {} +} + +@value +interface Ray { + readonly start: Vec; + readonly dir: Vec; +} + +type RayT = { start: Vec; dir: Vec }; + +class Hit { + r: Ray; + + constructor(r: Ray) { + this.r = r; + } +} + +class HitT { + r: RayT; + + constructor(r: RayT) { + this.r = r; + } +} + +function rayFromHit(h: Hit) { + const o: Ray = { start: h.r.start, dir: h.r.dir }; + return o.start.x + o.dir.x; +} + +function rayTFromHit(h: HitT) { + const o: RayT = { start: h.r.start, dir: h.r.dir }; + return o.start.x + o.dir.x; +} + +function startFromHit(h: Hit) { + const s = h.r.start; + h.r = { start: new Vec(5), dir: new Vec(6) }; + return s.x; +} + +function startTFromHit(h: HitT) { + const s = h.r.start; + h.r = { start: new Vec(5), dir: new Vec(6) }; + return s.x; +} + +function main() { + print(rayFromHit(new Hit({ start: new Vec(1), dir: new Vec(2) }))); + print(rayTFromHit(new HitT({ start: new Vec(1), dir: new Vec(2) }))); + print(startFromHit(new Hit({ start: new Vec(1), dir: new Vec(2) }))); + print(startTFromHit(new HitT({ start: new Vec(1), dir: new Vec(2) }))); +} diff --git a/tslang/test/tester/value/value_readonly_incdec.ts b/tslang/test/tester/value/value_readonly_incdec.ts new file mode 100644 index 000000000..af54a902a --- /dev/null +++ b/tslang/test/tester/value/value_readonly_incdec.ts @@ -0,0 +1,30 @@ +// The fields of a @value value are readonly: `++`/`--` assign them too, on a local's value, in a +// method and in a closure inside the constructor. +@value +class V { + constructor(public readonly x: number) {} + + bump() { + ++this.x; + return this.x; + } +} + +@value +class W { + readonly a: number; + + constructor(a: number) { + this.a = a; + const f = () => { + this.a++; + }; + f(); + } +} + +function main() { + let v = new V(1); + v.x--; + print(v.x, v.bump(), new W(5).a); +} diff --git a/tslang/test/tester/value/value_readonly_method.ts b/tslang/test/tester/value/value_readonly_method.ts new file mode 100644 index 000000000..885c0e8c3 --- /dev/null +++ b/tslang/test/tester/value/value_readonly_method.ts @@ -0,0 +1,19 @@ +// The fields of a @value value are readonly: a method does not assign them. +class Node { + constructor(public n: int) {} +} + +@value +class H { + constructor(public readonly node: Node) {} + + set(n: int) { + this.node = new Node(n); + return this.node.n; + } +} + +function main() { + const h = new H(new Node(1)); + print(h.set(5)); +} diff --git a/tslang/test/tester/value/value_readonly_nested_ctor.ts b/tslang/test/tester/value/value_readonly_nested_ctor.ts new file mode 100644 index 000000000..6b34bd02b --- /dev/null +++ b/tslang/test/tester/value/value_readonly_nested_ctor.ts @@ -0,0 +1,23 @@ +// The fields of a @value value are readonly: only its own constructor's body assigns them, through +// `this`, and a closure inside the constructor is not that body. +class Node { + constructor(public n: int) {} +} + +@value +class H { + readonly node: Node; + + constructor(n: int) { + this.node = new Node(0); + const f = () => { + this.node = new Node(n); + }; + f(); + } +} + +function main() { + const h = new H(7); + print(h.node.n); +} diff --git a/tslang/test/tester/value/value_readonly_outside.ts b/tslang/test/tester/value/value_readonly_outside.ts new file mode 100644 index 000000000..21c25ac19 --- /dev/null +++ b/tslang/test/tester/value/value_readonly_outside.ts @@ -0,0 +1,12 @@ +// The fields of a @value value are readonly: a @value class's value held in a variable is not +// assigned (a @value interface's: value_readonly_outside_iface.ts). +@value +class V { + constructor(public readonly x: number) {} +} + +function main() { + const v = new V(1); + v.x = 2; + print(v.x); +} diff --git a/tslang/test/tester/value/value_readonly_outside_iface.ts b/tslang/test/tester/value/value_readonly_outside_iface.ts new file mode 100644 index 000000000..14f3939fb --- /dev/null +++ b/tslang/test/tester/value/value_readonly_outside_iface.ts @@ -0,0 +1,17 @@ +// The fields of a @value value are readonly: a @value interface's value held in a variable is not +// assigned. +class Node { + constructor(public n: int) {} +} + +@value +interface Ray { + readonly start: Node; + readonly dir: Node; +} + +function main() { + const r: Ray = { start: new Node(1), dir: new Node(2) }; + r.start = new Node(3); + print(r.start.n); +} diff --git a/tslang/test/tester/value/value_refs.ts b/tslang/test/tester/value/value_refs.ts new file mode 100644 index 000000000..8bbeae911 --- /dev/null +++ b/tslang/test/tester/value/value_refs.ts @@ -0,0 +1,251 @@ +// A @value value holding references: copying it copies them as a tuple copy does (rc retains each +// one), through locals, an array, a generic and a closure, and a constructor's stores into its fields +// count as stores into an owned local's. A closure captures the binding of a @value local, not a +// snapshot; one in a @value constructor reads `this` as the value set so far (and is only called +// there), and one in a method takes a copy of `this`. Each read of a copy follows `churn()`, which +// reuses the blocks a missing retain would have freed (same-size objects), and reads the field first. +class Node { + constructor(public n: int) {} +} + +@value +interface Rec { + readonly node: Node; + readonly w: number; +} + +@value +class V { + constructor(public readonly x: number) {} + + static plus(a: V, b: V) { + return new V(a.x + b.x); + } +} + +// a field computed by a closure that reads `this` in the constructor +@value +class W { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + const f = () => this.a + 1; + this.b = f(); + } +} + +// ...and through a closure inside a closure, several values in one frame +@value +class W2 { + readonly a: number; + readonly b: number; + + constructor(a: number) { + this.a = a; + const f = () => { + const h = () => this.a + 1; + return h(); + }; + this.b = f(); + } +} + +// a constructor storing a new reference in a field, one storing its parameter (a parameter property +// and an assignment) +@value +class Holder { + readonly node: Node; + + constructor(n: int) { + this.node = new Node(n); + } +} + +@value +class HolderP { + constructor(public readonly node: Node) {} +} + +@value +class HolderA { + readonly node: Node; + + constructor(n: Node) { + this.node = n; + } +} + +// closures in methods, which take a copy of `this`: one returned, one inside another +@value +class Box { + constructor(public readonly node: Node) {} + + reader() { + return () => this.node.n; + } + + nested() { + const f = () => { + const h = () => this.node.n; + return h(); + }; + return f(); + } +} + +// a @value interface of references, held in an ordinary class's field +@value +interface Ray { + readonly start: Node; + readonly dir: Node; +} + +class Hit { + r: Ray; + + constructor(r: Ray) { + this.r = r; + } +} + +function churn() { + let s = 0; + for (let i = 0; i < 64; i++) { + const t = new Node(i); + s += t.n; + } + return s; +} + +function id(t: T) { + return t; +} + +function makeReader(r: Rec) { + return () => r.node.n; +} + +function makeHolder(i: int) { + return new Holder(i); +} + +function makeHolderP(i: int) { + return new HolderP(new Node(i)); +} + +function makeHolderA(i: int) { + return new HolderA(new Node(i)); +} + +// a value's fields hold what its constructor stored in them, a new reference too +function constructed() { + const h = new Holder(7); + churn(); + assert(h.node.n == 7); + + let sum = 0; + for (let i = 0; i < 100; i++) { + const a = makeHolder(i); + const b = makeHolderP(i); + const c = makeHolderA(i); + churn(); + sum += a.node.n + b.node.n + c.node.n; + } + + assert(sum == 3 * 4950); +} + +// a closure a method returned keeps its copy of `this` after the value it was called on is overwritten +function methodClosures() { + const boxes: Box[] = [new Box(new Node(9))]; + const r = boxes[0].reader(); + boxes[0] = new Box(new Node(-1)); + churn(); + assert(r() == 9); + assert(new Box(new Node(3)).nested() == 3); +} + +// several values in one frame, each from a constructor whose closures read `this` +function closuresInConstructors(k: number) { + const p = new W2(k); + const q = new W2(k + 10); + const r = new W2(k + 20); + assert(p.b == k + 1); + assert(q.b == k + 11); + assert(r.b == k + 21); + assert(new W(4).b == 5); +} + +// copies of an array's values outlive the array's reference to their Nodes +function copies() { + const recs: Rec[] = []; + for (let i = 0; i < 1000; i++) { + recs.push({ node: new Node(i), w: i }); + } + + let sum = 0; + for (let i = 0; i < 1000; i++) { + const a = recs[i]; + const b = recs[i]; + recs[i] = { node: new Node(-1), w: 0 }; + churn(); + sum += a.node.n + b.node.n; + } + + assert(sum == 999000); +} + +// ...and so does one passed through a generic +function throughGeneric() { + const recs: Rec[] = [{ node: new Node(11), w: 1 }]; + const c = id(recs[0]); + recs[0] = { node: new Node(-1), w: 0 }; + churn(); + assert(c.node.n == 11); +} + +// a literal of fields read from a value in a class's field, and a const of one, keep them after the +// field changes +function rayFromHit() { + const h = new Hit({ start: new Node(3), dir: new Node(4) }); + const o: Ray = { start: h.r.start, dir: h.r.dir }; + const s = h.r.start; + h.r = { start: new Node(5), dir: new Node(6) }; + churn(); + assert(o.start.n == 3); + assert(o.dir.n == 4); + assert(s.n == 3); +} + +// a closure that captures a Rec reads its own Node after the original's was overwritten +function closures() { + const recs: Rec[] = [{ node: new Node(7), w: 1 }]; + const r = recs[0]; + const f = () => r.node.n; + const g = makeReader(recs[0]); + recs[0] = { node: new Node(-1), w: 0 }; + churn(); + assert(f() == 7); + assert(g() == 7); +} + +function main() { + copies(); + throughGeneric(); + rayFromHit(); + closures(); + constructed(); + methodClosures(); + closuresInConstructors(1); + + assert([new V(1), new V(2), new V(3)].reduce((acc, x) => V.plus(acc, x), new V(0)).x == 6); + + let v = new V(1); + const f = () => v.x; + v = new V(2); + assert(f() == 2); + + print("done."); +} diff --git a/tslang/test/tester/value/value_self_array.ts b/tslang/test/tester/value/value_self_array.ts new file mode 100644 index 000000000..f2a92c174 --- /dev/null +++ b/tslang/test/tester/value/value_self_array.ts @@ -0,0 +1,11 @@ +// ...or an array of itself: the array's element type is the type being laid out +@value +interface L { + readonly v: number; + readonly next: L[]; +} + +function main() { + const a: L = { v: 1, next: [] }; + print(a.v); +} diff --git a/tslang/test/tester/value/value_self_class.ts b/tslang/test/tester/value/value_self_class.ts new file mode 100644 index 000000000..038bb5688 --- /dev/null +++ b/tslang/test/tester/value/value_self_class.ts @@ -0,0 +1,10 @@ +// ...a @value class as well +@value +class N { + constructor(public readonly v: number, public readonly next: N | null) {} +} + +function main() { + const b = new N(2, new N(1, null)); + print(b.next ? b.next.v : -1); +} diff --git a/tslang/test/tester/value/value_self_generic.ts b/tslang/test/tester/value/value_self_generic.ts new file mode 100644 index 000000000..03e723b6f --- /dev/null +++ b/tslang/test/tester/value/value_self_generic.ts @@ -0,0 +1,18 @@ +// A @value type named in a type argument of its own field's generic (`box: Box`): the specialized +// class's type is made from L's, so L cannot hold it. The unspecialized `Box` was taken instead, and +// the compiler crashed at the literal. +class Box { + constructor(public l: T | null) {} +} + +@value +interface L { + readonly v: number; + readonly box: Box; +} + +function main() { + const bx = new Box(null); + const a: L = { v: 1, box: bx }; + print(a.v); +} diff --git a/tslang/test/tester/value/value_self_generic_class.ts b/tslang/test/tester/value/value_self_generic_class.ts new file mode 100644 index 000000000..196ae8a46 --- /dev/null +++ b/tslang/test/tester/value/value_self_generic_class.ts @@ -0,0 +1,14 @@ +// ...a @value class as well +class Box { + constructor(public l: T | null) {} +} + +@value +class L { + constructor(public readonly v: number, public readonly box: Box) {} +} + +function main() { + const bx = new Box(null); + print(new L(1, bx).v); +} diff --git a/tslang/test/tester/value/value_self_generic_mutual.ts b/tslang/test/tester/value/value_self_generic_mutual.ts new file mode 100644 index 000000000..7827b9368 --- /dev/null +++ b/tslang/test/tester/value/value_self_generic_mutual.ts @@ -0,0 +1,23 @@ +// ...or through another @value type it names in a type argument, declared after it, with the generic +// declared first (the unspecialized Box was taken and the compiler crashed at the literal) +class Box { + constructor(public l: T | null) {} +} + +@value +interface A { + readonly v: number; + readonly p: Box; +} + +@value +interface B { + readonly w: number; + readonly a: A; +} + +function main() { + const bx = new Box(null); + const a: A = { v: 1, p: bx }; + print(a.v); +} diff --git a/tslang/test/tester/value/value_self_generic_pair.ts b/tslang/test/tester/value/value_self_generic_pair.ts new file mode 100644 index 000000000..d45b85120 --- /dev/null +++ b/tslang/test/tester/value/value_self_generic_pair.ts @@ -0,0 +1,21 @@ +// ...in any of the generic's type arguments +class Pair { + constructor(public a: X | null, public b: Y | null) {} +} + +@value +interface A { + readonly v: number; + readonly p: Pair; +} + +@value +interface B { + readonly w: number; + readonly a: A; +} + +function main() { + const a: A = { v: 1, p: new Pair(null, 3) }; + print(a.v); +} diff --git a/tslang/test/tester/value/value_self_iface.ts b/tslang/test/tester/value/value_self_iface.ts new file mode 100644 index 000000000..3a75fc9ce --- /dev/null +++ b/tslang/test/tester/value/value_self_iface.ts @@ -0,0 +1,13 @@ +// A @value type is the tuple of its fields, held in place: one that holds itself, even as +// `L | null`, would be infinitely large. +@value +interface L { + readonly v: number; + readonly next: L | null; +} + +function main() { + const a: L = { v: 1, next: null }; + const b: L = { v: 2, next: a }; + print(b.next ? b.next.v : -1); +} diff --git a/tslang/test/tester/value/value_self_mutual.ts b/tslang/test/tester/value/value_self_mutual.ts new file mode 100644 index 000000000..0478c6244 --- /dev/null +++ b/tslang/test/tester/value/value_self_mutual.ts @@ -0,0 +1,14 @@ +// ...or one that holds itself through another @value type +@value +interface A { + readonly b: B | null; +} + +@value +interface B { + readonly a: A; +} + +function main() { + print(1); +} diff --git a/tslang/test/tester/value/value_self_through_class.ts b/tslang/test/tester/value/value_self_through_class.ts new file mode 100644 index 000000000..389a983e2 --- /dev/null +++ b/tslang/test/tester/value/value_self_through_class.ts @@ -0,0 +1,33 @@ +// A @value type may reach itself through an ordinary class: the class holds a reference, not the +// value in place. Declared before and after the class. +class Box { + constructor(public l: L | null) {} +} + +@value +interface L { + readonly v: number; + readonly box: Box; +} + +@value +interface M { + readonly v: number; + readonly box: Box2; +} + +class Box2 { + constructor(public m: M | null) {} +} + +function main() { + const a: L = { v: 1, box: new Box(null) }; + const b: L = { v: 2, box: new Box(a) }; + const l = b.box.l; + assert(l !== null && l.v == 1); + const c: M = { v: 3, box: new Box2(null) }; + const d: M = { v: 4, box: new Box2(c) }; + const m = d.box.m; + assert(m !== null && m.v == 3); + print("done."); +} diff --git a/tslang/test/tester/value/value_setter.ts b/tslang/test/tester/value/value_setter.ts new file mode 100644 index 000000000..b325adaa6 --- /dev/null +++ b/tslang/test/tester/value/value_setter.ts @@ -0,0 +1,11 @@ +// A setter would change a value through one of its copies. +@value +class V { + constructor(public readonly x: number) {} + + set y(v: number) { + } +} + +function main() { +} diff --git a/tslang/test/tester/value/value_switch_identity.ts b/tslang/test/tester/value/value_switch_identity.ts new file mode 100644 index 000000000..ca0ddb650 --- /dev/null +++ b/tslang/test/tester/value/value_switch_identity.ts @@ -0,0 +1,17 @@ +// A `case` compares as `===` does: two @value values have no identity to compare. +@value +interface R { + readonly a: number; +} + +function main() { + const r1: R = { a: 1 }; + const r2: R = { a: 1 }; + switch (r1) { + case r2: + print("same"); + break; + default: + print("other"); + } +} diff --git a/tslang/test/tester/value/value_ternary_null.ts b/tslang/test/tester/value/value_ternary_null.ts new file mode 100644 index 000000000..26cdf688c --- /dev/null +++ b/tslang/test/tester/value/value_ternary_null.ts @@ -0,0 +1,34 @@ +// `c ? { ... } : null` returned as `T | null` of a @value type: the literal is the T, and the +// ternary is the missing type of T and null, as `if (c) return { ... }; return null;` is. +@value +interface Hit { + readonly d: number; +} + +interface Thing { + intersect(x: number): Hit | null; +} + +class S implements Thing { + intersect(x: number): Hit | null { + return x > 0 ? { d: x } : null; + } +} + +function find(x: number): Hit | null { + return x < 0 ? null : { d: x * 2 }; +} + +function main() { + const t: Thing = new S(); + const h = t.intersect(2); + assert(h != null && h.d == 2); + assert(t.intersect(-2) === null); + + assert(find(3).d == 6); + assert(find(-3) === null); + + const k: Hit | null = 1 < 2 ? { d: 5 } : null; + assert(k != null && k.d == 5); + print("done."); +} diff --git a/tslang/test/tester/value/value_to_any.ts b/tslang/test/tester/value/value_to_any.ts new file mode 100644 index 000000000..eba5bb42e --- /dev/null +++ b/tslang/test/tester/value/value_to_any.ts @@ -0,0 +1,10 @@ +// A @value class is nominal: it is not seen as `any`, which would box a copy without its class. +@value +class V { + constructor(public readonly x: number) {} +} + +function main() { + const a: any = new V(1); + print(a); +} diff --git a/tslang/test/tester/verify-ownership.cmake b/tslang/test/tester/verify-ownership.cmake index 6d0c02b72..5d2202579 100644 --- a/tslang/test/tester/verify-ownership.cmake +++ b/tslang/test/tester/verify-ownership.cmake @@ -45,7 +45,10 @@ set(not_compilable_alone export_cppvtable_hidden_return.ts import_cppvtable_hidden_return.ts # an error by design: it extends a @final class (test-compile-shared-import-final-extends) - import_final_extends.ts) + import_final_extends.ts + # an error by design: an object literal for an imported @value class + # (test-compile-shared-import-value-types-structural) + import_value_types_structural.ts) file(GLOB corpus "${TESTS_DIR}/*.ts") list(SORT corpus) diff --git a/tslang/unittests/MLIRGen/DeclarationPrinter.cpp b/tslang/unittests/MLIRGen/DeclarationPrinter.cpp index 821d494fa..dab576703 100644 --- a/tslang/unittests/MLIRGen/DeclarationPrinter.cpp +++ b/tslang/unittests/MLIRGen/DeclarationPrinter.cpp @@ -443,6 +443,75 @@ TEST_F(DeclarationPrinterTest, non_final_class_has_no_final_decorator) EXPECT_THAT(text, testing::Not(testing::HasSubstr("@final"))); } +// `@value` decides how an importer stores and passes the type, so the reimported declaration has +// to keep it. +TEST_F(DeclarationPrinterTest, value_class_prints_value_decorator) +{ + auto ci = makeClass("Vec"); + ci->isValue = true; + setClassFields(ci, {}); + auto text = printClass(ci); + EXPECT_THAT(text, testing::HasSubstr("@value")); + EXPECT_THAT(text, testing::HasSubstr("class Vec")); +} + +TEST_F(DeclarationPrinterTest, value_interface_prints_value_decorator) +{ + auto ii = makeInterface("Rec"); + ii->isValue = true; + auto text = printInterface(ii); + EXPECT_THAT(text, testing::HasSubstr("@value")); + EXPECT_THAT(text, testing::HasSubstr("interface Rec")); +} + +TEST_F(DeclarationPrinterTest, plain_interface_has_no_value_decorator) +{ + auto text = printInterface(makeInterface("Rec")); + EXPECT_THAT(text, testing::Not(testing::HasSubstr("@value"))); +} + +// a field of a @value interface is readonly, and an importer re-parsing the declaration checks it +TEST_F(DeclarationPrinterTest, value_interface_prints_readonly_fields) +{ + auto ii = makeInterface("Rec"); + ii->isValue = true; + ii->fields.push_back(ifield(strAttr("x"), get())); + auto text = printInterface(ii); + EXPECT_THAT(text, testing::HasSubstr("readonly x: number;")); + + auto plain = makeInterface("Rec2"); + plain->fields.push_back(ifield(strAttr("x"), get())); + auto plainText = printInterface(plain); + EXPECT_THAT(plainText, testing::HasSubstr("x: number;")); + EXPECT_THAT(plainText, testing::Not(testing::HasSubstr("readonly"))); +} + +// a field of a @value class is readonly (a parameter property `constructor(public readonly x)` is +// one), and an importer re-parsing the declaration checks it. `this` of its methods is the value - +// of its constructor, the slot `new` made - and is left out as a class's `this` is. +TEST_F(DeclarationPrinterTest, value_class_prints_readonly_fields) +{ + auto ci = makeClass("Vec"); + ci->isValue = true; + setClassFields(ci, {classField(strAttr("x"), get())}); + auto storage = mlir_ts::TupleType::get(getContext(), {classField(strAttr("x"), get())}); + auto valueType = mlir_ts::ValueType::get(sym("Vec"), storage); + ci->methods.push_back(method("constructor", getF({mlir_ts::RefType::get(storage), get()}, {}))); + ci->methods.push_back(method("dot", getF({valueType, valueType}, {get()}))); + ci->methods.push_back(method("plus", getF({valueType, valueType}, {valueType}), /*isStatic*/ true)); + auto text = printClass(ci); + EXPECT_THAT(text, testing::HasSubstr("readonly x: number;")); + EXPECT_THAT(text, testing::HasSubstr("constructor(p1 : number)")); + EXPECT_THAT(text, testing::HasSubstr("dot(p1 : Vec) : number")); + EXPECT_THAT(text, testing::HasSubstr("static plus(p0 : Vec, p1 : Vec) : Vec")); + + auto plain = makeClass("Vec2"); + setClassFields(plain, {classField(strAttr("x"), get())}); + auto plainText = printClass(plain); + EXPECT_THAT(plainText, testing::HasSubstr("x: number;")); + EXPECT_THAT(plainText, testing::Not(testing::HasSubstr("readonly"))); +} + TEST_F(DeclarationPrinterTest, abstract_method_prints_abstract_keyword) { auto ci = makeClass("Shape");