From 47042f3ebea9f6ddc63a8bd9124a432275d4bd2d Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Wed, 11 Nov 2026 16:21:14 -0600 Subject: [PATCH] Stop reporting Immutable escapes that untyped code cannot use --- CHANGELOG.md | 3 + packages/compiler/src/contracts/check.ts | 22 ++++++- .../lowering/class-dynamic-dispatch.ts | 58 +++++++++++++++++++ .../main.ts.json | 7 +++ .../main.ts.json | 8 +++ ...ontract-immutable-dynamic-receiver.ts.json | 6 ++ .../contract-immutable-element-reads.ts.json | 6 ++ .../immutable-array-foreign-elements/app.js | 7 +++ .../immutable-array-foreign-elements/main.ts | 20 +++++++ .../immutable-untyped-computed-read/app.js | 7 +++ .../immutable-untyped-computed-read/dom.ts | 18 ++++++ .../immutable-untyped-computed-read/main.ts | 10 ++++ .../contract-immutable-dynamic-receiver.ts | 22 +++++++ .../contract-immutable-element-reads.ts | 20 +++++++ ...contract-immutable-dynamic-receiver.ts.txt | 8 +++ .../contract-immutable-element-reads.ts.txt | 17 ++++++ .../main.ts.json | 1 + .../main.ts.json | 1 + 18 files changed, 238 insertions(+), 3 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-array-foreign-elements/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-untyped-computed-read/main.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-dynamic-receiver.ts.json create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-element-reads.ts.json create mode 100644 tests/corpus/immutable-array-foreign-elements/app.js create mode 100644 tests/corpus/immutable-array-foreign-elements/main.ts create mode 100644 tests/corpus/immutable-untyped-computed-read/app.js create mode 100644 tests/corpus/immutable-untyped-computed-read/dom.ts create mode 100644 tests/corpus/immutable-untyped-computed-read/main.ts create mode 100644 tests/diagnostics/contract-immutable-dynamic-receiver.ts create mode 100644 tests/diagnostics/contract-immutable-element-reads.ts create mode 100644 tests/harness/__snapshots__/contract-immutable-dynamic-receiver.ts.txt create mode 100644 tests/harness/__snapshots__/contract-immutable-element-reads.ts.txt create mode 100644 tests/harness/corpus-costs/immutable-array-foreign-elements/main.ts.json create mode 100644 tests/harness/corpus-costs/immutable-untyped-computed-read/main.ts.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 68c9d983ef..758277140b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,9 @@ All notable changes to scriptc will be documented in this file. - The six http header-limit getters and setters are classified as never throwing, since they are plain storage with no accessor, coercion or listener, and `http.serverOnDropRequest` as may-throw because it fires `'newListener'` before the add. - An `Immutable` annotation is recognized through a re-export, an alias or a path alias of `@scriptc/types`, and a marker whose import cannot be followed is refused with SC7006 instead of compiling as if the annotation were absent. - An array built by pushing values read from `Immutable` data, and the result of `filter` over an `Immutable` array, are accepted as fresh for a store into an `Immutable` field (SC7004), and each checked element read is read as the array passed at its call site, so a plain array's `.map` is no longer refused (SC7005) because an unrelated `Immutable` table of the same element type is indexed elsewhere. + - An `Immutable` value passed to a library call that always throws is no longer counted as escaping to it, because the call throws before it can keep or write the value: a `for…of` loop over an `Immutable` array compiles when some other array in the program holds elements of a foreign type and makes the loop's checked element read lower to `array.foreignThrow` (SC7005 before this change), the read still throws, and a write through the array is still refused. + - An indexed read of an `Immutable` array may yield an `Immutable` value only when the element type can hold an object: reading `t.nums[0]` of an `Immutable` into untyped code compiles, while an element of an `Immutable` or an `Immutable` keeps SC7005. + - A keyed read or write through an untyped value dispatches to the fields of a compiled class only when the value it receives can be a class instance, so a record or array receiver no longer hands a class's `Immutable` field to dynamic code; a site that can receive an instance keeps its per-class branches, and a write through an `Immutable` value is still refused. diff --git a/packages/compiler/src/contracts/check.ts b/packages/compiler/src/contracts/check.ts index feb956c990..ea5a015d30 100644 --- a/packages/compiler/src/contracts/check.ts +++ b/packages/compiler/src/contracts/check.ts @@ -39,6 +39,7 @@ import type { SrcLoc, } from "../ir/ir.js"; import { isRefCounted, typeKey } from "../ir/ir.js"; +import { ALWAYS_THROW_LIB_FNS } from "../ir/builtin-effects.js"; import { everyExprChild, everyStmtChild } from "../ir/traverse.js"; import { analyzeIntegerRanges, @@ -120,6 +121,16 @@ function cannotAlias(type: IrType): boolean { return !isRefCounted(type) || type.kind === "string"; } +/** Whether reading an element of an Immutable array can yield an Immutable + * value. Only an element whose type can reference an object can be one: a + * number, string or boolean element of an Immutable array carries nothing + * writable, so an ordinary indexed read of a `number[]` yields a plain value + * (even though the read's `number | undefined` result is a refcounted box). */ +function immutableElement(type: IrType, arrayDerived: boolean): boolean { + const elem = arrayElement(type); + return arrayDerived && elem !== undefined && !cannotAlias(elem); +} + /** Visit the `varRef`s that a stored value carries into the container * without handing them to other code: the value itself and the structural * slots a construction puts it in (array and record literals, Map and Set @@ -1913,7 +1924,7 @@ class ImmutableContracts { return; } case "libCall": - if (!LIB_READS.test(e.fn)) + if (!LIB_READS.test(e.fn) && !ALWAYS_THROW_LIB_FNS.has(e.fn)) for (const a of e.args) escape(a, a.loc, `the library call ${e.fn}`); return; case "callValue": @@ -2025,7 +2036,10 @@ class ImmutableContracts { ) || derived(e.obj) ); case "arrayGet": - return this.mayHold.has(`e:${typeKey(e.arr.type)}`) || derived(e.arr); + return ( + this.mayHold.has(`e:${typeKey(e.arr.type)}`) || + immutableElement(e.arr.type, derived(e.arr)) + ); case "mapIntrinsic": return ( MAP_ELEMENT_READS.has(e.method) && @@ -2045,7 +2059,9 @@ class ImmutableContracts { // when the array passed here may hold Immutable elements. const arg = e.args[0]; if (arg !== undefined && e.callee.startsWith("%arr.idxOr.")) - return this.mayHold.has(`e:${typeKey(arg.type)}`) || derived(arg); + return ( + this.mayHold.has(`e:${typeKey(arg.type)}`) || immutableElement(arg.type, derived(arg)) + ); return this.mayHold.has(`r:${e.callee}`); } case "virtualCall": diff --git a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts index 45d297f5f6..cffa5ffc77 100644 --- a/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts +++ b/packages/compiler/src/frontend/lowering/class-dynamic-dispatch.ts @@ -1670,6 +1670,13 @@ export class ClassDynamicDispatch { branchIndex: number; dynamicKey: boolean; numericKey: boolean; + /** Whether a receiver at one of the helper's call sites can be a + * compiled class instance (receiverCanBeInstance). Only then does the + * helper get a branch per boxed class and a class key table; a receiver + * that can only be a record, array or other builtin value matches no + * class, and reading class state for it would expose values its own + * dynamic code cannot reach. */ + instances: boolean; probe: "in" | "own" | "enumerable" | undefined; /** The operation the helper's per-class key tables answer * (computedTableOperation). */ @@ -3086,7 +3093,17 @@ export class ClassDynamicDispatch { ...(sloppyWrite ? ["sloppy"] : []), ...(namedWrite ? ["named"] : []), ]); + const receiver: IrExpr = reflect + ? (reflectRead ?? reflectWrite)!.args[0]! + : computedRead + ? computedRead.value + : (computedWrite ?? computedProbe)!.args[0]!; + const receiverIsInstance = this.receiverCanBeInstance(lowerer, receiver); let dispatch = this.computed.get(key); + if (dispatch && receiverIsInstance && !dispatch.instances) { + dispatch.instances = true; + changed = true; + } if (!dispatch) { const loc = expr.loc; const params = [ @@ -3381,6 +3398,7 @@ export class ClassDynamicDispatch { branchIndex: dynamicKey ? 3 : indexKey ? 2 : 0, dynamicKey, numericKey, + instances: receiverIsInstance, probe, operation: computedTableOperation({ write: !!computedWrite, @@ -4289,6 +4307,7 @@ export class ClassDynamicDispatch { } } for (const dispatch of this.computed.values()) { + if (!dispatch.instances) continue; for (const plan of this.propertyReceivers(lowerer, true)) { if (dispatch.classes.has(plan.key)) continue; const { info } = plan; @@ -6535,6 +6554,45 @@ export class ClassDynamicDispatch { add(root); } + /** Whether the dynamic value a computed-access helper is handed can be a + * compiled class instance. An object, which is a class instance, and an + * untyped value that may hold one need the helper's per-class branches. + * A record, array, bytes, string or other builtin value cannot be one: its + * members live in its property bag, which the helper's checked-dynamic + * fallthrough reads. A helper shared by such a site and a class site keeps + * its branches; one whose every site hands it a record or array answers + * from the fallthrough alone, so class state (Immutable fields included) + * stays out of reach of dynamic code at those sites. */ + private receiverCanBeInstance(lowerer: Lowerer, receiver: IrExpr): boolean { + let value = receiver; + // A record made dynamic is still a record: the conversions that keep a + // value's identity while changing its static type do not change what it + // is. (dynCheck keeps its own type: a class instance fails a check to a + // record or array, so the checked type tells the whole story.) + for (let steps = 0; steps < 32; steps++) { + if (value.kind === "dynFrom") value = value.value; + else if (value.kind === "seqExpr") value = value.result; + else break; + } + const seen = new Set(); + const holdsInstance = (type: IrType): boolean => { + switch (type.kind) { + case "object": + case "dyn": + case "jsval": + return true; + case "union": { + if (seen.has(type.unionId)) return false; + seen.add(type.unionId); + return (lowerer.unions.get(type.unionId)?.arms ?? []).some(holdsInstance); + } + default: + return false; + } + }; + return holdsInstance(value.type); + } + /** propertyReceivers results by mode, with the class graph they were * computed from: the boxed classes, the registered classes, the subclass * links and the constructed classes only grow, so equal counts and the diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-array-foreign-elements/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-array-foreign-elements/main.ts.json new file mode 100644 index 0000000000..a120cdf2e7 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-array-foreign-elements/main.ts.json @@ -0,0 +1,7 @@ +{ + "order": [ + "/tests/corpus/immutable-array-foreign-elements/app.js", + "/tests/corpus/immutable-array-foreign-elements/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-untyped-computed-read/main.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-untyped-computed-read/main.ts.json new file mode 100644 index 0000000000..7aa1eed7ce --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/immutable-untyped-computed-read/main.ts.json @@ -0,0 +1,8 @@ +{ + "order": [ + "/tests/corpus/immutable-untyped-computed-read/dom.ts", + "/tests/corpus/immutable-untyped-computed-read/app.js", + "/tests/corpus/immutable-untyped-computed-read/main.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-dynamic-receiver.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-dynamic-receiver.ts.json new file mode 100644 index 0000000000..acdfc4523d --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-dynamic-receiver.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/contract-immutable-dynamic-receiver.ts" + ], + "diags": [] +} diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-element-reads.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-element-reads.ts.json new file mode 100644 index 0000000000..1da84c64c5 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/diagnostics/contract-immutable-element-reads.ts.json @@ -0,0 +1,6 @@ +{ + "order": [ + "/tests/diagnostics/contract-immutable-element-reads.ts" + ], + "diags": [] +} diff --git a/tests/corpus/immutable-array-foreign-elements/app.js b/tests/corpus/immutable-array-foreign-elements/app.js new file mode 100644 index 0000000000..cd293958a0 --- /dev/null +++ b/tests/corpus/immutable-array-foreign-elements/app.js @@ -0,0 +1,7 @@ +// Untyped JavaScript whose own code makes a dynamic store possible: a +// keyed write through a value typed `any` can reach a native array as a +// live view, and the program's arrays of that element type are read +// through a checked element read from then on. +export function assign(n, l) { + for (const u in l) n[u] = l[u]; +} diff --git a/tests/corpus/immutable-array-foreign-elements/main.ts b/tests/corpus/immutable-array-foreign-elements/main.ts new file mode 100644 index 0000000000..907e9a268b --- /dev/null +++ b/tests/corpus/immutable-array-foreign-elements/main.ts @@ -0,0 +1,20 @@ +// A checked element read passes its array to the runtime helper that +// rejects a foreign element. That helper always throws, so it cannot keep +// or write the array: iterating an Immutable array is not an escape, even +// when some untyped code elsewhere made array elements dynamic-writable. +import type { Immutable } from "@scriptc/types"; +import { assign } from "./app.js"; + +class Tables { + nums: Immutable = [1, 2, 3]; +} + +const t = new Tables(); +let sum = 0; +for (const n of t.nums) sum += n; + +const scratch: number[] = [1, 2, 3]; +const dynamic: unknown = scratch; +const target: Record = {}; +assign(target, { a: "x" }); +console.log(target["a"], sum, Array.isArray(dynamic)); diff --git a/tests/corpus/immutable-untyped-computed-read/app.js b/tests/corpus/immutable-untyped-computed-read/app.js new file mode 100644 index 0000000000..a160eb677c --- /dev/null +++ b/tests/corpus/immutable-untyped-computed-read/app.js @@ -0,0 +1,7 @@ +// Untyped JavaScript that receives the class instance: it builds its own +// table and reads a key out of it. Neither value it creates is Immutable, +// so neither read may count as one. +export function setText(el, key) { + const table = { a: "hello" }; + el.text = table[key]; +} diff --git a/tests/corpus/immutable-untyped-computed-read/dom.ts b/tests/corpus/immutable-untyped-computed-read/dom.ts new file mode 100644 index 0000000000..a1939c467d --- /dev/null +++ b/tests/corpus/immutable-untyped-computed-read/dom.ts @@ -0,0 +1,18 @@ +// The typed half of the program: a class with an Immutable array field. +// Node erases the annotation; the field is an ordinary array. +import type { Immutable } from "@scriptc/types"; + +const RULES: Immutable = [1, 2, 3]; + +export class El { + rules: readonly number[] = RULES; + text = ""; +} + +export function count(el: El): number { + let t = 0; + for (const r of el.rules) t += r; + return t; +} + +export const root = new El(); diff --git a/tests/corpus/immutable-untyped-computed-read/main.ts b/tests/corpus/immutable-untyped-computed-read/main.ts new file mode 100644 index 0000000000..e7397ee08c --- /dev/null +++ b/tests/corpus/immutable-untyped-computed-read/main.ts @@ -0,0 +1,10 @@ +// Untyped JavaScript that creates its own values keeps them its own, even +// when a class in the program holds an Immutable field. The computed read +// `table[key]` is a fresh local object's member, so the keyed-access +// helper it shares with every other computed access must not read class +// state: the class instance is not one of its receivers. +import { count, root } from "./dom.ts"; +import { setText } from "./app.js"; + +setText(root, "a"); +console.log(count(root), root.text); diff --git a/tests/diagnostics/contract-immutable-dynamic-receiver.ts b/tests/diagnostics/contract-immutable-dynamic-receiver.ts new file mode 100644 index 0000000000..3bd139ed3c --- /dev/null +++ b/tests/diagnostics/contract-immutable-dynamic-receiver.ts @@ -0,0 +1,22 @@ +// Dynamic code that receives a class instance keeps its Immutable fields +// out of reach: the computed-access helper's per-class branches must not be +// narrowed away when a class instance can be its receiver. +import type { Immutable } from "@scriptc/types"; + +const RULES: Immutable = [1, 2, 3]; + +export class El { + rules: readonly number[] = RULES; + text = ""; +} + +export const root = new El(); + +function tamper(el: any, key: string): void { + const got = el[key]; + got.push(4); + el.text = "x"; +} + +tamper(root, "rules"); +console.log(root.text); diff --git a/tests/diagnostics/contract-immutable-element-reads.ts b/tests/diagnostics/contract-immutable-element-reads.ts new file mode 100644 index 0000000000..3d5d490814 --- /dev/null +++ b/tests/diagnostics/contract-immutable-element-reads.ts @@ -0,0 +1,20 @@ +// An element read out of an Immutable array is Immutable only when the +// element type can hold an object: a number element of an Immutable array +// is a plain value, while an object element (or an element that is itself +// an array) read into dynamic code stays refused. +import type { Immutable } from "@scriptc/types"; + +type Row = { n: number }; + +class Tables { + nums: Immutable = [1, 2, 3]; + rows: Immutable = [{ n: 1 }]; + grid: Immutable = [[1]]; +} + +const t = new Tables(); + +const plain: unknown = t.nums[0]; +const row: unknown = t.rows[0]; +const nested: unknown = t.grid[0]; +console.log(plain, row, nested); diff --git a/tests/harness/__snapshots__/contract-immutable-dynamic-receiver.ts.txt b/tests/harness/__snapshots__/contract-immutable-dynamic-receiver.ts.txt new file mode 100644 index 0000000000..977e90987d --- /dev/null +++ b/tests/harness/__snapshots__/contract-immutable-dynamic-receiver.ts.txt @@ -0,0 +1,8 @@ +contract-immutable-dynamic-receiver.ts:16:15 - error SC7005: a value that may be Immutable escapes to dynamic (any or unknown) code, where writes are not checked: 'el[key]' + + 15 | function tamper(el: any, key: string): void { + 16 | const got = el[key]; + | ^~~~~~~ + 17 | got.push(4); + + hint: keep Immutable values in typed code, or copy the value before handing it out \ No newline at end of file diff --git a/tests/harness/__snapshots__/contract-immutable-element-reads.ts.txt b/tests/harness/__snapshots__/contract-immutable-element-reads.ts.txt new file mode 100644 index 0000000000..61ecb5cf02 --- /dev/null +++ b/tests/harness/__snapshots__/contract-immutable-element-reads.ts.txt @@ -0,0 +1,17 @@ +contract-immutable-element-reads.ts:18:22 - error SC7005: a value that may be Immutable escapes to dynamic (any or unknown) code, where writes are not checked: 't.rows[0]' + + 17 | const plain: unknown = t.nums[0]; + 18 | const row: unknown = t.rows[0]; + | ^~~~~~~~~ + 19 | const nested: unknown = t.grid[0]; + + hint: keep Immutable values in typed code, or copy the value before handing it out + +contract-immutable-element-reads.ts:19:25 - error SC7005: a value that may be Immutable escapes to dynamic (any or unknown) code, where writes are not checked: 't.grid[0]' + + 18 | const row: unknown = t.rows[0]; + 19 | const nested: unknown = t.grid[0]; + | ^~~~~~~~~ + 20 | console.log(plain, row, nested); + + hint: keep Immutable values in typed code, or copy the value before handing it out \ No newline at end of file diff --git a/tests/harness/corpus-costs/immutable-array-foreign-elements/main.ts.json b/tests/harness/corpus-costs/immutable-array-foreign-elements/main.ts.json new file mode 100644 index 0000000000..a4a33f4478 --- /dev/null +++ b/tests/harness/corpus-costs/immutable-array-foreign-elements/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3100 } diff --git a/tests/harness/corpus-costs/immutable-untyped-computed-read/main.ts.json b/tests/harness/corpus-costs/immutable-untyped-computed-read/main.ts.json new file mode 100644 index 0000000000..e4ec7d37b3 --- /dev/null +++ b/tests/harness/corpus-costs/immutable-untyped-computed-read/main.ts.json @@ -0,0 +1 @@ +{ "plain": 3200 }