Skip to content

Destructuring defaults: missing elements take their default; rc/own pattern and parameter default leaks - #1022

Merged
ASDAlexander77 merged 8 commits into
mainfrom
destructuring-leftovers
Nov 24, 2026
Merged

ASDAlexander77 merged 8 commits into
mainfrom
destructuring-leftovers

Conversation

@ASDAlexander77

Copy link
Copy Markdown
Owner

Fixes the destructuring and default-value bugs left over from #1016.

Every memory model

  • An array pattern longer than its source (const [a = mk(1), b = mk(2)] = [mk(i)]) crashed the compiler. An element's default now applies wherever the element is missing: past the end of a literal, tuple or constant array, in the else branch of the bounds test, and where the element is undefined. [a = 1, b = 2] = [5] now gives b = 2 (was 0), matching tsc and node. IR changes in every model for these shapes; tests/00destructuring_redeclare_defaults.ts now prints the correct value.
  • An element past the end with no default stays undefined (user ruling; no TS2493 error).

rc and own

  • A pattern default that is a local (const e = mk(..); const { p = e } = X, and the assignment form) no longer leaks e.

own

Verification

  • New RUN tests match gc and node; new IR tests find 0 matches on main.
  • IR vs main: rc/own change only for the targeted shapes; gc/none only for the array-default shapes.
  • Guard-page heap (282 runs, 0 bad), mm_fuzz.py (0 failures, own acceptance unchanged), leaks flat on every fixed shape.
  • Full ctest 9410/9413; the three failures (test-compile-atomic-rc, the gc-defaultlib-collector tests) fail the same on main locally (DefaultLib archives older than TSLANG 177: names that start with __ are read as written; compiler helpers are named with . #1011).

Not in this PR (pre-existing)

  • Under own, an array literal passed straight to a function may leak (po([undefined], i)).
  • Under rc, const xs: number[] = c ? [i] : [] leaks.
  • Own refuses const [a = mk(1), b = mk(2)] = [mk(i)] and let { p = mk(1) } = r; p = mk(3) (refusals, not leaks).
  • An element past the end of an array value with no default reads as null, not undefined.

🤖 Generated with Claude Code

ASDAlexander77 and others added 8 commits November 24, 2026 12:21
… missing

`const [a = mk(1), b = mk(2)] = [mk(i)]` crashed the compiler in every
memory model (also a typed tuple, a nested pattern, a for...of pattern, a
parameter pattern), and `const [a = 1, b = 2] = [5]` gave b the default of
its type (0; a string null) instead of 2: array binding elements ignored
their defaults - an element past the end of a literal or tuple was
undefined, which the compiler then read as an object. The default is now
the element's value past the end of a literal, tuple or constant array, in
the bounds test's else branch for an array (the element then of both types
when the default is of another), and where the element read is undefined or
optional; as in TypeScript. An element a literal is known to have (also an
inner literal read out of an outer one) is read without a bounds test, so
its default never applies there. An element past the end without a default
stays undefined, as #964 made it (tsc reports TS2493 for a tuple there).

IR changes in every model on two existing tests, both this shape:
tests/00destructuring_redeclare_defaults.ts (`var [x, , y = 5] = [1, 2]`: y
is now 5, the assert was against the second declaration) and
own/rc_destructuring_literal.ts (in-bounds literal elements with defaults:
read directly).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
`const e = mk(i + 1); const { p = e } = r`, from a record literal, and the
assignment form `({ p: p2 = e ?? mk(1) } = ...)` leaked `e` every
evaluation under rc (main too; own too for a named record): the default
region yields the local as the value-or-default's result, and
handedOnByConditional knew only an IfOp branch handing a value on, so the
local's release took the default's ts.Result for an escape. A
ts.OptValueOrDefault's default is now handed on the same way, under rc and
own (set per module; gc and none keep their IR).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…f the scope

`const { p = mk(1) } = r`, `p = e ?? mk(1)`, `p = [mk(1)][0]`, `p = "q" + i`
leaked the new value under own every evaluation that ran the default (main
too): the pattern's value borrows the field or the default, and nothing
owned the default's value (own does not share rc's settling of
ts.OptValueOrDefault). Under own, optionalValueOrDefault now gives the
default a slot of the scope (an owned local, empty unless the default runs,
released when the scope ends) and the region yields a read of it. Once
calls are settled, settleOwnPatternDefaults keeps the store only for a new
value - at the region's yield, or in the branch of a conditional there
that makes it; the one element of a literal made only to read it is that
element - and drops it for a borrowed default (`p = e`), which yields its
borrow as before. Own acceptance unchanged (corpus, plain and
--own-fallback=count, which compiles these programs identically); rc, gc
and none IR unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rame's slot

