Indexing and loops: a[i]! wherever the bound is proved, own-key for...in, reused lists #70

Merged
sionzee merged 2 commits from evobug/fb3-indexing into main 2026-11-16 23:42:06 +01:00
Owner

Round 3 of the 0.2.0 adoption feedback: the area of indexing and loops (the a[i]! entry, #3 of the top ten; no-for-in; clearing a reused list).

Per feedback item

  1. Widen the a[i]! exemption: done. A new module, crates/safe_ts_core/src/bounds.rs, proves a read in bounds (an integer, >= 0, < a.length when the read happens) and replaces the one-shape check in analyze.rs. What's accepted now:

    • member paths (cart.lines[i]!, this.#queue[i]!, through const aliases and destructuring), and lets that nothing assigns between the check and the read;
    • any integer start (a literal, k + 1 of another loop's index, a.length - 1, x | 0);
    • descending loops;
    • neighbours: a[i + 1]! under i + 1 < a.length, and a[i - 1]! from i = 1, under i >= 1, or after if (i === 0) continue;;
    • a second array of the same length: both bounds in the test, a length check before the loop, or b = a.map(...) / toSorted / slice() / new Float64Array(a.length) / Array.from({ length: a.length });
    • tuples (also through a local type alias) and const array literals: a literal bound, a clamp of an integer (T[Math.max(0, Math.min(T.length - 1, n | 0))]!, Math.floor(x) || 0), and an index whose declared type is a union of integer literals in range. The last one is resolved across files in project.rs, like the loop rewrite's member types;
    • extra && conditions;
    • beyond the list: checks outside a for header (while, &&, ||, if, ?:, early exits, Number.isInteger(i), if (items.length === 0) return;).

    The check is sound up to documented limits. Every write, call and await in the file is an event. A bound only holds if no event between the check and the read can reach the array. That covers assigning it or any prefix of its path, shrinking methods, methods of a prefix, passing it (or a prefix) to a call, callbacks, local functions whose body may change it, await, and project calls for module-level arrays. A bound read before a loop must hold for the whole loop. Reads inside callbacks get no outer bounds. Arrays stored in a let or an object get no bounds at all; arrays stored in a container get none where that container is used. Option<T>[] and new Array(n) (holes) aren't covered, because a read in bounds can still be undefined there. The rule docs list exactly what's accepted and what the checker can't see: another object holding the same array, getters and Proxy, a typed array's buffer being transferred, and element types it can't see.

    Stricter than before, in two cases (both unsound before): a read that comes after a call, in the same iteration, that is passed the array or runs a callback; and a read from an array declared Option<T>[]. The fixture nulls_and_casts changed accordingly: words[i - 1]! from i = 1 is now accepted, and drain now pops before the read to stay a negative case.

  2. Better message: done. It now says why the read isn't proved, for example: "`i - 1` can be -1 here", "the loop starts at `start`, which isn't known to be an integer", "the call `removeEmpty(cart)` (line 83) ... may change `cart.lines`", "`quantities` ... check `quantities.length === prices.length` before the loop", "`Math.floor(x)` may be `NaN` ... clamp `x | 0` or `Math.floor(x) || 0`". The help points to a tuple type, ?? fallback, const x = a[i]; if (x === undefined) ... and for...of.

  3. Indices from data: done (docs, no exemption). A new "Reading by index" section in docs/guide/loops.md covers it. The pattern: check the index once (Number.isInteger(i) && i >= 0 && i < a.length, returning an err) and the reads after it are accepted; or give the index a literal-union type (size: 0 | 1 | 2, also after validate<T>), which needs no check over a table of that length; or use ?? fallback / at(-1) ?? fallback.

  4. no-for-in: done, with a measured correction. It now accepts for...in over a binding (never reassigned) of Object.create(null) or { __proto__: null }, and a body that starts with if (!Object.hasOwn(o, key)) continue; (or is a single if (Object.hasOwn(o, key))), which is what a library's dictionary needs. The measurement corrects the feedback's premise: V8 keeps null-prototype objects in dictionary mode, and there for...in allocates too (97 B per walk for 4 keys). Object.keys plus a lookup was the fastest (79 ns, against 92 ns for for...in and 281 ns for Object.values). for...in is allocation-free only on fixed-shape objects (7 ns, 0 B). The rule page has the table.
    Related fixes: no-null now allows __proto__: null. safe-ts migrate null-to-undefined used to rewrite it to __proto__: undefined, which silently gives the object its prototype back; it now keeps it and notes why (new case in tests/migrate/null-to-undefined/null-apis).

  5. Clearing a reused list: done (docs, measured). New section "Clearing a reused list" in docs/guide/performance-myths.md. Measured on Node 26.13, per frame:

    Form 100 items 1 000 items
    fill(undefined, 0, count) on an Option<T>[] 0.25 µs, 0 B 2.6–3.1 µs, 0 B
    fill(null!) (upstream's form) 0.24 µs, 0 B 2.4–3.9 µs, 0 B
    length = 0 0.38 µs, 2.3 kB 3.9–4.6 µs, 29 kB
    a new [] 0.36 µs, 2.4 kB 3.6–4.0 µs, 29 kB

    So length = 0 costs as much as a new array. The SAFE-TS form, with an example in the guide, is Option<T>[] with a count, cleared with fill(undefined).

  6. Real cases: done. The TwitchRTS adoption branch has already rewritten every rejected shape, so the count runs on its upstream code (origin/main, written without SAFE-TS, 525 files, with the branch's package.json files):

    • of 1 077 no-unchecked-cast findings on x[...]!, 94 are now accepted; the other 983 remain;
    • on the adoption branch itself there are no new findings (232 before, 232 after).

    A sample of the remaining 983 shows they really are unproven:

    • 380 index something that isn't a path: call results, the tests' global settlement, rows[r]![c]!;
    • 337 are literal indices into arrays of unknown length (server.commands[0]!);
    • 102 use a number that may be fractional. About 40 of those are a callback's index parameter (forEach((x, i) => other[i]!)), which isn't covered and is documented as such;
    • 24 clamp Math.floor(x), which may be NaN;
    • the rest are bounds over another array without an equality check, real callbacks in the loop, or bounds that come from an earlier loop's exit.

    In short, real code mostly indexes in ways nothing in the code bounds.

Docs pages changed

  • docs/rules/no-unchecked-cast.md: new section listing exactly what's accepted, the messages, rejected and accepted examples, and the limits.
  • docs/rules/no-for-in.md: the two accepted forms, plus the performance table.
  • docs/guide/loops.md: "Reading by index", including indices from data.
  • docs/guide/performance-myths.md: "Clearing a reused list".
  • docs/guide/absence.md: the items[i] paragraph.
  • README.md: rule-table rows for no-unchecked-cast and no-for-in.
  • CHANGELOG.md: Unreleased, under Changed (two entries) and Fixed (__proto__: null).

Verification

All passed: npm run build, cargo nextest run --workspace (210 tests), cargo clippy -q --workspace --all-targets (no warnings in the changed code), npm run test:std (285), npm run typecheck, npm run typecheck:emit, node scripts/docs-typecheck.mjs and npm run test:docs (386 examples), npm run test:vite, npm run bench:check, node scripts/verify-packages.mjs.

New tests: the fixture tests/fixtures/bounded_indexes (accepted and rejected shapes, in a shop and cart setting), a new case in the null codemod fixture, and the new docs examples, which are tested.

🤖 Generated with Claude Code

Round 3 of the 0.2.0 adoption feedback: the area of indexing and loops (the `a[i]!` entry, #3 of the top ten; `no-for-in`; clearing a reused list). ## Per feedback item 1. **Widen the `a[i]!` exemption: done.** A new module, `crates/safe_ts_core/src/bounds.rs`, proves a read in bounds (an integer, `>= 0`, `< a.length` when the read happens) and replaces the one-shape check in `analyze.rs`. What's accepted now: - member paths (`cart.lines[i]!`, `this.#queue[i]!`, through `const` aliases and destructuring), and `let`s that nothing assigns between the check and the read; - any integer start (a literal, `k + 1` of another loop's index, `a.length - 1`, `x | 0`); - descending loops; - neighbours: `a[i + 1]!` under `i + 1 < a.length`, and `a[i - 1]!` from `i = 1`, under `i >= 1`, or after `if (i === 0) continue;`; - a second array of the same length: both bounds in the test, a length check before the loop, or `b = a.map(...)` / `toSorted` / `slice()` / `new Float64Array(a.length)` / `Array.from({ length: a.length })`; - tuples (also through a local `type` alias) and `const` array literals: a literal bound, a clamp of an integer (`T[Math.max(0, Math.min(T.length - 1, n | 0))]!`, `Math.floor(x) || 0`), and an index whose declared type is a union of integer literals in range. The last one is resolved across files in `project.rs`, like the loop rewrite's member types; - extra `&&` conditions; - beyond the list: checks outside a `for` header (`while`, `&&`, `||`, `if`, `?:`, early exits, `Number.isInteger(i)`, `if (items.length === 0) return;`). The check is sound up to documented limits. Every write, call and `await` in the file is an event. A bound only holds if no event between the check and the read can reach the array. That covers assigning it or any prefix of its path, shrinking methods, methods of a prefix, passing it (or a prefix) to a call, callbacks, local functions whose body may change it, `await`, and project calls for module-level arrays. A bound read before a loop must hold for the whole loop. Reads inside callbacks get no outer bounds. Arrays stored in a `let` or an object get no bounds at all; arrays stored in a container get none where that container is used. `Option<T>[]` and `new Array(n)` (holes) aren't covered, because a read in bounds can still be `undefined` there. The rule docs list exactly what's accepted and what the checker can't see: another object holding the same array, getters and `Proxy`, a typed array's buffer being transferred, and element types it can't see. **Stricter than before, in two cases** (both unsound before): a read that comes after a call, in the same iteration, that is passed the array or runs a callback; and a read from an array declared `Option<T>[]`. The fixture `nulls_and_casts` changed accordingly: `words[i - 1]!` from `i = 1` is now accepted, and `drain` now pops before the read to stay a negative case. 2. **Better message: done.** It now says why the read isn't proved, for example: ``"`i - 1` can be -1 here"``, ``"the loop starts at `start`, which isn't known to be an integer"``, ``"the call `removeEmpty(cart)` (line 83) ... may change `cart.lines`"``, ``"`quantities` ... check `quantities.length === prices.length` before the loop"``, ``"`Math.floor(x)` may be `NaN` ... clamp `x | 0` or `Math.floor(x) || 0`"``. The help points to a tuple type, `?? fallback`, `const x = a[i]; if (x === undefined) ...` and `for...of`. 3. **Indices from data: done (docs, no exemption).** A new "Reading by index" section in `docs/guide/loops.md` covers it. The pattern: check the index once (`Number.isInteger(i) && i >= 0 && i < a.length`, returning an `err`) and the reads after it are accepted; or give the index a literal-union type (`size: 0 | 1 | 2`, also after `validate<T>`), which needs no check over a table of that length; or use `?? fallback` / `at(-1) ?? fallback`. 4. **`no-for-in`: done, with a measured correction.** It now accepts `for...in` over a binding (never reassigned) of `Object.create(null)` or `{ __proto__: null }`, and a body that starts with `if (!Object.hasOwn(o, key)) continue;` (or is a single `if (Object.hasOwn(o, key))`), which is what a library's dictionary needs. The measurement corrects the feedback's premise: V8 keeps null-prototype objects in dictionary mode, and there `for...in` allocates too (97 B per walk for 4 keys). `Object.keys` plus a lookup was the fastest (79 ns, against 92 ns for `for...in` and 281 ns for `Object.values`). `for...in` is allocation-free only on fixed-shape objects (7 ns, 0 B). The rule page has the table. Related fixes: `no-null` now allows `__proto__: null`. `safe-ts migrate null-to-undefined` used to rewrite it to `__proto__: undefined`, which silently gives the object its prototype back; it now keeps it and notes why (new case in `tests/migrate/null-to-undefined/null-apis`). 5. **Clearing a reused list: done (docs, measured).** New section "Clearing a reused list" in `docs/guide/performance-myths.md`. Measured on Node 26.13, per frame: | Form | 100 items | 1 000 items | |---|---|---| | `fill(undefined, 0, count)` on an `Option<T>[]` | 0.25 µs, 0 B | 2.6–3.1 µs, 0 B | | `fill(null!)` (upstream's form) | 0.24 µs, 0 B | 2.4–3.9 µs, 0 B | | `length = 0` | 0.38 µs, 2.3 kB | 3.9–4.6 µs, 29 kB | | a new `[]` | 0.36 µs, 2.4 kB | 3.6–4.0 µs, 29 kB | So `length = 0` costs as much as a new array. The SAFE-TS form, with an example in the guide, is `Option<T>[]` with a count, cleared with `fill(undefined)`. 6. **Real cases: done.** The TwitchRTS adoption branch has already rewritten every rejected shape, so the count runs on its upstream code (`origin/main`, written without SAFE-TS, 525 files, with the branch's package.json files): - of 1 077 `no-unchecked-cast` findings on `x[...]!`, **94 are now accepted**; the other 983 remain; - on the adoption branch itself there are **no new findings** (232 before, 232 after). A sample of the remaining 983 shows they really are unproven: - 380 index something that isn't a path: call results, the tests' global `settlement`, `rows[r]![c]!`; - 337 are literal indices into arrays of unknown length (`server.commands[0]!`); - 102 use a `number` that may be fractional. About 40 of those are a callback's index parameter (`forEach((x, i) => other[i]!)`), which isn't covered and is documented as such; - 24 clamp `Math.floor(x)`, which may be `NaN`; - the rest are bounds over another array without an equality check, real callbacks in the loop, or bounds that come from an earlier loop's exit. In short, real code mostly indexes in ways nothing in the code bounds. ## Docs pages changed - `docs/rules/no-unchecked-cast.md`: new section listing exactly what's accepted, the messages, rejected and accepted examples, and the limits. - `docs/rules/no-for-in.md`: the two accepted forms, plus the performance table. - `docs/guide/loops.md`: "Reading by index", including indices from data. - `docs/guide/performance-myths.md`: "Clearing a reused list". - `docs/guide/absence.md`: the `items[i]` paragraph. - `README.md`: rule-table rows for `no-unchecked-cast` and `no-for-in`. - `CHANGELOG.md`: Unreleased, under Changed (two entries) and Fixed (`__proto__: null`). ## Verification All passed: `npm run build`, `cargo nextest run --workspace` (210 tests), `cargo clippy -q --workspace --all-targets` (no warnings in the changed code), `npm run test:std` (285), `npm run typecheck`, `npm run typecheck:emit`, `node scripts/docs-typecheck.mjs` and `npm run test:docs` (386 examples), `npm run test:vite`, `npm run bench:check`, `node scripts/verify-packages.mjs`. New tests: the fixture `tests/fixtures/bounded_indexes` (accepted and rejected shapes, in a shop and cart setting), a new case in the null codemod fixture, and the new docs examples, which are tested. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Indexing and loops: a[i]! wherever the bound is proved, own-key for...in
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m15s
784fd56919
no-unchecked-cast accepts a[i]! wherever the checked bound proves the read
(new bounds.rs): member paths and lets, any integer start, descending loops,
neighbours, extra && conditions, twin arrays, tuples, clamps of integers,
literal-union indices, and checks in while/&&/if/?:/early exits. Nothing
between the check and the read may change the array or the index. An
unproved read says why and points to the alternatives.

no-for-in accepts loops over Object.create(null) / { __proto__: null }
bindings and bodies guarded by Object.hasOwn. no-null allows
__proto__: null, and null-to-undefined keeps it.

Docs: the rule pages list exactly what is accepted; the loops guide covers
indices from data; the performance guide measures clearing a reused list
and the for...in forms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge remote-tracking branch 'origin/main' into up-70
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m12s
3970afaa1c
sionzee deleted branch evobug/fb3-indexing 2026-11-16 23:42:06 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!70
No description provided.