From 33a2ccdeb4aacf795fcc4b4f5cab5387fff6461e Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Sat, 5 Dec 2026 06:09:08 -0600 Subject: [PATCH] Keep small array fields in their instances --- docs/content/docs/contracts.mdx | 2 +- docs/content/docs/experimental.mdx | 2 + packages/compiler/src/contracts/check.ts | 106 +++++++++- .../compiler/src/ir/inline-array-sources.ts | 17 +- packages/compiler/src/ir/inline-arrays.ts | 12 +- .../test/inline-array-inferred.test.ts | 192 ++++++++++++++++++ .../corpus/inline-array-inferred.ts.json | 6 + packages/experimental/README.md | 4 +- packages/experimental/index.d.ts | 7 +- tests/corpus/inline-array-inferred.ts | 77 +++++++ 10 files changed, 404 insertions(+), 21 deletions(-) create mode 100644 packages/compiler/test/inline-array-inferred.test.ts create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/inline-array-inferred.ts.json create mode 100644 tests/corpus/inline-array-inferred.ts diff --git a/docs/content/docs/contracts.mdx b/docs/content/docs/contracts.mdx index fe5b21a1dc..28cf03d91b 100644 --- a/docs/content/docs/contracts.mdx +++ b/docs/content/docs/contracts.mdx @@ -368,7 +368,7 @@ A long-running program, such as a compiler in watch mode, can free program-lifet ### Inline array fields -An array field of a program-lifetime class whose elements are program-lifetime instances can keep its elements in the instance itself, after the other fields, with `InlineArray` from [`@scriptc/experimental`](/docs/experimental). The constructor writes the field once from one of its parameters; reads that index the field, read its `length` or iterate it load the elements from the instance, and other reads get an array of them. The array passed to the constructor is one that nothing else keeps, and the arrays fields hold are never written. scriptc reports a field that does not keep these rules (SC7009). +An array field of a program-lifetime class whose elements are program-lifetime instances can keep its elements in the instance itself, after the other fields. scriptc gives the field this layout when the whole program shows that the constructor writes it once from one of its parameters, that reads which index the field, read its `length` or iterate it load the elements from the instance, that other reads get an array of them, that the array passed to the constructor is one nothing else keeps, and that the arrays fields hold are never written. Writing the field as `InlineArray` from [`@scriptc/experimental`](/docs/experimental) requires the layout and reports a field that does not keep these rules (SC7009); a field without the annotation keeps an ordinary array. ## Diagnostics diff --git a/docs/content/docs/experimental.mdx b/docs/content/docs/experimental.mdx index c186093fbd..a39ecf7769 100644 --- a/docs/content/docs/experimental.mdx +++ b/docs/content/docs/experimental.mdx @@ -339,6 +339,8 @@ A family holds a reference to each of the thread's values. A value is released w `InlineArray` marks an array field of a [`ProgramLifetime`](/docs/contracts#programlifetime) class whose elements scriptc keeps in the instance itself, after its other fields, instead of in an array object of their own. It suits a program with millions of short arrays that never change once built, such as the children of each node of a syntax tree: an ordinary array costs a separate allocation with a header, and a reference to it in the instance. +An array field of a `ProgramLifetime` class keeps its elements in the instance without the annotation too, when the whole program shows that the field keeps the rules below. Write `InlineArray` to require the layout: scriptc then reports a field that does not keep the rules (SC7009), where a field without the annotation keeps an ordinary array and builds without a diagnostic. A field that only a dynamic view of its instances would read stays an ordinary array either way, with a warning (SC6105). + ```ts:lists.ts import type { ProgramLifetime } from "@scriptc/types"; import type { InlineArray } from "@scriptc/experimental"; diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index 13da10c07c..d631c61ae1 100644 --- a/packages/compiler/src/contracts/check.ts +++ b/packages/compiler/src/contracts/check.ts @@ -68,7 +68,7 @@ import { type ContractAnnotations, type ContractNote, } from "../frontend/contract-types.js"; -import { planInlineArrays } from "../ir/inline-arrays.js"; +import { isSelf, planInlineArrays } from "../ir/inline-arrays.js"; import { checkInlineArraySources } from "../ir/inline-array-sources.js"; /** The largest array index: 2^32 - 2 (ECMA-262 array index). */ @@ -109,6 +109,31 @@ function samePlace(a: IrExpr, b: IrExpr): boolean { return false; } +/** The cheap half of ir/inline-arrays.ts's `writtenParam`: the class's + * constructor writes `field` once, as one of its own body statements, from a + * parameter it uses nowhere else. The whole-program plan decides the rest. */ +function storesParameter(ctor: IrFunction, className: string, field: string): boolean { + const self = ctor.params[0]?.localId; + const writes = ctor.body.filter( + (s): s is IrStmt & { kind: "fieldSet" } => + s.kind === "fieldSet" && s.field === field && s.className === className, + ); + if (writes.length !== 1) return false; + const write = writes[0]!; + if (!isSelf(write.obj, self)) return false; + if (write.value.kind !== "varRef") return false; + const valueId = write.value.localId; + const param = ctor.params.findIndex((p, i) => i > 0 && p.localId === valueId); + if (param < 0) return false; + let uses = 0; + walk(ctor.body, { + expr: (e) => { + if (e.kind === "varRef" && e.localId === valueId) uses++; + }, + }); + return uses === 1; +} + /** The element type of an array value, or undefined for anything else. */ function arrayElement(type: IrType): IrType | undefined { return type.kind === "array" ? type.elem : undefined; @@ -426,16 +451,20 @@ class ContractChecker { * (two reads need not give the same array), and no instance of the * hierarchy is constructed through a class value. A field whose instances * become dynamic values that generic code may read it through keeps an - * ordinary array, with a warning (SC6105). */ + * ordinary array, with a warning (SC6105). + * + * Every other array field of a ProgramLifetime class is offered the same + * layout without an annotation: when the whole-program checks above prove + * the same rules for it, the field's elements move into the instance too. + * A field they do not prove stays an ordinary array, silently. */ private checkInlineArrays(): void { - if (this.notes.inlineArrays.size === 0) return; const roots = new Set(this.contracts.programLifetime ?? []); const lifetime = (className: string): boolean => { let cls = this.classes.get(className); while (cls?.base !== undefined) cls = this.classes.get(cls.base); return cls !== undefined && roots.has(cls.name); }; - const entries: string[] = []; + const explicit: string[] = []; const notes = new Map(); for (const [key, note] of this.notes.inlineArrays) { const at = key.lastIndexOf("\0"); @@ -451,17 +480,70 @@ class ContractChecker { continue; } const entry = `${cls.name}\0${field}`; - entries.push(entry); + explicit.push(entry); notes.set(entry, note); } } - if (entries.length === 0) return; - const plan = planInlineArrays( - { ...this.mod, contracts: { ...this.mod.contracts, inlineArrays: entries } }, + const explicitSet = new Set(explicit); + // Array fields of ProgramLifetime classes that no annotation names. The + // plan below decides each one: a field it keeps gets the layout, one it + // rejects keeps an ordinary array without a diagnostic. + const inferred = new Set(); + if (this.mod.lib === undefined) { + for (const cls of this.classes.values()) { + if (cls.runtime === true || !lifetime(cls.name)) continue; + const base = cls.base === undefined ? undefined : this.classes.get(cls.base); + const ctor = this.functions.get(`%${cls.name}.constructor`); + if (ctor === undefined) continue; + for (const f of cls.fields) { + if (f.type.kind !== "array" || f.type.elem.kind !== "object") continue; + if (!lifetime(f.type.elem.className)) continue; + // Inherited fields are listed again in a subclass; the declaring + // class is the one whose layout the plan changes. + if (base?.fields.some((inherited) => inherited.name === f.name) === true) continue; + if (!storesParameter(ctor, cls.name, f.name)) continue; + const entry = `${cls.name}\0${f.name}`; + if (!explicitSet.has(entry)) inferred.add(entry); + } + } + } + if (explicit.length === 0 && inferred.size === 0) return; + // A field the source check rejects is dropped and the plan rebuilt: one + // inline field may take its constructor array from another's. + let plan = planInlineArrays( + { + ...this.mod, + contracts: { ...this.mod.contracts, inlineArrays: [...explicit, ...inferred] }, + }, lifetime, ); + let issues = checkInlineArraySources(this.mod, plan); + while (inferred.size > 0) { + const drop = new Set(); + for (const r of plan.rejected) { + const entry = `${r.declaringClass}\0${r.field}`; + if (inferred.has(entry)) drop.add(entry); + } + for (const issue of issues) { + if (issue.ownerKnown !== true) continue; + const entry = `${issue.declaringClass}\0${issue.field}`; + if (inferred.has(entry)) drop.add(entry); + } + if (drop.size === 0) break; + for (const entry of drop) inferred.delete(entry); + plan = planInlineArrays( + { + ...this.mod, + contracts: { ...this.mod.contracts, inlineArrays: [...explicit, ...inferred] }, + }, + lifetime, + ); + issues = checkInlineArraySources(this.mod, plan); + } for (const r of plan.rejected) { - const note = notes.get(`${r.declaringClass}\0${r.field}`)!; + const entry = `${r.declaringClass}\0${r.field}`; + if (!explicitSet.has(entry)) continue; + const note = notes.get(entry)!; const at = r.loc === undefined ? "" : ` (at ${this.where(r.loc)})`; // A dynamic view reads the field as Node.js does when the elements // stay in an ordinary array. @@ -482,8 +564,10 @@ class ContractChecker { ); } // Where the arrays come from and who writes them (ir/inline-array-sources.ts). - for (const issue of checkInlineArraySources(this.mod, plan)) { - const note = notes.get(`${issue.declaringClass}\0${issue.field}`)!; + for (const issue of issues) { + const entry = `${issue.declaringClass}\0${issue.field}`; + if (!explicitSet.has(entry)) continue; + const note = notes.get(entry)!; const from = issue.origin === undefined ? "" : ` (from ${this.where(issue.origin)})`; this.report( "SC7009", diff --git a/packages/compiler/src/ir/inline-array-sources.ts b/packages/compiler/src/ir/inline-array-sources.ts index 9ab77092c7..1bd7db3662 100644 --- a/packages/compiler/src/ir/inline-array-sources.ts +++ b/packages/compiler/src/ir/inline-array-sources.ts @@ -42,6 +42,10 @@ import { everyExprChild, everyStmtChild } from "./traverse.js"; export interface InlineArraySourceIssue extends Issue { readonly declaringClass: string; readonly field: string; + /** The issue names the field whose array reaches it, not the first planned + * field because no read of any field was found. Inferred fields are only + * dropped for the former. */ + readonly ownerKnown?: true; } interface Issue { @@ -592,15 +596,18 @@ class SourceAnalysis { return { declaringClass: cls.declaringClass, field: cls.field }; } - private report( - issue: Issue, - owner = (issue.origin && this.origins.get(issue.origin)) ?? this.anyField(), - ): void { + private report(issue: Issue, owner?: { declaringClass: string; field: string }): void { // One issue per site. const key = `${issue.loc.file}:${issue.loc.start}`; if (this.reported.has(key)) return; this.reported.add(key); - this.issues.push({ ...owner, ...issue }); + const known = + owner ?? (issue.origin === undefined ? undefined : this.origins.get(issue.origin)); + this.issues.push({ + ...(known ?? this.anyField()), + ...issue, + ...(known === undefined ? {} : { ownerKnown: true as const }), + }); } // ── Calls ── diff --git a/packages/compiler/src/ir/inline-arrays.ts b/packages/compiler/src/ir/inline-arrays.ts index 5fe27fdc66..e19e55063c 100644 --- a/packages/compiler/src/ir/inline-arrays.ts +++ b/packages/compiler/src/ir/inline-arrays.ts @@ -206,11 +206,19 @@ function writtenParam( const write = writes[0]!; // The write is one of the body's own statements: it runs exactly once. if (!ctor.body.includes(write)) return "the constructor writes the field conditionally"; - if (write.obj.kind !== "varRef" || write.obj.localId !== self) - return "the constructor writes the field of another object"; + if (!isSelf(write.obj, self)) return "the constructor writes the field of another object"; return parameterOf(ctor, write.value); } +/** Whether `e` evaluates to the constructor's `this`. The lowering guards a + * derived constructor's first access to `this` with a `seqExpr` that throws + * when the base constructor has not run; the guard's result is `this`. */ +export function isSelf(e: IrExpr, self: string | undefined): boolean { + if (self === undefined) return false; + if (e.kind === "varRef") return e.localId === self; + return e.kind === "seqExpr" && isSelf(e.result, self); +} + /** The index in `ctor.params` of the parameter a subclass constructor * passes to its base's at the base's length parameter, or why there is none. */ function forwardedParam( diff --git a/packages/compiler/test/inline-array-inferred.test.ts b/packages/compiler/test/inline-array-inferred.test.ts new file mode 100644 index 0000000000..54dc5e83b8 --- /dev/null +++ b/packages/compiler/test/inline-array-inferred.test.ts @@ -0,0 +1,192 @@ +import { mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, test } from "vitest"; +import { compile } from "../src/index.js"; + +// Inline array fields without an annotation (ir/inline-arrays.ts): an array +// field of a ProgramLifetime class that keeps the InlineArray rules keeps +// its elements in the instance; one that does not keeps an ordinary array, +// with no diagnostic. `readonly f: InlineArray` stays the way to require +// the layout (SC7009). + +const repoRoot = join(import.meta.dirname, "../../.."); + +const header = ` +import type { ProgramLifetime } from "@scriptc/types"; +`; + +async function build(source: string): Promise<{ + ok: boolean; + codes: string[]; + llvm: string; + messages: string[]; + warnings: string[]; +}> { + const dir = await mkdtemp(join(tmpdir(), "scriptc-inline-inferred-")); + try { + await symlink(join(repoRoot, "node_modules"), join(dir, "node_modules")); + const entry = join(dir, "main.ts"); + const outPath = join(dir, "main.ll"); + await writeFile(entry, header + source); + const result = await compile(entry, { outDir: dir, outPath, outputKind: "llvm" }); + const llvm = result.ok ? await readFile(outPath, "utf8") : ""; + return { + ok: result.ok, + codes: (result.diagnostics ?? []).map((d) => d.code), + llvm, + messages: (result.diagnostics ?? []).map((d) => d.message), + warnings: (result.ok ? (result.warnings ?? []) : []).map((d) => `${d.code}: ${d.message}`), + }; + } finally { + await rm(dir, { recursive: true, force: true }); + } +} + +const classes = ` +class Item implements ProgramLifetime { + readonly kind: number; + constructor(kind: number) { + this.kind = kind; + } +} +class List implements ProgramLifetime { + readonly pos: number; + readonly items: readonly Item[]; + constructor(pos: number, items: readonly Item[]) { + this.pos = pos; + this.items = items; + } +} +`; + +// The inline layout applies to executables whose compact instances live in +// the low region: Linux and macOS, 64-bit. +const lowRegion = + (process.platform === "linux" || process.platform === "darwin") && + (process.arch === "x64" || process.arch === "arm64"); + +function isInline(llvm: string): boolean { + return ( + /^%sc_o_List = type \{ i32, i32, i32 \}/m.test(llvm) && + llvm.includes("define internal ptr @sc_new_List(i32 %inl.len)") && + llvm.includes("call void @scr_arr_copy_cref_tail(") + ); +} + +test.runIf(lowRegion)("a field that keeps the rules keeps its elements inline", async () => { + const { ok, llvm, messages } = await build( + classes + + ` +function sum(list: List): number { + let s = 0; + for (const item of list.items) s += item.kind; + return s + list.items[0]!.kind; +} +const list = new List(0, [new Item(1), new Item(2)]); +console.log(sum(list)); +`, + ); + expect(ok, messages.join("\n")).toBe(true); + expect(isInline(llvm)).toBe(true); +}); + +test.runIf(lowRegion)("an ordinary array field is not inlined without proof", async () => { + const { ok, llvm, codes, messages } = await build( + classes + + ` +const a = new List(0, [new Item(1)]); +const b = new List(1, [new Item(2)]); +console.log(a.items === b.items); +`, + ); + expect(ok, messages.join("\n")).toBe(true); + expect(codes).not.toContain("SC7009"); + expect(isInline(llvm)).toBe(false); + expect(llvm).toMatch(/^define internal ptr @sc_new_List\(\)/m); + expect(llvm).not.toContain("call void @scr_arr_copy_cref_tail("); +}); + +test.runIf(lowRegion)("an array kept by the caller keeps the field ordinary", async () => { + const { ok, llvm, codes, messages } = await build( + classes + + ` +const shared = [new Item(1)]; +const list = new List(0, shared); +shared.push(new Item(2)); +console.log(list.items.length); +`, + ); + expect(ok, messages.join("\n")).toBe(true); + expect(codes).not.toContain("SC7009"); + expect(isInline(llvm)).toBe(false); +}); + +test.runIf(lowRegion)("a field declared by a subclass is inlined after super", async () => { + const { ok, llvm, messages } = await build( + ` +class Pair implements ProgramLifetime { + readonly kind: number; + constructor(kind: number) { + this.kind = kind; + } +} +class Base implements ProgramLifetime { + readonly pos: number; + constructor(pos: number) { + this.pos = pos; + } +} +class Derived extends Base { + readonly pairs: readonly Pair[]; + constructor(pos: number, pairs: readonly Pair[]) { + super(pos); + this.pairs = pairs; + } +} +const list = new Derived(1, [new Pair(2), new Pair(3)]); +console.log(list.pos, list.pairs.length, list.pairs[0]!.kind); +`, + ); + expect(ok, messages.join("\n")).toBe(true); + expect(llvm).toContain("define internal ptr @sc_new_Derived(i32 %inl.len)"); + expect(llvm).toContain("call void @scr_arr_copy_cref_tail("); +}); + +test("an annotation without a ProgramLifetime class still reports", async () => { + const { ok, codes, messages } = await build( + ` +import type { InlineArray } from "@scriptc/experimental"; +class Item { + readonly kind = 0; +} +class List { + readonly items: InlineArray; + constructor(items: readonly Item[]) { + this.items = items; + } +} +console.log(new List([new Item()]).items.length); +`, + ); + expect(ok).toBe(false); + expect(codes).toContain("SC7009"); + expect(messages.join("\n")).toContain("not ProgramLifetime"); +}); + +test.runIf(lowRegion)("a write through the field keeps it ordinary", async () => { + const { ok, llvm, codes, messages } = await build( + classes + + ` +function grow(list: List): void { + (list.items as Item[]).push(new Item(3)); +} +const list = new List(0, [new Item(1)]); +grow(list); +console.log(list.items.length); +`, + ); + expect(ok, messages.join("\n")).toBe(true); + expect(codes).not.toContain("SC7009"); + expect(isInline(llvm)).toBe(false); +}); diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/inline-array-inferred.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/inline-array-inferred.ts.json new file mode 100644 index 0000000000..44624ad5ed --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/inline-array-inferred.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/corpus/inline-array-inferred.ts" + ], + "diags": [] +} diff --git a/packages/experimental/README.md b/packages/experimental/README.md index 8912da3ca0..30021fb582 100644 --- a/packages/experimental/README.md +++ b/packages/experimental/README.md @@ -121,6 +121,8 @@ Under Node.js each family is a `WeakMap` per thread. `InlineArray` marks an array field of a `ProgramLifetime` class (`@scriptc/types`) whose elements scriptc keeps in the instance itself, after its other fields, instead of in an array object of their own. It suits a program with millions of short arrays that never change once built, such as the children of each node of a syntax tree. +An array field of a `ProgramLifetime` class keeps its elements in the instance without the annotation too, when the whole program shows that the field keeps the rules below. Write `InlineArray` to require the layout: scriptc then reports a field that does not keep the rules (SC7009), where a field without the annotation keeps an ordinary array and builds without a diagnostic. A field that only a dynamic view of its instances would read stays an ordinary array either way, with a warning (SC6105). + ```ts import type { ProgramLifetime } from "@scriptc/types"; import type { InlineArray } from "@scriptc/experimental"; @@ -275,6 +277,7 @@ NODE_OPTIONS=--disallow-code-generation-from-strings node --require @scriptc/exp ``` The hook prints a warning to stderr when the flag is missing, or when the running Node.js version differs from the release the refusal data describes. + ## Dual-run testing `@scriptc/experimental/dual-run` runs a test file twice, once under Node.js and once as the executable scriptc builds, and compares the runs: test names, pass and fail results, assertion messages, program output and the exit code, with durations and stack frames normalized away. It is Node.js tooling, so a scriptc-built program cannot call it, and a compiled program never needs to. @@ -295,4 +298,3 @@ $ node --test --test-reporter=@scriptc/experimental/dual-run/reporter --test-rep ``` It prints one line per file, shows a diff when the two runs differ, reports a file whose Node.js output itself varies as flaky, and fails the run on a difference. Both forms build through the `scriptc` command and its executable cache, found from `SCRIPTC_BIN`, `node_modules/.bin` or `PATH`. See [dual-run testing](https://scriptc.dev/docs/dual-run). - diff --git a/packages/experimental/index.d.ts b/packages/experimental/index.d.ts index eeb328cb44..964bc7e81d 100644 --- a/packages/experimental/index.d.ts +++ b/packages/experimental/index.d.ts @@ -82,7 +82,12 @@ export declare class ThreadSlots { * The constructor is passed an array nothing else keeps, and the arrays * fields hold are never written. Reading the field gives an array of its * elements, frozen in scriptc builds; two reads need not give the same - * array. Under Node.js it is the array the constructor stored. */ + * array. Under Node.js it is the array the constructor stored. + * + * A `ProgramLifetime` array field without this annotation keeps the same + * layout when the whole program shows that it keeps these rules; one that + * does not stays an ordinary array, with no diagnostic. Writing the + * annotation requires the layout and reports a field that breaks a rule. */ export type InlineArray = readonly T[]; /** A class each of whose instances has one owner: the field or variable diff --git a/tests/corpus/inline-array-inferred.ts b/tests/corpus/inline-array-inferred.ts new file mode 100644 index 0000000000..6b7f62bbd5 --- /dev/null +++ b/tests/corpus/inline-array-inferred.ts @@ -0,0 +1,77 @@ +// Array fields of ProgramLifetime classes keep their elements in the +// instance when the whole program shows that the field is written once in +// the constructor and never read by identity, with no InlineArray +// annotation. Reads that index the field, read its length or iterate it +// load the elements from the instance; reads that pass the array on give an +// array of them. Outputs are the same under Node and natively. +import type { ProgramLifetime } from "@scriptc/types"; + +class Item implements ProgramLifetime { + readonly id: number; + constructor(id: number) { + this.id = id; + } +} + +class Stable implements ProgramLifetime { + readonly pos: number; + readonly items: readonly Item[]; + constructor(pos: number, items: readonly Item[]) { + this.pos = pos; + this.items = items; + } +} + +class Flagged extends Stable { + readonly flags: number; + constructor(pos: number, items: readonly Item[], flags: number) { + super(pos, items); + this.flags = flags; + } +} + +function sum(list: Stable): number { + let total = list.pos; + const items = list.items; + for (let i = 0; i < items.length; i++) total += items[i]!.id; + for (const item of list.items) total += item.id; + return total; +} + +const one = new Stable(1, [new Item(10), new Item(20)]); +const two = new Flagged(2, [new Item(30)], 7); +console.log(sum(one), sum(two), one.items.length, two.flags); +console.log(one.items.map((item) => item.id).join(",")); +console.log(JSON.stringify(one.items)); +console.log(one.items.slice(1).length); + +// An array the caller keeps before the constructor gets it: this field +// stays an ordinary array, so later writes to it are visible through it. +class Kept implements ProgramLifetime { + readonly items: readonly Item[]; + constructor(items: readonly Item[]) { + this.items = items; + } +} +const shared = [new Item(40)]; +const sharedList = new Kept(shared); +shared.push(new Item(50)); +console.log(sharedList.items.length); + +// A field whose reads are compared by identity stays an ordinary array, so +// both reads give the same array. +class Compared implements ProgramLifetime { + readonly items: readonly Item[]; + constructor(items: readonly Item[]) { + this.items = items; + } +} +const a = new Compared([new Item(60)]); +const b = new Compared([new Item(70)]); +console.log(a.items === b.items); + +// An ordinary array of instances still behaves as an array. +const plain: Item[] = []; +plain.push(new Item(80)); +plain.push(new Item(90)); +console.log(plain.length, plain[0]!.id, [...plain].length);