`function f(p: N = mk(1))`, a method's, a constructor's, an arrow's, a
closure's and a default reading another parameter leaked the default under
own every call that took it (main too; #1015 fixed rc with a frame slot).
processOptionalParam now creates #1015's slot under own too, without its
retain: the default is stored and read back, and settleOwnPatternDefaults
(now also for a ts.ParamOpt region) keeps the store only for a new value; a
borrowed default (a global, another parameter) yields its borrow. A
parameter that may be kept - stored, returned, given to a call or a literal
(`constructor(public a = new C())`) - is left as before: own keeps it with
its default (own_param_default_kept). Own's field-locals rewrite read a
parameter's field again where the result is stored, after the slot's
release at the return; a release of a default slot now counts as a write
of fields there (OwnershipFacts mayWriteField). rc, gc and none IR
unchanged; own acceptance unchanged (corpus, plain and with
--own-fallback=count).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ade in front of the TryOp/SwitchOp

The slot holding a pattern default that makes a new value (0cde20d) was made where the
default is, inside the TryOp's or SwitchOp's region, and released where that region does
not reach: own failed with "operand #0 does not dominate this use" (`try { const { p =
mk(9) } = r; }`, `case 1: { ... }`, a case without a block, in a loop). It is now made
where an owned local of that scope is hoisted to. A generator keeps the default as before
(its locals are fields of the generator object). A slot made inside an expression (a
destructuring assignment in `?:`) reaches no scope exit: it is not released there, and
settleOwnPatternDefaults takes it out again, so own refuses that program with the ownership
error, as main does, not the internal one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… held by the pattern-default slot

Once 48daae3 applied an array element's default, own refused array patterns with an object
default that main accepted (`const [a = mk(1)] = xs`, `(N | null)[]`, `(N | undefined)[]`,
a destructured parameter `([a = mk(1)]: N[])`, `{ arr: [a = mk(1)] } = o`): the bounds
test's ts.If merged a borrow of the element with a new value nobody owned. The default
branch now stores into the same slot an object pattern's default uses, and
settleOwnPatternDefaults settles it there too (also through the ts.OptionalValue an element
of `T | undefined` wraps it in). A destructured parameter's slot is the frame's, listed with
the parameters' storage and given back at exit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ult on is read from the pass's options

The static thread_local flag set in runOnOperation (handsOnThroughDefaults) is gone:
handedOnByConditional reads compileOptions.tracksOwnership() itself, and it and the helpers
that call it (leavesBlockBy, yieldedByBranch, storedIntoUnownedLocalOutside, lastUseInBlock,
escapesThroughStore) are members now, all called from members already. No change in what
the pass emits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s undefined

As node has it (`const [a, b] = [mk(5)] as N[]`: b is undefined). A name bound to an
element of a reference type (a class, an interface, an object, an array, a tuple, a union
with one of those or null) is `T | undefined` behind the bounds test, and the past-end branch
yields undefined; it read null. That covers nested patterns, for-of, and destructured
parameters, in every memory model. Not where a literal source has the element, nor for an
inner pattern, which reads the element on. A primitive element (number[], string[], unions
of those) keeps its type, which cannot hold undefined, and reads as the type's default as
before. The assignment form gives undefined to a target that can hold it (`let t: N |
undefined; [s, t] = xs`); it read whatever followed the array's data.

A `const` read of an element through that optional wrapper is held like a plain element
read (readsElement looks through ts.OptionalValue): under rc the overwrite of the element
freed what the const still read (00const_element_read under the guard-page heap).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ASDAlexander77
ASDAlexander77 merged commit 9cf85b2 into main Nov 24, 2026
8 checks passed
@ASDAlexander77
ASDAlexander77 deleted the destructuring-leftovers branch November 24, 2026 17:08
ASDAlexander77 added a commit that referenced this pull request Nov 24, 2026
…; literal and conditional leaks; loose null narrowing; --own-fallback follow-ups (#1027)

* -mm=rc: an argument read out of a place a closure may overwrite is held across the call

A parameter borrows its argument. When the argument was read out of a field or an element of
an object a closure can reach - a captured local's array, a const object captured by value -
and the callee (or what it calls) gave that place a new value (`arr[0] = mk(i)`, `h.o =
mk(i)`), took the element out (pop/shift/splice) or gave the captured local a new array, the
parameter read freed memory (U10: rc printed 195751491, gc 4495501; main too).
holdGlobalArguments now also holds such an argument (readsCapturedPlace) when the call may
write a place (writesPlace, propagated through callees; a call through a value may write
any). The destructured-parameter form (U06, `([o]: N[]) => { arr[0] = mk(i); o.x }`) is fixed
in the callee: under rc the names a destructured parameter binds own what they read, as
locals do, and are given back at exit. Own refuses these programs, as before.

IR impact on the corpus (rc only; own, gc, none unchanged): 9 files, a RetainSlot/ReleaseSlot
for destructured parameter names; no corpus file gains a caller-side hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: an array literal of no values given straight to a call is given back after it

`po([undefined], i)`, `pn([null])` and `ln([])` leaked their array every call under own
(3M calls: 110-190 MB on main, 5.3 MB now; `[mk(i)]` and `[i]` were flat already). The
literal neither owned nor borrowed anything, so ownNewArrayArguments left it to nobody:
holdsWhatItIsGiven now counts a literal of undefined/null elements as owning what it holds,
and the empty constant array cast to an array (`[]`) holds nothing. IR: own only, the four
corpus files that pass `[]` or `[undefined]` to a call (an owned result and its release).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rc/own: conditionals and pattern defaults are settled in a module with no function returning a heap value

OwnedReturnConsumptionPass returned early when no function was classified as returning owned
(no class, no function returning a heap value), running only some of its module-local steps:
consumeConditionalResults and settleOwnPatternDefaults were skipped. Under rc `const xs:
number[] = c ? [i] : []` (a let, the assignment form, strings, nested arrays) kept the
branch's count of the new array beside the local's own and leaked it every evaluation (3M:
110-200 MB, now 5.3 MB). Both paths now run the same tail (settleModuleLocalResults).

IR: rc and own in the class-less files with a conditional of a new value (11 rc / 13 own
corpus files); gc and none gain the same annotations and retains the class-bearing modules
already had there (9 files), which their lowering drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* `x == null` of a value that may be undefined does not narrow it to null

Loose equality with null or undefined is true for both. Of a value whose type may be
undefined (an optional, a union with undefined), `c == null` narrowed the equal side to null:
in `c == null && c === undefined` the second test was false for undefined and `c === null`
true, also in `if (c == null) { ... }` (every memory model; node gives the opposite). Now
the equal side keeps its type and the other side is the type without null and undefined
(checkSafeCastLooseNullish); strict comparisons and types that cannot be undefined narrow as
before. Outputs of the tests whose IR changed (value_missing*, own_value_*, 01arguments)
are unchanged. No IR test: a narrowing fix, the RUN test fails on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: a `let` a pattern binds with a default can be given another value

`let { p = mk(1) } = r; p = mk(3)` was refused ("'p' borrows 'r.p' and cannot be assigned",
"'p' is merged from several branches"). Its value is a merge of the field's value and of the
pattern-default slot's, both borrows, which letBorrows did not see as one (a block argument
after lowering). It now does (mergeOfPatternDefault), and the `let` is split like one given a
field read (TSLANG 66): what it is given later goes into a holder of its own and the `let`
borrows it; no semantic change, the holder mechanism the plain `let p = r.p; p = mk(3)`
already uses. `const [a = mk(1), b = mk(2)] = [mk(i)]` (the other shape of the item) was
accepted already since the array-default slot (#1022); the test covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: pin that --own-fallback=count reads OwnershipModuleFactsPass's cached analysis

An interface-typed parameter given to two `Shape | null` fields is counted only when the
module's facts (DescriptorObjectsAnalysis, cached by OwnershipModuleFactsPass) say no class
here may hold a closure; without the cache the answer is "may hold" and the program would be
refused. own_fallback_cached_analysis (IR: compiles with the warning, 2 counted retains) fails
if a pipeline change drops the cache; own_fallback_cached_analysis_held (a class with a
closure field) stays an error. The probes of final-rereview m-1 (rr/ip.ts, ip_held.ts).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* --own-fallback=count: a function that fails reports no count beside its error

With the flag, a function refused for an error that stays could print "-mm=own counts this
object here" beside it (own_escaping_capture_used_after_error,
own_fallback_uncounted_error_same_place): the user read "counted" about a program that was
not built. The counts are reported only when the function does not fail. The
fallback test's EXPECT_ERROR mode now also checks that no count is reported (fails with the
previous binary on own_escaping_capture_used_after_error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: --own-fallback=count against the default library

No ctest used the flag with the default library (final-review M-5). own-defaultlib-facts.cmake
takes EXTRA options (compiled each run under the JIT then, and required to count something
when it is the flag); test-{jit,compile}-own-fallback-defaultlib run
defaultlib/own_fallback_default_lib.ts with --own-fallback=count: a node given two owners by
`link` is counted, read through the library's array helpers (map, find, some, indexOf,
filter of the mapped values) with its text kept in a Map and a Set, and prints what node
prints. (Own's Map and Set hold values, strings, any and Shared<T>, and `filter` of objects
is refused by design, so the counted object itself is not put in them.) Skipped when no own
default library has been built, like the facts test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: a kept parameter is released where an exception leaves through the function's own finally

