From b5e4cf3c55161b41dcc237084dd8419a26788770 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 06:37:16 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m2/ts-index-cleanup.md Quest-Claim: 10add91ec8013576 From d96c0b971bae3ed2e05d681153e89669d9077f87 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 07:01:04 -0700 Subject: [PATCH 2/2] fix(ts): replace an indexed element whose drop may panic A cleanup's index temporaries are declared before the `try`, typed where they are spilled; a store through a reference makes a cleanup visible; and a borrow through one reference holds only that reference. Co-Authored-By: Claude Opus 5.5 --- quest/m2/README.md | 1 - quest/m2/ts-index-cleanup.md | 28 -- ts/fixtures/task/expected/drops.Ring.ts | 51 +++ ts/fixtures/task/expected/drops.Slots.ts | 50 +++ ts/fixtures/task/expected/drops.ts | 533 ++++++++++++++++------- ts/fixtures/task/expected/futures.ts | 87 ++-- ts/fixtures/task/expected/kio.Park.ts | 31 +- ts/fixtures/task/expected/model.ts | 137 +++--- ts/fixtures/task/src/drops.rs | 68 ++- ts/src/lower/mir/call.rs | 7 +- ts/src/lower/mir/mod.rs | 91 +++- ts/src/lower/mir/place.rs | 57 ++- ts/src/lower/mir/unwind.rs | 40 +- 13 files changed, 843 insertions(+), 338 deletions(-) delete mode 100644 quest/m2/ts-index-cleanup.md create mode 100644 ts/fixtures/task/expected/drops.Ring.ts create mode 100644 ts/fixtures/task/expected/drops.Slots.ts diff --git a/quest/m2/README.md b/quest/m2/README.md index 672017ab4..02702f43e 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -27,7 +27,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export/README ## Required - [Byte-slice locals that crash the translator](/quest/m2/ts-scalar-ice.md) - `take_apart` never reaches the arm `find_scalars` promised it wouldn't -- [Replacing an indexed element whose drop may panic](/quest/m2/ts-index-cleanup.md) - `v[i] = x` type-checks and unwinds as Rust does when the old element's drop may panic - [Byte slices without objects](/quest/m2/ts-byte-views/README.md) - reading through a translated cursor allocates no object per read - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values diff --git a/quest/m2/ts-index-cleanup.md b/quest/m2/ts-index-cleanup.md deleted file mode 100644 index 3b62fc2a8..000000000 --- a/quest/m2/ts-index-cleanup.md +++ /dev/null @@ -1,28 +0,0 @@ -# [S] Replacing an indexed element whose drop may panic - -## Goal - -rust2-ts translates `v[i] = x`, where dropping the old element may panic, into -TypeScript that `tsc` accepts and that drops and replaces as native Rust does on every -path, a panic in the old element's `Drop` included, proven by differential tests. - -## Plan - -Found while testing [trait objects](/quest/m3/ts-dyn.md). The drop-and-replace through -`IndexMut` lowers the borrowed element as `v[at2]`, where `at2` is a `const` the body -declares inside the `try`. The unwind cleanup in the `catch` replays the assignment as -`v[at2] = x`, out of `at2`'s scope, so `tsc` rejects the output. A `Vec` of a type with -a `Drop` impl reproduces it, no trait object needed: - -```rust -let mut v = vec![Bomb::new()]; -v[0] = Bomb::new(); -``` - -kio's `self.children[index] = Some(Occupant { .. })` and `waiters[i] = Waiter::noop()` -have that shape. - -- Fix it where the cleanup reads what the body spilled, so every temporary an aliased - place names is in scope in the `catch`, not by special-casing indexing. - -Public API: none. diff --git a/ts/fixtures/task/expected/drops.Ring.ts b/ts/fixtures/task/expected/drops.Ring.ts new file mode 100644 index 000000000..dc319d7f3 --- /dev/null +++ b/ts/fixtures/task/expected/drops.Ring.ts @@ -0,0 +1,51 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { lend } from "./drops.ts"; +import type * as Bomb from "./drops.Bomb.ts"; + +/** Slots in an array, replaced through a reference to one. */ +export class Ring { + slots: Array; + + constructor(fields: { slots: Array }) { + this.slots = fields.slots; + } + + [Symbol.dispose](): void { + rt.dropAll(this.slots); + } +} + +export function lent(self: Ring, index: rt.usize, bomb: Bomb.Bomb): void { + let _7!: Bomb.Bomb | undefined; + let _9!: boolean; + let unwind: number = 0; + try { + unwind = 8; + _9 = false; + _9 = true; + if (!(index < 2)) { + rt.panic("index out of bounds: the len is " + 2 + " but the index is " + index); + } + lend(rt.place(() => self.slots[index], (value) => self.slots[index] = value)); + unwind = 5; + _9 = false; + _7 = bomb; + rt.drop(self.slots[index]); + self.slots[index] = _7; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 5) { + self.slots[index] = _7; + } + if (_9) { + rt.drop(bomb); + } + throw e; + } +} + +//# sourceMappingURL=drops.Ring.ts.map diff --git a/ts/fixtures/task/expected/drops.Slots.ts b/ts/fixtures/task/expected/drops.Slots.ts new file mode 100644 index 000000000..d390fae8f --- /dev/null +++ b/ts/fixtures/task/expected/drops.Slots.ts @@ -0,0 +1,50 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Bomb from "./drops.Bomb.ts"; + +/** Slots that may hold a value, replaced in place. */ +export class Slots { + _0: Array; + + constructor(_0: Array) { + this._0 = _0; + } + + [Symbol.dispose](): void { + rt.dropAll(this._0); + } +} + +export function put(self: Slots, index: rt.usize, bomb: Bomb.Bomb): void { + let at!: number; + let _4!: Bomb.Bomb | undefined; + let _7!: boolean; + let unwind: number = 0; + try { + unwind = 7; + _7 = false; + _7 = true; + _4 = bomb; + at = rt.idx(self._0, index); + unwind = 4; + rt.drop(self._0[at]); + _7 = false; + self._0[at] = _4; + _7 = false; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 4) { + _7 = false; + self._0[at] = _4; + } + if (_7) { + rt.drop(_4); + } + throw e; + } +} + +//# sourceMappingURL=drops.Slots.ts.map diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index a9a6a9ee0..cde9793ea 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -14,7 +14,9 @@ import * as Held from "./drops.Held.ts"; import * as Key from "./drops.Key.ts"; import * as Named from "./drops.Named.ts"; import * as Pair from "./drops.Pair.ts"; +import * as Ring from "./drops.Ring.ts"; import * as Shell from "./drops.Shell.ts"; +import * as Slots from "./drops.Slots.ts"; import type * as Text from "./drops.Text.ts"; import * as Wrap from "./drops.Wrap.ts"; import { recvFuture } from "./kio.ts"; @@ -2272,11 +2274,51 @@ export function arcs(log: Log.Log, id: rt.u32, at: rt.u8): void { } } +/** Each slot from `from` on, replaced through a reference to it. */ +export function refill$blown_closure3(slots: Array, from: rt.usize, bomb: (a0: rt.u32) => Bomb.Bomb): void { + let _10!: rt.usize; + let _15!: Bomb.Bomb | undefined; + let unwind: number = 0; + try { + let i: rt.usize = from; + while (i < slots.length) { + _10 = i; + rt.idx(slots, _10); + lend(rt.place(() => slots[_10], (value) => slots[_10] = value)); + const _16: Bomb.Bomb = bomb(i as rt.u32); + unwind = 8; + _15 = _16; + rt.drop(slots[_10]); + unwind = 0; + slots[_10] = _15; + i = rt.usizeAdd(i, 1); + } + } catch (e) { + if (unwind === 0) { + throw e; + } + slots[_10] = _15; + throw e; + } +} + +/** Logs the value a reference to a slot reads. */ +export function lend(slot: rt.Place): void { + if (slot.v !== undefined) { + const arg = slot.v.id; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; + const _6: string = rt.fmtFormat(["b", args2[0], " lent"]); + Log.note(slot.v.log, _6); + } +} + /** * What drops after a value's `Drop` panics, scenario `at`'s alone: the rest of the * value, and the rest of what holds it, as std's glue and collections go on. */ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { + let at2!: number; + let at3!: number; let v!: Bomb.Bomb[]; let _29!: Log.Log; let _30!: Bomb.Bomb; @@ -2299,24 +2341,38 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { let _137!: rt.u32; let map3!: rt.HashMap; let _157!: Key.Key; - let _170!: boolean; - let _171!: boolean; - let _172!: boolean; - let _173!: boolean; - let _174!: boolean; - let _175!: boolean; - let _176!: boolean; - let _177!: boolean; + let v3!: Bomb.Bomb[]; + let v4!: Bomb.Bomb[]; + let _178!: Bomb.Bomb; + let _183!: Bomb.Bomb; + let slots!: Slots.Slots; + let v5!: Array; + let ring!: Ring.Ring; + let _223!: Bomb.Bomb | undefined; + let slots2!: Array; + let v6!: Array; + let _261!: boolean; + let _262!: boolean; + let _263!: boolean; + let _264!: boolean; + let _265!: boolean; + let _266!: boolean; + let _267!: boolean; + let _268!: boolean; + let _269!: boolean; + let _270!: boolean; let unwind: number = 0; try { - _177 = false; - _176 = false; - _175 = false; - _174 = false; - _173 = false; - _172 = false; - _171 = false; - _170 = false; + _270 = false; + _269 = false; + _268 = false; + _267 = false; + _266 = false; + _265 = false; + _264 = false; + _263 = false; + _262 = false; + _261 = false; const bomb: (a0: rt.u32, a1: boolean) => Bomb.Bomb = (n2: rt.u32, blows: boolean): Bomb.Bomb => { return new Bomb.Bomb({ id: rt.u32Add(id, n2), log: Log.clone$Clone(log), blows }); }; @@ -2328,7 +2384,7 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { }; if (at === 0) { v = []; - unwind = 94; + unwind = 143; const _15: Bomb.Bomb = bomb(1, false); v.push(_15); const _20: Bomb.Bomb = bomb(2, true); @@ -2339,110 +2395,110 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.dropAll(v); } else if (at === 1) { _29 = Log.clone$Clone(log); - unwind = 93; + unwind = 142; _30 = bomb(1, false); - unwind = 92; + unwind = 141; const _33: Guard.Guard = guard(2); unwind = 0; rt.drop(new Shell.Shell({ log: _29, blows: true, first: _30, second: _33 })); } else if (at === 2) { _37 = Log.clone$Clone(log); - unwind = 91; + unwind = 140; _38 = bomb(1, true); - unwind = 90; + unwind = 139; const _41: Guard.Guard = guard(2); unwind = 0; rt.drop(new Shell.Shell({ log: _37, blows: false, first: _38, second: _41 })); } else if (at === 3) { _45 = guard(1); - unwind = 89; + unwind = 138; v2 = []; - unwind = 88; + unwind = 137; _54 = bomb(2, true); - unwind = 87; + unwind = 136; const _57: Guard.Guard = guard(3); - unwind = 88; + unwind = 137; v2.push([_54, _57] as [Bomb.Bomb, Guard.Guard]); _63 = bomb(4, false); - unwind = 86; + unwind = 135; const _66: Guard.Guard = guard(5); - unwind = 88; + unwind = 137; v2.push([_63, _66] as [Bomb.Bomb, Guard.Guard]); - unwind = 85; + unwind = 134; _48 = new Entries.Entries(v2); const _70: Guard.Guard = guard(6); unwind = 0; drop$Guard_Entries_Bomb_Guard_Held([_45, _48, { tag: "One", _0: _70 } as Held.Held] as [Guard.Guard, Entries.Entries, Held.Held]); } else if (at === 4) { map = rt.btreeNew(Key.cmp$Ord) as rt.BTreeMap; - unwind = 84; + unwind = 133; _76 = key(1, "Sound" as Fault.Fault); - unwind = 111; - _177 = true; + unwind = 164; + _270 = true; const _80: Bomb.Bomb = bomb(1, false); - _177 = false; + _270 = false; const _74: Bomb.Bomb | undefined = rt.btreeInsert(map, _76, _80, rt.drop, rt.drop); - unwind = 84; - _177 = false; + unwind = 133; + _270 = false; rt.drop(_74); _85 = key(2, "Sound" as Fault.Fault); - unwind = 109; - _176 = true; + unwind = 162; + _269 = true; const _89: Bomb.Bomb = bomb(2, true); - _176 = false; + _269 = false; const _83: Bomb.Bomb | undefined = rt.btreeInsert(map, _85, _89, rt.drop, rt.drop); - unwind = 84; - _176 = false; + unwind = 133; + _269 = false; rt.drop(_83); _94 = key(3, "Sound" as Fault.Fault); - unwind = 107; - _175 = true; + unwind = 160; + _268 = true; const _98: Bomb.Bomb = bomb(3, false); - _175 = false; + _268 = false; const _92: Bomb.Bomb | undefined = rt.btreeInsert(map, _94, _98, rt.drop, rt.drop); - unwind = 84; - _175 = false; + unwind = 133; + _268 = false; rt.drop(_92); rt.btreeClear(map, rt.drop, rt.drop); unwind = 0; rt.btreeDrop(map, rt.drop, rt.drop); } else if (at === 5) { - _174 = true; + _267 = true; map2 = rt.btreeNew(Key.cmp$Ord) as rt.BTreeMap; - unwind = 105; + unwind = 158; _106 = key(1, "Sound" as Fault.Fault); - unwind = 103; - _173 = true; + unwind = 156; + _266 = true; const _110: Guard.Guard = guard(1); - _173 = false; + _266 = false; const _104: Guard.Guard | undefined = rt.btreeInsert(map2, _106, _110, rt.drop, rt.drop); - unwind = 105; - _173 = false; + unwind = 158; + _266 = false; rt.drop(_104); _115 = key(2, "Blows" as Fault.Fault); - unwind = 101; - _172 = true; + unwind = 154; + _265 = true; const _119: Guard.Guard = guard(2); - _172 = false; + _265 = false; const _113: Guard.Guard | undefined = rt.btreeInsert(map2, _115, _119, rt.drop, rt.drop); - unwind = 105; - _172 = false; + unwind = 158; + _265 = false; rt.drop(_113); _124 = key(3, "Sound" as Fault.Fault); - unwind = 99; - _171 = true; + unwind = 152; + _264 = true; const _128: Guard.Guard = guard(3); - _171 = false; + _264 = false; const _122: Guard.Guard | undefined = rt.btreeInsert(map2, _124, _128, rt.drop, rt.drop); - unwind = 105; - _171 = false; + unwind = 158; + _264 = false; rt.drop(_122); - _174 = false; + _267 = false; rt.btreeDrop(map2, rt.drop, rt.drop); - _174 = false; + _267 = false; } else if (at === 6) { queue = rt.dequeNew() as rt.VecDeque; - unwind = 83; + unwind = 132; let iterStart: rt.u32 = 1; const iterEnd: rt.u32 = 5; while ((_137 = iterStart++) < iterEnd) { @@ -2455,21 +2511,94 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.dequeTruncate(queue, 1, rt.drop); unwind = 0; rt.dequeDrop(queue, rt.drop); - } else { + } else if (at === 7) { map3 = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashMap; - unwind = 82; + unwind = 131; _157 = key(1, "Blows" as Fault.Fault); - unwind = 97; - _170 = true; + unwind = 150; + _263 = true; const _161: Guard.Guard = guard(1); - _170 = false; + _263 = false; const _155: Guard.Guard | undefined = rt.hashInsert(map3, _157, _161, rt.drop, rt.drop); - unwind = 82; - _170 = false; + unwind = 131; + _263 = false; rt.drop(_155); rt.hashClear(map3, rt.drop, rt.drop); unwind = 0; rt.hashDrop(map3, rt.drop, rt.drop); + } else if (at === 8) { + v4 = []; + unwind = 130; + const _170: Bomb.Bomb = bomb(1, false); + v4.push(_170); + const _175: Bomb.Bomb = bomb(2, false); + v4.push(_175); + unwind = 129; + v3 = v4; + _178 = bomb(3, false); + unwind = 148; + _262 = true; + at2 = rt.idx(v3, 0); + unwind = 88; + rt.drop(v3[at2]); + unwind = 129; + _262 = false; + v3[at2] = _178; + _262 = false; + _183 = bomb(4, false); + unwind = 146; + _261 = true; + at3 = rt.idx(v3, 2); + unwind = 92; + rt.drop(v3[at3]); + unwind = 0; + _261 = false; + v3[at3] = _183; + _261 = false; + rt.dropAll(v3); + } else if (at === 9) { + v5 = []; + unwind = 128; + v5.push(undefined as Bomb.Bomb | undefined); + const _196: Bomb.Bomb | undefined = bomb(1, false); + v5.push(_196); + const _202: Bomb.Bomb | undefined = bomb(2, true); + v5.push(_202); + unwind = 127; + slots = new Slots.Slots(v5); + const _208: Bomb.Bomb = bomb(3, false); + Slots.put(slots, 0, _208); + const _213: Bomb.Bomb = bomb(4, false); + Slots.put(slots, 1, _213); + const _218: Bomb.Bomb = bomb(5, false); + Slots.put(slots, 2, _218); + unwind = 0; + rt.drop(slots); + } else { + unwind = 126; + _223 = undefined; + const _225: Bomb.Bomb = bomb(1, false); + unwind = 125; + ring = new Ring.Ring({ slots: [_223, _225] }); + const _230: Bomb.Bomb = bomb(2, false); + Ring.lent(ring, 0, _230); + const _235: Bomb.Bomb = bomb(3, false); + Ring.lent(ring, 1, _235); + v6 = []; + unwind = 124; + const _242: Bomb.Bomb | undefined = bomb(4, false); + v6.push(_242); + const _248: Bomb.Bomb | undefined = bomb(5, true); + v6.push(_248); + unwind = 123; + slots2 = v6; + refill$blown_closure3(slots2, 0, (n5: rt.u32): Bomb.Bomb => { + return bomb(rt.u32Add(n5, 6), false); + }); + unwind = 125; + rt.dropAll(slots2); + unwind = 0; + rt.drop(ring); } unwind = 0; Log.note(log, rt.fmtFormat(["unreached"])); @@ -2481,116 +2610,182 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { b7: { b8: { b9: { - if (unwind === 0) { - throw e; - } - if (unwind === 82) { - break b4; - } - if (unwind === 83) { - rt.dequeDrop(queue, rt.drop); - break b3; - } - if (unwind === 84) { - break b5; - } - if (unwind === 85) { - rt.drop(_48); - break b6; - } - if (unwind === 86) { - rt.drop(_63); - break b7; - } - if (unwind === 87) { - rt.drop(_54); - break b7; - } - if (unwind === 88) { - break b7; - } - if (unwind === 89) { - break b6; - } - if (unwind === 90) { - rt.drop(_38); - break b8; - } - if (unwind === 91) { - break b8; - } - if (unwind === 92) { - rt.drop(_30); - break b9; - } - if (unwind === 93) { - break b9; - } - if (unwind === 94) { - rt.dropAll(v); - break b3; - } - if (unwind === 97) { - if (!_170) { - break b4; - } - rt.drop(_157); - break b4; - } - if (unwind === 99) { - if (_171) { - rt.drop(_124); - } - } else if (unwind === 101) { - if (_172) { - rt.drop(_115); - } - } else if (unwind === 103) { - if (_173) { - rt.drop(_106); - } - } else if (unwind !== 105) { - if (unwind === 107) { - if (!_175) { - break b5; - } - rt.drop(_94); - break b5; - } - if (unwind === 109) { - if (!_176) { - break b5; + b10: { + b11: { + b12: { + b13: { + if (unwind === 0) { + throw e; + } + if (unwind === 88) { + _262 = false; + v3[at2] = _178; + break b5; + } + if (unwind === 92) { + _261 = false; + v3[at3] = _183; + break b6; + } + if (unwind === 123) { + rt.dropAll(slots2); + break b7; + } + if (unwind === 124) { + rt.dropAll(v6); + break b7; + } + if (unwind === 125) { + break b7; + } + if (unwind === 126) { + rt.drop(_223); + break b3; + } + if (unwind === 127) { + rt.drop(slots); + break b3; + } + if (unwind === 128) { + rt.dropAll(v5); + break b3; + } + if (unwind === 129) { + break b4; + } + if (unwind === 130) { + rt.dropAll(v4); + break b3; + } + if (unwind === 131) { + break b8; + } + if (unwind === 132) { + rt.dequeDrop(queue, rt.drop); + break b3; + } + if (unwind === 133) { + break b9; + } + if (unwind === 134) { + rt.drop(_48); + break b10; + } + if (unwind === 135) { + rt.drop(_63); + break b11; + } + if (unwind === 136) { + rt.drop(_54); + break b11; + } + if (unwind === 137) { + break b11; + } + if (unwind === 138) { + break b10; + } + if (unwind === 139) { + rt.drop(_38); + break b12; + } + if (unwind === 140) { + break b12; + } + if (unwind === 141) { + rt.drop(_30); + break b13; + } + if (unwind === 142) { + break b13; + } + if (unwind === 143) { + rt.dropAll(v); + break b3; + } + if (unwind === 146) { + break b6; + } + if (unwind === 148) { + break b5; + } + if (unwind === 150) { + if (!_263) { + break b8; + } + rt.drop(_157); + break b8; + } + if (unwind === 152) { + if (_264) { + rt.drop(_124); + } + } else if (unwind === 154) { + if (_265) { + rt.drop(_115); + } + } else if (unwind === 156) { + if (_266) { + rt.drop(_106); + } + } else if (unwind !== 158) { + if (unwind === 160) { + if (!_268) { + break b9; + } + rt.drop(_94); + break b9; + } + if (unwind === 162) { + if (!_269) { + break b9; + } + rt.drop(_85); + break b9; + } + if (!_270) { + break b9; + } + rt.drop(_76); + break b9; + } + if (!_267) { + break b3; + } + rt.btreeDrop(map2, rt.drop, rt.drop); + break b3; + } + rt.drop(_29); + break b3; } - rt.drop(_85); - break b5; + rt.drop(_37); + break b3; } - if (!_177) { - break b5; - } - rt.drop(_76); - break b5; - } - if (!_174) { - break b3; + rt.dropAll(v2, drop$Bomb_Guard); } - rt.btreeDrop(map2, rt.drop, rt.drop); + rt.drop(_45); break b3; } - rt.drop(_29); + rt.btreeDrop(map, rt.drop, rt.drop); break b3; } - rt.drop(_37); + rt.hashDrop(map3, rt.drop, rt.drop); break b3; } - rt.dropAll(v2, drop$Bomb_Guard); + rt.drop(ring); + break b3; + } + if (!_261) { + break b4; } - rt.drop(_45); - break b3; + rt.drop(_183); + break b4; + } + if (_262) { + rt.drop(_178); } - rt.btreeDrop(map, rt.drop, rt.drop); - break b3; } - rt.hashDrop(map3, rt.drop, rt.drop); + rt.dropAll(v3); } throw e; } diff --git a/ts/fixtures/task/expected/futures.ts b/ts/fixtures/task/expected/futures.ts index 0b8fc4832..cdfd640f6 100644 --- a/ts/fixtures/task/expected/futures.ts +++ b/ts/fixtures/task/expected/futures.ts @@ -163,6 +163,7 @@ export class helpersFuture { let captured5 = next; const captured6 = this.#total; this.#awaitee = new rt.PollFn(rt.closure((cx: rt.Context): rt.Poll> => { + let _11!: rt.Waker | undefined; let _152!: Log.Log; let _81!: boolean; let unwind2: number = 0; @@ -178,12 +179,13 @@ export class helpersFuture { const _18: rt.u32 = rt.u32Add(Guard.id(captured4), 100); _81 = false; const _122: rt.Waker = relayed(_132, _152, _18); - unwind2 = 0; + unwind2 = 15; _81 = false; - const _11: rt.Waker | undefined = _122; + _11 = _122; rt.drop(captured3); captured3 = _11; } + unwind2 = 0; const relay2: rt.Waker = rt.optionUnwrap(captured3); const polled: rt.Poll = captured5.poll(relay2); const _392: boolean = isPending$Poll_u64(waiting); @@ -213,7 +215,9 @@ export class helpersFuture { if (unwind2 === 0) { throw e2; } - if (_81) { + if (unwind2 === 15) { + captured3 = _11; + } else if (_81) { rt.drop(_152); } throw e2; @@ -469,7 +473,7 @@ export class boxedFuture { unwind = 54; rt.drop(this.#guard); if (this.#saved$2) { - unwind = 0; + unwind = 55; rt.drop(this.#rx); } this.#saved$2 = false; @@ -480,48 +484,53 @@ export class boxedFuture { b8: { b9: { b10: { - if (unwind === 0) { - throw e; - } - if (unwind === 34) { - rt.drop(this.#pinned); - } else if (unwind !== 37) { - if (unwind === 44) { - break b10; - } - if (unwind === 48) { - break b9; - } - if (unwind === 50) { - break b8; - } - if (unwind === 51) { - break b7; + b11: { + if (unwind === 0) { + throw e; } - if (unwind === 54) { - break b6; + if (unwind === 34) { + rt.drop(this.#pinned); + } else if (unwind !== 37) { + if (unwind === 44) { + break b11; + } + if (unwind === 48) { + break b10; + } + if (unwind === 50) { + break b9; + } + if (unwind === 51) { + break b8; + } + if (unwind === 54) { + break b7; + } + if (unwind === 55) { + break b6; + } + rt.drop(this.#guard); + break b5; } - rt.drop(this.#guard); - break b5; + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + this.#saved$7 = false; + } + if (this.#saved) { + rt.drop(this.#lend); } - this.#saved$3 = false; - this.#saved$4 = false; - this.#saved$5 = false; - this.#saved$6 = false; - this.#saved$7 = false; - } - if (this.#saved) { - rt.drop(this.#lend); } + this.#saved = false; + rt.drop(this.#log); } - this.#saved = false; - rt.drop(this.#log); } + rt.drop(this.#guard); + } + if (this.#saved$2) { + rt.drop(this.#rx); } - rt.drop(this.#guard); - } - if (this.#saved$2) { - rt.drop(this.#rx); } this.#saved$2 = false; } diff --git a/ts/fixtures/task/expected/kio.Park.ts b/ts/fixtures/task/expected/kio.Park.ts index 30d2f0410..9cd651cc7 100644 --- a/ts/fixtures/task/expected/kio.Park.ts +++ b/ts/fixtures/task/expected/kio.Park.ts @@ -26,17 +26,30 @@ export class Park { */ export function hold(self: Park, cx: rt.Context): Waiter.Waiter { let reuse!: boolean; - if (self._0 === undefined) { - reuse = false; - } else { - reuse = cx.willWake(self._0.waker); - } - if (!reuse) { - const _10: Waiter.Waiter | undefined = Waiter.new(cx.clone()); - rt.drop(self._0); + let _10!: Waiter.Waiter | undefined; + let unwind: number = 0; + try { + if (self._0 === undefined) { + reuse = false; + } else { + reuse = cx.willWake(self._0.waker); + } + if (!reuse) { + const _11: Waiter.Waiter = Waiter.new(cx.clone()); + unwind = 12; + _10 = _11; + rt.drop(self._0); + self._0 = _10; + } + unwind = 0; + return rt.optionUnwrap(self._0); + } catch (e) { + if (unwind === 0) { + throw e; + } self._0 = _10; + throw e; } - return rt.optionUnwrap(self._0); } //# sourceMappingURL=kio.Park.ts.map diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 96befdbff..9fac06669 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -302,7 +302,7 @@ export class blocksFuture { } this.#saved$3 = false; if (this.#saved$6) { - unwind = 0; + unwind = 77; rt.drop(this.#rx); } this.#saved$6 = false; @@ -321,91 +321,96 @@ export class blocksFuture { b21: { b22: { b23: { - if (unwind === 0) { - throw e; - } - if (unwind === 45) { - break b22; - } - if (unwind === 48) { - break b22; - } - if (unwind === 51) { - break b21; - } - if (unwind === 53) { - break b20; - } - if (unwind === 55) { - break b19; - } - if (unwind === 58) { - break b18; - } - if (unwind === 61) { - break b17; - } - if (unwind === 65) { - rt.drop(this.#saved); - break b23; - } - if (unwind === 66) { - break b23; - } - if (unwind === 69) { - break b15; - } - if (unwind === 70) { - rt.drop(this.#saved); - } else if (unwind !== 71) { - if (unwind === 74) { - break b13; + b24: { + if (unwind === 0) { + throw e; + } + if (unwind === 45) { + break b23; + } + if (unwind === 48) { + break b23; + } + if (unwind === 51) { + break b22; } - if (unwind === 75) { - break b12; + if (unwind === 53) { + break b21; } - if (unwind === 76) { - break b11; + if (unwind === 55) { + break b20; } - rt.drop(this.#guard); - break b10; + if (unwind === 58) { + break b19; + } + if (unwind === 61) { + break b18; + } + if (unwind === 65) { + rt.drop(this.#saved); + break b24; + } + if (unwind === 66) { + break b24; + } + if (unwind === 69) { + break b16; + } + if (unwind === 70) { + rt.drop(this.#saved); + } else if (unwind !== 71) { + if (unwind === 74) { + break b14; + } + if (unwind === 75) { + break b13; + } + if (unwind === 76) { + break b12; + } + if (unwind === 77) { + break b11; + } + rt.drop(this.#guard); + break b10; + } + this.#saved$9 = false; + break b15; } - this.#saved$9 = false; - break b14; + this.#saved$8 = false; + break b17; } - this.#saved$8 = false; - break b16; + rt.drop(this.#saved); } - rt.drop(this.#saved); + rt.drop(this.#nested); } - rt.drop(this.#nested); } } } + this.#saved$7 = false; } - this.#saved$7 = false; + rt.dropAll(this.#slots); } - rt.dropAll(this.#slots); + } + if (this.#saved$4) { + rt.drop(this.#second); } } - if (this.#saved$4) { - rt.drop(this.#second); + this.#saved$4 = false; + if (this.#saved$5) { + rt.drop(this.#first); } } - this.#saved$4 = false; - if (this.#saved$5) { - rt.drop(this.#first); + this.#saved$5 = false; + if (this.#saved$3) { + rt.drop(this.#guard); } } - this.#saved$5 = false; - if (this.#saved$3) { - rt.drop(this.#guard); + this.#saved$3 = false; + if (this.#saved$6) { + rt.drop(this.#rx); } } - this.#saved$3 = false; - if (this.#saved$6) { - rt.drop(this.#rx); - } this.#saved$6 = false; } throw e; diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index 4f5457c62..a4e37e85c 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -634,6 +634,46 @@ impl Drop for Shell { } } +/// Slots that may hold a value, replaced in place. +struct Slots(Vec>); + +impl Slots { + fn put(&mut self, index: usize, bomb: Bomb) { + self.0[index] = Some(bomb); + } +} + +/// Slots in an array, replaced through a reference to one. +struct Ring { + slots: [Option; 2], +} + +impl Ring { + fn lent(&mut self, index: usize, bomb: Bomb) { + let slot = &mut self.slots[index]; + lend(slot); + *slot = Some(bomb); + } +} + +/// Each slot from `from` on, replaced through a reference to it. +fn refill(slots: &mut [Option], from: usize, mut bomb: impl FnMut(u32) -> Bomb) { + let mut i = from; + while i < slots.len() { + let slot = &mut slots[i]; + lend(slot); + *slot = Some(bomb(i as u32)); + i += 1; + } +} + +/// Logs the value a reference to a slot reads. +fn lend(slot: &mut Option) { + if let Some(bomb) = slot { + bomb.log.note(format!("b{} lent", bomb.id)); + } +} + /// What drops after a value's `Drop` panics, scenario `at`'s alone: the rest of the /// value, and the rest of what holds it, as std's glue and collections go on. fn blown(log: &Log, id: u32, at: u8) { @@ -685,13 +725,39 @@ fn blown(log: &Log, id: u32, at: u8) { queue.push_front(bomb(0, false)); queue.truncate(1); } - _ => { + 7 => { // One entry, whose order std's hash table leaves no room to differ in, and // which leaves the map empty as unwinding drops it. let mut map = HashMap::new(); map.insert(key(1, Fault::Blows), guard(1)); map.clear(); } + 8 => { + // The old element drops before the new one takes its place; past the end, the + // index panics with nothing dropped but the new value. + let mut v = list![bomb(1, false), bomb(2, false)]; + v[0] = bomb(3, false); + v[2] = bomb(4, false); + } + 9 => { + // As kio's slab replaces an occupant through `&mut self`: as the old one panics, + // the new one still takes its place. + let mut slots = Slots(list![None, Some(bomb(1, false)), Some(bomb(2, true))]); + slots.put(0, bomb(3, false)); + slots.put(1, bomb(4, false)); + slots.put(2, bomb(5, false)); + } + _ => { + // The same through a reference to the slot, lent out first, and in a loop where + // the cleanup only stores the new value. + let mut ring = Ring { + slots: [None, Some(bomb(1, false))], + }; + ring.lent(0, bomb(2, false)); + ring.lent(1, bomb(3, false)); + let mut slots = list![Some(bomb(4, false)), Some(bomb(5, true))]; + refill(&mut slots, 0, |n| bomb(n + 6, false)); + } } log.note(format!("unreached")); } diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index d43537683..80928161a 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -12,7 +12,7 @@ use super::{Fx, Slot}; use crate::lower::fmt::{self, Piece}; use crate::lower::library::{self, Flow, Std}; use crate::lower::num::Int; -use crate::ts::{Expr, Stmt, StmtKind}; +use crate::ts::{Expr, Stmt, StmtKind, Type}; /// What a `&mut` borrows: its path, and the place a store through the reference writes, /// unless the reference is refused. @@ -857,10 +857,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Some(_) => { // A `Vec`'s element is its storage's, a byte vector's in `data`. let base = self.path(base, "slice", out); + let base_ty = self.b.t.ty(args[0].node.ty(&self.mir.local_decls, self.tcx), span); + self.spilled_as(&base, base_ty); let i = self.operand(&args[1].node, span, out); let i = self.path(i, "index", out); + let index = self.b.t.ty(index_ty, span); + self.spilled_as(&i, index); let checked = Expr::rt("idx", vec![base.clone(), i]); let checked = self.path(checked, "at", out); + self.spilled_as(&checked, Type::Builtin("number")); let place = match container.kind() { ty::Adt(..) if bytes => base.member("data").index(checked), // An array's bytes come through a reference, which is a slice of them. diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index dec05bf28..6f2a5dbc2 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -298,6 +298,9 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { /// Names nothing assigns again that `scalar` reads in place: variables of parts assigned /// once, and the slices it took apart. steady: FxHashSet, + /// The type of each temporary a place names, which a cleanup that reads the place + /// declares before the `try`. + spilled: FxHashMap, /// Those slices, with their types, which need declarations. scalar_binds: Vec<(String, Type)>, /// The tests and payload reads TypeScript may have narrowed stale. @@ -363,6 +366,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { widened: FxHashSet::default(), scalars: FxHashMap::default(), steady: FxHashSet::default(), + spilled: FxHashMap::default(), scalar_binds: Vec::new(), narrowing: decided::narrowing(tcx, mir), at: mir::START_BLOCK.start_location(), @@ -1441,8 +1445,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let mut labels = self.labels; let body = cfg::structure(&graph, self, &mut labels); self.labels = labels; - let body = self.catch(body); + let mut body = self.catch(body); let mut out = Vec::new(); + self.declare_caught(&mut body, &mut out); for local in self.mir.local_decls.indices() { // Parameters are declared by the signature. if self.is_arg(local) || !self.assigned[local] { @@ -2378,6 +2383,29 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Expr::ident(name) } + /// Note `ty` as the type of `held` if `path` made it a temporary, for a place that + /// names it. + pub(super) fn spilled_as(&mut self, held: &Expr, ty: Type) { + if let Expr::Ident(name) = held + && self.local_named(name).is_none() + { + self.spilled.insert(name.clone(), ty); + } + } + + /// Declare up front each temporary the `try` holds that the `catch` reads, which the + /// `try`'s block would otherwise scope. + fn declare_caught(&mut self, body: &mut [Stmt], out: &mut Vec) { + let mut held = Vec::new(); + assign_caught(body, &FxHashSet::default(), &mut held); + for name in held { + match self.spilled.get(&name) { + Some(ty) => out.push(StmtKind::Declare { name, ty: ty.clone() }.at(None)), + None => _ = self.err(self.span, format!("a cleanup that reads `{name}`, of no known type")), + } + } + } + /// Hold `slice`, an `rt.ByteSlice` to read more than once, in a path, as a tuple's part /// already is. pub(super) fn slice_path(&mut self, slice: Expr, out: &mut Vec) -> Expr { @@ -3792,6 +3820,67 @@ fn handler_reads(stmts: &[Stmt], out: &mut Vec) { } } +/// Turn each declaration in a `try` of a name its `catch` reads, or one around it does, +/// into an assignment to it, adding the name to `held`. +fn assign_caught(stmts: &mut [Stmt], reads: &FxHashSet, held: &mut Vec) { + for stmt in stmts { + match &mut stmt.kind { + StmtKind::Decl { + name, init: Some(init), .. + } if reads.contains(name.as_str()) => { + held.push(name.clone()); + let value = std::mem::replace(init, Expr::undefined()); + stmt.kind = StmtKind::Expr(Expr::ident(name.clone()).assign(value)); + } + StmtKind::If { then, els, .. } => { + assign_caught(then, reads, held); + assign_caught(els, reads, held); + } + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => { + assign_caught(body, reads, held) + } + StmtKind::Switch { cases, default, .. } => { + cases.iter_mut().for_each(|(_, body)| assign_caught(body, reads, held)); + assign_caught(default, reads, held); + } + StmtKind::Catch { body, handler, .. } => { + // What the handler declares itself, as inline drop glue does, it reads its own. + let mut caught = Vec::new(); + handler.iter().for_each(|s| scan_reads(s, &mut caught)); + let mut own = Vec::new(); + handler.iter().for_each(|s| declared(s, &mut own)); + let mut inner = reads.clone(); + inner.extend(caught.into_iter().filter(|n| !own.contains(n))); + assign_caught(body, &inner, held); + assign_caught(handler, reads, held); + } + _ => {} + } + } +} + +/// Every name `stmt` declares, in it and its blocks. +fn declared(stmt: &Stmt, out: &mut Vec) { + let mut each = |stmts: &[Stmt]| stmts.iter().for_each(|s| declared(s, out)); + match &stmt.kind { + StmtKind::Decl { name, .. } | StmtKind::Declare { name, .. } => out.push(name.clone()), + StmtKind::If { then, els, .. } => { + each(then); + each(els); + } + StmtKind::While { body, .. } | StmtKind::ForOf { body, .. } | StmtKind::Block { body, .. } => each(body), + StmtKind::Catch { body, handler, .. } => { + each(body); + each(handler); + } + StmtKind::Switch { cases, default, .. } => { + cases.iter().for_each(|(_, body)| each(body)); + each(default); + } + _ => {} + } +} + /// Move a `return x;` that follows an `if` or a labeled block into each way out of it, so /// each can return what it assigns `x` in place. fn sink_return(stmts: &mut Vec) { diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index a27ffa8ca..bb54277f0 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -759,24 +759,48 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ); } } - self.stable_path(target, super::own(place), span, out) + if super::own(place) { + return self.stable_path(target, true, span, out); + } + // A field or element of what one reference points at: only the reference can change + // while the borrow lives. + let through_one = match place.projection.as_slice() { + [ProjectionElem::Deref, inner @ .., last] => { + !matches!(last, ProjectionElem::Deref) + && inner + .iter() + .all(|e| matches!(e, ProjectionElem::Field(..) | ProjectionElem::Downcast(..))) + } + _ => false, + }; + let reference = match &self.slots[place.local] { + Slot::Var(name) if through_one && starts_from(&target, name) => name.clone(), + _ => return self.stable_path(target, false, span, out), + }; + let held = self.held_now(Expr::ident(&reference), out); + let ty = self.decl_ty(place.local); + self.spilled_as(&held, ty); + let target = from_held(target, &held); + self.stable_path(target, true, span, out) } /// `target`, a path, with the index it goes through held where it is now, and the - /// object too unless it is a local's `own` value, which can't change while borrowed. - pub(super) fn stable_path(&mut self, target: Expr, own: bool, span: Span, out: &mut Vec) -> Expr { + /// object too unless it is `fixed`, which can't change while borrowed. + pub(super) fn stable_path(&mut self, target: Expr, fixed: bool, span: Span, out: &mut Vec) -> Expr { self.materialize(&target, out); - let mut base = |fx: &mut Self, e: Expr| match own { + let mut base = |fx: &mut Self, e: Expr| match fixed { true => e, false => fx.held_now(e, out), }; match target { - Expr::Located(_, e) => self.stable_path(*e, own, span, out), + Expr::Located(_, e) => self.stable_path(*e, fixed, span, out), Expr::Ident(_) | Expr::This => target, Expr::Member(object, key) => Expr::Member(Box::new(base(self, *object)), key), Expr::Index(object, i) => { let object = base(self, *object); - Expr::Index(Box::new(object), Box::new(self.held_now(*i, out))) + let i = self.held_now(*i, out); + self.spilled_as(&i, crate::ts::Type::Builtin("number")); + Expr::Index(Box::new(object), Box::new(i)) } _ => self.err(span, "a mutable reference passed on or kept, to a value with no place"), } @@ -1244,3 +1268,24 @@ fn shared<'tcx>(fx: &Fx<'_, '_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { _ => false, } } + +/// Whether `path` reads through the variable `name` first. +fn starts_from(path: &Expr, name: &str) -> bool { + match path { + Expr::Located(_, e) | Expr::Member(e, _) | Expr::Index(e, _) | Expr::As(e, _) => starts_from(e, name), + Expr::Ident(n) => n == name, + _ => false, + } +} + +/// `path`, reading through `held` where it reads through the variable it starts from. +fn from_held(path: Expr, held: &Expr) -> Expr { + let from = |e: Box| Box::new(from_held(*e, held)); + match path { + Expr::Located(loc, e) => Expr::Located(loc, from(e)), + Expr::Member(e, key) => Expr::Member(from(e), key), + Expr::Index(e, i) => Expr::Index(from(e), i), + Expr::As(e, ty) => Expr::As(from(e), ty), + _ => held.clone(), + } +} diff --git a/ts/src/lower/mir/unwind.rs b/ts/src/lower/mir/unwind.rs index 4037c555a..c9bcd391c 100644 --- a/ts/src/lower/mir/unwind.rs +++ b/ts/src/lower/mir/unwind.rs @@ -31,7 +31,7 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { let mir = self.mir; let mut visible = FxHashSet::default(); for data in mir.basic_blocks.iter() { - if data.is_cleanup { + if data.is_cleanup || !self.can_panic(data.terminator()) { continue; } if let Some(UnwindAction::Cleanup(entry)) = data.terminator().unwind() @@ -63,11 +63,13 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { continue; } let data = &mir.basic_blocks[bb]; - if data - .statements - .iter() - .any(|s| matches!(s.kind, StatementKind::SetDiscriminant { .. })) - { + // What it stores through a reference outlives the frame, as a value dropped in + // place is replaced. + if data.statements.iter().any(|s| match &s.kind { + StatementKind::SetDiscriminant { .. } => true, + StatementKind::Assign(assign) => assign.0.is_indirect(), + _ => false, + }) { return true; } let term = data.terminator(); @@ -89,20 +91,12 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { /// Before a block whose terminator can panic: point the cleanup variable at what it /// unwinds to, if that changed. pub(super) fn set_unwind(&mut self, term: &mir::Terminator<'tcx>, out: &mut Vec) { + if !self.can_panic(term) { + return; + } let Some(unwind) = &self.unwind else { return; }; - let can_panic = match &term.kind { - TerminatorKind::Call { .. } | TerminatorKind::Assert { .. } => true, - TerminatorKind::Drop { place, .. } => { - let ty = place.ty(&self.mir.local_decls, self.tcx).ty; - self.b.t.drops(ty) - } - _ => false, - }; - if !can_panic { - return; - } let target = match term.unwind() { Some(UnwindAction::Cleanup(entry)) if unwind.visible.contains(entry) => entry.as_usize() + 1, _ => 0, @@ -119,6 +113,18 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { } } + /// Whether `term` can panic in JS: a drop only of a value that does something there. + fn can_panic(&mut self, term: &mir::Terminator<'tcx>) -> bool { + match &term.kind { + TerminatorKind::Call { .. } | TerminatorKind::Assert { .. } => true, + TerminatorKind::Drop { place, .. } => { + let ty = place.ty(&self.mir.local_decls, self.tcx).ty; + self.b.t.drops(ty) + } + _ => false, + } + } + /// Wrap `body` in the catch that runs the cleanup the variable names, then throws on. pub(super) fn catch(&mut self, body: Vec) -> Vec { let Some(unwind) = self.unwind.take() else {