Indexing and loops: a[i]! wherever the bound is proved, own-key for...in, reused lists #70
Loading…
Reference in a new issue
No description provided.
Delete branch "evobug/fb3-indexing"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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
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.lengthwhen the read happens) and replaces the one-shape check inanalyze.rs. What's accepted now:cart.lines[i]!,this.#queue[i]!, throughconstaliases and destructuring), andlets that nothing assigns between the check and the read;k + 1of another loop's index,a.length - 1,x | 0);a[i + 1]!underi + 1 < a.length, anda[i - 1]!fromi = 1, underi >= 1, or afterif (i === 0) continue;;b = a.map(...)/toSorted/slice()/new Float64Array(a.length)/Array.from({ length: a.length });typealias) andconstarray 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 inproject.rs, like the loop rewrite's member types;&&conditions;forheader (while,&&,||,if,?:, early exits,Number.isInteger(i),if (items.length === 0) return;).The check is sound up to documented limits. Every write, call and
awaitin 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 aletor an object get no bounds at all; arrays stored in a container get none where that container is used.Option<T>[]andnew Array(n)(holes) aren't covered, because a read in bounds can still beundefinedthere. The rule docs list exactly what's accepted and what the checker can't see: another object holding the same array, getters andProxy, 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 fixturenulls_and_castschanged accordingly:words[i - 1]!fromi = 1is now accepted, anddrainnow pops before the read to stay a negative case.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) ...andfor...of.Indices from data: done (docs, no exemption). A new "Reading by index" section in
docs/guide/loops.mdcovers it. The pattern: check the index once (Number.isInteger(i) && i >= 0 && i < a.length, returning anerr) and the reads after it are accepted; or give the index a literal-union type (size: 0 | 1 | 2, also aftervalidate<T>), which needs no check over a table of that length; or use?? fallback/at(-1) ?? fallback.no-for-in: done, with a measured correction. It now acceptsfor...inover a binding (never reassigned) ofObject.create(null)or{ __proto__: null }, and a body that starts withif (!Object.hasOwn(o, key)) continue;(or is a singleif (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 therefor...inallocates too (97 B per walk for 4 keys).Object.keysplus a lookup was the fastest (79 ns, against 92 ns forfor...inand 281 ns forObject.values).for...inis allocation-free only on fixed-shape objects (7 ns, 0 B). The rule page has the table.Related fixes:
no-nullnow allows__proto__: null.safe-ts migrate null-to-undefinedused to rewrite it to__proto__: undefined, which silently gives the object its prototype back; it now keeps it and notes why (new case intests/migrate/null-to-undefined/null-apis).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:fill(undefined, 0, count)on anOption<T>[]fill(null!)(upstream's form)length = 0[]So
length = 0costs as much as a new array. The SAFE-TS form, with an example in the guide, isOption<T>[]with a count, cleared withfill(undefined).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):no-unchecked-castfindings onx[...]!, 94 are now accepted; the other 983 remain;A sample of the remaining 983 shows they really are unproven:
settlement,rows[r]![c]!;server.commands[0]!);numberthat 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;Math.floor(x), which may beNaN;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: theitems[i]paragraph.README.md: rule-table rows forno-unchecked-castandno-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.mjsandnpm 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
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]>