A parameter the function keeps on some paths is released at its exits on the others: the
returns and the throws. The end of a cleanup the exception leaves the function from - its own
`finally`, an EndCleanup with no landing pad after it - was not one, and the parameter
leaked there (final-review M-1: probe s1 +9.9 MB per 400 runs under plain own, r5 the same
with --own-fallback=count for a counted kept parameter; both flat now). A parameter kept
before something throws past it (`h.node = n; mayThrow()`) stays the holder's (guard-page
heap: no fault). Tests: own_kept_param_finally_unwind (gc/rc/own) and
own_fallback_kept_param_finally (fallback RUN).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Deterministic IR: landing pad ids per function, stable fields sorted, a weak field named on its view

Compiling the same file twice could give different IR (final-review: own and rc, 21 corpus
files out of 1896 over three rounds of 8-way parallel compiles):
- `__eh_pad_id`: TSContext::nextCatchPadId counted on across the functions a thread's copy
  of the affine lowering pass had lowered before, so a function's pads were numbered by
  which thread took it. It starts at 0 for each function (beginRun); the ids only name pads
  within a function (Win32ExceptionPass).
- `ts.own_stable_fields`: built from a map keyed by type pointer; sorted by class name and
  field position.
- a @weak field's `weakField` name on a reread or a write: taken from the checked read
  found by walking the first operand of what made the view's value, which did not always
  reach it. weakFieldRead now names the field on the view (`__weak_field_view` = the name),
  and a reread or a write takes it from there.
