Stop reporting Immutable escapes that untyped code cannot use

This commit is contained in:
Chris Tate
2026-11-11 16:21:14 -06:00
parent 49201df379
commit 47042f3ebe
18 changed files with 238 additions and 3 deletions
+3
View File
@@ -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<number[]>` into untyped code compiles, while an element of an `Immutable<Row[]>` or an `Immutable<number[][]>` 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.
<!-- release:end -->
+19 -3
View File
@@ -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":
@@ -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<string>();
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
@@ -0,0 +1,7 @@
{
"order": [
"<repo>/tests/corpus/immutable-array-foreign-elements/app.js",
"<repo>/tests/corpus/immutable-array-foreign-elements/main.ts"
],
"diags": []
}
@@ -0,0 +1,8 @@
{
"order": [
"<repo>/tests/corpus/immutable-untyped-computed-read/dom.ts",
"<repo>/tests/corpus/immutable-untyped-computed-read/app.js",
"<repo>/tests/corpus/immutable-untyped-computed-read/main.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/diagnostics/contract-immutable-dynamic-receiver.ts"
],
"diags": []
}
@@ -0,0 +1,6 @@
{
"order": [
"<repo>/tests/diagnostics/contract-immutable-element-reads.ts"
],
"diags": []
}
@@ -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];
}
@@ -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<number[]> = [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<string, string> = {};
assign(target, { a: "x" });
console.log(target["a"], sum, Array.isArray(dynamic));
@@ -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];
}
@@ -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<number[]> = [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();
@@ -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);
@@ -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<number[]> = [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);
@@ -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<number[]> = [1, 2, 3];
rows: Immutable<Row[]> = [{ n: 1 }];
grid: Immutable<number[][]> = [[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);
@@ -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
@@ -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
@@ -0,0 +1 @@
{ "plain": 3100 }
@@ -0,0 +1 @@
{ "plain": 3200 }