After: 0 of 1896 files differ across three rounds (own and rc). IR changes: pad id numbers
(per function now), the order of ts.own_stable_fields (own_readonly_stable), the weak field
names on rereads (own_weak_field_logical).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rc/own: a concise arrow gives back what its destructured parameter owns before it returns

Item 1 follow-up. A concise arrow body (`({ a, b }) => a + b`) returns without a scope exit,
and only a parameter's rc default-value slot was given back there: the names a destructured
parameter binds, which own what they read under rc since 119bd34, were never released (the
ownership verifier refused 00untyped_binding_params and 01map; rc +7.2 MB per 400 runs), and
neither was own's slot for a destructured parameter's default (#1022, +5.4 MB). Both are
given back before the return now. Test 00param_pattern_concise_arrow (every model).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: a borrowed `N | null | undefined` narrowed by a loose `!= null` is a view again

Review I1 of 2495d6f. The loose narrowing cast an optional to its type without null and
undefined through a ts.SafeCast over the optional, which own took for a store of the borrow:
own refused `const c = vs[0]; if (c != null) c.x`, the for-of form, a field
`if (h.v != null) h.v.x` and the `&&`/`||`/`?:`/else-if forms, which main accepts. The side
that is not null nor undefined now reads an optional as `c !== undefined` does (its value,
a ts.Value - a null left in it reads as null). The equal side still keeps its type, so
item 5's results stay node's (00narrow_loose_nullish; the reviewer's L01-L14, M01-M11 under
gc, rc and own). Test 00narrow_loose_nullish_borrowed (every model).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: only a pattern default's merge is a borrow of its own; other merges as before

Review I2 of 9dddc3d. letBorrows returned mergeOfPatternDefault for every block-argument root,
shadowing what it decided before for other merges - the bounds test of an array element
(`const [a] = xs; let z = a; z = new N(6)`, refused: "'z' borrows 'xs[]' and cannot be
assigned"; main accepts it and prints 6). A merge that is a pattern default's is a borrow;
any other falls through to the previous checks. own_pattern_default_let_assigned covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* OwnedReturnConsumptionPass: say that writesPlace is deliberately coarse

Review m1 of 119bd34: any store into a field or an element counts, a constructor's too, so
nearly every function that makes an object "may write a place"; readsCapturedPlace is what
keeps the holds few. A comment only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: a @value record narrowed by a loose != null is also narrowed off its null niche

Follow-up to 6d6297a. Reading an optional's value left `Hit | null` for a @value record
whose null is a niche of its own (`Hit | null` is optional<null | Hit>): own_value_record and
own_value_loop (`if (h != null) h.thing.id()`) were then refused ("a value that borrows
'this' cannot be stored, returned or captured"; the full ctest caught it). For a @value
member the value just read is narrowed again off null, as `c !== null` narrows a union. A
class's null stays in it (a second narrowing of a field read, `h.v`, was taken for a store
of the borrow). ctest value|narrow|nullish|optional 742/742; reviewer L01-L14, M01-M11 as node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=rc: hold an argument whose place another name may reach and the call may write

Review I3 of 119bd34, the user's "narrow it first". The caller held an argument read out of
a place only when the place's object was a captured local's (or a const captured by value):
rc still read freed memory when the object was reachable through another name the callee
writes - stored in a global (`G = h; gw2(h.o)`), put in another argument's container
(`aw(bx, arr[0])`, `bx = [arr]`), a second const a closure pops, a captured array holding
it (main too). readsAliasedPlace holds it when both:
- some object on the way to the place may be aliased: it is not one made here that never
  escapes - a parameter's object, a captured local's, one read out of somewhere else, one
  stored, captured, passed on or copied to another local;
- the call may write a place of a kind on that way: writtenKinds per function, propagated
  through callees (a call through a value: what the module writes), by a field's name, an
  element, a captured local's cell. Writes that only make an object - a constructor's into
  `this`, into an object or box the function just made, into a local record - do not count.
Corpus impact (rc only; own, gc and none unchanged): 9 files, 22 retains (00any_keys_write 11)
- the unnarrowed rule was 40 files and 77, 7 of them in raytrace's per-light callback; now
raytrace and own_raytrace gain none (rc release: main 66-83 ms, branch 66-74 ms). Test
00rc_argument_place_aliased (the reviewer's X01-X21, gc/rc/none) and its IR test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=rc: `a.length = n` and `delete` count as writes for the argument hold

Re-review I1 of a2c6ac0: ts.SetLengthOf (`a.length = n`) gives back the elements it drops
but was not an element write in writtenKinds, so `f4(arr[0], al[0])` with `al = [arr]` and
`f4` doing `a.length = 0` still read freed memory (rc 3751995, gc 4498500). It is "E" now,
beside pop/shift/splice; ts.Delete frees what it deletes with every place in it and is "*".
Test 00rc_argument_place_set_length (gc/rc/none; faults under the guard-page heap with the
previous binary) and its IR test; the repro is in 00rc_argument_place_aliased too. m1: a
comment that a bodiless callee counts as writing nothing because the library's mutating array
methods are generic, their bodies analysed here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* -mm=own: an empty literal given to a keeping callee is moved, not also given back

Fixes the DefaultLib worker_objects failure on wasm32/wasm64 (PR #1027 CI): 3fc0e02 marked
the empty constant array cast to an array (`[]`) given to a call an owned result, which the
inference gives back after the call - also after a callee that keeps it: `new Order(-1, [])`
stores it in a field, so the object freed it again (a free of a freed block, under the
guard-page heap natively too). The cast is now replaced by the new empty array it is
(ts.NewEmptyArray), which the inference moves into a keeping callee and gives back after one
that does not (`ln([])` stays leak-free). Test own_empty_literal_kept_arg (gc/rc/own; faults
under the guard-page heap with the previous binary).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant