From 51fd6159139c76baf634ae0a42ae4209145a2925 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:11:49 -0700 Subject: [PATCH 01/18] chore(quest): claim quest/m2/ts-drop.md Quest-Claim: 662797e1badcb803 From d8b28ddf7deb669bbb155a4422706a0573d4acb5 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:41:51 -0700 Subject: [PATCH 02/18] feat(ts): drop what std's iterators own A `for` over a `Vec`, `collect`, `extend`, `drain`, `into_keys`, and `into_values` of values that drop, and the adaptors that discard or hold them, drop each where std's do, a panic included. A field of an aggregate read again through a reference is re-read only if reading it runs nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/fmt.ts | 62 +- ts/fixtures/lang/expected/generics.ts | 14 +- ts/fixtures/lang/expected/ints.ts | 126 +- ts/fixtures/lang/expected/iters.ts | 6 +- ts/fixtures/lang/expected/keys.ts | 9 +- ts/fixtures/reject/census.md | 47 +- ts/fixtures/reject/expected.txt | 6 +- ts/fixtures/reject/src/lib.rs | 20 +- ts/fixtures/reject/ts.toml | 6 +- ts/fixtures/task/expected/drops.ts | 237 +-- ts/fixtures/task/expected/drops/iters.ts | 2232 ++++++++++++++++++++++ ts/fixtures/task/expected/lib.ts | 72 + ts/fixtures/task/src/drops.rs | 13 +- ts/fixtures/task/src/drops/iters.rs | 383 ++++ ts/runtime/rt/collections.ts | 403 ++-- ts/runtime/rt/iter.ts | 1422 +++++++++++--- ts/runtime/rt/task.ts | 16 +- ts/src/census.rs | 4 + ts/src/lower/collections.rs | 283 ++- ts/src/lower/drop.rs | 33 + ts/src/lower/iter.rs | 474 ++++- ts/src/lower/mir/call.rs | 8 +- ts/src/lower/mir/mod.rs | 6 +- ts/src/lower/mir/place.rs | 7 +- ts/src/lower/mir/step.rs | 19 +- ts/tests/task.ts | 2 +- 26 files changed, 5100 insertions(+), 810 deletions(-) create mode 100644 ts/fixtures/task/expected/drops/iters.ts create mode 100644 ts/fixtures/task/src/drops/iters.rs diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 5955d67a1..299c148b2 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -140,10 +140,10 @@ export function strings(data: Uint8Array, out: rt.ByteVec): void { if (!(_15 < 14)) { rt.panic("index out of bounds: the len is " + 14 + " but the index is " + _15); } - [["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"][_15]] as [string]; - const arg = ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"][_15]; + const args: [string] = [["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"][_15]]; + const arg = args[0]; const _31: rt.Fmt = (f: rt.Formatter) => rt.fmtPad(f, arg); - const arg2 = ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"][_15]; + const arg2 = args[0]; const args2: rt.Fmt[] = [_31, (f: rt.Formatter) => rt.fmtStr(arg2, f)]; put(out, rt.fmtFormat([args2[0], "|", rt.fmtSpec({ width: 8 }, args2[0]), "|", rt.fmtSpec({ align: ">", width: 8 }, args2[0]), "|", rt.fmtSpec({ align: "^", width: 8 }, args2[0]), "|", rt.fmtSpec({ fill: "-", align: "<", width: 3 }, args2[0]), "|", args2[1], "|", rt.fmtSpec({ width: 12 }, args2[1]), "|", rt.fmtSpec({ alternate: true }, args2[1]), "|{", args2[0], "}"])); } @@ -253,11 +253,12 @@ export function derived(data: Uint8Array, out: rt.ByteVec): void { put(out, rt.fmtFormat([rt.fmtSpec({ alternate: true }, args4[0])])); const wide: Wide.Wide = { a: at(0), b: 300, c: 70000, d: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, e: -1, f: at(1) > 10 }; const six: Six.Six = { _0: at(0), _1: 1, _2: 2, _3: 3, _4: 4, _5: at(1) }; + const args5: [Unit.Unit, Unit.Unit, Wide.Wide, Six.Six] = [{}, {}, wide, six]; const _56: rt.Fmt = (f: rt.Formatter) => Wide.fmt$Debug(wide, f); const _57: rt.Fmt = (f: rt.Formatter) => Six.fmt$Debug(six, f); - const arg3 = {}; + const arg3 = args5[0]; const _58: rt.Fmt = (f: rt.Formatter) => Unit.fmt$Debug(arg3, f); - const arg4 = {}; + const arg4 = args5[1]; const args6: rt.Fmt[] = [_56, _57, _58, (f: rt.Formatter) => Unit.fmt$Debug(arg4, f)]; put(out, rt.fmtFormat([args6[0], " ", args6[1], " ", args6[2], " ", rt.fmtSpec({ alternate: true }, args6[3])])); const args8: rt.Fmt[] = [(f: rt.Formatter) => Wide.fmt$Debug(wide, f), (f: rt.Formatter) => Six.fmt$Debug(six, f)]; @@ -278,13 +279,14 @@ export function derived(data: Uint8Array, out: rt.ByteVec): void { const _155: rt.u8 | undefined = rt.sliceGet(data, 100); const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(data, f, rt.u8Display), (f: rt.Formatter) => rt.fmtList(words, f, rt.u16Display), (f: rt.Formatter) => rt.fmtOption(_153, f, rt.u8Display), (f: rt.Formatter) => rt.fmtOption(_155, f, rt.u8Display)]; put(out, rt.fmtFormat([args16[0], " ", args16[1], " ", args16[2], " ", args16[3]])); - const arg6 = {}; + const args17: [Braced.Braced, Braced.Braced, Bare.Bare, Bare.Bare] = [{}, {}, {}, {}]; + const arg6 = args17[0]; const _177: rt.Fmt = (f: rt.Formatter) => Braced.fmt$Debug(arg6, f); - const arg7 = {}; + const arg7 = args17[1]; const _178: rt.Fmt = (f: rt.Formatter) => Braced.fmt$Debug(arg7, f); - const arg8 = {}; + const arg8 = args17[2]; const _179: rt.Fmt = (f: rt.Formatter) => Bare.fmt$Debug(arg8, f); - const arg9 = {}; + const arg9 = args17[3]; const args18: rt.Fmt[] = [_177, _178, _179, (f: rt.Formatter) => Bare.fmt$Debug(arg9, f)]; put(out, rt.fmtFormat([args18[0], " ", rt.fmtSpec({ alternate: true }, args18[1]), " ", args18[2], " ", rt.fmtSpec({ alternate: true }, args18[3])])); rt.byteVecExtendFromSlice(out, Uint8Array.of(Braced.eq$PartialEq({}, {}) ? 1 : 0, Bare.eq$PartialEq({}, {}) ? 1 : 0)); @@ -303,16 +305,16 @@ export function written(data: Uint8Array, out: rt.ByteVec): void { const arg = ([{ _0: "pad" }] as [Padded.Padded])[0]; const args4: rt.Fmt[] = [(f: rt.Formatter) => Padded.fmt$Display(arg, f)]; put(out, rt.fmtFormat([args4[0], "|", rt.fmtSpec({ align: ">", width: 6 }, args4[0]), "|", rt.fmtSpec({ fill: "_", align: "^", width: 9 }, args4[0]), "|", rt.fmtSpec({ width: 30 }, args4[0]), "|"])); - [{ id: at(1), list: [1, at(2) as rt.u16].slice() }, { id: 0, list: [] }] as [Manual.Manual, Manual.Manual]; - const arg2 = { id: at(1), list: [1, at(2) as rt.u16].slice() }; + const args5: [Manual.Manual, Manual.Manual] = [{ id: at(1), list: [1, at(2) as rt.u16].slice() }, { id: 0, list: [] }]; + const arg2 = args5[0]; const _66: rt.Fmt = (f: rt.Formatter) => Manual.fmt$Debug(arg2, f); - const arg3 = { id: 0, list: [] }; + const arg3 = args5[1]; const args6: rt.Fmt[] = [_66, (f: rt.Formatter) => Manual.fmt$Debug(arg3, f)]; put(out, rt.fmtFormat([args6[0], " ", rt.fmtSpec({ alternate: true }, args6[0]), " ", args6[1]])); - [{ _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair) }, { _0: [] }] as [Seq.Seq, Seq.Seq]; - const arg4 = { _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair) }; + const args7: [Seq.Seq, Seq.Seq] = [{ _0: [{ _0: at(3), _1: 0 }, { _0: 1, _1: -1 }].map(copy$Pair) }, { _0: [] }]; + const arg4 = args7[0]; const _92: rt.Fmt = (f: rt.Formatter) => Seq.fmt$Debug(arg4, f); - const arg5 = { _0: [] }; + const arg5 = args7[1]; const args8: rt.Fmt[] = [_92, (f: rt.Formatter) => Seq.fmt$Debug(arg5, f)]; put(out, rt.fmtFormat([args8[0], " ", rt.fmtSpec({ alternate: true }, args8[0]), " ", args8[1], " ", rt.fmtSpec({ alternate: true }, args8[1])])); const _97: rt.u8 = at(4); @@ -327,12 +329,12 @@ export function written(data: Uint8Array, out: rt.ByteVec): void { const arg7 = ([{ _0: at(6) & (~1 & 0xff) }] as [Fails.Fails])[0]; const args12: rt.Fmt[] = [(f: rt.Formatter) => Fails.fmt$Display(arg7, f)]; put(out, rt.fmtFormat([args12[0], " ", rt.fmtSpec({ align: ">", width: 9 }, args12[0])])); - [at(7), at(8), "named"] as [rt.u8, rt.u8, string]; - const arg8 = at(8); + const args13: [rt.u8, rt.u8, string] = [at(7), at(8), "named"]; + const arg8 = args13[1]; const _157: rt.Fmt = (f: rt.Formatter) => rt.u8Display(arg8, f); - const arg9 = at(7); + const arg9 = args13[0]; const _158: rt.Fmt = (f: rt.Formatter) => rt.u8Display(arg9, f); - const arg10 = at(7); + const arg10 = args13[0]; const args14: rt.Fmt[] = [_157, _158, (f: rt.Formatter) => rt.u8Display(arg10, f), (f: rt.Formatter) => rt.fmtPad(f, "named")]; put(out, rt.fmtFormat([args14[0], " ", args14[1], " ", args14[2], " named ", rt.fmtSpec({ align: ">", width: 5 }, args14[3])])); } @@ -349,14 +351,16 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(n, f), (f: rt.Formatter) => rt.fmtList(rest, f, rt.u8Display)]; rt.panicFmt(["bad ", args2[0], ": ", args2[1]]); } else if (_7 === 1) { + const args3: [Hex.Hex, rt.u8] = [{ _0: n as rt.u32 }, n]; const _27: rt.Fmt = (f: rt.Formatter) => rt.u8LowerHex(n, f); - const arg14 = { _0: n as rt.u32 }; + const arg14 = args3[0]; const args4: rt.Fmt[] = [_27, (f: rt.Formatter) => Hex.fmt$Display(arg14, f)]; rt.panicFmt(["internal error: entered unreachable code: never ", rt.fmtSpec({ alternate: true }, args4[0]), " ", args4[1]]); } else if (_7 === 2) { if (!(n > 200)) { + const args5: [rt.u8, Pair.Pair] = [n, { _0: n, _1: 0 }]; const _39: rt.Fmt = (f: rt.Formatter) => rt.u8Display(n, f); - const arg13 = { _0: n, _1: 0 }; + const arg13 = args5[1]; const args6: rt.Fmt[] = [_39, (f: rt.Formatter) => Pair.fmt$Debug(arg13, f)]; rt.panicFmt(["small ", args6[0], " ", args6[1]]); } @@ -369,13 +373,14 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { rt.assertFailed("==", (f: rt.Formatter) => rt.u8Display(n, f), (f: rt.Formatter) => rt.u8Display(7, f), undefined); } } else if (_7 === 5) { - if (Pair.eq$PartialEq({ _0: n, _1: 1 }, { _0: n, _1: 1 })) { + const _56: [Pair.Pair, Pair.Pair] = [{ _0: n, _1: 1 }, { _0: n, _1: 1 }]; + if (Pair.eq$PartialEq(_56[0], _56[1])) { const arg10 = ([n] as [rt.u8])[0]; const kind3: string = "!="; const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(arg10, f)]; const _66: rt.Arguments | undefined = ["same ", args8[0]]; - const arg11 = { _0: n, _1: 1 }; - const arg12 = { _0: n, _1: 1 }; + const arg11 = _56[0]; + const arg12 = _56[1]; rt.assertFailed(kind3, (f: rt.Formatter) => Pair.fmt$Debug(arg11, f), (f: rt.Formatter) => Pair.fmt$Debug(arg12, f), _66); } } else if (_7 === 6) { @@ -415,9 +420,10 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { const _157: Fails.Fails = { _0: n }; put(out, rt.fmtToString((f: rt.Formatter) => Fails.fmt$Display(_157, f))); } else if (_7 === 13) { - const arg6 = { _0: n as rt.u32 }; + const args13: [Hex.Hex, Fails.Fails] = [{ _0: n as rt.u32 }, { _0: n }]; + const arg6 = args13[0]; const _167: rt.Fmt = (f: rt.Formatter) => Hex.fmt$Display(arg6, f); - const arg7 = { _0: n }; + const arg7 = args13[1]; const args14: rt.Fmt[] = [_167, (f: rt.Formatter) => Fails.fmt$Display(arg7, f)]; rt.panicFmt([args14[0], " then ", args14[1]]); } else if (_7 === 14) { @@ -425,9 +431,9 @@ export function panics(kind: rt.u8, rest: Uint8Array, out: rt.ByteVec): void { const start: rt.usize = _173[0]; const end: rt.usize = _173[1]; const _189: Uint8Array = rt.sliceRange(rest, start); - [_189, rt.sliceRange(rest, start, end)] as [Uint8Array, Uint8Array]; + const args15: [Uint8Array, Uint8Array] = [_189, rt.sliceRange(rest, start, end)]; const _196: rt.Fmt = (f: rt.Formatter) => rt.fmtList(_189, f, rt.u8Display); - const arg5 = rt.sliceRange(rest, start, end); + const arg5 = args15[1]; const args16: rt.Fmt[] = [_196, (f: rt.Formatter) => rt.fmtList(arg5, f, rt.u8Display)]; put(out, rt.fmtFormat([args16[0], " ", args16[1]])); } else if (_7 === 15) { diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index a37d3b059..4fbb3d89a 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -40,9 +40,9 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { return { _0: b, _1: at(6) as rt.i64 }; }); const _119: Wrap.Wrap = Wrap.new$Pair({ _0: at(1), _1: 0 }); - [Wrap.eq$PartialEq_Pair(mapped, _119), mapped] as [boolean, Wrap.Wrap]; + const args5: [boolean, Wrap.Wrap] = [Wrap.eq$PartialEq_Pair(mapped, _119), mapped]; const _126: rt.Fmt = (f: rt.Formatter) => Wrap.fmt$Debug_Pair(mapped, f); - const arg2 = Wrap.eq$PartialEq_Pair(mapped, _119); + const arg2 = args5[0]; const args6: rt.Fmt[] = [_126, (f: rt.Formatter) => rt.fmtBool(arg2, f)]; put(out, rt.fmtFormat([args6[0], " ", args6[1]])); const iter: rt.Iter> = rt.iterSlice([{ tag: "Left", _0: at(7) } as Either.Either, { tag: "Right", value: Point.new(1, -1) } as Either.Either, { tag: "Neither" } as Either.Either]); @@ -53,12 +53,12 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { } const either: Either.Either = _140; const flipped: Either.Either = Either.flip$u8_Point(either); - [Either.left$u8_Point(either), Either.left$Point_u8(flipped), either, flipped] as [rt.u8 | undefined, Point.Point | undefined, Either.Either, Either.Either]; + const args7: [rt.u8 | undefined, Point.Point | undefined, Either.Either, Either.Either] = [Either.left$u8_Point(either), Either.left$Point_u8(flipped), either, flipped]; const _161: rt.Fmt = (f: rt.Formatter) => Either.fmt$Debug_u8_Point(either, f); const _162: rt.Fmt = (f: rt.Formatter) => Either.fmt$Debug_Point_u8(flipped, f); - const arg3 = Either.left$u8_Point(either); + const arg3 = args7[0]; const _163: rt.Fmt = (f: rt.Formatter) => rt.fmtOption(arg3, f, rt.u8Display); - const arg4 = Either.left$Point_u8(flipped); + const arg4 = args7[1]; const args8: rt.Fmt[] = [_161, _162, _163, (f: rt.Formatter) => rt.fmtOption(arg4, f, (value: Point.Point, f: rt.Formatter) => Point.fmt$Debug(value, f))]; put(out, rt.fmtFormat([args8[0], " ", rt.fmtSpec({ alternate: true }, args8[1]), " ", args8[2], " ", args8[3]])); } @@ -73,9 +73,9 @@ export function methods(data: Uint8Array, out: rt.ByteVec): void { const args10: rt.Fmt[] = [(f: rt.Formatter) => Wrap.fmt$Debug_Vec_u16(list, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(none, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(some, f), (f: rt.Formatter) => Wrap.fmt$Debug_Result_u8_Shape(err, f), (f: rt.Formatter) => rt.u8Display(_193, f)]; put(out, rt.fmtFormat([args10[0], " ", args10[1], " ", args10[2], " ", args10[3], " ", args10[4]])); const tagged: Tagged.Tagged, rt.i16> = new Tagged.Tagged({ key: { tag: "Right", value: 500 } as Either.Either, inner: Wrap.new$i16(rt.i16Sub(at(8) as rt.i16, 100)), all: [Wrap.new$i16(-1), Wrap.new$i16(at(9) as rt.i16)].map(copy$Wrap_i16) }); - [Tagged.first$Either_u8_u16_i16(tagged), tagged] as [Wrap.Wrap | undefined, Tagged.Tagged, rt.i16>]; + const args11: [Wrap.Wrap | undefined, Tagged.Tagged, rt.i16>] = [Tagged.first$Either_u8_u16_i16(tagged), tagged]; const _241: rt.Fmt = (f: rt.Formatter) => Tagged.fmt$Debug_Either_u8_u16_i16(tagged, f); - const arg5 = Tagged.first$Either_u8_u16_i16(tagged); + const arg5 = args11[0]; const args12: rt.Fmt[] = [_241, (f: rt.Formatter) => rt.fmtOption(arg5, f, (value: Wrap.Wrap, f: rt.Formatter) => Wrap.fmt$Debug_i16(value, f))]; put(out, rt.fmtFormat([args12[0], " ", args12[1]])); rt.byteVecExtendFromSlice(out, rt.i16ToBeBytes(tagged.inner.value)); diff --git a/ts/fixtures/lang/expected/ints.ts b/ts/fixtures/lang/expected/ints.ts index d0dc26415..590fdf060 100644 --- a/ts/fixtures/lang/expected/ints.ts +++ b/ts/fixtures/lang/expected/ints.ts @@ -23,15 +23,15 @@ export function u8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.u8, Uint8Array] = [rt.u8FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.u8 = _6[0]; const buf2: Uint8Array = Uint8Array.of(0); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.u8 = rt.u8FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.u8, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.u8, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.u8 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 8); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.u8Add(a, b); @@ -140,15 +140,15 @@ export function u16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.u16, Uint8Array] = [rt.u16FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.u16 = _6[0]; const buf2: Uint8Array = rt.bytes(2); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.u16 = rt.u16FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.u16, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.u16, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.u16 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 16); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.u16Add(a, b); @@ -257,15 +257,15 @@ export function u32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.u32, Uint8Array] = [rt.u32FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.u32 = _6[0]; const buf2: Uint8Array = rt.bytes(4); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.u32 = rt.u32FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.u32, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.u32, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.u32 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.u32Add(a, b); @@ -374,15 +374,15 @@ export function u64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.u64, Uint8Array] = [rt.u64FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.u64 = _6[0]; const buf2: Uint8Array = rt.bytes(8); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.u64 = rt.u64FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.u64, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.u64, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.u64 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 64); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.u64Add(a, b); @@ -491,15 +491,15 @@ export function u128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.u128, Uint8Array] = [rt.u128FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.u128 = _6[0]; const buf2: Uint8Array = rt.bytes(16); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.u128 = rt.u128FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.u128, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.u128, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.u128 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 128); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.u128Add(a, b); @@ -608,15 +608,15 @@ export function usizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.usize, Uint8Array] = [rt.usizeFromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.usize = _6[0]; const buf2: Uint8Array = rt.bytes(4); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.usize = rt.usizeFromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.usize, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.usize, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.usize = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.usizeAdd(a, b); @@ -725,15 +725,15 @@ export function i8Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.i8, Uint8Array] = [rt.i8FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.i8 = _6[0]; const buf2: Uint8Array = Uint8Array.of(0); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.i8 = rt.i8FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.i8, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.i8, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.i8 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 8); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.i8Add(a, b); @@ -842,15 +842,15 @@ export function i16Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.i16, Uint8Array] = [rt.i16FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.i16 = _6[0]; const buf2: Uint8Array = rt.bytes(2); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.i16 = rt.i16FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.i16, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.i16, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.i16 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 16); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.i16Add(a, b); @@ -959,15 +959,15 @@ export function i32Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.i32, Uint8Array] = [rt.i32FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.i32 = _6[0]; const buf2: Uint8Array = rt.bytes(4); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.i32 = rt.i32FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.i32, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.i32, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.i32 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.i32Add(a, b); @@ -1076,15 +1076,15 @@ export function i64Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.i64, Uint8Array] = [rt.i64FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.i64 = _6[0]; const buf2: Uint8Array = rt.bytes(8); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.i64 = rt.i64FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.i64, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.i64, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.i64 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 64); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.i64Add(a, b); @@ -1193,15 +1193,15 @@ export function i128Op(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.i128, Uint8Array] = [rt.i128FromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.i128 = _6[0]; const buf2: Uint8Array = rt.bytes(16); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.i128 = rt.i128FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.i128, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.i128, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.i128 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 128); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.i128Add(a, b); @@ -1310,15 +1310,15 @@ export function isizeOp(op: rt.u8, data: Uint8Array, out: rt.ByteVec): void { const _6: [rt.isize, Uint8Array] = [rt.isizeFromBeBytes(buf), rt.sliceRange(data, n)]; const a: rt.isize = _6[0]; const buf2: Uint8Array = rt.bytes(4); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_6[1].length, buf2.length); const _33: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _6[1]; rt.sliceCopyFromSlice(_33, rt.sliceRange(slice, 0, n2)); const _38: rt.isize = rt.isizeFromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); - [_38, rt.sliceRange(slice2, n2)] as [rt.isize, Uint8Array]; + const slice2 = _6[1]; + const _25: [rt.isize, Uint8Array] = [_38, rt.sliceRange(slice2, n2)]; const b: rt.isize = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(rt.sliceRange(slice2, n2)), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.sliceFirst(_25[1]), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { const part16 = rt.isizeAdd(a, b); @@ -2128,12 +2128,12 @@ export function convert(data: Uint8Array, out: rt.ByteVec): void { const _5: [rt.u64, Uint8Array] = [rt.u64FromBeBytes(buf), rt.sliceRange(data, n)]; const wide: rt.u64 = _5[0]; const buf2: Uint8Array = rt.bytes(4); - const n2: rt.usize = rt.min(rt.sliceRange(data, n).length, buf2.length); + const n2: rt.usize = rt.min(_5[1].length, buf2.length); const _31: Uint8Array = rt.sliceRange(buf2, 0, n2); - const slice = rt.sliceRange(data, n); + const slice = _5[1]; rt.sliceCopyFromSlice(_31, rt.sliceRange(slice, 0, n2)); const _36: rt.i32 = rt.i32FromBeBytes(buf2); - const slice2 = rt.sliceRange(data, n); + const slice2 = _5[1]; const signed: rt.i32 = ([_36, rt.sliceRange(slice2, n2)] as [rt.i32, Uint8Array])[0]; rt.byteVecPush(out, rt.u8TryFrom(wide).ok ? 1 : 0); const _46: rt.Result = rt.u32TryFrom(wide); diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 685b5970f..d1d200399 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -632,10 +632,10 @@ export function values(data: Uint8Array, out: rt.ByteVec): void { } rt.byteVecPush(out, _21); } - [{ _0: data }, { _0: rt.sliceRange(data, 0, rt.min(data.length, 2)) }] as [Doubled.Doubled, Doubled.Doubled]; - const arg = { _0: data }; + const args: [Doubled.Doubled, Doubled.Doubled] = [{ _0: data }, { _0: rt.sliceRange(data, 0, rt.min(data.length, 2)) }]; + const arg = args[0]; const _39: rt.Fmt = (f: rt.Formatter) => Doubled.fmt$Debug(arg, f); - const arg2 = { _0: rt.sliceRange(data, 0, rt.min(data.length, 2)) }; + const arg2 = args[1]; const args2: rt.Fmt[] = [_39, (f: rt.Formatter) => Doubled.fmt$Debug(arg2, f)]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0], "|", rt.fmtSpec({ alternate: true }, args2[1])]))); const tags: Tag.Tag[] = rt.iterToArray(rt.iterMap(rt.iterSlice(data), (_2: rt.u8): Tag.Tag => { diff --git a/ts/fixtures/lang/expected/keys.ts b/ts/fixtures/lang/expected/keys.ts index 22af19ef7..de1a6cdcd 100644 --- a/ts/fixtures/lang/expected/keys.ts +++ b/ts/fixtures/lang/expected/keys.ts @@ -248,8 +248,9 @@ export function borrows(data: Uint8Array, out: rt.ByteVec): void { const g: Horizon.Horizon = { exclude: a, local: _28 }; unwind = 0; const _32: boolean = rt.u8Rem(d, 2) === 0; + const _37: [Horizon.Horizon, Horizon.Horizon] = [g, { exclude: b, local: _32 }]; const gr: Horizon.Horizon = g; - const hr: Horizon.Horizon = { exclude: b, local: _32 }; + const hr: Horizon.Horizon = _37[1]; _43 = name(c); unwind = 55; const _44: Name.Name = name(d); @@ -478,9 +479,9 @@ export function arcs(data: Uint8Array, out: rt.ByteVec): void { _165 = true; b = _20; rt.byteVecPush(out, order(rt.cmpArc(rt.cmpStr)(a.text, b.text)) | ((order(Name.cmp$Ord(a, b)) << 2) & 0xff)); - [rt.ordMax(a.text, b.text, rt.cmpArc(rt.cmpStr)), rt.ordMin(a.text, b.text, rt.cmpArc(rt.cmpStr))] as [rt.Arc, rt.Arc]; - rt.byteVecPush(out, (rt.ordMax(a.text, b.text, rt.cmpArc(rt.cmpStr)) === b.text ? 1 : 0) | (((rt.ordMin(a.text, b.text, rt.cmpArc(rt.cmpStr)) === a.text ? 1 : 0) << 1) & 0xff)); - rt.byteVecPush(out, (rt.eqArc(rt.same, true)(a.text, b.text) ? 1 : 0) | (((Name.eq$PartialEq(a, b) ? 1 : 0) << 1) & 0xff) | (((rt.eqArc(rt.same, true)(rt.ordMax(a.text, b.text, rt.cmpArc(rt.cmpStr)), b.text) ? 1 : 0) << 2) & 0xff)); + const _39: [rt.Arc, rt.Arc] = [rt.ordMax(a.text, b.text, rt.cmpArc(rt.cmpStr)), rt.ordMin(a.text, b.text, rt.cmpArc(rt.cmpStr))]; + rt.byteVecPush(out, (_39[0] === b.text ? 1 : 0) | (((_39[1] === a.text ? 1 : 0) << 1) & 0xff)); + rt.byteVecPush(out, (rt.eqArc(rt.same, true)(a.text, b.text) ? 1 : 0) | (((Name.eq$PartialEq(a, b) ? 1 : 0) << 1) & 0xff) | (((rt.eqArc(rt.same, true)(_39[0], b.text) ? 1 : 0) << 2) & 0xff)); rt.byteVecPush(out, (rt.u64Eq(hashOf$Arc_str(a.text), hashOf$Arc_str(b.text)) ? 1 : 0) | (((rt.u64Eq(hashOf$Name(a), hashOf$Name(b)) ? 1 : 0) << 1) & 0xff)); const text: string = a.text.value; const _102: string = b.text.value; diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index c7a4a6ebb..4349202cb 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -13,7 +13,6 @@ | 5 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:15:13 | | 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:32:4 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:6:14 | -| 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:55:2 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:107:2 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:127:20 | | 2 | a field of `_` | fixtures/reject/src/lib.rs:289:7 | @@ -26,10 +25,13 @@ | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:89:3 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | fixtures/reject/src/lib.rs:294:6 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:317:6 | +| 1 | `_` of `_`, which drops `_`, which is not supported yet | fixtures/reject/src/lib.rs:55:13 | | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:349:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | fixtures/reject/src/lib.rs:359:6 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:325:9 | +| 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | fixtures/reject/src/lib.rs:248:26 | | 1 | a `_` cast from `_` to `_` | fixtures/reject/src/lib.rs:118:2 | +| 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:253:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:199:51 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:102:2 | | 1 | a copy of a closure that changes what it captured | fixtures/reject/src/lib.rs:283:14 | @@ -56,31 +58,33 @@ The type or module each refused type or path belongs to. | 6 | `Option` | fixtures/reject/src/lib.rs:27:15 | | 6 | `f64` | fixtures/reject/src/lib.rs:6:14 | | 6 | `u8` | fixtures/reject/src/lib.rs:64:10 | -| 4 | `std::vec::Vec` | fixtures/reject/src/lib.rs:55:2 | | 4 | `u32` | fixtures/reject/src/lib.rs:15:13 | +| 3 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:55:13 | | 2 | `Iterator` | fixtures/reject/src/lib.rs:166:2 | | 2 | `Meters` | fixtures/reject/src/lib.rs:107:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:127:20 | -| 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:294:6 | +| 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:172:23 | +| 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:207:8 | | 2 | `std::option::Option` | fixtures/reject/src/lib.rs:294:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:143:2 | | 2 | `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:123:2 | +| 2 | `std::vec::Vec` | fixtures/reject/src/lib.rs:299:52 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:186:1 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:240:1 | | 1 | `HashMap` | fixtures/reject/src/lib.rs:317:6 | | 1 | `Hasher` | fixtures/reject/src/lib.rs:325:9 | | 1 | `IntToFloat` | fixtures/reject/src/lib.rs:118:2 | -| 1 | `Noisy` | fixtures/reject/src/lib.rs:253:20 | +| 1 | `Noisy` | fixtures/reject/src/lib.rs:55:13 | | 1 | `[u8; 1]` | fixtures/reject/src/lib.rs:272:22 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:10:16 | +| 1 | `into_keys` | fixtures/reject/src/lib.rs:55:13 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:199:51 | -| 1 | `std::iter::Map` | fixtures/reject/src/lib.rs:172:23 | +| 1 | `std::iter::Flatten` | fixtures/reject/src/lib.rs:248:26 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:193:14 | | 1 | `std::mem` | fixtures/reject/src/lib.rs:48:18 | | 1 | `std::ops::RangeFrom` | fixtures/reject/src/lib.rs:289:48 | | 1 | `std::ops::RangeTo` | fixtures/reject/src/lib.rs:289:7 | -| 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:207:8 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:153:11 | | 1 | `std::slice` | fixtures/reject/src/lib.rs:32:4 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:148:2 | @@ -98,15 +102,17 @@ The type or module each refused type or path belongs to. | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u8`, `u8` | fixtures/reject/src/lib.rs:64:10 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:143:2 | | 2 | an assignment through a reference to `_` | `u8` | fixtures/reject/src/lib.rs:65:3 | -| 2 | an iterator that owns `_`, which drops, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:55:2 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:107:2 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | `std::collections::HashMap`, `std::option::Option` | fixtures/reject/src/lib.rs:294:6 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:317:6 | +| 1 | `_` of `_`, which drops `_`, which is not supported yet | `into_keys`, `std::collections::HashMap`, `Noisy` | fixtures/reject/src/lib.rs:55:13 | | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:349:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | `std::option::Option` | fixtures/reject/src/lib.rs:359:6 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:325:9 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:94:16 | +| 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | `std::iter::Flatten` | fixtures/reject/src/lib.rs:248:26 | | 1 | a `_` cast from `_` to `_` | `IntToFloat`, `u64`, `f64` | fixtures/reject/src/lib.rs:118:2 | +| 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:253:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:199:51 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:102:2 | | 1 | a field of `_` | `std::ops::RangeFrom` | fixtures/reject/src/lib.rs:289:48 | @@ -119,7 +125,6 @@ The type or module each refused type or path belongs to. | 1 | an assignment through a reference to `_` | `u32` | fixtures/reject/src/lib.rs:16:2 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:186:1 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:240:1 | -| 1 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:253:20 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:299:52 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:172:23 | @@ -189,14 +194,6 @@ The type or module each refused type or path belongs to. -
an iterator that owns `_`, which drops, which is not supported yet (3) - -- fixtures/reject/src/lib.rs:55:2: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:248:4: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:253:20: an iterator that owns `Noisy`, which drops, which is not supported yet - -
-
replacing the value behind a reference to `_` (3) - fixtures/reject/src/lib.rs:107:2: replacing the value behind a reference to `Meters` @@ -276,6 +273,12 @@ The type or module each refused type or path belongs to.
+
`_` of `_`, which drops `_`, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:55:13: `into_keys` of `std::collections::HashMap`, which drops `Noisy`, which is not supported yet + +
+
`_` through a held type's own, which is not supported yet (1) - fixtures/reject/src/lib.rs:349:2: ` as PartialEq>::ne` through a held type's own, which is not supported yet @@ -294,12 +297,24 @@ The type or module each refused type or path belongs to.
+
`fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:248:26: `fold` of `std::iter::Flatten>>`, which folds a `flatten` whose source and iterators both drop, which is not supported yet + +
+
a `_` cast from `_` to `_` (1) - fixtures/reject/src/lib.rs:118:2: a `IntToFloat` cast from `u64` to `f64`
+
a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:253:30: a `zip` of `std::iter::Map, {closure@fixtures/reject/src/lib.rs:253:15: 253:19}>` and `std::ops::Range`, which std reads by index, of items that drop, which is not supported yet + +
+
a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` (1) - fixtures/reject/src/lib.rs:199:51: a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:199:15: 199:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 93c2a4da5..33f3c994e 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -16,7 +16,7 @@ unsupported call to `std::slice::::sort` at fixtures/reject/src/lib.r `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:36:42 unsupported call to `std::mem::size_of_val::` at fixtures/reject/src/lib.rs:48:18 dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:50:1 -an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:55:11 +`into_keys` of `std::collections::HashMap`, which drops `Noisy`, which is not supported yet at fixtures/reject/src/lib.rs:55:13 `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:64:10 an assignment through a reference to `u8` at fixtures/reject/src/lib.rs:65:3 a zero-sized constant of type `{async closure@fixtures/reject/src/lib.rs:73:10: 73:18}` at fixtures/reject/src/lib.rs:74:2 @@ -46,8 +46,8 @@ constructing `std::iter::Map` from another crate at fixtures/reject/src/lib.rs:193:14 a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:199:15: 199:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` at fixtures/reject/src/lib.rs:199:51 unsupported call to `std::ops::Range::::contains::` at fixtures/reject/src/lib.rs:207:8 -an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:248:4 -an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:253:20 +`fold` of `std::iter::Flatten>>`, which folds a `flatten` whose source and iterators both drop, which is not supported yet at fixtures/reject/src/lib.rs:248:26 +a `zip` of `std::iter::Map, {closure@fixtures/reject/src/lib.rs:253:15: 253:19}>` and `std::ops::Range`, which std reads by index, of items that drop, which is not supported yet at fixtures/reject/src/lib.rs:253:30 a mutable borrow of a subslice of `u32`, which JS would copy, having no views at fixtures/reject/src/lib.rs:258:13 an assignment through a reference to `std::pin::Pin<&mut Noisy>` at fixtures/reject/src/lib.rs:266:2 replacing the value behind a reference to `[u8; 1]` at fixtures/reject/src/lib.rs:272:22 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index f103c13df..a074b46d4 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -49,11 +49,11 @@ pub fn owning_closure() -> u8 { f() } -/// Each element drops at the end of its iteration, and the rest on a `break`. -pub fn each(v: Vec) -> u8 { +/// std's `fold` of `into_keys` drops each value after its key, where `next` drops it first. +pub fn keys(m: std::collections::HashMap) -> u8 { let mut sum = 0; - for n in v { - sum += n.0; + for k in m.into_keys() { + sum += k; } sum } @@ -243,14 +243,14 @@ pub fn fused() -> usize { Fused.fuse().count() } -/// The items `next` leaves drop with the iterator, which an `rt.Iter` never drops. -pub fn drained(v: Vec) -> Option { - v.into_iter().next() +/// A panic in `fold` drops the `Vec` `flatten` took mid-way before the rest, as `next` does not. +pub fn flattened(v: Vec>) -> usize { + v.into_iter().flatten().fold(0, |n, _| n + 1) } -/// `count` drops each item it consumes. -pub fn counted() -> usize { - (0..2).map(Noisy).count() +/// std's `zip` of two `TrustedRandomAccess` iterators makes one item past the shorter, and drops it. +pub fn zip_dropped(v: &[u8]) -> usize { + v.iter().map(|&n| Noisy(n)).zip(0..2).count() } /// `rest` borrows the tail of `items` mutably, but a JS array has no views. diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 7aa37b14c..6745725b5 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -9,7 +9,7 @@ roots = [ "iterators", "Noisy", "owning_closure", - "each", + "keys", "async_borrow", "async_closure", "specs", @@ -31,8 +31,8 @@ roots = [ "keyed", "hinted", "fused", - "drained", - "counted", + "flattened", + "zip_dropped", "rest_mut", "replace_pinned_ref", "replace_captured", diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 020543a35..774a8c724 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Guard_Bomb_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; +import { looped, collected, drained, extended, bombed } from "./drops/iters.ts"; import * as Bomb from "./drops.Bomb.ts"; import type * as Fault from "./drops.Fault.ts"; import * as Held from "./drops.Held.ts"; @@ -15,7 +16,7 @@ import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; /** - * Run scenario `arg % 13`, panicking at the point `arg / 13 % 8` names, if any: what + * Run scenario `arg % 18`, panicking at the point `arg / 18 % 8` names, if any: what * every value std holds drops, where Rust drops it, and in Rust's order. */ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { @@ -73,7 +74,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _353 = false; _352 = false; _351 = false; - const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 13), 8); + const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 18), 8); const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -83,8 +84,18 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { rt.panicFmt(["d", args16[0], " at ", args16[1]]); } }; - const _13: rt.u8 = rt.u8Rem(arg, 13); - if (_13 === 4) { + const _13: rt.u8 = rt.u8Rem(arg, 18); + if (_13 === 13) { + looped(log, id, at); + } else if (_13 === 14) { + collected(log, id, at); + } else if (_13 === 15) { + drained(log, id, at); + } else if (_13 === 16) { + extended(log, id, at); + } else if (_13 === 17) { + bombed(log, id, at); + } else if (_13 === 4) { ordered(log, id, at); } else if (_13 === 5) { hashed(log, id, at); @@ -104,23 +115,23 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { grown(log, id, at, false); } else if (_13 === 0) { v = []; - unwind = 197; + unwind = 202; const _19: Held.Held = { tag: "One", _0: guard(1) }; v.push(_19); v.push({ tag: "Empty" } as Held.Held); _29 = guard(2); - unwind = 196; + unwind = 201; const _32: Guard.Guard = guard(3); - unwind = 197; + unwind = 202; v.push({ tag: "Two", _0: _29, _1: _32 } as Held.Held); - unwind = 195; + unwind = 200; held_ = v; check(1); arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); - unwind = 214; + unwind = 219; _358 = true; shared = rt.arcClone(arc); - unwind = 194; + unwind = 199; _358 = false; rt.arcDrop(arc, drop$Held); const arg7 = ([shared.strong] as [rt.usize])[0]; @@ -128,22 +139,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { Log.note(log, rt.fmtFormat(["arc ", args2[0]])); check(2); v2 = []; - unwind = 193; + unwind = 198; const _67: Held.Held = { tag: "One", _0: guard(5) }; v2.push(_67); - unwind = 194; + unwind = 199; mutex = new rt.Mutex(v2); - unwind = 212; + unwind = 217; _357 = true; _73 = guard(6); - unwind = 192; + unwind = 197; const _76: Guard.Guard = guard(7); - unwind = 212; + unwind = 217; boxed = { tag: "Two", _0: _73, _1: _76 } as Held.Held; - unwind = 210; + unwind = 215; _356 = true; const _80: Held.Held = { tag: "One", _0: guard(8) }; - unwind = 191; + unwind = 196; maybe = _80; check(3); [held_.length, maybe !== undefined] as [rt.usize, boolean]; @@ -157,9 +168,9 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _357 = false; rt.dropAll(mutex.value, drop$Held); check(5); - unwind = 210; + unwind = 215; drop$Option_Box_Held(maybe); - unwind = 214; + unwind = 219; _356 = false; _357 = false; rt.arcDrop(shared, drop$Held); @@ -169,53 +180,53 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 1) { const _115: rt.u32 = rt.u32Add(id, 10); _117 = Log.clone$Clone(log); - unwind = 190; + unwind = 195; const _119: Guard.Guard = guard(11); - unwind = 189; + unwind = 194; wrapped = new Wrap.Wrap({ id: _115, log: _117, inner: { tag: "One", _0: _119 } as Held.Held }); const _123: rt.u32 = rt.u32Add(id, 20); _125 = Log.clone$Clone(log); - unwind = 188; + unwind = 193; const _126: Guard.Guard = guard(21); - unwind = 187; + unwind = 192; guarded = new Wrap.Wrap({ id: _123, log: _125, inner: _126 }); check(1); _134 = guard(31); - unwind = 186; + unwind = 191; const _137: Guard.Guard = guard(32); - unwind = 185; + unwind = 190; _133 = { tag: "Two", _0: _134, _1: _137 } as Held.Held; const _140: Guard.Guard = guard(33); - unwind = 208; + unwind = 213; _355 = true; pair = new Pair.Pair({ first: _133, second: _140 }); v3 = []; - unwind = 184; + unwind = 189; _148 = guard(41); - unwind = 183; + unwind = 188; const _151: Guard.Guard = guard(42); - unwind = 184; + unwind = 189; v3.push(new Pair.Pair({ first: _148, second: _151 })); _157 = guard(43); - unwind = 182; + unwind = 187; const _160: Guard.Guard = guard(44); - unwind = 184; + unwind = 189; v3.push(new Pair.Pair({ first: _157, second: _160 })); - unwind = 181; + unwind = 186; pairs = v3; check(2); const _167: rt.u32 = rt.u32Add(id, 50); _169 = Log.clone$Clone(log); - unwind = 180; + unwind = 185; v4 = []; - unwind = 179; + unwind = 184; const _175: rt.u32 = rt.u32Add(id, 60); _177 = Log.clone$Clone(log); - unwind = 178; + unwind = 183; const _179: Guard.Guard = guard(61); - unwind = 179; + unwind = 184; v4.push(new Wrap.Wrap({ id: _175, log: _177, inner: { tag: "One", _0: _179 } as Held.Held })); - unwind = 177; + unwind = 182; nested = new Wrap.Wrap({ id: _167, log: _169, inner: v4 }); check(3); _355 = false; @@ -226,17 +237,17 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const at2 = rt.idx(pairs, 1); const _204: rt.u32 = Guard.id(pairs[at2].first); const at3 = rt.idx(pairs, 0); - [_196, _199, rt.u32Add(rt.u32Add(_204, Guard.id(pairs[at3].second)), nested.inner.length as rt.u32)] as [boolean, rt.u32, rt.u32]; + const args5: [boolean, rt.u32, rt.u32] = [_196, _199, rt.u32Add(rt.u32Add(_204, Guard.id(pairs[at3].second)), nested.inner.length as rt.u32)]; const _218: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(_196, f); const _219: rt.Fmt = (f: rt.Formatter) => rt.u32Display(_199, f); - const arg6 = rt.u32Add(rt.u32Add(_204, Guard.id(pairs[at3].second)), nested.inner.length as rt.u32); + const arg6 = args5[2]; const args6: rt.Fmt[] = [_218, _219, (f: rt.Formatter) => rt.u32Display(arg6, f)]; Log.note(log, rt.fmtFormat(["wraps ", args6[0], " ", args6[1], " ", args6[2]])); - unwind = 181; + unwind = 186; drop$Wrap_Vec_Wrap_Held(nested); - unwind = 208; + unwind = 213; rt.dropAll(pairs); - unwind = 189; + unwind = 194; _355 = false; drop$Wrap_Guard(guarded); unwind = 0; @@ -244,22 +255,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 2) { const _225: rt.u32 = rt.u32Add(id, 70); _227 = Log.clone$Clone(log); - unwind = 176; + unwind = 181; const _230: Guard.Guard = guard(71); - unwind = 175; + unwind = 180; _229 = { tag: "One", _0: _230 } as Held.Held; const _233: Guard.Guard = guard(72); unwind = 0; shared2 = new rt.Arc(new Wrap.Wrap({ id: _225, log: _227, inner: new Pair.Pair({ first: _229, second: _233 }) })); - unwind = 206; + unwind = 211; _354 = true; v5 = []; - unwind = 174; + unwind = 179; const _240: rt.Arc>> = rt.arcClone(shared2); v5.push(_240); const _244: rt.Arc>> = rt.arcClone(shared2); v5.push(_244); - unwind = 173; + unwind = 178; clones = v5; check(1); _354 = false; @@ -271,37 +282,37 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg5 = ([!bail(log, id, at).ok] as [boolean])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg5, f)]; Log.note(log, rt.fmtFormat(["bailed ", args10[0]])); - unwind = 206; + unwind = 211; rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); _354 = false; } else { _282 = guard(81); - unwind = 172; + unwind = 177; const _285: Guard.Guard = guard(82); unwind = 0; arc2 = new rt.Arc(new rt.Mutex({ tag: "Two", _0: _282, _1: _285 } as Held.Held)); - unwind = 204; + unwind = 209; _353 = true; other = rt.arcClone(arc2); - unwind = 171; + unwind = 176; check(1); _353 = false; rt.arcDrop(arc2, drop$Mutex_Held); check(2); const _301: rt.Mutex = other.value; - unwind = 170; + unwind = 175; const held2: boolean = Held.isSome(_301.value); - unwind = 171; + unwind = 176; const arg2 = ([held2] as [boolean])[0]; const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg2, f)]; Log.note(log, rt.fmtFormat(["locked ", args12[0]])); lent = guard(83); - unwind = 169; + unwind = 174; borrowed = new rt.Arc(lent); - unwind = 202; + unwind = 207; _352 = true; again = rt.arcClone(borrowed); - unwind = 200; + unwind = 205; _351 = true; _352 = false; rt.arcDrop(borrowed); @@ -311,11 +322,11 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg3 = ([Guard.id(lent)] as [rt.u32])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; Log.note(log, rt.fmtFormat(["lent ", args14[0]])); - unwind = 171; + unwind = 176; _351 = false; _352 = false; rt.drop(lent); - unwind = 204; + unwind = 209; rt.arcDrop(other, drop$Mutex_Held); _353 = false; } @@ -342,127 +353,127 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { if (unwind === 0) { throw e; } - if (unwind === 169) { + if (unwind === 174) { break b4; } - if (unwind === 170) { + if (unwind === 175) { break b3; } - if (unwind === 171) { + if (unwind === 176) { break b3; } - if (unwind === 172) { + if (unwind === 177) { rt.drop(_282); break b1; } - if (unwind === 173) { + if (unwind === 178) { rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 174) { + if (unwind === 179) { rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 175) { + if (unwind === 180) { drop$Held(_229); break b6; } - if (unwind === 176) { + if (unwind === 181) { break b6; } - if (unwind === 177) { + if (unwind === 182) { drop$Wrap_Vec_Wrap_Held(nested); break b10; } - if (unwind === 178) { + if (unwind === 183) { rt.drop(_177); break b12; } - if (unwind === 179) { + if (unwind === 184) { break b12; } - if (unwind === 180) { + if (unwind === 185) { break b11; } - if (unwind === 181) { + if (unwind === 186) { break b10; } - if (unwind === 182) { + if (unwind === 187) { rt.drop(_157); break b13; } - if (unwind === 183) { + if (unwind === 188) { rt.drop(_148); break b13; } - if (unwind === 184) { + if (unwind === 189) { break b13; } - if (unwind === 185) { + if (unwind === 190) { drop$Held(_133); break b8; } - if (unwind === 186) { + if (unwind === 191) { rt.drop(_134); break b8; } - if (unwind === 187) { + if (unwind === 192) { break b8; } - if (unwind === 188) { + if (unwind === 193) { rt.drop(_125); break b7; } - if (unwind === 189) { + if (unwind === 194) { break b7; } - if (unwind === 190) { + if (unwind === 195) { rt.drop(_117); break b1; } - if (unwind === 191) { + if (unwind === 196) { drop$Option_Box_Held(maybe); break b18; } - if (unwind === 192) { + if (unwind === 197) { rt.drop(_73); break b17; } - if (unwind === 193) { + if (unwind === 198) { rt.dropAll(v2, drop$Held); break b16; } - if (unwind === 194) { + if (unwind === 199) { break b16; } - if (unwind === 195) { + if (unwind === 200) { break b14; } - if (unwind === 196) { + if (unwind === 201) { rt.drop(_29); break b19; } - if (unwind === 197) { + if (unwind === 202) { break b19; } - if (unwind === 200) { + if (unwind === 205) { if (_351) { rt.arcDrop(again); } - } else if (unwind !== 202) { - if (unwind === 204) { + } else if (unwind !== 207) { + if (unwind === 209) { break b2; } - if (unwind === 206) { + if (unwind === 211) { break b5; } - if (unwind === 208) { + if (unwind === 213) { break b9; } - if (unwind === 210) { + if (unwind === 215) { break b18; } - if (unwind === 212) { + if (unwind === 217) { break b17; } break b15; @@ -552,9 +563,9 @@ export function bail(log: Log.Log, id: rt.u32, at: rt.u8): rt.Result = fails(at); if (_18.ok) { const n: rt.u32 = _18.value; - [held_.length, Held.isSome(wrap.inner)] as [rt.usize, boolean]; + const args: [rt.usize, boolean] = [held_.length, Held.isSome(wrap.inner)]; const _35: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(held_.length, f); - const arg = Held.isSome(wrap.inner); + const arg = args[1]; const args2: rt.Fmt[] = [_35, (f: rt.Formatter) => rt.fmtBool(arg, f)]; Log.note(log, rt.fmtFormat(["not bailed ", args2[0], " ", args2[1]])); unwind = 27; @@ -713,11 +724,11 @@ export class heldFuture { const result: rt.u64 | undefined = _36; rt.drop(this.#awaitee); const value: rt.u64 = rt.optionUnwrapOr(result, 0); - [this.#held.length, Held.isSome(this.#wrap.inner.value), this.#id] as [rt.usize, boolean, rt.u32]; + const args: [rt.usize, boolean, rt.u32] = [this.#held.length, Held.isSome(this.#wrap.inner.value), this.#id]; const arg = this.#id; const _59: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg, f); const _60: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(this.#held.length, f); - const arg2 = Held.isSome(this.#wrap.inner.value); + const arg2 = args[1]; const args2: rt.Fmt[] = [_59, _60, (f: rt.Formatter) => rt.fmtBool(arg2, f)]; const _46: string = rt.fmtFormat(["g", args2[0], " held ", args2[1], " ", args2[2]]); Log.note(this.#log, _46); @@ -944,9 +955,9 @@ export function ordered(log: Log.Log, id: rt.u32, at: rt.u8): void { const _137: Guard.Guard = rt.entryOrInsert(_138, _143, rt.drop); unwind = 147; _298 = false; - [kept, Guard.id(_137)] as [rt.u32, rt.u32]; + const args9: [rt.u32, rt.u32] = [kept, Guard.id(_137)]; const _154: rt.Fmt = (f: rt.Formatter) => rt.u32Display(kept, f); - const arg5 = Guard.id(_137); + const arg5 = args9[1]; const args10: rt.Fmt[] = [_154, (f: rt.Formatter) => rt.u32Display(arg5, f)]; Log.note(log, rt.fmtFormat(["or_insert ", args10[0], " ", args10[1]])); _160 = key(8); @@ -1004,10 +1015,10 @@ export function ordered(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.btreeClear(map, rt.drop, rt.drop); rt.btreeClear(set, rt.drop); check(6); - [rt.btreeLen(map), rt.btreeLen(set), queue.n] as [rt.usize, rt.usize, rt.usize]; - const arg9 = rt.btreeLen(map); + const args17: [rt.usize, rt.usize, rt.usize] = [rt.btreeLen(map), rt.btreeLen(set), queue.n]; + const arg9 = args17[0]; const _280: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg9, f); - const arg10 = rt.btreeLen(set); + const arg10 = args17[1]; const args18: rt.Fmt[] = [_280, (f: rt.Formatter) => rt.usizeDisplay(arg10, f), (f: rt.Formatter) => rt.usizeDisplay(queue.n, f)]; Log.note(log, rt.fmtFormat(["left ", args18[0], " ", args18[1], " ", args18[2]])); unwind = 144; @@ -1305,9 +1316,9 @@ export function hashed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _122: Guard.Guard = rt.entryOrInsert(_123, _128, rt.drop); unwind = 161; _302 = false; - [kept, Guard.id(_122)] as [rt.u32, rt.u32]; + const args3: [rt.u32, rt.u32] = [kept, Guard.id(_122)]; const _139: rt.Fmt = (f: rt.Formatter) => rt.u32Display(kept, f); - const arg2 = Guard.id(_122); + const arg2 = args3[1]; const args4: rt.Fmt[] = [_139, (f: rt.Formatter) => rt.u32Display(arg2, f)]; Log.note(log, rt.fmtFormat(["or_insert ", args4[0], " ", args4[1]])); tally("or_insert"); @@ -1667,14 +1678,14 @@ export function options(log: Log.Log, id: rt.u32, at: rt.u8): void { error = rt.resultUnwrapOr(_105, _109, rt.drop, rt.drop); unwind = 105; _213 = false; - [Guard.id(kept), Guard.id(fallback), Guard.id(value), Guard.id(error)] as [rt.u32, rt.u32, rt.u32, rt.u32]; - const arg4 = Guard.id(kept); + const args5: [rt.u32, rt.u32, rt.u32, rt.u32] = [Guard.id(kept), Guard.id(fallback), Guard.id(value), Guard.id(error)]; + const arg4 = args5[0]; const _130: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg4, f); - const arg5 = Guard.id(fallback); + const arg5 = args5[1]; const _131: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg5, f); - const arg6 = Guard.id(value); + const arg6 = args5[2]; const _132: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg6, f); - const arg7 = Guard.id(error); + const arg7 = args5[3]; const args6: rt.Fmt[] = [_130, _131, _132, (f: rt.Formatter) => rt.u32Display(arg7, f)]; Log.note(log, rt.fmtFormat(["unwrap_or ", args6[0], " ", args6[1], " ", args6[2], " ", args6[3]])); check(3); @@ -1687,10 +1698,10 @@ export function options(log: Log.Log, id: rt.u32, at: rt.u8): void { return Guard.new(n3, Log.clone$Clone(log)); }, rt.drop); unwind = 103; - [Guard.id(mapped), Guard.id(unmapped)] as [rt.u32, rt.u32]; - const arg8 = Guard.id(mapped); + const args7: [rt.u32, rt.u32] = [Guard.id(mapped), Guard.id(unmapped)]; + const arg8 = args7[0]; const _163: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg8, f); - const arg9 = Guard.id(unmapped); + const arg9 = args7[1]; const args8: rt.Fmt[] = [_163, (f: rt.Formatter) => rt.u32Display(arg9, f)]; Log.note(log, rt.fmtFormat(["map_or ", args8[0], " ", args8[1]])); check(4); diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts new file mode 100644 index 000000000..5e31be067 --- /dev/null +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -0,0 +1,2232 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import { drop$Guard_Guard, drop$Guard_u32, drop$Key_Guard, drop$Option_Key_Guard, drop$Option_u32_Bomb, drop$Result_Vec_Guard_Guard, drop$Vec_Bomb, drop$Vec_Guard, drop$u32_Bomb, drop$u32_Guard } from "../lib.ts"; +import * as Bomb from "../drops.Bomb.ts"; +import * as Key from "../drops.Key.ts"; +import * as Log from "../log.Log.ts"; +import * as Guard from "../model.Guard.ts"; + +/** + * What `for` leaves of what it iterates, and what adaptors discard, hold, and return, + * panicking at point `at`, if any, some inside an adaptor's closure. + */ +export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { + let v!: Guard.Guard[]; + let iterS!: Guard.Guard[]; + let iterI!: number; + let g!: Guard.Guard; + let _39!: Guard.Guard; + let _42!: Guard.Guard; + let iter2!: rt.Iter; + let g2!: Guard.Guard; + let iter3!: rt.Iter; + let g3!: Guard.Guard; + let even!: Guard.Guard[]; + let v2!: Guard.Guard[]; + let rest!: rt.Iter; + let v3!: Guard.Guard[]; + let peek!: rt.Peekable; + let v4!: Guard.Guard[]; + let first!: Guard.Guard | undefined; + let second!: Guard.Guard | undefined; + let _237!: rt.Iter; + let v5!: Guard.Guard[]; + let v6!: Guard.Guard[]; + let nth!: Guard.Guard | undefined; + let _275!: rt.Iter; + let _277!: rt.Iter; + let v7!: Guard.Guard[]; + let v8!: Guard.Guard[]; + let best!: Guard.Guard | undefined; + let v9!: Guard.Guard[]; + let found!: Guard.Guard | undefined; + let _333!: rt.Iter; + let v10!: Array; + let v11!: Guard.Guard[]; + let v12!: Guard.Guard[]; + let flat!: rt.Iter; + let v13!: Guard.Guard[][]; + let v14!: Guard.Guard[]; + let v15!: Guard.Guard[]; + let v16!: Guard.Guard[]; + let _510!: boolean; + let _511!: boolean; + let _512!: boolean; + let _513!: boolean; + let _514!: boolean; + let _515!: boolean; + let _516!: boolean; + let unwind: number = 0; + try { + _516 = false; + _515 = false; + _514 = false; + _512 = false; + _513 = false; + _511 = false; + _510 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args24[0], " at ", args24[1]]); + } + }; + v = []; + unwind = 274; + const _14: Guard.Guard = guard(1); + v.push(_14); + const _19: Guard.Guard = guard(2); + v.push(_19); + const _24: Guard.Guard = guard(3); + v.push(_24); + unwind = 0; + iterS = v; + iterI = 0; + while (true) { + unwind = 273; + const _28: Guard.Guard | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_28 === rt.DONE) { + break; + } + unwind = 272; + g = _28; + if (!(Guard.id(g) === rt.u32Add(id, 2))) { + unwind = 273; + rt.drop(g); + } else { + unwind = 273; + rt.drop(g); + break; + } + } + unwind = 0; + rt.dropAll(iterS, rt.drop, iterI); + _39 = guard(4); + unwind = 271; + _42 = guard(5); + unwind = 270; + const _45: Guard.Guard = guard(6); + unwind = 0; + iter2 = rt.iterSlice([_39, _42, _45], rt.drop); + while (true) { + unwind = 269; + const _49: Guard.Guard | rt.Done = iter2.next(); + if (_49 === rt.DONE) { + break; + } + unwind = 268; + g2 = _49; + const arg = ([Guard.id(g2)] as [rt.u32])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; + Log.note(log, rt.fmtFormat(["array ", args2[0]])); + if (Guard.id(g2) === rt.u32Add(id, 5)) { + check(1); + } + unwind = 269; + rt.drop(g2); + } + unwind = 0; + rt.drop(iter2); + iter3 = rt.iterOption(guard(7), rt.drop); + while (true) { + unwind = 267; + const _79: Guard.Guard | rt.Done = iter3.next(); + if (_79 === rt.DONE) { + break; + } + unwind = 266; + g3 = _79; + const arg2 = ([Guard.id(g3)] as [rt.u32])[0]; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; + Log.note(log, rt.fmtFormat(["option ", args4[0]])); + unwind = 267; + rt.drop(g3); + } + unwind = 0; + rt.drop(iter3); + v2 = []; + unwind = 265; + const _102: Guard.Guard = guard(8); + v2.push(_102); + const _107: Guard.Guard = guard(9); + v2.push(_107); + const _112: Guard.Guard = guard(10); + v2.push(_112); + const _117: Guard.Guard = guard(11); + v2.push(_117); + unwind = 0; + even = rt.iterToArray(rt.iterFilter(rt.iterSlice(v2, rt.drop), (g4: Guard.Guard): boolean => { + if (Guard.id(g4) === rt.u32Add(id, 10)) { + check(2); + } + return rt.u32Rem(Guard.id(g4), 2) === 0; + }, rt.drop), true, rt.drop, rt.drop); + unwind = 264; + const arg3 = ([even.length] as [rt.usize])[0]; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; + Log.note(log, rt.fmtFormat(["even ", args6[0]])); + v3 = []; + unwind = 263; + const _142: Guard.Guard = guard(12); + v3.push(_142); + const _147: Guard.Guard = guard(13); + v3.push(_147); + const _152: Guard.Guard = guard(14); + v3.push(_152); + const _157: Guard.Guard = guard(15); + v3.push(_157); + const _162: Guard.Guard = guard(16); + v3.push(_162); + unwind = 264; + rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); + unwind = 289; + _516 = true; + const arg4 = ([rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { + let unwind2: number = 0; + try { + unwind2 = 4; + const _03: rt.u32 = Guard.id(g5); + unwind2 = 0; + rt.drop(g5); + return _03; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(g5); + throw e2; + } + })] as [rt.u32])[0]; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; + Log.note(log, rt.fmtFormat(["next ", args8[0]])); + check(3); + _516 = false; + const arg5 = ([rt.iterCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; + Log.note(log, rt.fmtFormat(["count ", args10[0]])); + v4 = []; + unwind = 262; + const _199: Guard.Guard = guard(17); + v4.push(_199); + const _204: Guard.Guard = guard(18); + v4.push(_204); + unwind = 289; + peek = rt.iterPeekable(rt.iterSlice(v4, rt.drop), rt.drop); + unwind = 287; + _515 = true; + first = rt.peekableNextIf(peek, (g6: Guard.Guard): boolean => { + return Guard.id(g6) === rt.u32Add(id, 17); + }); + unwind = 261; + second = rt.peekableNextIf(peek, (g7: Guard.Guard): boolean => { + return Guard.id(g7) === rt.u32Add(id, 99); + }); + unwind = 260; + [first !== undefined, second !== undefined] as [boolean, boolean]; + const arg6 = first !== undefined; + const _227: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(arg6, f); + const arg7 = second !== undefined; + const args12: rt.Fmt[] = [_227, (f: rt.Formatter) => rt.fmtBool(arg7, f)]; + Log.note(log, rt.fmtFormat(["peek ", args12[0], " ", args12[1]])); + check(4); + _515 = false; + rt.drop(peek); + v5 = []; + unwind = 259; + const _242: Guard.Guard = guard(20); + v5.push(_242); + const _247: Guard.Guard = guard(21); + v5.push(_247); + const _252: Guard.Guard = guard(22); + v5.push(_252); + unwind = 260; + _237 = rt.iterSlice(v5, rt.drop); + unwind = 285; + _514 = true; + v6 = []; + unwind = 258; + const _259: Guard.Guard = guard(23); + v6.push(_259); + unwind = 285; + const _255: Guard.Guard[] = v6; + _514 = false; + const pairs: rt.Iter<[Guard.Guard, Guard.Guard]> = rt.iterZip(_237, rt.iterSlice(_255, rt.drop), false, rt.drop, rt.drop); + unwind = 260; + _514 = false; + const arg8 = ([rt.iterCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg8, f)]; + Log.note(log, rt.fmtFormat(["zip ", args14[0]])); + v7 = []; + unwind = 257; + const _282: Guard.Guard = guard(24); + v7.push(_282); + unwind = 260; + _277 = rt.iterSlice(v7, rt.drop); + unwind = 283; + _513 = true; + v8 = []; + unwind = 256; + const _289: Guard.Guard = guard(25); + v8.push(_289); + const _294: Guard.Guard = guard(26); + v8.push(_294); + unwind = 283; + const _285: Guard.Guard[] = v8; + _513 = false; + const _276: rt.Iter = rt.iterChain(_277, rt.iterSlice(_285, rt.drop)); + unwind = 260; + _513 = false; + _275 = rt.iterRev(_276); + unwind = 255; + nth = rt.iterNth(_275, 1, rt.drop); + unwind = 281; + _512 = true; + rt.drop(_275); + _512 = false; + const arg9 = ([rt.optionMapOr(nth, 0, (g8: Guard.Guard): rt.u32 => { + let unwind3: number = 0; + try { + unwind3 = 4; + const _06: rt.u32 = Guard.id(g8); + unwind3 = 0; + rt.drop(g8); + return _06; + } catch (e3) { + if (unwind3 === 0) { + throw e3; + } + rt.drop(g8); + throw e3; + } + })] as [rt.u32])[0]; + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg9, f)]; + Log.note(log, rt.fmtFormat(["nth ", args16[0]])); + check(5); + v9 = []; + unwind = 254; + const _318: Guard.Guard = guard(27); + v9.push(_318); + const _323: Guard.Guard = guard(28); + v9.push(_323); + const _328: Guard.Guard = guard(29); + v9.push(_328); + unwind = 281; + best = rt.iterMaxByKey(rt.iterSlice(v9, rt.drop), (g9: Guard.Guard): rt.u32 => { + return rt.u32Rem(Guard.id(g9), 2); + }, rt.drop, rt.drop); + unwind = 279; + _511 = true; + v10 = []; + unwind = 253; + const _339: Guard.Guard | undefined = guard(30); + v10.push(_339); + v10.push(undefined); + const _348: Guard.Guard | undefined = guard(31); + v10.push(_348); + const _354: Guard.Guard | undefined = guard(32); + v10.push(_354); + unwind = 279; + _333 = rt.iterFlatten(rt.iterSlice(v10, rt.drop), (value: Guard.Guard | undefined) => rt.iterOption(value, rt.drop), true); + unwind = 252; + found = rt.iterFind(_333, (g10: Guard.Guard): boolean => { + return Guard.id(g10) === rt.u32Add(id, 31); + }, rt.drop); + unwind = 251; + rt.drop(_333); + _511 = false; + const args17: [rt.u32, boolean] = [rt.optionMapOr(best, 0, (g11: Guard.Guard): rt.u32 => { + let unwind4: number = 0; + try { + unwind4 = 4; + const _09: rt.u32 = Guard.id(g11); + unwind4 = 0; + rt.drop(g11); + return _09; + } catch (e4) { + if (unwind4 === 0) { + throw e4; + } + rt.drop(g11); + throw e4; + } + }), found !== undefined]; + const arg10 = args17[0]; + const _372: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg10, f); + const arg11 = found !== undefined; + const args18: rt.Fmt[] = [_372, (f: rt.Formatter) => rt.fmtBool(arg11, f)]; + Log.note(log, rt.fmtFormat(["found ", args18[0], " ", args18[1]])); + check(6); + v11 = []; + unwind = 250; + const _385: Guard.Guard = guard(33); + v11.push(_385); + const _390: Guard.Guard = guard(34); + v11.push(_390); + const _395: Guard.Guard = guard(35); + v11.push(_395); + unwind = 251; + const folded: rt.u32 = rt.iterFold(rt.iterSlice(v11, rt.drop), 0, (n2: rt.u32, g12: Guard.Guard): rt.u32 => { + let unwind5: number = 0; + try { + unwind5 = 10; + if (Guard.id(g12) === rt.u32Add(id, 34)) { + check(7); + } + const _173: rt.u32 = rt.u32Sub(rt.u32Add(n2, Guard.id(g12)), id); + unwind5 = 0; + rt.drop(g12); + return _173; + } catch (e5) { + if (unwind5 === 0) { + throw e5; + } + rt.drop(g12); + throw e5; + } + }, rt.drop); + v12 = []; + unwind = 249; + const _408: Guard.Guard = guard(36); + v12.push(_408); + const _413: Guard.Guard = guard(37); + v12.push(_413); + const _418: Guard.Guard = guard(38); + v12.push(_418); + unwind = 251; + const args19: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { + let unwind6: number = 0; + try { + unwind6 = 4; + const _011: rt.u32 = Guard.id(g13); + unwind6 = 0; + rt.drop(g13); + return _011; + } catch (e6) { + if (unwind6 === 0) { + throw e6; + } + rt.drop(g13); + throw e6; + } + }), folded]; + const _430: rt.Fmt = (f: rt.Formatter) => rt.u32Display(folded, f); + const arg12 = args19[0]; + const args20: rt.Fmt[] = [_430, (f: rt.Formatter) => rt.u32Display(arg12, f)]; + Log.note(log, rt.fmtFormat(["fold ", args20[0], " ", args20[1]])); + v13 = []; + unwind = 248; + v14 = []; + unwind = 247; + const _444: Guard.Guard = guard(39); + v14.push(_444); + const _449: Guard.Guard = guard(40); + v14.push(_449); + unwind = 248; + v13.push(v14); + v15 = []; + unwind = 246; + const _458: Guard.Guard = guard(41); + v15.push(_458); + unwind = 248; + v13.push(v15); + v16 = []; + unwind = 245; + const _467: Guard.Guard = guard(42); + v16.push(_467); + const _472: Guard.Guard = guard(43); + v16.push(_472); + unwind = 248; + v13.push(v16); + unwind = 251; + flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); + unwind = 277; + _510 = true; + const args21: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { + let unwind7: number = 0; + try { + unwind7 = 4; + const _012: rt.u32 = Guard.id(g14); + unwind7 = 0; + rt.drop(g14); + return _012; + } catch (e7) { + if (unwind7 === 0) { + throw e7; + } + rt.drop(g14); + throw e7; + } + }), rt.optionMapOr(rt.iterToOption(flat.nextBack()), 0, (g15: Guard.Guard): rt.u32 => { + let unwind8: number = 0; + try { + unwind8 = 4; + const _013: rt.u32 = Guard.id(g15); + unwind8 = 0; + rt.drop(g15); + return _013; + } catch (e8) { + if (unwind8 === 0) { + throw e8; + } + rt.drop(g15); + throw e8; + } + })]; + const arg13 = args21[0]; + const _489: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg13, f); + const arg14 = args21[1]; + const args22: rt.Fmt[] = [_489, (f: rt.Formatter) => rt.u32Display(arg14, f)]; + Log.note(log, rt.fmtFormat(["flat ", args22[0], " ", args22[1]])); + _510 = false; + rt.drop(flat); + unwind = 279; + _510 = false; + rt.drop(found); + unwind = 261; + _511 = false; + _512 = false; + rt.drop(second); + unwind = 287; + rt.drop(first); + unwind = 0; + _515 = false; + _516 = false; + rt.dropAll(even); + } catch (e) { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + b19: { + b20: { + b21: { + if (unwind === 0) { + throw e; + } + if (unwind === 245) { + rt.dropAll(v16); + break b16; + } + if (unwind === 246) { + rt.dropAll(v15); + break b16; + } + if (unwind === 247) { + rt.dropAll(v14); + break b16; + } + if (unwind === 248) { + break b16; + } + if (unwind === 249) { + rt.dropAll(v12); + break b15; + } + if (unwind === 250) { + rt.dropAll(v11); + break b15; + } + if (unwind === 251) { + break b15; + } + if (unwind === 252) { + rt.drop(_333); + break b14; + } + if (unwind === 253) { + rt.dropAll(v10); + break b14; + } + if (unwind === 254) { + rt.dropAll(v9); + break b13; + } + if (unwind === 255) { + rt.drop(_275); + break b12; + } + if (unwind === 256) { + rt.dropAll(v8); + break b17; + } + if (unwind === 257) { + rt.dropAll(v7); + break b12; + } + if (unwind === 258) { + rt.dropAll(v6); + break b18; + } + if (unwind === 259) { + rt.dropAll(v5); + break b12; + } + if (unwind === 260) { + break b12; + } + if (unwind === 261) { + break b11; + } + if (unwind === 262) { + rt.dropAll(v4); + break b9; + } + if (unwind === 263) { + rt.dropAll(v3); + break b8; + } + if (unwind === 264) { + break b8; + } + if (unwind === 265) { + rt.dropAll(v2); + break b7; + } + if (unwind === 266) { + rt.drop(g3); + break b19; + } + if (unwind === 267) { + break b19; + } + if (unwind === 268) { + rt.drop(g2); + break b20; + } + if (unwind === 269) { + break b20; + } + if (unwind === 270) { + rt.drop(_42); + break b21; + } + if (unwind === 271) { + break b21; + } + if (unwind === 272) { + rt.drop(g); + } else if (unwind !== 273) { + if (unwind === 274) { + rt.dropAll(v); + break b7; + } + if (unwind === 277) { + if (!_510) { + break b15; + } + rt.drop(flat); + break b15; + } + if (unwind === 279) { + break b14; + } + if (unwind === 281) { + break b13; + } + if (unwind === 283) { + break b17; + } + if (unwind === 285) { + break b18; + } + if (unwind === 287) { + break b10; + } + break b9; + } + rt.dropAll(iterS, rt.drop, iterI); + break b7; + } + rt.drop(_39); + break b7; + } + rt.drop(iter2); + break b7; + } + rt.drop(iter3); + break b7; + } + if (!_514) { + break b12; + } + rt.drop(_237); + break b12; + } + if (!_513) { + break b12; + } + rt.drop(_277); + break b12; + } + rt.dropAll(v13, drop$Vec_Guard); + } + rt.drop(found); + } + if (_511) { + rt.drop(best); + } + } + if (_512) { + rt.drop(nth); + } + } + rt.drop(second); + } + rt.drop(first); + } + if (_515) { + rt.drop(peek); + } + } + if (_516) { + rt.drop(rest); + } + } + rt.dropAll(even); + } + throw e; + } +} + +/** + * What `collect` drops: in place of the `Vec` its items come from, what it collected + * before the rest of the source as a panic unwinds, and else the source first; the + * values before the first `Err` or `None`, and the rest; and of equal keys, the one a + * map or set does not keep. + */ +export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { + let same!: Guard.Guard[]; + let v!: Guard.Guard[]; + let wider!: [Guard.Guard, rt.u32][]; + let v2!: Guard.Guard[]; + let chained!: Guard.Guard[]; + let _60!: rt.Iter; + let v3!: Guard.Guard[]; + let v4!: Guard.Guard[]; + let results!: rt.Result; + let v5!: Guard.Guard[]; + let v6!: Guard.Guard[]; + let tree!: rt.BTreeMap; + let v7!: [rt.u32, Guard.Guard][]; + let queue!: rt.VecDeque; + let v8!: Guard.Guard[]; + let hashed!: rt.HashMap; + let v9!: [rt.u32, Guard.Guard][]; + let set!: rt.HashSet; + let v10!: Key.Key[]; + let _291!: boolean; + let _292!: boolean; + let unwind: number = 0; + try { + _292 = false; + _291 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const key: (a0: rt.u32) => Key.Key = (n2: rt.u32): Key.Key => { + return Key.new(rt.u32Add(id, n2), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args12[0], " at ", args12[1]]); + } + }; + v = []; + unwind = 149; + const _18: Guard.Guard = guard(1); + v.push(_18); + const _23: Guard.Guard = guard(2); + v.push(_23); + const _28: Guard.Guard = guard(3); + v.push(_28); + unwind = 0; + same = rt.iterToArray(rt.iterMap(rt.iterSlice(v, rt.drop), (g: Guard.Guard): Guard.Guard => { + let unwind2: number = 0; + try { + unwind2 = 6; + if (Guard.id(g) === rt.u32Add(id, 2)) { + check(1); + return g; + } + return g; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(g); + throw e2; + } + }), true, rt.drop, rt.drop); + unwind = 148; + v2 = []; + unwind = 147; + const _41: Guard.Guard = guard(4); + v2.push(_41); + const _46: Guard.Guard = guard(5); + v2.push(_46); + const _51: Guard.Guard = guard(6); + v2.push(_51); + unwind = 148; + wider = rt.iterToArray(rt.iterMap(rt.iterSlice(v2, rt.drop), (g2: Guard.Guard): [Guard.Guard, rt.u32] => { + let unwind3: number = 0; + try { + unwind3 = 6; + if (Guard.id(g2) === rt.u32Add(id, 5)) { + check(2); + } + return [g2, 0] as [Guard.Guard, rt.u32]; + } catch (e3) { + if (unwind3 === 0) { + throw e3; + } + rt.drop(g2); + throw e3; + } + }), false, rt.drop, drop$Guard_u32); + unwind = 146; + v3 = []; + unwind = 145; + const _65: Guard.Guard = guard(7); + v3.push(_65); + unwind = 146; + _60 = rt.iterSlice(v3, rt.drop); + unwind = 154; + _292 = true; + v4 = []; + unwind = 144; + const _72: Guard.Guard = guard(8); + v4.push(_72); + const _77: Guard.Guard = guard(9); + v4.push(_77); + unwind = 154; + const _68: Guard.Guard[] = v4; + _292 = false; + const _59: rt.Iter = rt.iterChain(_60, rt.iterSlice(_68, rt.drop)); + unwind = 146; + _292 = false; + chained = rt.iterToArray(rt.iterMap(_59, (g3: Guard.Guard): Guard.Guard => { + let unwind4: number = 0; + try { + unwind4 = 6; + if (Guard.id(g3) === rt.u32Add(id, 8)) { + check(3); + return g3; + } + return g3; + } catch (e4) { + if (unwind4 === 0) { + throw e4; + } + rt.drop(g3); + throw e4; + } + }), false, rt.drop, rt.drop); + unwind = 143; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(same.length, f), (f: rt.Formatter) => rt.usizeDisplay(wider.length, f), (f: rt.Formatter) => rt.usizeDisplay(chained.length, f)]; + Log.note(log, rt.fmtFormat(["vecs ", args2[0], " ", args2[1], " ", args2[2]])); + v5 = []; + unwind = 142; + const _110: Guard.Guard = guard(10); + v5.push(_110); + const _115: Guard.Guard = guard(11); + v5.push(_115); + const _120: Guard.Guard = guard(12); + v5.push(_120); + unwind = 143; + results = rt.iterCollectResult(rt.iterMap(rt.iterSlice(v5, rt.drop), (g4: Guard.Guard): rt.Result => { + let unwind5: number = 0; + try { + unwind5 = 7; + if (!(Guard.id(g4) === rt.u32Add(id, 11))) { + return rt.Ok(g4); + } + return rt.Err(g4); + } catch (e5) { + if (unwind5 === 0) { + throw e5; + } + rt.drop(g4); + throw e5; + } + }), (values: rt.Iter) => rt.iterToArray(values, true, rt.drop, rt.drop), drop$Vec_Guard, rt.drop); + unwind = 152; + _291 = true; + const arg = ([results.ok] as [boolean])[0]; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg, f)]; + Log.note(log, rt.fmtFormat(["result ", args4[0]])); + _291 = false; + drop$Result_Vec_Guard_Guard(results); + v6 = []; + unwind = 141; + const _146: Guard.Guard = guard(13); + v6.push(_146); + const _151: Guard.Guard = guard(14); + v6.push(_151); + const _156: Guard.Guard = guard(15); + v6.push(_156); + unwind = 152; + const arg2 = ([rt.optionMapOr(rt.iterCollectOption(rt.iterMap(rt.iterSlice(v6, rt.drop), (g5: Guard.Guard): Guard.Guard | undefined => { + let unwind6: number = 0; + try { + unwind6 = 6; + if (Guard.id(g5) === rt.u32Add(id, 14)) { + check(4); + return g5; + } + return g5; + } catch (e6) { + if (unwind6 === 0) { + throw e6; + } + rt.drop(g5); + throw e6; + } + }), (values: rt.Iter) => rt.iterToArray(values, true, rt.drop, rt.drop), drop$Vec_Guard), 0, (v11: Guard.Guard[]): rt.usize => { + let unwind7: number = 0; + try { + unwind7 = 4; + const _08: rt.usize = v11.length; + unwind7 = 0; + rt.dropAll(v11); + return _08; + } catch (e7) { + if (unwind7 === 0) { + throw e7; + } + rt.dropAll(v11); + throw e7; + } + })] as [rt.usize])[0]; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg2, f)]; + Log.note(log, rt.fmtFormat(["option ", args6[0]])); + v7 = []; + unwind = 140; + const _179: [rt.u32, Guard.Guard] = [2, guard(16)]; + v7.push(_179); + const _185: [rt.u32, Guard.Guard] = [1, guard(17)]; + v7.push(_185); + const _191: [rt.u32, Guard.Guard] = [2, guard(18)]; + v7.push(_191); + unwind = 152; + const _174: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterSlice(v7, drop$u32_Guard); + tree = rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_174, true, rt.drop, drop$u32_Guard), undefined, rt.drop); + unwind = 139; + const arg3 = ([rt.btreeLen(tree)] as [rt.usize])[0]; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; + Log.note(log, rt.fmtFormat(["tree ", args8[0]])); + check(5); + v8 = []; + unwind = 138; + const _217: Guard.Guard = guard(19); + v8.push(_217); + const _222: Guard.Guard = guard(20); + v8.push(_222); + unwind = 139; + const _211: rt.Iter = rt.iterMap(rt.iterSlice(v8, rt.drop), (g6: Guard.Guard): Guard.Guard => { + let unwind8: number = 0; + try { + unwind8 = 6; + if (Guard.id(g6) === rt.u32Add(id, 20)) { + check(6); + return g6; + } + return g6; + } catch (e8) { + if (unwind8 === 0) { + throw e8; + } + rt.drop(g6); + throw e8; + } + }); + queue = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, rt.iterSlice(rt.iterToArray(_211, true, rt.drop, rt.drop))); + unwind = 137; + v9 = []; + unwind = 136; + const _235: [rt.u32, Guard.Guard] = [1, guard(21)]; + v9.push(_235); + const _241: [rt.u32, Guard.Guard] = [1, guard(22)]; + v9.push(_241); + unwind = 137; + const _229: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterMap(rt.iterSlice(v9, drop$u32_Guard), (e9: [rt.u32, Guard.Guard]): [rt.u32, Guard.Guard] => { + let unwind9: number = 0; + try { + unwind9 = 6; + if (Guard.id(e9[1]) === rt.u32Add(id, 22)) { + check(7); + return e9; + } + return e9; + } catch (e10) { + if (unwind9 === 0) { + throw e10; + } + drop$u32_Guard(e9); + throw e10; + } + }); + hashed = rt.hashExtend(rt.hashNew() as rt.HashMap, _229, undefined, rt.drop, rt.drop, true); + unwind = 135; + v10 = []; + unwind = 134; + const _254: Key.Key = key(23); + v10.push(_254); + const _259: Key.Key = key(23); + v10.push(_259); + unwind = 135; + const _249: rt.Iter = rt.iterSlice(v10, rt.drop); + set = rt.hashExtendKeys(rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashSet, _249, rt.drop, rt.drop, true); + unwind = 133; + const args9: [rt.usize, rt.usize, rt.usize] = [queue.n, rt.hashLen(hashed), rt.hashLen(set)]; + const _277: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(queue.n, f); + const arg4 = args9[1]; + const _278: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg4, f); + const arg5 = args9[2]; + const args10: rt.Fmt[] = [_277, _278, (f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; + Log.note(log, rt.fmtFormat(["collected ", args10[0], " ", args10[1], " ", args10[2]])); + unwind = 135; + rt.hashDrop(set, rt.drop); + unwind = 137; + rt.hashDrop(hashed, undefined, rt.drop); + unwind = 139; + rt.dequeDrop(queue, rt.drop); + unwind = 152; + rt.btreeDrop(tree, undefined, rt.drop); + unwind = 146; + _291 = false; + rt.dropAll(chained); + unwind = 148; + rt.dropAll(wider, drop$Guard_u32); + unwind = 0; + rt.dropAll(same); + } catch (e) { + b0: { + b1: { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + if (unwind === 0) { + throw e; + } + if (unwind === 133) { + rt.hashDrop(set, rt.drop); + break b7; + } + if (unwind === 134) { + rt.dropAll(v10); + break b7; + } + if (unwind === 135) { + break b7; + } + if (unwind === 136) { + rt.dropAll(v9, drop$u32_Guard); + break b6; + } + if (unwind === 137) { + break b6; + } + if (unwind === 138) { + rt.dropAll(v8); + break b5; + } + if (unwind === 139) { + break b5; + } + if (unwind === 140) { + rt.dropAll(v7, drop$u32_Guard); + break b4; + } + if (unwind === 141) { + rt.dropAll(v6); + break b4; + } + if (unwind === 142) { + rt.dropAll(v5); + break b3; + } + if (unwind === 143) { + break b3; + } + if (unwind === 144) { + rt.dropAll(v4); + } else { + if (unwind === 145) { + rt.dropAll(v3); + break b2; + } + if (unwind === 146) { + break b2; + } + if (unwind === 147) { + rt.dropAll(v2); + break b1; + } + if (unwind === 148) { + break b1; + } + if (unwind === 149) { + rt.dropAll(v); + break b0; + } + if (unwind === 152) { + break b4; + } + } + if (!_292) { + break b2; + } + rt.drop(_60); + break b2; + } + rt.hashDrop(hashed, undefined, rt.drop); + } + rt.dequeDrop(queue, rt.drop); + } + rt.btreeDrop(tree, undefined, rt.drop); + } + if (_291) { + drop$Result_Vec_Guard_Guard(results); + } + } + rt.dropAll(chained); + } + rt.dropAll(wider, drop$Guard_u32); + } + rt.dropAll(same); + } + throw e; + } +} + +/** + * What draining a collection drops: the items taken, the half of each entry + * `into_keys` or `into_values` leaves, and what is left when the iterator drops, as a + * panic may drop it. + */ +export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { + let it!: rt.Iter<[Key.Key, Guard.Guard]>; + let first!: [Key.Key, Guard.Guard] | undefined; + let back!: [Key.Key, Guard.Guard] | undefined; + let keys!: Key.Key[]; + let values!: rt.Iter; + let set!: rt.BTreeSet; + let _85!: rt.Iter; + let queue!: rt.VecDeque; + let _95!: rt.u32; + let range!: rt.Iter; + let _137!: rt.Iter; + let map!: rt.HashMap; + let _147!: Key.Key; + let entries!: rt.Iter<[Key.Key, Guard.Guard]>; + let _166!: [Key.Key, Guard.Guard] | undefined; + let map2!: rt.HashMap; + let _175!: Key.Key; + let set2!: rt.HashSet; + let taken!: rt.Iter; + let sink!: Log.Log; + let map3!: rt.HashMap; + let _225!: rt.u32; + let values2!: rt.Iter; + let one!: Guard.Guard | undefined; + let _290!: boolean; + let _291!: boolean; + let _292!: boolean; + let _293!: boolean; + let _294!: boolean; + let _295!: boolean; + let _296!: boolean; + let _297!: boolean; + let _298!: boolean; + let _299!: boolean; + let _300!: boolean; + let _301!: boolean; + let _302!: boolean; + let unwind: number = 0; + try { + _302 = false; + _301 = false; + _300 = false; + _299 = false; + _298 = false; + _297 = false; + _296 = false; + _295 = false; + _294 = false; + _293 = false; + _292 = false; + _291 = false; + _290 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n3: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n3), Log.clone$Clone(log)); + }; + const key: (a0: rt.u32) => Key.Key = (n4: rt.u32): Key.Key => { + return Key.new(rt.u32Add(id, n4), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args20[0], " at ", args20[1]]); + } + }; + const tree: (a0: rt.u32) => rt.BTreeMap = (base: rt.u32): rt.BTreeMap => { + let map4!: rt.BTreeMap; + let _9!: rt.u32; + let _153!: Key.Key; + let _21!: boolean; + let unwind2: number = 0; + try { + _21 = false; + map4 = rt.btreeNew(Key.cmp$Ord) as rt.BTreeMap; + unwind2 = 13; + const _67: rt.u32 = rt.u32Add(base, 4); + let iterStart3: rt.u32 = base; + const iterEnd3: rt.u32 = _67; + while (true) { + if (!((_9 = iterStart3++) < iterEnd3)) { + return map4; + } + const n5: rt.u32 = _9; + _153 = key(n5); + unwind2 = 16; + _21 = true; + const _172: Guard.Guard = guard(n5); + _21 = false; + const _132: Guard.Guard | undefined = rt.btreeInsert(map4, _153, _172, rt.drop, rt.drop); + unwind2 = 13; + _21 = false; + rt.drop(_132); + } + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + if (unwind2 !== 13) { + if (_21) { + rt.drop(_153); + } + } + rt.btreeDrop(map4, rt.drop, rt.drop); + throw e2; + } + }; + it = rt.btreeIter(tree(1), rt.drop, rt.drop); + unwind = 186; + _302 = true; + first = rt.iterToOption(it.next()); + unwind = 184; + _301 = true; + back = rt.iterToOption(it.nextBack()); + unwind = 182; + _300 = true; + _301 = false; + drop$Option_Key_Guard(first); + check(1); + _302 = false; + rt.drop(it); + _300 = false; + drop$Option_Key_Guard(back); + keys = rt.iterToArray(rt.btreeKeys(tree(5), rt.drop, rt.drop, true), false, rt.drop, rt.drop); + unwind = 159; + check(2); + values = rt.btreeValues(tree(9), rt.drop, rt.drop); + unwind = 180; + _299 = true; + const args: [rt.usize, rt.u32] = [keys.length, rt.optionMapOr(rt.iterToOption(values.next()), 0, (g: Guard.Guard): rt.u32 => { + let unwind3: number = 0; + try { + unwind3 = 4; + const _04: rt.u32 = Guard.id(g); + unwind3 = 0; + rt.drop(g); + return _04; + } catch (e3) { + if (unwind3 === 0) { + throw e3; + } + rt.drop(g); + throw e3; + } + })]; + const _56: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(keys.length, f); + const arg = args[1]; + const args2: rt.Fmt[] = [_56, (f: rt.Formatter) => rt.u32Display(arg, f)]; + Log.note(log, rt.fmtFormat(["values ", args2[0], " ", args2[1]])); + check(3); + _299 = false; + rt.drop(values); + set = rt.btreeNew(Key.cmp$Ord) as rt.BTreeSet; + unwind = 178; + _298 = true; + const _68: Key.Key = key(13); + rt.btreeAdd(set, _68, rt.drop); + const _73: Key.Key = key(14); + rt.btreeAdd(set, _73, rt.drop); + _298 = false; + _85 = rt.btreeKeys(set, rt.drop); + unwind = 158; + const arg2 = ([rt.optionMapOr(rt.iterToOption(_85.next()), 0, (k: Key.Key): rt.u32 => { + const _05: rt.u32 = k.id; + rt.drop(k); + return _05; + })] as [rt.u32])[0]; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; + const _78: string = rt.fmtFormat(["set ", args4[0]]); + unwind = 178; + rt.drop(_85); + Log.note(log, _78); + queue = rt.dequeNew() as rt.VecDeque; + unwind = 176; + _297 = true; + let iterStart: rt.u32 = 15; + const iterEnd: rt.u32 = 20; + while ((_95 = iterStart++) < iterEnd) { + const _101: Guard.Guard = guard(_95); + rt.dequePushBack(queue, _101); + } + range = rt.dequeDrain(queue, new rt.Range(1, 4), rt.drop); + unwind = 174; + _296 = true; + const arg3 = ([rt.optionMapOr(rt.iterToOption(range.next()), 0, (g2: Guard.Guard): rt.u32 => { + let unwind4: number = 0; + try { + unwind4 = 4; + const _06: rt.u32 = Guard.id(g2); + unwind4 = 0; + rt.drop(g2); + return _06; + } catch (e4) { + if (unwind4 === 0) { + throw e4; + } + rt.drop(g2); + throw e4; + } + })] as [rt.u32])[0]; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; + Log.note(log, rt.fmtFormat(["drain ", args6[0]])); + check(4); + _296 = false; + rt.drop(range); + const _131: rt.usize = queue.n; + _297 = false; + _137 = rt.dequeIter(queue, rt.drop); + unwind = 157; + const args7: [rt.usize, rt.u32] = [_131, rt.optionMapOr(rt.iterToOption(_137.next()), 0, (g3: Guard.Guard): rt.u32 => { + let unwind5: number = 0; + try { + unwind5 = 4; + const _07: rt.u32 = Guard.id(g3); + unwind5 = 0; + rt.drop(g3); + return _07; + } catch (e5) { + if (unwind5 === 0) { + throw e5; + } + rt.drop(g3); + throw e5; + } + })]; + const _140: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(_131, f); + const arg4 = args7[1]; + const args8: rt.Fmt[] = [_140, (f: rt.Formatter) => rt.u32Display(arg4, f)]; + const _127: string = rt.fmtFormat(["queue ", args8[0], " ", args8[1]]); + unwind = 174; + rt.drop(_137); + Log.note(log, _127); + map = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashMap; + unwind = 172; + _295 = true; + _147 = key(20); + unwind = 170; + _294 = true; + const _150: Guard.Guard = guard(20); + _294 = false; + const _145: Guard.Guard | undefined = rt.hashInsert(map, _147, _150, rt.drop, rt.drop); + unwind = 172; + _294 = false; + rt.drop(_145); + _295 = false; + entries = rt.hashIter(map, rt.drop, rt.drop); + unwind = 156; + check(5); + _166 = rt.iterToOption(entries.next()); + unwind = 155; + const arg5 = ([_166 !== undefined] as [boolean])[0]; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg5, f)]; + const _160: string = rt.fmtFormat(["entry ", args10[0]]); + unwind = 156; + drop$Option_Key_Guard(_166); + Log.note(log, _160); + map2 = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashMap; + unwind = 154; + _175 = key(21); + unwind = 168; + _293 = true; + const _178: Guard.Guard = guard(21); + _293 = false; + const _173: Guard.Guard | undefined = rt.hashInsert(map2, _175, _178, rt.drop, rt.drop); + unwind = 154; + _293 = false; + rt.drop(_173); + rt.drop(rt.hashDrain(map2, rt.drop, rt.drop)); + const arg6 = ([rt.hashLen(map2)] as [rt.usize])[0]; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg6, f)]; + Log.note(log, rt.fmtFormat(["drained ", args12[0]])); + set2 = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashSet; + unwind = 153; + const _199: Key.Key = key(22); + rt.hashAdd(set2, _199, rt.drop); + taken = rt.hashDrainKeys(set2, rt.drop); + unwind = 152; + check(6); + const arg7 = ([rt.optionMapOr(rt.iterToOption(taken.next()), 0, (k2: Key.Key): rt.u32 => { + const _08: rt.u32 = k2.id; + rt.drop(k2); + return _08; + })] as [rt.u32])[0]; + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg7, f)]; + Log.note(log, rt.fmtFormat(["taken ", args14[0]])); + sink = Log.new(); + unwind = 151; + map3 = rt.hashNew() as rt.HashMap; + unwind = 166; + _292 = true; + let iterStart2: rt.u32 = 23; + const iterEnd2: rt.u32 = 27; + while ((_225 = iterStart2++) < iterEnd2) { + const n2: rt.u32 = _225; + const _231: Guard.Guard = Guard.new(rt.u32Add(id, n2), Log.clone$Clone(sink)); + rt.drop(rt.hashInsert(map3, n2, _231, undefined, rt.drop)); + } + _292 = false; + values2 = rt.hashValues(map3, rt.drop); + unwind = 164; + _291 = true; + one = rt.iterToOption(values2.next()); + unwind = 162; + _290 = true; + check(7); + _291 = false; + const args15: [rt.usize, boolean] = [rt.iterCount(values2, rt.drop, rt.drop), one !== undefined]; + const arg8 = args15[0]; + const _255: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg8, f); + const arg9 = one !== undefined; + const args16: rt.Fmt[] = [_255, (f: rt.Formatter) => rt.fmtBool(arg9, f)]; + Log.note(log, rt.fmtFormat(["rest ", args16[0], " ", args16[1]])); + _290 = false; + rt.drop(one); + const _272: rt.ByteVec = Log.text(sink); + unwind = 150; + const arg10 = ([rt.iterSum(rt.iterMap(rt.iterSlice(rt.byteVecView(_272)), (_2: rt.u8): rt.u32 => { + return _2 as rt.u32; + }), rt.u32Add, 0)] as [rt.u32])[0]; + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg10, f)]; + const _263: string = rt.fmtFormat(["sink ", args18[0]]); + unwind = 162; + Log.note(log, _263); + unwind = 152; + _290 = false; + _291 = false; + _292 = false; + rt.drop(sink); + unwind = 153; + rt.drop(taken); + unwind = 154; + rt.hashDrop(set2, rt.drop); + unwind = 156; + rt.hashDrop(map2, rt.drop, rt.drop); + unwind = 172; + rt.drop(entries); + unwind = 182; + _295 = false; + _296 = false; + _297 = false; + _298 = false; + _299 = false; + rt.dropAll(keys); + _300 = false; + _301 = false; + _302 = false; + } catch (e) { + b4: { + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + b19: { + if (unwind === 0) { + throw e; + } + if (unwind !== 150) { + if (unwind === 151) { + break b17; + } + if (unwind === 152) { + break b16; + } + if (unwind === 153) { + break b15; + } + if (unwind === 154) { + break b14; + } + if (unwind === 155) { + drop$Option_Key_Guard(_166); + break b13; + } + if (unwind === 156) { + break b13; + } + if (unwind === 157) { + rt.drop(_137); + break b11; + } + if (unwind === 158) { + rt.drop(_85); + break b9; + } + if (unwind === 159) { + break b7; + } + if (unwind !== 162) { + if (unwind === 164) { + break b19; + } + if (unwind === 166) { + break b18; + } + if (unwind === 168) { + if (!_293) { + break b14; + } + rt.drop(_175); + break b14; + } + if (unwind === 170) { + if (!_294) { + break b12; + } + rt.drop(_147); + break b12; + } + if (unwind === 172) { + break b12; + } + if (unwind === 174) { + break b11; + } + if (unwind === 176) { + break b10; + } + if (unwind === 178) { + break b9; + } + if (unwind === 180) { + break b8; + } + if (unwind === 182) { + break b6; + } + if (unwind === 184) { + break b5; + } + break b4; + } + } + if (_290) { + rt.drop(one); + } + } + if (_291) { + rt.drop(values2); + } + } + if (_292) { + rt.hashDrop(map3, undefined, rt.drop); + } + } + rt.drop(sink); + } + rt.drop(taken); + } + rt.hashDrop(set2, rt.drop); + } + rt.hashDrop(map2, rt.drop, rt.drop); + } + rt.drop(entries); + } + if (_295) { + rt.hashDrop(map, rt.drop, rt.drop); + } + } + if (_296) { + rt.drop(range); + } + } + if (_297) { + rt.dequeDrop(queue, rt.drop); + } + } + if (_298) { + rt.btreeDrop(set, rt.drop); + } + } + if (_299) { + rt.drop(values); + } + } + rt.dropAll(keys); + } + if (_300) { + drop$Option_Key_Guard(back); + } + } + if (_301) { + drop$Option_Key_Guard(first); + } + } + if (_302) { + rt.drop(it); + } + throw e; + } +} + +/** + * What `extend` drops: what a map or set does not keep of equal keys, and as a panic + * unwinds, the rest of what it extends from, and what it has added. + */ +export function extended(log: Log.Log, id: rt.u32, at: rt.u8): void { + let list!: Guard.Guard[]; + let v!: Guard.Guard[]; + let v2!: Guard.Guard[]; + let v3!: Guard.Guard[]; + let map!: rt.HashMap; + let _81!: Key.Key; + let v4!: [Key.Key, Guard.Guard][]; + let _96!: Key.Key; + let _105!: Key.Key; + let set!: rt.HashSet; + let v5!: Key.Key[]; + let tree!: rt.BTreeMap; + let _153!: Key.Key; + let v6!: [Key.Key, Guard.Guard][]; + let _168!: Key.Key; + let _177!: Key.Key; + let _186!: Key.Key; + let ordered!: rt.BTreeSet; + let v7!: Key.Key[]; + let queue!: rt.VecDeque; + let v8!: Guard.Guard[]; + let _272!: boolean; + let _273!: boolean; + let unwind: number = 0; + try { + _273 = false; + _272 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const key: (a0: rt.u32) => Key.Key = (n2: rt.u32): Key.Key => { + return Key.new(rt.u32Add(id, n2), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args8[0], " at ", args8[1]]); + } + }; + v = []; + unwind = 137; + const _15: Guard.Guard = guard(1); + v.push(_15); + unwind = 136; + list = v; + v2 = []; + unwind = 135; + const _26: Guard.Guard = guard(2); + v2.push(_26); + const _31: Guard.Guard = guard(3); + v2.push(_31); + const _36: Guard.Guard = guard(4); + v2.push(_36); + unwind = 136; + const _20: rt.Iter = rt.iterMap(rt.iterSlice(v2, rt.drop), (g: Guard.Guard): Guard.Guard => { + let unwind2: number = 0; + try { + unwind2 = 6; + if (Guard.id(g) === rt.u32Add(id, 3)) { + check(1); + return g; + } + return g; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(g); + throw e2; + } + }); + rt.iterExtend(list, _20, rt.drop); + v3 = []; + unwind = 134; + const _50: Guard.Guard = guard(5); + v3.push(_50); + const _55: Guard.Guard = guard(6); + v3.push(_55); + const _60: Guard.Guard = guard(7); + v3.push(_60); + unwind = 136; + const _44: rt.Iter = rt.iterFilter(rt.iterSlice(v3, rt.drop), (g2: Guard.Guard): boolean => { + if (Guard.id(g2) === rt.u32Add(id, 6)) { + check(2); + } + return Guard.id(g2) !== rt.u32Add(id, 5); + }, rt.drop); + rt.iterExtend(list, _44, rt.drop); + const arg = ([list.length] as [rt.usize])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg, f)]; + Log.note(log, rt.fmtFormat(["list ", args2[0]])); + map = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashMap; + unwind = 133; + _81 = key(8); + unwind = 142; + _273 = true; + const _84: Guard.Guard = guard(8); + _273 = false; + const _79: Guard.Guard | undefined = rt.hashInsert(map, _81, _84, rt.drop, rt.drop); + unwind = 133; + _273 = false; + rt.drop(_79); + v4 = []; + unwind = 132; + _96 = key(8); + unwind = 131; + const _99: Guard.Guard = guard(9); + unwind = 132; + v4.push([_96, _99] as [Key.Key, Guard.Guard]); + _105 = key(8); + unwind = 130; + const _108: Guard.Guard = guard(10); + unwind = 132; + v4.push([_105, _108] as [Key.Key, Guard.Guard]); + unwind = 133; + const _89: rt.Iter<[Key.Key, Guard.Guard]> = rt.iterMap(rt.iterSlice(v4, drop$Key_Guard), (e3: [Key.Key, Guard.Guard]): [Key.Key, Guard.Guard] => { + let unwind3: number = 0; + try { + unwind3 = 6; + if (Guard.id(e3[1]) === rt.u32Add(id, 10)) { + check(3); + return e3; + } + return e3; + } catch (e4) { + if (unwind3 === 0) { + throw e4; + } + drop$Key_Guard(e3); + throw e4; + } + }); + rt.hashExtend(map, _89, rt.drop, rt.drop, rt.drop); + set = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashSet; + unwind = 129; + const _117: Key.Key = key(11); + rt.hashAdd(set, _117, rt.drop); + v5 = []; + unwind = 128; + const _126: Key.Key = key(11); + v5.push(_126); + const _131: Key.Key = key(11); + v5.push(_131); + unwind = 129; + rt.hashExtendKeys(set, rt.iterSlice(v5, rt.drop), rt.drop, rt.drop); + const args3: [rt.usize, rt.usize] = [rt.hashLen(map), rt.hashLen(set)]; + const arg2 = args3[0]; + const _146: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg2, f); + const arg3 = args3[1]; + const args4: rt.Fmt[] = [_146, (f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; + Log.note(log, rt.fmtFormat(["hashed ", args4[0], " ", args4[1]])); + tree = rt.btreeNew(Key.cmp$Ord) as rt.BTreeMap; + unwind = 127; + _153 = key(12); + unwind = 140; + _272 = true; + const _156: Guard.Guard = guard(12); + _272 = false; + const _151: Guard.Guard | undefined = rt.btreeInsert(tree, _153, _156, rt.drop, rt.drop); + unwind = 127; + _272 = false; + rt.drop(_151); + v6 = []; + unwind = 126; + _168 = key(13); + unwind = 125; + const _171: Guard.Guard = guard(13); + unwind = 126; + v6.push([_168, _171] as [Key.Key, Guard.Guard]); + _177 = key(12); + unwind = 124; + const _180: Guard.Guard = guard(14); + unwind = 126; + v6.push([_177, _180] as [Key.Key, Guard.Guard]); + _186 = key(15); + unwind = 123; + const _189: Guard.Guard = guard(15); + unwind = 126; + v6.push([_186, _189] as [Key.Key, Guard.Guard]); + unwind = 127; + const _161: rt.Iter<[Key.Key, Guard.Guard]> = rt.iterMap(rt.iterSlice(v6, drop$Key_Guard), (e5: [Key.Key, Guard.Guard]): [Key.Key, Guard.Guard] => { + let unwind4: number = 0; + try { + unwind4 = 6; + if (Guard.id(e5[1]) === rt.u32Add(id, 14)) { + check(4); + return e5; + } + return e5; + } catch (e6) { + if (unwind4 === 0) { + throw e6; + } + drop$Key_Guard(e5); + throw e6; + } + }); + rt.btreeExtend(tree, _161, false, rt.drop, rt.drop, rt.drop); + check(5); + ordered = rt.btreeNew(Key.cmp$Ord) as rt.BTreeSet; + unwind = 122; + const _201: Key.Key = key(16); + rt.btreeAdd(ordered, _201, rt.drop); + v7 = []; + unwind = 121; + const _210: Key.Key = key(17); + v7.push(_210); + const _215: Key.Key = key(16); + v7.push(_215); + unwind = 122; + rt.btreeExtendKeys(ordered, rt.iterSlice(v7, rt.drop), false, rt.drop, rt.drop); + queue = rt.dequeNew() as rt.VecDeque; + unwind = 120; + const _221: Guard.Guard = guard(18); + rt.dequePushBack(queue, _221); + v8 = []; + unwind = 119; + const _232: Guard.Guard = guard(19); + v8.push(_232); + const _237: Guard.Guard = guard(20); + v8.push(_237); + unwind = 120; + const _226: rt.Iter = rt.iterMap(rt.iterSlice(v8, rt.drop), (g3: Guard.Guard): Guard.Guard => { + let unwind5: number = 0; + try { + unwind5 = 6; + if (Guard.id(g3) === rt.u32Add(id, 20)) { + check(6); + return g3; + } + return g3; + } catch (e7) { + if (unwind5 === 0) { + throw e7; + } + rt.drop(g3); + throw e7; + } + }); + rt.dequeExtend(queue, _226, rt.drop); + check(7); + const args5: [rt.usize, rt.usize, rt.usize] = [rt.btreeLen(tree), rt.btreeLen(ordered), queue.n]; + const arg4 = args5[0]; + const _261: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(arg4, f); + const arg5 = args5[1]; + const args6: rt.Fmt[] = [_261, (f: rt.Formatter) => rt.usizeDisplay(arg5, f), (f: rt.Formatter) => rt.usizeDisplay(queue.n, f)]; + Log.note(log, rt.fmtFormat(["ordered ", args6[0], " ", args6[1], " ", args6[2]])); + unwind = 122; + rt.dequeDrop(queue, rt.drop); + unwind = 127; + rt.btreeDrop(ordered, rt.drop); + unwind = 129; + rt.btreeDrop(tree, rt.drop, rt.drop); + unwind = 133; + rt.hashDrop(set, rt.drop); + unwind = 136; + rt.hashDrop(map, rt.drop, rt.drop); + unwind = 0; + rt.dropAll(list); + } catch (e) { + b0: { + b1: { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + if (unwind === 0) { + throw e; + } + if (unwind === 119) { + rt.dropAll(v8); + break b6; + } + if (unwind === 120) { + break b6; + } + if (unwind === 121) { + rt.dropAll(v7); + break b5; + } + if (unwind === 122) { + break b5; + } + if (unwind === 123) { + rt.drop(_186); + break b7; + } + if (unwind === 124) { + rt.drop(_177); + break b7; + } + if (unwind === 125) { + rt.drop(_168); + break b7; + } + if (unwind === 126) { + break b7; + } + if (unwind === 127) { + break b4; + } + if (unwind === 128) { + rt.dropAll(v5); + break b3; + } + if (unwind === 129) { + break b3; + } + if (unwind === 130) { + rt.drop(_105); + } else if (unwind === 131) { + rt.drop(_96); + } else if (unwind !== 132) { + if (unwind === 133) { + break b2; + } + if (unwind === 134) { + rt.dropAll(v3); + break b1; + } + if (unwind === 135) { + rt.dropAll(v2); + break b1; + } + if (unwind === 136) { + break b1; + } + if (unwind === 137) { + rt.dropAll(v); + break b0; + } + if (unwind === 140) { + if (!_272) { + break b4; + } + rt.drop(_153); + break b4; + } + if (!_273) { + break b2; + } + rt.drop(_81); + break b2; + } + rt.dropAll(v4, drop$Key_Guard); + break b2; + } + rt.dropAll(v6, drop$Key_Guard); + break b4; + } + rt.dequeDrop(queue, rt.drop); + } + rt.btreeDrop(ordered, rt.drop); + } + rt.btreeDrop(tree, rt.drop, rt.drop); + } + rt.hashDrop(set, rt.drop); + } + rt.hashDrop(map, rt.drop, rt.drop); + } + rt.dropAll(list); + } + throw e; + } +} + +/** + * What drops after a value's `Drop` panics in an iterator, scenario `at`'s alone: the + * rest of what the iterator holds, or what std's code leaves. + */ +export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { + let it!: rt.Iter; + let v!: Bomb.Bomb[]; + let _32!: rt.Iter; + let v2!: Bomb.Bomb[]; + let v3!: Bomb.Bomb[]; + let map!: rt.BTreeMap; + let _70!: rt.u32; + let it2!: rt.Iter<[rt.u32, Bomb.Bomb]>; + let queue!: rt.VecDeque; + let _91!: rt.u32; + let v4!: [rt.u32, Bomb.Bomb][]; + let v5!: Bomb.Bomb[]; + let flat!: rt.Iter; + let v6!: Bomb.Bomb[][]; + let v7!: Bomb.Bomb[]; + let v8!: Bomb.Bomb[]; + let _183!: boolean; + let _184!: boolean; + let _185!: boolean; + let _186!: boolean; + let unwind: number = 0; + try { + _186 = false; + _185 = false; + _184 = false; + _183 = false; + const bomb: (a0: rt.u32, a1: boolean) => Bomb.Bomb = (n3: rt.u32, blows: boolean): Bomb.Bomb => { + return new Bomb.Bomb({ id: rt.u32Add(id, n3), log: Log.clone$Clone(log), blows }); + }; + if (at === 0) { + v = []; + unwind = 111; + const _12: Bomb.Bomb = bomb(1, false); + v.push(_12); + const _17: Bomb.Bomb = bomb(2, true); + v.push(_17); + const _22: Bomb.Bomb = bomb(3, false); + v.push(_22); + unwind = 0; + it = rt.iterSlice(v, rt.drop); + unwind = 120; + _186 = true; + rt.drop(rt.iterToOption(it.next())); + _186 = false; + rt.drop(it); + _186 = false; + } else if (at === 1) { + v2 = []; + unwind = 110; + const _38: Bomb.Bomb = bomb(1, true); + v2.push(_38); + const _43: Bomb.Bomb = bomb(2, false); + v2.push(_43); + unwind = 0; + _32 = rt.iterSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); + unwind = 109; + rt.drop(rt.iterToOption(_32.next())); + unwind = 0; + rt.drop(_32); + } else if (at === 2) { + v3 = []; + unwind = 108; + const _53: Bomb.Bomb = bomb(1, false); + v3.push(_53); + const _58: Bomb.Bomb = bomb(2, true); + v3.push(_58); + const _63: Bomb.Bomb = bomb(3, false); + v3.push(_63); + unwind = 0; + rt.iterCount(rt.iterFilter(rt.iterSlice(v3, rt.drop), (b: Bomb.Bomb): boolean => { + return !b.blows; + }, rt.drop), rt.drop, rt.drop); + } else if (at === 3) { + _185 = true; + map = rt.btreeNew(rt.cmp) as rt.BTreeMap; + unwind = 118; + let iterStart: rt.u32 = 1; + const iterEnd: rt.u32 = 4; + while ((_70 = iterStart++) < iterEnd) { + const n: rt.u32 = _70; + const _76: Bomb.Bomb = bomb(n, n === 2); + rt.drop(rt.btreeInsert(map, n, _76, undefined, rt.drop)); + } + _185 = false; + it2 = rt.btreeIter(map, undefined, rt.drop); + unwind = 116; + _184 = true; + drop$Option_u32_Bomb(rt.iterToOption(it2.next())); + _184 = false; + rt.drop(it2); + _184 = false; + _185 = false; + } else if (at === 4) { + queue = rt.dequeNew() as rt.VecDeque; + unwind = 107; + let iterStart2: rt.u32 = 1; + const iterEnd2: rt.u32 = 5; + while ((_91 = iterStart2++) < iterEnd2) { + const n2: rt.u32 = _91; + const _97: Bomb.Bomb = bomb(n2, n2 === 2); + rt.dequePushBack(queue, _97); + } + rt.drop(rt.dequeDrain(queue, { end: 3 }, rt.drop)); + unwind = 0; + rt.dequeDrop(queue, rt.drop); + } else if (at === 5) { + v4 = []; + unwind = 106; + const _111: [rt.u32, Bomb.Bomb] = [1, bomb(1, true)]; + v4.push(_111); + const _117: [rt.u32, Bomb.Bomb] = [1, bomb(2, false)]; + v4.push(_117); + const _123: [rt.u32, Bomb.Bomb] = [2, bomb(3, false)]; + v4.push(_123); + unwind = 0; + const _106: rt.Iter<[rt.u32, Bomb.Bomb]> = rt.iterSlice(v4, drop$u32_Bomb); + rt.btreeDrop(rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_106, true, rt.drop, drop$u32_Bomb), undefined, rt.drop), undefined, rt.drop); + } else if (at === 6) { + v5 = []; + unwind = 105; + const _134: Bomb.Bomb = bomb(1, false); + v5.push(_134); + const _139: Bomb.Bomb = bomb(2, true); + v5.push(_139); + const _144: Bomb.Bomb = bomb(3, false); + v5.push(_144); + unwind = 0; + rt.iterCount(rt.iterTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); + } else { + v6 = []; + unwind = 104; + v7 = []; + unwind = 103; + const _157: Bomb.Bomb = bomb(1, false); + v7.push(_157); + unwind = 104; + v6.push(v7); + v8 = []; + unwind = 102; + const _166: Bomb.Bomb = bomb(2, true); + v8.push(_166); + const _171: Bomb.Bomb = bomb(3, false); + v8.push(_171); + unwind = 104; + v6.push(v8); + unwind = 0; + flat = rt.iterFlatten(rt.iterSlice(v6, drop$Vec_Bomb), (value: Bomb.Bomb[]) => rt.iterSlice(value, rt.drop), true); + unwind = 114; + _183 = true; + rt.drop(rt.iterToOption(flat.next())); + _183 = false; + rt.drop(flat); + _183 = false; + } + unwind = 0; + Log.note(log, rt.fmtFormat(["unreached"])); + } catch (e) { + b5: { + b6: { + if (unwind === 0) { + throw e; + } + if (unwind === 102) { + rt.dropAll(v8); + break b6; + } + if (unwind === 103) { + rt.dropAll(v7); + break b6; + } + if (unwind === 104) { + break b6; + } + if (unwind === 105) { + rt.dropAll(v5); + break b5; + } + if (unwind === 106) { + rt.dropAll(v4, drop$u32_Bomb); + break b5; + } + if (unwind === 107) { + rt.dequeDrop(queue, rt.drop); + break b5; + } + if (unwind === 108) { + rt.dropAll(v3); + break b5; + } + if (unwind === 109) { + rt.drop(_32); + break b5; + } + if (unwind === 110) { + rt.dropAll(v2); + break b5; + } + if (unwind === 111) { + rt.dropAll(v); + break b5; + } + if (unwind === 114) { + if (!_183) { + break b5; + } + rt.drop(flat); + break b5; + } + if (unwind === 116) { + if (_184) { + rt.drop(it2); + } + } else if (unwind !== 118) { + if (!_186) { + break b5; + } + rt.drop(it); + break b5; + } + if (!_185) { + break b5; + } + rt.btreeDrop(map, undefined, rt.drop); + break b5; + } + rt.dropAll(v6, drop$Vec_Bomb); + } + throw e; + } +} + +//# sourceMappingURL=iters.ts.map diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index e1bbe24ba..aa4f24d2b 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -60,6 +60,26 @@ export function drop$Guard_Bomb_Held(_1: [Guard.Guard, Bomb.Bomb, Held.Held]): v } } +export function drop$Guard_Guard(_1: [Guard.Guard, Guard.Guard]): void { + let unwind: number = 0; + try { + unwind = 4; + rt.drop(_1[0]); + unwind = 0; + rt.drop(_1[1]); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(_1[1]); + throw e; + } +} + +export function drop$Guard_u32(_1: [Guard.Guard, rt.u32]): void { + rt.drop(_1[0]); +} + export function drop$Held(_1: Held.Held): void { let unwind: number = 0; try { @@ -80,6 +100,22 @@ export function drop$Held(_1: Held.Held): void { } } +export function drop$Key_Guard(_1: [Key.Key, Guard.Guard]): void { + let unwind: number = 0; + try { + unwind = 4; + rt.drop(_1[0]); + unwind = 0; + rt.drop(_1[1]); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(_1[1]); + throw e; + } +} + export function drop$Mutex_Held(value: rt.Mutex): void { drop$Held(value.value); } @@ -96,6 +132,18 @@ export function drop$Option_Held(_1: Held.Held | undefined): void { } } +export function drop$Option_Key_Guard(_1: [Key.Key, Guard.Guard] | undefined): void { + if (_1 !== undefined) { + drop$Key_Guard(_1); + } +} + +export function drop$Option_u32_Bomb(_1: [rt.u32, Bomb.Bomb] | undefined): void { + if (_1 !== undefined) { + drop$u32_Bomb(_1); + } +} + export function drop$Pair_Held(_1: Pair.Pair): void { let unwind: number = 0; try { @@ -120,6 +168,14 @@ export function drop$Result_Guard_Guard(_1: rt.Result) } } +export function drop$Result_Vec_Guard_Guard(_1: rt.Result): void { + if (_1.ok) { + rt.dropAll(_1.value); + } else { + rt.drop(_1.error); + } +} + export function drop$Result_u32_Guard(_1: rt.Result): void { if (!_1.ok) { rt.drop(_1.error); @@ -132,6 +188,14 @@ export function drop$Result_u8_Key(_1: rt.Result): void { } } +export function drop$Vec_Bomb(value: Bomb.Bomb[]): void { + rt.dropAll(value); +} + +export function drop$Vec_Guard(value: Guard.Guard[]): void { + rt.dropAll(value); +} + export function drop$Wrap_Arc_Held(_1: Wrap.Wrap>): void { let unwind: number = 0; try { @@ -237,4 +301,12 @@ export function drop$Wrap_Vec_Wrap_Held(_1: Wrap.Wrap[]>): } } +export function drop$u32_Bomb(_1: [rt.u32, Bomb.Bomb]): void { + rt.drop(_1[1]); +} + +export function drop$u32_Guard(_1: [rt.u32, Guard.Guard]): void { + rt.drop(_1[1]); +} + //# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index 06736ebe4..0d488a7be 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -21,6 +21,8 @@ macro_rules! list { }}; } +mod iters; + /// A value of a type that drops, with no `[Symbol.dispose]` of its own. pub enum Held { One(Guard), @@ -47,17 +49,22 @@ pub struct Pair { second: Guard, } -/// Run scenario `arg % 13`, panicking at the point `arg / 13 % 8` names, if any: what +/// Run scenario `arg % 18`, panicking at the point `arg / 18 % 8` names, if any: what /// every value std holds drops, where Rust drops it, and in Rust's order. pub fn run(log: &Log, id: u32, arg: u8) { - let at = arg / 13 % 8; + let at = arg / 18 % 8; let guard = |n: u32| Guard::new(id + n, log.clone()); let check = |point: u8| { if point == at { panic!("d{id} at {point}"); } }; - match arg % 13 { + match arg % 18 { + 13 => iters::looped(log, id, at), + 14 => iters::collected(log, id, at), + 15 => iters::drained(log, id, at), + 16 => iters::extended(log, id, at), + 17 => iters::bombed(log, id, at), 4 => ordered(log, id, at), 5 => hashed(log, id, at), 6 => options(log, id, at), diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs new file mode 100644 index 000000000..223662779 --- /dev/null +++ b/ts/fixtures/task/src/drops/iters.rs @@ -0,0 +1,383 @@ +//! What std's iterators drop of the values they own: the items a `for` leaves, what +//! adaptors discard or hold, what `collect` and `extend` drop as they go or as a panic +//! unwinds, and what draining a collection leaves in it. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; + +use super::{Bomb, Key}; +use crate::log::Log; +use crate::model::Guard; + +/// What `for` leaves of what it iterates, and what adaptors discard, hold, and return, +/// panicking at point `at`, if any, some inside an adaptor's closure. +pub(super) fn looped(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + for g in list![guard(1), guard(2), guard(3)] { + if g.id() == id + 2 { + break; + } + } + for g in [guard(4), guard(5), guard(6)] { + log.note(format!("array {}", g.id())); + if g.id() == id + 5 { + check(1); + } + } + for g in Some(guard(7)) { + log.note(format!("option {}", g.id())); + } + let even: Vec = list![guard(8), guard(9), guard(10), guard(11)] + .into_iter() + .filter(|g| { + if g.id() == id + 10 { + check(2); + } + g.id() % 2 == 0 + }) + .collect(); + log.note(format!("even {}", even.len())); + let mut rest = list![guard(12), guard(13), guard(14), guard(15), guard(16)] + .into_iter() + .skip(1) + .take(3); + log.note(format!("next {}", rest.next().map_or(0, |g| g.id()))); + check(3); + log.note(format!("count {}", rest.count())); + let mut peek = list![guard(17), guard(18)].into_iter().peekable(); + let first = peek.next_if(|g| g.id() == id + 17); + let second = peek.next_if(|g| g.id() == id + 99); + log.note(format!("peek {} {}", first.is_some(), second.is_some())); + check(4); + drop(peek); + let pairs = list![guard(20), guard(21), guard(22)].into_iter().zip(list![guard(23)]); + log.note(format!("zip {}", pairs.count())); + let nth = list![guard(24)] + .into_iter() + .chain(list![guard(25), guard(26)]) + .rev() + .nth(1); + log.note(format!("nth {}", nth.map_or(0, |g| g.id()))); + check(5); + let best = list![guard(27), guard(28), guard(29)] + .into_iter() + .max_by_key(|g| g.id() % 2); + let found = list![Some(guard(30)), None, Some(guard(31)), Some(guard(32))] + .into_iter() + .flatten() + .find(|g| g.id() == id + 31); + log.note(format!("found {} {}", best.map_or(0, |g| g.id()), found.is_some())); + check(6); + let folded = list![guard(33), guard(34), guard(35)].into_iter().fold(0, |n, g| { + if g.id() == id + 34 { + check(7); + } + n + g.id() - id + }); + let last = list![guard(36), guard(37), guard(38)].into_iter().step_by(2).last(); + log.note(format!("fold {folded} {}", last.map_or(0, |g| g.id()))); + // What drops with a `flatten`: its source, then what it read of the front and back. + let mut flat = list![ + list![guard(39), guard(40)], + list![guard(41)], + list![guard(42), guard(43)] + ] + .into_iter() + .flatten(); + let front = flat.next().map_or(0, |g| g.id()); + let back = flat.next_back().map_or(0, |g| g.id()); + log.note(format!("flat {front} {back}")); + drop(flat); +} + +/// What `collect` drops: in place of the `Vec` its items come from, what it collected +/// before the rest of the source as a panic unwinds, and else the source first; the +/// values before the first `Err` or `None`, and the rest; and of equal keys, the one a +/// map or set does not keep. +pub(super) fn collected(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let key = |n: u32| Key::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + let same: Vec = list![guard(1), guard(2), guard(3)] + .into_iter() + .map(|g| { + if g.id() == id + 2 { + check(1); + } + g + }) + .collect(); + // Larger than what it is made from, so not in place. + let wider: Vec<(Guard, u32)> = list![guard(4), guard(5), guard(6)] + .into_iter() + .map(|g| { + if g.id() == id + 5 { + check(2); + } + (g, 0) + }) + .collect(); + let chained: Vec = list![guard(7)] + .into_iter() + .chain(list![guard(8), guard(9)]) + .map(|g| { + if g.id() == id + 8 { + check(3); + } + g + }) + .collect(); + log.note(format!("vecs {} {} {}", same.len(), wider.len(), chained.len())); + let results: Result, Guard> = list![guard(10), guard(11), guard(12)] + .into_iter() + .map(|g| if g.id() == id + 11 { Err(g) } else { Ok(g) }) + .collect(); + log.note(format!("result {}", results.is_ok())); + drop(results); + let options: Option> = list![guard(13), guard(14), guard(15)] + .into_iter() + .map(|g| { + if g.id() == id + 14 { + check(4); + } + Some(g) + }) + .collect(); + log.note(format!("option {}", options.map_or(0, |v| v.len()))); + let tree: BTreeMap = list![(2, guard(16)), (1, guard(17)), (2, guard(18))] + .into_iter() + .collect(); + log.note(format!("tree {}", tree.len())); + check(5); + let queue: VecDeque = list![guard(19), guard(20)] + .into_iter() + .map(|g| { + if g.id() == id + 20 { + check(6); + } + g + }) + .collect(); + let hashed: HashMap = list![(1, guard(21)), (1, guard(22))] + .into_iter() + .map(|e| { + if e.1.id() == id + 22 { + check(7); + } + e + }) + .collect(); + let set: HashSet = list![key(23), key(23)].into_iter().collect(); + log.note(format!("collected {} {} {}", queue.len(), hashed.len(), set.len())); +} + +/// What draining a collection drops: the items taken, the half of each entry +/// `into_keys` or `into_values` leaves, and what is left when the iterator drops, as a +/// panic may drop it. +pub(super) fn drained(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let key = |n: u32| Key::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + let tree = |base: u32| { + let mut map = BTreeMap::new(); + for n in base..base + 4 { + map.insert(key(n), guard(n)); + } + map + }; + let mut it = tree(1).into_iter(); + let first = it.next(); + let back = it.next_back(); + drop(first); + check(1); + drop(it); + drop(back); + let keys: Vec = tree(5).into_keys().collect(); + check(2); + let mut values = tree(9).into_values(); + log.note(format!("values {} {}", keys.len(), values.next().map_or(0, |g| g.id()))); + check(3); + drop(values); + let mut set = BTreeSet::new(); + set.insert(key(13)); + set.insert(key(14)); + log.note(format!("set {}", set.into_iter().next().map_or(0, |k| k.id))); + let mut queue = VecDeque::new(); + for n in 15..20 { + queue.push_back(guard(n)); + } + let mut range = queue.drain(1..4); + log.note(format!("drain {}", range.next().map_or(0, |g| g.id()))); + check(4); + drop(range); + log.note(format!( + "queue {} {}", + queue.len(), + queue.into_iter().next().map_or(0, |g| g.id()) + )); + // One entry each, whose order std's hash table leaves no room to differ in. + let mut map = HashMap::new(); + map.insert(key(20), guard(20)); + let mut entries = map.into_iter(); + check(5); + log.note(format!("entry {}", entries.next().is_some())); + let mut map = HashMap::new(); + map.insert(key(21), guard(21)); + drop(map.drain()); + log.note(format!("drained {}", map.len())); + let mut set = HashSet::new(); + set.insert(key(22)); + let mut taken = set.drain(); + check(6); + log.note(format!("taken {}", taken.next().map_or(0, |k| k.id))); + // Many, read by a sink in an order it ignores. + let sink = Log::new(); + let mut map = HashMap::new(); + for n in 23..27 { + map.insert(n, Guard::new(id + n, sink.clone())); + } + let mut values = map.into_values(); + let one = values.next(); + check(7); + log.note(format!("rest {} {}", values.count(), one.is_some())); + drop(one); + log.note(format!( + "sink {}", + sink.text().iter().map(|&b| u32::from(b)).sum::() + )); +} + +/// What `extend` drops: what a map or set does not keep of equal keys, and as a panic +/// unwinds, the rest of what it extends from, and what it has added. +pub(super) fn extended(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let key = |n: u32| Key::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + let mut list = list![guard(1)]; + list.extend(list![guard(2), guard(3), guard(4)].into_iter().map(|g| { + if g.id() == id + 3 { + check(1); + } + g + })); + list.extend(list![guard(5), guard(6), guard(7)].into_iter().filter(|g| { + if g.id() == id + 6 { + check(2); + } + g.id() != id + 5 + })); + log.note(format!("list {}", list.len())); + let mut map = HashMap::new(); + map.insert(key(8), guard(8)); + map.extend(list![(key(8), guard(9)), (key(8), guard(10))].into_iter().map(|e| { + if e.1.id() == id + 10 { + check(3); + } + e + })); + let mut set = HashSet::new(); + set.insert(key(11)); + set.extend(list![key(11), key(11)]); + log.note(format!("hashed {} {}", map.len(), set.len())); + let mut tree = BTreeMap::new(); + tree.insert(key(12), guard(12)); + tree.extend( + list![(key(13), guard(13)), (key(12), guard(14)), (key(15), guard(15))] + .into_iter() + .map(|e| { + if e.1.id() == id + 14 { + check(4); + } + e + }), + ); + check(5); + let mut ordered = BTreeSet::new(); + ordered.insert(key(16)); + ordered.extend(list![key(17), key(16)]); + let mut queue = VecDeque::new(); + queue.push_back(guard(18)); + queue.extend(list![guard(19), guard(20)].into_iter().map(|g| { + if g.id() == id + 20 { + check(6); + } + g + })); + check(7); + log.note(format!("ordered {} {} {}", tree.len(), ordered.len(), queue.len())); +} + +/// What drops after a value's `Drop` panics in an iterator, scenario `at`'s alone: the +/// rest of what the iterator holds, or what std's code leaves. +pub(super) fn bombed(log: &Log, id: u32, at: u8) { + let bomb = |n: u32, blows: bool| Bomb { + id: id + n, + log: log.clone(), + blows, + }; + match at { + 0 => { + let mut it = list![bomb(1, false), bomb(2, true), bomb(3, false)].into_iter(); + drop(it.next()); + drop(it); + } + 1 => drop(list![bomb(1, true), bomb(2, false)].into_iter().skip(1).next()), + 2 => drop( + list![bomb(1, false), bomb(2, true), bomb(3, false)] + .into_iter() + .filter(|b| !b.blows) + .count(), + ), + 3 => { + let mut map = BTreeMap::new(); + for n in 1..4 { + map.insert(n, bomb(n, n == 2)); + } + let mut it = map.into_iter(); + drop(it.next()); + drop(it); + } + 4 => { + let mut queue = VecDeque::new(); + for n in 1..5 { + queue.push_back(bomb(n, n == 2)); + } + drop(queue.drain(..3)); + } + 5 => drop( + list![(1, bomb(1, true)), (1, bomb(2, false)), (2, bomb(3, false))] + .into_iter() + .collect::>(), + ), + 6 => drop( + list![bomb(1, false), bomb(2, true), bomb(3, false)] + .into_iter() + .take(2) + .count(), + ), + _ => { + let mut flat = list![list![bomb(1, false)], list![bomb(2, true), bomb(3, false)]] + .into_iter() + .flatten(); + drop(flat.next()); + drop(flat); + } + } + log.note(format!("unreached")); +} diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index 58824a4bd..8ca66e0cb 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -16,7 +16,7 @@ import { panic } from "../rt.ts"; import { type Limbs, lt } from "./int.ts"; -import { DONE, type Done, Iter, iterToArray, RangeInclusive } from "./iter.ts"; +import { DONE, type Done, Iter, iterSlice, RangeInclusive } from "./iter.ts"; import { type Arc, dropAll } from "./task.ts"; // Ordering @@ -568,64 +568,100 @@ const ENTRIES = 0; const KEYS = 1; const VALUES = 2; -/** An iterator of a hash collection: `iter`, `keys`, `values`, `drain`, and the rest. */ +/** + * An iterator of a hash collection: `iter`, `keys`, `values`, `drain`, and the rest. + * One that owns its entries is given what drops each key and value of those that drop, + * and drops each entry it still holds as it drops. + */ class HashIter extends Iter { private readonly p: Iterator<[K, V]>; private readonly o: Iterator> | undefined; private at: Slot | undefined; private readonly pick: Pick; private left: number; + private readonly k: ((key: K) => void) | undefined; + private readonly v: ((value: V) => void) | undefined; + /** Whether it is a `drain`, whose `count` reads each entry, as an `into_iter`'s does not. */ + private readonly drain: boolean; - constructor(m: HashMap, pick: Pick) { + constructor(m: HashMap, pick: Pick, k?: (key: K) => void, v?: (value: V) => void, drain = false) { super(); this.p = m.p.entries(); this.o = m.o?.values(); this.pick = pick; this.left = hashLen(m); + this.k = k; + this.v = v; + this.drain = drain; } - next(): T | Done { - if (this.left === 0) return DONE; - this.left--; + /** The next entry, of the `left` it has. */ + private entry(): [K, V] { const entry = this.p.next(); - if (!entry.done) { - const [k, v] = entry.value; - return (this.pick === ENTRIES ? entry.value : this.pick === KEYS ? k : v) as T; - } + if (!entry.done) return entry.value; if (this.at === undefined) this.at = (this.o as Iterator>).next().value; const s = this.at as Slot; this.at = s.next; - return (this.pick === ENTRIES ? [s.k, s.v] : this.pick === KEYS ? s.k : s.v) as T; + return [s.k, s.v]; + } + + next(): T | Done { + if (this.left === 0) return DONE; + this.left--; + const entry = this.entry(); + if (this.pick === ENTRIES) return entry as T; + return (this.pick === KEYS ? entry[0] : entry[1]) as unknown as T; } override len(): number { return this.left; } + + /** std's `into_iter`'s: its length, and then each entry drops with it. */ + override countItems(drop?: (item: T) => void): number { + if (this.drain) return super.countItems(drop); + const n = this.left; + this[Symbol.dispose](); + return n; + } + + override [Symbol.dispose](): void { + if (this.k === undefined && this.v === undefined) return; + // A panic leaves the entries after it undropped, as std's table does. + for (let n = this.left; n > 0; n--) { + this.left--; + const [key, value] = this.entry(); + dropPair(key, value, this.k, this.v); + } + } } -/** `iter`, `iter_mut`, and `into_iter` of a map: its entries, as `[key, value]`. */ -export function hashIter(m: HashMap): Iter<[K, V]> { - return new HashIter(m, ENTRIES); +/** + * `iter` and `iter_mut` of a map, and with what drops each key and value of those that + * drop, `into_iter`: its entries, as `[key, value]`. + */ +export function hashIter(m: HashMap, k?: (key: K) => void, v?: (value: V) => void): Iter<[K, V]> { + return new HashIter(m, ENTRIES, k, v); } -/** `keys` and `into_keys` of a map, and `iter` and `into_iter` of a set. */ -export function hashKeys(m: HashMap): Iter { - return new HashIter(m, KEYS); +/** `keys` of a map and `iter` of a set, and with what drops each key, `into_keys` of values that don't drop and `into_iter`. */ +export function hashKeys(m: HashMap, k?: (key: K) => void): Iter { + return new HashIter(m, KEYS, k); } -/** `values`, `values_mut`, and `into_values`. */ -export function hashValues(m: HashMap): Iter { - return new HashIter(m, VALUES); +/** `values` and `values_mut`, and with what drops each value, `into_values` of keys that don't drop. */ +export function hashValues(m: HashMap, v?: (value: V) => void): Iter { + return new HashIter(m, VALUES, undefined, v); } -/** `drain` of a map: every entry, taken out at once. */ -export function hashDrain(m: HashMap): Iter<[K, V]> { - return hashIter(taken(m)); +/** `drain` of a map: every entry, taken out at once, which drops as `hashIter`'s. */ +export function hashDrain(m: HashMap, k?: (key: K) => void, v?: (value: V) => void): Iter<[K, V]> { + return new HashIter(taken(m), ENTRIES, k, v, true); } /** `drain` of a set: every key, taken out at once. */ -export function hashDrainKeys(m: HashMap): Iter { - return hashKeys(taken(m)); +export function hashDrainKeys(m: HashMap, k?: (key: K) => void): Iter { + return new HashIter(taken(m), KEYS, k, undefined, true); } /** What `m` held, which it no longer does. */ @@ -637,21 +673,58 @@ function taken(m: HashMap): HashMap { } /** - * `extend` of a map with `[key, value]`s, and `collect` into one through `hashNew`. Of - * equal keys, the first stays and each later one drops, then the value it replaced. + * Run `f`, which extends `c` from `items`, and then drop `items` by `dropIt`, as std's + * `extend` drops the iterator it takes. A panic drops `items`, and then, if `c` is + * `fresh`, one `collect` made, `c` by `drop`. */ -export function hashExtend(m: HashMap, items: Iter<[K, V]>, k?: (key: K) => void, v?: (value: V) => void): HashMap { - for (let item = items.next(); item !== DONE; item = items.next()) { - const old = hashInsert(m, item[0], item[1], k, v); - if (old !== undefined) v?.(old); +function extending(c: C, items: Iter, f: () => void, dropIt?: (it: Iter) => void, fresh = false, drop?: (c: C) => void): C { + if (dropIt === undefined && !fresh) { + f(); + return c; } - return m; + try { + try { + f(); + } catch (e) { + dropIt?.(items); + throw e; + } + dropIt?.(items); + } catch (e) { + if (fresh) drop?.(c); + throw e; + } + return c; } -/** `extend` of a set with keys, and `collect` into one through `hashNew`: a key already there drops. */ -export function hashExtendKeys(m: HashSet, keys: Iter, k?: (key: K) => void): HashSet { - for (let key = keys.next(); key !== DONE; key = keys.next()) hashAdd(m, key, k); - return m; +/** + * `extend` of a map with `[key, value]`s, and if `fresh`, `collect` into one through + * `hashNew`. Of equal keys, the first stays and each later one drops, then the value it + * replaced. + */ +export function hashExtend( + m: HashMap, + items: Iter<[K, V]>, + k?: (key: K) => void, + v?: (value: V) => void, + dropIt?: (it: Iter<[K, V]>) => void, + fresh = false, +): HashMap { + const f = () => { + for (let item = items.next(); item !== DONE; item = items.next()) { + const old = hashInsert(m, item[0], item[1], k, v); + if (old !== undefined) v?.(old); + } + }; + return extending(m, items, f, dropIt, fresh, (m) => hashDrop(m, k, v)); +} + +/** `extend` of a set with keys, and `collect` into one, as `hashExtend`: a key already there drops. */ +export function hashExtendKeys(m: HashSet, keys: Iter, k?: (key: K) => void, dropIt?: (it: Iter) => void, fresh = false): HashSet { + const f = () => { + for (let key = keys.next(); key !== DONE; key = keys.next()) hashAdd(m, key, k); + }; + return extending(m, keys, f, dropIt, fresh, (m) => hashDrop(m, k)); } /** `clone`, with each key and value through its `Clone`, or as itself without one. */ @@ -1130,7 +1203,9 @@ export function btreeRetain(m: BTreeMap, f: (key: K, value: V) => bo /** * An iterator of a B-tree's entries, keys, or values, from index `fi` of leaf `fl` up to * before index `bi` of leaf `bl`. The front moves to the next leaf as it passes a leaf's - * last key, and the back to the previous leaf as it passes a leaf's first key. + * last key, and the back to the previous leaf as it passes a leaf's first key. One that + * owns its entries drops as `HashIter` does, but a panic dropping one still drops the + * rest, as std's B-trees do. */ class BTreeIter extends Iter { fl: Leaf; @@ -1140,8 +1215,12 @@ class BTreeIter extends Iter { /** How many items are left, where it is known: an iterator of the whole map. */ private n: number; private readonly pick: Pick; + private readonly k: ((key: K) => void) | undefined; + private readonly v: ((value: V) => void) | undefined; + /** Whether its `last` reads from the back, as a map's `into_keys`' and `into_values`' do. */ + private readonly back: boolean; - constructor(pick: Pick, fl: Leaf, fi: number, bl: Leaf, bi: number, n = -1) { + constructor(pick: Pick, fl: Leaf, fi: number, bl: Leaf, bi: number, n = -1, k?: (key: K) => void, v?: (value: V) => void, back = false) { super(); this.pick = pick; if (fi === fl.k.length && fl.next !== undefined) { @@ -1157,35 +1236,80 @@ class BTreeIter extends Iter { this.bl = bl; this.bi = bi; this.n = n; + this.k = k; + this.v = v; + this.back = back; } next(): T | Done { if (done(this)) return DONE; const l = this.fl; - const item = picked(this.pick, l, this.fi++); + const i = this.fi++; if (this.fi === l.k.length && l.next !== undefined) { this.fl = l.next; this.fi = 0; } this.n--; - return item; + return this.picked(l, i); } override nextBack(): T | Done { if (done(this)) return DONE; const l = this.bl; - const item = picked(this.pick, l, --this.bi); + const i = --this.bi; if (this.bi === 0 && l.prev !== undefined) { this.bl = l.prev; this.bi = this.bl.k.length; } this.n--; - return item; + return this.picked(l, i); + } + + /** + * What it yields of index `i` of leaf `l`: of `into_keys` or `into_values`, the other + * half drops first, and a panic there leaks this one, as std's unwinding does a + * returned value. + */ + private picked(l: Leaf, i: number): T { + if (this.pick === ENTRIES) return [l.k[i], l.v[i]] as T; + if (this.pick === KEYS) { + this.v?.(l.v[i]); + return l.k[i] as unknown as T; + } + this.k?.(l.k[i]); + return l.v[i] as unknown as T; } override len(): number { return this.n; } + + /** std's `into_keys`' and `into_values`': the last, and then the rest drop with it. */ + override lastItem(drop?: (item: T) => void): T | Done { + if (!this.back) return super.lastItem(drop); + const last = this.nextBack(); + // A panic here leaks the last, as std's unwinding does a returned value. + this[Symbol.dispose](); + return last; + } + + override [Symbol.dispose](): void { + if (this.k === undefined && this.v === undefined) return; + const keys: K[] = []; + const values: V[] = []; + while (!done(this)) { + const l = this.fl; + keys.push(l.k[this.fi]); + values.push(l.v[this.fi]); + this.fi++; + if (this.fi === l.k.length && l.next !== undefined) { + this.fl = l.next; + this.fi = 0; + } + } + this.n = 0; + dropPairs(keys, values, this.k, this.v); + } } /** Whether `it`'s front has met its back. */ @@ -1193,29 +1317,30 @@ function done(it: BTreeIter): boolean { return it.fl === it.bl ? it.fi >= it.bi : it.fi === 0 && it.bl.next === it.fl && it.bi === it.bl.k.length; } -/** What `pick` yields of index `i` of leaf `l`. */ -function picked(pick: Pick, l: Leaf, i: number): T { - return (pick === ENTRIES ? [l.k[i], l.v[i]] : pick === KEYS ? l.k[i] : l.v[i]) as T; -} - -function whole(m: BTreeMap, pick: Pick): Iter { +function whole(m: BTreeMap, pick: Pick, k?: (key: K) => void, v?: (value: V) => void, back = false): Iter { const last = end(m, true); - return new BTreeIter(pick, end(m, false), 0, last, last.k.length, m.n); + return new BTreeIter(pick, end(m, false), 0, last, last.k.length, m.n, k, v, back); } -/** `iter`, `iter_mut`, and `into_iter` of a map: its entries in key order. */ -export function btreeIter(m: BTreeMap): Iter<[K, V]> { - return whole(m, ENTRIES); +/** + * `iter` and `iter_mut` of a map, and with what drops each key and value of those that + * drop, `into_iter`: its entries in key order. + */ +export function btreeIter(m: BTreeMap, k?: (key: K) => void, v?: (value: V) => void): Iter<[K, V]> { + return whole(m, ENTRIES, k, v); } -/** `keys` and `into_keys` of a map, and `iter` and `into_iter` of a set. */ -export function btreeKeys(m: BTreeMap): Iter { - return whole(m, KEYS); +/** + * `keys` of a map and `iter` of a set, and with droppers as `btreeIter`'s, `into_iter` of + * a set, or with `back`, `into_keys`. + */ +export function btreeKeys(m: BTreeMap, k?: (key: K) => void, v?: (value: V) => void, back = false): Iter { + return whole(m, KEYS, k, v, back); } -/** `values`, `values_mut`, and `into_values`. */ -export function btreeValues(m: BTreeMap): Iter { - return whole(m, VALUES); +/** `values` and `values_mut`, and with droppers as `btreeIter`'s, `into_values`. */ +export function btreeValues(m: BTreeMap, k?: (key: K) => void, v?: (value: V) => void): Iter { + return whole(m, VALUES, k, v, k !== undefined || v !== undefined); } /** @@ -1264,63 +1389,95 @@ function edge(m: BTreeMap, key: K, past: boolean): [Leaf, numb /** * `extend` of a map with `[key, value]`s, which keeps an equal key already there and drops - * the one given, then the value it replaced. With `last`, `collect` and `from` into an - * empty one, which keep the last of equal keys: std's sorts every entry by key, stably, - * and then drops each but the last of equal keys in that order. + * the one given, then the value it replaced, and drops `items` by `dropIt` once done. With + * `last`, `collect` and `from` of entries that drop nothing into an empty one, which keep + * the last of equal keys, as `btreeCollect` does. */ -export function btreeExtend(m: BTreeMap, items: Iter<[K, V]>, last = false, k?: (key: K) => void, v?: (value: V) => void): BTreeMap { - if (last && (k !== undefined || v !== undefined)) { - const sorted = iterToArray(items).sort((a, b) => m.c(a[0], b[0])); - for (let i = 0; i < sorted.length; i++) { - if (i + 1 < sorted.length && m.c(sorted[i][0], sorted[i + 1][0]) === 0) { - k?.(sorted[i][0]); - v?.(sorted[i][1]); +export function btreeExtend( + m: BTreeMap, + items: Iter<[K, V]>, + last = false, + k?: (key: K) => void, + v?: (value: V) => void, + dropIt?: (it: Iter<[K, V]>) => void, +): BTreeMap { + const f = () => { + for (let item = items.next(); item !== DONE; item = items.next()) { + if (!last) { + const old = btreeInsert(m, item[0], item[1], k, v); + if (old !== undefined) v?.(old); continue; } - btreeInsert(m, sorted[i][0], sorted[i][1]); - } - return m; - } - for (let item = items.next(); item !== DONE; item = items.next()) { - if (!last) { - const old = btreeInsert(m, item[0], item[1], k, v); - if (old !== undefined) v?.(old); - continue; - } - const l = leafOf(m, item[0]); - const i = search(l.k, item[0], m.c); - if (i < 0) insertAt(m, l, ~i, item[0], item[1]); - else { - l.k[i] = item[0]; - l.v[i] = item[1]; + const l = leafOf(m, item[0]); + const i = search(l.k, item[0], m.c); + if (i < 0) insertAt(m, l, ~i, item[0], item[1]); + else { + l.k[i] = item[0]; + l.v[i] = item[1]; + } } - } - return m; + }; + return extending(m, items, f, dropIt); } /** `extend` of a set with keys, and with `last`, `collect` and `from`, as `btreeExtend`. */ -export function btreeExtendKeys(m: BTreeSet, keys: Iter, last = false, k?: (key: K) => void): BTreeSet { - if (last && k !== undefined) { - const sorted = iterToArray(keys).sort(m.c); - for (let i = 0; i < sorted.length; i++) { - if (i + 1 < sorted.length && m.c(sorted[i], sorted[i + 1]) === 0) k(sorted[i]); - else btreeAdd(m, sorted[i]); +export function btreeExtendKeys(m: BTreeSet, keys: Iter, last = false, k?: (key: K) => void, dropIt?: (it: Iter) => void): BTreeSet { + const f = () => { + for (let key = keys.next(); key !== DONE; key = keys.next()) { + if (!last) { + btreeAdd(m, key, k); + continue; + } + const l = leafOf(m, key); + const i = search(l.k, key, m.c); + if (i < 0) insertAt(m, l, ~i, key, undefined); + else l.k[i] = key; } - return m; - } - for (let key = keys.next(); key !== DONE; key = keys.next()) { - if (!last) { - btreeAdd(m, key, k); + }; + return extending(m, keys, f, dropIt); +} + +/** + * `collect` and `from` into `m`, an empty map, of `entries`, which std's collects into a + * `Vec` first: it sorts them by key, stably, and builds the tree of each but the last of + * equal keys, which drop in order. A panic dropping one drops the entries after the next + * and then the next, which std's had peeked, and leaks the tree built so far, as std's. + */ +export function btreeCollect(m: BTreeMap, entries: [K, V][], k?: (key: K) => void, v?: (value: V) => void): BTreeMap { + const sorted = entries.sort((a, b) => m.c(a[0], b[0])); + const keys: K[] = []; + const values: V[] = []; + for (let i = 0; i < sorted.length; i++) { + const [key, value] = sorted[i]; + if (i + 1 === sorted.length || m.c(key, sorted[i + 1][0]) !== 0) { + keys.push(key); + values.push(value); continue; } - const l = leafOf(m, key); - const i = search(l.k, key, m.c); - if (i < 0) insertAt(m, l, ~i, key, undefined); - else l.k[i] = key; + try { + dropPair(key, value, k, v); + } catch (e) { + try { + dropPairs(sorted.map((e) => e[0]), sorted.map((e) => e[1]), k, v, i + 2); + } finally { + dropPair(sorted[i + 1][0], sorted[i + 1][1], k, v); + } + throw e; + } } + build(m, keys, values); return m; } +/** `collect` and `from` into `m`, an empty set, of `keys`, as `btreeCollect`. */ +export function btreeCollectKeys(m: BTreeSet, keys: K[], k?: (key: K) => void): BTreeSet { + return btreeCollect( + m, + keys.map((key) => [key, undefined]), + k, + ); +} + /** `clone`, with each key and value through its `Clone`, or as itself without one. */ export function btreeClone(m: BTreeMap, key: (k: K) => K = itself, value: (v: V) => V = itself): BTreeMap { const keys: K[] = []; @@ -1666,17 +1823,22 @@ export function dequeInsert(q: VecDeque, i: number, item: T): void { q.b[at(q, i)] = item; } -/** An iterator of a deque's items from index `front` up to `back`. */ +/** + * An iterator of a deque's items from index `front` up to `back`, which drops those it + * still holds by `drop` as it drops, if it owns them, as a `drain` does. + */ class DequeIter extends Iter { private readonly q: VecDeque; private front: number; private back: number; + private readonly drop: ((item: T) => void) | undefined; - constructor(q: VecDeque, front: number, back: number) { + constructor(q: VecDeque, front: number, back: number, drop?: (item: T) => void) { super(); this.q = q; this.front = front; this.back = back; + this.drop = drop; } next(): T | Done { @@ -1690,15 +1852,28 @@ class DequeIter extends Iter { override len(): number { return this.back - this.front; } + + override [Symbol.dispose](): void { + if (this.drop === undefined) return; + const items: T[] = []; + while (this.front < this.back) items.push(this.q.b[at(this.q, this.front++)] as T); + dropAll(items, this.drop); + } } -/** `iter`, `iter_mut`, and `into_iter`. */ -export function dequeIter(q: VecDeque): Iter { - return new DequeIter(q, 0, q.n); +/** + * `iter` and `iter_mut`, and with what drops each item, `into_iter`, whose `last`, + * `count`, and skips are a `Vec`'s. + */ +export function dequeIter(q: VecDeque, drop?: (item: T) => void): Iter { + if (drop === undefined) return new DequeIter(q, 0, q.n); + const items: T[] = []; + for (let i = 0; i < q.n; i++) items.push(q.b[at(q, i)] as T); + return iterSlice(items, drop); } -/** `drain`: the items within `r`, taken out at once. */ -export function dequeDrain(q: VecDeque, r: Bounds): Iter { +/** `drain`: the items within `r`, taken out at once, which drop by `drop` as `dequeIter`'s. */ +export function dequeDrain(q: VecDeque, r: Bounds, drop?: (item: T) => void): Iter { // As `slice::range` checks it. const [lo, hi, inclusive] = bounds(r); if (hi !== undefined && (inclusive ? hi.key >= q.n : hi.key > q.n)) panic(`range end index ${hi.key} out of range for slice of length ${q.n}`); @@ -1711,13 +1886,15 @@ export function dequeDrain(q: VecDeque, r: Bounds): Iter { for (let i = start; i < end; i++) dequePushBack(taken, q.b[at(q, i)] as T); for (let i = end; i < q.n; i++) q.b[at(q, i - (end - start))] = q.b[at(q, i)]; dequeTruncate(q, q.n - (end - start)); - return new DequeIter(taken, 0, taken.n); + return new DequeIter(taken, 0, taken.n, drop); } -/** `extend`, and `collect` into a deque through `dequeNew`. */ -export function dequeExtend(q: VecDeque, items: Iter): VecDeque { - for (let item = items.next(); item !== DONE; item = items.next()) dequePushBack(q, item); - return q; +/** `extend`, and `collect` into a deque through `dequeNew`, which drops `items` by `dropIt` once done. */ +export function dequeExtend(q: VecDeque, items: Iter, dropIt?: (it: Iter) => void): VecDeque { + const f = () => { + for (let item = items.next(); item !== DONE; item = items.next()) dequePushBack(q, item); + }; + return extending(q, items, f, dropIt); } /** `clone`, with each item through its `Clone`, or as itself without one. */ diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index 4bc45aaa4..dd9150060 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -7,9 +7,16 @@ // stops: a `find` or `any` reads no further than its match. Adaptors and consumers are // functions, `iterMap(it, f)`, so a bundler drops the ones nothing calls; an iterator's // methods are only what each kind does its own way. +// +// An iterator that owns its items, as a `Vec`'s `into_iter` does, is given what drops +// each, and drops those it still holds as it drops, by `[Symbol.dispose]`; an adaptor +// drops what it wraps. Where std drops an item it skips, rejects, or replaces, the runtime +// function is given what drops it, after its own arguments, and so is a consumer that +// takes the iterator by value, which drops it as std's does, a panic included. import { ByteVec, byteVecPush, Err, Ok, panic, type Result } from "../rt.ts"; import { type Limbs, lt as wideLt, type Step } from "./int.ts"; +import { dropAll, dropRange } from "./task.ts"; /** What `next` returns once an iterator is exhausted, which no item is. */ export const DONE: unique symbol = /* @__PURE__ */ Symbol("DONE"); @@ -17,8 +24,11 @@ export const DONE: unique symbol = /* @__PURE__ */ Symbol("DONE"); /** The type of `DONE`. */ export type Done = typeof DONE; +/** What drops a value. */ +type Drop = (value: T) => void; + /** `Iterator`: `next`, and the methods std's iterators each do their own way. */ -export abstract class Iter implements Iterable { +export abstract class Iter implements Iterable, Disposable { /** The next item, or `DONE`. */ abstract next(): T | Done; @@ -32,24 +42,104 @@ export abstract class Iter implements Iterable { throw new Error("rust2-ts: an iterator without `len`"); } - /** `nth`, as `next` returns it. */ - nthItem(n: number): T | Done { - for (let i = 0; i < n; i++) if (this.next() === DONE) return DONE; - return this.next(); + /** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ + advanceBy(n: number, drop?: Drop): number { + for (let i = 0; i < n; i++) { + const item = this.next(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; + } + + /** `advance_back_by`, from the back. */ + advanceBackBy(n: number, drop?: Drop): number { + for (let i = 0; i < n; i++) { + const item = this.nextBack(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; + } + + /** `nth`, as `next` returns it, dropping what it skips by `drop`. */ + nthItem(n: number, drop?: Drop): T | Done { + return this.advanceBy(n, drop) === 0 ? this.next() : DONE; } /** `nth_back`, as `next_back` returns it. */ - nthBackItem(n: number): T | Done { - for (let i = 0; i < n; i++) if (this.nextBack() === DONE) return DONE; - return this.nextBack(); + nthBackItem(n: number, drop?: Drop): T | Done { + return this.advanceBackBy(n, drop) === 0 ? this.nextBack() : DONE; + } + + /** `count`, dropping each item by `drop`. */ + countItems(drop?: Drop): number { + let n = 0; + for (let item = this.next(); item !== DONE; item = this.next()) { + drop?.(item); + n++; + } + return n; + } + + /** + * `last`, as std's `fold` takes it: each item drops by `drop` as the next replaces it. + * A panic reading the next drops the last; one dropping it leaks the next, as std's + * unwinding leaves a returned value. + */ + lastItem(drop?: Drop): T | Done { + let last: T | Done = DONE; + if (drop === undefined) { + for (let item = this.next(); item !== DONE; item = this.next()) last = item; + return last; + } + for (;;) { + let item: T | Done; + try { + item = this.next(); + } catch (e) { + if (last !== DONE) drop(last); + throw e; + } + if (item === DONE) return last; + const prev = last; + last = item; + if (prev !== DONE) drop(prev); + } } + /** Drop what it owns and still holds: nothing, unless it was made owning its items. */ + [Symbol.dispose](): void {} + /** Its items, for a JS `for ... of`. */ *[Symbol.iterator](): Iterator { for (let item = this.next(); item !== DONE; item = this.next()) yield item; } } +/** An adaptor of `inner`, which drops with it. */ +abstract class Adaptor extends Iter { + readonly inner: Iter; + + constructor(inner: Iter) { + super(); + this.inner = inner; + } + + override [Symbol.dispose](): void { + this.inner[Symbol.dispose](); + } +} + +/** Run `a`, then `b` even if `a` panics, as glue drops each field after one panics. */ +function both(a: () => void, b: () => void): void { + try { + a(); + } finally { + b(); + } +} + /** The item `next` returned, as an `Option`. */ export function iterToOption(item: T | Done): T | undefined { return item === DONE ? undefined : item; @@ -62,19 +152,19 @@ export function iterFromOption(option: T | undefined): T | Done { // Where std's iterators come from. -/** `slice::Iter`, and what iterating a `Vec` or array by value makes. */ -export function iterSlice(s: ArrayLike): Iter { - return new SliceIter(s); +/** `slice::Iter`, and with what drops each item, what iterating a `Vec` or array by value makes. */ +export function iterSlice(s: ArrayLike, drop?: Drop): Iter { + return new SliceIter(s, drop); } -/** `Option::iter`, and `option::IntoIter`. */ -export function iterOption(o: T | undefined): Iter { - return new OptionIter(o); +/** `Option::iter`, and with what drops its item, `option::IntoIter`. */ +export function iterOption(o: T | undefined, drop?: Drop): Iter { + return new OptionIter(o, o !== undefined, drop); } /** `iter::once`. */ -export function iterOnce(value: T): Iter { - return new OptionIter(value, true); +export function iterOnce(value: T, drop?: Drop): Iter { + return new OptionIter(value, true, drop); } /** `iter::empty`. */ @@ -87,19 +177,36 @@ export function iterFromFn(f: () => T | undefined): Iter { return new FromNext(f, (f) => iterFromOption(f())); } -/** An `impl Iterator` of the translated crate, which `next` calls the `next` of. */ -export function iterFrom(source: S, next: (source: S) => T | Done): Iter { - return new FromNext(source, next); +/** An `impl Iterator` of the translated crate, which `next` calls the `next` of, and `drop` drops. */ +export function iterFrom(source: S, next: (source: S) => T | Done, drop?: Drop): Iter { + return new FromNext(source, next, drop); +} + +/** An iterator borrowed by `&mut`, which std's adaptors take as one: its items, but never it to drop. */ +export function iterBorrow(it: Iter): Iter { + return new Borrowed(it); } -/** `Extend::extend` of a `Vec`. */ -export function iterExtend(v: T[], items: Iter): void { - for (let item = items.next(); item !== DONE; item = items.next()) v.push(item); +/** `Extend::extend` of a `Vec`, which drops `items` by `dropIt` once done or a panic. */ +export function iterExtend(v: T[], items: Iter, dropIt?: Drop>): void { + if (dropIt === undefined) { + for (let item = items.next(); item !== DONE; item = items.next()) v.push(item); + return; + } + try { + for (let item = items.next(); item !== DONE; item = items.next()) v.push(item); + } finally { + dropIt(items); + } } /** `Extend::extend` of a `Vec`. */ -export function iterExtendBytes(v: ByteVec, items: Iter): void { - for (let item = items.next(); item !== DONE; item = items.next()) byteVecPush(v, item); +export function iterExtendBytes(v: ByteVec, items: Iter, dropIt?: Drop>): void { + try { + for (let item = items.next(); item !== DONE; item = items.next()) byteVecPush(v, item); + } finally { + dropIt?.(items); + } } // Adaptors @@ -109,9 +216,9 @@ export function iterMap(it: Iter, f: (item: T) => U): Iter { return new MapIter(it, f); } -/** `Iterator::filter`. */ -export function iterFilter(it: Iter, f: (item: T) => boolean): Iter { - return new FilterIter(it, f); +/** `Iterator::filter`, dropping what `f` rejects by `drop`. */ +export function iterFilter(it: Iter, f: (item: T) => boolean, drop?: Drop): Iter { + return new FilterIter(it, f, drop); } /** `Iterator::filter_map`. */ @@ -130,12 +237,13 @@ export function iterChain(it: Iter, other: Iter): Iter { } /** - * `zip`, with `other` already made an iterator, as std does when it is called. A - * `trusted` zip is one of two `TrustedRandomAccess` iterators, which std reads by - * index up to the shorter length and never past it. + * `zip`, with `other` already made an iterator, as std does when it is called, dropping + * an item of either it reads without one of the other by `dropA` or `dropB`. A `trusted` + * zip is one of two `TrustedRandomAccess` iterators, which std reads by index up to the + * shorter length and never past it. */ -export function iterZip(it: Iter, other: Iter, trusted = false): Iter<[T, U]> { - return trusted ? new TrustedZipIter(it, other) : new ZipIter(it, other); +export function iterZip(it: Iter, other: Iter, trusted = false, dropA?: Drop, dropB?: Drop): Iter<[T, U]> { + return trusted ? new TrustedZipIter(it, other) : new ZipIter(it, other, dropA, dropB); } /** `Iterator::rev`. */ @@ -143,24 +251,24 @@ export function iterRev(it: Iter): Iter { return new RevIter(it); } -/** `Iterator::skip`. */ -export function iterSkip(it: Iter, n: number): Iter { - return new SkipIter(it, n); +/** `Iterator::skip`, dropping what it skips by `drop`. */ +export function iterSkip(it: Iter, n: number, drop?: Drop): Iter { + return new SkipIter(it, n, drop); } -/** `Iterator::take`. */ -export function iterTake(it: Iter, n: number): Iter { - return new TakeIter(it, n); +/** `Iterator::take`, dropping what `next_back` skips past its limit by `drop`. */ +export function iterTake(it: Iter, n: number, drop?: Drop): Iter { + return new TakeIter(it, n, drop); } -/** `Iterator::skip_while`. */ -export function iterSkipWhile(it: Iter, f: (item: T) => boolean): Iter { - return new SkipWhileIter(it, f); +/** `Iterator::skip_while`, dropping what it skips by `drop`. */ +export function iterSkipWhile(it: Iter, f: (item: T) => boolean, drop?: Drop): Iter { + return new SkipWhileIter(it, f, drop); } -/** `Iterator::take_while`. */ -export function iterTakeWhile(it: Iter, f: (item: T) => boolean): Iter { - return new TakeWhileIter(it, f); +/** `Iterator::take_while`, dropping the item that ends it by `drop`. */ +export function iterTakeWhile(it: Iter, f: (item: T) => boolean, drop?: Drop): Iter { + return new TakeWhileIter(it, f, drop); } /** `Iterator::map_while`. */ @@ -168,59 +276,77 @@ export function iterMapWhile(it: Iter, f: (item: T) => U | undefined): return new MapWhileIter(it, f); } -/** `Iterator::step_by`, panicking on a step of 0. */ -export function iterStepBy(it: Iter, step: number): Iter { - return new StepByIter(it, step); +/** `Iterator::step_by`, panicking on a step of 0, and dropping what it steps over by `drop`. */ +export function iterStepBy(it: Iter, step: number, drop?: Drop): Iter { + return new StepByIter(it, step, drop); } -/** `Iterator::inspect`. */ -export function iterInspect(it: Iter, f: (item: T) => void): Iter { - return new InspectIter(it, f); +/** `Iterator::inspect`, dropping the item `f` panics on by `drop`. */ +export function iterInspect(it: Iter, f: (item: T) => void, drop?: Drop): Iter { + return new InspectIter(it, f, drop); } -/** `Iterator::fuse`. */ -export function iterFuse(it: Iter): Iter { - return new FuseIter(it); +/** + * `Iterator::fuse`, which drops `it` once it ends, unless it is `fused`, a + * `FusedIterator`, which std's keeps. + */ +export function iterFuse(it: Iter, fused = false): Iter { + return new FuseIter(it, fused); } -/** `Iterator::peekable`. */ -export function iterPeekable(it: Iter): Peekable { - return new Peekable(it); +/** `Iterator::peekable`, which drops an item it peeked by `drop`. */ +export function iterPeekable(it: Iter, drop?: Drop): Peekable { + return new Peekable(it, drop); } -/** `flat_map`: `into` makes each of `f`'s results an iterator, as `IntoIterator` does. */ +/** + * `flat_map`: `into` makes each of `f`'s results an iterator, as `IntoIterator` does. Its + * source drops once it ends unless it is `fused`, as `fuse` does. + */ export function iterFlatMap(it: Iter, f: (item: T) => Iter): Iter; -export function iterFlatMap(it: Iter, f: (item: T) => U, into: (value: U) => Iter): Iter; -export function iterFlatMap(it: Iter, f: (item: T) => U, into?: (value: U) => Iter): Iter { - return new FlattenIter(new MapIter(it, f), into ?? (itself as (value: U) => Iter)); +export function iterFlatMap(it: Iter, f: (item: T) => U, into?: (value: U) => Iter, fused?: boolean): Iter; +export function iterFlatMap(it: Iter, f: (item: T) => U, into?: (value: U) => Iter, fused = false): Iter { + return new FlattenIter(new MapIter(it, f), into ?? (itself as (value: U) => Iter), fused); } -/** `flatten`: `into` makes each item an iterator, as `IntoIterator` does. */ +/** `flatten`: `into` makes each item an iterator, as `IntoIterator` does, and `fused` is as `flat_map`'s. */ export function iterFlatten(it: Iter>): Iter; -export function iterFlatten(it: Iter, into: (value: T) => Iter): Iter; -export function iterFlatten(it: Iter, into?: (value: T) => Iter): Iter { - return new FlattenIter(it, into ?? (itself as (value: T) => Iter)); +export function iterFlatten(it: Iter, into?: (value: T) => Iter, fused?: boolean): Iter; +export function iterFlatten(it: Iter, into?: (value: T) => Iter, fused = false): Iter { + return new FlattenIter(it, into ?? (itself as (value: T) => Iter), fused); } -// Consumers +// Consumers. Each that takes the iterator by value drops it by `dropIt` once done, or as +// a panic unwinds through it. -/** `Iterator::count`. */ -export function iterCount(it: Iter): number { - let n = 0; - while (it.next() !== DONE) n++; - return n; +/** `Iterator::count`, dropping each item by `drop`. */ +export function iterCount(it: Iter, dropIt?: Drop>, drop?: Drop): number { + if (dropIt === undefined) return it.countItems(drop); + try { + return it.countItems(drop); + } finally { + dropIt(it); + } } -/** `Iterator::last`. */ -export function iterLast(it: Iter): T | undefined { - let last: T | undefined; - for (let item = it.next(); item !== DONE; item = it.next()) last = item; - return last; +/** `Iterator::last`, dropping each item but the last by `drop`. */ +export function iterLast(it: Iter, dropIt?: Drop>, drop?: Drop): T | undefined { + if (dropIt === undefined) return iterToOption(it.lastItem(drop)); + let last: T | Done; + try { + last = it.lastItem(drop); + } catch (e) { + dropIt(it); + throw e; + } + // A panic here leaks the last, as std's unwinding does a returned value. + dropIt(it); + return iterToOption(last); } -/** `Iterator::nth`. */ -export function iterNth(it: Iter, n: number): T | undefined { - return iterToOption(it.nthItem(n)); +/** `Iterator::nth`, dropping what it skips by `drop`. */ +export function iterNth(it: Iter, n: number, drop?: Drop): T | undefined { + return iterToOption(it.nthItem(n, drop)); } /** `Iterator::any`. */ @@ -235,21 +361,41 @@ export function iterAll(it: Iter, f: (item: T) => boolean): boolean { return true; } -/** `find`, as `next` returns it. */ -function findItem(it: Iter, f: (item: T) => boolean): T | Done { - for (let item = it.next(); item !== DONE; item = it.next()) if (f(item)) return item; +/** `find`, as `next` returns it: what `f` rejects, or panics on, drops by `drop`. */ +function findItem(it: Iter, f: (item: T) => boolean, drop?: Drop): T | Done { + if (drop === undefined) { + for (let item = it.next(); item !== DONE; item = it.next()) if (f(item)) return item; + return DONE; + } + for (let item = it.next(); item !== DONE; item = it.next()) { + if (test(f, item, drop)) return item; + drop(item); + } return DONE; } /** `rfind`, as `next_back` returns it. */ -function rfindItem(it: Iter, f: (item: T) => boolean): T | Done { - for (let item = it.nextBack(); item !== DONE; item = it.nextBack()) if (f(item)) return item; +function rfindItem(it: Iter, f: (item: T) => boolean, drop?: Drop): T | Done { + for (let item = it.nextBack(); item !== DONE; item = it.nextBack()) { + if (drop === undefined ? f(item) : test(f, item, drop)) return item; + drop?.(item); + } return DONE; } -/** `Iterator::find`. */ -export function iterFind(it: Iter, f: (item: T) => boolean): T | undefined { - return iterToOption(findItem(it, f)); +/** `f(item)`, dropping `item` by `drop` if it panics. */ +function test(f: (item: T) => boolean, item: T, drop: Drop): boolean { + try { + return f(item); + } catch (e) { + drop(item); + throw e; + } +} + +/** `Iterator::find`, dropping what `f` rejects by `drop`. */ +export function iterFind(it: Iter, f: (item: T) => boolean, drop?: Drop): T | undefined { + return iterToOption(findItem(it, f, drop)); } /** `Iterator::find_map`. */ @@ -271,100 +417,215 @@ export function iterPosition(it: Iter, f: (item: T) => boolean): number | return undefined; } -/** `Iterator::fold`. */ -export function iterFold(it: Iter, init: A, f: (acc: A, item: T) => A): A { +/** + * `Iterator::fold`. A panic reading an item drops the accumulator by `dropAcc`; one in + * `f`, which took it, leaves it to `f`. + */ +export function iterFold(it: Iter, init: A, f: (acc: A, item: T) => A, dropIt?: Drop>, dropAcc?: Drop): A { let acc = init; - for (let item = it.next(); item !== DONE; item = it.next()) acc = f(acc, item); + if (dropIt === undefined && dropAcc === undefined) { + for (let item = it.next(); item !== DONE; item = it.next()) acc = f(acc, item); + return acc; + } + try { + for (;;) { + let item: T | Done; + try { + item = it.next(); + } catch (e) { + dropAcc?.(acc); + throw e; + } + if (item === DONE) break; + acc = f(acc, item); + } + } catch (e) { + dropIt?.(it); + throw e; + } + // A panic here leaks the accumulator, as std's unwinding does a returned value. + dropIt?.(it); return acc; } /** `Iterator::for_each`. */ -export function iterForEach(it: Iter, f: (item: T) => void): void { - for (let item = it.next(); item !== DONE; item = it.next()) f(item); +export function iterForEach(it: Iter, f: (item: T) => void, dropIt?: Drop>): void { + if (dropIt === undefined) { + for (let item = it.next(); item !== DONE; item = it.next()) f(item); + return; + } + try { + for (let item = it.next(); item !== DONE; item = it.next()) f(item); + } finally { + dropIt(it); + } } /** `sum`, adding with an integer type's checked `add`, so overflow panics as Rust's does. */ -export function iterSum(it: Iter, add: (a: T, b: T) => T, zero: T): T { - return iterFold(it, zero, add); +export function iterSum(it: Iter, add: (a: T, b: T) => T, zero: T, dropIt?: Drop>): T { + return iterFold(it, zero, add, dropIt); } /** `product`, multiplying with an integer type's checked `mul`. */ -export function iterProduct(it: Iter, mul: (a: T, b: T) => T, one: T): T { - return iterFold(it, one, mul); +export function iterProduct(it: Iter, mul: (a: T, b: T) => T, one: T, dropIt?: Drop>): T { + return iterFold(it, one, mul, dropIt); } /** `max` of integers or booleans: the last of the greatest, as `Ord::max` keeps it. */ -export function iterMax(it: Iter): K | undefined { - return iterMaxByKey(it, (item) => item); +export function iterMax(it: Iter, dropIt?: Drop>): K | undefined { + return iterMaxByKey(it, (item) => item, dropIt); } /** `min` of integers or booleans: the first of the least. */ -export function iterMin(it: Iter): K | undefined { - return iterMinByKey(it, (item) => item); +export function iterMin(it: Iter, dropIt?: Drop>): K | undefined { + return iterMinByKey(it, (item) => item, dropIt); } -/** `max_by_key` with an integer or boolean key, each item's taken once. */ -export function iterMaxByKey(it: Iter, f: (item: T) => K): T | undefined { - let best = it.next(); - if (best === DONE) return undefined; - let key = f(best); - for (let item = it.next(); item !== DONE; item = it.next()) { - const k = f(item); - if (!lt(k, key)) [best, key] = [item, k]; - } - return best; +/** `max_by_key` with an integer or boolean key, each item's taken once, dropping the others by `drop`. */ +export function iterMaxByKey(it: Iter, f: (item: T) => K, dropIt?: Drop>, drop?: Drop): T | undefined { + return best(it, f, false, dropIt, drop); } -/** `min_by_key` with an integer or boolean key, each item's taken once. */ -export function iterMinByKey(it: Iter, f: (item: T) => K): T | undefined { - let best = it.next(); - if (best === DONE) return undefined; - let key = f(best); - for (let item = it.next(); item !== DONE; item = it.next()) { - const k = f(item); - if (lt(k, key)) [best, key] = [item, k]; +/** `min_by_key` with an integer or boolean key, each item's taken once, dropping the others by `drop`. */ +export function iterMinByKey(it: Iter, f: (item: T) => K, dropIt?: Drop>, drop?: Drop): T | undefined { + return best(it, f, true, dropIt, drop); +} + +/** + * The item of the greatest key, the last of equal ones, or of the least if `least`, the + * first, as std's `reduce` keeps it: each other drops as it loses. A panic in `f` drops + * its item, then the best, then the iterator; one dropping a loser leaks the winner, as + * std's unwinding does a returned value. + */ +function best(it: Iter, f: (item: T) => K, least: boolean, dropIt?: Drop>, drop?: Drop): T | undefined { + if (dropIt === undefined && drop === undefined) { + let best = it.next(); + if (best === DONE) return undefined; + let key = f(best); + for (let item = it.next(); item !== DONE; item = it.next()) { + const k = f(item); + if (least ? lt(k, key) : !lt(k, key)) [best, key] = [item, k]; + } + return best; + } + let best: T | Done = DONE; + let key: K | undefined; + try { + for (let item = it.next(); item !== DONE; item = it.next()) { + let k: K; + try { + k = f(item); + } catch (e) { + drop?.(item); + throw e; + } + if (best === DONE) { + [best, key] = [item, k]; + continue; + } + const wins = least ? lt(k, key as K) : !lt(k, key as K); + const loser = wins ? best : item; + if (wins) [best, key] = [item, k]; + if (drop !== undefined) { + const held: T | Done = best; + best = DONE; + drop(loser); + best = held; + } + } + } catch (e) { + try { + if (best !== DONE) drop?.(best); + } finally { + dropIt?.(it); + } + throw e; } - return best; + // A panic here leaks the best, as std's unwinding does a returned value. + dropIt?.(it); + return iterToOption(best); } -/** `collect` into a `Vec`. */ -export function iterToArray(it: Iter): T[] { +/** + * `collect` into a `Vec`. A panic drops `it` by `dropIt` and then what it collected by + * `drop`, or with `inPlace`, as std's collects into the source `Vec`'s buffer, the other + * way around. + */ +export function iterToArray(it: Iter, inPlace = false, dropIt?: Drop>, drop?: Drop): T[] { const out: T[] = []; - for (let item = it.next(); item !== DONE; item = it.next()) out.push(item); + if (dropIt === undefined && drop === undefined) { + for (let item = it.next(); item !== DONE; item = it.next()) out.push(item); + return out; + } + try { + for (let item = it.next(); item !== DONE; item = it.next()) out.push(item); + } catch (e) { + if (inPlace) both(() => dropAll(out, drop), () => dropIt?.(it)); + else both(() => dropIt?.(it), () => dropAll(out, drop)); + throw e; + } + try { + dropIt?.(it); + } catch (e) { + dropAll(out, drop); + throw e; + } return out; } /** `collect` into a `Vec`. */ -export function iterToByteVec(it: Iter): ByteVec { +export function iterToByteVec(it: Iter, dropIt?: Drop>): ByteVec { const out = new ByteVec(); // Its own loop: through `iterExtendBytes`, JavaScriptCore took 1.9x as long. - for (let item = it.next(); item !== DONE; item = it.next()) byteVecPush(out, item); + try { + for (let item = it.next(); item !== DONE; item = it.next()) byteVecPush(out, item); + } finally { + dropIt?.(it); + } return out; } -/** `collect` of `Result`s: the first error, or every value collected by `into`. */ -export function iterCollectResult(it: Iter>, into: (values: Iter) => C): Result { +/** + * `collect` of `Result`s: the first error, or every value collected by `into`, which drops + * the iterator. On an error, what it collected drops by `drop`; on a panic after one, the + * error drops by `dropErr`. + */ +export function iterCollectResult(it: Iter>, into: (values: Iter) => C, drop?: Drop, dropErr?: Drop): Result { const shunt = new ResultShunt(it); - const values = into(shunt); - return shunt.error === undefined ? Ok(values) : Err(shunt.error.value); + let values: C; + try { + values = into(shunt); + } catch (e) { + if (shunt.error !== undefined) dropErr?.(shunt.error.value); + throw e; + } + if (shunt.error === undefined) return Ok(values); + const error = Err(shunt.error.value); + drop?.(values); + return error; } -/** `collect` of `Option`s: `None` at the first `None`, or every value collected by `into`. */ -export function iterCollectOption(it: Iter, into: (values: Iter) => C): C | undefined { +/** `collect` of `Option`s: `None` at the first `None`, or every value collected by `into`, as `iterCollectResult`. */ +export function iterCollectOption(it: Iter, into: (values: Iter) => C, drop?: Drop): C | undefined { const shunt = new OptionShunt(it); const values = into(shunt); - return shunt.none ? undefined : values; + if (!shunt.none) return values; + drop?.(values); + return undefined; } class SliceIter extends Iter { private readonly s: ArrayLike; private front = 0; private back: number; + /** What drops each item it still holds, if it owns them. */ + private readonly drop: Drop | undefined; - constructor(s: ArrayLike) { + constructor(s: ArrayLike, drop?: Drop) { super(); this.s = s; this.back = s.length; + this.drop = drop; } next(): T | Done { @@ -378,17 +639,52 @@ class SliceIter extends Iter { override len(): number { return this.back - this.front; } + + /** std's, of a `Vec`'s: past them all first, then each dropped, as a slice drops. */ + override advanceBy(n: number, drop?: Drop): number { + const step = Math.min(n, this.back - this.front); + const from = this.front; + this.front += step; + if (drop !== undefined) dropRange(this.s, drop, from, this.front); + return n - step; + } + + /** std's: those it skips drop front to back, as a slice drops. */ + override advanceBackBy(n: number, drop?: Drop): number { + const step = Math.min(n, this.back - this.front); + this.back -= step; + if (drop !== undefined) dropRange(this.s, drop, this.back, this.back + step); + return n - step; + } + + /** std's, of a `Vec`'s or an array's: the last item, then the rest drop with it. */ + override lastItem(drop?: Drop): T | Done { + if (drop === undefined) return super.lastItem(); + const last = this.nextBack(); + // A panic here leaks the last, as std's unwinding does a returned value. + this[Symbol.dispose](); + return last; + } + + override [Symbol.dispose](): void { + if (this.drop === undefined) return; + const from = this.front; + this.front = this.back; + dropRange(this.s, this.drop, from, this.back); + } } /** `option::IntoIter`, `Once`, and `Empty`: at most one item. */ class OptionIter extends Iter { private item: T | undefined; private some: boolean; + private readonly drop: Drop | undefined; - constructor(item: T | undefined, some = item !== undefined) { + constructor(item: T | undefined, some: boolean, drop?: Drop) { super(); this.item = item; this.some = some; + this.drop = drop; } next(): T | Done { @@ -406,31 +702,76 @@ class OptionIter extends Iter { override len(): number { return this.some ? 1 : 0; } + + override [Symbol.dispose](): void { + if (this.drop === undefined) return; + const item = this.next(); + if (item !== DONE) this.drop(item); + } } -/** An iterator whose `next` is a function of its source. */ +/** An iterator whose `next` is a function of its source, which `drop` drops. */ class FromNext extends Iter { private readonly source: S; private readonly step: (source: S) => T | Done; + private drop: Drop | undefined; - constructor(source: S, step: (source: S) => T | Done) { + constructor(source: S, step: (source: S) => T | Done, drop?: Drop) { super(); this.source = source; this.step = step; + this.drop = drop; } next(): T | Done { return this.step(this.source); } + + override [Symbol.dispose](): void { + const drop = this.drop; + this.drop = undefined; + drop?.(this.source); + } +} + +/** An iterator borrowed by `&mut`: dropping it drops nothing. */ +class Borrowed extends Adaptor { + next(): T | Done { + return this.inner.next(); + } + + override nextBack(): T | Done { + return this.inner.nextBack(); + } + + override len(): number { + return this.inner.len(); + } + + override advanceBy(n: number, drop?: Drop): number { + return this.inner.advanceBy(n, drop); + } + + override advanceBackBy(n: number, drop?: Drop): number { + return this.inner.advanceBackBy(n, drop); + } + + override nthItem(n: number, drop?: Drop): T | Done { + return this.inner.nthItem(n, drop); + } + + override nthBackItem(n: number, drop?: Drop): T | Done { + return this.inner.nthBackItem(n, drop); + } + + override [Symbol.dispose](): void {} } -class MapIter extends Iter { - private readonly inner: Iter; +class MapIter extends Adaptor { private readonly f: (item: T) => U; constructor(inner: Iter, f: (item: T) => U) { - super(); - this.inner = inner; + super(inner); this.f = f; } @@ -449,32 +790,30 @@ class MapIter extends Iter { } } -class FilterIter extends Iter { - private readonly inner: Iter; +class FilterIter extends Adaptor { private readonly f: (item: T) => boolean; + private readonly drop: Drop | undefined; - constructor(inner: Iter, f: (item: T) => boolean) { - super(); - this.inner = inner; + constructor(inner: Iter, f: (item: T) => boolean, drop?: Drop) { + super(inner); this.f = f; + this.drop = drop; } next(): T | Done { - return findItem(this.inner, this.f); + return findItem(this.inner, this.f, this.drop); } override nextBack(): T | Done { - return rfindItem(this.inner, this.f); + return rfindItem(this.inner, this.f, this.drop); } } -class FilterMapIter extends Iter { - private readonly inner: Iter; +class FilterMapIter extends Adaptor { private readonly f: (item: T) => U | undefined; constructor(inner: Iter, f: (item: T) => U | undefined) { - super(); - this.inner = inner; + super(inner); this.f = f; } @@ -495,15 +834,9 @@ class FilterMapIter extends Iter { } } -class EnumerateIter extends Iter<[number, T]> { - private readonly inner: Iter; +class EnumerateIter extends Adaptor { private index = 0; - constructor(inner: Iter) { - super(); - this.inner = inner; - } - next(): [number, T] | Done { const item = this.inner.next(); return item === DONE ? DONE : [this.index++, item]; @@ -514,26 +847,49 @@ class EnumerateIter extends Iter<[number, T]> { return item === DONE ? DONE : [this.index + this.inner.len(), item]; } + /** std's, which counts what its iterator skipped. */ + override advanceBy(n: number, drop?: Drop<[number, T]>): number { + const left = this.inner.advanceBy(n, items(drop)); + this.index += n - left; + return left; + } + + override advanceBackBy(n: number, drop?: Drop<[number, T]>): number { + return this.inner.advanceBackBy(n, items(drop)); + } + /** std's `nth`, which counts only when it finds an item. */ - override nthItem(n: number): [number, T] | Done { - const item = this.inner.nthItem(n); + override nthItem(n: number, drop?: Drop<[number, T]>): [number, T] | Done { + const item = this.inner.nthItem(n, items(drop)); if (item === DONE) return DONE; const i = this.index + n; this.index = i + 1; return [i, item]; } - override nthBackItem(n: number): [number, T] | Done { - const item = this.inner.nthBackItem(n); + override nthBackItem(n: number, drop?: Drop<[number, T]>): [number, T] | Done { + const item = this.inner.nthBackItem(n, items(drop)); return item === DONE ? DONE : [this.index + this.inner.len(), item]; } + override countItems(drop?: Drop<[number, T]>): number { + return this.inner.countItems(items(drop)); + } + override len(): number { return this.inner.len(); } } -/** `Chain`, which stops reading its first iterator once it ends, but not its second. */ +/** What drops an `enumerate`'s item, of one its iterator yields. */ +function items(drop: Drop<[number, T]> | undefined): Drop | undefined { + return drop === undefined ? undefined : (item) => drop([0, item]); +} + +/** + * `Chain`, which drops its first iterator once it ends, but not its second, as std's + * stops reading it. + */ class ChainIter extends Iter { private a: Iter | undefined; private b: Iter | undefined; @@ -544,11 +900,25 @@ class ChainIter extends Iter { this.b = b; } + /** Drop `a`, which ended. */ + private endA(): void { + const a = this.a; + this.a = undefined; + a?.[Symbol.dispose](); + } + + /** Drop `b`, which ended from the back. */ + private endB(): void { + const b = this.b; + this.b = undefined; + b?.[Symbol.dispose](); + } + next(): T | Done { if (this.a !== undefined) { const item = this.a.next(); if (item !== DONE) return item; - this.a = undefined; + this.endA(); } return this.b === undefined ? DONE : this.b.next(); } @@ -557,37 +927,161 @@ class ChainIter extends Iter { if (this.b !== undefined) { const item = this.b.nextBack(); if (item !== DONE) return item; - this.b = undefined; + this.endB(); } return this.a === undefined ? DONE : this.a.nextBack(); } + + override advanceBy(n: number, drop?: Drop): number { + if (this.a !== undefined) { + n = this.a.advanceBy(n, drop); + if (n === 0) return 0; + this.endA(); + } + return this.b === undefined ? n : this.b.advanceBy(n, drop); + } + + override advanceBackBy(n: number, drop?: Drop): number { + if (this.b !== undefined) { + n = this.b.advanceBackBy(n, drop); + if (n === 0) return 0; + this.endB(); + } + return this.a === undefined ? n : this.a.advanceBackBy(n, drop); + } + + override nthItem(n: number, drop?: Drop): T | Done { + if (this.a !== undefined) { + n = this.a.advanceBy(n, drop); + if (n === 0) { + const item = this.a.next(); + if (item !== DONE) return item; + } + this.endA(); + } + return this.b === undefined ? DONE : this.b.nthItem(n, drop); + } + + override nthBackItem(n: number, drop?: Drop): T | Done { + if (this.b !== undefined) { + n = this.b.advanceBackBy(n, drop); + if (n === 0) { + const item = this.b.nextBack(); + if (item !== DONE) return item; + } + this.endB(); + } + return this.a === undefined ? DONE : this.a.nthBackItem(n, drop); + } + + /** std's: each iterator's own `count`, the first's first. */ + override countItems(drop?: Drop): number { + const a = this.a; + this.a = undefined; + const n = a === undefined ? 0 : consumed(a, () => a.countItems(drop)); + const b = this.b; + this.b = undefined; + return n + (b === undefined ? 0 : consumed(b, () => b.countItems(drop))); + } + + /** + * std's: each iterator's last, the first's held while the second is read, and dropped + * once the second has one. + */ + override lastItem(drop?: Drop): T | Done { + const a = this.a; + this.a = undefined; + const aLast = a === undefined ? DONE : consumed(a, () => a.lastItem(drop)); + const b = this.b; + this.b = undefined; + if (b === undefined) return aLast; + let bLast: T | Done; + try { + bLast = consumed(b, () => b.lastItem(drop)); + } catch (e) { + if (aLast !== DONE) drop?.(aLast); + throw e; + } + if (bLast === DONE) return aLast; + // A panic here leaks the second's, as std's unwinding does a returned value. + if (aLast !== DONE) drop?.(aLast); + return bLast; + } + + override [Symbol.dispose](): void { + both( + () => this.endA(), + () => this.endB(), + ); + } +} + +/** + * `f()`, a consumer of `it` by value, and then `it` dropped, as a panic unwinds too; a + * panic dropping it leaks what `f` returned, as std's unwinding does. + */ +function consumed(it: Iter, f: () => R): R { + let r: R; + try { + r = f(); + } catch (e) { + it[Symbol.dispose](); + throw e; + } + it[Symbol.dispose](); + return r; } class ZipIter extends Iter<[A, B]> { - private readonly a: Iter; - private readonly b: Iter; + protected readonly a: Iter; + protected readonly b: Iter; + private readonly dropA: Drop | undefined; + private readonly dropB: Drop | undefined; - constructor(a: Iter, b: Iter) { + constructor(a: Iter, b: Iter, dropA?: Drop, dropB?: Drop) { super(); this.a = a; this.b = b; + this.dropA = dropA; + this.dropB = dropB; } + /** An item of `a` it read, dropped if reading `b` panics or ends. */ next(): [A, B] | Done { const a = this.a.next(); if (a === DONE) return DONE; - const b = this.b.next(); - return b === DONE ? DONE : [a, b]; + let b: B | Done; + try { + b = this.b.next(); + } catch (e) { + this.dropA?.(a); + throw e; + } + if (b !== DONE) return [a, b]; + this.dropA?.(a); + return DONE; } /** std's: the longer side drops its extra items from the back first. */ override nextBack(): [A, B] | Done { const aLen = this.a.len(); const bLen = this.b.len(); - for (let i = bLen; i < aLen; i++) this.a.nextBack(); - for (let i = aLen; i < bLen; i++) this.b.nextBack(); + for (let i = bLen; i < aLen; i++) { + const item = this.a.nextBack(); + if (item !== DONE) this.dropA?.(item); + } + for (let i = aLen; i < bLen; i++) { + const item = this.b.nextBack(); + if (item !== DONE) this.dropB?.(item); + } const a = this.a.nextBack(); - const b = this.b.nextBack(); + let b: B | Done; + try { + b = this.b.nextBack(); + } catch (e) { + if (a !== DONE) this.dropA?.(a); + throw e; + } if (a === DONE && b === DONE) return DONE; if (a === DONE || b === DONE) panic("internal error: entered unreachable code"); return [a, b]; @@ -596,6 +1090,13 @@ class ZipIter extends Iter<[A, B]> { override len(): number { return Math.min(this.a.len(), this.b.len()); } + + override [Symbol.dispose](): void { + both( + () => this.a[Symbol.dispose](), + () => this.b[Symbol.dispose](), + ); + } } /** std's `Zip` of two `TrustedRandomAccess` iterators, which counts the pairs it reads. */ @@ -625,14 +1126,7 @@ class TrustedZipIter extends ZipIter { } } -class RevIter extends Iter { - private readonly inner: Iter; - - constructor(inner: Iter) { - super(); - this.inner = inner; - } - +class RevIter extends Adaptor { next(): T | Done { return this.inner.nextBack(); } @@ -641,12 +1135,20 @@ class RevIter extends Iter { return this.inner.next(); } - override nthItem(n: number): T | Done { - return this.inner.nthBackItem(n); + override advanceBy(n: number, drop?: Drop): number { + return this.inner.advanceBackBy(n, drop); } - override nthBackItem(n: number): T | Done { - return this.inner.nthItem(n); + override advanceBackBy(n: number, drop?: Drop): number { + return this.inner.advanceBy(n, drop); + } + + override nthItem(n: number, drop?: Drop): T | Done { + return this.inner.nthBackItem(n, drop); + } + + override nthBackItem(n: number, drop?: Drop): T | Done { + return this.inner.nthItem(n, drop); } override len(): number { @@ -654,40 +1156,78 @@ class RevIter extends Iter { } } -class SkipIter extends Iter { - private readonly inner: Iter; +class SkipIter extends Adaptor { private n: number; + private readonly drop: Drop | undefined; - constructor(inner: Iter, n: number) { - super(); - this.inner = inner; + constructor(inner: Iter, n: number, drop?: Drop) { + super(inner); this.n = n; + this.drop = drop; } next(): T | Done { if (this.n === 0) return this.inner.next(); const n = this.n; this.n = 0; - return this.inner.nthItem(n); + return this.inner.nthItem(n, this.drop); } override nextBack(): T | Done { return this.len() > 0 ? this.inner.nextBack() : DONE; } + /** std's: what it still skips and then `n` more, in one step. */ + override nthItem(n: number, drop?: Drop): T | Done { + const skip = this.n; + this.n = 0; + return this.inner.nthItem(skip + n, drop); + } + + override advanceBy(n: number, drop?: Drop): number { + const skip = this.n; + const left = this.inner.advanceBy(skip + n, drop); + const advanced = skip + n - left; + this.n = Math.max(skip - advanced, 0); + return n - Math.max(advanced - skip, 0); + } + + /** std's: past what it skips by `nth`, and then its iterator's own `count`. */ + override countItems(drop?: Drop): number { + if (this.skipped(drop)) return 0; + return consumed(this.inner, () => this.inner.countItems(drop)); + } + + /** std's: past what it skips by `nth`, and then its iterator's own `last`. */ + override lastItem(drop?: Drop): T | Done { + if (this.skipped(drop)) return DONE; + return consumed(this.inner, () => this.inner.lastItem(drop)); + } + + /** Read past what it still skips, as `nth` reads, and whether its iterator ended first. */ + private skipped(drop: Drop | undefined): boolean { + if (this.n === 0) return false; + const n = this.n; + this.n = 0; + const item = this.inner.nthItem(n - 1, drop); + if (item === DONE) return true; + drop?.(item); + return false; + } + override len(): number { return Math.max(this.inner.len() - this.n, 0); } } -class TakeIter extends Iter { - private readonly inner: Iter; +class TakeIter extends Adaptor { private n: number; + private readonly drop: Drop | undefined; - constructor(inner: Iter, n: number) { - super(); - this.inner = inner; + constructor(inner: Iter, n: number, drop?: Drop) { + super(inner); this.n = n; + this.drop = drop; } next(): T | Done { @@ -696,93 +1236,116 @@ class TakeIter extends Iter { return this.inner.next(); } + /** std's: what its iterator holds past the limit drops as it reads from the back. */ override nextBack(): T | Done { if (this.n === 0) return DONE; const n = this.n--; - return this.inner.nthBackItem(Math.max(this.inner.len() - n, 0)); + return this.inner.nthBackItem(Math.max(this.inner.len() - n, 0), this.drop); } - /** std's `nth`: past the limit, it reads the rest of the limit through and ends. */ - override nthItem(n: number): T | Done { + /** std's `nth`: past the limit, it reads the rest of the limit through, drops it, and ends. */ + override nthItem(n: number, drop?: Drop): T | Done { if (this.n > n) { this.n -= n + 1; - return this.inner.nthItem(n); + return this.inner.nthItem(n, drop); } if (this.n > 0) { - this.inner.nthItem(this.n - 1); + const item = this.inner.nthItem(this.n - 1, drop); + if (item !== DONE) drop?.(item); this.n = 0; } return DONE; } /** std's `nth_back`: past the limit, it reads the whole rest from the back, even at a limit of 0. */ - override nthBackItem(n: number): T | Done { + override nthBackItem(n: number, drop?: Drop): T | Done { const len = this.inner.len(); if (this.n > n) { const m = Math.max(len - this.n, 0) + n; this.n -= n + 1; - return this.inner.nthBackItem(m); + return this.inner.nthBackItem(m, drop); + } + if (len > 0) { + const item = this.inner.nthBackItem(len - 1, drop); + if (item !== DONE) drop?.(item); } - if (len > 0) this.inner.nthBackItem(len - 1); return DONE; } + /** std's: its iterator advanced through the limit, dropping what it passes. */ + override countItems(drop?: Drop): number { + if (this.n === 0) return 0; + const n = this.n; + this.n = 0; + return n - this.inner.advanceBy(n, drop); + } + + override advanceBy(n: number, drop?: Drop): number { + const min = Math.min(this.n, n); + const advanced = min - this.inner.advanceBy(min, drop); + this.n -= advanced; + return n - advanced; + } + override len(): number { return Math.min(this.inner.len(), this.n); } } -class SkipWhileIter extends Iter { - private readonly inner: Iter; +class SkipWhileIter extends Adaptor { private readonly f: (item: T) => boolean; + private readonly drop: Drop | undefined; private flag = false; - constructor(inner: Iter, f: (item: T) => boolean) { - super(); - this.inner = inner; + constructor(inner: Iter, f: (item: T) => boolean, drop?: Drop) { + super(inner); this.f = f; + this.drop = drop; } next(): T | Done { - return findItem(this.inner, (item) => { - if (this.flag || !this.f(item)) { - this.flag = true; - return true; - } - return false; - }); + return findItem( + this.inner, + (item) => { + if (this.flag || !this.f(item)) { + this.flag = true; + return true; + } + return false; + }, + this.drop, + ); } } -class TakeWhileIter extends Iter { - private readonly inner: Iter; +class TakeWhileIter extends Adaptor { private readonly f: (item: T) => boolean; + private readonly drop: Drop | undefined; private flag = false; - constructor(inner: Iter, f: (item: T) => boolean) { - super(); - this.inner = inner; + constructor(inner: Iter, f: (item: T) => boolean, drop?: Drop) { + super(inner); this.f = f; + this.drop = drop; } next(): T | Done { if (this.flag) return DONE; const item = this.inner.next(); if (item === DONE) return DONE; - if (this.f(item)) return item; + if (this.drop === undefined ? this.f(item) : test(this.f, item, this.drop)) return item; this.flag = true; + this.drop?.(item); return DONE; } } /** `MapWhile`, which reads on after `f` returns `None` if called again, as std's does. */ -class MapWhileIter extends Iter { - private readonly inner: Iter; +class MapWhileIter extends Adaptor { private readonly f: (item: T) => U | undefined; constructor(inner: Iter, f: (item: T) => U | undefined) { - super(); - this.inner = inner; + super(inner); this.f = f; } @@ -792,28 +1355,32 @@ class MapWhileIter extends Iter { } } -class StepByIter extends Iter { - private readonly inner: Iter; +class StepByIter extends Adaptor { private readonly step: number; + private readonly drop: Drop | undefined; private firstTake = true; - constructor(inner: Iter, step: number) { - super(); - if (step === 0) panic("assertion failed: step != 0"); - this.inner = inner; + constructor(inner: Iter, step: number, drop?: Drop) { + super(inner); + // The iterator it was given drops as the panic unwinds. + if (step === 0) { + inner[Symbol.dispose](); + panic("assertion failed: step != 0"); + } this.step = step - 1; + this.drop = drop; } next(): T | Done { const n = this.firstTake ? 0 : this.step; this.firstTake = false; - return this.inner.nthItem(n); + return this.inner.nthItem(n, this.drop); } override nextBack(): T | Done { const rem = this.inner.len() % (this.step + 1); const n = this.firstTake ? (rem === 0 ? this.step : rem - 1) : rem; - return this.inner.nthBackItem(n); + return this.inner.nthBackItem(n, this.drop); } override len(): number { @@ -823,25 +1390,29 @@ class StepByIter extends Iter { } } -class InspectIter extends Iter { - private readonly inner: Iter; +class InspectIter extends Adaptor { private readonly f: (item: T) => void; + private readonly drop: Drop | undefined; - constructor(inner: Iter, f: (item: T) => void) { - super(); - this.inner = inner; + constructor(inner: Iter, f: (item: T) => void, drop?: Drop) { + super(inner); this.f = f; + this.drop = drop; } next(): T | Done { - const item = this.inner.next(); - if (item !== DONE) this.f(item); - return item; + return this.inspect(this.inner.next()); } override nextBack(): T | Done { - const item = this.inner.nextBack(); - if (item !== DONE) this.f(item); + return this.inspect(this.inner.nextBack()); + } + + /** `f` of `item`, which drops if `f` panics. */ + private inspect(item: T | Done): T | Done { + if (item === DONE) return item; + if (this.drop === undefined) this.f(item); + else test((item) => (this.f(item), true), item, this.drop); return item; } @@ -852,56 +1423,126 @@ class InspectIter extends Iter { class FuseIter extends Iter { private inner: Iter | undefined; + /** Whether its iterator is a `FusedIterator`, which std's keeps once it ends. */ + private readonly fused: boolean; - constructor(inner: Iter) { + constructor(inner: Iter, fused: boolean) { super(); this.inner = inner; + this.fused = fused; } - next(): T | Done { - if (this.inner === undefined) return DONE; - const item = this.inner.next(); - if (item === DONE) this.inner = undefined; + /** `item`, dropping its iterator first if it ended there and is not fused. */ + private clear(item: T | Done): T | Done { + if (item === DONE && !this.fused) { + const inner = this.inner; + this.inner = undefined; + inner?.[Symbol.dispose](); + } return item; } + next(): T | Done { + return this.inner === undefined ? DONE : this.clear(this.inner.next()); + } + override nextBack(): T | Done { - if (this.inner === undefined) return DONE; - const item = this.inner.nextBack(); - if (item === DONE) this.inner = undefined; - return item; + return this.inner === undefined ? DONE : this.clear(this.inner.nextBack()); + } + + override nthItem(n: number, drop?: Drop): T | Done { + return this.inner === undefined ? DONE : this.clear(this.inner.nthItem(n, drop)); + } + + override nthBackItem(n: number, drop?: Drop): T | Done { + return this.inner === undefined ? DONE : this.clear(this.inner.nthBackItem(n, drop)); + } + + override advanceBy(n: number, drop?: Drop): number { + if (this.inner === undefined) return n; + const left = this.inner.advanceBy(n, drop); + if (left > 0) this.clear(DONE); + return left; + } + + override advanceBackBy(n: number, drop?: Drop): number { + if (this.inner === undefined) return n; + const left = this.inner.advanceBackBy(n, drop); + if (left > 0) this.clear(DONE); + return left; + } + + override countItems(drop?: Drop): number { + const inner = this.inner; + this.inner = undefined; + return inner === undefined ? 0 : consumed(inner, () => inner.countItems(drop)); + } + + override lastItem(drop?: Drop): T | Done { + const inner = this.inner; + this.inner = undefined; + return inner === undefined ? DONE : consumed(inner, () => inner.lastItem(drop)); } override len(): number { return this.inner === undefined ? 0 : this.inner.len(); } + + override [Symbol.dispose](): void { + const inner = this.inner; + this.inner = undefined; + inner?.[Symbol.dispose](); + } } -/** `Flatten` and `FlatMap`, which stop reading their outer iterator once it ends. */ +/** + * `Flatten` and `FlatMap`: the iterator of each item it reads, which drops once it ends, + * as does its source unless it is `fused`. + */ class FlattenIter extends Iter { private outer: Iter | undefined; private readonly into: (value: T) => Iter; + private readonly fused: boolean; private front: Iter | undefined; private back: Iter | undefined; - constructor(outer: Iter, into: (value: T) => Iter) { + constructor(outer: Iter, into: (value: T) => Iter, fused: boolean) { super(); this.outer = outer; this.into = into; + this.fused = fused; + } + + /** The source's next item, or `DONE`, which drops it unless it is fused. */ + private nextOuter(back: boolean): T | Done { + const outer = this.outer; + if (outer === undefined) return DONE; + const item = back ? outer.nextBack() : outer.next(); + if (item === DONE && !this.fused) { + this.outer = undefined; + outer[Symbol.dispose](); + } + return item; + } + + /** `it`'s next item, from the back if `back`, dropping it if it ended. */ + private static step(it: Iter, back: boolean): V | Done { + const item = back ? it.nextBack() : it.next(); + if (item === DONE) it[Symbol.dispose](); + return item; } next(): V | Done { for (;;) { if (this.front !== undefined) { - const item = this.front.next(); + const item = FlattenIter.step(this.front, false); if (item !== DONE) return item; this.front = undefined; } - const inner = this.outer === undefined ? DONE : this.outer.next(); + const inner = this.nextOuter(false); if (inner === DONE) { - this.outer = undefined; if (this.back === undefined) return DONE; - const item = this.back.next(); + const item = FlattenIter.step(this.back, false); if (item === DONE) this.back = undefined; return item; } @@ -912,38 +1553,201 @@ class FlattenIter extends Iter { override nextBack(): V | Done { for (;;) { if (this.back !== undefined) { - const item = this.back.nextBack(); + const item = FlattenIter.step(this.back, true); if (item !== DONE) return item; this.back = undefined; } - const inner = this.outer === undefined ? DONE : this.outer.nextBack(); + const inner = this.nextOuter(true); if (inner === DONE) { - this.outer = undefined; if (this.front === undefined) return DONE; - const item = this.front.nextBack(); + const item = FlattenIter.step(this.front, true); if (item === DONE) this.front = undefined; return item; } this.back = this.into(inner); } } + + /** Hold `it` as the front iterator, dropping the one it held, as std's `insert` does. */ + private setFront(it: Iter | undefined): void { + const old = this.front; + this.front = it; + old?.[Symbol.dispose](); + } + + private setBack(it: Iter | undefined): void { + const old = this.back; + this.back = it; + old?.[Symbol.dispose](); + } + + /** + * std's, by `try_fold`: each iterator in turn advanced by its own `advance_by`, one that + * falls short dropped only as the next replaces it, and the source dropped once it ends + * unless it is fused. + */ + override advanceBy(n: number, drop?: Drop): number { + if (this.front !== undefined) { + n = this.front.advanceBy(n, drop); + if (n === 0) return 0; + } + this.setFront(undefined); + const outer = this.outer; + if (outer !== undefined) { + for (let inner = outer.next(); inner !== DONE; inner = outer.next()) { + const it = this.into(inner); + this.setFront(it); + n = it.advanceBy(n, drop); + if (n === 0) return 0; + } + if (!this.fused) { + this.outer = undefined; + outer[Symbol.dispose](); + } + } + this.setFront(undefined); + if (this.back !== undefined) { + n = this.back.advanceBy(n, drop); + if (n === 0) return 0; + } + this.setBack(undefined); + return n; + } + + override advanceBackBy(n: number, drop?: Drop): number { + if (this.back !== undefined) { + n = this.back.advanceBackBy(n, drop); + if (n === 0) return 0; + } + this.setBack(undefined); + const outer = this.outer; + if (outer !== undefined) { + for (let inner = outer.nextBack(); inner !== DONE; inner = outer.nextBack()) { + const it = this.into(inner); + this.setBack(it); + n = it.advanceBackBy(n, drop); + if (n === 0) return 0; + } + if (!this.fused) { + this.outer = undefined; + outer[Symbol.dispose](); + } + } + this.setBack(undefined); + if (this.front !== undefined) { + n = this.front.advanceBackBy(n, drop); + if (n === 0) return 0; + } + this.setFront(undefined); + return n; + } + + /** std's: each iterator's own `count` in turn, each dropped once counted. */ + override countItems(drop?: Drop): number { + let n = 0; + const count = (it: Iter): void => { + n += consumed(it, () => it.countItems(drop)); + }; + this.consume(count); + return n; + } + + /** + * Run `f` on each iterator in turn, the front, each of the source's, and the back, as + * std's `fold` takes them by value; the source drops once read through. + */ + private consume(f: (it: Iter) => void, onPanic?: () => void): void { + const front = this.front; + this.front = undefined; + if (front !== undefined) f(front); + const outer = this.outer; + this.outer = undefined; + if (outer !== undefined) { + consumed(outer, () => { + for (;;) { + let inner: T | Done; + try { + inner = outer.next(); + } catch (e) { + onPanic?.(); + throw e; + } + if (inner === DONE) return; + f(this.into(inner)); + } + }); + } + const back = this.back; + this.back = undefined; + if (back !== undefined) f(back); + } + + /** + * std's: the last of each iterator in turn, each dropped once read, and the last so far + * dropped once a later one has one. + */ + override lastItem(drop?: Drop): V | Done { + let last: V | Done = DONE; + const take = (it: Iter): void => { + let item: V | Done; + try { + item = consumed(it, () => it.lastItem(drop)); + } catch (e) { + if (last !== DONE) drop?.(last); + throw e; + } + if (item === DONE) return; + const prev = last; + last = item; + // A panic here leaks the later one, as std's unwinding does a returned value. + if (prev !== DONE) drop?.(prev); + }; + this.consume(take, () => { + if (last !== DONE) drop?.(last); + }); + return last; + } + + override [Symbol.dispose](): void { + const outer = this.outer; + const front = this.front; + const back = this.back; + this.outer = undefined; + this.front = undefined; + this.back = undefined; + both( + () => outer?.[Symbol.dispose](), + () => + both( + () => front?.[Symbol.dispose](), + () => back?.[Symbol.dispose](), + ), + ); + } } -/** `Peekable`. */ -export class Peekable extends Iter { - readonly inner: Iter; +/** `Peekable`, which drops the item it peeked by `drop`. */ +export class Peekable extends Adaptor { peeked = false; item: T | Done = DONE; + readonly drop: Drop | undefined; - constructor(inner: Iter) { - super(); - this.inner = inner; + constructor(inner: Iter, drop?: Drop) { + super(inner); + this.drop = drop; + } + + /** The item it peeked, if any, which it no longer holds. */ + private take(): T | Done { + this.peeked = false; + const item = this.item; + this.item = DONE; + return item; } next(): T | Done { if (!this.peeked) return this.inner.next(); - this.peeked = false; - return this.item; + return this.take(); } override nextBack(): T | Done { @@ -957,10 +1761,70 @@ export class Peekable extends Iter { return peeked; } + /** std's: the item it peeked drops after what its iterator skips. */ + override nthItem(n: number, drop?: Drop): T | Done { + if (!this.peeked) return this.inner.nthItem(n, drop); + const peeked = this.take(); + if (peeked === DONE) return DONE; + if (n === 0) return peeked; + let item: T | Done; + try { + item = this.inner.nthItem(n - 1, drop); + } catch (e) { + drop?.(peeked); + throw e; + } + // A panic here leaks the item, as std's unwinding does a returned value. + drop?.(peeked); + return item; + } + + /** std's: the item it peeked drops after its iterator is counted. */ + override countItems(drop?: Drop): number { + if (!this.peeked) return consumed(this.inner, () => this.inner.countItems(drop)); + const peeked = this.take(); + if (peeked === DONE) return 0; + try { + return 1 + consumed(this.inner, () => this.inner.countItems(drop)); + } finally { + drop?.(peeked); + } + } + + /** std's: the item it peeked, unless its iterator has a last, which drops it after. */ + override lastItem(drop?: Drop): T | Done { + let peeked: T | Done = DONE; + if (this.peeked) { + peeked = this.take(); + if (peeked === DONE) return DONE; + } + let last: T | Done; + try { + last = consumed(this.inner, () => this.inner.lastItem(drop)); + } catch (e) { + if (peeked !== DONE) drop?.(peeked); + throw e; + } + if (last === DONE) return peeked; + // A panic here leaks the last, as std's unwinding does a returned value. + if (peeked !== DONE) drop?.(peeked); + return last; + } + override len(): number { if (!this.peeked) return this.inner.len(); return this.item === DONE ? 0 : this.inner.len() + 1; } + + override [Symbol.dispose](): void { + both( + () => this.inner[Symbol.dispose](), + () => { + const item = this.take(); + if (item !== DONE) this.drop?.(item); + }, + ); + } } /** `Peekable::peek`. */ @@ -972,25 +1836,19 @@ export function peekablePeek(p: Peekable): T | undefined { return iterToOption(p.item); } -/** `Peekable::next_if`. */ +/** `Peekable::next_if`: an item `f` rejects is peeked again, and one it panics on drops. */ export function peekableNextIf(p: Peekable, f: (item: T) => boolean): T | undefined { const item = p.next(); - if (item !== DONE && f(item)) return item; + if (item !== DONE && (p.drop === undefined ? f(item) : test(f, item, p.drop))) return item; p.peeked = true; p.item = item; return undefined; } /** What `iterCollectResult` collects from: values until the first error, which it keeps. */ -class ResultShunt extends Iter { - private readonly inner: Iter>; +class ResultShunt extends Adaptor, U> { error: { value: E } | undefined; - constructor(inner: Iter>) { - super(); - this.inner = inner; - } - next(): U | Done { if (this.error !== undefined) return DONE; const item = this.inner.next(); @@ -1002,15 +1860,9 @@ class ResultShunt extends Iter { } /** What `iterCollectOption` collects from: values until the first `None`. */ -class OptionShunt extends Iter { - private readonly inner: Iter; +class OptionShunt extends Adaptor { none = false; - constructor(inner: Iter) { - super(); - this.inner = inner; - } - next(): U | Done { if (this.none) return DONE; const item = this.inner.next(); diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index ab34eef1b..42b48ea09 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -15,18 +15,20 @@ export function drop(value: unknown): void { } /** - * Drop every element of `values`, in order, by `f` if it has no `[Symbol.dispose]`. A - * panic in one still drops the rest, and then goes on, as std's slices do. + * Drop every element of `values` from `from` on, in order, by `f` if it has no + * `[Symbol.dispose]`. A panic in one still drops the rest, and then goes on, as std's + * slices do. */ -export function dropAll(values: readonly T[] | undefined, f: (value: T) => void = drop): void { - if (values !== undefined) dropFrom(values, f, 0); +export function dropAll(values: ArrayLike | undefined, f: (value: T) => void = drop, from = 0): void { + if (values !== undefined) dropRange(values, f, from, values.length); } -function dropFrom(values: readonly T[], f: (value: T) => void, i: number): void { +/** Drop `values[from..to]` as `dropAll` does. */ +export function dropRange(values: ArrayLike, f: (value: T) => void, from: number, to: number): void { try { - for (; i < values.length; i++) f(values[i]); + for (; from < to; from++) f(values[from]); } catch (e) { - dropFrom(values, f, i + 1); + dropRange(values, f, from + 1, to); throw e; } } diff --git a/ts/src/census.rs b/ts/src/census.rs index 7232f8ee5..efc4a8c9e 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -139,6 +139,7 @@ const VERBATIM: &[&str] = &[ "Binary", "Copy", "Debug", + "DebugList::entries", "Display", "Drop", "From", @@ -147,6 +148,7 @@ const VERBATIM: &[&str] = &[ "None", "Octal", "Option", + "Ord", "Pointer", "Ready", "Reborrow", @@ -157,7 +159,9 @@ const VERBATIM: &[&str] = &[ "become", "bool", "break", + "collect", "copy_nonoverlapping", + "flatten", "fold", "for", "format_args!", diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index 3c5130046..5d7a96101 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -151,22 +151,12 @@ pub fn call<'tcx>( let Some(lost) = discarded(std, owner, name) else { return Ok(Some(e)); }; - if lost.is_empty() && b.t.drops(coll) { - return Ok(Some(b.err( - span, - format!("`{owner}::{name}` of `{coll}`, which may drop what it holds, which is not supported yet"), - ))); - } - let Some(mut droppers) = b.t.droppers(lost.iter().map(|&n| arg(coll, n)), span) else { + let Some(droppers) = b.t.droppers(lost.iter().map(|&n| arg(coll, n)), span) else { return Ok(Some(Expr::undefined())); }; if droppers.is_empty() { return Ok(Some(e)); } - // `extend` comes before `last`, which only `from` sets. - if owner == "Extend" && matches!(std, Std::BTreeMap | Std::BTreeSet) { - droppers.insert(0, Expr::lit("false")); - } Ok(Some(match e { Expr::Call(f, mut args) => { args.extend(droppers); @@ -181,8 +171,8 @@ pub fn call<'tcx>( /// after its own arguments: the key `insert` and `entry` are given if an equal one is there /// already, and the value `insert` is given if the key's `Hash`, `Eq`, or `Ord` panics, /// the key `remove` takes out, the value `or_insert` is given if one is, the key an -/// `or_insert_with` keeps if its closure panics, and what `clear`, `retain`, `truncate`, -/// `extend`, and `from` discard. An empty list is what an iterator owns, which is refused. +/// `or_insert_with` keeps if its closure panics, and what `clear`, `retain`, and +/// `truncate` discard. An iterator, and `extend` and `from`, take theirs where they map. fn discarded(std: Std, owner: &str, name: &str) -> Option<&'static [usize]> { let map = matches!(std, Std::HashMap | Std::BTreeMap); let set = matches!(std, Std::HashSet | Std::BTreeSet); @@ -191,14 +181,31 @@ fn discarded(std: Std, owner: &str, name: &str) -> Option<&'static [usize]> { (_, "insert" | "entry" | "remove") if map || set => &[0], (_, "remove" | "or_insert_with" | "or_insert_with_key" | "or_default") if std == Std::Entry => &[0], (_, "or_insert") if std == Std::Entry => &[1], - (_, "clear" | "retain" | "retain_mut") | ("Extend", _) | ("From", _) if map => &[0, 1], - (_, "clear" | "retain" | "retain_mut") | ("Extend", _) | ("From", _) if set => &[0], + (_, "clear" | "retain" | "retain_mut") if map => &[0, 1], + (_, "clear" | "retain" | "retain_mut") if set => &[0], (_, "clear" | "retain" | "retain_mut" | "truncate") if std == Std::VecDeque => &[0], - (_, "drain" | "into_keys" | "into_values") => &[], _ => return None, }) } +/// What drops each key, and each value of a map, of a collection of type `coll`, of those +/// that drop: `undefined` for one that drops nothing. +fn entry_droppers<'tcx>(b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, span: Span) -> Vec { + let n = match b.t.std_of(coll) { + Some(Std::HashMap | Std::BTreeMap) => 2, + _ => 1, + }; + (0..n).map(|i| b.t.dropper(arg(coll, i), span)).collect() +} + +/// What a collection of type `coll` stores each of: a key, a `(key, value)`, or an item. +fn stored<'tcx>(b: &Body<'_, '_, 'tcx>, coll: Ty<'tcx>) -> Ty<'tcx> { + match b.t.std_of(coll) { + Some(Std::HashMap | Std::BTreeMap) => Ty::new_tup(b.t.tcx, &[arg(coll, 0), arg(coll, 1)]), + _ => arg(coll, 0), + } +} + /// The type a lookup of a map or set takes its key as: the `Q` of `get` where /// `K: Borrow`, or of `Index<&Q>`. fn lookup_ty<'tcx>(b: &Body<'_, '_, 'tcx>, std: Std, call: &Call<'tcx>, owner: &str, name: &str) -> Option> { @@ -349,10 +356,30 @@ fn hash<'tcx>( (_, "remove_entry") => Expr::rt("hashRemoveEntry", values), (_, "retain") => Expr::rt("hashRetain", values), (_, "iter" | "iter_mut") if !set => Expr::rt("hashIter", values), - (_, "iter" | "keys" | "into_keys") => Expr::rt("hashKeys", values), - (_, "values" | "values_mut" | "into_values") => Expr::rt("hashValues", values), - (_, "drain") if set => Expr::rt("hashDrainKeys", values), - (_, "drain") => Expr::rt("hashDrain", values), + (_, "iter" | "keys") => Expr::rt("hashKeys", values), + (_, "values" | "values_mut") => Expr::rt("hashValues", values), + // std's `fold` of either drops the half it does not yield after the one it does, where + // `next` drops it before. + (_, "into_keys" | "into_values") => { + let (kept, other) = if name == "into_keys" { (0, 1) } else { (1, 0) }; + if b.t.drops(arg(coll, other)) { + let other = arg(coll, other); + return Some(b.err( + span, + format!("`{name}` of `{coll}`, which drops `{other}`, which is not supported yet"), + )); + } + let dropper = b.t.dropper(arg(coll, kept), span); + let f = if name == "into_keys" { "hashKeys" } else { "hashValues" }; + Expr::rt(f, super::iter::tail(values, vec![dropper])) + } + (_, "drain") => { + let droppers = entry_droppers(b, coll, span); + Expr::rt( + if set { "hashDrainKeys" } else { "hashDrain" }, + super::iter::tail(values, droppers), + ) + } (_, "entry") => Expr::rt("entry", values), (_, "reserve" | "shrink_to_fit") => { discard(values, out); @@ -369,18 +396,39 @@ fn hash<'tcx>( Expr::rt("hashClone", values) } ("Extend", "extend") | ("From", "from") => { - let source = extend_source(b, coll, call, owner, values.pop()?)?; + let (source, iter) = extend_source(b, coll, call, owner, values.pop()?)?; let target = match owner { "From" => hash_new(b, coll, span)?, _ => values.pop()?, }; - Expr::rt(if set { "hashExtendKeys" } else { "hashExtend" }, vec![target, source]) + hash_extend(b, coll, target, source, iter, owner == "From", span) } _ => return None, }; Some(e) } +/// `extend` of `target`, a hash collection of type `coll`, from `source`, an iterator of +/// type `iter`, or with `fresh`, `collect` into an empty one, which drops if a panic does. +fn hash_extend<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + coll: Ty<'tcx>, + target: Expr, + source: Expr, + iter: Ty<'tcx>, + fresh: bool, + span: Span, +) -> Expr { + let mut droppers = entry_droppers(b, coll, span); + droppers.push(super::iter::iter_dropper(b, iter, span)); + droppers.push(Expr::lit(if fresh && b.t.drops(coll) { "true" } else { "false" })); + let f = match b.t.std_of(coll) { + Some(Std::HashSet) => "hashExtendKeys", + _ => "hashExtend", + }; + Expr::rt(f, super::iter::tail(vec![target, source], droppers)) +} + /// An empty hash collection of type `coll`, which finds its keys as their type needs. fn hash_new<'tcx>(b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, span: Span) -> Option { let key = arg(coll, 0); @@ -516,8 +564,22 @@ fn btree<'tcx>( (_, "first_entry") => Expr::rt("btreeFirstEntry", values), (_, "last_entry") => Expr::rt("btreeFirstEntry", last(values)), (_, "iter" | "iter_mut") if !set => Expr::rt("btreeIter", values), - (_, "iter" | "keys" | "into_keys") => Expr::rt("btreeKeys", values), - (_, "values" | "values_mut" | "into_values") => Expr::rt("btreeValues", values), + (_, "iter" | "keys") => Expr::rt("btreeKeys", values), + (_, "values" | "values_mut") => Expr::rt("btreeValues", values), + // Each of which drops the half it does not yield as it reads, and whose `last` reads + // the back. + (_, "into_keys" | "into_values") => { + let mut droppers = entry_droppers(b, coll, span); + if name == "into_keys" && b.t.drops(coll) { + droppers.push(Expr::lit("true")); + } + let f = if name == "into_keys" { + "btreeKeys" + } else { + "btreeValues" + }; + Expr::rt(f, super::iter::tail(values, droppers)) + } (_, "range") if set => Expr::rt("btreeRangeKeys", values), (_, "range" | "range_mut") => Expr::rt("btreeRange", values), (_, "entry") => Expr::rt("entry", values), @@ -531,24 +593,90 @@ fn btree<'tcx>( values.extend([k, v]); Expr::rt("btreeClone", values) } - ("Extend", "extend") | ("From", "from") => { - let source = extend_source(b, coll, call, owner, values.pop()?)?; - let target = match owner { - "From" => btree_new(b, coll, span), - _ => values.pop()?, - }; - let mut values = vec![target, source]; - // `from` keeps the last of equal keys, as std's sorted bulk build does. - if owner == "From" { - values.push(Expr::lit("true")); - } - Expr::rt(if set { "btreeExtendKeys" } else { "btreeExtend" }, values) + ("Extend", "extend") => { + let (source, iter) = extend_source(b, coll, call, owner, values.pop()?)?; + let mut droppers = vec![Expr::lit("false")]; + droppers.extend(entry_droppers(b, coll, span)); + droppers.push(super::iter::iter_dropper(b, iter, span)); + let target = values.pop()?; + let f = if set { "btreeExtendKeys" } else { "btreeExtend" }; + Expr::rt(f, super::iter::tail(vec![target, source], droppers)) + } + ("From", "from") => { + let (source, iter) = extend_source(b, coll, call, owner, values.pop()?)?; + btree_collect(b, coll, source, iter, span) } _ => return None, }; Some(e) } +/// `collect` and `from` into an empty B-tree of type `coll`, from `source`, an iterator of +/// type `iter`, which keep the last of equal keys, as std's sorted bulk build does. Of +/// entries that drop, std's collects into a `Vec` first, and then drops each but the last +/// of equal keys in the order a stable sort leaves them. +fn btree_collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, source: Expr, iter: Ty<'tcx>, span: Span) -> Expr { + let set = b.t.std_of(coll) == Some(Std::BTreeSet); + let target = btree_new(b, coll, span); + let key = arg(coll, 0); + if !b.t.drops(coll) { + let mut droppers = vec![Expr::lit("true"), Expr::undefined()]; + if !set { + droppers.push(Expr::undefined()); + } + droppers.push(super::iter::iter_dropper(b, iter, span)); + let f = if set { "btreeExtendKeys" } else { "btreeExtend" }; + return Expr::rt(f, super::iter::tail(vec![target, source], droppers)); + } + // A sort by an `Ord` of the crate's may panic, or leave equal keys in another order. + if own_ord(b, key, &mut Default::default()) { + return b.err( + span, + format!( + "`collect` of `{coll}`, which sorts by `{key}`'s own `Ord`, of entries that drop, which is not supported yet" + ), + ); + } + let entries = super::iter::to_array(b, source, iter, stored(b, coll), span); + let droppers = entry_droppers(b, coll, span); + let f = if set { "btreeCollectKeys" } else { "btreeCollect" }; + Expr::rt(f, super::iter::tail(vec![target, entries], droppers)) +} + +/// Whether ordering or comparing a `ty` may run the crate's own `Ord` or `PartialEq`, +/// rather than one derived, which may panic or disagree with itself. +fn own_ord<'tcx>( + b: &Body<'_, '_, 'tcx>, + ty: Ty<'tcx>, + seen: &mut rustc_data_structures::fx::FxHashSet>, +) -> bool { + let tcx = b.t.tcx; + let ty = peel(b, ty); + if !seen.insert(ty) { + return false; + } + match ty.kind() { + ty::Tuple(tys) => tys.iter().any(|t| own_ord(b, t, seen)), + ty::Adt(..) if let Some(inner) = option_of(b, ty).or_else(|| arc_of(b, ty)) => own_ord(b, inner, seen), + ty::Adt(adt, args) if adt.did().is_local() => { + let derived = |tr: &str, item: &str, args: &[ty::GenericArg<'tcx>]| { + let f = trait_fn(tcx, tr, item); + Instance::try_resolve(tcx, b.t.typing_env_pub(), f, tcx.mk_args(args)) + .ok() + .flatten() + .and_then(|instance| tcx.impl_of_assoc(instance.def_id())) + .is_some_and(|imp| tcx.is_automatically_derived(imp)) + }; + !derived("Ord", "cmp", &[ty.into()]) + || !derived("PartialEq", "eq", &[ty.into(), ty.into()]) + || adt + .all_fields() + .any(|f| own_ord(b, f.ty(tcx, args).skip_norm_wip(), seen)) + } + _ => false, + } +} + /// An empty B-tree of type `coll`, ordered by its keys' `Ord`. fn btree_new<'tcx>(b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, span: Span) -> Expr { let cmp = cmp_fn(b, arg(coll, 0), false, span); @@ -601,7 +729,10 @@ fn deque<'tcx>( Expr::rt("dequeContains", values) } (_, "iter" | "iter_mut") => Expr::rt("dequeIter", values), - (_, "drain") => Expr::rt("dequeDrain", values), + (_, "drain") => { + let droppers = entry_droppers(b, coll, span); + Expr::rt("dequeDrain", super::iter::tail(values, droppers)) + } (_, "reserve" | "reserve_exact" | "shrink_to_fit") => { discard(values, out); Expr::undefined() @@ -612,30 +743,38 @@ fn deque<'tcx>( Expr::rt("dequeClone", values) } ("Extend", "extend") | ("From", "from") => { - let source = extend_source(b, coll, call, owner, values.pop()?)?; + let (source, iter) = extend_source(b, coll, call, owner, values.pop()?)?; let target = match owner { "From" => deque_new(b, coll, span), _ => values.pop()?, }; - Expr::rt("dequeExtend", vec![target, source]) + let dropper = super::iter::iter_dropper(b, iter, span); + Expr::rt("dequeExtend", super::iter::tail(vec![target, source], vec![dropper])) } _ => return None, }; Some(e) } -/// What `extend` or `from` adds to a collection: an `rt.Iter` of what `source` holds. +/// What `extend` or `from` adds to a collection: an `rt.Iter` of what `source` holds, and +/// the type of the iterator std's makes of it. fn extend_source<'tcx>( b: &mut Body<'_, '_, 'tcx>, coll: Ty<'tcx>, call: &Call<'tcx>, owner: &str, source: Expr, -) -> Option { +) -> Option<(Expr, Ty<'tcx>)> { // `Extend::extend::` and `From::from`. let ty = library::targ(call.args, if owner == "Extend" { 2 } else { 1 }); + let iter = super::iter::iter_of(b.t, ty)?; + // Each but a `Vec`'s, by `for_each`. + super::iter::folds(b, iter, owner, call.span); let Some(items) = super::iter::into_iter(b, ty, source, call.span) else { - return Some(b.err(call.span, format!("`{owner}` from `{ty}`, which is not supported yet"))); + return Some(( + b.err(call.span, format!("`{owner}` from `{ty}`, which is not supported yet")), + iter, + )); }; // `Extend<&T>` and `Extend<(&K, &V)>`, whose items are `Copy`, copy each one. let elems: Vec> = match b.t.std_of(coll) { @@ -648,12 +787,13 @@ fn extend_source<'tcx>( }; let borrowed = owner == "Extend" && library::targ(call.args, 1) != stored; if !borrowed || !elems.iter().any(|&t| b.t.needs_copy(t)) { - return Some(items); + return Some((items, iter)); } - Some(match b.t.copy_fn(stored, call.span) { + let items = match b.t.copy_fn(stored, call.span) { Some(copy) => Expr::rt("iterMap", vec![items, copy]), None => items, - }) + }; + Some((items, iter)) } /// A method of an `Entry`, `OccupiedEntry`, or `VacantEntry`. @@ -935,9 +1075,10 @@ fn trait_fn(tcx: ty::TyCtxt<'_>, tr: &str, item: &str) -> rustc_hir::def_id::Def } /// What `into_iter` makes of a collection of type `ty`, by value or by reference: an -/// `rt.Iter` of its entries, keys, or items. -pub fn into_iter<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr) -> Option { - let name = match b.t.std_of(ty.peel_refs())? { +/// `rt.Iter` of its entries, keys, or items, which by value drops those it still holds. +pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, span: Span) -> Option { + let coll = ty.peel_refs(); + let name = match b.t.std_of(coll)? { Std::HashMap => "hashIter", Std::HashSet => "hashKeys", Std::BTreeMap => "btreeIter", @@ -945,11 +1086,15 @@ pub fn into_iter<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr) -> Opt Std::VecDeque => "dequeIter", _ => return None, }; - Some(Expr::rt(name, vec![value])) + let droppers = match ty.is_ref() { + true => Vec::new(), + false => entry_droppers(b, coll, span), + }; + Some(Expr::rt(name, super::iter::tail(vec![value], droppers))) } -/// `collect` into a collection of type `ty`. -pub fn collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, iter: Expr, span: Span) -> Option { +/// `collect` into a collection of type `ty` from `iter`, an iterator of type `from`. +pub fn collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, iter: Expr, from: Ty<'tcx>, span: Span) -> Option { let std = b.t.std_of(ty)?; if let Some(elem) = undefined_arg(b, std, ty) { return Some(b.err( @@ -957,22 +1102,24 @@ pub fn collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, iter: Expr, span: format!("`{ty}` holds `{elem}`, which is `undefined` as `None` is, which is not supported"), )); } - let (target, extend) = match std { - Std::HashMap => (hash_new(b, ty, span)?, "hashExtend"), - Std::HashSet => (hash_new(b, ty, span)?, "hashExtendKeys"), - Std::BTreeMap => (btree_new(b, ty, span), "btreeExtend"), - Std::BTreeSet => (btree_new(b, ty, span), "btreeExtendKeys"), - Std::VecDeque => (deque_new(b, ty, span), "dequeExtend"), + Some(match std { + Std::HashMap | Std::HashSet => { + let target = hash_new(b, ty, span)?; + hash_extend(b, ty, target, iter, from, true, span) + } + Std::BTreeMap | Std::BTreeSet => btree_collect(b, ty, iter, from, span), + // std's collects into a `Vec` first. + Std::VecDeque => { + let target = deque_new(b, ty, span); + let item = arg(ty, 0); + if !b.t.drops(item) { + let dropper = super::iter::iter_dropper(b, from, span); + Expr::rt("dequeExtend", super::iter::tail(vec![target, iter], vec![dropper])) + } else { + let items = super::iter::to_array(b, iter, from, item, span); + Expr::rt("dequeExtend", vec![target, Expr::rt("iterSlice", vec![items])]) + } + } _ => return None, - }; - let mut values = vec![target, iter]; - // A B-tree's `collect` keeps the last of equal keys, as std's sorted bulk build does. - if matches!(std, Std::BTreeMap | Std::BTreeSet) { - values.push(Expr::lit("true")); - } - // A map or set drops the duplicates it is given. - if let Some(lost) = discarded(std, "From", "from") { - values.extend(b.t.droppers(lost.iter().map(|&n| arg(ty, n)), span)?); - } - Some(Expr::rt(extend, values)) + }) } diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 707cc0340..1f4fe34bc 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -47,6 +47,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ) => args.types().any(|t| self.drops(t)), // An entry borrows its map, and holds only the key it was given. Some(Std::Entry) => args.types().next().is_some_and(|k| self.drops(k)), + None | Some(Std::Peekable) if self.std_iter(ty) => match adt.has_dtor(tcx) { + // What owns its items, an `IntoIter` or a `Drain`, drops those it still holds. + true => args.types().any(|t| self.drops(t)), + false => self.fields_drop(*adt, args, true), + }, Some(_) => false, None if adt.did().is_local() => adt.has_dtor(tcx) || self.fields_drop(*adt, args, true), None => false, @@ -69,6 +74,18 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { drops } + /// Whether `ty` is one of std's iterators, or a type they are built of, which an `rt.Iter` + /// stands for: it drops what it owns, of its fields or, with a `Drop` impl, its items. + fn std_iter(&self, ty: Ty<'tcx>) -> bool { + let ty::Adt(adt, _) = ty.kind() else { + return false; + }; + matches!( + self.tcx.crate_name(adt.did().krate).as_str(), + "core" | "alloc" | "std" | "hashbrown" + ) && self.iter_item(ty).is_some() + } + /// Whether any field of `adt` with `args` drops, counting one of a type parameter only /// if `params`. pub fn fields_drop(&mut self, adt: AdtDef<'tcx>, args: ty::GenericArgsRef<'tcx>, params: bool) -> bool { @@ -97,6 +114,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { Some(Std::Arc | Std::Mutex | Std::Option | Std::Box | Std::Pin) => { self.disposable(args.type_at(0), span) } + // An `rt.Iter` drops what it was given to, but not a closure's captures. + None | Some(Std::Peekable) if self.std_iter(ty) => !ty + .walk() + .filter_map(|arg| arg.as_type()) + .any(|t| matches!(t.kind(), ty::Closure(..)) && self.drops(t)), Some(_) => false, // A generic `Drop` impl has an instance per type, which one class's glue can't call. None if adt.is_struct() && !self.generic_dtor(*adt) => { @@ -125,6 +147,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { match ty.kind() { ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { Some(Std::Waker) => false, + // What it holds of its own, or of its items. + None | Some(Std::Peekable) if self.std_iter(ty) => { + args.types().any(|t| self.drop_panics(t, seen)) + || self.iter_item(ty).is_some_and(|item| self.drop_panics(item, seen)) + } Some(_) => args.types().any(|t| self.drop_panics(t, seen)), None if adt.did().is_local() => { let env = self.typing_env_pub(); @@ -288,6 +315,12 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { super::mir::glue::shim(self, ty, span).map(Expr::Sym) } + /// What drops a `ty`, as a runtime function takes it after its own arguments: + /// `undefined` if JS would see nothing drop, or if translation refused it. + pub fn dropper(&mut self, ty: Ty<'tcx>, span: Span) -> Expr { + self.drop_fn(ty, span).unwrap_or_else(Expr::undefined) + } + /// What drops each of `tys`, as a runtime function takes them after its own arguments: /// `undefined` for one that drops nothing, up to the last that drops. `None` if /// translation refused one. diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index c180f8d50..291085768 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -111,10 +111,11 @@ pub fn next<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, iter: Expr) -> Expr } /// What `IntoIterator::into_iter` makes of `value`, a `ty`: an `rt.Iter`, or `None` for a -/// type without a mapping. +/// type without a mapping. One that owns what it yields, by value, is given what drops +/// each, and the crate's own iterator what drops it. pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, span: Span) -> Option { let tcx = b.t.tcx; - no_drops(b, ty, span); + let owned = !ty.is_ref(); if b.t.iter_item(ty).is_some() { return Some(match own_next(b, ty) { Some(instance) => { @@ -126,20 +127,38 @@ pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, sp name: it, ty: Some(param_ty), }; - Expr::rt("iterFrom", vec![value, Expr::Lambda(vec![param], Box::new(next))]) + let mut args = vec![value, Expr::Lambda(vec![param], Box::new(next))]; + if owned && b.t.drops(ty) { + args.push(b.t.dropper(ty, span)); + } + Expr::rt("iterFrom", args) } + // One borrowed by `&mut`, which std's adaptors may drop once it ends, but which + // is its owner's to drop. + None if !owned && b.t.drops(ty.peel_refs()) => Expr::rt("iterBorrow", vec![value]), None => value, }); } + // What drops each item of one that owns them. + let each = |b: &mut Body<'_, '_, 'tcx>, elem: Ty<'tcx>, mut args: Vec| { + if owned && b.t.drops(elem) { + args.push(b.t.dropper(elem, span)); + } + args + }; match ty.peel_refs().kind() { - ty::Slice(_) | ty::Array(..) => Some(Expr::rt("iterSlice", vec![value])), + ty::Slice(_) => Some(Expr::rt("iterSlice", vec![value])), + ty::Array(elem, _) => Some(Expr::rt("iterSlice", each(b, *elem, vec![value]))), ty::Adt(adt, args) => match Std::of(tcx, adt.did())? { - Std::Vec => Some(Expr::rt("iterSlice", vec![library::vec_view(value, ty)])), + Std::Vec => { + let values = each(b, args.type_at(0), vec![library::vec_view(value, ty)]); + Some(Expr::rt("iterSlice", values)) + } Std::Option => { option_ok(b, args.type_at(0), span); - Some(Expr::rt("iterOption", vec![value])) + Some(Expr::rt("iterOption", each(b, args.type_at(0), vec![value]))) } - _ => super::collections::into_iter(b, ty, value), + _ => super::collections::into_iter(b, ty, value, span), }, _ => None, } @@ -147,28 +166,30 @@ pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, sp /// A function doing `into_iter` on each `ty`, or `None` where it is the value itself. fn into_fn<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Option> { - if b.t.iter_item(ty).is_some() && own_next(b, ty).is_none() { + let body = into_iter(b, ty, Expr::ident("value"), span)?; + if matches!(&body, Expr::Ident(name) if name == "value") { return Some(None); } let param = Param { name: "value".into(), ty: Some(b.t.ty(ty, span)), }; - let body = into_iter(b, ty, Expr::ident("value"), span)?; Some(Some(Expr::Lambda(vec![param], Box::new(body)))) } -/// Refuse an iterator that owns a `ty` that drops: an `rt.Iter` drops nothing it skips, -/// consumes, or holds when it is dropped. -fn no_drops<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) { - if b.t.drops(ty) { - b.t.err( - span, - format!("an iterator that owns `{ty}`, which drops, which is not supported yet"), - ); - } +/// `::IntoIter`: the iterator `into_iter` makes of a `ty`. +pub(super) fn iter_of<'tcx>(t: &Translator<'_, 'tcx>, ty: Ty<'tcx>) -> Option> { + let tcx = t.tcx; + let into = tcx.get_diagnostic_item(rustc_span::sym::IntoIterator)?; + let item = tcx + .associated_items(into) + .filter_by_name_unhygienic(rustc_span::Symbol::intern("IntoIter")) + .next()? + .def_id; + let projection = Ty::new_projection(tcx, ty::IsRigid::No, item, [ty]); + tcx.try_normalize_erasing_regions(t.typing_env_pub(), ty::Unnormalized::new_wip(projection)) + .ok() } - /// Refuse an `Option` of `ty` that `T | undefined` can't hold, as the type would be. pub fn option_ok<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) { if b.t.erases_to(ty).undefined { @@ -179,7 +200,9 @@ pub fn option_ok<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) { } } -/// The mapping of a call on or to an iterator, if it is one. +/// The mapping of a call on or to an iterator, if it is one. Where std drops an item it +/// skips, rejects, or holds, or an iterator it takes by value, the runtime function is +/// given what drops it after its own arguments. pub fn call<'tcx>( b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, @@ -211,15 +234,15 @@ pub fn call<'tcx>( } match path.as_slice() { ["iter", "sources", "once", "once"] => { - no_drops(b, targ(0)?, span); - return Some(Expr::rt("iterOnce", args)); + let dropper = b.t.dropper(targ(0)?, span); + return Some(Expr::rt("iterOnce", tail(args, vec![dropper]))); } ["iter", "sources", "empty", "empty"] => return Some(Expr::rt("iterEmpty", Vec::new())), ["iter", "sources", "from_fn", "from_fn"] => return Some(Expr::rt("iterFromFn", args)), _ => {} } - // `Vec::extend` with an iterator. + // `Vec::extend` with an iterator, which it drops once done. if (owner, name) == ("Extend", "extend") { let (vec, item, source) = (targ(0)?, targ(1)?, targ(2)?); let ty::Adt(adt, vec_args) = vec.kind() else { @@ -229,6 +252,11 @@ pub fn call<'tcx>( return None; } let [v, items] = <[Expr; 2]>::try_from(args).ok()?; + let iter = iter_of(b.t, source)?; + // Of a `TrustedLen` iterator, by `for_each`. + if implements(b.t, iter, "TrustedLen") { + folds(b, iter, "extend", span); + } let mut items = into_iter(b, source, items, span)?; // `Extend<&T>` copies each element. if item != vec_args.type_at(0) @@ -240,7 +268,8 @@ pub fn call<'tcx>( ty::Uint(ty::UintTy::U8) => "iterExtendBytes", _ => "iterExtend", }; - return Some(Expr::rt(extend, vec![v, items])); + let dropper = iter_dropper(b, iter, span); + return Some(Expr::rt(extend, tail(vec![v, items], vec![dropper]))); } let self_ty = match (owner, name) { @@ -253,10 +282,6 @@ pub fn call<'tcx>( _ => return None, }; let item = b.t.iter_item(self_ty.peel_refs())?; - // The crate's own `next` hands its item over; every other call may leave items behind. - if name != "by_ref" && !(name == "next" && own_next(b, self_ty).is_some()) { - no_drops(b, item, span); - } let mut values = args.into_iter(); let recv = values.next()?; let rest: Vec = values.collect(); @@ -267,7 +292,10 @@ pub fn call<'tcx>( let item = match name { "next" => next(b, self_ty, recv), "next_back" => recv.member("nextBack").call(Vec::new()), - _ => recv.member("nthBackItem").call(rest), + _ => { + let dropper = b.t.dropper(item, span); + recv.member("nthBackItem").call(tail(rest, vec![dropper])) + } }; return Some(Expr::rt("iterToOption", vec![item])); } @@ -285,30 +313,86 @@ pub fn call<'tcx>( }; Some(Expr::rt_of(of, name).call([vec![recv.clone()], args].concat())) }; + // Each consumer that takes the iterator by value drops it, by `fold` but for `nth`'s. + if matches!( + name, + "count" | "last" | "fold" | "for_each" | "sum" | "product" | "max" | "min" | "max_by_key" | "min_by_key" + ) { + folds(b, self_ty, name, span); + } + let camel = super::camel(name); match name { - "map" | "filter" | "filter_map" | "enumerate" | "rev" | "skip" | "take" | "skip_while" | "take_while" - | "map_while" | "step_by" | "inspect" | "fuse" | "peekable" | "count" | "any" | "all" | "find_map" - | "position" | "fold" | "for_each" => method(&super::camel(name), rest), + "map" | "filter_map" | "enumerate" | "rev" | "map_while" | "any" | "all" | "find_map" | "position" => { + method(&camel, rest) + } + // What each drops: an item it skips or rejects, or one it peeked. + "filter" | "skip" | "take" | "skip_while" | "take_while" | "step_by" | "inspect" | "peekable" => { + let dropper = b.t.dropper(item, span); + method(&camel, tail(rest, vec![dropper])) + } + "fuse" => { + let fused = fused(b, self_ty); + method(name, tail(rest, vec![fused])) + } + "count" => { + let droppers = vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)]; + method(name, tail(rest, droppers)) + } + "for_each" => { + let dropper = iter_dropper(b, self_ty, span); + method(&camel, tail(rest, vec![dropper])) + } + "sum" | "product" => { + let int = Int::of(targ(1)?)?; + let (op, unit) = match name { + "sum" => ("add", 0), + _ => ("mul", 1), + }; + let dropper = iter_dropper(b, self_ty, span); + method(name, tail(vec![int.func(op), int.lit(unit)], vec![dropper])) + } + // `fold::`, whose accumulator drops if reading an item panics. + "fold" => { + let droppers = vec![iter_dropper(b, self_ty, span), b.t.dropper(targ(1)?, span)]; + method(name, tail(rest, droppers)) + } // `ExactSizeIterator::len` is each iterator's own. "len" => Some(recv.member("len").call(rest)), "last" | "nth" | "find" | "peek" | "next_if" => { option_ok(b, item, span); - method(&super::camel(name), rest) + let droppers = match name { + "last" => vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)], + "nth" | "find" => vec![b.t.dropper(item, span)], + _ => Vec::new(), + }; + method(&camel, tail(rest, droppers)) } "max" | "min" if primitive(item.peel_refs()) => { option_ok(b, item, span); - method(name, rest) + // A `BTreeMap`'s `into_keys` reads the one end and drops the rest with it. + if std_iter_path(tcx, self_ty).is_some_and(|p| p == ["collections", "btree", "map", "IntoKeys"]) + && b.t.drops(self_ty) + { + return Some(b.err( + span, + format!("`{name}` of `{self_ty}`, which drops its values, which is not supported yet"), + )); + } + let dropper = iter_dropper(b, self_ty, span); + method(name, tail(rest, vec![dropper])) } "max_by_key" | "min_by_key" if primitive(targ(1)?) => { option_ok(b, item, span); - method(&super::camel(name), rest) + let droppers = vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)]; + method(&camel, tail(rest, droppers)) } "chain" => { let other = into_iter(b, targ(1)?, rest.into_iter().next()?, span)?; method(name, vec![other]) } "zip" => { - let other = into_iter(b, targ(1)?, rest.into_iter().next()?, span)?; + let other_ty = targ(1)?; + let other = into_iter(b, other_ty, rest.into_iter().next()?, span)?; let sig = tcx.fn_sig(call.def_id).instantiate(tcx, gargs).skip_norm_wip(); let zip = b.t.subst( ty::List::empty(), @@ -317,20 +401,40 @@ pub fn call<'tcx>( let ty::Adt(_, sides) = zip.kind() else { return None; }; - let mut args = vec![other]; - if zip_reads_by_index(b, sides.type_at(0), sides.type_at(1), span) { - args.push(Expr::lit("true")); + let (a, other_iter) = (sides.type_at(0), sides.type_at(1)); + let other_item = b.t.iter_item(other_iter)?; + let trusted = zip_reads_by_index(b, a, other_iter, span); + // std's reads one item past the end of the first, which it drops, where `next` + // could see the difference. + if trusted && (b.t.drops(item) || b.t.drops(other_item)) { + return Some(b.err( + span, + format!( + "a `zip` of `{a}` and `{other_iter}`, which std reads by index, of items that drop, which is not supported yet" + ), + )); } - method(name, args) + let droppers = vec![ + Expr::lit(if trusted { "true" } else { "false" }), + b.t.dropper(item, span), + b.t.dropper(other_item, span), + ]; + method(name, tail(vec![other], droppers)) } + // `flat_map::`, of the source mapped by `F`, which drops as the source does. "flat_map" => { - let mut rest = rest; - rest.extend(into_fn(b, targ(1)?, span)?); - method("flatMap", rest) + let inner = iter_of(b.t, targ(1)?)?; + flattens(b, inner, span); + let into = into_fn(b, targ(1)?, span)?.unwrap_or_else(Expr::undefined); + let fused = fused(b, self_ty); + method("flatMap", tail(rest, vec![into, fused])) } "flatten" => { - let into = into_fn(b, item, span)?; - method("flatten", into.into_iter().collect()) + let inner = iter_of(b.t, item)?; + flattens(b, inner, span); + let into = into_fn(b, item, span)?.unwrap_or_else(Expr::undefined); + let fused = fused(b, self_ty); + method("flatten", tail(Vec::new(), vec![into, fused])) } "copied" | "cloned" => { let ty::Ref(_, inner, _) = item.kind() else { @@ -359,19 +463,109 @@ pub fn call<'tcx>( } } } - "sum" | "product" => { - let int = Int::of(targ(1)?)?; - let (op, unit) = match name { - "sum" => ("add", 0), - _ => ("mul", 1), - }; - method(name, vec![int.func(op), int.lit(unit)]) - } - "collect" => collect(b, targ(1)?, item, recv, span), + "collect" => collect(b, targ(1)?, item, recv, self_ty, span), _ => None, } } +/// `args`, then `tail` without the `undefined`s and `false`s it ends with, which a runtime +/// function's optional parameters default to. +pub(super) fn tail(mut args: Vec, mut tail: Vec) -> Vec { + while matches!(tail.last(), Some(Expr::Lit(l)) if l == "undefined" || l == "false") { + tail.pop(); + } + args.extend(tail); + args +} + +/// Whether an iterator of type `ty` that drops is a `FusedIterator`, which std's `fuse` and +/// `flatten` keep once it ends rather than drop: `true` or `false`. +fn fused<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> Expr { + Expr::lit(match b.t.drops(ty) && implements(b.t, ty, "FusedIterator") { + true => "true", + false => "false", + }) +} + +/// The path of the std type `ty` is, if it is one. +fn std_iter_path(tcx: ty::TyCtxt<'_>, ty: Ty<'_>) -> Option> { + let ty::Adt(adt, _) = ty.kind() else { + return None; + }; + Some(library::std_path(tcx, adt.did())).filter(|p| !p.is_empty()) +} + +/// Refuse a `flatten` or `flat_map` of `inner` iterators that drop and may hold what drops +/// once they end: std's `try_fold` drops each such one only as it reads the next, where +/// `next` drops it as it ends. What std's collections' and `Option`'s `into_iter` make +/// holds nothing then. +fn flattens<'tcx>(b: &mut Body<'_, '_, 'tcx>, inner: Ty<'tcx>, span: Span) { + if !b.t.drops(inner) { + return; + } + let path = std_iter_path(b.t.tcx, inner).unwrap_or_default(); + let path: Vec<&str> = path.iter().map(String::as_str).collect(); + let empties = matches!( + path.as_slice(), + ["vec", "into_iter", "IntoIter"] + | ["array", "iter", "IntoIter"] + | ["option", "IntoIter"] + | ["iter", "sources", "once", "Once"] + | ["collections", "hash", "map", "IntoIter" | "IntoKeys" | "IntoValues"] + | ["collections", "hash", "set", "IntoIter"] + | ["collections", "btree", "map", "IntoIter" | "IntoKeys" | "IntoValues"] + | ["collections", "btree", "set", "IntoIter"] + | ["collections", "vec_deque", "into_iter", "IntoIter"] + ); + if !empties { + b.t.err( + span, + format!("a `flatten` of `{inner}`, which drops what it may hold once it ends, which is not supported yet"), + ); + } +} + +/// Refuse std's `name` folding `ty` through a `flatten` or `flat_map` whose source and +/// iterators both drop: a panic in `fold` drops the iterator it took before the source, +/// as a panic in `next` does not. +pub(super) fn folds<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, name: &str, span: Span) { + let tcx = b.t.tcx; + let flattens: Vec> = ty + .walk() + .filter_map(|arg| arg.as_type()) + .filter(|&t| { + std_iter_path(tcx, t).is_some_and(|p| { + p.len() == 4 + && p[..3] == ["iter", "adapters", "flatten"] + && matches!(p[3].as_str(), "Flatten" | "FlatMap") + }) + }) + .collect(); + for t in flattens { + let ty::Adt(_, args) = t.kind() else { + continue; + }; + let outer = args.type_at(0); + // `Flatten` of `I::Item`s, or `FlatMap` of `U`s by `F`. + let (outer_drops, inner) = match args.types().count() { + 1 => (b.t.drops(outer), b.t.iter_item(outer).and_then(|i| iter_of(b.t, i))), + _ => ( + b.t.drops(outer) || b.t.drops(args.type_at(2)), + iter_of(b.t, args.type_at(1)), + ), + }; + if outer_drops && inner.is_some_and(|i| b.t.drops(i)) { + b.t.err( + span, + format!( + "`{name}` of `{ty}`, which folds a `flatten` whose source and iterators both drop, which is not supported yet" + ), + ); + return; + } + } +} + /// Whether std's `Zip` of `a` and `b` reads both by index, never past the shorter: when /// both are `TrustedRandomAccess`. Refuse one that `fold` reads that way but `next` does /// not, where the first calls a closure that would see the difference. @@ -407,35 +601,55 @@ pub(super) fn implements<'tcx>(t: &Translator<'_, 'tcx>, ty: Ty<'tcx>, name: &st use rustc_infer::infer::TyCtxtInferExt; use rustc_trait_selection::infer::InferCtxtExt; let tcx = t.tcx; - let Some(&core) = tcx - .crates(()) - .iter() - .find(|&&c| tcx.crate_name(c) == rustc_span::sym::core) - else { - return false; - }; - let Some(&tr) = tcx.traits(core).iter().find(|&&tr| tcx.item_name(tr).as_str() == name) else { + let Some(tr) = core_trait(tcx, name) else { return false; }; let (infcx, env) = tcx.infer_ctxt().build_with_typing_env(t.typing_env_pub()); infcx.type_implements_trait(tr, [ty], env).must_apply_modulo_regions() } +/// `core`'s trait `name`. +fn core_trait(tcx: ty::TyCtxt<'_>, name: &str) -> Option { + let &core = tcx + .crates(()) + .iter() + .find(|&&c| tcx.crate_name(c) == rustc_span::sym::core)?; + tcx.traits(core) + .iter() + .copied() + .find(|&tr| tcx.item_name(tr).as_str() == name) +} + /// Whether `ty` compares in JS as Rust's `Ord` does: an integer, a `bool`, or a `char`. fn primitive(ty: Ty<'_>) -> bool { matches!(ty.kind(), ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_)) } -/// `iter.collect::()` of `item`s. -fn collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, item: Ty<'tcx>, iter: Expr, span: Span) -> Option { +/// `iter.collect::()` of `item`s, from an iterator of type `from`, which it drops. +fn collect<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + ty: Ty<'tcx>, + item: Ty<'tcx>, + iter: Expr, + from: Ty<'tcx>, + span: Span, +) -> Option { let tcx = b.t.tcx; let ty::Adt(adt, args) = ty.kind() else { return None; }; - match Std::of(tcx, adt.did())? { + let std = Std::of(tcx, adt.did())?; + // Into a `Vec` of a `TrustedLen` iterator, and into any other collection, by `for_each`. + if !matches!(std, Std::Result | Std::Option) && (std != Std::Vec || implements(b.t, from, "TrustedLen")) { + folds(b, from, "collect", span); + } + match std { Std::Vec => Some(match args.type_at(0).kind() { - ty::Uint(ty::UintTy::U8) => Expr::rt("iterToByteVec", vec![iter]), - _ => Expr::rt("iterToArray", vec![iter]), + ty::Uint(ty::UintTy::U8) => { + let dropper = iter_dropper(b, from, span); + Expr::rt("iterToByteVec", tail(vec![iter], vec![dropper])) + } + _ => to_array(b, iter, from, args.type_at(0), span), }), // The values, collected as the `Ok` or `Some` type is, until the first `Err` or `None`. std @ (Std::Result | Std::Option) => { @@ -447,20 +661,128 @@ fn collect<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, item: Ty<'tcx>, iter: option_ok(b, args.type_at(0), span); } let value_ty = b.t.ty(value, span); - let values = collect(b, args.type_at(0), value, Expr::ident("values"), span)?; + // What it collects from is what `from` yields up to the first `Err` or `None`, which + // std's collects in place of `from`'s source as it would `from`. + let values = collect(b, args.type_at(0), value, Expr::ident("values"), from, span)?; let param = Param { name: "values".into(), ty: Some(Type::Rt("Iter", vec![value_ty])), }; - let collect = match std { - Std::Result => "iterCollectResult", - _ => "iterCollectOption", + let (collect, mut droppers) = match std { + Std::Result => ("iterCollectResult", vec![b.t.dropper(args.type_at(1), span)]), + _ => ("iterCollectOption", Vec::new()), }; - Some(Expr::rt( - collect, - vec![iter, Expr::Lambda(vec![param], Box::new(values))], - )) + droppers.insert(0, b.t.dropper(args.type_at(0), span)); + let args = vec![iter, Expr::Lambda(vec![param], Box::new(values))]; + Some(Expr::rt(collect, tail(args, droppers))) } - _ => super::collections::collect(b, ty, iter, span), + _ => super::collections::collect(b, ty, iter, from, span), } } + +/// What drops an iterator of type `ty` that a runtime function takes by value: `rt.drop`, +/// since each is an `rt.Iter`, or `undefined` for one that drops nothing. +pub(super) fn iter_dropper<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Expr { + if !b.t.drops(ty) { + return Expr::undefined(); + } + // The crate's own drops through `rt.iterFrom`; any other refuses one it can't drop. + if own_next(b, ty).is_none() { + b.t.dropper(ty, span); + } + Expr::Rt("drop".into()) +} + +/// `rt.iterToArray` of `iter`, an iterator of type `from`, collected into a `Vec` as +/// std's does: in place of the `Vec` its items come from, where it can. +pub(super) fn to_array<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + iter: Expr, + from: Ty<'tcx>, + elem: Ty<'tcx>, + span: Span, +) -> Expr { + let drop_it = iter_dropper(b, from, span); + let drop_elem = b.t.dropper(elem, span); + let drops = !matches!(&drop_it, Expr::Lit(l) if l == "undefined") + || !matches!(&drop_elem, Expr::Lit(l) if l == "undefined"); + let in_place = drops && in_place(b.t, from, elem); + if in_place && let Some(zip) = zip_holding(b, from) { + return b.err( + span, + format!("a `collect` in place of `{zip}`, whose second iterator drops, which is not supported yet"), + ); + } + let droppers = vec![Expr::lit(if in_place { "true" } else { "false" }), drop_it, drop_elem]; + Expr::rt("iterToArray", tail(vec![iter], droppers)) +} + +/// A `Zip` in `ty` whose second iterator drops, which std's `collect` in place drops after +/// what it collected, where `rt.iterToArray` drops the whole iterator before. +fn zip_holding<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> Option> { + let tcx = b.t.tcx; + let zips: Vec> = ty + .walk() + .filter_map(|arg| arg.as_type()) + .filter(|&t| std_iter_path(tcx, t).is_some_and(|p| p == ["iter", "adapters", "zip", "Zip"])) + .collect(); + zips.into_iter().find(|t| match t.kind() { + ty::Adt(_, args) => b.t.drops(args.type_at(1)), + _ => false, + }) +} + +/// Whether std's `collect` of an iterator of type `iter` into a `Vec` writes in place +/// of the `Vec` its items come from, as its adaptors let it where each item's layout leaves +/// room: then a panic drops what it collected before the rest of the source. +fn in_place<'tcx>(t: &Translator<'_, 'tcx>, iter: Ty<'tcx>, elem: Ty<'tcx>) -> bool { + let tcx = t.tcx; + let env = t.typing_env_pub(); + let (Some(steps), Some(source)) = (core_trait(tcx, "InPlaceIterable"), core_trait(tcx, "SourceIter")) else { + return false; + }; + if !implements(t, iter, "InPlaceIterable") || !implements(t, iter, "SourceIter") { + return false; + } + let assoc = |tr: DefId, name: &str| { + tcx.associated_items(tr) + .filter_by_name_unhygienic(rustc_span::Symbol::intern(name)) + .next() + .map(|item| item.def_id) + }; + // `::Source`, a `vec::IntoIter` of what it collects in place of. + let Some(src) = assoc(source, "Source").and_then(|item| { + let projection = Ty::new_projection(tcx, ty::IsRigid::No, item, [iter]); + tcx.try_normalize_erasing_regions(env, ty::Unnormalized::new_wip(projection)) + .ok() + }) else { + return false; + }; + let ty::Adt(adt, src_args) = src.kind() else { + return false; + }; + if library::std_path(tcx, adt.did()) != ["vec", "into_iter", "IntoIter"] { + return false; + } + // `MERGE_BY` and `EXPAND_BY`: how many source items make how many it collects, if known. + let step = |name: &str| -> Option { + let item = assoc(steps, name)?; + let instance = Instance::try_resolve(tcx, env, item, tcx.mk_args(&[iter.into()])).ok()??; + let value = tcx.const_eval_instance(env, instance, rustc_span::DUMMY_SP).ok()?; + Some(value.try_to_scalar_int()?.to_bits_unchecked()) + }; + let (Some(merge), Some(expand)) = (step("MERGE_BY"), step("EXPAND_BY")) else { + return false; + }; + let layout = |ty: Ty<'tcx>| tcx.layout_of(env.as_query_input(ty)).ok(); + let (Some(from), Some(to)) = (layout(src_args.type_at(0)), layout(elem)) else { + return false; + }; + // As std's `in_place_collectible`, where `None`, an overflow, is 0. + !from.is_zst() + && !to.is_zst() + && from.align.abi == to.align.abi + && merge > 0 + && expand > 0 + && u128::from(from.size.bytes()) * merge >= u128::from(to.size.bytes()) * expand +} diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index dd1bec09a..574637295 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -701,9 +701,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } - /// What a `DebugList` iterates, as an iterable JS value. + /// What a `DebugList` iterates, as an iterable JS value, which drops nothing it reads. fn items(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Option { let tcx = self.tcx; + if self.b.t.drops(ty) { + return Some(self.err( + span, + format!("`DebugList::entries` of `{ty}`, which drops, which is not supported yet"), + )); + } match ty.peel_refs().kind() { ty::Slice(_) | ty::Array(..) => Some(value), ty::Adt(adt, _) if Std::of(tcx, adt.did()) == Some(Std::Vec) => Some(library::vec_view(value, ty)), diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 8eca465ac..ea70eaa85 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2021,7 +2021,11 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { if self.b.t.drops(ty) { let mut pre = Vec::new(); let value = self.place_expr(*place, span, &mut pre); - if let Some(dropped) = self.b.t.drop_value(value, ty, span) { + let dropped = match place.as_local().is_some_and(|l| self.stepped.contains(&l)) { + true => self.stepped_drop(&value, ty, span), + false => self.b.t.drop_value(value, ty, span), + }; + if let Some(dropped) = dropped { pre.push(StmtKind::Expr(dropped).at(None)); } self.emit(pre, None, false, out); diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 15b9d998e..014cb18af 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -67,12 +67,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } // A field of an aggregate made once and never changed is its operand: a - // reference, which borrow checking keeps as it was, or a path that stays put. + // reference, which borrow checking keeps as it was, read again only if reading + // it runs nothing, or a path that stays put. (_, _) if let Some(parts) = self.var_parts.get(&place.local) && let Some(ProjectionElem::Field(field, field_ty)) = projection.peek() && let Some(part) = parts.get(field.as_usize()) - && (matches!(field_ty.kind(), ty::Ref(..)) || part.is_constant() || self.stable_name(part)) => + && ((matches!(field_ty.kind(), ty::Ref(..)) && super::cfg::pure(part)) + || part.is_constant() + || self.stable_name(part)) => { let part = part.clone(); let elem = *projection.peek().unwrap(); diff --git a/ts/src/lower/mir/step.rs b/ts/src/lower/mir/step.rs index 82adb926c..6e8681b97 100644 --- a/ts/src/lower/mir/step.rs +++ b/ts/src/lower/mir/step.rs @@ -266,15 +266,17 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { } /// An iterator stepped in place, from the `rt.Iter` its mapping makes: `{ s, i: 0 }` - /// from `rt.iterSlice(s)`, and `{ start, end }` from `new rt.Range(start, end)`. A - /// moved one is already made. + /// from `rt.iterSlice(s)`, or `rt.iterSlice(s, drop)` of items it owns, which its drop + /// drops again, and `{ start, end }` from `new rt.Range(start, end)`. A moved one is + /// already made. pub(super) fn stepped_make(&mut self, value: Expr, span: rustc_span::Span) -> Expr { let rt = |f: &Expr, name: &str| matches!(f, Expr::Rt(n) if n == name); let object = |fields: [(&str, Expr); 2]| { Expr::Object(fields.into_iter().map(|(k, v)| (Key::Name(k.into()), v)).collect()) }; match value { - Expr::Call(f, mut args) if rt(&f, "iterSlice") && args.len() == 1 => { + Expr::Call(f, mut args) if rt(&f, "iterSlice") && matches!(args.len(), 1 | 2) => { + args.truncate(1); object([("s", args.pop().unwrap()), ("i", Expr::lit("0"))]) } Expr::New(f, args) if rt(&f, "Range") && args.len() == 2 => { @@ -299,6 +301,17 @@ impl<'tcx> Fx<'_, '_, '_, 'tcx> { ) } + /// What drops a `Vec`'s iterator stepped in place, of type `ty`, as `it`: the items from + /// its index on. + pub(super) fn stepped_drop(&mut self, it: &Expr, ty: Ty<'tcx>, span: rustc_span::Span) -> Option { + let item = array_iter(self.tcx, ty)?; + let dropper = self.b.t.drop_fn(item, span)?; + Some(Expr::rt( + "dropAll", + vec![stepped_field(it, "s"), dropper, stepped_field(it, "i")], + )) + } + /// The types of a stepped local's variables: its array and index, or its bounds. pub(super) fn stepped_tys(&mut self, local: Local) -> [Type; 2] { let ty = self.mir.local_decls[local].ty; diff --git a/ts/tests/task.ts b/ts/tests/task.ts index e00a5d77e..b1562b783 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -281,5 +281,5 @@ export const cases: Uint8Array[] = [ [0, 0, 12, 0, 6, 0, 3, 5, 6, 0], [0, 0, 12, 0, 12, 1, 6, 0, 9, 1, 9, 0], // Each scenario of values std holds that drop, panicking at each point or none. - ...Array.from({ length: 104 }, (_, arg) => [11, arg]), + ...Array.from({ length: 144 }, (_, arg) => [11, arg]), ].map((script) => Uint8Array.from(script)); From 0a01766e8c82544bfe562157f6bf2ab2fbcd7ee0 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:06:22 -0700 Subject: [PATCH 03/18] feat(ts): skip iterator drop paths where nothing drops, and rewrite the quest `count` and a byte `collect` loop without a dropper check where nothing drops. The drop quest now holds what remains: closures that own values that drop, and the refusals without a census instance. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 35 +++++++++++++++++------------------ ts/README.md | 5 ++++- ts/runtime/rt/iter.ts | 10 +++++++++- 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index a78ec7fe0..46f26a599 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -1,4 +1,4 @@ -# [M] Drop in the TypeScript translator +# [S] Drop in the TypeScript translator ## Goal @@ -15,27 +15,26 @@ a flag where a value moved on some paths only. A panic unwinds through the clean blocks of `-C panic=unwind` MIR, which a function runs from a `catch`. A value without `[Symbol.dispose]`, such as an enum or a tuple, drops through glue lowered from rustc's `drop_in_place` shim. A runtime function that may drop what std's would (a collection's -`clear`, `unwrap_or`'s fallback) takes a dropper for each such type after its own -arguments (`drop_fn` and `droppers` in `drop.rs`). The task fixture's `drops.rs` checks -these against native Rust, natively unwinding too. +`clear`, `unwrap_or`'s fallback, an adaptor's rejects) takes a dropper for each such +type after its own arguments (`drop_fn` and `droppers` in `drop.rs`), and a consumer +that takes an iterator by value takes `rt.drop` for it. The task fixture's `drops.rs` +and `drops/iters.rs` check these against native Rust, natively unwinding too. What still fails translation, by the census at the pinned moq revision (moq-net's, then kio's): -- An iterator that owns a value that drops (124, 6), and the collection methods that - make one (19): `drain`, `into_keys`, and `into_values`. Most are a `for` loop over a - `Vec` or a map, and a `collect` of cloned `Path`s. An `rt.Iter` drops nothing it - skips, consumes, or still holds when it drops. Sources that own items need droppers - and a `[Symbol.dispose]` for what remains; adaptors drop what they discard (`filter`'s - rejects, `skip`, `nth`, `last`, `count`, `zip`'s unmatched item, `max_by_key`'s - losers) and what they hold (`Peekable`'s item, `Flatten`'s inner iterators); a - consumer that takes the iterator by value drops it, also when a closure panics. Look - out for `collect`, whose order of drops on a panic may differ between std's in-place and - generic paths, and for closures an adaptor holds, which must drop with it or refuse. - `extend` of a map or set already inserts each item as `insert` does, panics included, - but nothing tests it yet. A B-tree's `collect` sorts first, and a panicking `Ord` leaves - Rust's `Vec` in an order JS's `sort` won't match. -- A closure that owns a value that drops, dropped without a call that takes it (10, 0). +- A closure that owns a value that drops, dropped without a call that takes it (8, 0). + An arrow function has no `[Symbol.dispose]`; one that owns droppable captures needs + one, and so do the adaptors that hold it (`map`'s, `filter`'s), which drop it after + their iterator, as std's fields do. + +Refused with none in the census, each where std's order is one JS's can't follow yet: +`into_keys` and `into_values` of a hash map whose other half drops (`fold` drops it +after the half it yields, `next` before); `zip` of two `TrustedRandomAccess` iterators +of items that drop; a `flatten` whose inner iterator holds items once ended, or that a +`fold` reads where both its source and inner iterators drop; a B-tree's `collect` of +entries that drop, sorted by the crate's own `Ord`; a `collect` in place of a `zip` +whose second iterator drops; and `DebugList::entries` of items that drop. Watch the cost: a function whose cleanup does something JS can see sets a variable before each call that can panic and wraps its body in a `try`; measure any change on diff --git a/ts/README.md b/ts/README.md index d01719fd7..e81bcc9fe 100644 --- a/ts/README.md +++ b/ts/README.md @@ -173,7 +173,10 @@ panic drops matches native Rust's. A value without `[Symbol.dispose]` of its own an enum or a tuple, drops through glue lowered from rustc's `drop_in_place` shim, a function of its type's own (`drop$Held`). The runtime functions for std's collections, `Arc`, and the std functions that may discard an operand (`unwrap_or`, a map's `insert`) -take what drops each value they may drop, and drop it where std's do. A `Drop` impl that +take what drops each value they may drop, and drop it where std's do. So do iterators: one +that owns its items, as a `Vec`'s `into_iter` or a map's `drain` does, drops those it still +holds by `[Symbol.dispose]`, an adaptor drops what it skips or rejects, and a consumer that +takes an iterator by value drops it, a panic included. A `Drop` impl that panics leaves the rest to drop as Rust's does: a class's glue and the runtime's droppers go on to the rest of the value and its container, but a hash table leaks its other entries, as std's does. diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index dd9150060..d448e6e4b 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -75,8 +75,12 @@ export abstract class Iter implements Iterable, Disposable { /** `count`, dropping each item by `drop`. */ countItems(drop?: Drop): number { let n = 0; + if (drop === undefined) { + while (this.next() !== DONE) n++; + return n; + } for (let item = this.next(); item !== DONE; item = this.next()) { - drop?.(item); + drop(item); n++; } return n; @@ -577,6 +581,10 @@ export function iterToArray(it: Iter, inPlace = false, dropIt?: Drop, dropIt?: Drop>): ByteVec { const out = new ByteVec(); // Its own loop: through `iterExtendBytes`, JavaScriptCore took 1.9x as long. + if (dropIt === undefined) { + for (let item = it.next(); item !== DONE; item = it.next()) byteVecPush(out, item); + return out; + } try { for (let item = it.next(); item !== DONE; item = it.next()) byteVecPush(out, item); } finally { From eb9d8765b1d8b0877eb0c05f779eb5a3070577ac Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:18:21 -0700 Subject: [PATCH 04/18] fix(ts): drop a hash iterator's entries once when a drop panics A hash iterator's dispose resumed where a panicking drop left it, so a consumer that disposed it again after `count` dropped the entries std's table leaks. It now takes its count first. The task fixture's `spent` covers each consumer that drops an iterator it already disposed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops.ts | 186 ++++++------ .../task/expected/drops/iters.Count.ts | 45 +++ .../task/expected/drops/iters.First.ts | 51 ++++ ts/fixtures/task/expected/drops/iters.ts | 264 +++++++++++++++++- ts/fixtures/task/expected/lib.ts | 5 + ts/fixtures/task/src/drops.rs | 7 +- ts/fixtures/task/src/drops/iters.rs | 104 +++++++ ts/runtime/rt/collections.ts | 8 +- ts/tests/task.ts | 2 +- 9 files changed, 572 insertions(+), 100 deletions(-) create mode 100644 ts/fixtures/task/expected/drops/iters.Count.ts create mode 100644 ts/fixtures/task/expected/drops/iters.First.ts diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 4a3bf1290..c122034b1 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -2,7 +2,7 @@ import * as rt from "./rt.ts"; import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Guard_Bomb_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; -import { looped, collected, drained, extended, bombed } from "./drops/iters.ts"; +import { looped, collected, drained, extended, bombed, spent } from "./drops/iters.ts"; import * as Bomb from "./drops.Bomb.ts"; import type * as Fault from "./drops.Fault.ts"; import * as Held from "./drops.Held.ts"; @@ -16,7 +16,7 @@ import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; /** - * Run scenario `arg % 18`, panicking at the point `arg / 18 % 8` names, if any: what + * Run scenario `arg % 19`, panicking at the point `arg / 19 % 8` names, if any: what * every value std holds drops, where Rust drops it, and in Rust's order. */ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { @@ -74,7 +74,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _353 = false; _352 = false; _351 = false; - const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 18), 8); + const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 19), 8); const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -84,7 +84,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { rt.panicFmt(["d", args16[0], " at ", args16[1]]); } }; - const _13: rt.u8 = rt.u8Rem(arg, 18); + const _13: rt.u8 = rt.u8Rem(arg, 19); if (_13 === 13) { looped(log, id, at); } else if (_13 === 14) { @@ -95,6 +95,8 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { extended(log, id, at); } else if (_13 === 17) { bombed(log, id, at); + } else if (_13 === 18) { + spent(log, id, at); } else if (_13 === 4) { ordered(log, id, at); } else if (_13 === 5) { @@ -115,23 +117,23 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { grown(log, id, at, false); } else if (_13 === 0) { v = []; - unwind = 202; + unwind = 203; const _19: Held.Held = { tag: "One", _0: guard(1) }; v.push(_19); v.push({ tag: "Empty" } as Held.Held); _29 = guard(2); - unwind = 201; - const _32: Guard.Guard = guard(3); unwind = 202; + const _32: Guard.Guard = guard(3); + unwind = 203; v.push({ tag: "Two", _0: _29, _1: _32 } as Held.Held); - unwind = 200; + unwind = 201; held_ = v; check(1); arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); - unwind = 219; + unwind = 220; _358 = true; shared = rt.arcClone(arc); - unwind = 199; + unwind = 200; _358 = false; rt.arcDrop(arc, drop$Held); const arg7 = ([shared.strong] as [rt.usize])[0]; @@ -139,22 +141,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { Log.note(log, rt.fmtFormat(["arc ", args2[0]])); check(2); v2 = []; - unwind = 198; + unwind = 199; const _67: Held.Held = { tag: "One", _0: guard(5) }; v2.push(_67); - unwind = 199; + unwind = 200; mutex = new rt.Mutex(v2); - unwind = 217; + unwind = 218; _357 = true; _73 = guard(6); - unwind = 197; + unwind = 198; const _76: Guard.Guard = guard(7); - unwind = 217; + unwind = 218; boxed = { tag: "Two", _0: _73, _1: _76 } as Held.Held; - unwind = 215; + unwind = 216; _356 = true; const _80: Held.Held = { tag: "One", _0: guard(8) }; - unwind = 196; + unwind = 197; maybe = _80; check(3); [held_.length, maybe !== undefined] as [rt.usize, boolean]; @@ -168,9 +170,9 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _357 = false; rt.dropAll(mutex.value, drop$Held); check(5); - unwind = 215; + unwind = 216; drop$Option_Box_Held(maybe); - unwind = 219; + unwind = 220; _356 = false; _357 = false; rt.arcDrop(shared, drop$Held); @@ -180,53 +182,53 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 1) { const _115: rt.u32 = rt.u32Add(id, 10); _117 = Log.clone$Clone(log); - unwind = 195; + unwind = 196; const _119: Guard.Guard = guard(11); - unwind = 194; + unwind = 195; wrapped = new Wrap.Wrap({ id: _115, log: _117, inner: { tag: "One", _0: _119 } as Held.Held }); const _123: rt.u32 = rt.u32Add(id, 20); _125 = Log.clone$Clone(log); - unwind = 193; + unwind = 194; const _126: Guard.Guard = guard(21); - unwind = 192; + unwind = 193; guarded = new Wrap.Wrap({ id: _123, log: _125, inner: _126 }); check(1); _134 = guard(31); - unwind = 191; + unwind = 192; const _137: Guard.Guard = guard(32); - unwind = 190; + unwind = 191; _133 = { tag: "Two", _0: _134, _1: _137 } as Held.Held; const _140: Guard.Guard = guard(33); - unwind = 213; + unwind = 214; _355 = true; pair = new Pair.Pair({ first: _133, second: _140 }); v3 = []; - unwind = 189; + unwind = 190; _148 = guard(41); - unwind = 188; - const _151: Guard.Guard = guard(42); unwind = 189; + const _151: Guard.Guard = guard(42); + unwind = 190; v3.push(new Pair.Pair({ first: _148, second: _151 })); _157 = guard(43); - unwind = 187; + unwind = 188; const _160: Guard.Guard = guard(44); - unwind = 189; + unwind = 190; v3.push(new Pair.Pair({ first: _157, second: _160 })); - unwind = 186; + unwind = 187; pairs = v3; check(2); const _167: rt.u32 = rt.u32Add(id, 50); _169 = Log.clone$Clone(log); - unwind = 185; + unwind = 186; v4 = []; - unwind = 184; + unwind = 185; const _175: rt.u32 = rt.u32Add(id, 60); _177 = Log.clone$Clone(log); - unwind = 183; - const _179: Guard.Guard = guard(61); unwind = 184; + const _179: Guard.Guard = guard(61); + unwind = 185; v4.push(new Wrap.Wrap({ id: _175, log: _177, inner: { tag: "One", _0: _179 } as Held.Held })); - unwind = 182; + unwind = 183; nested = new Wrap.Wrap({ id: _167, log: _169, inner: v4 }); check(3); _355 = false; @@ -243,11 +245,11 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg6 = args5[2]; const args6: rt.Fmt[] = [_218, _219, (f: rt.Formatter) => rt.u32Display(arg6, f)]; Log.note(log, rt.fmtFormat(["wraps ", args6[0], " ", args6[1], " ", args6[2]])); - unwind = 186; + unwind = 187; drop$Wrap_Vec_Wrap_Held(nested); - unwind = 213; + unwind = 214; rt.dropAll(pairs); - unwind = 194; + unwind = 195; _355 = false; drop$Wrap_Guard(guarded); unwind = 0; @@ -255,22 +257,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 2) { const _225: rt.u32 = rt.u32Add(id, 70); _227 = Log.clone$Clone(log); - unwind = 181; + unwind = 182; const _230: Guard.Guard = guard(71); - unwind = 180; + unwind = 181; _229 = { tag: "One", _0: _230 } as Held.Held; const _233: Guard.Guard = guard(72); unwind = 0; shared2 = new rt.Arc(new Wrap.Wrap({ id: _225, log: _227, inner: new Pair.Pair({ first: _229, second: _233 }) })); - unwind = 211; + unwind = 212; _354 = true; v5 = []; - unwind = 179; + unwind = 180; const _240: rt.Arc>> = rt.arcClone(shared2); v5.push(_240); const _244: rt.Arc>> = rt.arcClone(shared2); v5.push(_244); - unwind = 178; + unwind = 179; clones = v5; check(1); _354 = false; @@ -282,37 +284,37 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg5 = ([!bail(log, id, at).ok] as [boolean])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg5, f)]; Log.note(log, rt.fmtFormat(["bailed ", args10[0]])); - unwind = 211; + unwind = 212; rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); _354 = false; } else { _282 = guard(81); - unwind = 177; + unwind = 178; const _285: Guard.Guard = guard(82); unwind = 0; arc2 = new rt.Arc(new rt.Mutex({ tag: "Two", _0: _282, _1: _285 } as Held.Held)); - unwind = 209; + unwind = 210; _353 = true; other = rt.arcClone(arc2); - unwind = 176; + unwind = 177; check(1); _353 = false; rt.arcDrop(arc2, drop$Mutex_Held); check(2); const _301: rt.Mutex = other.value; - unwind = 175; - const held2: boolean = Held.isSome(_301.value); unwind = 176; + const held2: boolean = Held.isSome(_301.value); + unwind = 177; const arg2 = ([held2] as [boolean])[0]; const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg2, f)]; Log.note(log, rt.fmtFormat(["locked ", args12[0]])); lent = guard(83); - unwind = 174; + unwind = 175; borrowed = new rt.Arc(lent); - unwind = 207; + unwind = 208; _352 = true; again = rt.arcClone(borrowed); - unwind = 205; + unwind = 206; _351 = true; _352 = false; rt.arcDrop(borrowed); @@ -322,11 +324,11 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg3 = ([Guard.id(lent)] as [rt.u32])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; Log.note(log, rt.fmtFormat(["lent ", args14[0]])); - unwind = 176; + unwind = 177; _351 = false; _352 = false; rt.drop(lent); - unwind = 209; + unwind = 210; rt.arcDrop(other, drop$Mutex_Held); _353 = false; } @@ -353,127 +355,127 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { if (unwind === 0) { throw e; } - if (unwind === 174) { - break b4; - } if (unwind === 175) { - break b3; + break b4; } if (unwind === 176) { break b3; } if (unwind === 177) { + break b3; + } + if (unwind === 178) { rt.drop(_282); break b1; } - if (unwind === 178) { + if (unwind === 179) { rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 179) { + if (unwind === 180) { rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 180) { + if (unwind === 181) { drop$Held(_229); break b6; } - if (unwind === 181) { + if (unwind === 182) { break b6; } - if (unwind === 182) { + if (unwind === 183) { drop$Wrap_Vec_Wrap_Held(nested); break b10; } - if (unwind === 183) { + if (unwind === 184) { rt.drop(_177); break b12; } - if (unwind === 184) { + if (unwind === 185) { break b12; } - if (unwind === 185) { + if (unwind === 186) { break b11; } - if (unwind === 186) { + if (unwind === 187) { break b10; } - if (unwind === 187) { + if (unwind === 188) { rt.drop(_157); break b13; } - if (unwind === 188) { + if (unwind === 189) { rt.drop(_148); break b13; } - if (unwind === 189) { + if (unwind === 190) { break b13; } - if (unwind === 190) { + if (unwind === 191) { drop$Held(_133); break b8; } - if (unwind === 191) { + if (unwind === 192) { rt.drop(_134); break b8; } - if (unwind === 192) { + if (unwind === 193) { break b8; } - if (unwind === 193) { + if (unwind === 194) { rt.drop(_125); break b7; } - if (unwind === 194) { + if (unwind === 195) { break b7; } - if (unwind === 195) { + if (unwind === 196) { rt.drop(_117); break b1; } - if (unwind === 196) { + if (unwind === 197) { drop$Option_Box_Held(maybe); break b18; } - if (unwind === 197) { + if (unwind === 198) { rt.drop(_73); break b17; } - if (unwind === 198) { + if (unwind === 199) { rt.dropAll(v2, drop$Held); break b16; } - if (unwind === 199) { + if (unwind === 200) { break b16; } - if (unwind === 200) { + if (unwind === 201) { break b14; } - if (unwind === 201) { + if (unwind === 202) { rt.drop(_29); break b19; } - if (unwind === 202) { + if (unwind === 203) { break b19; } - if (unwind === 205) { + if (unwind === 206) { if (_351) { rt.arcDrop(again); } - } else if (unwind !== 207) { - if (unwind === 209) { + } else if (unwind !== 208) { + if (unwind === 210) { break b2; } - if (unwind === 211) { + if (unwind === 212) { break b5; } - if (unwind === 213) { + if (unwind === 214) { break b9; } - if (unwind === 215) { + if (unwind === 216) { break b18; } - if (unwind === 217) { + if (unwind === 218) { break b17; } break b15; diff --git a/ts/fixtures/task/expected/drops/iters.Count.ts b/ts/fixtures/task/expected/drops/iters.Count.ts new file mode 100644 index 000000000..77250efc2 --- /dev/null +++ b/ts/fixtures/task/expected/drops/iters.Count.ts @@ -0,0 +1,45 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import * as Log from "../log.Log.ts"; + +/** Logs how many values dropped to its sink, as it drops last. */ +export class Count { + sink: Log.Log; + log: Log.Log; + + constructor(fields: { sink: Log.Log; log: Log.Log }) { + this.sink = fields.sink; + this.log = fields.log; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + drop$Drop(this); + dropped = 1; + rt.drop(this.sink); + dropped = 2; + rt.drop(this.log); + } catch (e) { + if (dropped < 1) { + rt.drop(this.sink); + } + if (dropped < 2) { + rt.drop(this.log); + } + throw e; + } + } +} + +export function drop$Drop(self: Count): void { + const arg = ([rt.iterCount(rt.iterFilter(rt.iterSlice(rt.byteSliceView(rt.byteVecSlice(Log.text(self.sink)))), (_2: rt.u8): boolean => { + return _2 === 10; + }))] as [rt.usize])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg, f)]; + const _11: string = rt.fmtFormat(["dropped ", args2[0]]); + Log.note(self.log, _11); +} + +//# sourceMappingURL=iters.Count.ts.map diff --git a/ts/fixtures/task/expected/drops/iters.First.ts b/ts/fixtures/task/expected/drops/iters.First.ts new file mode 100644 index 000000000..12acc920b --- /dev/null +++ b/ts/fixtures/task/expected/drops/iters.First.ts @@ -0,0 +1,51 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import * as Log from "../log.Log.ts"; + +/** + * A value that logs its drop to a sink, and panics if it is the first there: which one + * that is, std's hash tables leave unspecified, but not how many drop after. + */ +export class First { + id: rt.u32; + sink: Log.Log; + + constructor(fields: { id: rt.u32; sink: Log.Log }) { + this.id = fields.id; + this.sink = fields.sink; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + drop$Drop(this); + dropped = 1; + rt.drop(this.sink); + } catch (e) { + if (dropped < 1) { + rt.drop(this.sink); + } + throw e; + } + } +} + +export function drop$Drop(self: First): void { + const first: boolean = Log.text(self.sink).length === 0; + const _8: string = rt.fmtFormat(["dropped"]); + Log.note(self.sink, _8); + if (first) { + rt.panicFmt(["first blew"]); + } +} + +export function eq$PartialEq(self: First, other: First): boolean { + return self.id === other.id; +} + +export function hash$Hash_DefaultHasher(self: First, state: rt.Hasher): void { + rt.hashInt(self.id, state); +} + +//# sourceMappingURL=iters.First.ts.map diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index b8c992c4e..24548580a 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -1,7 +1,9 @@ // Generated by rust2-ts. Do not edit. import * as rt from "../rt.ts"; -import { drop$Guard_Guard, drop$Guard_u32, drop$Key_Guard, drop$Option_Key_Guard, drop$Option_u32_Bomb, drop$Result_Vec_Guard_Guard, drop$Vec_Bomb, drop$Vec_Guard, drop$u32_Bomb, drop$u32_Guard } from "../lib.ts"; +import { drop$Guard_Guard, drop$Guard_u32, drop$Key_Guard, drop$Option_Key_Guard, drop$Option_u32_Bomb, drop$Result_Vec_Guard_Guard, drop$Vec_Bomb, drop$Vec_Guard, drop$u32_Bomb, drop$u32_First, drop$u32_Guard } from "../lib.ts"; +import * as Count from "../drops/iters.Count.ts"; +import * as First from "../drops/iters.First.ts"; import * as Bomb from "../drops.Bomb.ts"; import * as Key from "../drops.Key.ts"; import * as Log from "../log.Log.ts"; @@ -2229,4 +2231,264 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { } } +/** + * What drops after an item's `Drop` panics inside a consumer that drops the iterator it + * was given, scenario `at`'s alone: the rest, as std's iterator leaves it, each once. + */ +export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { + let sink!: Log.Log; + let _count!: Count.Count; + let _6!: Log.Log; + let map!: rt.HashMap; + let _17!: rt.u32; + let set!: rt.HashSet; + let _34!: rt.u32; + let v!: First.First[]; + let peek!: rt.Peekable; + let v2!: First.First[]; + let _96!: rt.Iter; + let v3!: First.First[]; + let v4!: First.First[]; + let map2!: rt.BTreeMap; + let _120!: rt.u32; + let queue!: rt.VecDeque; + let _137!: rt.u32; + let map3!: rt.HashMap; + let _154!: rt.u32; + let _171!: boolean; + let _172!: boolean; + let _173!: boolean; + let _174!: boolean; + let _175!: boolean; + let _176!: boolean; + let unwind: number = 0; + try { + _176 = false; + _175 = false; + _174 = false; + _173 = false; + _172 = false; + _171 = false; + sink = Log.new(); + unwind = 116; + _6 = Log.clone$Clone(sink); + unwind = 115; + _count = new Count.Count({ sink: _6, log: Log.clone$Clone(log) }); + const first: (a0: rt.u32) => First.First = (n6: rt.u32): First.First => { + return new First.First({ id: rt.u32Add(id, n6), sink: Log.clone$Clone(sink) }); + }; + if (at === 0) { + unwind = 114; + map = rt.hashNew() as rt.HashMap; + unwind = 129; + _176 = true; + let iterStart: rt.u32 = 0; + const iterEnd: rt.u32 = 3; + while ((_17 = iterStart++) < iterEnd) { + const n: rt.u32 = _17; + const _23: First.First = first(n); + rt.drop(rt.hashInsert(map, n, _23, undefined, rt.drop)); + } + _176 = false; + rt.iterCount(rt.hashIter(map, undefined, rt.drop), rt.drop, drop$u32_First); + _176 = false; + } else if (at === 1) { + unwind = 114; + set = rt.hashNew(rt.hashing(First.hash$Hash_DefaultHasher, First.eq$PartialEq)) as rt.HashSet; + unwind = 127; + _175 = true; + let iterStart2: rt.u32 = 0; + const iterEnd2: rt.u32 = 3; + while ((_34 = iterStart2++) < iterEnd2) { + const _40: First.First = first(_34); + rt.hashAdd(set, _40, rt.drop); + } + _175 = false; + rt.iterCount(rt.hashKeys(set, rt.drop), rt.drop, rt.drop); + _175 = false; + } else if (at === 2) { + unwind = 114; + v = []; + unwind = 113; + const _54: First.First = first(0); + v.push(_54); + const _59: First.First = first(1); + v.push(_59); + const _64: First.First = first(2); + v.push(_64); + unwind = 114; + rt.iterCount(rt.iterSkip(rt.iterSlice(v, rt.drop), 1, rt.drop), rt.drop, rt.drop); + } else if (at === 3) { + unwind = 114; + v2 = []; + unwind = 112; + const _73: First.First = first(0); + v2.push(_73); + const _78: First.First = first(1); + v2.push(_78); + const _83: First.First = first(2); + v2.push(_83); + unwind = 114; + peek = rt.iterPeekable(rt.iterSlice(v2, rt.drop), rt.drop); + unwind = 125; + _174 = true; + rt.peekablePeek(peek) !== undefined; + _174 = false; + rt.iterCount(peek, rt.drop, rt.drop); + _174 = false; + } else if (at === 4) { + unwind = 114; + v3 = []; + unwind = 111; + const _101: First.First = first(0); + v3.push(_101); + unwind = 114; + _96 = rt.iterSlice(v3, rt.drop); + unwind = 123; + _173 = true; + v4 = []; + unwind = 110; + const _108: First.First = first(1); + v4.push(_108); + const _113: First.First = first(2); + v4.push(_113); + unwind = 123; + const _104: First.First[] = v4; + _173 = false; + const _95: rt.Iter = rt.iterChain(_96, rt.iterSlice(_104, rt.drop)); + unwind = 114; + _173 = false; + rt.iterCount(_95, rt.drop, rt.drop); + } else if (at === 5) { + unwind = 114; + map2 = rt.btreeNew(rt.cmp) as rt.BTreeMap; + unwind = 121; + _172 = true; + let iterStart3: rt.u32 = 0; + const iterEnd3: rt.u32 = 3; + while ((_120 = iterStart3++) < iterEnd3) { + const n3: rt.u32 = _120; + const _126: First.First = first(n3); + rt.drop(rt.btreeInsert(map2, n3, _126, undefined, rt.drop)); + } + _172 = false; + rt.iterCount(rt.btreeIter(map2, undefined, rt.drop), rt.drop, drop$u32_First); + _172 = false; + } else if (at === 6) { + unwind = 114; + queue = rt.dequeNew() as rt.VecDeque; + unwind = 119; + _171 = true; + let iterStart4: rt.u32 = 0; + const iterEnd4: rt.u32 = 3; + while ((_137 = iterStart4++) < iterEnd4) { + const _143: First.First = first(_137); + rt.dequePushBack(queue, _143); + } + _171 = false; + rt.iterCount(rt.dequeIter(queue, rt.drop), rt.drop, rt.drop); + _171 = false; + } else { + unwind = 114; + map3 = rt.hashNew() as rt.HashMap; + unwind = 109; + let iterStart5: rt.u32 = 0; + const iterEnd5: rt.u32 = 3; + while ((_154 = iterStart5++) < iterEnd5) { + const n5: rt.u32 = _154; + const _160: First.First = first(n5); + rt.drop(rt.hashInsert(map3, n5, _160, undefined, rt.drop)); + } + rt.iterCount(rt.hashDrain(map3, undefined, rt.drop), rt.drop, drop$u32_First); + unwind = 114; + rt.hashDrop(map3, undefined, rt.drop); + } + unwind = 114; + Log.note(log, rt.fmtFormat(["unreached"])); + unwind = 116; + rt.drop(_count); + unwind = 0; + rt.drop(sink); + } catch (e) { + b11: { + b12: { + if (unwind === 0) { + throw e; + } + if (unwind === 109) { + rt.hashDrop(map3, undefined, rt.drop); + break b12; + } + if (unwind === 110) { + rt.dropAll(v4); + } else { + if (unwind === 111) { + rt.dropAll(v3); + break b12; + } + if (unwind === 112) { + rt.dropAll(v2); + break b12; + } + if (unwind === 113) { + rt.dropAll(v); + break b12; + } + if (unwind === 114) { + break b12; + } + if (unwind === 115) { + rt.drop(_6); + break b11; + } + if (unwind === 116) { + break b11; + } + if (unwind === 119) { + if (!_171) { + break b12; + } + rt.dequeDrop(queue, rt.drop); + break b12; + } + if (unwind === 121) { + if (!_172) { + break b12; + } + rt.btreeDrop(map2, undefined, rt.drop); + break b12; + } + if (unwind !== 123) { + if (unwind === 125) { + if (!_174) { + break b12; + } + rt.drop(peek); + break b12; + } + if (unwind === 127) { + if (!_175) { + break b12; + } + rt.hashDrop(set, rt.drop); + break b12; + } + if (!_176) { + break b12; + } + rt.hashDrop(map, undefined, rt.drop); + break b12; + } + } + if (_173) { + rt.drop(_96); + } + } + rt.drop(_count); + } + rt.drop(sink); + throw e; + } +} + //# sourceMappingURL=iters.ts.map diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index aa4f24d2b..dff38654c 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import type * as First from "./drops/iters.First.ts"; import type * as Bomb from "./drops.Bomb.ts"; import type * as Held from "./drops.Held.ts"; import type * as Key from "./drops.Key.ts"; @@ -305,6 +306,10 @@ export function drop$u32_Bomb(_1: [rt.u32, Bomb.Bomb]): void { rt.drop(_1[1]); } +export function drop$u32_First(_1: [rt.u32, First.First]): void { + rt.drop(_1[1]); +} + export function drop$u32_Guard(_1: [rt.u32, Guard.Guard]): void { rt.drop(_1[1]); } diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index 0d488a7be..dac26786f 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -49,22 +49,23 @@ pub struct Pair { second: Guard, } -/// Run scenario `arg % 18`, panicking at the point `arg / 18 % 8` names, if any: what +/// Run scenario `arg % 19`, panicking at the point `arg / 19 % 8` names, if any: what /// every value std holds drops, where Rust drops it, and in Rust's order. pub fn run(log: &Log, id: u32, arg: u8) { - let at = arg / 18 % 8; + let at = arg / 19 % 8; let guard = |n: u32| Guard::new(id + n, log.clone()); let check = |point: u8| { if point == at { panic!("d{id} at {point}"); } }; - match arg % 18 { + match arg % 19 { 13 => iters::looped(log, id, at), 14 => iters::collected(log, id, at), 15 => iters::drained(log, id, at), 16 => iters::extended(log, id, at), 17 => iters::bombed(log, id, at), + 18 => iters::spent(log, id, at), 4 => ordered(log, id, at), 5 => hashed(log, id, at), 6 => options(log, id, at), diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index 223662779..3804182c5 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -381,3 +381,107 @@ pub(super) fn bombed(log: &Log, id: u32, at: u8) { } log.note(format!("unreached")); } + +/// A value that logs its drop to a sink, and panics if it is the first there: which one +/// that is, std's hash tables leave unspecified, but not how many drop after. +struct First { + id: u32, + sink: Log, +} + +impl Drop for First { + fn drop(&mut self) { + let first = self.sink.text().is_empty(); + self.sink.note(format!("dropped")); + if first { + panic!("first blew"); + } + } +} + +impl PartialEq for First { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +impl Eq for First {} + +impl std::hash::Hash for First { + fn hash(&self, state: &mut H) { + self.id.hash(state); + } +} + +/// Logs how many values dropped to its sink, as it drops last. +struct Count { + sink: Log, + log: Log, +} + +impl Drop for Count { + fn drop(&mut self) { + let text = self.sink.text(); + let lines = text.iter().filter(|&&b| b == b'\n').count(); + self.log.note(format!("dropped {lines}")); + } +} + +/// What drops after an item's `Drop` panics inside a consumer that drops the iterator it +/// was given, scenario `at`'s alone: the rest, as std's iterator leaves it, each once. +pub(super) fn spent(log: &Log, id: u32, at: u8) { + let sink = Log::new(); + let _count = Count { + sink: sink.clone(), + log: log.clone(), + }; + let first = |n: u32| First { + id: id + n, + sink: sink.clone(), + }; + match at { + 0 => { + let mut map = HashMap::new(); + for n in 0..3 { + map.insert(n, first(n)); + } + drop(map.into_iter().count()); + } + 1 => { + let mut set = HashSet::new(); + for n in 0..3 { + set.insert(first(n)); + } + drop(set.into_iter().count()); + } + 2 => drop(list![first(0), first(1), first(2)].into_iter().skip(1).count()), + 3 => { + let mut peek = list![first(0), first(1), first(2)].into_iter().peekable(); + drop(peek.peek().is_some()); + drop(peek.count()); + } + 4 => drop(list![first(0)].into_iter().chain(list![first(1), first(2)]).count()), + 5 => { + let mut map = BTreeMap::new(); + for n in 0..3 { + map.insert(n, first(n)); + } + drop(map.into_iter().count()); + } + 6 => { + let mut queue = VecDeque::new(); + for n in 0..3 { + queue.push_back(first(n)); + } + drop(queue.into_iter().count()); + } + _ => { + let mut map = HashMap::new(); + for n in 0..3 { + map.insert(n, first(n)); + } + drop(map.drain().count()); + } + } + log.note(format!("unreached")); +} diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index 8ca66e0cb..b715fda2a 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -627,9 +627,11 @@ class HashIter extends Iter { override [Symbol.dispose](): void { if (this.k === undefined && this.v === undefined) return; - // A panic leaves the entries after it undropped, as std's table does. - for (let n = this.left; n > 0; n--) { - this.left--; + // A panic leaves the entries after it undropped, as std's table does, even as what + // consumed it drops it again. + const n = this.left; + this.left = 0; + for (let i = 0; i < n; i++) { const [key, value] = this.entry(); dropPair(key, value, this.k, this.v); } diff --git a/ts/tests/task.ts b/ts/tests/task.ts index b1562b783..3ea7207bb 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -281,5 +281,5 @@ export const cases: Uint8Array[] = [ [0, 0, 12, 0, 6, 0, 3, 5, 6, 0], [0, 0, 12, 0, 12, 1, 6, 0, 9, 1, 9, 0], // Each scenario of values std holds that drop, panicking at each point or none. - ...Array.from({ length: 144 }, (_, arg) => [11, arg]), + ...Array.from({ length: 152 }, (_, arg) => [11, arg]), ].map((script) => Uint8Array.from(script)); From c06f73a0cfc8a2bb41b002046ea36443d5fa40c1 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:57:10 -0700 Subject: [PATCH 05/18] fix(ts): skip from the back as std's `skip`, `take`, and `step_by` do `Skip`'s `nth_back` and `advance_back_by`, `Take`'s `advance_back_by`, and `StepBy`'s `nth_back` read their iterator from the back in one step, so what they pass drops front to back, as a `Vec`'s slice does, where the generic loop dropped it one item at a time from the back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 651 ++++++++++++++--------- ts/fixtures/task/src/drops/iters.rs | 19 + ts/runtime/rt/iter.ts | 39 +- 3 files changed, 460 insertions(+), 249 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 24548580a..29e69fbfe 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -52,33 +52,44 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { let v14!: Guard.Guard[]; let v15!: Guard.Guard[]; let v16!: Guard.Guard[]; - let _510!: boolean; - let _511!: boolean; - let _512!: boolean; - let _513!: boolean; - let _514!: boolean; - let _515!: boolean; - let _516!: boolean; + let _499!: Guard.Guard | undefined; + let _501!: rt.Iter; + let _509!: rt.Iter; + let _517!: rt.Iter; + let _518!: rt.Iter; + let _528!: rt.Iter; + let _529!: rt.Iter; + let _571!: boolean; + let _572!: boolean; + let _573!: boolean; + let _574!: boolean; + let _575!: boolean; + let _576!: boolean; + let _577!: boolean; + let _578!: boolean; + let _579!: boolean; let unwind: number = 0; try { - _516 = false; - _515 = false; - _514 = false; - _512 = false; - _513 = false; - _511 = false; - _510 = false; + _579 = false; + _578 = false; + _577 = false; + _575 = false; + _576 = false; + _574 = false; + _573 = false; + _572 = false; + _571 = false; const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; const check: (a0: rt.u8) => void = (point: rt.u8): void => { if (point === at) { - const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; - rt.panicFmt(["d", args24[0], " at ", args24[1]]); + const args26: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args26[0], " at ", args26[1]]); } }; v = []; - unwind = 274; + unwind = 318; const _14: Guard.Guard = guard(1); v.push(_14); const _19: Guard.Guard = guard(2); @@ -89,18 +100,18 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { iterS = v; iterI = 0; while (true) { - unwind = 273; + unwind = 317; const _28: Guard.Guard | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; if (_28 === rt.DONE) { break; } - unwind = 272; + unwind = 316; g = _28; if (!(Guard.id(g) === rt.u32Add(id, 2))) { - unwind = 273; + unwind = 317; rt.drop(g); } else { - unwind = 273; + unwind = 317; rt.drop(g); break; } @@ -108,19 +119,19 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 0; rt.dropAll(iterS, rt.drop, iterI); _39 = guard(4); - unwind = 271; + unwind = 315; _42 = guard(5); - unwind = 270; + unwind = 314; const _45: Guard.Guard = guard(6); unwind = 0; iter2 = rt.iterSlice([_39, _42, _45], rt.drop); while (true) { - unwind = 269; + unwind = 313; const _49: Guard.Guard | rt.Done = iter2.next(); if (_49 === rt.DONE) { break; } - unwind = 268; + unwind = 312; g2 = _49; const arg = ([Guard.id(g2)] as [rt.u32])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; @@ -128,30 +139,30 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { if (Guard.id(g2) === rt.u32Add(id, 5)) { check(1); } - unwind = 269; + unwind = 313; rt.drop(g2); } unwind = 0; rt.drop(iter2); iter3 = rt.iterOption(guard(7), rt.drop); while (true) { - unwind = 267; + unwind = 311; const _79: Guard.Guard | rt.Done = iter3.next(); if (_79 === rt.DONE) { break; } - unwind = 266; + unwind = 310; g3 = _79; const arg2 = ([Guard.id(g3)] as [rt.u32])[0]; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; Log.note(log, rt.fmtFormat(["option ", args4[0]])); - unwind = 267; + unwind = 311; rt.drop(g3); } unwind = 0; rt.drop(iter3); v2 = []; - unwind = 265; + unwind = 309; const _102: Guard.Guard = guard(8); v2.push(_102); const _107: Guard.Guard = guard(9); @@ -167,12 +178,12 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } return rt.u32Rem(Guard.id(g4), 2) === 0; }, rt.drop), true, rt.drop, rt.drop); - unwind = 264; + unwind = 308; const arg3 = ([even.length] as [rt.usize])[0]; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; Log.note(log, rt.fmtFormat(["even ", args6[0]])); v3 = []; - unwind = 263; + unwind = 307; const _142: Guard.Guard = guard(12); v3.push(_142); const _147: Guard.Guard = guard(13); @@ -183,10 +194,10 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v3.push(_157); const _162: Guard.Guard = guard(16); v3.push(_162); - unwind = 264; + unwind = 308; rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); - unwind = 289; - _516 = true; + unwind = 337; + _579 = true; const arg4 = ([rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { let unwind2: number = 0; try { @@ -206,28 +217,28 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; Log.note(log, rt.fmtFormat(["next ", args8[0]])); check(3); - _516 = false; + _579 = false; const arg5 = ([rt.iterCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; Log.note(log, rt.fmtFormat(["count ", args10[0]])); v4 = []; - unwind = 262; + unwind = 306; const _199: Guard.Guard = guard(17); v4.push(_199); const _204: Guard.Guard = guard(18); v4.push(_204); - unwind = 289; + unwind = 337; peek = rt.iterPeekable(rt.iterSlice(v4, rt.drop), rt.drop); - unwind = 287; - _515 = true; + unwind = 335; + _578 = true; first = rt.peekableNextIf(peek, (g6: Guard.Guard): boolean => { return Guard.id(g6) === rt.u32Add(id, 17); }); - unwind = 261; + unwind = 305; second = rt.peekableNextIf(peek, (g7: Guard.Guard): boolean => { return Guard.id(g7) === rt.u32Add(id, 99); }); - unwind = 260; + unwind = 304; [first !== undefined, second !== undefined] as [boolean, boolean]; const arg6 = first !== undefined; const _227: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(arg6, f); @@ -235,60 +246,60 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args12: rt.Fmt[] = [_227, (f: rt.Formatter) => rt.fmtBool(arg7, f)]; Log.note(log, rt.fmtFormat(["peek ", args12[0], " ", args12[1]])); check(4); - _515 = false; + _578 = false; rt.drop(peek); v5 = []; - unwind = 259; + unwind = 303; const _242: Guard.Guard = guard(20); v5.push(_242); const _247: Guard.Guard = guard(21); v5.push(_247); const _252: Guard.Guard = guard(22); v5.push(_252); - unwind = 260; + unwind = 304; _237 = rt.iterSlice(v5, rt.drop); - unwind = 285; - _514 = true; + unwind = 333; + _577 = true; v6 = []; - unwind = 258; + unwind = 302; const _259: Guard.Guard = guard(23); v6.push(_259); - unwind = 285; + unwind = 333; const _255: Guard.Guard[] = v6; - _514 = false; + _577 = false; const pairs: rt.Iter<[Guard.Guard, Guard.Guard]> = rt.iterZip(_237, rt.iterSlice(_255, rt.drop), false, rt.drop, rt.drop); - unwind = 260; - _514 = false; + unwind = 304; + _577 = false; const arg8 = ([rt.iterCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg8, f)]; Log.note(log, rt.fmtFormat(["zip ", args14[0]])); v7 = []; - unwind = 257; + unwind = 301; const _282: Guard.Guard = guard(24); v7.push(_282); - unwind = 260; + unwind = 304; _277 = rt.iterSlice(v7, rt.drop); - unwind = 283; - _513 = true; + unwind = 331; + _576 = true; v8 = []; - unwind = 256; + unwind = 300; const _289: Guard.Guard = guard(25); v8.push(_289); const _294: Guard.Guard = guard(26); v8.push(_294); - unwind = 283; + unwind = 331; const _285: Guard.Guard[] = v8; - _513 = false; + _576 = false; const _276: rt.Iter = rt.iterChain(_277, rt.iterSlice(_285, rt.drop)); - unwind = 260; - _513 = false; + unwind = 304; + _576 = false; _275 = rt.iterRev(_276); - unwind = 255; + unwind = 299; nth = rt.iterNth(_275, 1, rt.drop); - unwind = 281; - _512 = true; + unwind = 329; + _575 = true; rt.drop(_275); - _512 = false; + _575 = false; const arg9 = ([rt.optionMapOr(nth, 0, (g8: Guard.Guard): rt.u32 => { let unwind3: number = 0; try { @@ -309,21 +320,21 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["nth ", args16[0]])); check(5); v9 = []; - unwind = 254; + unwind = 298; const _318: Guard.Guard = guard(27); v9.push(_318); const _323: Guard.Guard = guard(28); v9.push(_323); const _328: Guard.Guard = guard(29); v9.push(_328); - unwind = 281; + unwind = 329; best = rt.iterMaxByKey(rt.iterSlice(v9, rt.drop), (g9: Guard.Guard): rt.u32 => { return rt.u32Rem(Guard.id(g9), 2); }, rt.drop, rt.drop); - unwind = 279; - _511 = true; + unwind = 327; + _574 = true; v10 = []; - unwind = 253; + unwind = 297; const _339: Guard.Guard | undefined = guard(30); v10.push(_339); v10.push(undefined); @@ -331,15 +342,15 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v10.push(_348); const _354: Guard.Guard | undefined = guard(32); v10.push(_354); - unwind = 279; + unwind = 327; _333 = rt.iterFlatten(rt.iterSlice(v10, rt.drop), (value: Guard.Guard | undefined) => rt.iterOption(value, rt.drop), true); - unwind = 252; + unwind = 296; found = rt.iterFind(_333, (g10: Guard.Guard): boolean => { return Guard.id(g10) === rt.u32Add(id, 31); }, rt.drop); - unwind = 251; + unwind = 295; rt.drop(_333); - _511 = false; + _574 = false; const args17: [rt.u32, boolean] = [rt.optionMapOr(best, 0, (g11: Guard.Guard): rt.u32 => { let unwind4: number = 0; try { @@ -363,14 +374,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["found ", args18[0], " ", args18[1]])); check(6); v11 = []; - unwind = 250; + unwind = 294; const _385: Guard.Guard = guard(33); v11.push(_385); const _390: Guard.Guard = guard(34); v11.push(_390); const _395: Guard.Guard = guard(35); v11.push(_395); - unwind = 251; + unwind = 295; const folded: rt.u32 = rt.iterFold(rt.iterSlice(v11, rt.drop), 0, (n2: rt.u32, g12: Guard.Guard): rt.u32 => { let unwind5: number = 0; try { @@ -391,14 +402,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }, rt.drop); v12 = []; - unwind = 249; + unwind = 293; const _408: Guard.Guard = guard(36); v12.push(_408); const _413: Guard.Guard = guard(37); v12.push(_413); const _418: Guard.Guard = guard(38); v12.push(_418); - unwind = 251; + unwind = 295; const args19: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { @@ -420,33 +431,33 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args20: rt.Fmt[] = [_430, (f: rt.Formatter) => rt.u32Display(arg12, f)]; Log.note(log, rt.fmtFormat(["fold ", args20[0], " ", args20[1]])); v13 = []; - unwind = 248; + unwind = 292; v14 = []; - unwind = 247; + unwind = 291; const _444: Guard.Guard = guard(39); v14.push(_444); const _449: Guard.Guard = guard(40); v14.push(_449); - unwind = 248; + unwind = 292; v13.push(v14); v15 = []; - unwind = 246; + unwind = 290; const _458: Guard.Guard = guard(41); v15.push(_458); - unwind = 248; + unwind = 292; v13.push(v15); v16 = []; - unwind = 245; + unwind = 289; const _467: Guard.Guard = guard(42); v16.push(_467); const _472: Guard.Guard = guard(43); v16.push(_472); - unwind = 248; + unwind = 292; v13.push(v16); - unwind = 251; + unwind = 295; flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); - unwind = 277; - _510 = true; + unwind = 325; + _573 = true; const args21: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { let unwind7: number = 0; try { @@ -483,20 +494,128 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const arg14 = args21[1]; const args22: rt.Fmt[] = [_489, (f: rt.Formatter) => rt.u32Display(arg14, f)]; Log.note(log, rt.fmtFormat(["flat ", args22[0], " ", args22[1]])); - _510 = false; + _573 = false; rt.drop(flat); - unwind = 279; - _510 = false; + const five: (a0: rt.u32) => Guard.Guard[] = (n3: rt.u32): Guard.Guard[] => { + let v17!: Guard.Guard[]; + let unwind9: number = 0; + try { + v17 = []; + unwind9 = 17; + const _613: Guard.Guard = guard(n3); + v17.push(_613); + const _106: Guard.Guard = guard(rt.u32Add(n3, 1)); + v17.push(_106); + const _165: Guard.Guard = guard(rt.u32Add(n3, 2)); + v17.push(_165); + const _22: Guard.Guard = guard(rt.u32Add(n3, 3)); + v17.push(_22); + const _283: Guard.Guard = guard(rt.u32Add(n3, 4)); + v17.push(_283); + return v17; + } catch (e9) { + if (unwind9 === 0) { + throw e9; + } + rt.dropAll(v17); + throw e9; + } + }; + _501 = rt.iterSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); + unwind = 288; + _499 = rt.iterToOption(_501.nthBackItem(3, rt.drop)); + unwind = 287; + const skipped: boolean = _499 !== undefined; + unwind = 288; + rt.drop(_499); + unwind = 325; + rt.drop(_501); + _509 = rt.iterStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); + unwind = 286; + const stepped: rt.u32 = rt.optionMapOr(rt.iterToOption(_509.nthBackItem(1, rt.drop)), 0, (g16: Guard.Guard): rt.u32 => { + let unwind10: number = 0; + try { + unwind10 = 4; + const _015: rt.u32 = Guard.id(g16); + unwind10 = 0; + rt.drop(g16); + return _015; + } catch (e10) { + if (unwind10 === 0) { + throw e10; + } + rt.drop(g16); + throw e10; + } + }); + unwind = 325; + rt.drop(_509); + _518 = rt.iterRev(rt.iterTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); + unwind = 323; + _572 = true; + const _524: Guard.Guard[] = []; + _572 = false; + _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); + unwind = 285; + _572 = false; + const taken: rt.u32 = rt.optionMapOr(rt.iterNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { + let unwind11: number = 0; + try { + unwind11 = 4; + const _016: rt.u32 = Guard.id(g17); + unwind11 = 0; + rt.drop(g17); + return _016; + } catch (e11) { + if (unwind11 === 0) { + throw e11; + } + rt.drop(g17); + throw e11; + } + }); + unwind = 325; + rt.drop(_517); + _529 = rt.iterRev(rt.iterSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); + unwind = 321; + _571 = true; + const _535: Guard.Guard[] = []; + _571 = false; + _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); + unwind = 284; + _571 = false; + const passed: rt.u32 = rt.optionMapOr(rt.iterNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { + let unwind12: number = 0; + try { + unwind12 = 4; + const _017: rt.u32 = Guard.id(g18); + unwind12 = 0; + rt.drop(g18); + return _017; + } catch (e12) { + if (unwind12 === 0) { + throw e12; + } + rt.drop(g18); + throw e12; + } + }); + unwind = 325; + rt.drop(_528); + const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(skipped, f), (f: rt.Formatter) => rt.u32Display(stepped, f), (f: rt.Formatter) => rt.u32Display(taken, f), (f: rt.Formatter) => rt.u32Display(passed, f)]; + Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3]])); + unwind = 327; + _573 = false; rt.drop(found); - unwind = 261; - _511 = false; - _512 = false; + unwind = 305; + _574 = false; + _575 = false; rt.drop(second); - unwind = 287; + unwind = 335; rt.drop(first); unwind = 0; - _515 = false; - _516 = false; + _578 = false; + _579 = false; rt.dropAll(even); } catch (e) { b7: { @@ -514,173 +633,211 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { b19: { b20: { b21: { - if (unwind === 0) { - throw e; - } - if (unwind === 245) { - rt.dropAll(v16); - break b16; - } - if (unwind === 246) { - rt.dropAll(v15); - break b16; - } - if (unwind === 247) { - rt.dropAll(v14); - break b16; - } - if (unwind === 248) { - break b16; - } - if (unwind === 249) { - rt.dropAll(v12); - break b15; - } - if (unwind === 250) { - rt.dropAll(v11); - break b15; - } - if (unwind === 251) { - break b15; - } - if (unwind === 252) { - rt.drop(_333); - break b14; - } - if (unwind === 253) { - rt.dropAll(v10); - break b14; - } - if (unwind === 254) { - rt.dropAll(v9); - break b13; - } - if (unwind === 255) { - rt.drop(_275); - break b12; - } - if (unwind === 256) { - rt.dropAll(v8); - break b17; - } - if (unwind === 257) { - rt.dropAll(v7); - break b12; - } - if (unwind === 258) { - rt.dropAll(v6); - break b18; - } - if (unwind === 259) { - rt.dropAll(v5); - break b12; - } - if (unwind === 260) { - break b12; - } - if (unwind === 261) { - break b11; - } - if (unwind === 262) { - rt.dropAll(v4); - break b9; - } - if (unwind === 263) { - rt.dropAll(v3); - break b8; - } - if (unwind === 264) { - break b8; - } - if (unwind === 265) { - rt.dropAll(v2); - break b7; - } - if (unwind === 266) { - rt.drop(g3); - break b19; - } - if (unwind === 267) { - break b19; - } - if (unwind === 268) { - rt.drop(g2); - break b20; - } - if (unwind === 269) { - break b20; - } - if (unwind === 270) { - rt.drop(_42); - break b21; - } - if (unwind === 271) { - break b21; - } - if (unwind === 272) { - rt.drop(g); - } else if (unwind !== 273) { - if (unwind === 274) { - rt.dropAll(v); - break b7; - } - if (unwind === 277) { - if (!_510) { + b22: { + b23: { + if (unwind === 0) { + throw e; + } + if (unwind === 284) { + rt.drop(_528); + break b16; + } + if (unwind === 285) { + rt.drop(_517); + break b16; + } + if (unwind === 286) { + rt.drop(_509); + break b16; + } + if (unwind === 287) { + rt.drop(_499); + break b17; + } + if (unwind === 288) { + break b17; + } + if (unwind === 289) { + rt.dropAll(v16); + break b18; + } + if (unwind === 290) { + rt.dropAll(v15); + break b18; + } + if (unwind === 291) { + rt.dropAll(v14); + break b18; + } + if (unwind === 292) { + break b18; + } + if (unwind === 293) { + rt.dropAll(v12); break b15; } - rt.drop(flat); - break b15; - } - if (unwind === 279) { - break b14; - } - if (unwind === 281) { - break b13; - } - if (unwind === 283) { - break b17; - } - if (unwind === 285) { - break b18; - } - if (unwind === 287) { - break b10; + if (unwind === 294) { + rt.dropAll(v11); + break b15; + } + if (unwind === 295) { + break b15; + } + if (unwind === 296) { + rt.drop(_333); + break b14; + } + if (unwind === 297) { + rt.dropAll(v10); + break b14; + } + if (unwind === 298) { + rt.dropAll(v9); + break b13; + } + if (unwind === 299) { + rt.drop(_275); + break b12; + } + if (unwind === 300) { + rt.dropAll(v8); + break b19; + } + if (unwind === 301) { + rt.dropAll(v7); + break b12; + } + if (unwind === 302) { + rt.dropAll(v6); + break b20; + } + if (unwind === 303) { + rt.dropAll(v5); + break b12; + } + if (unwind === 304) { + break b12; + } + if (unwind === 305) { + break b11; + } + if (unwind === 306) { + rt.dropAll(v4); + break b9; + } + if (unwind === 307) { + rt.dropAll(v3); + break b8; + } + if (unwind === 308) { + break b8; + } + if (unwind === 309) { + rt.dropAll(v2); + break b7; + } + if (unwind === 310) { + rt.drop(g3); + break b21; + } + if (unwind === 311) { + break b21; + } + if (unwind === 312) { + rt.drop(g2); + break b22; + } + if (unwind === 313) { + break b22; + } + if (unwind === 314) { + rt.drop(_42); + break b23; + } + if (unwind === 315) { + break b23; + } + if (unwind === 316) { + rt.drop(g); + } else if (unwind !== 317) { + if (unwind === 318) { + rt.dropAll(v); + break b7; + } + if (unwind === 321) { + if (!_571) { + break b16; + } + rt.drop(_529); + break b16; + } + if (unwind === 323) { + if (!_572) { + break b16; + } + rt.drop(_518); + break b16; + } + if (unwind === 325) { + break b16; + } + if (unwind === 327) { + break b14; + } + if (unwind === 329) { + break b13; + } + if (unwind === 331) { + break b19; + } + if (unwind === 333) { + break b20; + } + if (unwind === 335) { + break b10; + } + break b9; + } + rt.dropAll(iterS, rt.drop, iterI); + break b7; } - break b9; + rt.drop(_39); + break b7; } - rt.dropAll(iterS, rt.drop, iterI); + rt.drop(iter2); break b7; } - rt.drop(_39); + rt.drop(iter3); break b7; } - rt.drop(iter2); - break b7; + if (!_577) { + break b12; + } + rt.drop(_237); + break b12; } - rt.drop(iter3); - break b7; - } - if (!_514) { + if (!_576) { + break b12; + } + rt.drop(_277); break b12; } - rt.drop(_237); - break b12; + rt.dropAll(v13, drop$Vec_Guard); + break b15; } - if (!_513) { - break b12; - } - rt.drop(_277); - break b12; + rt.drop(_501); + } + if (_573) { + rt.drop(flat); } - rt.dropAll(v13, drop$Vec_Guard); } rt.drop(found); } - if (_511) { + if (_574) { rt.drop(best); } } - if (_512) { + if (_575) { rt.drop(nth); } } @@ -688,11 +845,11 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } rt.drop(first); } - if (_515) { + if (_578) { rt.drop(peek); } } - if (_516) { + if (_579) { rt.drop(rest); } } diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index 3804182c5..b142a4296 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -92,6 +92,25 @@ pub(super) fn looped(log: &Log, id: u32, at: u8) { let back = flat.next_back().map_or(0, |g| g.id()); log.note(format!("flat {front} {back}")); drop(flat); + // What reading past items skips, from either end, of `skip`, `take`, and `step_by`. + let five = |n: u32| list![guard(n), guard(n + 1), guard(n + 2), guard(n + 3), guard(n + 4)]; + let skipped = five(44).into_iter().skip(2).nth_back(3).is_some(); + let stepped = five(49).into_iter().step_by(2).nth_back(1).map_or(0, |g| g.id()); + let taken = five(59) + .into_iter() + .take(3) + .rev() + .chain(Vec::new()) + .nth(1) + .map_or(0, |g| g.id()); + let passed = five(64) + .into_iter() + .skip(2) + .rev() + .chain(Vec::new()) + .nth(2) + .map_or(0, |g| g.id()); + log.note(format!("back {skipped} {stepped} {taken} {passed}")); } /// What `collect` drops: in place of the `Vec` its items come from, what it collected diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index d448e6e4b..d6dd27dbb 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -1185,6 +1185,24 @@ class SkipIter extends Adaptor { return this.len() > 0 ? this.inner.nextBack() : DONE; } + /** std's: past what it doesn't skip, its iterator read from the back through what it does. */ + override nthBackItem(n: number, drop?: Drop): T | Done { + const len = this.len(); + if (n < len) return this.inner.nthBackItem(n, drop); + if (len > 0) { + const item = this.inner.nthBackItem(len - 1, drop); + if (item !== DONE) drop?.(item); + } + return DONE; + } + + /** std's: its iterator advanced from the back in one step, short of what it skips. */ + override advanceBackBy(n: number, drop?: Drop): number { + const min = Math.min(this.len(), n); + this.inner.advanceBackBy(min, drop); + return n - min; + } + /** std's: what it still skips and then `n` more, in one step. */ override nthItem(n: number, drop?: Drop): T | Done { const skip = this.n; @@ -1295,6 +1313,14 @@ class TakeIter extends Adaptor { return n - advanced; } + /** std's: its iterator advanced from the back past the limit and `n` more, in one step. */ + override advanceBackBy(n: number, drop?: Drop): number { + const trim = Math.max(this.inner.len() - this.n, 0); + const advanced = trim + n - this.inner.advanceBackBy(trim + n, drop) - trim; + this.n -= advanced; + return n - advanced; + } + override len(): number { return Math.min(this.inner.len(), this.n); } @@ -1386,9 +1412,18 @@ class StepByIter extends Adaptor { } override nextBack(): T | Done { + return this.inner.nthBackItem(this.backIndex(), this.drop); + } + + /** std's: every step from the back in one. */ + override nthBackItem(n: number, drop?: Drop): T | Done { + return this.inner.nthBackItem(n * (this.step + 1) + this.backIndex(), drop); + } + + /** How far from the back its last item is. */ + private backIndex(): number { const rem = this.inner.len() % (this.step + 1); - const n = this.firstTake ? (rem === 0 ? this.step : rem - 1) : rem; - return this.inner.nthBackItem(n, this.drop); + return this.firstTake ? (rem === 0 ? this.step : rem - 1) : rem; } override len(): number { From 114b9a4c0909efa4a040ace6d02226d8846ecc10 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:07:00 -0700 Subject: [PATCH 06/18] fix(ts): step forward as std's `step_by` does, and saturate its counts `StepBy`'s `nth` drops the first item, then reads every step in one `nth`, so a reversed source drops what it passes front to back, as std's does. Its `nth_back` saturates at wasm32's `usize::MAX`, as std's does, rather than passing on a count past it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 374 ++++++++++++----------- ts/fixtures/task/src/drops/iters.rs | 4 +- ts/runtime/rt/iter.ts | 40 ++- 3 files changed, 244 insertions(+), 174 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 29e69fbfe..2afe9d9ea 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -59,26 +59,27 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { let _518!: rt.Iter; let _528!: rt.Iter; let _529!: rt.Iter; - let _571!: boolean; - let _572!: boolean; - let _573!: boolean; - let _574!: boolean; - let _575!: boolean; - let _576!: boolean; - let _577!: boolean; - let _578!: boolean; - let _579!: boolean; + let _539!: rt.Iter; + let _593!: boolean; + let _594!: boolean; + let _595!: boolean; + let _596!: boolean; + let _597!: boolean; + let _598!: boolean; + let _599!: boolean; + let _600!: boolean; + let _601!: boolean; let unwind: number = 0; try { - _579 = false; - _578 = false; - _577 = false; - _575 = false; - _576 = false; - _574 = false; - _573 = false; - _572 = false; - _571 = false; + _601 = false; + _600 = false; + _599 = false; + _597 = false; + _598 = false; + _596 = false; + _595 = false; + _594 = false; + _593 = false; const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -89,7 +90,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }; v = []; - unwind = 318; + unwind = 333; const _14: Guard.Guard = guard(1); v.push(_14); const _19: Guard.Guard = guard(2); @@ -100,18 +101,18 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { iterS = v; iterI = 0; while (true) { - unwind = 317; + unwind = 332; const _28: Guard.Guard | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; if (_28 === rt.DONE) { break; } - unwind = 316; + unwind = 331; g = _28; if (!(Guard.id(g) === rt.u32Add(id, 2))) { - unwind = 317; + unwind = 332; rt.drop(g); } else { - unwind = 317; + unwind = 332; rt.drop(g); break; } @@ -119,19 +120,19 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 0; rt.dropAll(iterS, rt.drop, iterI); _39 = guard(4); - unwind = 315; + unwind = 330; _42 = guard(5); - unwind = 314; + unwind = 329; const _45: Guard.Guard = guard(6); unwind = 0; iter2 = rt.iterSlice([_39, _42, _45], rt.drop); while (true) { - unwind = 313; + unwind = 328; const _49: Guard.Guard | rt.Done = iter2.next(); if (_49 === rt.DONE) { break; } - unwind = 312; + unwind = 327; g2 = _49; const arg = ([Guard.id(g2)] as [rt.u32])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; @@ -139,30 +140,30 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { if (Guard.id(g2) === rt.u32Add(id, 5)) { check(1); } - unwind = 313; + unwind = 328; rt.drop(g2); } unwind = 0; rt.drop(iter2); iter3 = rt.iterOption(guard(7), rt.drop); while (true) { - unwind = 311; + unwind = 326; const _79: Guard.Guard | rt.Done = iter3.next(); if (_79 === rt.DONE) { break; } - unwind = 310; + unwind = 325; g3 = _79; const arg2 = ([Guard.id(g3)] as [rt.u32])[0]; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; Log.note(log, rt.fmtFormat(["option ", args4[0]])); - unwind = 311; + unwind = 326; rt.drop(g3); } unwind = 0; rt.drop(iter3); v2 = []; - unwind = 309; + unwind = 324; const _102: Guard.Guard = guard(8); v2.push(_102); const _107: Guard.Guard = guard(9); @@ -178,12 +179,12 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } return rt.u32Rem(Guard.id(g4), 2) === 0; }, rt.drop), true, rt.drop, rt.drop); - unwind = 308; + unwind = 323; const arg3 = ([even.length] as [rt.usize])[0]; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; Log.note(log, rt.fmtFormat(["even ", args6[0]])); v3 = []; - unwind = 307; + unwind = 322; const _142: Guard.Guard = guard(12); v3.push(_142); const _147: Guard.Guard = guard(13); @@ -194,10 +195,10 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v3.push(_157); const _162: Guard.Guard = guard(16); v3.push(_162); - unwind = 308; + unwind = 323; rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); - unwind = 337; - _579 = true; + unwind = 352; + _601 = true; const arg4 = ([rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { let unwind2: number = 0; try { @@ -217,28 +218,28 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; Log.note(log, rt.fmtFormat(["next ", args8[0]])); check(3); - _579 = false; + _601 = false; const arg5 = ([rt.iterCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; Log.note(log, rt.fmtFormat(["count ", args10[0]])); v4 = []; - unwind = 306; + unwind = 321; const _199: Guard.Guard = guard(17); v4.push(_199); const _204: Guard.Guard = guard(18); v4.push(_204); - unwind = 337; + unwind = 352; peek = rt.iterPeekable(rt.iterSlice(v4, rt.drop), rt.drop); - unwind = 335; - _578 = true; + unwind = 350; + _600 = true; first = rt.peekableNextIf(peek, (g6: Guard.Guard): boolean => { return Guard.id(g6) === rt.u32Add(id, 17); }); - unwind = 305; + unwind = 320; second = rt.peekableNextIf(peek, (g7: Guard.Guard): boolean => { return Guard.id(g7) === rt.u32Add(id, 99); }); - unwind = 304; + unwind = 319; [first !== undefined, second !== undefined] as [boolean, boolean]; const arg6 = first !== undefined; const _227: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(arg6, f); @@ -246,60 +247,60 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args12: rt.Fmt[] = [_227, (f: rt.Formatter) => rt.fmtBool(arg7, f)]; Log.note(log, rt.fmtFormat(["peek ", args12[0], " ", args12[1]])); check(4); - _578 = false; + _600 = false; rt.drop(peek); v5 = []; - unwind = 303; + unwind = 318; const _242: Guard.Guard = guard(20); v5.push(_242); const _247: Guard.Guard = guard(21); v5.push(_247); const _252: Guard.Guard = guard(22); v5.push(_252); - unwind = 304; + unwind = 319; _237 = rt.iterSlice(v5, rt.drop); - unwind = 333; - _577 = true; + unwind = 348; + _599 = true; v6 = []; - unwind = 302; + unwind = 317; const _259: Guard.Guard = guard(23); v6.push(_259); - unwind = 333; + unwind = 348; const _255: Guard.Guard[] = v6; - _577 = false; + _599 = false; const pairs: rt.Iter<[Guard.Guard, Guard.Guard]> = rt.iterZip(_237, rt.iterSlice(_255, rt.drop), false, rt.drop, rt.drop); - unwind = 304; - _577 = false; + unwind = 319; + _599 = false; const arg8 = ([rt.iterCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg8, f)]; Log.note(log, rt.fmtFormat(["zip ", args14[0]])); v7 = []; - unwind = 301; + unwind = 316; const _282: Guard.Guard = guard(24); v7.push(_282); - unwind = 304; + unwind = 319; _277 = rt.iterSlice(v7, rt.drop); - unwind = 331; - _576 = true; + unwind = 346; + _598 = true; v8 = []; - unwind = 300; + unwind = 315; const _289: Guard.Guard = guard(25); v8.push(_289); const _294: Guard.Guard = guard(26); v8.push(_294); - unwind = 331; + unwind = 346; const _285: Guard.Guard[] = v8; - _576 = false; + _598 = false; const _276: rt.Iter = rt.iterChain(_277, rt.iterSlice(_285, rt.drop)); - unwind = 304; - _576 = false; + unwind = 319; + _598 = false; _275 = rt.iterRev(_276); - unwind = 299; + unwind = 314; nth = rt.iterNth(_275, 1, rt.drop); - unwind = 329; - _575 = true; + unwind = 344; + _597 = true; rt.drop(_275); - _575 = false; + _597 = false; const arg9 = ([rt.optionMapOr(nth, 0, (g8: Guard.Guard): rt.u32 => { let unwind3: number = 0; try { @@ -320,21 +321,21 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["nth ", args16[0]])); check(5); v9 = []; - unwind = 298; + unwind = 313; const _318: Guard.Guard = guard(27); v9.push(_318); const _323: Guard.Guard = guard(28); v9.push(_323); const _328: Guard.Guard = guard(29); v9.push(_328); - unwind = 329; + unwind = 344; best = rt.iterMaxByKey(rt.iterSlice(v9, rt.drop), (g9: Guard.Guard): rt.u32 => { return rt.u32Rem(Guard.id(g9), 2); }, rt.drop, rt.drop); - unwind = 327; - _574 = true; + unwind = 342; + _596 = true; v10 = []; - unwind = 297; + unwind = 312; const _339: Guard.Guard | undefined = guard(30); v10.push(_339); v10.push(undefined); @@ -342,15 +343,15 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v10.push(_348); const _354: Guard.Guard | undefined = guard(32); v10.push(_354); - unwind = 327; + unwind = 342; _333 = rt.iterFlatten(rt.iterSlice(v10, rt.drop), (value: Guard.Guard | undefined) => rt.iterOption(value, rt.drop), true); - unwind = 296; + unwind = 311; found = rt.iterFind(_333, (g10: Guard.Guard): boolean => { return Guard.id(g10) === rt.u32Add(id, 31); }, rt.drop); - unwind = 295; + unwind = 310; rt.drop(_333); - _574 = false; + _596 = false; const args17: [rt.u32, boolean] = [rt.optionMapOr(best, 0, (g11: Guard.Guard): rt.u32 => { let unwind4: number = 0; try { @@ -374,14 +375,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["found ", args18[0], " ", args18[1]])); check(6); v11 = []; - unwind = 294; + unwind = 309; const _385: Guard.Guard = guard(33); v11.push(_385); const _390: Guard.Guard = guard(34); v11.push(_390); const _395: Guard.Guard = guard(35); v11.push(_395); - unwind = 295; + unwind = 310; const folded: rt.u32 = rt.iterFold(rt.iterSlice(v11, rt.drop), 0, (n2: rt.u32, g12: Guard.Guard): rt.u32 => { let unwind5: number = 0; try { @@ -402,14 +403,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }, rt.drop); v12 = []; - unwind = 293; + unwind = 308; const _408: Guard.Guard = guard(36); v12.push(_408); const _413: Guard.Guard = guard(37); v12.push(_413); const _418: Guard.Guard = guard(38); v12.push(_418); - unwind = 295; + unwind = 310; const args19: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { @@ -431,33 +432,33 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args20: rt.Fmt[] = [_430, (f: rt.Formatter) => rt.u32Display(arg12, f)]; Log.note(log, rt.fmtFormat(["fold ", args20[0], " ", args20[1]])); v13 = []; - unwind = 292; + unwind = 307; v14 = []; - unwind = 291; + unwind = 306; const _444: Guard.Guard = guard(39); v14.push(_444); const _449: Guard.Guard = guard(40); v14.push(_449); - unwind = 292; + unwind = 307; v13.push(v14); v15 = []; - unwind = 290; + unwind = 305; const _458: Guard.Guard = guard(41); v15.push(_458); - unwind = 292; + unwind = 307; v13.push(v15); v16 = []; - unwind = 289; + unwind = 304; const _467: Guard.Guard = guard(42); v16.push(_467); const _472: Guard.Guard = guard(43); v16.push(_472); - unwind = 292; + unwind = 307; v13.push(v16); - unwind = 295; + unwind = 310; flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); - unwind = 325; - _573 = true; + unwind = 340; + _595 = true; const args21: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { let unwind7: number = 0; try { @@ -494,7 +495,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const arg14 = args21[1]; const args22: rt.Fmt[] = [_489, (f: rt.Formatter) => rt.u32Display(arg14, f)]; Log.note(log, rt.fmtFormat(["flat ", args22[0], " ", args22[1]])); - _573 = false; + _595 = false; rt.drop(flat); const five: (a0: rt.u32) => Guard.Guard[] = (n3: rt.u32): Guard.Guard[] => { let v17!: Guard.Guard[]; @@ -522,16 +523,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }; _501 = rt.iterSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); - unwind = 288; + unwind = 303; _499 = rt.iterToOption(_501.nthBackItem(3, rt.drop)); - unwind = 287; + unwind = 302; const skipped: boolean = _499 !== undefined; - unwind = 288; + unwind = 303; rt.drop(_499); - unwind = 325; + unwind = 340; rt.drop(_501); _509 = rt.iterStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); - unwind = 286; + unwind = 301; const stepped: rt.u32 = rt.optionMapOr(rt.iterToOption(_509.nthBackItem(1, rt.drop)), 0, (g16: Guard.Guard): rt.u32 => { let unwind10: number = 0; try { @@ -548,16 +549,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e10; } }); - unwind = 325; + unwind = 340; rt.drop(_509); _518 = rt.iterRev(rt.iterTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); - unwind = 323; - _572 = true; + unwind = 338; + _594 = true; const _524: Guard.Guard[] = []; - _572 = false; + _594 = false; _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); - unwind = 285; - _572 = false; + unwind = 300; + _594 = false; const taken: rt.u32 = rt.optionMapOr(rt.iterNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { let unwind11: number = 0; try { @@ -574,16 +575,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e11; } }); - unwind = 325; + unwind = 340; rt.drop(_517); _529 = rt.iterRev(rt.iterSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); - unwind = 321; - _571 = true; + unwind = 336; + _593 = true; const _535: Guard.Guard[] = []; - _571 = false; + _593 = false; _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); - unwind = 284; - _571 = false; + unwind = 299; + _593 = false; const passed: rt.u32 = rt.optionMapOr(rt.iterNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { let unwind12: number = 0; try { @@ -600,22 +601,49 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e12; } }); - unwind = 325; + unwind = 340; rt.drop(_528); - const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(skipped, f), (f: rt.Formatter) => rt.u32Display(stepped, f), (f: rt.Formatter) => rt.u32Display(taken, f), (f: rt.Formatter) => rt.u32Display(passed, f)]; - Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3]])); - unwind = 327; - _573 = false; + _539 = rt.iterStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); + unwind = 298; + const strode: rt.u32 = rt.optionMapOr(rt.iterNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { + let unwind13: number = 0; + try { + unwind13 = 4; + const _018: rt.u32 = Guard.id(g19); + unwind13 = 0; + rt.drop(g19); + return _018; + } catch (e13) { + if (unwind13 === 0) { + throw e13; + } + rt.drop(g19); + throw e13; + } + }); + unwind = 340; + rt.drop(_539); + const args23: [boolean, rt.u32, rt.u32, rt.u32, rt.u32, rt.usize] = [skipped, stepped, taken, passed, strode, rt.iterCount(rt.iterTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop)]; + const _564: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(skipped, f); + const _565: rt.Fmt = (f: rt.Formatter) => rt.u32Display(stepped, f); + const _566: rt.Fmt = (f: rt.Formatter) => rt.u32Display(taken, f); + const _567: rt.Fmt = (f: rt.Formatter) => rt.u32Display(passed, f); + const _568: rt.Fmt = (f: rt.Formatter) => rt.u32Display(strode, f); + const arg15 = args23[5]; + const args24: rt.Fmt[] = [_564, _565, _566, _567, _568, (f: rt.Formatter) => rt.usizeDisplay(arg15, f)]; + Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3], " ", args24[4], " ", args24[5]])); + unwind = 342; + _595 = false; rt.drop(found); - unwind = 305; - _574 = false; - _575 = false; + unwind = 320; + _596 = false; + _597 = false; rt.drop(second); - unwind = 335; + unwind = 350; rt.drop(first); unwind = 0; - _578 = false; - _579 = false; + _600 = false; + _601 = false; rt.dropAll(even); } catch (e) { b7: { @@ -638,162 +666,166 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { if (unwind === 0) { throw e; } - if (unwind === 284) { + if (unwind === 298) { + rt.drop(_539); + break b16; + } + if (unwind === 299) { rt.drop(_528); break b16; } - if (unwind === 285) { + if (unwind === 300) { rt.drop(_517); break b16; } - if (unwind === 286) { + if (unwind === 301) { rt.drop(_509); break b16; } - if (unwind === 287) { + if (unwind === 302) { rt.drop(_499); break b17; } - if (unwind === 288) { + if (unwind === 303) { break b17; } - if (unwind === 289) { + if (unwind === 304) { rt.dropAll(v16); break b18; } - if (unwind === 290) { + if (unwind === 305) { rt.dropAll(v15); break b18; } - if (unwind === 291) { + if (unwind === 306) { rt.dropAll(v14); break b18; } - if (unwind === 292) { + if (unwind === 307) { break b18; } - if (unwind === 293) { + if (unwind === 308) { rt.dropAll(v12); break b15; } - if (unwind === 294) { + if (unwind === 309) { rt.dropAll(v11); break b15; } - if (unwind === 295) { + if (unwind === 310) { break b15; } - if (unwind === 296) { + if (unwind === 311) { rt.drop(_333); break b14; } - if (unwind === 297) { + if (unwind === 312) { rt.dropAll(v10); break b14; } - if (unwind === 298) { + if (unwind === 313) { rt.dropAll(v9); break b13; } - if (unwind === 299) { + if (unwind === 314) { rt.drop(_275); break b12; } - if (unwind === 300) { + if (unwind === 315) { rt.dropAll(v8); break b19; } - if (unwind === 301) { + if (unwind === 316) { rt.dropAll(v7); break b12; } - if (unwind === 302) { + if (unwind === 317) { rt.dropAll(v6); break b20; } - if (unwind === 303) { + if (unwind === 318) { rt.dropAll(v5); break b12; } - if (unwind === 304) { + if (unwind === 319) { break b12; } - if (unwind === 305) { + if (unwind === 320) { break b11; } - if (unwind === 306) { + if (unwind === 321) { rt.dropAll(v4); break b9; } - if (unwind === 307) { + if (unwind === 322) { rt.dropAll(v3); break b8; } - if (unwind === 308) { + if (unwind === 323) { break b8; } - if (unwind === 309) { + if (unwind === 324) { rt.dropAll(v2); break b7; } - if (unwind === 310) { + if (unwind === 325) { rt.drop(g3); break b21; } - if (unwind === 311) { + if (unwind === 326) { break b21; } - if (unwind === 312) { + if (unwind === 327) { rt.drop(g2); break b22; } - if (unwind === 313) { + if (unwind === 328) { break b22; } - if (unwind === 314) { + if (unwind === 329) { rt.drop(_42); break b23; } - if (unwind === 315) { + if (unwind === 330) { break b23; } - if (unwind === 316) { + if (unwind === 331) { rt.drop(g); - } else if (unwind !== 317) { - if (unwind === 318) { + } else if (unwind !== 332) { + if (unwind === 333) { rt.dropAll(v); break b7; } - if (unwind === 321) { - if (!_571) { + if (unwind === 336) { + if (!_593) { break b16; } rt.drop(_529); break b16; } - if (unwind === 323) { - if (!_572) { + if (unwind === 338) { + if (!_594) { break b16; } rt.drop(_518); break b16; } - if (unwind === 325) { + if (unwind === 340) { break b16; } - if (unwind === 327) { + if (unwind === 342) { break b14; } - if (unwind === 329) { + if (unwind === 344) { break b13; } - if (unwind === 331) { + if (unwind === 346) { break b19; } - if (unwind === 333) { + if (unwind === 348) { break b20; } - if (unwind === 335) { + if (unwind === 350) { break b10; } break b9; @@ -810,13 +842,13 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(iter3); break b7; } - if (!_577) { + if (!_599) { break b12; } rt.drop(_237); break b12; } - if (!_576) { + if (!_598) { break b12; } rt.drop(_277); @@ -827,17 +859,17 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } rt.drop(_501); } - if (_573) { + if (_595) { rt.drop(flat); } } rt.drop(found); } - if (_574) { + if (_596) { rt.drop(best); } } - if (_575) { + if (_597) { rt.drop(nth); } } @@ -845,11 +877,11 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } rt.drop(first); } - if (_578) { + if (_600) { rt.drop(peek); } } - if (_579) { + if (_601) { rt.drop(rest); } } diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index b142a4296..8d451a070 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -110,7 +110,9 @@ pub(super) fn looped(log: &Log, id: u32, at: u8) { .chain(Vec::new()) .nth(2) .map_or(0, |g| g.id()); - log.note(format!("back {skipped} {stepped} {taken} {passed}")); + let strode = five(69).into_iter().rev().step_by(2).nth(2).map_or(0, |g| g.id()); + let counted = five(74).into_iter().rev().take(3).count(); + log.note(format!("back {skipped} {stepped} {taken} {passed} {strode} {counted}")); } /// What `collect` drops: in place of the `Vec` its items come from, what it collected diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index d6dd27dbb..b9dd26f73 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -24,6 +24,9 @@ export const DONE: unique symbol = /* @__PURE__ */ Symbol("DONE"); /** The type of `DONE`. */ export type Done = typeof DONE; +/** wasm32's `usize::MAX`, where std's adaptors saturate or split a count. */ +const USIZE_MAX = 0xffffffff; + /** What drops a value. */ type Drop = (value: T) => void; @@ -1415,9 +1418,42 @@ class StepByIter extends Adaptor { return this.inner.nthBackItem(this.backIndex(), this.drop); } - /** std's: every step from the back in one. */ + /** + * std's: the first item, dropped unless it is the one, then every step in one `nth`, as + * many as a `usize` counts at a time. + */ + override nthItem(n: number, drop?: Drop): T | Done { + if (this.firstTake) { + this.firstTake = false; + const first = this.inner.next(); + if (first === DONE || n === 0) return first; + drop?.(first); + n -= 1; + } + let step = this.step + 1; + if (n === USIZE_MAX) { + const item = this.inner.nthItem(step - 1, drop); + if (item === DONE) return DONE; + drop?.(item); + } else { + n += 1; + } + for (;;) { + if (n * step <= USIZE_MAX) return this.inner.nthItem(n * step - 1, drop); + const byN = Math.floor(USIZE_MAX / n) * n; + const byStep = Math.floor(USIZE_MAX / step) * step; + if (byN > byStep) step -= Math.floor(USIZE_MAX / n); + else n -= Math.floor(USIZE_MAX / step); + const item = this.inner.nthItem(Math.max(byN, byStep) - 1, drop); + if (item === DONE) return DONE; + drop?.(item); + } + } + + /** std's: every step from the back in one, saturating at a `usize`'s greatest. */ override nthBackItem(n: number, drop?: Drop): T | Done { - return this.inner.nthBackItem(n * (this.step + 1) + this.backIndex(), drop); + const steps = Math.min(n * (this.step + 1), USIZE_MAX); + return this.inner.nthBackItem(Math.min(steps + this.backIndex(), USIZE_MAX), drop); } /** How far from the back its last item is. */ From 1672244203e1c4f81d9638f1ba18fe3f91acd3d4 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:08:57 -0700 Subject: [PATCH 07/18] test(ts): a step_by count past usize::MAX saturates Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 368 ++++++++++++----------- ts/fixtures/task/src/drops/iters.rs | 6 +- 2 files changed, 190 insertions(+), 184 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 2afe9d9ea..5512cae42 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -60,26 +60,26 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { let _528!: rt.Iter; let _529!: rt.Iter; let _539!: rt.Iter; - let _593!: boolean; - let _594!: boolean; - let _595!: boolean; - let _596!: boolean; - let _597!: boolean; - let _598!: boolean; - let _599!: boolean; - let _600!: boolean; - let _601!: boolean; + let _602!: boolean; + let _603!: boolean; + let _604!: boolean; + let _605!: boolean; + let _606!: boolean; + let _607!: boolean; + let _608!: boolean; + let _609!: boolean; + let _610!: boolean; let unwind: number = 0; try { - _601 = false; - _600 = false; - _599 = false; - _597 = false; - _598 = false; - _596 = false; - _595 = false; - _594 = false; - _593 = false; + _610 = false; + _609 = false; + _608 = false; + _606 = false; + _607 = false; + _605 = false; + _604 = false; + _603 = false; + _602 = false; const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -90,7 +90,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }; v = []; - unwind = 333; + unwind = 337; const _14: Guard.Guard = guard(1); v.push(_14); const _19: Guard.Guard = guard(2); @@ -101,18 +101,18 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { iterS = v; iterI = 0; while (true) { - unwind = 332; + unwind = 336; const _28: Guard.Guard | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; if (_28 === rt.DONE) { break; } - unwind = 331; + unwind = 335; g = _28; if (!(Guard.id(g) === rt.u32Add(id, 2))) { - unwind = 332; + unwind = 336; rt.drop(g); } else { - unwind = 332; + unwind = 336; rt.drop(g); break; } @@ -120,19 +120,19 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 0; rt.dropAll(iterS, rt.drop, iterI); _39 = guard(4); - unwind = 330; + unwind = 334; _42 = guard(5); - unwind = 329; + unwind = 333; const _45: Guard.Guard = guard(6); unwind = 0; iter2 = rt.iterSlice([_39, _42, _45], rt.drop); while (true) { - unwind = 328; + unwind = 332; const _49: Guard.Guard | rt.Done = iter2.next(); if (_49 === rt.DONE) { break; } - unwind = 327; + unwind = 331; g2 = _49; const arg = ([Guard.id(g2)] as [rt.u32])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; @@ -140,30 +140,30 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { if (Guard.id(g2) === rt.u32Add(id, 5)) { check(1); } - unwind = 328; + unwind = 332; rt.drop(g2); } unwind = 0; rt.drop(iter2); iter3 = rt.iterOption(guard(7), rt.drop); while (true) { - unwind = 326; + unwind = 330; const _79: Guard.Guard | rt.Done = iter3.next(); if (_79 === rt.DONE) { break; } - unwind = 325; + unwind = 329; g3 = _79; const arg2 = ([Guard.id(g3)] as [rt.u32])[0]; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; Log.note(log, rt.fmtFormat(["option ", args4[0]])); - unwind = 326; + unwind = 330; rt.drop(g3); } unwind = 0; rt.drop(iter3); v2 = []; - unwind = 324; + unwind = 328; const _102: Guard.Guard = guard(8); v2.push(_102); const _107: Guard.Guard = guard(9); @@ -179,12 +179,12 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } return rt.u32Rem(Guard.id(g4), 2) === 0; }, rt.drop), true, rt.drop, rt.drop); - unwind = 323; + unwind = 327; const arg3 = ([even.length] as [rt.usize])[0]; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg3, f)]; Log.note(log, rt.fmtFormat(["even ", args6[0]])); v3 = []; - unwind = 322; + unwind = 326; const _142: Guard.Guard = guard(12); v3.push(_142); const _147: Guard.Guard = guard(13); @@ -195,10 +195,10 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v3.push(_157); const _162: Guard.Guard = guard(16); v3.push(_162); - unwind = 323; + unwind = 327; rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); - unwind = 352; - _601 = true; + unwind = 356; + _610 = true; const arg4 = ([rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { let unwind2: number = 0; try { @@ -218,28 +218,28 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; Log.note(log, rt.fmtFormat(["next ", args8[0]])); check(3); - _601 = false; + _610 = false; const arg5 = ([rt.iterCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; Log.note(log, rt.fmtFormat(["count ", args10[0]])); v4 = []; - unwind = 321; + unwind = 325; const _199: Guard.Guard = guard(17); v4.push(_199); const _204: Guard.Guard = guard(18); v4.push(_204); - unwind = 352; + unwind = 356; peek = rt.iterPeekable(rt.iterSlice(v4, rt.drop), rt.drop); - unwind = 350; - _600 = true; + unwind = 354; + _609 = true; first = rt.peekableNextIf(peek, (g6: Guard.Guard): boolean => { return Guard.id(g6) === rt.u32Add(id, 17); }); - unwind = 320; + unwind = 324; second = rt.peekableNextIf(peek, (g7: Guard.Guard): boolean => { return Guard.id(g7) === rt.u32Add(id, 99); }); - unwind = 319; + unwind = 323; [first !== undefined, second !== undefined] as [boolean, boolean]; const arg6 = first !== undefined; const _227: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(arg6, f); @@ -247,60 +247,60 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args12: rt.Fmt[] = [_227, (f: rt.Formatter) => rt.fmtBool(arg7, f)]; Log.note(log, rt.fmtFormat(["peek ", args12[0], " ", args12[1]])); check(4); - _600 = false; + _609 = false; rt.drop(peek); v5 = []; - unwind = 318; + unwind = 322; const _242: Guard.Guard = guard(20); v5.push(_242); const _247: Guard.Guard = guard(21); v5.push(_247); const _252: Guard.Guard = guard(22); v5.push(_252); - unwind = 319; + unwind = 323; _237 = rt.iterSlice(v5, rt.drop); - unwind = 348; - _599 = true; + unwind = 352; + _608 = true; v6 = []; - unwind = 317; + unwind = 321; const _259: Guard.Guard = guard(23); v6.push(_259); - unwind = 348; + unwind = 352; const _255: Guard.Guard[] = v6; - _599 = false; + _608 = false; const pairs: rt.Iter<[Guard.Guard, Guard.Guard]> = rt.iterZip(_237, rt.iterSlice(_255, rt.drop), false, rt.drop, rt.drop); - unwind = 319; - _599 = false; + unwind = 323; + _608 = false; const arg8 = ([rt.iterCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg8, f)]; Log.note(log, rt.fmtFormat(["zip ", args14[0]])); v7 = []; - unwind = 316; + unwind = 320; const _282: Guard.Guard = guard(24); v7.push(_282); - unwind = 319; + unwind = 323; _277 = rt.iterSlice(v7, rt.drop); - unwind = 346; - _598 = true; + unwind = 350; + _607 = true; v8 = []; - unwind = 315; + unwind = 319; const _289: Guard.Guard = guard(25); v8.push(_289); const _294: Guard.Guard = guard(26); v8.push(_294); - unwind = 346; + unwind = 350; const _285: Guard.Guard[] = v8; - _598 = false; + _607 = false; const _276: rt.Iter = rt.iterChain(_277, rt.iterSlice(_285, rt.drop)); - unwind = 319; - _598 = false; + unwind = 323; + _607 = false; _275 = rt.iterRev(_276); - unwind = 314; + unwind = 318; nth = rt.iterNth(_275, 1, rt.drop); - unwind = 344; - _597 = true; + unwind = 348; + _606 = true; rt.drop(_275); - _597 = false; + _606 = false; const arg9 = ([rt.optionMapOr(nth, 0, (g8: Guard.Guard): rt.u32 => { let unwind3: number = 0; try { @@ -321,21 +321,21 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["nth ", args16[0]])); check(5); v9 = []; - unwind = 313; + unwind = 317; const _318: Guard.Guard = guard(27); v9.push(_318); const _323: Guard.Guard = guard(28); v9.push(_323); const _328: Guard.Guard = guard(29); v9.push(_328); - unwind = 344; + unwind = 348; best = rt.iterMaxByKey(rt.iterSlice(v9, rt.drop), (g9: Guard.Guard): rt.u32 => { return rt.u32Rem(Guard.id(g9), 2); }, rt.drop, rt.drop); - unwind = 342; - _596 = true; + unwind = 346; + _605 = true; v10 = []; - unwind = 312; + unwind = 316; const _339: Guard.Guard | undefined = guard(30); v10.push(_339); v10.push(undefined); @@ -343,15 +343,15 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { v10.push(_348); const _354: Guard.Guard | undefined = guard(32); v10.push(_354); - unwind = 342; + unwind = 346; _333 = rt.iterFlatten(rt.iterSlice(v10, rt.drop), (value: Guard.Guard | undefined) => rt.iterOption(value, rt.drop), true); - unwind = 311; + unwind = 315; found = rt.iterFind(_333, (g10: Guard.Guard): boolean => { return Guard.id(g10) === rt.u32Add(id, 31); }, rt.drop); - unwind = 310; + unwind = 314; rt.drop(_333); - _596 = false; + _605 = false; const args17: [rt.u32, boolean] = [rt.optionMapOr(best, 0, (g11: Guard.Guard): rt.u32 => { let unwind4: number = 0; try { @@ -375,14 +375,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["found ", args18[0], " ", args18[1]])); check(6); v11 = []; - unwind = 309; + unwind = 313; const _385: Guard.Guard = guard(33); v11.push(_385); const _390: Guard.Guard = guard(34); v11.push(_390); const _395: Guard.Guard = guard(35); v11.push(_395); - unwind = 310; + unwind = 314; const folded: rt.u32 = rt.iterFold(rt.iterSlice(v11, rt.drop), 0, (n2: rt.u32, g12: Guard.Guard): rt.u32 => { let unwind5: number = 0; try { @@ -403,14 +403,14 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }, rt.drop); v12 = []; - unwind = 308; + unwind = 312; const _408: Guard.Guard = guard(36); v12.push(_408); const _413: Guard.Guard = guard(37); v12.push(_413); const _418: Guard.Guard = guard(38); v12.push(_418); - unwind = 310; + unwind = 314; const args19: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { @@ -432,33 +432,33 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const args20: rt.Fmt[] = [_430, (f: rt.Formatter) => rt.u32Display(arg12, f)]; Log.note(log, rt.fmtFormat(["fold ", args20[0], " ", args20[1]])); v13 = []; - unwind = 307; + unwind = 311; v14 = []; - unwind = 306; + unwind = 310; const _444: Guard.Guard = guard(39); v14.push(_444); const _449: Guard.Guard = guard(40); v14.push(_449); - unwind = 307; + unwind = 311; v13.push(v14); v15 = []; - unwind = 305; + unwind = 309; const _458: Guard.Guard = guard(41); v15.push(_458); - unwind = 307; + unwind = 311; v13.push(v15); v16 = []; - unwind = 304; + unwind = 308; const _467: Guard.Guard = guard(42); v16.push(_467); const _472: Guard.Guard = guard(43); v16.push(_472); - unwind = 307; + unwind = 311; v13.push(v16); - unwind = 310; + unwind = 314; flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); - unwind = 340; - _595 = true; + unwind = 344; + _604 = true; const args21: [rt.u32, rt.u32] = [rt.optionMapOr(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { let unwind7: number = 0; try { @@ -495,7 +495,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const arg14 = args21[1]; const args22: rt.Fmt[] = [_489, (f: rt.Formatter) => rt.u32Display(arg14, f)]; Log.note(log, rt.fmtFormat(["flat ", args22[0], " ", args22[1]])); - _595 = false; + _604 = false; rt.drop(flat); const five: (a0: rt.u32) => Guard.Guard[] = (n3: rt.u32): Guard.Guard[] => { let v17!: Guard.Guard[]; @@ -503,8 +503,8 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { try { v17 = []; unwind9 = 17; - const _613: Guard.Guard = guard(n3); - v17.push(_613); + const _614: Guard.Guard = guard(n3); + v17.push(_614); const _106: Guard.Guard = guard(rt.u32Add(n3, 1)); v17.push(_106); const _165: Guard.Guard = guard(rt.u32Add(n3, 2)); @@ -523,16 +523,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } }; _501 = rt.iterSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); - unwind = 303; + unwind = 307; _499 = rt.iterToOption(_501.nthBackItem(3, rt.drop)); - unwind = 302; + unwind = 306; const skipped: boolean = _499 !== undefined; - unwind = 303; + unwind = 307; rt.drop(_499); - unwind = 340; + unwind = 344; rt.drop(_501); _509 = rt.iterStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); - unwind = 301; + unwind = 305; const stepped: rt.u32 = rt.optionMapOr(rt.iterToOption(_509.nthBackItem(1, rt.drop)), 0, (g16: Guard.Guard): rt.u32 => { let unwind10: number = 0; try { @@ -549,16 +549,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e10; } }); - unwind = 340; + unwind = 344; rt.drop(_509); _518 = rt.iterRev(rt.iterTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); - unwind = 338; - _594 = true; + unwind = 342; + _603 = true; const _524: Guard.Guard[] = []; - _594 = false; + _603 = false; _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); - unwind = 300; - _594 = false; + unwind = 304; + _603 = false; const taken: rt.u32 = rt.optionMapOr(rt.iterNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { let unwind11: number = 0; try { @@ -575,16 +575,16 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e11; } }); - unwind = 340; + unwind = 344; rt.drop(_517); _529 = rt.iterRev(rt.iterSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); - unwind = 336; - _593 = true; + unwind = 340; + _602 = true; const _535: Guard.Guard[] = []; - _593 = false; + _602 = false; _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); - unwind = 299; - _593 = false; + unwind = 303; + _602 = false; const passed: rt.u32 = rt.optionMapOr(rt.iterNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { let unwind12: number = 0; try { @@ -601,10 +601,10 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e12; } }); - unwind = 340; + unwind = 344; rt.drop(_528); _539 = rt.iterStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); - unwind = 298; + unwind = 302; const strode: rt.u32 = rt.optionMapOr(rt.iterNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { let unwind13: number = 0; try { @@ -621,29 +621,31 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e13; } }); - unwind = 340; + unwind = 344; rt.drop(_539); - const args23: [boolean, rt.u32, rt.u32, rt.u32, rt.u32, rt.usize] = [skipped, stepped, taken, passed, strode, rt.iterCount(rt.iterTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop)]; - const _564: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(skipped, f); - const _565: rt.Fmt = (f: rt.Formatter) => rt.u32Display(stepped, f); - const _566: rt.Fmt = (f: rt.Formatter) => rt.u32Display(taken, f); - const _567: rt.Fmt = (f: rt.Formatter) => rt.u32Display(passed, f); - const _568: rt.Fmt = (f: rt.Formatter) => rt.u32Display(strode, f); - const arg15 = args23[5]; - const args24: rt.Fmt[] = [_564, _565, _566, _567, _568, (f: rt.Formatter) => rt.usizeDisplay(arg15, f)]; - Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3], " ", args24[4], " ", args24[5]])); - unwind = 342; - _595 = false; + const counted: rt.usize = rt.iterCount(rt.iterTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop); + const args23: [boolean, rt.u32, rt.u32, rt.u32, rt.u32, rt.usize, boolean] = [skipped, stepped, taken, passed, strode, counted, rt.iterToOption(rt.iterStepBy(new rt.Range(0, 10), 4294967295).nthBackItem(4294967295)) === undefined]; + const _571: rt.Fmt = (f: rt.Formatter) => rt.fmtBool(skipped, f); + const _572: rt.Fmt = (f: rt.Formatter) => rt.u32Display(stepped, f); + const _573: rt.Fmt = (f: rt.Formatter) => rt.u32Display(taken, f); + const _574: rt.Fmt = (f: rt.Formatter) => rt.u32Display(passed, f); + const _575: rt.Fmt = (f: rt.Formatter) => rt.u32Display(strode, f); + const _576: rt.Fmt = (f: rt.Formatter) => rt.usizeDisplay(counted, f); + const arg15 = args23[6]; + const args24: rt.Fmt[] = [_571, _572, _573, _574, _575, _576, (f: rt.Formatter) => rt.fmtBool(arg15, f)]; + Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3], " ", args24[4], " ", args24[5], " ", args24[6]])); + unwind = 346; + _604 = false; rt.drop(found); - unwind = 320; - _596 = false; - _597 = false; + unwind = 324; + _605 = false; + _606 = false; rt.drop(second); - unwind = 350; + unwind = 354; rt.drop(first); unwind = 0; - _600 = false; - _601 = false; + _609 = false; + _610 = false; rt.dropAll(even); } catch (e) { b7: { @@ -666,166 +668,166 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { if (unwind === 0) { throw e; } - if (unwind === 298) { + if (unwind === 302) { rt.drop(_539); break b16; } - if (unwind === 299) { + if (unwind === 303) { rt.drop(_528); break b16; } - if (unwind === 300) { + if (unwind === 304) { rt.drop(_517); break b16; } - if (unwind === 301) { + if (unwind === 305) { rt.drop(_509); break b16; } - if (unwind === 302) { + if (unwind === 306) { rt.drop(_499); break b17; } - if (unwind === 303) { + if (unwind === 307) { break b17; } - if (unwind === 304) { + if (unwind === 308) { rt.dropAll(v16); break b18; } - if (unwind === 305) { + if (unwind === 309) { rt.dropAll(v15); break b18; } - if (unwind === 306) { + if (unwind === 310) { rt.dropAll(v14); break b18; } - if (unwind === 307) { + if (unwind === 311) { break b18; } - if (unwind === 308) { + if (unwind === 312) { rt.dropAll(v12); break b15; } - if (unwind === 309) { + if (unwind === 313) { rt.dropAll(v11); break b15; } - if (unwind === 310) { + if (unwind === 314) { break b15; } - if (unwind === 311) { + if (unwind === 315) { rt.drop(_333); break b14; } - if (unwind === 312) { + if (unwind === 316) { rt.dropAll(v10); break b14; } - if (unwind === 313) { + if (unwind === 317) { rt.dropAll(v9); break b13; } - if (unwind === 314) { + if (unwind === 318) { rt.drop(_275); break b12; } - if (unwind === 315) { + if (unwind === 319) { rt.dropAll(v8); break b19; } - if (unwind === 316) { + if (unwind === 320) { rt.dropAll(v7); break b12; } - if (unwind === 317) { + if (unwind === 321) { rt.dropAll(v6); break b20; } - if (unwind === 318) { + if (unwind === 322) { rt.dropAll(v5); break b12; } - if (unwind === 319) { + if (unwind === 323) { break b12; } - if (unwind === 320) { + if (unwind === 324) { break b11; } - if (unwind === 321) { + if (unwind === 325) { rt.dropAll(v4); break b9; } - if (unwind === 322) { + if (unwind === 326) { rt.dropAll(v3); break b8; } - if (unwind === 323) { + if (unwind === 327) { break b8; } - if (unwind === 324) { + if (unwind === 328) { rt.dropAll(v2); break b7; } - if (unwind === 325) { + if (unwind === 329) { rt.drop(g3); break b21; } - if (unwind === 326) { + if (unwind === 330) { break b21; } - if (unwind === 327) { + if (unwind === 331) { rt.drop(g2); break b22; } - if (unwind === 328) { + if (unwind === 332) { break b22; } - if (unwind === 329) { + if (unwind === 333) { rt.drop(_42); break b23; } - if (unwind === 330) { + if (unwind === 334) { break b23; } - if (unwind === 331) { + if (unwind === 335) { rt.drop(g); - } else if (unwind !== 332) { - if (unwind === 333) { + } else if (unwind !== 336) { + if (unwind === 337) { rt.dropAll(v); break b7; } - if (unwind === 336) { - if (!_593) { + if (unwind === 340) { + if (!_602) { break b16; } rt.drop(_529); break b16; } - if (unwind === 338) { - if (!_594) { + if (unwind === 342) { + if (!_603) { break b16; } rt.drop(_518); break b16; } - if (unwind === 340) { + if (unwind === 344) { break b16; } - if (unwind === 342) { + if (unwind === 346) { break b14; } - if (unwind === 344) { + if (unwind === 348) { break b13; } - if (unwind === 346) { + if (unwind === 350) { break b19; } - if (unwind === 348) { + if (unwind === 352) { break b20; } - if (unwind === 350) { + if (unwind === 354) { break b10; } break b9; @@ -842,13 +844,13 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(iter3); break b7; } - if (!_599) { + if (!_608) { break b12; } rt.drop(_237); break b12; } - if (!_598) { + if (!_607) { break b12; } rt.drop(_277); @@ -859,17 +861,17 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } rt.drop(_501); } - if (_595) { + if (_604) { rt.drop(flat); } } rt.drop(found); } - if (_596) { + if (_605) { rt.drop(best); } } - if (_597) { + if (_606) { rt.drop(nth); } } @@ -877,11 +879,11 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { } rt.drop(first); } - if (_600) { + if (_609) { rt.drop(peek); } } - if (_601) { + if (_610) { rt.drop(rest); } } diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index 8d451a070..048d9d3e0 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -112,7 +112,11 @@ pub(super) fn looped(log: &Log, id: u32, at: u8) { .map_or(0, |g| g.id()); let strode = five(69).into_iter().rev().step_by(2).nth(2).map_or(0, |g| g.id()); let counted = five(74).into_iter().rev().take(3).count(); - log.note(format!("back {skipped} {stepped} {taken} {passed} {strode} {counted}")); + // A count past `usize::MAX` saturates. + let far = (0i32..10).step_by(usize::MAX).nth_back(usize::MAX).is_none(); + log.note(format!( + "back {skipped} {stepped} {taken} {passed} {strode} {counted} {far}" + )); } /// What `collect` drops: in place of the `Vec` its items come from, what it collected From e732b4b509ada689c73c897d931350650124986f Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:20:57 -0700 Subject: [PATCH 08/18] fix(ts): a hash iterator that drops nothing reads each entry to count A borrowed one is read again after `by_ref().count()`, so its count must end it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/collections.ts | 251 ++++++++++++----------- ts/fixtures/lang/src/collections.rs | 3 + ts/runtime/rt/collections.ts | 7 +- 3 files changed, 135 insertions(+), 126 deletions(-) diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index e84410d41..56090c5df 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -48,11 +48,11 @@ export function rankByte(r: Rank.Rank): rt.u8 { /** A `HashMap` by each kind of key, through a script of inserts, lookups, and removals. */ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { - let _161!: rt.usize; - let _286!: rt.usize; - let _364!: rt.u8; - let _416!: rt.u8; - const _430: (a0: Nibble.Nibble) => rt.u64 = (n: Nibble.Nibble): rt.u64 => { + let _174!: rt.usize; + let _299!: rt.usize; + let _377!: rt.u8; + let _429!: rt.u8; + const _443: (a0: Nibble.Nibble) => rt.u64 = (n: Nibble.Nibble): rt.u64 => { const h2: rt.Hasher = rt.hasher(); Nibble.hash$Hash_DefaultHasher(n, h2); return rt.hashFinish(h2); @@ -90,20 +90,23 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } rt.byteVecPush(out, rt.hashLen(map) & 0xff); rt.byteVecPush(out, rt.hashLen(map) === 0 ? 1 : 0); + const it: rt.Iter<[rt.u8, rt.u16]> = rt.hashIter(map); + rt.byteVecPush(out, rt.iterCount(it) & 0xff); + rt.byteVecPush(out, rt.iterToOption(it.next()) === undefined ? 1 : 0); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(rt.iterSum(rt.iterMap(rt.hashValues(map), (v5: rt.u16): rt.u16 => { return rt.u16Rem(v5, 256); }), rt.u16Add, 0)))); - const _67: rt.Iter<[rt.u8, rt.u16]> = rt.iterMap(rt.hashIter(map), (_227: [rt.u8, rt.u16]): [rt.u8, rt.u16] => { - return [_227[0], _227[1]] as [rt.u8, rt.u16]; + const _80: rt.Iter<[rt.u8, rt.u16]> = rt.iterMap(rt.hashIter(map), (_231: [rt.u8, rt.u16]): [rt.u8, rt.u16] => { + return [_231[0], _231[1]] as [rt.u8, rt.u16]; }); - const iter2: rt.Iter<[rt.u8, rt.u16]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(rt.cmp) as rt.BTreeMap, _67, true)); + const iter2: rt.Iter<[rt.u8, rt.u16]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(rt.cmp) as rt.BTreeMap, _80, true)); while (true) { - const _73: [rt.u8, rt.u16] | rt.Done = iter2.next(); - if (_73 === rt.DONE) { + const _86: [rt.u8, rt.u16] | rt.Done = iter2.next(); + if (_86 === rt.DONE) { break; } - rt.byteVecPush(out, _73[0]); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(_73[1]))); + rt.byteVecPush(out, _86[0]); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(_86[1]))); } rt.hashClear(map); rt.byteVecPush(out, rt.hashLen(map) & 0xff); @@ -111,36 +114,36 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const map2: rt.HashMap = rt.hashNew(rt.hashing(rt.hashInt, rt.u64Eq)) as rt.HashMap; const iter3: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterSlice(rt.byteSliceView(data))); while (true) { - const _97: [rt.usize, rt.u8] | rt.Done = iter3.next(); - if (_97 === rt.DONE) { + const _110: [rt.usize, rt.u8] | rt.Done = iter3.next(); + if (_110 === rt.DONE) { break; } - const i2: rt.usize = _97[0]; - const b: rt.u8 = _97[1]; + const i2: rt.usize = _110[0]; + const b: rt.u8 = _110[1]; const k2: rt.u64 = wide(rt.u8Rem(b, 12)); - const _105: rt.u8 = rt.u8Rem(rt.u8Div(b, 12), 4); - if (_105 === 0) { + const _118: rt.u8 = rt.u8Rem(rt.u8Div(b, 12), 4); + if (_118 === 0) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashRemove(map2, k2), 238)); - } else if (_105 === 1) { + } else if (_118 === 1) { rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashGet(map2, k2), 221)); } else { rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(map2, k2, i2 & 0xff), 204)); } } - const _123: rt.Iter = rt.hashKeys(map2); - const iter4: rt.Iter = rt.btreeKeys(rt.btreeExtendKeys(rt.btreeNew(rt.cmp) as rt.BTreeSet, _123, true)); + const _136: rt.Iter = rt.hashKeys(map2); + const iter4: rt.Iter = rt.btreeKeys(rt.btreeExtendKeys(rt.btreeNew(rt.cmp) as rt.BTreeSet, _136, true)); while (true) { - const _129: rt.u64 | rt.Done = iter4.next(); - if (_129 === rt.DONE) { + const _142: rt.u64 | rt.Done = iter4.next(); + if (_142 === rt.DONE) { break; } - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(_129))); - rt.byteVecPush(out, rt.hashIndex(map2, _129)); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(_142))); + rt.byteVecPush(out, rt.hashIndex(map2, _142)); } - const _142: rt.u8 | undefined = rt.byteSliceFirst(data); - if (_142 !== undefined) { - const _150: rt.u64 = wide(rt.u8Rem(_142, 13)); - rt.byteVecPush(out, rt.hashIndex(map2, _150)); + const _155: rt.u8 | undefined = rt.byteSliceFirst(data); + if (_155 !== undefined) { + const _163: rt.u64 = wide(rt.u8Rem(_155, 13)); + rt.byteVecPush(out, rt.hashIndex(map2, _163)); } } else if (_4 === 2) { const map3: rt.HashMap = rt.hashNew(rt.hashing(Nibble.hash$Hash_DefaultHasher, Nibble.eq$PartialEq)) as rt.HashMap; @@ -149,107 +152,107 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const tuples: rt.HashMap<[rt.u8, string], rt.u8> = rt.hashNew(rt.hashing(rt.hashTuple([rt.hashInt, rt.hashStr]), rt.eqTuple([rt.same, rt.same]))) as rt.HashMap<[rt.u8, string], rt.u8>; let iterStart: rt.usize = 1; const iterEnd: rt.usize = data.length; - while ((_161 = iterStart++) < iterEnd) { - const i3: rt.usize = _161; - const _169: rt.usize = rt.usizeSub(i3, 1); - rt.idx(data, _169); - const _168: rt.u8 = data.data[data.start + _169]; + while ((_174 = iterStart++) < iterEnd) { + const i3: rt.usize = _174; + const _182: rt.usize = rt.usizeSub(i3, 1); + rt.idx(data, _182); + const _181: rt.u8 = data.data[data.start + _182]; rt.idx(data, i3); - const _167: [rt.u8, rt.u8] = [_168, data.data[data.start + i3]]; - const a: rt.u8 = _168; - const b3: rt.u8 = _167[1]; + const _180: [rt.u8, rt.u8] = [_181, data.data[data.start + i3]]; + const a: rt.u8 = _181; + const b3: rt.u8 = _180[1]; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(map3, { _0: a }, b3), 204)); const pair: Pair.Pair = { a: rt.u8Rem(a, 4), b: rt.u16Rem(b3 as rt.u16, 3) }; const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(pairs, copy$Pair(pair)), Tally.default$Default); t.n = rt.u16Add(t.n, 1); const r: Rank.Rank = rank(a, b3); - const _192: Tally.Tally | undefined = rt.hashGet(ranks, r); - if (_192 !== undefined) { - _192.n = rt.u16Add(_192.n, 1); + const _205: Tally.Tally | undefined = rt.hashGet(ranks, r); + if (_205 !== undefined) { + _205.n = rt.u16Add(_205.n, 1); } else { rt.hashInsert(ranks, copy$Rank(r), { n: i3 & 0xffff }); } - const _203: rt.u8 = rt.u8Rem(a, 3); - const _207: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); - if (!(_207 < 8)) { - rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _207); + const _216: rt.u8 = rt.u8Rem(a, 3); + const _220: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); + if (!(_220 < 8)) { + rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _220); } - const t2: [rt.u8, string] = [_203, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_207]]; + const t2: [rt.u8, string] = [_216, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_220]]; rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashRemove(tuples, t2), 187)); if (rt.u8Rem(a, 2) === 0) { rt.hashInsert(tuples, copy$u8_str(t2), a); } } - const _225: rt.Iter<[rt.u8, rt.u8]> = rt.iterMap(rt.hashIter(map3), (_214: [Nibble.Nibble, rt.u8]): [rt.u8, rt.u8] => { - return [_214[0]._0, _214[1]] as [rt.u8, rt.u8]; + const _238: rt.Iter<[rt.u8, rt.u8]> = rt.iterMap(rt.hashIter(map3), (_212: [Nibble.Nibble, rt.u8]): [rt.u8, rt.u8] => { + return [_212[0]._0, _212[1]] as [rt.u8, rt.u8]; }); - const iter6: rt.Iter<[rt.u8, rt.u8]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(rt.cmp) as rt.BTreeMap, _225, true)); + const iter6: rt.Iter<[rt.u8, rt.u8]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(rt.cmp) as rt.BTreeMap, _238, true)); while (true) { - const _230: [rt.u8, rt.u8] | rt.Done = iter6.next(); - if (_230 === rt.DONE) { + const _243: [rt.u8, rt.u8] | rt.Done = iter6.next(); + if (_243 === rt.DONE) { break; } - const k3: rt.u8 = _230[0]; - const v2: rt.u8 = _230[1]; + const k3: rt.u8 = _243[0]; + const v2: rt.u8 = _243[1]; rt.byteVecPush(out, k3); rt.byteVecPush(out, v2); } const key: Pair.Pair = { a: 9, b: 9 }; const local: Tally.Tally = { n: 7 }; - const _241: Tally.Tally = copy$Tally(local); - rt.hashInsert(pairs, copy$Pair(key), _241); + const _254: Tally.Tally = copy$Tally(local); + rt.hashInsert(pairs, copy$Pair(key), _254); local.n = 8; const before: Tally.Tally = copy$Tally(rt.hashIndex(pairs, key)); - const _246: Tally.Tally | undefined = rt.hashGet(pairs, key); - if (_246 !== undefined) { - _246.n = rt.u16Add(_246.n, 2); + const _259: Tally.Tally | undefined = rt.hashGet(pairs, key); + if (_259 !== undefined) { + _259.n = rt.u16Add(_259.n, 2); } rt.byteVecPush(out, local.n & 0xff); rt.byteVecPush(out, before.n & 0xff); rt.byteVecPush(out, rt.hashIndex(pairs, key).n & 0xff); - const _265: rt.Iter<[Pair.Pair, Tally.Tally]> = rt.hashIter(pairs); - const iter7: rt.Iter<[Pair.Pair, Tally.Tally]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(Pair.cmp$Ord) as rt.BTreeMap, _265, true)); + const _278: rt.Iter<[Pair.Pair, Tally.Tally]> = rt.hashIter(pairs); + const iter7: rt.Iter<[Pair.Pair, Tally.Tally]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(Pair.cmp$Ord) as rt.BTreeMap, _278, true)); while (true) { - const _269: [Pair.Pair, Tally.Tally] | rt.Done = iter7.next(); - if (_269 === rt.DONE) { + const _282: [Pair.Pair, Tally.Tally] | rt.Done = iter7.next(); + if (_282 === rt.DONE) { break; } - const p: Pair.Pair = _269[0]; - const t3: Tally.Tally = _269[1]; + const p: Pair.Pair = _282[0]; + const t3: Tally.Tally = _282[1]; rt.byteVecPush(out, p.a); rt.byteVecPush(out, p.b & 0xff); rt.byteVecPush(out, t3.n & 0xff); } let iterStart2: rt.usize = 1; const iterEnd2: rt.usize = data.length; - while ((_286 = iterStart2++) < iterEnd2) { - const i4: rt.usize = _286; - const _294: rt.usize = rt.usizeSub(i4, 1); - rt.idx(data, _294); - const _293: rt.u8 = data.data[data.start + _294]; + while ((_299 = iterStart2++) < iterEnd2) { + const i4: rt.usize = _299; + const _307: rt.usize = rt.usizeSub(i4, 1); + rt.idx(data, _307); + const _306: rt.u8 = data.data[data.start + _307]; rt.idx(data, i4); - const _292: [rt.u8, rt.u8] = [_293, data.data[data.start + i4]]; - const a2: rt.u8 = _293; - const b4: rt.u8 = _292[1]; - const _305: Rank.Rank = copy$Rank(rank(b4, a2)); - const t4: Tally.Tally = rt.entryOrInsertWith(rt.entryAndModify(rt.entry(ranks, _305), (t9: Tally.Tally): void => { + const _305: [rt.u8, rt.u8] = [_306, data.data[data.start + i4]]; + const a2: rt.u8 = _306; + const b4: rt.u8 = _305[1]; + const _318: Rank.Rank = copy$Rank(rank(b4, a2)); + const t4: Tally.Tally = rt.entryOrInsertWith(rt.entryAndModify(rt.entry(ranks, _318), (t9: Tally.Tally): void => { t9.n = t9.n ^ 3; }), (): Tally.Tally => { return { n: b4 as rt.u16 }; }); t4.n = rt.u16WrappingAdd(t4.n, t4.n); rt.idx(data, i4); - const _313: Rank.Rank = copy$Rank(rank(data.data[data.start + i4], 0)); - const e: rt.Entry = rt.entry(ranks, _313); + const _326: Rank.Rank = copy$Rank(rank(data.data[data.start + i4], 0)); + const e: rt.Entry = rt.entry(ranks, _326); rt.byteVecPush(out, rankByte(rt.entryKey(e))); rt.byteVecPush(out, rt.entryOrInsertWith(e, (k9: Rank.Rank): Tally.Tally => { return { n: rankByte(k9) as rt.u16 }; }).n & 0xff); } const copy: rt.HashMap = rt.hashClone(ranks, copy$Rank, copy$Tally); - const _327: Tally.Tally | undefined = rt.hashGet(copy, { tag: "Low" } as Rank.Rank); - if (_327 !== undefined) { - _327.n = 119; + const _340: Tally.Tally | undefined = rt.hashGet(copy, { tag: "Low" } as Rank.Rank); + if (_340 !== undefined) { + _340.n = 119; } rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(ranks, { tag: "Low" } as Rank.Rank), 255, (t10: Tally.Tally): rt.u8 => { return t10.n & 0xff; @@ -262,24 +265,24 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const t12: Tally.Tally = _218[1]; return rankByte(k10) ^ (t12.n & 0xff); })); - const _348: rt.Iter<[rt.u8, Tally.Tally]> = rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_223: rt.u8): [rt.u8, Tally.Tally] => { - const b8: rt.u8 = _223; + const _361: rt.Iter<[rt.u8, Tally.Tally]> = rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_227: rt.u8): [rt.u8, Tally.Tally] => { + const b8: rt.u8 = _227; return [rt.u8Rem(b8, 8), { n: b8 as rt.u16 }] as [rt.u8, Tally.Tally]; }); - const bytes: rt.HashMap = rt.hashExtend(rt.hashNew() as rt.HashMap, _348); + const bytes: rt.HashMap = rt.hashExtend(rt.hashNew() as rt.HashMap, _361); const copy2: rt.HashMap = rt.hashClone(bytes, undefined, copy$Tally); const iter9: rt.Iter = rt.hashValues(copy2); while (true) { - const _356: Tally.Tally | rt.Done = iter9.next(); - if (_356 === rt.DONE) { + const _369: Tally.Tally | rt.Done = iter9.next(); + if (_369 === rt.DONE) { break; } - _356.n = rt.u16Add(_356.n, 1); + _369.n = rt.u16Add(_369.n, 1); } let iterStart3: rt.u8 = 0; const iterEnd3: rt.u8 = 8; - while ((_364 = iterStart3++) < iterEnd3) { - const k4: rt.u8 = _364; + while ((_377 = iterStart3++) < iterEnd3) { + const k4: rt.u8 = _377; rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(bytes, k4), 255, (t13: Tally.Tally): rt.u8 => { return t13.n & 0xff; })); @@ -298,16 +301,16 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void rt.hashExtend(extended, rt.iterMap(rt.hashIter(bytes), copy$u8_Tally)); const iter12: rt.Iter = rt.hashValues(extended); while (true) { - const _409: Tally.Tally | rt.Done = iter12.next(); - if (_409 === rt.DONE) { + const _422: Tally.Tally | rt.Done = iter12.next(); + if (_422 === rt.DONE) { break; } - _409.n = _409.n ^ 17; + _422.n = _422.n ^ 17; } let iterStart4: rt.u8 = 0; const iterEnd4: rt.u8 = 8; - while ((_416 = iterStart4++) < iterEnd4) { - const k5: rt.u8 = _416; + while ((_429 = iterStart4++) < iterEnd4) { + const k5: rt.u8 = _429; rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(bytes, k5), 255, (t15: Tally.Tally): rt.u8 => { return t15.n & 0xff; })); @@ -316,12 +319,12 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void })); } const first: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); - rt.byteVecPush(out, rt.u64Eq(_430({ _0: first }), _430({ _0: first ^ 240 })) ? 1 : 0); - const _448: [rt.Hasher, Tally.Tally] = [rt.hasher(), { n: first as rt.u16 }]; - const h: rt.Hasher = _448[0]; - const counted: Tally.Tally = copy$Tally(_448[1]); - const _453: rt.Hasher = countedHasher(h, counted); - rt.hashInt(counted.n, _453); + rt.byteVecPush(out, rt.u64Eq(_443({ _0: first }), _443({ _0: first ^ 240 })) ? 1 : 0); + const _461: [rt.Hasher, Tally.Tally] = [rt.hasher(), { n: first as rt.u16 }]; + const h: rt.Hasher = _461[0]; + const counted: Tally.Tally = copy$Tally(_461[1]); + const _466: rt.Hasher = countedHasher(h, counted); + rt.hashInt(counted.n, _466); const want: rt.Hasher = rt.hasher(); rt.hashInt(rt.u16Add(first as rt.u16, 1), want); rt.byteVecPush(out, rt.u64Eq(rt.hashFinish(h), rt.hashFinish(want)) ? 1 : 0); @@ -331,47 +334,47 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } return true; }); - const _473: rt.Iter<[Rank.Rank, rt.u16]> = rt.iterMap(rt.hashIter(ranks), (_224: [Rank.Rank, Tally.Tally]): [Rank.Rank, rt.u16] => { - return [copy$Rank(_224[0]), _224[1].n] as [Rank.Rank, rt.u16]; + const _486: rt.Iter<[Rank.Rank, rt.u16]> = rt.iterMap(rt.hashIter(ranks), (_230: [Rank.Rank, Tally.Tally]): [Rank.Rank, rt.u16] => { + return [copy$Rank(_230[0]), _230[1].n] as [Rank.Rank, rt.u16]; }); - const iter14: rt.Iter<[Rank.Rank, rt.u16]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(Rank.cmp$Ord) as rt.BTreeMap, _473, true)); + const iter14: rt.Iter<[Rank.Rank, rt.u16]> = rt.btreeIter(rt.btreeExtend(rt.btreeNew(Rank.cmp$Ord) as rt.BTreeMap, _486, true)); while (true) { - const _479: [Rank.Rank, rt.u16] | rt.Done = iter14.next(); - if (_479 === rt.DONE) { + const _492: [Rank.Rank, rt.u16] | rt.Done = iter14.next(); + if (_492 === rt.DONE) { break; } - rt.byteVecPush(out, rankByte(_479[0])); - rt.byteVecPush(out, _479[1] & 0xff); + rt.byteVecPush(out, rankByte(_492[0])); + rt.byteVecPush(out, _492[1] & 0xff); } rt.byteVecPush(out, rt.hashLen(tuples) & 0xff); } else { const words: rt.HashMap = rt.hashNew() as rt.HashMap; for (const b6 of rt.byteSliceView(data)) { - const _502: rt.usize = rt.usizeRem(b6 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); - if (!(_502 < 8)) { - rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _502); + const _515: rt.usize = rt.usizeRem(b6 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); + if (!(_515 < 8)) { + rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _515); } - rt.byteVecPush(rt.entryOrInsertWith(rt.entry(words, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_502]), (): rt.ByteVec => { + rt.byteVecPush(rt.entryOrInsertWith(rt.entry(words, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_515]), (): rt.ByteVec => { return new rt.ByteVec(); }), b6); } const lens: rt.BTreeMap = rt.btreeNew(rt.cmpStr) as rt.BTreeMap; const iter16: rt.Iter<[string, rt.ByteVec]> = rt.hashIter(words); while (true) { - const _517: [string, rt.ByteVec] | rt.Done = iter16.next(); - if (_517 === rt.DONE) { + const _530: [string, rt.ByteVec] | rt.Done = iter16.next(); + if (_530 === rt.DONE) { break; } - rt.btreeInsert(lens, _517[0], _517[1].length); + rt.btreeInsert(lens, _530[0], _530[1].length); } const iter17: rt.Iter<[string, rt.usize]> = rt.btreeIter(lens); while (true) { - const _529: [string, rt.usize] | rt.Done = iter17.next(); - if (_529 === rt.DONE) { + const _542: [string, rt.usize] | rt.Done = iter17.next(); + if (_542 === rt.DONE) { break; } - rt.byteVecExtendFromSlice(out, rt.stringAsBytes(_529[0])); - rt.byteVecPush(out, _529[1] & 0xff); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(_542[0])); + rt.byteVecPush(out, _542[1] & 0xff); } rt.byteVecPush(out, rt.iterSum(rt.iterMap(rt.hashDrain(words), (_2: [string, rt.ByteVec]): rt.usize => { return _2[1].length; @@ -380,19 +383,19 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const clashes: rt.HashMap = rt.hashNew(rt.hashing(Clash.hash$Hash_DefaultHasher, Clash.eq$PartialEq)) as rt.HashMap; const iter18: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(rt.iterSlice(rt.byteSliceView(data))); while (true) { - const _555: [rt.usize, rt.u8] | rt.Done = iter18.next(); - if (_555 === rt.DONE) { + const _568: [rt.usize, rt.u8] | rt.Done = iter18.next(); + if (_568 === rt.DONE) { break; } - const i5: rt.usize = _555[0]; - const b7: rt.u8 = _555[1]; + const i5: rt.usize = _568[0]; + const b7: rt.u8 = _568[1]; const k6: Clash.Clash = { _0: rt.u8Rem(b7, 8) }; - const _563: rt.u8 = rt.u8Rem(rt.u8Div(b7, 8), 4); - if (_563 === 0) { + const _576: rt.u8 = rt.u8Rem(rt.u8Div(b7, 8), 4); + if (_576 === 0) { rt.byteVecPush(out, rt.optionMapOr(rt.hashRemove(clashes, k6), 238, (t7: Tally.Tally): rt.u8 => { return t7.n & 0xff; })); - } else if (_563 === 1) { + } else if (_576 === 1) { rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(clashes, k6), 221, (t6: Tally.Tally): rt.u8 => { return t6.n & 0xff; })); @@ -408,10 +411,10 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } return true; }); - const _583: rt.Iter = rt.iterMap(rt.hashKeys(clashes), (k8: Clash.Clash): rt.u8 => { + const _596: rt.Iter = rt.iterMap(rt.hashKeys(clashes), (k8: Clash.Clash): rt.u8 => { return k8._0; }); - rt.iterExtendBytes(out, rt.btreeKeys(rt.btreeExtendKeys(rt.btreeNew(rt.cmp) as rt.BTreeSet, _583, true))); + rt.iterExtendBytes(out, rt.btreeKeys(rt.btreeExtendKeys(rt.btreeNew(rt.cmp) as rt.BTreeSet, _596, true))); const copy3: rt.HashMap = rt.hashClone(clashes, copy$Clash, copy$Tally); rt.byteVecPush(out, rt.hashLen(copy3) & 0xff); rt.byteVecPush(out, rt.hashContains(copy3, { _0: 1 }) ? 1 : 0); diff --git a/ts/fixtures/lang/src/collections.rs b/ts/fixtures/lang/src/collections.rs index f083b1e58..27721da28 100644 --- a/ts/fixtures/lang/src/collections.rs +++ b/ts/fixtures/lang/src/collections.rs @@ -154,6 +154,9 @@ pub fn hash_maps(kind: u8, data: &[u8], out: &mut Vec) { } out.push(map.len() as u8); out.push(map.is_empty() as u8); + let mut it = map.iter(); + out.push(it.by_ref().count() as u8); + out.push(it.next().is_none() as u8); let total: u16 = map.values().map(|v| v % 256).sum(); out.extend_from_slice(&total.to_be_bytes()); let sorted: BTreeMap = map.iter().map(|(k, v)| (*k, *v)).collect(); diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index b715fda2a..566779f1d 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -617,9 +617,12 @@ class HashIter extends Iter { return this.left; } - /** std's `into_iter`'s: its length, and then each entry drops with it. */ + /** + * std's `into_iter`'s: its length, and then each entry drops with it. One that drops + * nothing reads each entry, as it may be borrowed and read again after. + */ override countItems(drop?: (item: T) => void): number { - if (this.drain) return super.countItems(drop); + if (this.drain || (this.k === undefined && this.v === undefined)) return super.countItems(drop); const n = this.left; this[Symbol.dispose](); return n; From 9f7a821bca92915bc8c41729a731eb4f0b25f655 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:26:05 -0700 Subject: [PATCH 09/18] fix(ts): refuse a closure that drops, passed to a map that may drop it `Option::map` drops its closure on `None`, and `Result`'s `map`, `map_err`, and `and_then` on the variant they skip, which an arrow function can't. They now list the closure among what they discard, so one that owns a value that drops is refused where it was leaked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 9 +++++---- ts/fixtures/reject/census.md | 20 +++++++++++--------- ts/fixtures/reject/expected.txt | 2 ++ ts/fixtures/reject/src/lib.rs | 15 +++++++++++++++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/library.rs | 7 +++++-- 6 files changed, 39 insertions(+), 15 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 46f26a599..00fb28c76 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -23,10 +23,11 @@ and `drops/iters.rs` check these against native Rust, natively unwinding too. What still fails translation, by the census at the pinned moq revision (moq-net's, then kio's): -- A closure that owns a value that drops, dropped without a call that takes it (8, 0). - An arrow function has no `[Symbol.dispose]`; one that owns droppable captures needs - one, and so do the adaptors that hold it (`map`'s, `filter`'s), which drop it after - their iterator, as std's fields do. +- A closure that owns a value that drops, dropped without a call that takes it (17, 0), + as `Option::map` drops it on `None` and `Result::map` on an error. An arrow function + has no `[Symbol.dispose]`; one that owns droppable captures needs one, and so do the + adaptors that hold it (`map`'s, `filter`'s), which drop it after their iterator, as + std's fields do. Refused with none in the census, each where std's order is one JS's can't follow yet: `into_keys` and `into_values` of a hash map whose other half drops (`fold` drops it diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 61ccf63a0..69689eb6a 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 74 -- Function instances: 61 +- Refusals: 76 +- Function instances: 62 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -14,6 +14,7 @@ | 6 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:15:13 | | 4 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:107:2 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:6:14 | +| 3 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:50:1 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:127:20 | | 2 | a field of `_` | fixtures/reject/src/lib.rs:289:7 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:186:1 | @@ -44,7 +45,6 @@ | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:74:2 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:299:52 | -| 1 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:50:1 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:299:52 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:87:3 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:82:3 | @@ -212,6 +212,14 @@ The type or module each refused type or path belongs to.
+
dropping a closure that owns a value that drops, which is not supported yet (3) + +- fixtures/reject/src/lib.rs:50:1: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:390:12: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:394:12: dropping a closure that owns a value that drops, which is not supported yet + +
+
`_` is not supported: it would be pending two ways with one value (2) - fixtures/reject/src/lib.rs:127:20: `Poll>>` is not supported: it would be pending two ways with one value @@ -397,12 +405,6 @@ The type or module each refused type or path belongs to.
-
dropping a closure that owns a value that drops, which is not supported yet (1) - -- fixtures/reject/src/lib.rs:50:1: dropping a closure that owns a value that drops, which is not supported yet - -
-
hashing `_` as a key, which is not supported yet (1) - fixtures/reject/src/lib.rs:299:52: hashing `std::vec::Vec` as a key, which is not supported yet diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index f0282352f..ed7eef34f 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -64,6 +64,8 @@ a coercion to `std::sync::Arc<[u8]>` at fixtures/reject/src/lib.rs:372:2 `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:376:15 replacing the value behind a reference to `std::string::String` at fixtures/reject/src/lib.rs:377:4 unsupported call to `core::str::::split::<[char; 2]>` at fixtures/reject/src/lib.rs:383:4 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:390:12 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:394:12 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:166:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:186:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:220:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 7cdc5b3e8..b1a9c40f9 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -382,3 +382,18 @@ pub fn pushed(s: &mut String) { pub fn split_chars(s: &str) -> usize { s.split(['a', 'b']).count() } + +/// `Option::map` drops its closure on `None`, as `Result::map_err` does on `Ok`, and with +/// it what it captured, which lives in an arrow function. +pub fn discarded_closure(a: Option, b: Result) -> u8 { + let (m, n) = (Noisy(1), Noisy(2)); + let a = a.map(move |x| { + drop(m); + x + }); + let b = b.map_err(move |e| { + drop(n); + e + }); + a.unwrap_or(0) + b.unwrap_or(0) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 86d1f0f94..5c35f06d3 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -46,6 +46,7 @@ roots = [ "shared", "pushed", "split_chars", + "discarded_closure", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 74279f234..6dcb23832 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -380,8 +380,7 @@ pub struct Call<'tcx> { /// any other mapping, which is refused an operand that drops. Iterators refuse their own. fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { Some(match (owner, name) { - ("Option", "map" | "unwrap" | "expect") - | ("Result", "map" | "map_err" | "and_then") + ("Option", "unwrap" | "expect") | ("Vec", "push") | ("Box", "new") | ("mem", "replace" | "take" | "swap") @@ -393,6 +392,10 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { ("Option", "ok_or") => &[1], ("Option", "unwrap_or") => &[0], ("Option", "map_or") => &[1, 2], + // `Option::map::` drops its closure on `None`, and `Result`'s + // `map::` and `and_then::` on an error, as `map_err::` on a value. + ("Option", "map") => &[2], + ("Result", "map" | "map_err" | "and_then") => &[3], // `Result::ok` drops an error, `err` a value, and `unwrap_or` its fallback or // the error. ("Result", "ok") => &[1], From 1b072d4878a57005f5f47decd600dff4e3df60a1 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:31:44 -0700 Subject: [PATCH 10/18] fix(ts): read an iterator borrowed by `&mut` through its borrow A consumer of a borrow took the iterator's by-value overrides, so `it.by_ref().count()` of a `Chain` ended both halves where std's reads on. Every `&mut` iterator is now `iterBorrow`'s, not only one that drops, which also covers the borrowed hash iterator's count that e732b4b special-cased. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/collections.ts | 2 +- ts/fixtures/lang/expected/iters.ts | 31 +++++++++++++++++------- ts/fixtures/lang/src/iters.rs | 8 ++++++ ts/runtime/rt/collections.ts | 7 ++---- ts/src/lower/iter.rs | 5 ++-- 5 files changed, 36 insertions(+), 17 deletions(-) diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index 56090c5df..d7a515aca 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -91,7 +91,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void rt.byteVecPush(out, rt.hashLen(map) & 0xff); rt.byteVecPush(out, rt.hashLen(map) === 0 ? 1 : 0); const it: rt.Iter<[rt.u8, rt.u16]> = rt.hashIter(map); - rt.byteVecPush(out, rt.iterCount(it) & 0xff); + rt.byteVecPush(out, rt.iterCount(rt.iterBorrow(it)) & 0xff); rt.byteVecPush(out, rt.iterToOption(it.next()) === undefined ? 1 : 0); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(rt.iterSum(rt.iterMap(rt.hashValues(map), (v5: rt.u16): rt.u16 => { return rt.u16Rem(v5, 256); diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index f27a4f825..7774ab669 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -105,7 +105,7 @@ export function adaptors(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } if (_4 === 6) { const it2: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); - rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.iterToByteVec(rt.iterTake(it2, 2)))); + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.iterToByteVec(rt.iterTake(rt.iterBorrow(it2), 2)))); rt.byteVecPush(out, it2.len() & 0xff); const _152: rt.u8 | undefined = rt.iterToOption(it2.nextBack()); if (_152 === undefined) { @@ -251,9 +251,13 @@ export function consumers(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterLast(rt.iterSlice(rt.byteSliceView(data))), 221)); rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterSlice(rt.byteSliceView(data)), 3), 204)); const it: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(rt.iterTake(it, rt.usizeRem(data.length, 3)).nthBackItem(1)), 187)); + const _148: rt.Iter = it; + const _150: rt.usize = rt.usizeRem(data.length, 3); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(rt.iterTake(rt.iterBorrow(_148), _150).nthBackItem(1)), 187)); rt.byteVecPush(out, it.len() & 0xff); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterTake(it, rt.usizeRem(data.length, 5)), 2), 187)); + const _163: rt.Iter = it; + const _165: rt.usize = rt.usizeRem(data.length, 5); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterTake(rt.iterBorrow(_163), _165), 2), 187)); rt.byteVecPush(out, it.len() & 0xff); } else if (_5 === 3) { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.iterSum(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_214: rt.u8): rt.u64 => { @@ -345,7 +349,7 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.rangeInclusiveEnd(low)); rt.byteVecPush(out, rt.rangeInclusiveContains(low, rt.u8Div(b, 2)) ? 1 : 0); const reversed: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterRev(reversed), a as rt.usize), 238)); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterRev(rt.iterBorrow(reversed)), a as rt.usize), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(reversed)); rt.byteVecPush(out, rt.rangeInclusiveContains(reversed, a) ? 1 : 0); const counted: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(new rt.RangeInclusive(a, b, rt.u8Step)); @@ -358,13 +362,13 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { return _2[0] & 0xff; })); const stepped: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); - rt.byteVecPush(out, rt.iterCount(rt.iterStepBy(stepped, 3)) & 0xff); + rt.byteVecPush(out, rt.iterCount(rt.iterStepBy(rt.iterBorrow(stepped), 3)) & 0xff); rt.byteVecPush(out, rt.rangeInclusiveStart(stepped)); rt.iterExtendBytes(out, rt.iterMap(rt.iterRev(new rt.RangeInclusive((a << 24) >> 24, (b << 24) >> 24, rt.i8Step)), (i5: rt.i8): rt.u8 => { return i5 & 0xff; })); const wide: rt.Range = new rt.Range(a as rt.u64, rt.u64Mul(b as rt.u64, 3), rt.u64Step); - rt.byteVecPush(out, rt.iterCount(rt.iterFilter(rt.iterMap(wide, (n2: rt.u64): rt.u64 => { + rt.byteVecPush(out, rt.iterCount(rt.iterFilter(rt.iterMap(rt.iterBorrow(wide), (n2: rt.u64): rt.u64 => { return rt.u64Rem(n2, 5); }), (_23: rt.u64): boolean => { return _23 === 0; @@ -497,13 +501,22 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { n = rt.u8Add(n, 1); return rt.thenSome(n < 4, n); })))); + let k: rt.u8 = 0; + rt.iterEmpty(); + const _70: rt.Iter = rt.iterFromFn((): rt.u8 | undefined => { + k = rt.u8Add(k, 1); + return rt.thenSome(k !== 2, k); + }); + const gappy: rt.Iter = rt.iterChain(rt.iterEmpty(), _70); + rt.byteVecPush(out, rt.iterCount(rt.iterBorrow(gappy)) & 0xff); + rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(gappy.next()), 238)); const iter3: Gaps.Gaps = { data, at: 0 }; while (true) { - const _70: rt.u8 | undefined | rt.Done = Gaps.next$Iterator(iter3); - if (_70 === rt.DONE) { + const _85: rt.u8 | undefined | rt.Done = Gaps.next$Iterator(iter3); + if (_85 === rt.DONE) { break; } - rt.byteVecPush(out, rt.optionMapOr(_70, 170, (b6: rt.u8): rt.u8 => { + rt.byteVecPush(out, rt.optionMapOr(_85, 170, (b6: rt.u8): rt.u8 => { return b6; })); } diff --git a/ts/fixtures/lang/src/iters.rs b/ts/fixtures/lang/src/iters.rs index d63ef607d..da16845c0 100644 --- a/ts/fixtures/lang/src/iters.rs +++ b/ts/fixtures/lang/src/iters.rs @@ -397,6 +397,14 @@ pub fn options(data: &[u8], out: &mut Vec) { }) .collect(); out.extend_from_slice(&counted); + // Counted through a borrow, which leaves a `Chain` to read on past a gap. + let mut k = 0u8; + let mut gappy = std::iter::empty().chain(std::iter::from_fn(|| { + k += 1; + (k != 2).then_some(k) + })); + out.push(gappy.by_ref().count() as u8); + out.push(gappy.next().unwrap_or(0xee)); // The crate's own iterator, whose items are options. let gaps = Gaps { data, at: 0 }; for gap in gaps { diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index 566779f1d..b715fda2a 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -617,12 +617,9 @@ class HashIter extends Iter { return this.left; } - /** - * std's `into_iter`'s: its length, and then each entry drops with it. One that drops - * nothing reads each entry, as it may be borrowed and read again after. - */ + /** std's `into_iter`'s: its length, and then each entry drops with it. */ override countItems(drop?: (item: T) => void): number { - if (this.drain || (this.k === undefined && this.v === undefined)) return super.countItems(drop); + if (this.drain) return super.countItems(drop); const n = this.left; this[Symbol.dispose](); return n; diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index d508e9941..4f2174490 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -134,8 +134,9 @@ pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, sp Expr::rt("iterFrom", args) } // One borrowed by `&mut`, which std's adaptors may drop once it ends, but which - // is its owner's to drop. - None if !owned && b.t.drops(ty.peel_refs()) => Expr::rt("iterBorrow", vec![value]), + // is its owner's to drop, and which a consumer reads on through the borrow + // rather than by its by-value overrides, as `Chain::count` ends both halves. + None if !owned => Expr::rt("iterBorrow", vec![value]), None => value, }); } From 8fb077ea153b0800437c306428628bdaca7f3ced Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:25:25 -0700 Subject: [PATCH 11/18] feat(ts): drop what closures own A closure that owns a value that drops carries [Symbol.dispose], which drops its captures in order, the rest still dropping after one panics. An FnOnce body that drops its closure whole drops each capture. One that Fn or FnMut call drops after a call through FnOnce, as rustc's shim does. Option::map, map_or, and Result's map, map_err, and_then, and inspect_err drop the closure they discard. A closure that owns a value that drops, given to any other std function that calls it, is refused rather than leaked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 24 +- ts/README.md | 7 +- ts/fixtures/reject/census.md | 37 +- ts/fixtures/reject/expected.txt | 9 +- ts/fixtures/reject/src/lib.rs | 30 +- ts/fixtures/reject/ts.toml | 2 +- ts/fixtures/task/expected/drops.ts | 191 +-- .../task/expected/drops/closures.Holder.ts | 31 + ts/fixtures/task/expected/drops/closures.ts | 1330 +++++++++++++++++ ts/fixtures/task/expected/model.ts | 4 +- ts/fixtures/task/src/drops.rs | 10 +- ts/fixtures/task/src/drops/closures.rs | 210 +++ ts/runtime/rt.ts | 41 +- ts/runtime/rt/task.ts | 24 + ts/src/lower/drop.rs | 31 +- ts/src/lower/library.rs | 88 +- ts/src/lower/mir/call.rs | 9 + ts/src/lower/mir/mod.rs | 19 +- ts/src/lower/mir/rvalue.rs | 14 +- ts/tests/task.ts | 2 +- 20 files changed, 1933 insertions(+), 180 deletions(-) create mode 100644 ts/fixtures/task/expected/drops/closures.Holder.ts create mode 100644 ts/fixtures/task/expected/drops/closures.ts create mode 100644 ts/fixtures/task/src/drops/closures.rs diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 00fb28c76..032a46f87 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -17,19 +17,17 @@ blocks of `-C panic=unwind` MIR, which a function runs from a `catch`. A value w `drop_in_place` shim. A runtime function that may drop what std's would (a collection's `clear`, `unwrap_or`'s fallback, an adaptor's rejects) takes a dropper for each such type after its own arguments (`drop_fn` and `droppers` in `drop.rs`), and a consumer -that takes an iterator by value takes `rt.drop` for it. The task fixture's `drops.rs` -and `drops/iters.rs` check these against native Rust, natively unwinding too. - -What still fails translation, by the census at the pinned moq revision (moq-net's, then -kio's): - -- A closure that owns a value that drops, dropped without a call that takes it (17, 0), - as `Option::map` drops it on `None` and `Result::map` on an error. An arrow function - has no `[Symbol.dispose]`; one that owns droppable captures needs one, and so do the - adaptors that hold it (`map`'s, `filter`'s), which drop it after their iterator, as - std's fields do. - -Refused with none in the census, each where std's order is one JS's can't follow yet: +that takes an iterator by value takes `rt.drop` for it. A closure that owns a value that +drops carries `[Symbol.dispose]` (`rt.closure`), and one that `Fn` or `FnMut` call drops +after a call through `FnOnce` (`rt.callOnce`, and `rt.once` for std's). The task +fixture's `drops.rs`, `drops/iters.rs`, and `drops/closures.rs` check these against +native Rust, natively unwinding too. + +Nothing that drops fails translation in the census at the pinned moq revision. Refused +with none in the census, each where std's order is one JS's can't follow yet: +a closure that owns a value that drops, given to std's iterators or a collection's +methods, which hold or call it (an adaptor drops it after its iterator, as std's fields +do, and each consumer where its `fold` path does); `into_keys` and `into_values` of a hash map whose other half drops (`fold` drops it after the half it yields, `next` before); `zip` of two `TrustedRandomAccess` iterators of items that drop; a `flatten` whose inner iterator holds items once ended, or that a diff --git a/ts/README.md b/ts/README.md index 7e942a963..87f9c628f 100644 --- a/ts/README.md +++ b/ts/README.md @@ -72,7 +72,7 @@ in `rt/str.ts`, collections in `rt/collections.ts`, and ownership and async in | `a..b`, `a..=b` | `rt.Range`, `rt.RangeInclusive`, which are iterators too | | `HashMap`, `HashSet`, `BTreeMap`, `BTreeSet`, `VecDeque` | `rt.HashMap` and so on, each a plain object whose functions are the runtime's: `rt.hashGet(map, key)` | | `Ordering`, `DefaultHasher` | `rt.Ordering`, which is `-1`, `0`, or `1`; `rt.Hasher` | -| closure | an arrow function | +| closure | an arrow function, with `[Symbol.dispose]` if it owns a value that drops | | constant | its value, inlined as Rust inlines it | | a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | | a type's function | a function of the type's module, taking `self` first: `Decoder.slice(dec, 4)` after `import * as Decoder` | @@ -318,8 +318,9 @@ bind to hand-written TS through config ([model](/quest/m2/ts-model.md)). ## Not yet These fail translation: floats, statics, async blocks that borrow a number -mutably and async closures, values that drop in a closure dropped without a call that -takes it or in an iterator ([Drop](/quest/m2/ts-drop.md)), a collection holding a type that can be +mutably and async closures, a closure that owns a value that drops given to std's +iterators or collections, and values that drop in some iterators +([Drop](/quest/m2/ts-drop.md)), a collection holding a type that can be `undefined`, as `()` and `Option` can, a collection's `capacity`, looking up a key by another type it borrows as through the crate's own `Borrow`, a `&mut` to a value a map holds that JS copies kept other than to read and write it, `Hasher::write` of bytes, the adaptors diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 69689eb6a..44083d0e8 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 76 -- Function instances: 62 +- Refusals: 77 +- Function instances: 63 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -14,7 +14,7 @@ | 6 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:15:13 | | 4 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:107:2 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:6:14 | -| 3 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:50:1 | +| 3 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:49:11 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:127:20 | | 2 | a field of `_` | fixtures/reject/src/lib.rs:289:7 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:186:1 | @@ -45,6 +45,7 @@ | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:74:2 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:299:52 | +| 1 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:49:18 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:299:52 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:87:3 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:82:3 | @@ -59,20 +60,22 @@ The type or module each refused type or path belongs to. | 6 | `Option` | fixtures/reject/src/lib.rs:27:15 | | 6 | `f64` | fixtures/reject/src/lib.rs:6:14 | | 6 | `u8` | fixtures/reject/src/lib.rs:64:10 | +| 4 | `Iterator` | fixtures/reject/src/lib.rs:49:11 | | 4 | `std::string::String` | fixtures/reject/src/lib.rs:94:16 | | 4 | `u32` | fixtures/reject/src/lib.rs:15:13 | | 3 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:55:13 | +| 3 | `std::iter::Map` | fixtures/reject/src/lib.rs:49:18 | | 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:123:2 | -| 2 | `Iterator` | fixtures/reject/src/lib.rs:166:2 | +| 3 | `{closure}` | fixtures/reject/src/lib.rs:49:11 | | 2 | `Meters` | fixtures/reject/src/lib.rs:107:2 | | 2 | `Poll` | fixtures/reject/src/lib.rs:127:20 | -| 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:172:23 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:207:8 | | 2 | `std::option::Option` | fixtures/reject/src/lib.rs:294:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:143:2 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:32:4 | | 2 | `std::vec::Vec` | fixtures/reject/src/lib.rs:299:52 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:186:1 | +| 1 | `Entry` | fixtures/reject/src/lib.rs:393:13 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:240:1 | | 1 | `HashMap` | fixtures/reject/src/lib.rs:317:6 | | 1 | `Hasher` | fixtures/reject/src/lib.rs:325:9 | @@ -84,7 +87,7 @@ The type or module each refused type or path belongs to. | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:199:51 | | 1 | `std::iter::Flatten` | fixtures/reject/src/lib.rs:248:26 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:193:14 | -| 1 | `std::mem` | fixtures/reject/src/lib.rs:48:18 | +| 1 | `std::mem` | fixtures/reject/src/lib.rs:48:29 | | 1 | `std::ops::RangeFrom` | fixtures/reject/src/lib.rs:289:48 | | 1 | `std::ops::RangeTo` | fixtures/reject/src/lib.rs:289:7 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:153:11 | @@ -132,14 +135,18 @@ The type or module each refused type or path belongs to. | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:299:52 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:172:23 | | 1 | constructing `_` from another crate | `std::iter::Rev` | fixtures/reject/src/lib.rs:193:14 | +| 1 | dropping `_`, which is not supported yet | `std::iter::Map` | fixtures/reject/src/lib.rs:49:18 | | 1 | hashing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:299:52 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:166:2 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:220:2 | +| 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Entry::or_insert_with` | fixtures/reject/src/lib.rs:393:13 | +| 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Iterator::any` | fixtures/reject/src/lib.rs:394:11 | +| 1 | passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet | `{closure}`, `Iterator::map` | fixtures/reject/src/lib.rs:49:11 | | 1 | replacing the value behind a reference to `_` | `[u8; 1]` | fixtures/reject/src/lib.rs:272:22 | | 1 | replacing the value behind a reference to `_` | `std::string::String` | fixtures/reject/src/lib.rs:377:4 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:153:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:96:10 | -| 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:48:18 | +| 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:48:29 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:207:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:367:4 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:32:4 | @@ -163,7 +170,7 @@ The type or module each refused type or path belongs to.
unsupported call to `_` (7) - fixtures/reject/src/lib.rs:32:4: unsupported call to `std::slice::::sort` -- fixtures/reject/src/lib.rs:48:18: unsupported call to `std::mem::size_of_val::` +- fixtures/reject/src/lib.rs:48:29: unsupported call to `std::mem::size_of_val::` - fixtures/reject/src/lib.rs:96:10: unsupported call to `::write_fmt` - fixtures/reject/src/lib.rs:153:11: unsupported call to ` as std::iter::Iterator>::cycle` - fixtures/reject/src/lib.rs:207:8: unsupported call to `std::ops::Range::::contains::` @@ -212,11 +219,11 @@ The type or module each refused type or path belongs to.
-
dropping a closure that owns a value that drops, which is not supported yet (3) +
passing `_`, a closure that owns a value that drops, to `_`, which is not supported yet (3) -- fixtures/reject/src/lib.rs:50:1: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:390:12: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:394:12: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:49:11: passing `{closure@fixtures/reject/src/lib.rs:48:10: 48:23}`, a closure that owns a value that drops, to `Iterator::map`, which is not supported yet +- fixtures/reject/src/lib.rs:393:13: passing `{closure@fixtures/reject/src/lib.rs:393:28: 393:35}`, a closure that owns a value that drops, to `Entry::or_insert_with`, which is not supported yet +- fixtures/reject/src/lib.rs:394:11: passing `{closure@fixtures/reject/src/lib.rs:394:15: 394:24}`, a closure that owns a value that drops, to `Iterator::any`, which is not supported yet
@@ -405,6 +412,12 @@ The type or module each refused type or path belongs to.
+
dropping `_`, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:49:18: dropping `std::iter::Map, {closure@fixtures/reject/src/lib.rs:48:10: 48:23}>`, which is not supported yet + +
+
hashing `_` as a key, which is not supported yet (1) - fixtures/reject/src/lib.rs:299:52: hashing `std::vec::Vec` as a key, which is not supported yet diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index ed7eef34f..104d44076 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -14,8 +14,9 @@ an assignment through a reference to `u32` at fixtures/reject/src/lib.rs:16:2 unsupported call to `std::slice::::sort` at fixtures/reject/src/lib.rs:32:4 `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:36:2 `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:36:42 -unsupported call to `std::mem::size_of_val::` at fixtures/reject/src/lib.rs:48:18 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:50:1 +unsupported call to `std::mem::size_of_val::` at fixtures/reject/src/lib.rs:48:29 +passing `{closure@fixtures/reject/src/lib.rs:48:10: 48:23}`, a closure that owns a value that drops, to `Iterator::map`, which is not supported yet at fixtures/reject/src/lib.rs:49:11 +dropping `std::iter::Map, {closure@fixtures/reject/src/lib.rs:48:10: 48:23}>`, which is not supported yet at fixtures/reject/src/lib.rs:49:18 `into_keys` of `std::collections::HashMap`, which drops `Noisy`, which is not supported yet at fixtures/reject/src/lib.rs:55:13 `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:64:10 an assignment through a reference to `u8` at fixtures/reject/src/lib.rs:65:3 @@ -64,8 +65,8 @@ a coercion to `std::sync::Arc<[u8]>` at fixtures/reject/src/lib.rs:372:2 `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:376:15 replacing the value behind a reference to `std::string::String` at fixtures/reject/src/lib.rs:377:4 unsupported call to `core::str::::split::<[char; 2]>` at fixtures/reject/src/lib.rs:383:4 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:390:12 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:394:12 +passing `{closure@fixtures/reject/src/lib.rs:393:28: 393:35}`, a closure that owns a value that drops, to `Entry::or_insert_with`, which is not supported yet at fixtures/reject/src/lib.rs:393:13 +passing `{closure@fixtures/reject/src/lib.rs:394:15: 394:24}`, a closure that owns a value that drops, to `Iterator::any`, which is not supported yet at fixtures/reject/src/lib.rs:394:11 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:166:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:186:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:220:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index b1a9c40f9..1532886a4 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -42,11 +42,11 @@ impl Drop for Noisy { fn drop(&mut self) {} } -/// Dropping the closure would drop what it captured, which lives in an arrow function. -pub fn owning_closure() -> u8 { +/// A closure that owns a value that drops, which `map` would hold but never drop. +pub fn owning_closure(v: &[u8]) -> usize { let n = Noisy(1); - let f = move || std::mem::size_of_val(&n) as u8; - f() + let f = move |x: &u8| *x + std::mem::size_of_val(&n) as u8; + v.iter().map(f).count() } /// std's `fold` of `into_keys` drops each value after its key, where `next` drops it first. @@ -383,17 +383,13 @@ pub fn split_chars(s: &str) -> usize { s.split(['a', 'b']).count() } -/// `Option::map` drops its closure on `None`, as `Result::map_err` does on `Ok`, and with -/// it what it captured, which lives in an arrow function. -pub fn discarded_closure(a: Option, b: Result) -> u8 { - let (m, n) = (Noisy(1), Noisy(2)); - let a = a.map(move |x| { - drop(m); - x - }); - let b = b.map_err(move |e| { - drop(n); - e - }); - a.unwrap_or(0) + b.unwrap_or(0) +/// Closures that own a value that drops, which `any` and `or_insert_with` would call but +/// never drop. +pub fn called_closure(v: &[u8], m: &mut std::collections::HashMap) -> bool { + fn id(n: &Noisy) -> u8 { + n.0 + } + let (a, b) = (Noisy(1), Noisy(2)); + m.entry(1).or_insert_with(move || b); + v.iter().any(move |&x| x == id(&a)) } diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 5c35f06d3..fb917186b 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -46,7 +46,7 @@ roots = [ "shared", "pushed", "split_chars", - "discarded_closure", + "called_closure", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 00dfeb714..76520662e 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Guard_Bomb_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; +import { scoped, discarded, blasted } from "./drops/closures.ts"; import { looped, collected, drained, extended, bombed, spent } from "./drops/iters.ts"; import * as Bomb from "./drops.Bomb.ts"; import type * as Fault from "./drops.Fault.ts"; @@ -16,7 +17,7 @@ import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; /** - * Run scenario `arg % 19`, panicking at the point `arg / 19 % 8` names, if any: what + * Run scenario `arg % 22`, panicking at the point `arg / 22 % 8` names, if any: what * every value std holds drops, where Rust drops it, and in Rust's order. */ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { @@ -74,7 +75,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _353 = false; _352 = false; _351 = false; - const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 19), 8); + const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 22), 8); const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -84,8 +85,14 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { rt.panicFmt(["d", args16[0], " at ", args16[1]]); } }; - const _13: rt.u8 = rt.u8Rem(arg, 19); - if (_13 === 13) { + const _13: rt.u8 = rt.u8Rem(arg, 22); + if (_13 === 19) { + scoped(log, id, at); + } else if (_13 === 20) { + discarded(log, id, at); + } else if (_13 === 21) { + blasted(log, id, at); + } else if (_13 === 13) { looped(log, id, at); } else if (_13 === 14) { collected(log, id, at); @@ -117,23 +124,23 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { grown(log, id, at, false); } else if (_13 === 0) { v = []; - unwind = 203; + unwind = 206; const _19: Held.Held = { tag: "One", _0: guard(1) }; v.push(_19); v.push({ tag: "Empty" } as Held.Held); _29 = guard(2); - unwind = 202; + unwind = 205; const _32: Guard.Guard = guard(3); - unwind = 203; + unwind = 206; v.push({ tag: "Two", _0: _29, _1: _32 } as Held.Held); - unwind = 201; + unwind = 204; held_ = v; check(1); arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); - unwind = 220; + unwind = 223; _358 = true; shared = rt.arcClone(arc); - unwind = 200; + unwind = 203; _358 = false; rt.arcDrop(arc, drop$Held); const arg7 = ([shared.strong] as [rt.usize])[0]; @@ -141,22 +148,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { Log.note(log, rt.fmtFormat(["arc ", args2[0]])); check(2); v2 = []; - unwind = 199; + unwind = 202; const _67: Held.Held = { tag: "One", _0: guard(5) }; v2.push(_67); - unwind = 200; + unwind = 203; mutex = new rt.Mutex(v2); - unwind = 218; + unwind = 221; _357 = true; _73 = guard(6); - unwind = 198; + unwind = 201; const _76: Guard.Guard = guard(7); - unwind = 218; + unwind = 221; boxed = { tag: "Two", _0: _73, _1: _76 } as Held.Held; - unwind = 216; + unwind = 219; _356 = true; const _80: Held.Held = { tag: "One", _0: guard(8) }; - unwind = 197; + unwind = 200; maybe = _80; check(3); [held_.length, maybe !== undefined] as [rt.usize, boolean]; @@ -170,9 +177,9 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { _357 = false; rt.dropAll(mutex.value, drop$Held); check(5); - unwind = 216; + unwind = 219; drop$Option_Box_Held(maybe); - unwind = 220; + unwind = 223; _356 = false; _357 = false; rt.arcDrop(shared, drop$Held); @@ -182,53 +189,53 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 1) { const _115: rt.u32 = rt.u32Add(id, 10); _117 = Log.clone$Clone(log); - unwind = 196; + unwind = 199; const _119: Guard.Guard = guard(11); - unwind = 195; + unwind = 198; wrapped = new Wrap.Wrap({ id: _115, log: _117, inner: { tag: "One", _0: _119 } as Held.Held }); const _123: rt.u32 = rt.u32Add(id, 20); _125 = Log.clone$Clone(log); - unwind = 194; + unwind = 197; const _126: Guard.Guard = guard(21); - unwind = 193; + unwind = 196; guarded = new Wrap.Wrap({ id: _123, log: _125, inner: _126 }); check(1); _134 = guard(31); - unwind = 192; + unwind = 195; const _137: Guard.Guard = guard(32); - unwind = 191; + unwind = 194; _133 = { tag: "Two", _0: _134, _1: _137 } as Held.Held; const _140: Guard.Guard = guard(33); - unwind = 214; + unwind = 217; _355 = true; pair = new Pair.Pair({ first: _133, second: _140 }); v3 = []; - unwind = 190; + unwind = 193; _148 = guard(41); - unwind = 189; + unwind = 192; const _151: Guard.Guard = guard(42); - unwind = 190; + unwind = 193; v3.push(new Pair.Pair({ first: _148, second: _151 })); _157 = guard(43); - unwind = 188; + unwind = 191; const _160: Guard.Guard = guard(44); - unwind = 190; + unwind = 193; v3.push(new Pair.Pair({ first: _157, second: _160 })); - unwind = 187; + unwind = 190; pairs = v3; check(2); const _167: rt.u32 = rt.u32Add(id, 50); _169 = Log.clone$Clone(log); - unwind = 186; + unwind = 189; v4 = []; - unwind = 185; + unwind = 188; const _175: rt.u32 = rt.u32Add(id, 60); _177 = Log.clone$Clone(log); - unwind = 184; + unwind = 187; const _179: Guard.Guard = guard(61); - unwind = 185; + unwind = 188; v4.push(new Wrap.Wrap({ id: _175, log: _177, inner: { tag: "One", _0: _179 } as Held.Held })); - unwind = 183; + unwind = 186; nested = new Wrap.Wrap({ id: _167, log: _169, inner: v4 }); check(3); _355 = false; @@ -242,11 +249,11 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg6 = args5[2]; const args6: rt.Fmt[] = [_218, _219, (f: rt.Formatter) => rt.u32Display(arg6, f)]; Log.note(log, rt.fmtFormat(["wraps ", args6[0], " ", args6[1], " ", args6[2]])); - unwind = 187; + unwind = 190; drop$Wrap_Vec_Wrap_Held(nested); - unwind = 214; + unwind = 217; rt.dropAll(pairs); - unwind = 195; + unwind = 198; _355 = false; drop$Wrap_Guard(guarded); unwind = 0; @@ -254,22 +261,22 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } else if (_13 === 2) { const _225: rt.u32 = rt.u32Add(id, 70); _227 = Log.clone$Clone(log); - unwind = 182; + unwind = 185; const _230: Guard.Guard = guard(71); - unwind = 181; + unwind = 184; _229 = { tag: "One", _0: _230 } as Held.Held; const _233: Guard.Guard = guard(72); unwind = 0; shared2 = new rt.Arc(new Wrap.Wrap({ id: _225, log: _227, inner: new Pair.Pair({ first: _229, second: _233 }) })); - unwind = 212; + unwind = 215; _354 = true; v5 = []; - unwind = 180; + unwind = 183; const _240: rt.Arc>> = rt.arcClone(shared2); v5.push(_240); const _244: rt.Arc>> = rt.arcClone(shared2); v5.push(_244); - unwind = 179; + unwind = 182; clones = v5; check(1); _354 = false; @@ -281,37 +288,37 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg5 = ([!bail(log, id, at).ok] as [boolean])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg5, f)]; Log.note(log, rt.fmtFormat(["bailed ", args10[0]])); - unwind = 212; + unwind = 215; rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); _354 = false; } else { _282 = guard(81); - unwind = 178; + unwind = 181; const _285: Guard.Guard = guard(82); unwind = 0; arc2 = new rt.Arc(new rt.Mutex({ tag: "Two", _0: _282, _1: _285 } as Held.Held)); - unwind = 210; + unwind = 213; _353 = true; other = rt.arcClone(arc2); - unwind = 177; + unwind = 180; check(1); _353 = false; rt.arcDrop(arc2, drop$Mutex_Held); check(2); const _301: rt.Mutex = other.value; - unwind = 176; + unwind = 179; const held2: boolean = Held.isSome(_301.value); - unwind = 177; + unwind = 180; const arg2 = ([held2] as [boolean])[0]; const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(arg2, f)]; Log.note(log, rt.fmtFormat(["locked ", args12[0]])); lent = guard(83); - unwind = 175; + unwind = 178; borrowed = new rt.Arc(lent); - unwind = 208; + unwind = 211; _352 = true; again = rt.arcClone(borrowed); - unwind = 206; + unwind = 209; _351 = true; _352 = false; rt.arcDrop(borrowed); @@ -321,11 +328,11 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const arg3 = ([Guard.id(lent)] as [rt.u32])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; Log.note(log, rt.fmtFormat(["lent ", args14[0]])); - unwind = 177; + unwind = 180; _351 = false; _352 = false; rt.drop(lent); - unwind = 210; + unwind = 213; rt.arcDrop(other, drop$Mutex_Held); _353 = false; } @@ -352,127 +359,127 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { if (unwind === 0) { throw e; } - if (unwind === 175) { + if (unwind === 178) { break b4; } - if (unwind === 176) { + if (unwind === 179) { break b3; } - if (unwind === 177) { + if (unwind === 180) { break b3; } - if (unwind === 178) { + if (unwind === 181) { rt.drop(_282); break b1; } - if (unwind === 179) { + if (unwind === 182) { rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 180) { + if (unwind === 183) { rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); break b5; } - if (unwind === 181) { + if (unwind === 184) { drop$Held(_229); break b6; } - if (unwind === 182) { + if (unwind === 185) { break b6; } - if (unwind === 183) { + if (unwind === 186) { drop$Wrap_Vec_Wrap_Held(nested); break b10; } - if (unwind === 184) { + if (unwind === 187) { rt.drop(_177); break b12; } - if (unwind === 185) { + if (unwind === 188) { break b12; } - if (unwind === 186) { + if (unwind === 189) { break b11; } - if (unwind === 187) { + if (unwind === 190) { break b10; } - if (unwind === 188) { + if (unwind === 191) { rt.drop(_157); break b13; } - if (unwind === 189) { + if (unwind === 192) { rt.drop(_148); break b13; } - if (unwind === 190) { + if (unwind === 193) { break b13; } - if (unwind === 191) { + if (unwind === 194) { drop$Held(_133); break b8; } - if (unwind === 192) { + if (unwind === 195) { rt.drop(_134); break b8; } - if (unwind === 193) { + if (unwind === 196) { break b8; } - if (unwind === 194) { + if (unwind === 197) { rt.drop(_125); break b7; } - if (unwind === 195) { + if (unwind === 198) { break b7; } - if (unwind === 196) { + if (unwind === 199) { rt.drop(_117); break b1; } - if (unwind === 197) { + if (unwind === 200) { drop$Option_Box_Held(maybe); break b18; } - if (unwind === 198) { + if (unwind === 201) { rt.drop(_73); break b17; } - if (unwind === 199) { + if (unwind === 202) { rt.dropAll(v2, drop$Held); break b16; } - if (unwind === 200) { + if (unwind === 203) { break b16; } - if (unwind === 201) { + if (unwind === 204) { break b14; } - if (unwind === 202) { + if (unwind === 205) { rt.drop(_29); break b19; } - if (unwind === 203) { + if (unwind === 206) { break b19; } - if (unwind === 206) { + if (unwind === 209) { if (_351) { rt.arcDrop(again); } - } else if (unwind !== 208) { - if (unwind === 210) { + } else if (unwind !== 211) { + if (unwind === 213) { break b2; } - if (unwind === 212) { + if (unwind === 215) { break b5; } - if (unwind === 214) { + if (unwind === 217) { break b9; } - if (unwind === 216) { + if (unwind === 219) { break b18; } - if (unwind === 218) { + if (unwind === 221) { break b17; } break b15; diff --git a/ts/fixtures/task/expected/drops/closures.Holder.ts b/ts/fixtures/task/expected/drops/closures.Holder.ts new file mode 100644 index 000000000..5853f49dd --- /dev/null +++ b/ts/fixtures/task/expected/drops/closures.Holder.ts @@ -0,0 +1,31 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as Guard from "../model.Guard.ts"; + +/** Hold `f`, which drops with it. */ +export class Holder { + f: F; + guard: Guard.Guard; + + constructor(fields: { f: F; guard: Guard.Guard }) { + this.f = fields.f; + this.guard = fields.guard; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + rt.drop(this.f); + dropped = 1; + rt.drop(this.guard); + } catch (e) { + if (dropped < 1) { + rt.drop(this.guard); + } + throw e; + } + } +} + +//# sourceMappingURL=closures.Holder.ts.map diff --git a/ts/fixtures/task/expected/drops/closures.ts b/ts/fixtures/task/expected/drops/closures.ts new file mode 100644 index 000000000..6a90debd2 --- /dev/null +++ b/ts/fixtures/task/expected/drops/closures.ts @@ -0,0 +1,1330 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import * as Holder from "../drops/closures.Holder.ts"; +import * as Bomb from "../drops.Bomb.ts"; +import * as Log from "../log.Log.ts"; +import * as Guard from "../model.Guard.ts"; + +/** Call `f` once, which consumes it. */ +export function once$u32_blasted_closure4(f: () => rt.u32): rt.u32 { + return f(); +} + +/** Call `f` once, which consumes it. */ +export function once$u32_blasted_closure5(f: () => rt.u32): rt.u32 { + return rt.callOnce(f); +} + +/** Call `f` once, which consumes it. */ +export function once$u32_scoped_closure4(f: () => rt.u32): rt.u32 { + return f(); +} + +/** Call `f` once, which consumes it. */ +export function once$u32_scoped_closure5(f: () => rt.u32): rt.u32 { + return f(); +} + +/** Call `f` once, which consumes it. */ +export function once$u32_scoped_closure6(f: () => rt.u32): rt.u32 { + return rt.callOnce(f); +} + +/** Call `f` once, which consumes it. */ +export function once$u32_scoped_closure9(f: () => rt.u32): rt.u32 { + return rt.callOnce(f); +} + +/** Call `f` with each of `n` and `n + 1`, which borrows it, and drop it. */ +export function twice$scoped_closure11(n: rt.u32, f: (a0: rt.u32) => rt.u32): rt.u32 { + let unwind: number = 0; + try { + unwind = 7; + const _11: rt.u32 = rt.u32Add(f(n), f(rt.u32Add(n, 1))); + unwind = 0; + rt.drop(f); + return _11; + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(f); + throw e; + } +} + +/** + * The id of `bomb`, which a closure that calls it captures whole, where one that reads + * its field captures only that. + */ +export function bombId(bomb: Bomb.Bomb): rt.u32 { + return bomb.id; +} + +/** + * What closures that own guards drop, panicking at point `at`, if any, some inside a + * closure's body. + */ +export function scoped(log: Log.Log, id: rt.u32, at: rt.u8): void { + let a!: Guard.Guard; + let b!: Guard.Guard; + let _12!: Guard.Guard; + let unused!: () => rt.u32; + let read!: (a0: rt.u32) => rt.u32; + let e!: Guard.Guard; + let f!: Guard.Guard; + let holder!: Holder.Holder<(a0: rt.u32) => rt.u32>; + let _110!: (a0: rt.u32) => rt.u32; + let outer!: () => rt.u32; + let push!: (a0: Guard.Guard) => rt.usize; + let _179!: boolean; + let _180!: boolean; + let _181!: boolean; + let _182!: boolean; + let _183!: boolean; + let _184!: boolean; + let unwind: number = 0; + try { + _184 = false; + _183 = false; + _182 = false; + _181 = false; + _180 = false; + _179 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args16[0], " at ", args16[1]]); + } + }; + _12 = guard(1); + unwind = 74; + const _15: Guard.Guard = guard(2); + unwind = 83; + _184 = true; + a = _12; + _183 = true; + b = _15; + _184 = false; + _183 = false; + _182 = true; + const captured = a; + const captured2 = b; + unused = rt.closure((): rt.u32 => { + return rt.u32Add(Guard.id(captured), Guard.id(captured2)); + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured); + dropped = 1; + rt.drop(captured2); + } catch (e) { + if (dropped < 1) { + rt.drop(captured2); + } + throw e; + } + }); + const c: Guard.Guard = guard(3); + unwind = 71; + const captured3 = c; + read = rt.closure((n2: rt.u32): rt.u32 => { + return rt.u32Add(n2, Guard.id(captured3)); + }, (): void => { + rt.drop(captured3); + }); + const arg = ([rt.u32Add(read(1), read(2))] as [rt.u32])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; + Log.note(log, rt.fmtFormat(["read ", args2[0]])); + check(1); + _182 = false; + rt.drop(unused); + const captured4 = guard(4); + const arg3 = ([once$u32_scoped_closure4(rt.closure((): rt.u32 => { + let _172!: boolean; + let unwind2: number = 0; + try { + unwind2 = 11; + _172 = false; + _172 = true; + const n3: rt.u32 = Guard.id(captured4); + _172 = false; + rt.drop(captured4); + const arg2 = ([n3] as [rt.u32])[0]; + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg2, f)]; + Log.note(log, rt.fmtFormat(["moved ", args18[0]])); + return n3; + } catch (e3) { + if (unwind2 === 0) { + throw e3; + } + if (_172) { + rt.drop(captured4); + } + throw e3; + } + }, (): void => { + rt.drop(captured4); + }))] as [rt.u32])[0]; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; + Log.note(log, rt.fmtFormat(["moved ", args4[0]])); + e = guard(5); + const captured5 = check; + const captured6 = e; + const arg4 = ([once$u32_scoped_closure5(rt.closure((): rt.u32 => { + let unwind3: number = 0; + try { + unwind3 = 5; + captured5(2); + const _04: rt.u32 = Guard.id(captured6); + unwind3 = 0; + rt.drop(captured6); + return _04; + } catch (e4) { + if (unwind3 === 0) { + throw e4; + } + rt.drop(captured6); + throw e4; + } + }, (): void => { + rt.drop(captured6); + }))] as [rt.u32])[0]; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; + Log.note(log, rt.fmtFormat(["kept ", args6[0]])); + f = guard(6); + const captured7 = check; + const captured8 = f; + const arg5 = ([once$u32_scoped_closure6(rt.closure((): rt.u32 => { + captured7(3); + return Guard.id(captured8); + }, (): void => { + rt.drop(captured8); + }))] as [rt.u32])[0]; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg5, f)]; + Log.note(log, rt.fmtFormat(["by ref ", args8[0]])); + const captured9 = guard(7); + const arg6 = ([twice$scoped_closure11(1, rt.closure((n4: rt.u32): rt.u32 => { + return rt.u32Add(n4, Guard.id(captured9)); + }, (): void => { + rt.drop(captured9); + }))] as [rt.u32])[0]; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg6, f)]; + Log.note(log, rt.fmtFormat(["twice ", args10[0]])); + const h: Guard.Guard = guard(8); + unwind = 70; + const captured10 = h; + _110 = rt.closure((n5: rt.u32): rt.u32 => { + return rt.u32Add(n5, Guard.id(captured10)); + }, (): void => { + rt.drop(captured10); + }); + const _111: Guard.Guard = guard(9); + unwind = 81; + _181 = true; + holder = new Holder.Holder({ f: _110, guard: _111 }); + const arg7 = ([rt.u32Add(holder.f(1), Guard.id(holder.guard))] as [rt.u32])[0]; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg7, f)]; + Log.note(log, rt.fmtFormat(["holder ", args12[0]])); + const i: Guard.Guard = guard(10); + unwind = 79; + const captured11 = i; + _180 = true; + const captured12 = rt.closure((n6: rt.u32): rt.u32 => { + return rt.u32Add(n6, Guard.id(captured11)); + }, (): void => { + rt.drop(captured11); + }); + outer = rt.closure((): rt.u32 => { + return captured12(1); + }, (): void => { + rt.drop(captured12); + }); + check(4); + _180 = false; + const arg8 = ([once$u32_scoped_closure9(outer)] as [rt.u32])[0]; + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg8, f)]; + Log.note(log, rt.fmtFormat(["outer ", args14[0]])); + _181 = false; + rt.drop(holder); + const held: Guard.Guard[] = []; + unwind = 77; + _179 = true; + const captured13 = held; + push = rt.closure((g2: Guard.Guard): rt.usize => { + captured13.push(g2); + return captured13.length; + }, (): void => { + rt.dropAll(captured13); + }); + const part = guard(11); + push(part); + const part2 = guard(12); + push(part2); + check(5); + _179 = false; + rt.drop(push); + unwind = 83; + _179 = false; + _180 = false; + _181 = false; + rt.drop(read); + _182 = false; + _183 = false; + _184 = false; + } catch (e2) { + b0: { + b1: { + b2: { + b3: { + if (unwind === 0) { + throw e2; + } + if (unwind === 70) { + rt.drop(_110); + break b2; + } + if (unwind === 71) { + break b2; + } + if (unwind === 74) { + rt.drop(_12); + break b0; + } + if (unwind === 77) { + if (_179) { + rt.drop(push); + } + } else if (unwind !== 79) { + if (unwind === 81) { + break b3; + } + break b1; + } + if (_180) { + rt.drop(outer); + } + } + if (_181) { + rt.drop(holder); + } + } + rt.drop(read); + } + if (_182) { + rt.drop(unused); + } + if (_183) { + rt.drop(b); + } + if (_184) { + rt.drop(a); + } + } + throw e2; + } +} + +/** + * What std does with a closure that owns a guard: drops it where it is not called, and + * leaves it to the call where it is. + */ +export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { + let some!: rt.u32 | undefined; + let none!: rt.u32 | undefined; + let a!: Guard.Guard; + let b!: Guard.Guard; + let _16!: Guard.Guard; + let c!: Guard.Guard; + let d!: Guard.Guard; + let e!: Guard.Guard; + let f!: Guard.Guard; + let _47!: Guard.Guard; + let _50!: Guard.Guard; + let _53!: Guard.Guard; + let g!: Guard.Guard; + let h!: Guard.Guard; + let _84!: Guard.Guard; + let i!: Guard.Guard; + let j!: Guard.Guard; + let _98!: Guard.Guard; + let k!: Guard.Guard; + let l!: Guard.Guard; + let _124!: Guard.Guard; + let o!: Guard.Guard; + let p!: Guard.Guard; + let _150!: Guard.Guard; + let other!: (a0: rt.u32) => rt.u32; + let _205!: boolean; + let _206!: boolean; + let _207!: boolean; + let _208!: boolean; + let _209!: boolean; + let _210!: boolean; + let _211!: boolean; + let _212!: boolean; + let _213!: boolean; + let _214!: boolean; + let _215!: boolean; + let _216!: boolean; + let _217!: boolean; + let _218!: boolean; + let _219!: boolean; + let unwind: number = 0; + try { + _219 = false; + _218 = false; + _217 = false; + _216 = false; + _215 = false; + _214 = false; + _213 = false; + _212 = false; + _211 = false; + _210 = false; + _209 = false; + _208 = false; + _207 = false; + _206 = false; + _205 = false; + const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args14[0], " at ", args14[1]]); + } + }; + if (!(at < 8)) { + some = undefined; + } else { + some = id; + } + if (!(at > 8)) { + none = undefined; + } else { + none = id; + } + _16 = guard(1); + unwind = 89; + const _19: Guard.Guard = guard(2); + unwind = 110; + _219 = true; + a = _16; + _218 = true; + b = _19; + _219 = false; + const captured = check; + const captured2 = a; + const mapped: rt.u32 | undefined = rt.optionMap(some, rt.closure((n2: rt.u32): rt.u32 => { + let unwind2: number = 0; + try { + unwind2 = 6; + captured(1); + const _8: rt.u32 = rt.u32Add(n2, Guard.id(captured2)); + unwind2 = 0; + rt.drop(captured2); + return _8; + } catch (e3) { + if (unwind2 === 0) { + throw e3; + } + rt.drop(captured2); + throw e3; + } + }, (): void => { + rt.drop(captured2); + }), rt.drop); + _218 = false; + const captured3 = b; + const args: [rt.u32 | undefined, rt.u32 | undefined] = [mapped, rt.optionMap(none, rt.closure((n3: rt.u32): rt.u32 => { + let unwind3: number = 0; + try { + unwind3 = 5; + const _57: rt.u32 = rt.u32Add(n3, Guard.id(captured3)); + unwind3 = 0; + rt.drop(captured3); + return _57; + } catch (e4) { + if (unwind3 === 0) { + throw e4; + } + rt.drop(captured3); + throw e4; + } + }, (): void => { + rt.drop(captured3); + }), rt.drop)]; + const _36: rt.Fmt = (f: rt.Formatter) => rt.fmtOption(mapped, f, rt.u32Display); + const arg = args[1]; + const args2: rt.Fmt[] = [_36, (f: rt.Formatter) => rt.fmtOption(arg, f, rt.u32Display)]; + Log.note(log, rt.fmtFormat(["map ", args2[0], " ", args2[1]])); + const ok: rt.Result = rt.Ok(id); + const err: rt.Result = rt.Err(id); + _47 = guard(3); + unwind = 87; + _50 = guard(4); + unwind = 86; + _53 = guard(5); + unwind = 85; + const _56: Guard.Guard = guard(6); + unwind = 105; + _217 = true; + c = _47; + _216 = true; + d = _50; + _215 = true; + e = _53; + _214 = true; + f = _56; + _217 = false; + const captured4 = c; + const _60: rt.Result = rt.resultMap(ok, rt.closure((n4: rt.u32): rt.u32 => { + let unwind4: number = 0; + try { + unwind4 = 5; + const _59: rt.u32 = rt.u32Add(n4, Guard.id(captured4)); + unwind4 = 0; + rt.drop(captured4); + return _59; + } catch (e5) { + if (unwind4 === 0) { + throw e5; + } + rt.drop(captured4); + throw e5; + } + }, (): void => { + rt.drop(captured4); + }), rt.drop); + _216 = false; + const captured5 = d; + const values: [rt.Result, rt.Result] = [_60, rt.resultMap(err, rt.closure((n5: rt.u32): rt.u32 => { + let unwind5: number = 0; + try { + unwind5 = 5; + const _510: rt.u32 = rt.u32Add(n5, Guard.id(captured5)); + unwind5 = 0; + rt.drop(captured5); + return _510; + } catch (e6) { + if (unwind5 === 0) { + throw e6; + } + rt.drop(captured5); + throw e6; + } + }, (): void => { + rt.drop(captured5); + }), rt.drop)]; + _215 = false; + const captured6 = e; + const _65: rt.Result = rt.resultMapErr(ok, rt.closure((n6: rt.u32): rt.u32 => { + let unwind6: number = 0; + try { + unwind6 = 5; + const _511: rt.u32 = rt.u32Add(n6, Guard.id(captured6)); + unwind6 = 0; + rt.drop(captured6); + return _511; + } catch (e7) { + if (unwind6 === 0) { + throw e7; + } + rt.drop(captured6); + throw e7; + } + }, (): void => { + rt.drop(captured6); + }), rt.drop); + _214 = false; + const captured7 = check; + const captured8 = f; + const args3: [[rt.Result, rt.Result], [rt.Result, rt.Result]] = [values, [_65, rt.resultMapErr(err, rt.closure((n7: rt.u32): rt.u32 => { + let unwind7: number = 0; + try { + unwind7 = 6; + captured7(2); + const _82: rt.u32 = rt.u32Add(n7, Guard.id(captured8)); + unwind7 = 0; + rt.drop(captured8); + return _82; + } catch (e8) { + if (unwind7 === 0) { + throw e8; + } + rt.drop(captured8); + throw e8; + } + }, (): void => { + rt.drop(captured8); + }), rt.drop)] as [rt.Result, rt.Result]]; + const _77: rt.Fmt = (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(values[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(values[1], f, rt.u32Display, rt.u32Display)], f); + const arg2 = args3[1]; + const args4: rt.Fmt[] = [_77, (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(arg2[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(arg2[1], f, rt.u32Display, rt.u32Display)], f)]; + Log.note(log, rt.fmtFormat(["result ", args4[0], " ", args4[1]])); + _84 = guard(7); + unwind = 81; + const _87: Guard.Guard = guard(8); + unwind = 102; + _213 = true; + g = _84; + _212 = true; + h = _87; + _213 = false; + const captured9 = g; + const _91: rt.Result = rt.resultAndThen(ok, rt.closure((n8: rt.u32): rt.Result => { + let unwind8: number = 0; + try { + unwind8 = 5; + const _611: rt.u32 = rt.u32Add(n8, Guard.id(captured9)); + unwind8 = 0; + const _08: rt.Result = rt.Ok(_611); + rt.drop(captured9); + return _08; + } catch (e9) { + if (unwind8 === 0) { + throw e9; + } + rt.drop(captured9); + throw e9; + } + }, (): void => { + rt.drop(captured9); + }), rt.drop); + _212 = false; + const captured10 = h; + const chained: [rt.Result, rt.Result] = [_91, rt.resultAndThen(err, rt.closure((n9: rt.u32): rt.Result => { + let unwind9: number = 0; + try { + unwind9 = 5; + const _612: rt.u32 = rt.u32Add(n9, Guard.id(captured10)); + unwind9 = 0; + const _09: rt.Result = rt.Ok(_612); + rt.drop(captured10); + return _09; + } catch (e10) { + if (unwind9 === 0) { + throw e10; + } + rt.drop(captured10); + throw e10; + } + }, (): void => { + rt.drop(captured10); + }), rt.drop)]; + _98 = guard(9); + unwind = 79; + const _101: Guard.Guard = guard(10); + unwind = 99; + _211 = true; + i = _98; + _210 = true; + j = _101; + _211 = false; + const captured11 = i; + const _105: rt.Result = rt.resultInspectErr(ok, rt.closure((_2: rt.u32): void => { + let unwind10: number = 0; + try { + unwind10 = 9; + const arg3 = ([Guard.id(captured11)] as [rt.u32])[0]; + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg3, f)]; + Log.note(log, rt.fmtFormat(["inspect ", args16[0]])); + unwind10 = 0; + rt.drop(captured11); + } catch (e11) { + if (unwind10 === 0) { + throw e11; + } + rt.drop(captured11); + throw e11; + } + }, (): void => { + rt.drop(captured11); + }), undefined, rt.drop); + _210 = false; + const captured12 = check; + const captured13 = j; + const args5: [[rt.Result, rt.Result], [rt.Result, rt.Result]] = [chained, [_105, rt.resultInspectErr(err, rt.closure((_22: rt.u32): void => { + let unwind11: number = 0; + try { + unwind11 = 10; + captured12(3); + const arg4 = ([Guard.id(captured13)] as [rt.u32])[0]; + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg4, f)]; + Log.note(log, rt.fmtFormat(["inspect ", args18[0]])); + unwind11 = 0; + rt.drop(captured13); + } catch (e12) { + if (unwind11 === 0) { + throw e12; + } + rt.drop(captured13); + throw e12; + } + }, (): void => { + rt.drop(captured13); + }), undefined, rt.drop)] as [rt.Result, rt.Result]]; + const _117: rt.Fmt = (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(chained[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(chained[1], f, rt.u32Display, rt.u32Display)], f); + const arg5 = args5[1]; + const args6: rt.Fmt[] = [_117, (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(arg5[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(arg5[1], f, rt.u32Display, rt.u32Display)], f)]; + Log.note(log, rt.fmtFormat(["chained ", args6[0], " ", args6[1]])); + _124 = guard(11); + unwind = 77; + const _127: Guard.Guard = guard(12); + unwind = 96; + _209 = true; + k = _124; + _208 = true; + l = _127; + _209 = false; + const captured14 = check; + const captured15 = k; + const _131: rt.u32 = rt.optionMapOr(some, 0, rt.closure((n10: rt.u32): rt.u32 => { + let unwind12: number = 0; + try { + unwind12 = 6; + captured14(4); + const _810: rt.u32 = rt.u32Add(n10, Guard.id(captured15)); + unwind12 = 0; + rt.drop(captured15); + return _810; + } catch (e13) { + if (unwind12 === 0) { + throw e13; + } + rt.drop(captured15); + throw e13; + } + }, (): void => { + rt.drop(captured15); + }), undefined, rt.drop); + _208 = false; + const captured16 = l; + const arg6 = ([[_131, rt.optionMapOr(none, 0, rt.closure((n11: rt.u32): rt.u32 => { + let unwind13: number = 0; + try { + unwind13 = 5; + const _516: rt.u32 = rt.u32Add(n11, Guard.id(captured16)); + unwind13 = 0; + rt.drop(captured16); + return _516; + } catch (e14) { + if (unwind13 === 0) { + throw e14; + } + rt.drop(captured16); + throw e14; + } + }, (): void => { + rt.drop(captured16); + }), undefined, rt.drop)] as [rt.u32, rt.u32]] as [[rt.u32, rt.u32]])[0]; + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.u32Display(arg6[0], f), (f: rt.Formatter) => rt.u32Display(arg6[1], f)], f)]; + Log.note(log, rt.fmtFormat(["map_or ", args8[0]])); + _150 = guard(15); + unwind = 75; + const _153: Guard.Guard = guard(16); + unwind = 92; + _207 = true; + o = _150; + _206 = true; + p = _153; + _207 = false; + const captured17 = check; + const captured18 = o; + const plus: (a0: rt.u32) => rt.u32 = rt.closure((n12: rt.u32): rt.u32 => { + captured17(5); + return rt.u32Add(n12, Guard.id(captured18)); + }, (): void => { + rt.drop(captured18); + }); + _206 = false; + _205 = true; + const captured19 = p; + other = rt.closure((n13: rt.u32): rt.u32 => { + return rt.u32Add(n13, Guard.id(captured19)); + }, (): void => { + rt.drop(captured19); + }); + const _164: rt.u32 | undefined = rt.optionMap(some, rt.once(plus), rt.drop); + _205 = false; + const args9: [rt.u32 | undefined, rt.u32 | undefined] = [_164, rt.optionMap(none, rt.once(other), rt.drop)]; + const _171: rt.Fmt = (f: rt.Formatter) => rt.fmtOption(_164, f, rt.u32Display); + const arg7 = args9[1]; + const args10: rt.Fmt[] = [_171, (f: rt.Formatter) => rt.fmtOption(arg7, f, rt.u32Display)]; + Log.note(log, rt.fmtFormat(["by ref ", args10[0], " ", args10[1]])); + const captured20 = guard(17); + const captured21 = check; + const captured22 = rt.closure((n14: rt.u32): rt.u32 => { + return rt.u32Add(n14, Guard.id(captured20)); + }, (): void => { + rt.drop(captured20); + }); + const arg8 = ([rt.optionMap(some, rt.closure((n15: rt.u32): rt.u32 => { + let unwind14: number = 0; + try { + unwind14 = 5; + captured21(6); + const _015: rt.u32 = captured22(n15); + unwind14 = 0; + rt.drop(captured22); + return _015; + } catch (e15) { + if (unwind14 === 0) { + throw e15; + } + rt.drop(captured22); + throw e15; + } + }, (): void => { + rt.drop(captured22); + }), rt.drop)] as [rt.u32 | undefined])[0]; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(arg8, f, rt.u32Display)]; + Log.note(log, rt.fmtFormat(["nested ", args12[0]])); + check(7); + _205 = false; + _206 = false; + _207 = false; + _208 = false; + _209 = false; + _210 = false; + _211 = false; + _212 = false; + _213 = false; + _214 = false; + _215 = false; + _216 = false; + _217 = false; + _218 = false; + _219 = false; + } catch (e2) { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + b8: { + if (unwind === 0) { + throw e2; + } + if (unwind === 75) { + rt.drop(_150); + break b7; + } + if (unwind === 77) { + rt.drop(_124); + break b6; + } + if (unwind === 79) { + rt.drop(_98); + break b5; + } + if (unwind === 81) { + rt.drop(_84); + break b4; + } + if (unwind === 85) { + rt.drop(_53); + } else if (unwind !== 86) { + if (unwind === 87) { + break b8; + } + if (unwind === 89) { + rt.drop(_16); + break b2; + } + if (unwind === 92) { + if (_205) { + rt.drop(other); + } + if (_206) { + rt.drop(p); + } + if (!_207) { + break b7; + } + rt.drop(o); + break b7; + } + if (unwind === 96) { + break b7; + } + if (unwind === 99) { + break b6; + } + if (unwind === 102) { + break b5; + } + if (unwind === 105) { + break b4; + } + break b3; + } + rt.drop(_50); + } + rt.drop(_47); + break b3; + } + if (_208) { + rt.drop(l); + } + if (_209) { + rt.drop(k); + } + } + if (_210) { + rt.drop(j); + } + if (_211) { + rt.drop(i); + } + } + if (_212) { + rt.drop(h); + } + if (_213) { + rt.drop(g); + } + } + if (_214) { + rt.drop(f); + } + if (_215) { + rt.drop(e); + } + if (_216) { + rt.drop(d); + } + if (_217) { + rt.drop(c); + } + } + if (_218) { + rt.drop(b); + } + if (_219) { + rt.drop(a); + } + } + throw e2; + } +} + +/** + * What drops of a closure's captures when one's `Drop` panics: the rest still drop, in + * order, and the panic goes on. + */ +export function blasted(log: Log.Log, id: rt.u32, at: rt.u8): void { + let a!: Bomb.Bomb; + let b!: Bomb.Bomb; + let c!: Guard.Guard; + let _12!: Bomb.Bomb; + let _15!: Bomb.Bomb; + let f!: () => rt.u32; + let a2!: Bomb.Bomb; + let b2!: Guard.Guard; + let _37!: Bomb.Bomb; + let a3!: Bomb.Bomb; + let b3!: Guard.Guard; + let _50!: Bomb.Bomb; + let a4!: Bomb.Bomb; + let b4!: Guard.Guard; + let _62!: Bomb.Bomb; + let a5!: Bomb.Bomb; + let b5!: Guard.Guard; + let _74!: Bomb.Bomb; + let g!: () => rt.u32; + let h!: Guard.Guard; + let _90!: boolean; + let _91!: boolean; + let _92!: boolean; + let _93!: boolean; + let _94!: boolean; + let _95!: boolean; + let _96!: boolean; + let _97!: boolean; + let _98!: boolean; + let _99!: boolean; + let _100!: boolean; + let _101!: boolean; + let _102!: boolean; + let unwind: number = 0; + try { + _102 = false; + _101 = false; + _100 = false; + _99 = false; + _98 = false; + _97 = false; + _96 = false; + _95 = false; + _94 = false; + _93 = false; + _92 = false; + _91 = false; + _90 = false; + const bomb: (a0: rt.u32, a1: boolean) => Bomb.Bomb = (n: rt.u32, blows: boolean): Bomb.Bomb => { + return new Bomb.Bomb({ id: rt.u32Add(id, n), log: Log.clone$Clone(log), blows }); + }; + const guard: (a0: rt.u32) => Guard.Guard = (n2: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n2), Log.clone$Clone(log)); + }; + if (at === 0) { + _12 = bomb(1, false); + unwind = 49; + _15 = bomb(2, true); + unwind = 48; + const _18: Guard.Guard = guard(3); + unwind = 45; + _102 = true; + a = _12; + _101 = true; + b = _15; + _100 = true; + c = _18; + _102 = false; + _101 = false; + _100 = false; + const captured10 = a; + const captured11 = b; + const captured12 = c; + f = rt.closure((): rt.u32 => { + return rt.u32Add(rt.u32Add(bombId(captured10), bombId(captured11)), Guard.id(captured12)); + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured10); + dropped = 1; + rt.drop(captured11); + dropped = 2; + rt.drop(captured12); + } catch (e) { + if (dropped < 1) { + rt.drop(captured11); + } + if (dropped < 2) { + rt.drop(captured12); + } + throw e; + } + }); + const arg = ([f()] as [rt.u32])[0]; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; + Log.note(log, rt.fmtFormat(["blasted ", args2[0]])); + unwind = 66; + rt.drop(f); + _100 = false; + _101 = false; + _102 = false; + } else if (at === 1) { + _37 = bomb(1, true); + unwind = 44; + const _40: Guard.Guard = guard(2); + unwind = 63; + _99 = true; + a2 = _37; + _98 = true; + b2 = _40; + _99 = false; + _98 = false; + const captured8 = a2; + const captured9 = b2; + rt.optionMap(undefined, rt.closure((n3: rt.u32): rt.u32 => { + let unwind3: number = 0; + try { + unwind3 = 7; + const _9: rt.u32 = rt.u32Add(rt.u32Add(n3, bombId(captured8)), Guard.id(captured9)); + unwind3 = 0; + const _07: rt.u32 = _9; + let dropped: number = 0; + try { + rt.drop(captured8); + dropped = 1; + rt.drop(captured9); + } catch (e) { + if (dropped < 1) { + rt.drop(captured9); + } + throw e; + } + return _07; + } catch (e3) { + if (unwind3 === 0) { + throw e3; + } + let dropped: number = 0; + try { + rt.drop(captured8); + dropped = 1; + rt.drop(captured9); + } catch (e) { + if (dropped < 1) { + rt.drop(captured9); + } + throw e; + } + throw e3; + } + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured8); + dropped = 1; + rt.drop(captured9); + } catch (e) { + if (dropped < 1) { + rt.drop(captured9); + } + throw e; + } + }), rt.drop); + _98 = false; + _99 = false; + } else if (at === 2) { + _50 = bomb(1, true); + unwind = 42; + const _53: Guard.Guard = guard(2); + unwind = 60; + _97 = true; + a3 = _50; + _96 = true; + b3 = _53; + _97 = false; + _96 = false; + const captured6 = a3; + const captured7 = b3; + once$u32_blasted_closure4(rt.closure((): rt.u32 => { + let unwind2: number = 0; + try { + unwind2 = 6; + const _69: rt.u32 = rt.u32Add(bombId(captured6), Guard.id(captured7)); + unwind2 = 0; + const _06: rt.u32 = _69; + let dropped: number = 0; + try { + rt.drop(captured6); + dropped = 1; + rt.drop(captured7); + } catch (e) { + if (dropped < 1) { + rt.drop(captured7); + } + throw e; + } + return _06; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + let dropped: number = 0; + try { + rt.drop(captured6); + dropped = 1; + rt.drop(captured7); + } catch (e) { + if (dropped < 1) { + rt.drop(captured7); + } + throw e; + } + throw e2; + } + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured6); + dropped = 1; + rt.drop(captured7); + } catch (e) { + if (dropped < 1) { + rt.drop(captured7); + } + throw e; + } + })); + _96 = false; + _97 = false; + } else if (at === 3) { + _62 = bomb(1, true); + unwind = 40; + const _65: Guard.Guard = guard(2); + unwind = 57; + _95 = true; + a4 = _62; + _94 = true; + b4 = _65; + _95 = false; + _94 = false; + const captured4 = a4; + const captured5 = b4; + once$u32_blasted_closure5(rt.closure((): rt.u32 => { + return rt.u32Add(bombId(captured4), Guard.id(captured5)); + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured4); + dropped = 1; + rt.drop(captured5); + } catch (e) { + if (dropped < 1) { + rt.drop(captured5); + } + throw e; + } + })); + _94 = false; + _95 = false; + } else { + _74 = bomb(1, true); + unwind = 38; + const _77: Guard.Guard = guard(2); + unwind = 35; + _93 = true; + a5 = _74; + _92 = true; + b5 = _77; + _93 = false; + _92 = false; + const captured = a5; + const captured2 = b5; + _91 = true; + const captured3 = rt.closure((): rt.u32 => { + return rt.u32Add(bombId(captured), Guard.id(captured2)); + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured); + dropped = 1; + rt.drop(captured2); + } catch (e) { + if (dropped < 1) { + rt.drop(captured2); + } + throw e; + } + }); + g = rt.closure((): rt.u32 => { + return captured3(); + }, (): void => { + rt.drop(captured3); + }); + h = guard(3); + unwind = 52; + _90 = true; + _91 = false; + rt.drop(g); + _90 = false; + rt.drop(h); + _90 = false; + _91 = false; + _92 = false; + _93 = false; + } + } catch (e) { + b1: { + b2: { + b3: { + if (unwind === 0) { + throw e; + } + if (unwind === 35) { + break b2; + } + if (unwind === 38) { + rt.drop(_74); + break b1; + } + if (unwind === 40) { + rt.drop(_62); + break b1; + } + if (unwind === 42) { + rt.drop(_50); + break b1; + } + if (unwind === 44) { + rt.drop(_37); + break b1; + } + if (unwind === 45) { + rt.drop(f); + break b3; + } + if (unwind === 48) { + rt.drop(_15); + } else if (unwind !== 49) { + if (unwind === 52) { + if (!_90) { + break b2; + } + rt.drop(h); + break b2; + } + if (unwind === 57) { + if (_94) { + rt.drop(b4); + } + if (!_95) { + break b1; + } + rt.drop(a4); + break b1; + } + if (unwind === 60) { + if (_96) { + rt.drop(b3); + } + if (!_97) { + break b1; + } + rt.drop(a3); + break b1; + } + if (unwind === 63) { + if (_98) { + rt.drop(b2); + } + if (!_99) { + break b1; + } + rt.drop(a2); + break b1; + } + break b3; + } + rt.drop(_12); + break b1; + } + if (_100) { + rt.drop(c); + } + if (_101) { + rt.drop(b); + } + if (!_102) { + break b1; + } + rt.drop(a); + break b1; + } + if (_91) { + rt.drop(g); + } + if (_92) { + rt.drop(b5); + } + if (_93) { + rt.drop(a5); + } + } + throw e; + } +} + +//# sourceMappingURL=closures.ts.map diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index d7ca065a0..5f60b6d2a 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -1291,8 +1291,10 @@ export function temporaries(log: Log.Log, id: rt.u32): void { const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg4, f)]; Log.note(log, rt.fmtFormat(["empty ", args8[0]])); const captured = guard(1100); - const arg5 = ([((): rt.u32 => { + const arg5 = ([rt.closure((): rt.u32 => { return Guard.finish(captured, "closure"); + }, (): void => { + rt.drop(captured); })()] as [rt.u32])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg5, f)]; Log.note(log, rt.fmtFormat(["closed ", args10[0]])); diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index dac26786f..7576c2d65 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -21,6 +21,7 @@ macro_rules! list { }}; } +mod closures; mod iters; /// A value of a type that drops, with no `[Symbol.dispose]` of its own. @@ -49,17 +50,20 @@ pub struct Pair { second: Guard, } -/// Run scenario `arg % 19`, panicking at the point `arg / 19 % 8` names, if any: what +/// Run scenario `arg % 22`, panicking at the point `arg / 22 % 8` names, if any: what /// every value std holds drops, where Rust drops it, and in Rust's order. pub fn run(log: &Log, id: u32, arg: u8) { - let at = arg / 19 % 8; + let at = arg / 22 % 8; let guard = |n: u32| Guard::new(id + n, log.clone()); let check = |point: u8| { if point == at { panic!("d{id} at {point}"); } }; - match arg % 19 { + match arg % 22 { + 19 => closures::scoped(log, id, at), + 20 => closures::discarded(log, id, at), + 21 => closures::blasted(log, id, at), 13 => iters::looped(log, id, at), 14 => iters::collected(log, id, at), 15 => iters::drained(log, id, at), diff --git a/ts/fixtures/task/src/drops/closures.rs b/ts/fixtures/task/src/drops/closures.rs new file mode 100644 index 000000000..c4559c560 --- /dev/null +++ b/ts/fixtures/task/src/drops/closures.rs @@ -0,0 +1,210 @@ +//! What a closure drops of the values it owns: where it goes out of scope, where std +//! discards it uncalled, and where a call consumes it, a panic included. + +use super::Bomb; +use crate::log::Log; +use crate::model::Guard; + +/// Call `f` once, which consumes it. +fn once(f: impl FnOnce() -> R) -> R { + f() +} + +/// Call `f` with each of `n` and `n + 1`, which borrows it, and drop it. +fn twice(n: u32, mut f: impl FnMut(u32) -> u32) -> u32 { + f(n) + f(n + 1) +} + +/// The id of `bomb`, which a closure that calls it captures whole, where one that reads +/// its field captures only that. +fn bomb_id(bomb: &Bomb) -> u32 { + bomb.id +} + +/// Hold `f`, which drops with it. +struct Holder { + f: F, + guard: Guard, +} + +/// What closures that own guards drop, panicking at point `at`, if any, some inside a +/// closure's body. +pub(super) fn scoped(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + // Out of scope uncalled, or called by reference and then dropped, as the scope ends or + // a panic unwinds it. + let (a, b) = (guard(1), guard(2)); + let unused = move || a.id() + b.id(); + let c = guard(3); + let read = move |n: u32| n + c.id(); + log.note(format!("read {}", read(1) + read(2))); + check(1); + drop(unused); + // A body that moves what it owns out drops it there; one that keeps it drops it as it + // returns, or as a panic in it unwinds. + let d = guard(4); + let moved = once(move || { + let n = d.id(); + drop(d); + log.note(format!("moved {n}")); + n + }); + log.note(format!("moved {moved}")); + let e = guard(5); + let kept = once(move || { + check(2); + e.id() + }); + log.note(format!("kept {kept}")); + // One that `Fn` calls, consumed by a call through `FnOnce`, drops after it, or as a + // panic in it unwinds. + let f = guard(6); + let by_ref = move || { + check(3); + f.id() + }; + log.note(format!("by ref {}", once(by_ref))); + let g = guard(7); + log.note(format!("twice {}", twice(1, move |n| n + g.id()))); + // Held in a struct, and in a closure that owns it. + let h = guard(8); + let holder = Holder { + f: move |n: u32| n + h.id(), + guard: guard(9), + }; + log.note(format!("holder {}", (holder.f)(1) + holder.guard.id())); + let i = guard(10); + let inner = move |n: u32| n + i.id(); + let outer = move || inner(1); + check(4); + log.note(format!("outer {}", once(outer))); + drop(holder); + // Changing what it owns, through `FnMut`. + let mut held = Vec::new(); + let mut push = move |g: Guard| { + held.push(g); + held.len() + }; + push(guard(11)); + push(guard(12)); + check(5); + drop(push); +} + +/// What std does with a closure that owns a guard: drops it where it is not called, and +/// leaves it to the call where it is. +pub(super) fn discarded(log: &Log, id: u32, at: u8) { + let guard = |n: u32| Guard::new(id + n, log.clone()); + let check = |point: u8| { + if point == at { + panic!("d{id} at {point}"); + } + }; + let some = if at < 8 { Some(id) } else { None }; + let none = if at > 8 { Some(id) } else { None }; + let (a, b) = (guard(1), guard(2)); + let mapped = some.map(move |n| { + check(1); + n + a.id() + }); + let unmapped = none.map(move |n| n + b.id()); + log.note(format!("map {mapped:?} {unmapped:?}")); + let ok = Ok::(id); + let err = Err::(id); + let (c, d, e, f) = (guard(3), guard(4), guard(5), guard(6)); + let values = (ok.map(move |n| n + c.id()), err.map(move |n| n + d.id())); + let errors = ( + ok.map_err(move |n| n + e.id()), + err.map_err(move |n| { + check(2); + n + f.id() + }), + ); + log.note(format!("result {values:?} {errors:?}")); + let (g, h) = (guard(7), guard(8)); + let chained = ( + ok.and_then(move |n| Ok::(n + g.id())), + err.and_then(move |n| Ok::(n + h.id())), + ); + let (i, j) = (guard(9), guard(10)); + let inspected = ( + ok.inspect_err(move |_| log.note(format!("inspect {}", i.id()))), + err.inspect_err(move |_| { + check(3); + log.note(format!("inspect {}", j.id())) + }), + ); + log.note(format!("chained {chained:?} {inspected:?}")); + let (k, l) = (guard(11), guard(12)); + let defaults = ( + some.map_or(0, move |n| { + check(4); + n + k.id() + }), + none.map_or(0, move |n| n + l.id()), + ); + log.note(format!("map_or {defaults:?}")); + // One that `Fn` calls, which std consumes by `FnOnce`: called, then dropped. + let (o, p) = (guard(15), guard(16)); + let plus = move |n: u32| { + check(5); + n + o.id() + }; + let other = move |n: u32| n + p.id(); + log.note(format!("by ref {:?} {:?}", some.map(plus), none.map(other))); + // A closure that owns one that owns a guard, as a helper's would. + let q = guard(17); + let inner = move |n: u32| n + q.id(); + log.note(format!( + "nested {:?}", + some.map(move |n| { + check(6); + inner(n) + }) + )); + check(7); +} + +/// What drops of a closure's captures when one's `Drop` panics: the rest still drop, in +/// order, and the panic goes on. +pub(super) fn blasted(log: &Log, id: u32, at: u8) { + let bomb = |n: u32, blows: bool| Bomb { + id: id + n, + log: log.clone(), + blows, + }; + let guard = |n: u32| Guard::new(id + n, log.clone()); + match at { + 0 => { + let (a, b, c) = (bomb(1, false), bomb(2, true), guard(3)); + let f = move || bomb_id(&a) + bomb_id(&b) + c.id(); + log.note(format!("blasted {}", f())); + } + 1 => { + let (a, b) = (bomb(1, true), guard(2)); + drop(None::.map(move |n| n + bomb_id(&a) + b.id())); + } + 2 => { + let (a, b) = (bomb(1, true), guard(2)); + drop(once(move || bomb_id(&a) + b.id())); + } + 3 => { + let (a, b) = (bomb(1, true), guard(2)); + let f = move || bomb_id(&a) + b.id(); + drop(once(f)); + } + _ => { + let (a, b) = (bomb(1, true), guard(2)); + let f = move || bomb_id(&a) + b.id(); + let g = move || f(); + let h = guard(3); + drop(g); + drop(h); + } + } +} diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 1d32dbcf8..0720b7ee3 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -87,24 +87,33 @@ export function resultErr(r: Result, drop?: (value: T) => void): E | return undefined; } -/** `Result::map`. */ -export function resultMap(r: Result, f: (value: T) => U): Result { - return r.ok ? Ok(f(r.value)) : r; +/** `Result::map`: `f` of the value, or else the error, and `f` drops. */ +export function resultMap(r: Result, f: (value: T) => U, dropF?: (f: (value: T) => U) => void): Result { + if (r.ok) return Ok(f(r.value)); + dropF?.(f); + return r; } -/** `Result::map_err`. */ -export function resultMapErr(r: Result, f: (error: E) => F): Result { - return r.ok ? r : Err(f(r.error)); +/** `Result::map_err`: `f` of the error, or else the value, and `f` drops. */ +export function resultMapErr(r: Result, f: (error: E) => F, dropF?: (f: (error: E) => F) => void): Result { + if (!r.ok) return Err(f(r.error)); + dropF?.(f); + return r; } -/** `Result::and_then`. */ -export function resultAndThen(r: Result, f: (value: T) => Result): Result { - return r.ok ? f(r.value) : r; +/** `Result::and_then`: `f` of the value, or else the error, and `f` drops. */ +export function resultAndThen(r: Result, f: (value: T) => Result, dropF?: (f: (value: T) => Result) => void): Result { + if (r.ok) return f(r.value); + dropF?.(f); + return r; } -/** `Result::inspect_err`, whose error drops if `f` panics. */ -export function resultInspectErr(r: Result, f: (error: E) => void, drop?: (error: E) => void): Result { - if (r.ok) return r; +/** `Result::inspect_err`, whose error drops if `f` panics, and `f` on a value. */ +export function resultInspectErr(r: Result, f: (error: E) => void, drop?: (error: E) => void, dropF?: (f: (error: E) => void) => void): Result { + if (r.ok) { + dropF?.(f); + return r; + } try { f(r.error); } catch (e) { @@ -144,9 +153,11 @@ export function resultUnwrapErr(r: Result, debug: Debug, drop?: ( // Options, which are `T | undefined`. -/** `Option::map`. */ -export function optionMap(o: T | undefined, f: (value: T) => U): U | undefined { - return o === undefined ? undefined : f(o); +/** `Option::map`: `f` of the value, or else `undefined`, and `f` drops. */ +export function optionMap(o: T | undefined, f: (value: T) => U, dropF?: (f: (value: T) => U) => void): U | undefined { + if (o !== undefined) return f(o); + dropF?.(f); + return undefined; } /** `Option::unwrap_or`: the value, and the fallback drops, or else the fallback. */ diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 42b48ea09..f87b0df2b 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -33,6 +33,30 @@ export function dropRange(values: ArrayLike, f: (value: T) => void, from: } } +// Closures. One that owns a value that drops is an arrow function with +// `[Symbol.dispose]`, which drops what it owns. Calling one that `FnOnce` calls consumes +// it, as its body drops what it owns; one that `Fn` or `FnMut` call drops after a call +// through `FnOnce`, as rustc's shim does. + +/** A closure `f`, which owns what `dispose` drops. */ +export function closure unknown>(f: F, dispose: () => void): F & Disposable { + return Object.assign(f, { [Symbol.dispose]: dispose }); +} + +/** `FnOnce::call_once` of a closure that `Fn` or `FnMut` call: `f(...args)`, then `f` drops, a panic included. */ +export function callOnce(f: (...args: A) => R, ...args: A): R { + try { + return f(...args); + } finally { + drop(f); + } +} + +/** A closure that `Fn` or `FnMut` call, as one `FnOnce` calls: a call drops it after. */ +export function once(f: (...args: A) => R): ((...args: A) => R) & Disposable { + return closure((...args: A) => callOnce(f, ...args), () => drop(f)); +} + // Shared ownership /** `Arc`: every clone is this one object, counted. */ diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 1f4fe34bc..53a5cd90f 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -131,7 +131,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } None => false, }, - ty::Coroutine(..) | ty::Param(_) => true, + // A closure's `[Symbol.dispose]` drops what it owns. + ty::Closure(..) | ty::Coroutine(..) | ty::Param(_) => true, _ => false, } } @@ -269,14 +270,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { let rustc = match ty.kind() { ty::Tuple(_) => true, ty::Adt(adt, _) => adt.is_enum() || adt.did().is_local(), - ty::Closure(..) => { - // Its captures live in an arrow function's scope, where nothing outside can drop them. - self.err( - span, - "dropping a closure that owns a value that drops, which is not supported yet", - ); - return None; - } _ => false, }; if rustc && let Some(sym) = super::mir::glue::shim(self, ty, span) { @@ -309,9 +302,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { let body = self.drop_value(Expr::ident("value"), ty, span)?; return Some(Expr::Lambda(vec![param], Box::new(body))); } - if let ty::Closure(..) = ty.kind() { - return self.drop_glue_call(Expr::undefined(), ty, span); - } super::mir::glue::shim(self, ty, span).map(Expr::Sym) } @@ -354,6 +344,23 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } } + /// Statements dropping what a closure of type `ty` owns, whose captures are `captures`: + /// each that drops, in order, the rest still dropping after one panics, as rustc's glue + /// drops a closure. Its `[Symbol.dispose]`, and what ends an `FnOnce` body that drops + /// its closure whole. + pub fn closure_glue(&mut self, ty: Ty<'tcx>, captures: &[Expr], span: Span) -> Vec { + let ty::Closure(_, args) = ty.kind() else { + unreachable!("closure glue of a closure") + }; + let mut steps = Vec::new(); + for (capture, ty) in captures.iter().zip(args.as_closure().upvar_tys()) { + if let Some(dropped) = self.drop_value(capture.clone(), ty, span) { + steps.push((dropped, self.drop_panics(ty, &mut Default::default()))); + } + } + unwinding(steps) + } + /// Give a class whose own fields or `Drop` impl drop its drop glue up front, so JS /// that holds one can drop it. One that drops only through a type parameter gets /// it once an instance that drops does. diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 6dcb23832..4cfe61ec4 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -402,14 +402,71 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { ("Result", "err") => &[0], ("Result", "unwrap_or") => &[0, 1], // `unwrap` and `expect` drop the error they panic with, `unwrap_err` the value, and - // `inspect_err` its error if its closure panics. - ("Result", "unwrap" | "expect" | "inspect_err") => &[1], + // `inspect_err::` its error if its closure panics, and its closure on a value. + ("Result", "unwrap" | "expect") => &[1], + ("Result", "inspect_err") => &[1, 2], ("Result", "unwrap_err") => &[0], ("bool", "then_some") => &[0], _ => return None, }) } +/// The first closure `call` calls that owns a value that drops, of those its mapping does +/// not drop where std would: not in `discarded`, the types it may drop by their index among +/// the call's type arguments. A closure that `Fn` or `FnMut` call, given to one that calls +/// it through `FnOnce`, becomes `rt.once` of it, which drops it after the call, as rustc's +/// shim does. +fn called_closures<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + discarded: Option<&[usize]>, + args: &mut [Expr], +) -> Option> { + let tcx = b.t.tcx; + let sig = tcx.fn_sig(call.def_id).instantiate_identity().skip_norm_wip(); + let inputs = tcx.instantiate_bound_regions_with_erased(sig).inputs().to_vec(); + let bounds = tcx.param_env(call.def_id).caller_bounds(); + for (i, input) in inputs.into_iter().enumerate() { + let ty::Param(param) = *input.kind() else { + continue; + }; + let ty = call.args[param.index as usize].expect_ty(); + let ty::Closure(_, closure) = ty.kind() else { + continue; + }; + // The trait it is called by: `Fn`, then `FnMut`, whichever it is bound by, or else `FnOnce`. + let Some(bound) = bounds + .clone() + .filter_map(|p| p.as_trait_clause()) + .filter(|t| t.self_ty().skip_binder() == input) + .filter_map(|t| tcx.fn_trait_kind_from_def_id(t.def_id())) + .min_by_key(|kind| match kind { + ty::ClosureKind::Fn => 0, + ty::ClosureKind::FnMut => 1, + ty::ClosureKind::FnOnce => 2, + }) + else { + continue; + }; + if !b.t.drops(ty) { + continue; + } + let index = call.args[..param.index as usize] + .iter() + .filter(|a| a.as_type().is_some()) + .count(); + if !discarded.is_some_and(|d| d.contains(&index)) { + return Some(ty); + } + if bound == ty::ClosureKind::FnOnce && closure.as_closure().kind() != ty::ClosureKind::FnOnce && i < args.len() + { + let f = std::mem::replace(&mut args[i], Expr::undefined()); + args[i] = Expr::rt("once", vec![f]); + } + } + None +} + /// The first type `call` takes by value that drops. fn dropping_operand<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>) -> Option> { let tcx = b.t.tcx; @@ -469,6 +526,32 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec return None; } let (owner, name) = key(tcx, call.def_id)?; + let discarded = discards(&owner, &name); + let mut args = args; + let leaked = called_closures(b, call, discarded, &mut args); + let e = mapping(b, call, owner.clone(), name.clone(), discarded, args, out)?; + if let Some(ty) = leaked { + return Some(b.err( + call.span, + format!( + "passing `{ty}`, a closure that owns a value that drops, to `{owner}::{name}`, which is not supported yet" + ), + )); + } + Some(e) +} + +/// The mapping of a call of std's `owner::name`, which may discard what `discarded` says. +fn mapping<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + owner: String, + name: String, + discarded: Option<&'static [usize]>, + args: Vec, + out: &mut Vec, +) -> Option { + let tcx = b.t.tcx; let span = call.span; let gargs = call.args; let args = match super::task::call(b, call, &owner, &name, args) { @@ -479,7 +562,6 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec Ok(e) => return e, Err(args) => args, }; - let discarded = discards(&owner, &name); let dropping = match discarded { Some(_) => None, None => dropping_operand(b, call), diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 290ef6f4a..bee57d36c 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -207,6 +207,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return self.b.call_def(inner, inner_args.skip_binder(), values, span, out); } let f = self.operand(&callee.node, span, out); + // `FnOnce::call_once` of a closure that `Fn` or `FnMut` call drops it after, + // as rustc's shim does, where an `FnOnce` closure's body drops what it owns. + if tcx.fn_trait_kind_from_def_id(trait_id) == Some(ty::ClosureKind::FnOnce) + && let ty::Closure(_, closure) = callee_ty.kind() + && closure.as_closure().kind() != ty::ClosureKind::FnOnce + && self.b.t.drops(callee_ty) + { + return Expr::rt("callOnce", [vec![f], values].concat()); + } return f.call(values); } // A function of the crate gets what JS passes, so a `&mut` to a number can't reach it. diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 1d9aa8d63..74a08775d 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2158,7 +2158,24 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { TerminatorKind::SwitchInt { discr, targets } => self.switch(discr, targets, span, out), TerminatorKind::Drop { place, target, .. } => { let ty = place.ty(&self.mir.local_decls, self.tcx).ty; - if self.b.t.drops(ty) { + // An `FnOnce` body drops its closure whole, which is what it captured. + if let Env::Closure(captures) = &self.env + && place.local.as_u32() == 1 + && place.projection.is_empty() + { + let mut glue = self.b.t.closure_glue(ty, &captures.clone(), span); + // In a block of its own, whose variable no other drop's can clash with. + if glue.iter().any(|s| matches!(s.kind, StmtKind::Decl { .. })) { + glue = vec![ + StmtKind::Block { + label: None, + body: glue, + } + .at(None), + ]; + } + self.emit(glue, None, false, out); + } else if self.b.t.drops(ty) { let mut pre = Vec::new(); let value = self.place_expr(*place, span, &mut pre); let dropped = match place.as_local().is_some_and(|l| self.stepped.contains(&l)) { diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 24d5900d8..91ccb342a 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -11,7 +11,7 @@ use super::{Env, Fx, Slot}; use crate::lower::library::Std; use crate::lower::num::{self, Int}; use crate::lower::{AdtRepr, field_name}; -use crate::ts::{Expr, Key, Stmt, StmtKind}; +use crate::ts::{Expr, Key, Stmt, StmtKind, Type}; impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { /// The value of `rvalue`, assigned to `dest`, or `None` if it has none to assign. @@ -455,10 +455,20 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { .b .t .ret_ty(sig.output(), mir.local_decls[mir::RETURN_PLACE].source_info.span); + let ty = Ty::new_closure(tcx, def_id, args); + let glue = match self.b.t.drops(ty) { + true => Some(self.b.t.closure_glue(ty, &captures, span)), + false => None, + }; let mut inner = Fx::new(&mut *self.b, &mir, Env::Closure(captures), span); let params = inner.params(); let body = inner.lower(); - Expr::Arrow(params, ret, body) + let f = Expr::Arrow(params, ret, body); + // One that owns what drops carries the glue that drops it. + match glue { + Some(glue) => Expr::rt("closure", vec![f, Expr::Arrow(Vec::new(), Type::Builtin("void"), glue)]), + None => f, + } } } diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 3ea7207bb..f9d314f30 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -281,5 +281,5 @@ export const cases: Uint8Array[] = [ [0, 0, 12, 0, 6, 0, 3, 5, 6, 0], [0, 0, 12, 0, 12, 1, 6, 0, 9, 1, 9, 0], // Each scenario of values std holds that drop, panicking at each point or none. - ...Array.from({ length: 152 }, (_, arg) => [11, arg]), + ...Array.from({ length: 176 }, (_, arg) => [11, arg]), ].map((script) => Uint8Array.from(script)); From 37cccfa948b6473d99f0bdd6b8edff8c395da660 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:42:28 -0700 Subject: [PATCH 12/18] fix(ts): drop a closure whole only where it is one Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/src/lower/mir/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 74a08775d..09a525fb0 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2162,6 +2162,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { if let Env::Closure(captures) = &self.env && place.local.as_u32() == 1 && place.projection.is_empty() + && matches!(ty.kind(), ty::Closure(..)) { let mut glue = self.b.t.closure_glue(ty, &captures.clone(), span); // In a block of its own, whose variable no other drop's can clash with. From 2c01ac1d9c00176d55151d8f545b36fa50e93488 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:59:12 -0700 Subject: [PATCH 13/18] perf(ts): drop-aware iterator paths as functions a bundle can leave out std's `nth`, `advance_by`, `count` and `last` drop items in an order each kind of iterator has its own. These were methods on every adaptor, which a bundler can't drop, so every bundle carried them. They are now module-private dispatchers on the kind, reached only through `rt.owned*` functions the translation calls where an item or the iterator drops; the plain `rt.iterCount`, `iterLast`, `iterNth`, `iterSkip`, `iterTake` and `iterStepBy` take no droppers. `[Symbol.dispose]` stays a method where `rt.drop` calls it without knowing the kind: an iterator that owns items, and an adaptor, which drops what it wraps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 56 +- ts/runtime/rt/collections.ts | 35 +- ts/runtime/rt/iter.ts | 1457 ++++++++++++---------- ts/src/lower/iter.rs | 35 +- 4 files changed, 849 insertions(+), 734 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 13446f143..ac17a5aea 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -196,7 +196,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const _162: Guard.Guard = guard(16); v3.push(_162); unwind = 327; - rest = rt.iterTake(rt.iterSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); + rest = rt.ownedTake(rt.ownedSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); unwind = 356; _610 = true; const arg4 = ([rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { @@ -219,7 +219,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["next ", args8[0]])); check(3); _610 = false; - const arg5 = ([rt.iterCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; + const arg5 = ([rt.ownedCount(rest, rt.drop, rt.drop)] as [rt.usize])[0]; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg5, f)]; Log.note(log, rt.fmtFormat(["count ", args10[0]])); v4 = []; @@ -269,7 +269,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const pairs: rt.Iter<[Guard.Guard, Guard.Guard]> = rt.iterZip(_237, rt.iterSlice(_255, rt.drop), false, rt.drop, rt.drop); unwind = 323; _608 = false; - const arg6 = ([rt.iterCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; + const arg6 = ([rt.ownedCount(pairs, rt.drop, drop$Guard_Guard)] as [rt.usize])[0]; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(arg6, f)]; Log.note(log, rt.fmtFormat(["zip ", args14[0]])); v7 = []; @@ -294,7 +294,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _607 = false; _275 = rt.iterRev(_276); unwind = 318; - nth = rt.iterNth(_275, 1, rt.drop); + nth = rt.ownedNth(_275, 1, rt.drop); unwind = 348; _606 = true; rt.drop(_275); @@ -407,7 +407,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const _418: Guard.Guard = guard(38); v12.push(_418); unwind = 314; - const _427: rt.u32 = rt.optionMapOr(rt.iterLast(rt.iterStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { + const _427: rt.u32 = rt.optionMapOr(rt.ownedLast(rt.ownedStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { unwind6 = 4; @@ -514,18 +514,18 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e9; } }; - _501 = rt.iterSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); + _501 = rt.ownedSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); unwind = 307; - _499 = rt.iterToOption(_501.nthBackItem(3, rt.drop)); + _499 = rt.ownedNthBack(_501, 3, rt.drop); unwind = 306; const skipped: boolean = _499 !== undefined; unwind = 307; rt.drop(_499); unwind = 344; rt.drop(_501); - _509 = rt.iterStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); + _509 = rt.ownedStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); unwind = 305; - const stepped: rt.u32 = rt.optionMapOr(rt.iterToOption(_509.nthBackItem(1, rt.drop)), 0, (g16: Guard.Guard): rt.u32 => { + const stepped: rt.u32 = rt.optionMapOr(rt.ownedNthBack(_509, 1, rt.drop), 0, (g16: Guard.Guard): rt.u32 => { let unwind10: number = 0; try { unwind10 = 4; @@ -543,7 +543,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_509); - _518 = rt.iterRev(rt.iterTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); + _518 = rt.iterRev(rt.ownedTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); unwind = 342; _603 = true; const _524: Guard.Guard[] = []; @@ -551,7 +551,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); unwind = 304; _603 = false; - const taken: rt.u32 = rt.optionMapOr(rt.iterNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { + const taken: rt.u32 = rt.optionMapOr(rt.ownedNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { let unwind11: number = 0; try { unwind11 = 4; @@ -569,7 +569,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_517); - _529 = rt.iterRev(rt.iterSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); + _529 = rt.iterRev(rt.ownedSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); unwind = 340; _602 = true; const _535: Guard.Guard[] = []; @@ -577,7 +577,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); unwind = 303; _602 = false; - const passed: rt.u32 = rt.optionMapOr(rt.iterNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { + const passed: rt.u32 = rt.optionMapOr(rt.ownedNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { let unwind12: number = 0; try { unwind12 = 4; @@ -595,9 +595,9 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_528); - _539 = rt.iterStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); + _539 = rt.ownedStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); unwind = 302; - const strode: rt.u32 = rt.optionMapOr(rt.iterNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { + const strode: rt.u32 = rt.optionMapOr(rt.ownedNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { let unwind13: number = 0; try { unwind13 = 4; @@ -615,7 +615,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { }); unwind = 344; rt.drop(_539); - const counted: rt.usize = rt.iterCount(rt.iterTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop); + const counted: rt.usize = rt.ownedCount(rt.ownedTake(rt.iterRev(rt.iterSlice(five(74), rt.drop)), 3, rt.drop), rt.drop, rt.drop); const far: boolean = rt.iterToOption(rt.iterStepBy(new rt.Range(0, 10), 4294967295).nthBackItem(4294967295)) === undefined; const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(skipped, f), (f: rt.Formatter) => rt.u32Display(stepped, f), (f: rt.Formatter) => rt.u32Display(taken, f), (f: rt.Formatter) => rt.u32Display(passed, f), (f: rt.Formatter) => rt.u32Display(strode, f), (f: rt.Formatter) => rt.usizeDisplay(counted, f), (f: rt.Formatter) => rt.fmtBool(far, f)]; Log.note(log, rt.fmtFormat(["back ", args24[0], " ", args24[1], " ", args24[2], " ", args24[3], " ", args24[4], " ", args24[5], " ", args24[6]])); @@ -1601,7 +1601,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { _290 = true; check(7); _291 = false; - const _249: rt.usize = rt.iterCount(values2, rt.drop, rt.drop); + const _249: rt.usize = rt.ownedCount(values2, rt.drop, rt.drop); const _252: boolean = one !== undefined; const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_249, f), (f: rt.Formatter) => rt.fmtBool(_252, f)]; Log.note(log, rt.fmtFormat(["rest ", args16[0], " ", args16[1]])); @@ -2223,7 +2223,7 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _43: Bomb.Bomb = bomb(2, false); v2.push(_43); unwind = 0; - _32 = rt.iterSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); + _32 = rt.ownedSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); unwind = 109; rt.drop(rt.iterToOption(_32.next())); unwind = 0; @@ -2238,7 +2238,7 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _63: Bomb.Bomb = bomb(3, false); v3.push(_63); unwind = 0; - rt.iterCount(rt.iterFilter(rt.iterSlice(v3, rt.drop), (b: Bomb.Bomb): boolean => { + rt.ownedCount(rt.iterFilter(rt.iterSlice(v3, rt.drop), (b: Bomb.Bomb): boolean => { return !b.blows; }, rt.drop), rt.drop, rt.drop); } else if (at === 3) { @@ -2296,7 +2296,7 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { const _144: Bomb.Bomb = bomb(3, false); v5.push(_144); unwind = 0; - rt.iterCount(rt.iterTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.ownedTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); } else { v6 = []; unwind = 104; @@ -2459,7 +2459,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(rt.hashInsert(map, n, _23, undefined, rt.drop)); } _176 = false; - rt.iterCount(rt.hashIter(map, undefined, rt.drop), rt.drop, drop$u32_First); + rt.ownedCount(rt.hashIter(map, undefined, rt.drop), rt.drop, drop$u32_First); _176 = false; } else if (at === 1) { unwind = 114; @@ -2473,7 +2473,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.hashAdd(set, _40, rt.drop); } _175 = false; - rt.iterCount(rt.hashKeys(set, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.hashKeys(set, rt.drop), rt.drop, rt.drop); _175 = false; } else if (at === 2) { unwind = 114; @@ -2486,7 +2486,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { const _64: First.First = first(2); v.push(_64); unwind = 114; - rt.iterCount(rt.iterSkip(rt.iterSlice(v, rt.drop), 1, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.ownedSkip(rt.iterSlice(v, rt.drop), 1, rt.drop), rt.drop, rt.drop); } else if (at === 3) { unwind = 114; v2 = []; @@ -2503,7 +2503,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { _174 = true; rt.peekablePeek(peek) !== undefined; _174 = false; - rt.iterCount(peek, rt.drop, rt.drop); + rt.ownedCount(peek, rt.drop, rt.drop); _174 = false; } else if (at === 4) { unwind = 114; @@ -2527,7 +2527,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { const _95: rt.Iter = rt.iterChain(_96, rt.iterSlice(_104, rt.drop)); unwind = 114; _173 = false; - rt.iterCount(_95, rt.drop, rt.drop); + rt.ownedCount(_95, rt.drop, rt.drop); } else if (at === 5) { unwind = 114; map2 = rt.btreeNew(rt.cmp) as rt.BTreeMap; @@ -2541,7 +2541,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(rt.btreeInsert(map2, n3, _126, undefined, rt.drop)); } _172 = false; - rt.iterCount(rt.btreeIter(map2, undefined, rt.drop), rt.drop, drop$u32_First); + rt.ownedCount(rt.btreeIter(map2, undefined, rt.drop), rt.drop, drop$u32_First); _172 = false; } else if (at === 6) { unwind = 114; @@ -2555,7 +2555,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.dequePushBack(queue, _143); } _171 = false; - rt.iterCount(rt.dequeIter(queue, rt.drop), rt.drop, rt.drop); + rt.ownedCount(rt.dequeIter(queue, rt.drop), rt.drop, rt.drop); _171 = false; } else { unwind = 114; @@ -2568,7 +2568,7 @@ export function spent(log: Log.Log, id: rt.u32, at: rt.u8): void { const _160: First.First = first(n5); rt.drop(rt.hashInsert(map3, n5, _160, undefined, rt.drop)); } - rt.iterCount(rt.hashDrain(map3, undefined, rt.drop), rt.drop, drop$u32_First); + rt.ownedCount(rt.hashDrain(map3, undefined, rt.drop), rt.drop, drop$u32_First); unwind = 114; rt.hashDrop(map3, undefined, rt.drop); } diff --git a/ts/runtime/rt/collections.ts b/ts/runtime/rt/collections.ts index b715fda2a..70c627ef7 100644 --- a/ts/runtime/rt/collections.ts +++ b/ts/runtime/rt/collections.ts @@ -573,16 +573,16 @@ const VALUES = 2; * One that owns its entries is given what drops each key and value of those that drop, * and drops each entry it still holds as it drops. */ -class HashIter extends Iter { +export class HashIter extends Iter implements Disposable { private readonly p: Iterator<[K, V]>; private readonly o: Iterator> | undefined; private at: Slot | undefined; private readonly pick: Pick; - private left: number; + left: number; private readonly k: ((key: K) => void) | undefined; private readonly v: ((value: V) => void) | undefined; /** Whether it is a `drain`, whose `count` reads each entry, as an `into_iter`'s does not. */ - private readonly drain: boolean; + readonly drain: boolean; constructor(m: HashMap, pick: Pick, k?: (key: K) => void, v?: (value: V) => void, drain = false) { super(); @@ -617,15 +617,7 @@ class HashIter extends Iter { return this.left; } - /** std's `into_iter`'s: its length, and then each entry drops with it. */ - override countItems(drop?: (item: T) => void): number { - if (this.drain) return super.countItems(drop); - const n = this.left; - this[Symbol.dispose](); - return n; - } - - override [Symbol.dispose](): void { + [Symbol.dispose](): void { if (this.k === undefined && this.v === undefined) return; // A panic leaves the entries after it undropped, as std's table does, even as what // consumed it drops it again. @@ -1209,7 +1201,7 @@ export function btreeRetain(m: BTreeMap, f: (key: K, value: V) => bo * owns its entries drops as `HashIter` does, but a panic dropping one still drops the * rest, as std's B-trees do. */ -class BTreeIter extends Iter { +export class BTreeIter extends Iter implements Disposable { fl: Leaf; fi: number; bl: Leaf; @@ -1220,7 +1212,7 @@ class BTreeIter extends Iter { private readonly k: ((key: K) => void) | undefined; private readonly v: ((value: V) => void) | undefined; /** Whether its `last` reads from the back, as a map's `into_keys`' and `into_values`' do. */ - private readonly back: boolean; + readonly back: boolean; constructor(pick: Pick, fl: Leaf, fi: number, bl: Leaf, bi: number, n = -1, k?: (key: K) => void, v?: (value: V) => void, back = false) { super(); @@ -1286,16 +1278,7 @@ class BTreeIter extends Iter { return this.n; } - /** std's `into_keys`' and `into_values`': the last, and then the rest drop with it. */ - override lastItem(drop?: (item: T) => void): T | Done { - if (!this.back) return super.lastItem(drop); - const last = this.nextBack(); - // A panic here leaks the last, as std's unwinding does a returned value. - this[Symbol.dispose](); - return last; - } - - override [Symbol.dispose](): void { + [Symbol.dispose](): void { if (this.k === undefined && this.v === undefined) return; const keys: K[] = []; const values: V[] = []; @@ -1829,7 +1812,7 @@ export function dequeInsert(q: VecDeque, i: number, item: T): void { * An iterator of a deque's items from index `front` up to `back`, which drops those it * still holds by `drop` as it drops, if it owns them, as a `drain` does. */ -class DequeIter extends Iter { +class DequeIter extends Iter implements Disposable { private readonly q: VecDeque; private front: number; private back: number; @@ -1855,7 +1838,7 @@ class DequeIter extends Iter { return this.back - this.front; } - override [Symbol.dispose](): void { + [Symbol.dispose](): void { if (this.drop === undefined) return; const items: T[] = []; while (this.front < this.back) items.push(this.q.b[at(this.q, this.front++)] as T); diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index b9dd26f73..455021bd9 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -12,11 +12,15 @@ // each, and drops those it still holds as it drops, by `[Symbol.dispose]`; an adaptor // drops what it wraps. Where std drops an item it skips, rejects, or replaces, the runtime // function is given what drops it, after its own arguments, and so is a consumer that -// takes the iterator by value, which drops it as std's does, a panic included. +// takes the iterator by value, which drops it as std's does, a panic included. Where +// std's `nth`, `advance_by`, `count`, and `last` drop items in an order each kind of +// iterator has its own, the `owned` functions follow it, dispatching on the kind, so a +// bundle that never drops an item carries none of it. import { ByteVec, byteVecPush, Err, Ok, panic, type Result } from "../rt.ts"; +import { BTreeIter, HashIter } from "./collections.ts"; import { type Limbs, lt as wideLt, type Step } from "./int.ts"; -import { dropAll, dropRange } from "./task.ts"; +import { drop as dispose, dropAll, dropRange } from "./task.ts"; /** What `next` returns once an iterator is exhausted, which no item is. */ export const DONE: unique symbol = /* @__PURE__ */ Symbol("DONE"); @@ -31,7 +35,7 @@ const USIZE_MAX = 0xffffffff; type Drop = (value: T) => void; /** `Iterator`: `next`, and the methods std's iterators each do their own way. */ -export abstract class Iter implements Iterable, Disposable { +export abstract class Iter implements Iterable { /** The next item, or `DONE`. */ abstract next(): T | Done; @@ -45,79 +49,18 @@ export abstract class Iter implements Iterable, Disposable { throw new Error("rust2-ts: an iterator without `len`"); } - /** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ - advanceBy(n: number, drop?: Drop): number { - for (let i = 0; i < n; i++) { - const item = this.next(); - if (item === DONE) return n - i; - drop?.(item); - } - return 0; - } - - /** `advance_back_by`, from the back. */ - advanceBackBy(n: number, drop?: Drop): number { - for (let i = 0; i < n; i++) { - const item = this.nextBack(); - if (item === DONE) return n - i; - drop?.(item); - } - return 0; - } - - /** `nth`, as `next` returns it, dropping what it skips by `drop`. */ - nthItem(n: number, drop?: Drop): T | Done { - return this.advanceBy(n, drop) === 0 ? this.next() : DONE; - } - - /** `nth_back`, as `next_back` returns it. */ - nthBackItem(n: number, drop?: Drop): T | Done { - return this.advanceBackBy(n, drop) === 0 ? this.nextBack() : DONE; - } - - /** `count`, dropping each item by `drop`. */ - countItems(drop?: Drop): number { - let n = 0; - if (drop === undefined) { - while (this.next() !== DONE) n++; - return n; - } - for (let item = this.next(); item !== DONE; item = this.next()) { - drop(item); - n++; - } - return n; + /** `nth` of items that don't drop, as `next` returns it. */ + nthItem(n: number): T | Done { + for (let i = 0; i < n; i++) if (this.next() === DONE) return DONE; + return this.next(); } - /** - * `last`, as std's `fold` takes it: each item drops by `drop` as the next replaces it. - * A panic reading the next drops the last; one dropping it leaks the next, as std's - * unwinding leaves a returned value. - */ - lastItem(drop?: Drop): T | Done { - let last: T | Done = DONE; - if (drop === undefined) { - for (let item = this.next(); item !== DONE; item = this.next()) last = item; - return last; - } - for (;;) { - let item: T | Done; - try { - item = this.next(); - } catch (e) { - if (last !== DONE) drop(last); - throw e; - } - if (item === DONE) return last; - const prev = last; - last = item; - if (prev !== DONE) drop(prev); - } + /** `nth_back` of items that don't drop, as `next_back` returns it. */ + nthBackItem(n: number): T | Done { + for (let i = 0; i < n; i++) if (this.nextBack() === DONE) return DONE; + return this.nextBack(); } - /** Drop what it owns and still holds: nothing, unless it was made owning its items. */ - [Symbol.dispose](): void {} - /** Its items, for a JS `for ... of`. */ *[Symbol.iterator](): Iterator { for (let item = this.next(); item !== DONE; item = this.next()) yield item; @@ -125,7 +68,7 @@ export abstract class Iter implements Iterable, Disposable { } /** An adaptor of `inner`, which drops with it. */ -abstract class Adaptor extends Iter { +abstract class Adaptor extends Iter implements Disposable { readonly inner: Iter; constructor(inner: Iter) { @@ -133,8 +76,8 @@ abstract class Adaptor extends Iter { this.inner = inner; } - override [Symbol.dispose](): void { - this.inner[Symbol.dispose](); + [Symbol.dispose](): void { + dispose(this.inner); } } @@ -258,14 +201,14 @@ export function iterRev(it: Iter): Iter { return new RevIter(it); } -/** `Iterator::skip`, dropping what it skips by `drop`. */ -export function iterSkip(it: Iter, n: number, drop?: Drop): Iter { - return new SkipIter(it, n, drop); +/** `Iterator::skip` of items that don't drop. */ +export function iterSkip(it: Iter, n: number): Iter { + return new SkipIter(it, n); } -/** `Iterator::take`, dropping what `next_back` skips past its limit by `drop`. */ -export function iterTake(it: Iter, n: number, drop?: Drop): Iter { - return new TakeIter(it, n, drop); +/** `Iterator::take` of items that don't drop. */ +export function iterTake(it: Iter, n: number): Iter { + return new TakeIter(it, n); } /** `Iterator::skip_while`, dropping what it skips by `drop`. */ @@ -283,9 +226,9 @@ export function iterMapWhile(it: Iter, f: (item: T) => U | undefined): return new MapWhileIter(it, f); } -/** `Iterator::step_by`, panicking on a step of 0, and dropping what it steps over by `drop`. */ -export function iterStepBy(it: Iter, step: number, drop?: Drop): Iter { - return new StepByIter(it, step, drop); +/** `Iterator::step_by` of items that don't drop, panicking on a step of 0. */ +export function iterStepBy(it: Iter, step: number): Iter { + return new StepByIter(it, step); } /** `Iterator::inspect`, dropping the item `f` panics on by `drop`. */ @@ -326,34 +269,23 @@ export function iterFlatten(it: Iter, into?: (value: T) => Iter, fus // Consumers. Each that takes the iterator by value drops it by `dropIt` once done, or as // a panic unwinds through it. -/** `Iterator::count`, dropping each item by `drop`. */ -export function iterCount(it: Iter, dropIt?: Drop>, drop?: Drop): number { - if (dropIt === undefined) return it.countItems(drop); - try { - return it.countItems(drop); - } finally { - dropIt(it); - } +/** `Iterator::count` of an iterator that drops nothing. */ +export function iterCount(it: Iter): number { + let n = 0; + while (it.next() !== DONE) n++; + return n; } -/** `Iterator::last`, dropping each item but the last by `drop`. */ -export function iterLast(it: Iter, dropIt?: Drop>, drop?: Drop): T | undefined { - if (dropIt === undefined) return iterToOption(it.lastItem(drop)); - let last: T | Done; - try { - last = it.lastItem(drop); - } catch (e) { - dropIt(it); - throw e; - } - // A panic here leaks the last, as std's unwinding does a returned value. - dropIt(it); +/** `Iterator::last` of an iterator that drops nothing. */ +export function iterLast(it: Iter): T | undefined { + let last: T | Done = DONE; + for (let item = it.next(); item !== DONE; item = it.next()) last = item; return iterToOption(last); } -/** `Iterator::nth`, dropping what it skips by `drop`. */ -export function iterNth(it: Iter, n: number, drop?: Drop): T | undefined { - return iterToOption(it.nthItem(n, drop)); +/** `Iterator::nth` of items that don't drop. */ +export function iterNth(it: Iter, n: number): T | undefined { + return iterToOption(it.nthItem(n)); } /** `Iterator::any`. */ @@ -625,10 +557,616 @@ export function iterCollectOption(it: Iter, into: (values: return undefined; } -class SliceIter extends Iter { - private readonly s: ArrayLike; - private front = 0; - private back: number; +// What std's iterators override to skip, count, or take the last: `nth`, `advance_by`, +// `count`, and `last`, each of which drops items in an order of its own kind's. These +// follow it, dispatching on the kind, rather than as methods every iterator would carry, +// and the translation calls them only where an item or the iterator drops. + +/** `Iterator::count` of an iterator that drops what it holds: each item by `drop`, as its own `count` does, and then it by `dropIt`, a panic included. */ +export function ownedCount(it: Iter, dropIt?: Drop>, drop?: Drop): number { + try { + return count(it, drop); + } finally { + dropIt?.(it); + } +} + +/** `Iterator::last` of an iterator that drops what it holds: each item but the last by `drop`, as its own `last` does, and then it by `dropIt`. */ +export function ownedLast(it: Iter, dropIt?: Drop>, drop?: Drop): T | undefined { + let item: T | Done; + try { + item = last(it, drop); + } catch (e) { + dropIt?.(it); + throw e; + } + // A panic here leaks the last, as std's unwinding does a returned value. + dropIt?.(it); + return iterToOption(item); +} + +/** `Iterator::nth`, dropping what it skips by `drop`, as its own `nth` does. */ +export function ownedNth(it: Iter, n: number, drop: Drop): T | undefined { + return iterToOption(nth(it, n, drop)); +} + +/** `DoubleEndedIterator::nth_back`, dropping what it skips by `drop`, as its own `nth_back` does. */ +export function ownedNthBack(it: Iter, n: number, drop: Drop): T | undefined { + return iterToOption(nthBack(it, n, drop)); +} + +/** `Iterator::skip`, dropping what it skips by `drop`, through its iterator's own `nth`. */ +export function ownedSkip(it: Iter, n: number, drop: Drop): Iter { + return new OwnedSkip(it, n, drop); +} + +/** `Iterator::take`, dropping what `next_back` skips past its limit by `drop`. */ +export function ownedTake(it: Iter, n: number, drop: Drop): Iter { + return new OwnedTake(it, n, drop); +} + +/** `Iterator::step_by`, panicking on a step of 0, and dropping what it steps over by `drop`. */ +export function ownedStepBy(it: Iter, step: number, drop: Drop): Iter { + return new OwnedStepBy(it, step, drop); +} + +/** `advance_by`: skip up to `n` items, each dropped by `drop`, and return how many it fell short. */ +function advance(it: Iter, n: number, drop: Drop | undefined): number { + if (it instanceof SliceIter) { + // std's, of a `Vec`'s: past them all first, then each dropped, as a slice drops. + const step = Math.min(n, it.back - it.front); + const from = it.front; + it.front += step; + if (drop !== undefined) dropRange(it.s, drop, from, it.front); + return n - step; + } + if (it instanceof Borrowed) return advance(it.inner, n, drop); + if (it instanceof EnumerateIter) { + // std's, which counts what its iterator skipped. + const left = advance(it.inner, n, items(drop)); + it.index += n - left; + return left; + } + if (it instanceof ChainIter) { + if (it.a !== undefined) { + n = advance(it.a, n, drop); + if (n === 0) return 0; + it.endA(); + } + return it.b === undefined ? n : advance(it.b, n, drop); + } + if (it instanceof RevIter) return advanceBack(it.inner, n, drop); + if (it instanceof SkipIter) { + const skip = it.n; + const left = advance(it.inner, skip + n, drop); + const advanced = skip + n - left; + it.n = Math.max(skip - advanced, 0); + return n - Math.max(advanced - skip, 0); + } + if (it instanceof TakeIter) { + const min = Math.min(it.n, n); + const advanced = min - advance(it.inner, min, drop); + it.n -= advanced; + return n - advanced; + } + if (it instanceof FuseIter) { + if (it.inner === undefined) return n; + const left = advance(it.inner, n, drop); + if (left > 0) it.clear(DONE); + return left; + } + if (it instanceof FlattenIter) return flattenAdvance(it, n, drop); + for (let i = 0; i < n; i++) { + const item = it.next(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; +} + +/** `advance_back_by`, from the back. */ +function advanceBack(it: Iter, n: number, drop: Drop | undefined): number { + if (it instanceof SliceIter) { + // std's: those it skips drop front to back, as a slice drops. + const step = Math.min(n, it.back - it.front); + it.back -= step; + if (drop !== undefined) dropRange(it.s, drop, it.back, it.back + step); + return n - step; + } + if (it instanceof Borrowed) return advanceBack(it.inner, n, drop); + if (it instanceof EnumerateIter) return advanceBack(it.inner, n, items(drop)); + if (it instanceof ChainIter) { + if (it.b !== undefined) { + n = advanceBack(it.b, n, drop); + if (n === 0) return 0; + it.endB(); + } + return it.a === undefined ? n : advanceBack(it.a, n, drop); + } + if (it instanceof RevIter) return advance(it.inner, n, drop); + if (it instanceof SkipIter) { + // std's: its iterator advanced from the back in one step, short of what it skips. + const min = Math.min(it.len(), n); + advanceBack(it.inner, min, drop); + return n - min; + } + if (it instanceof TakeIter) { + // std's: its iterator advanced from the back past the limit and `n` more, in one step. + const trim = Math.max(it.inner.len() - it.n, 0); + const advanced = trim + n - advanceBack(it.inner, trim + n, drop) - trim; + it.n -= advanced; + return n - advanced; + } + if (it instanceof FuseIter) { + if (it.inner === undefined) return n; + const left = advanceBack(it.inner, n, drop); + if (left > 0) it.clear(DONE); + return left; + } + if (it instanceof FlattenIter) return flattenAdvanceBack(it, n, drop); + for (let i = 0; i < n; i++) { + const item = it.nextBack(); + if (item === DONE) return n - i; + drop?.(item); + } + return 0; +} + +/** `nth`, as `next` returns it, dropping what it skips by `drop`. */ +function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { + // Skipping items that don't drop, each kind's own `nth` reads the same items. + if (drop === undefined) return it.nthItem(n); + if (it instanceof Borrowed) return nth(it.inner, n, drop); + if (it instanceof EnumerateIter) { + // std's, which counts only when it finds an item. + const item = nth(it.inner, n, items(drop)); + if (item === DONE) return DONE; + const i = it.index + n; + it.index = i + 1; + return [i, item] as T; + } + if (it instanceof ChainIter) { + if (it.a !== undefined) { + n = advance(it.a, n, drop); + if (n === 0) { + const item = it.a.next(); + if (item !== DONE) return item; + } + it.endA(); + } + return it.b === undefined ? DONE : nth(it.b, n, drop); + } + if (it instanceof RevIter) return nthBack(it.inner, n, drop); + if (it instanceof SkipIter) { + // std's: what it still skips and then `n` more, in one step. + const skip = it.n; + it.n = 0; + return nth(it.inner, skip + n, drop); + } + if (it instanceof TakeIter) { + // std's: past the limit, it reads the rest of the limit through, drops it, and ends. + if (it.n > n) { + it.n -= n + 1; + return nth(it.inner, n, drop); + } + if (it.n > 0) { + const item = nth(it.inner, it.n - 1, drop); + if (item !== DONE) drop(item); + it.n = 0; + } + return DONE; + } + if (it instanceof StepByIter) return stepByNth(it, n, drop); + if (it instanceof FuseIter) return it.inner === undefined ? DONE : it.clear(nth(it.inner, n, drop)); + if (it instanceof Peekable) { + // std's: the item it peeked drops after what its iterator skips. + if (!it.peeked) return nth(it.inner, n, drop); + const peeked = it.take(); + if (peeked === DONE) return DONE; + if (n === 0) return peeked; + let item: T | Done; + try { + item = nth(it.inner, n - 1, drop); + } catch (e) { + drop(peeked); + throw e; + } + // A panic here leaks the item, as std's unwinding does a returned value. + drop(peeked); + return item; + } + return advance(it, n, drop) === 0 ? it.next() : DONE; +} + +/** + * `StepBy::nth`, std's: the first item, dropped unless it is the one, then every step in + * one `nth`, as many as a `usize` counts at a time. + */ +function stepByNth(it: StepByIter, n: number, drop: Drop): T | Done { + if (it.firstTake) { + it.firstTake = false; + const first = it.inner.next(); + if (first === DONE || n === 0) return first; + drop(first); + n -= 1; + } + let step = it.step + 1; + if (n === USIZE_MAX) { + const item = nth(it.inner, step - 1, drop); + if (item === DONE) return DONE; + drop(item); + } else { + n += 1; + } + for (;;) { + if (n * step <= USIZE_MAX) return nth(it.inner, n * step - 1, drop); + const byN = Math.floor(USIZE_MAX / n) * n; + const byStep = Math.floor(USIZE_MAX / step) * step; + if (byN > byStep) step -= Math.floor(USIZE_MAX / n); + else n -= Math.floor(USIZE_MAX / step); + const item = nth(it.inner, Math.max(byN, byStep) - 1, drop); + if (item === DONE) return DONE; + drop(item); + } +} + +/** `nth_back`, as `next_back` returns it. */ +function nthBack(it: Iter, n: number, drop: Drop | undefined): T | Done { + if (drop === undefined) return it.nthBackItem(n); + if (it instanceof Borrowed) return nthBack(it.inner, n, drop); + if (it instanceof EnumerateIter) { + const item = nthBack(it.inner, n, items(drop)); + return item === DONE ? DONE : ([it.index + it.inner.len(), item] as T); + } + if (it instanceof ChainIter) { + if (it.b !== undefined) { + n = advanceBack(it.b, n, drop); + if (n === 0) { + const item = it.b.nextBack(); + if (item !== DONE) return item; + } + it.endB(); + } + return it.a === undefined ? DONE : nthBack(it.a, n, drop); + } + if (it instanceof RevIter) return nth(it.inner, n, drop); + if (it instanceof SkipIter) { + // std's: past what it doesn't skip, its iterator read from the back through what it does. + const len = it.len(); + if (n < len) return nthBack(it.inner, n, drop); + if (len > 0) { + const item = nthBack(it.inner, len - 1, drop); + if (item !== DONE) drop(item); + } + return DONE; + } + if (it instanceof TakeIter) { + // std's: past the limit, it reads the whole rest from the back, even at a limit of 0. + const len = it.inner.len(); + if (it.n > n) { + const m = Math.max(len - it.n, 0) + n; + it.n -= n + 1; + return nthBack(it.inner, m, drop); + } + if (len > 0) { + const item = nthBack(it.inner, len - 1, drop); + if (item !== DONE) drop(item); + } + return DONE; + } + if (it instanceof StepByIter) { + // std's: every step from the back in one, saturating at a `usize`'s greatest. + const steps = Math.min(n * (it.step + 1), USIZE_MAX); + return nthBack(it.inner, Math.min(steps + it.backIndex(), USIZE_MAX), drop); + } + if (it instanceof FuseIter) return it.inner === undefined ? DONE : it.clear(nthBack(it.inner, n, drop)); + return advanceBack(it, n, drop) === 0 ? it.nextBack() : DONE; +} + +/** `count`, dropping each item by `drop`. */ +function count(it: Iter, drop: Drop | undefined): number { + if (it instanceof EnumerateIter) return count(it.inner, items(drop)); + if (it instanceof ChainIter) { + // std's: each iterator's own `count`, the first's first. + const a = it.a; + it.a = undefined; + const n = a === undefined ? 0 : consumed(a, () => count(a, drop)); + const b = it.b; + it.b = undefined; + return n + (b === undefined ? 0 : consumed(b, () => count(b, drop))); + } + if (it instanceof SkipIter) { + // std's: past what it skips by `nth`, and then its iterator's own `count`. + if (skipped(it, drop)) return 0; + return consumed(it.inner, () => count(it.inner, drop)); + } + if (it instanceof TakeIter) { + // std's: its iterator advanced through the limit, dropping what it passes. + if (it.n === 0) return 0; + const n = it.n; + it.n = 0; + return n - advance(it.inner, n, drop); + } + if (it instanceof FuseIter) { + const inner = it.inner; + it.inner = undefined; + return inner === undefined ? 0 : consumed(inner, () => count(inner, drop)); + } + if (it instanceof FlattenIter) { + // std's: each iterator's own `count` in turn, each dropped once counted. + let n = 0; + flattenEach(it, (inner) => { + n += consumed(inner, () => count(inner, drop)); + }); + return n; + } + if (it instanceof Peekable) { + // std's: the item it peeked drops after its iterator is counted. + if (!it.peeked) return consumed(it.inner, () => count(it.inner, drop)); + const peeked = it.take(); + if (peeked === DONE) return 0; + try { + return 1 + consumed(it.inner, () => count(it.inner, drop)); + } finally { + drop?.(peeked); + } + } + if (it instanceof HashIter && !it.drain) { + // std's `into_iter`'s: its length, and then each entry drops with it. + const n = it.left; + dispose(it); + return n; + } + let n = 0; + for (let item = it.next(); item !== DONE; item = it.next()) { + drop?.(item); + n++; + } + return n; +} + +/** + * `last`, as std's `fold` takes it: each item drops by `drop` as the next replaces it. + * A panic reading the next drops the last; one dropping it leaks the next, as std's + * unwinding leaves a returned value. + */ +function last(it: Iter, drop: Drop | undefined): T | Done { + if ((it instanceof SliceIter && drop !== undefined) || (it instanceof BTreeIter && it.back)) { + // std's, of a `Vec`'s or an array's, and of a B-tree's `into_keys` and + // `into_values`: the last item, and then the rest drop with it. + const item = it.nextBack(); + // A panic here leaks the last, as std's unwinding does a returned value. + dispose(it); + return item; + } + if (it instanceof ChainIter) { + // std's: each iterator's last, the first's held while the second is read, and + // dropped once the second has one. + const a = it.a; + it.a = undefined; + const aLast = a === undefined ? DONE : consumed(a, () => last(a, drop)); + const b = it.b; + it.b = undefined; + if (b === undefined) return aLast; + let bLast: T | Done; + try { + bLast = consumed(b, () => last(b, drop)); + } catch (e) { + if (aLast !== DONE) drop?.(aLast); + throw e; + } + if (bLast === DONE) return aLast; + // A panic here leaks the second's, as std's unwinding does a returned value. + if (aLast !== DONE) drop?.(aLast); + return bLast; + } + if (it instanceof SkipIter) { + // std's: past what it skips by `nth`, and then its iterator's own `last`. + if (skipped(it, drop)) return DONE; + return consumed(it.inner, () => last(it.inner, drop)); + } + if (it instanceof FuseIter) { + const inner = it.inner; + it.inner = undefined; + return inner === undefined ? DONE : consumed(inner, () => last(inner, drop)); + } + if (it instanceof FlattenIter) return flattenLast(it, drop); + if (it instanceof Peekable) { + // std's: the item it peeked, unless its iterator has a last, which drops it after. + let peeked: T | Done = DONE; + if (it.peeked) { + peeked = it.take(); + if (peeked === DONE) return DONE; + } + let item: T | Done; + try { + item = consumed(it.inner, () => last(it.inner, drop)); + } catch (e) { + if (peeked !== DONE) drop?.(peeked); + throw e; + } + if (item === DONE) return peeked; + // A panic here leaks the last, as std's unwinding does a returned value. + if (peeked !== DONE) drop?.(peeked); + return item; + } + let item: T | Done = DONE; + if (drop === undefined) { + for (let next = it.next(); next !== DONE; next = it.next()) item = next; + return item; + } + for (;;) { + let next: T | Done; + try { + next = it.next(); + } catch (e) { + if (item !== DONE) drop(item); + throw e; + } + if (next === DONE) return item; + const prev = item; + item = next; + if (prev !== DONE) drop(prev); + } +} + +/** + * `f()`, a consumer of `it` by value, and then `it` dropped, as a panic unwinds too; a + * panic dropping it leaks what `f` returned, as std's unwinding does. + */ +function consumed(it: Iter, f: () => R): R { + let r: R; + try { + r = f(); + } catch (e) { + dispose(it); + throw e; + } + dispose(it); + return r; +} + +/** What drops an `enumerate`'s item, of one its iterator yields: `drop` is of `[number, T]`. */ +function items(drop: Drop | undefined): Drop | undefined { + return drop === undefined ? undefined : (item) => drop([0, item] as never); +} + +/** Read past what `it` still skips, as `nth` reads, and whether its iterator ended first. */ +function skipped(it: SkipIter, drop: Drop | undefined): boolean { + if (it.n === 0) return false; + const n = it.n; + it.n = 0; + const item = nth(it.inner, n - 1, drop); + if (item === DONE) return true; + drop?.(item); + return false; +} + +/** + * `Flatten::advance_by`, std's, by `try_fold`: each iterator in turn advanced by its own + * `advance_by`, one that falls short dropped only as the next replaces it, and the source + * dropped once it ends unless it is fused. + */ +function flattenAdvance(it: FlattenIter, n: number, drop: Drop | undefined): number { + if (it.front !== undefined) { + n = advance(it.front, n, drop); + if (n === 0) return 0; + } + it.setFront(undefined); + const outer = it.outer; + if (outer !== undefined) { + for (let inner = outer.next(); inner !== DONE; inner = outer.next()) { + const front = it.into(inner); + it.setFront(front); + n = advance(front, n, drop); + if (n === 0) return 0; + } + if (!it.fused) { + it.outer = undefined; + dispose(outer); + } + } + it.setFront(undefined); + if (it.back !== undefined) { + n = advance(it.back, n, drop); + if (n === 0) return 0; + } + it.setBack(undefined); + return n; +} + +/** `Flatten::advance_back_by`, from the back. */ +function flattenAdvanceBack(it: FlattenIter, n: number, drop: Drop | undefined): number { + if (it.back !== undefined) { + n = advanceBack(it.back, n, drop); + if (n === 0) return 0; + } + it.setBack(undefined); + const outer = it.outer; + if (outer !== undefined) { + for (let inner = outer.nextBack(); inner !== DONE; inner = outer.nextBack()) { + const back = it.into(inner); + it.setBack(back); + n = advanceBack(back, n, drop); + if (n === 0) return 0; + } + if (!it.fused) { + it.outer = undefined; + dispose(outer); + } + } + it.setBack(undefined); + if (it.front !== undefined) { + n = advanceBack(it.front, n, drop); + if (n === 0) return 0; + } + it.setFront(undefined); + return n; +} + +/** + * Run `f` on each iterator of `it` in turn, the front, each of the source's, and the back, + * as std's `fold` takes them by value; the source drops once read through. + */ +function flattenEach(it: FlattenIter, f: (inner: Iter) => void, onPanic?: () => void): void { + const front = it.front; + it.front = undefined; + if (front !== undefined) f(front); + const outer = it.outer; + it.outer = undefined; + if (outer !== undefined) { + consumed(outer, () => { + for (;;) { + let inner: T | Done; + try { + inner = outer.next(); + } catch (e) { + onPanic?.(); + throw e; + } + if (inner === DONE) return; + f(it.into(inner)); + } + }); + } + const back = it.back; + it.back = undefined; + if (back !== undefined) f(back); +} + +/** + * `Flatten::last`, std's: the last of each iterator in turn, each dropped once read, and + * the last so far dropped once a later one has one. + */ +function flattenLast(it: FlattenIter, drop: Drop | undefined): V | Done { + let item: V | Done = DONE; + const take = (inner: Iter): void => { + let next: V | Done; + try { + next = consumed(inner, () => last(inner, drop)); + } catch (e) { + if (item !== DONE) drop?.(item); + throw e; + } + if (next === DONE) return; + const prev = item; + item = next; + // A panic here leaks the later one, as std's unwinding does a returned value. + if (prev !== DONE) drop?.(prev); + }; + flattenEach(it, take, () => { + if (item !== DONE) drop?.(item); + }); + return item; +} + +// Iterators. One has `[Symbol.dispose]` if it owns items or wraps an iterator: what holds +// it drops it by `rt.drop`, not knowing its kind. + +class SliceIter extends Iter implements Disposable { + readonly s: ArrayLike; + front = 0; + back: number; /** What drops each item it still holds, if it owns them. */ private readonly drop: Drop | undefined; @@ -651,33 +1189,7 @@ class SliceIter extends Iter { return this.back - this.front; } - /** std's, of a `Vec`'s: past them all first, then each dropped, as a slice drops. */ - override advanceBy(n: number, drop?: Drop): number { - const step = Math.min(n, this.back - this.front); - const from = this.front; - this.front += step; - if (drop !== undefined) dropRange(this.s, drop, from, this.front); - return n - step; - } - - /** std's: those it skips drop front to back, as a slice drops. */ - override advanceBackBy(n: number, drop?: Drop): number { - const step = Math.min(n, this.back - this.front); - this.back -= step; - if (drop !== undefined) dropRange(this.s, drop, this.back, this.back + step); - return n - step; - } - - /** std's, of a `Vec`'s or an array's: the last item, then the rest drop with it. */ - override lastItem(drop?: Drop): T | Done { - if (drop === undefined) return super.lastItem(); - const last = this.nextBack(); - // A panic here leaks the last, as std's unwinding does a returned value. - this[Symbol.dispose](); - return last; - } - - override [Symbol.dispose](): void { + [Symbol.dispose](): void { if (this.drop === undefined) return; const from = this.front; this.front = this.back; @@ -686,7 +1198,7 @@ class SliceIter extends Iter { } /** `option::IntoIter`, `Once`, and `Empty`: at most one item. */ -class OptionIter extends Iter { +class OptionIter extends Iter implements Disposable { private item: T | undefined; private some: boolean; private readonly drop: Drop | undefined; @@ -714,7 +1226,7 @@ class OptionIter extends Iter { return this.some ? 1 : 0; } - override [Symbol.dispose](): void { + [Symbol.dispose](): void { if (this.drop === undefined) return; const item = this.next(); if (item !== DONE) this.drop(item); @@ -722,7 +1234,7 @@ class OptionIter extends Iter { } /** An iterator whose `next` is a function of its source, which `drop` drops. */ -class FromNext extends Iter { +class FromNext extends Iter implements Disposable { private readonly source: S; private readonly step: (source: S) => T | Done; private drop: Drop | undefined; @@ -738,15 +1250,25 @@ class FromNext extends Iter { return this.step(this.source); } - override [Symbol.dispose](): void { + [Symbol.dispose](): void { const drop = this.drop; this.drop = undefined; drop?.(this.source); } -} +} + +/** + * An iterator borrowed by `&mut`, which forwards only what std's `impl Iterator for &mut + * I` does, and which dropping drops nothing. + */ +class Borrowed extends Iter { + readonly inner: Iter; + + constructor(inner: Iter) { + super(); + this.inner = inner; + } -/** An iterator borrowed by `&mut`: dropping it drops nothing. */ -class Borrowed extends Adaptor { next(): T | Done { return this.inner.next(); } @@ -759,23 +1281,13 @@ class Borrowed extends Adaptor { return this.inner.len(); } - override advanceBy(n: number, drop?: Drop): number { - return this.inner.advanceBy(n, drop); - } - - override advanceBackBy(n: number, drop?: Drop): number { - return this.inner.advanceBackBy(n, drop); - } - - override nthItem(n: number, drop?: Drop): T | Done { - return this.inner.nthItem(n, drop); + override nthItem(n: number): T | Done { + return this.inner.nthItem(n); } - override nthBackItem(n: number, drop?: Drop): T | Done { - return this.inner.nthBackItem(n, drop); + override nthBackItem(n: number): T | Done { + return this.inner.nthBackItem(n); } - - override [Symbol.dispose](): void {} } class MapIter extends Adaptor { @@ -846,7 +1358,7 @@ class FilterMapIter extends Adaptor { } class EnumerateIter extends Adaptor { - private index = 0; + index = 0; next(): [number, T] | Done { const item = this.inner.next(); @@ -858,52 +1370,32 @@ class EnumerateIter extends Adaptor { return item === DONE ? DONE : [this.index + this.inner.len(), item]; } - /** std's, which counts what its iterator skipped. */ - override advanceBy(n: number, drop?: Drop<[number, T]>): number { - const left = this.inner.advanceBy(n, items(drop)); - this.index += n - left; - return left; - } - - override advanceBackBy(n: number, drop?: Drop<[number, T]>): number { - return this.inner.advanceBackBy(n, items(drop)); - } - /** std's `nth`, which counts only when it finds an item. */ - override nthItem(n: number, drop?: Drop<[number, T]>): [number, T] | Done { - const item = this.inner.nthItem(n, items(drop)); + override nthItem(n: number): [number, T] | Done { + const item = this.inner.nthItem(n); if (item === DONE) return DONE; const i = this.index + n; this.index = i + 1; return [i, item]; } - override nthBackItem(n: number, drop?: Drop<[number, T]>): [number, T] | Done { - const item = this.inner.nthBackItem(n, items(drop)); + override nthBackItem(n: number): [number, T] | Done { + const item = this.inner.nthBackItem(n); return item === DONE ? DONE : [this.index + this.inner.len(), item]; } - override countItems(drop?: Drop<[number, T]>): number { - return this.inner.countItems(items(drop)); - } - override len(): number { return this.inner.len(); } } -/** What drops an `enumerate`'s item, of one its iterator yields. */ -function items(drop: Drop<[number, T]> | undefined): Drop | undefined { - return drop === undefined ? undefined : (item) => drop([0, item]); -} - /** * `Chain`, which drops its first iterator once it ends, but not its second, as std's * stops reading it. */ -class ChainIter extends Iter { - private a: Iter | undefined; - private b: Iter | undefined; +class ChainIter extends Iter implements Disposable { + a: Iter | undefined; + b: Iter | undefined; constructor(a: Iter, b: Iter) { super(); @@ -912,17 +1404,17 @@ class ChainIter extends Iter { } /** Drop `a`, which ended. */ - private endA(): void { + endA(): void { const a = this.a; this.a = undefined; - a?.[Symbol.dispose](); + dispose(a); } /** Drop `b`, which ended from the back. */ - private endB(): void { + endB(): void { const b = this.b; this.b = undefined; - b?.[Symbol.dispose](); + dispose(b); } next(): T | Done { @@ -943,83 +1435,7 @@ class ChainIter extends Iter { return this.a === undefined ? DONE : this.a.nextBack(); } - override advanceBy(n: number, drop?: Drop): number { - if (this.a !== undefined) { - n = this.a.advanceBy(n, drop); - if (n === 0) return 0; - this.endA(); - } - return this.b === undefined ? n : this.b.advanceBy(n, drop); - } - - override advanceBackBy(n: number, drop?: Drop): number { - if (this.b !== undefined) { - n = this.b.advanceBackBy(n, drop); - if (n === 0) return 0; - this.endB(); - } - return this.a === undefined ? n : this.a.advanceBackBy(n, drop); - } - - override nthItem(n: number, drop?: Drop): T | Done { - if (this.a !== undefined) { - n = this.a.advanceBy(n, drop); - if (n === 0) { - const item = this.a.next(); - if (item !== DONE) return item; - } - this.endA(); - } - return this.b === undefined ? DONE : this.b.nthItem(n, drop); - } - - override nthBackItem(n: number, drop?: Drop): T | Done { - if (this.b !== undefined) { - n = this.b.advanceBackBy(n, drop); - if (n === 0) { - const item = this.b.nextBack(); - if (item !== DONE) return item; - } - this.endB(); - } - return this.a === undefined ? DONE : this.a.nthBackItem(n, drop); - } - - /** std's: each iterator's own `count`, the first's first. */ - override countItems(drop?: Drop): number { - const a = this.a; - this.a = undefined; - const n = a === undefined ? 0 : consumed(a, () => a.countItems(drop)); - const b = this.b; - this.b = undefined; - return n + (b === undefined ? 0 : consumed(b, () => b.countItems(drop))); - } - - /** - * std's: each iterator's last, the first's held while the second is read, and dropped - * once the second has one. - */ - override lastItem(drop?: Drop): T | Done { - const a = this.a; - this.a = undefined; - const aLast = a === undefined ? DONE : consumed(a, () => a.lastItem(drop)); - const b = this.b; - this.b = undefined; - if (b === undefined) return aLast; - let bLast: T | Done; - try { - bLast = consumed(b, () => b.lastItem(drop)); - } catch (e) { - if (aLast !== DONE) drop?.(aLast); - throw e; - } - if (bLast === DONE) return aLast; - // A panic here leaks the second's, as std's unwinding does a returned value. - if (aLast !== DONE) drop?.(aLast); - return bLast; - } - - override [Symbol.dispose](): void { + [Symbol.dispose](): void { both( () => this.endA(), () => this.endB(), @@ -1027,23 +1443,7 @@ class ChainIter extends Iter { } } -/** - * `f()`, a consumer of `it` by value, and then `it` dropped, as a panic unwinds too; a - * panic dropping it leaks what `f` returned, as std's unwinding does. - */ -function consumed(it: Iter, f: () => R): R { - let r: R; - try { - r = f(); - } catch (e) { - it[Symbol.dispose](); - throw e; - } - it[Symbol.dispose](); - return r; -} - -class ZipIter extends Iter<[A, B]> { +class ZipIter extends Iter<[A, B]> implements Disposable { protected readonly a: Iter; protected readonly b: Iter; private readonly dropA: Drop | undefined; @@ -1102,10 +1502,10 @@ class ZipIter extends Iter<[A, B]> { return Math.min(this.a.len(), this.b.len()); } - override [Symbol.dispose](): void { + [Symbol.dispose](): void { both( - () => this.a[Symbol.dispose](), - () => this.b[Symbol.dispose](), + () => dispose(this.a), + () => dispose(this.b), ); } } @@ -1146,20 +1546,12 @@ class RevIter extends Adaptor { return this.inner.next(); } - override advanceBy(n: number, drop?: Drop): number { - return this.inner.advanceBackBy(n, drop); - } - - override advanceBackBy(n: number, drop?: Drop): number { - return this.inner.advanceBy(n, drop); - } - - override nthItem(n: number, drop?: Drop): T | Done { - return this.inner.nthBackItem(n, drop); + override nthItem(n: number): T | Done { + return this.inner.nthBackItem(n); } - override nthBackItem(n: number, drop?: Drop): T | Done { - return this.inner.nthItem(n, drop); + override nthBackItem(n: number): T | Done { + return this.inner.nthItem(n); } override len(): number { @@ -1168,95 +1560,52 @@ class RevIter extends Adaptor { } class SkipIter extends Adaptor { - private n: number; - private readonly drop: Drop | undefined; + n: number; - constructor(inner: Iter, n: number, drop?: Drop) { + constructor(inner: Iter, n: number) { super(inner); this.n = n; - this.drop = drop; } next(): T | Done { if (this.n === 0) return this.inner.next(); const n = this.n; this.n = 0; - return this.inner.nthItem(n, this.drop); + return this.inner.nthItem(n); } override nextBack(): T | Done { return this.len() > 0 ? this.inner.nextBack() : DONE; } - /** std's: past what it doesn't skip, its iterator read from the back through what it does. */ - override nthBackItem(n: number, drop?: Drop): T | Done { - const len = this.len(); - if (n < len) return this.inner.nthBackItem(n, drop); - if (len > 0) { - const item = this.inner.nthBackItem(len - 1, drop); - if (item !== DONE) drop?.(item); - } - return DONE; - } - - /** std's: its iterator advanced from the back in one step, short of what it skips. */ - override advanceBackBy(n: number, drop?: Drop): number { - const min = Math.min(this.len(), n); - this.inner.advanceBackBy(min, drop); - return n - min; - } - - /** std's: what it still skips and then `n` more, in one step. */ - override nthItem(n: number, drop?: Drop): T | Done { - const skip = this.n; - this.n = 0; - return this.inner.nthItem(skip + n, drop); - } - - override advanceBy(n: number, drop?: Drop): number { - const skip = this.n; - const left = this.inner.advanceBy(skip + n, drop); - const advanced = skip + n - left; - this.n = Math.max(skip - advanced, 0); - return n - Math.max(advanced - skip, 0); + override len(): number { + return Math.max(this.inner.len() - this.n, 0); } +} - /** std's: past what it skips by `nth`, and then its iterator's own `count`. */ - override countItems(drop?: Drop): number { - if (this.skipped(drop)) return 0; - return consumed(this.inner, () => this.inner.countItems(drop)); - } +/** `Skip` of items that drop, which drop as its iterator's own `nth` skips them. */ +class OwnedSkip extends SkipIter { + private readonly drop: Drop; - /** std's: past what it skips by `nth`, and then its iterator's own `last`. */ - override lastItem(drop?: Drop): T | Done { - if (this.skipped(drop)) return DONE; - return consumed(this.inner, () => this.inner.lastItem(drop)); + constructor(inner: Iter, n: number, drop: Drop) { + super(inner, n); + this.drop = drop; } - /** Read past what it still skips, as `nth` reads, and whether its iterator ended first. */ - private skipped(drop: Drop | undefined): boolean { - if (this.n === 0) return false; + override next(): T | Done { + if (this.n === 0) return this.inner.next(); const n = this.n; this.n = 0; - const item = this.inner.nthItem(n - 1, drop); - if (item === DONE) return true; - drop?.(item); - return false; - } - - override len(): number { - return Math.max(this.inner.len() - this.n, 0); + return nth(this.inner, n, this.drop); } } class TakeIter extends Adaptor { - private n: number; - private readonly drop: Drop | undefined; + n: number; - constructor(inner: Iter, n: number, drop?: Drop) { + constructor(inner: Iter, n: number) { super(inner); this.n = n; - this.drop = drop; } next(): T | Done { @@ -1265,67 +1614,56 @@ class TakeIter extends Adaptor { return this.inner.next(); } - /** std's: what its iterator holds past the limit drops as it reads from the back. */ + /** std's: what its iterator holds past the limit is read through from the back. */ override nextBack(): T | Done { if (this.n === 0) return DONE; const n = this.n--; - return this.inner.nthBackItem(Math.max(this.inner.len() - n, 0), this.drop); + return this.inner.nthBackItem(Math.max(this.inner.len() - n, 0)); } - /** std's `nth`: past the limit, it reads the rest of the limit through, drops it, and ends. */ - override nthItem(n: number, drop?: Drop): T | Done { + /** std's `nth`: past the limit, it reads the rest of the limit through and ends. */ + override nthItem(n: number): T | Done { if (this.n > n) { this.n -= n + 1; - return this.inner.nthItem(n, drop); + return this.inner.nthItem(n); } if (this.n > 0) { - const item = this.inner.nthItem(this.n - 1, drop); - if (item !== DONE) drop?.(item); + this.inner.nthItem(this.n - 1); this.n = 0; } return DONE; } /** std's `nth_back`: past the limit, it reads the whole rest from the back, even at a limit of 0. */ - override nthBackItem(n: number, drop?: Drop): T | Done { + override nthBackItem(n: number): T | Done { const len = this.inner.len(); if (this.n > n) { const m = Math.max(len - this.n, 0) + n; this.n -= n + 1; - return this.inner.nthBackItem(m, drop); - } - if (len > 0) { - const item = this.inner.nthBackItem(len - 1, drop); - if (item !== DONE) drop?.(item); + return this.inner.nthBackItem(m); } + if (len > 0) this.inner.nthBackItem(len - 1); return DONE; } - /** std's: its iterator advanced through the limit, dropping what it passes. */ - override countItems(drop?: Drop): number { - if (this.n === 0) return 0; - const n = this.n; - this.n = 0; - return n - this.inner.advanceBy(n, drop); + override len(): number { + return Math.min(this.inner.len(), this.n); } +} - override advanceBy(n: number, drop?: Drop): number { - const min = Math.min(this.n, n); - const advanced = min - this.inner.advanceBy(min, drop); - this.n -= advanced; - return n - advanced; - } +/** `Take` of items that drop, which what its iterator holds past the limit drops as `next_back` reads through. */ +class OwnedTake extends TakeIter { + private readonly drop: Drop; - /** std's: its iterator advanced from the back past the limit and `n` more, in one step. */ - override advanceBackBy(n: number, drop?: Drop): number { - const trim = Math.max(this.inner.len() - this.n, 0); - const advanced = trim + n - this.inner.advanceBackBy(trim + n, drop) - trim; - this.n -= advanced; - return n - advanced; + constructor(inner: Iter, n: number, drop: Drop) { + super(inner, n); + this.drop = drop; } - override len(): number { - return Math.min(this.inner.len(), this.n); + override nextBack(): T | Done { + if (this.n === 0) return DONE; + const n = this.n--; + return nthBack(this.inner, Math.max(this.inner.len() - n, 0), this.drop); } } @@ -1393,71 +1731,31 @@ class MapWhileIter extends Adaptor { } class StepByIter extends Adaptor { - private readonly step: number; - private readonly drop: Drop | undefined; - private firstTake = true; + readonly step: number; + firstTake = true; - constructor(inner: Iter, step: number, drop?: Drop) { + constructor(inner: Iter, step: number) { super(inner); // The iterator it was given drops as the panic unwinds. if (step === 0) { - inner[Symbol.dispose](); + dispose(inner); panic("assertion failed: step != 0"); } this.step = step - 1; - this.drop = drop; } next(): T | Done { const n = this.firstTake ? 0 : this.step; this.firstTake = false; - return this.inner.nthItem(n, this.drop); + return this.inner.nthItem(n); } override nextBack(): T | Done { - return this.inner.nthBackItem(this.backIndex(), this.drop); - } - - /** - * std's: the first item, dropped unless it is the one, then every step in one `nth`, as - * many as a `usize` counts at a time. - */ - override nthItem(n: number, drop?: Drop): T | Done { - if (this.firstTake) { - this.firstTake = false; - const first = this.inner.next(); - if (first === DONE || n === 0) return first; - drop?.(first); - n -= 1; - } - let step = this.step + 1; - if (n === USIZE_MAX) { - const item = this.inner.nthItem(step - 1, drop); - if (item === DONE) return DONE; - drop?.(item); - } else { - n += 1; - } - for (;;) { - if (n * step <= USIZE_MAX) return this.inner.nthItem(n * step - 1, drop); - const byN = Math.floor(USIZE_MAX / n) * n; - const byStep = Math.floor(USIZE_MAX / step) * step; - if (byN > byStep) step -= Math.floor(USIZE_MAX / n); - else n -= Math.floor(USIZE_MAX / step); - const item = this.inner.nthItem(Math.max(byN, byStep) - 1, drop); - if (item === DONE) return DONE; - drop?.(item); - } - } - - /** std's: every step from the back in one, saturating at a `usize`'s greatest. */ - override nthBackItem(n: number, drop?: Drop): T | Done { - const steps = Math.min(n * (this.step + 1), USIZE_MAX); - return this.inner.nthBackItem(Math.min(steps + this.backIndex(), USIZE_MAX), drop); + return this.inner.nthBackItem(this.backIndex()); } /** How far from the back its last item is. */ - private backIndex(): number { + backIndex(): number { const rem = this.inner.len() % (this.step + 1); return this.firstTake ? (rem === 0 ? this.step : rem - 1) : rem; } @@ -1469,6 +1767,26 @@ class StepByIter extends Adaptor { } } +/** `StepBy` of items that drop, which drop as its iterator's own `nth` and `nth_back` step over them. */ +class OwnedStepBy extends StepByIter { + private readonly drop: Drop; + + constructor(inner: Iter, step: number, drop: Drop) { + super(inner, step); + this.drop = drop; + } + + override next(): T | Done { + const n = this.firstTake ? 0 : this.step; + this.firstTake = false; + return nth(this.inner, n, this.drop); + } + + override nextBack(): T | Done { + return nthBack(this.inner, this.backIndex(), this.drop); + } +} + class InspectIter extends Adaptor { private readonly f: (item: T) => void; private readonly drop: Drop | undefined; @@ -1500,8 +1818,8 @@ class InspectIter extends Adaptor { } } -class FuseIter extends Iter { - private inner: Iter | undefined; +class FuseIter extends Iter implements Disposable { + inner: Iter | undefined; /** Whether its iterator is a `FusedIterator`, which std's keeps once it ends. */ private readonly fused: boolean; @@ -1512,11 +1830,11 @@ class FuseIter extends Iter { } /** `item`, dropping its iterator first if it ended there and is not fused. */ - private clear(item: T | Done): T | Done { + clear(item: T | Done): T | Done { if (item === DONE && !this.fused) { const inner = this.inner; this.inner = undefined; - inner?.[Symbol.dispose](); + dispose(inner); } return item; } @@ -1529,48 +1847,14 @@ class FuseIter extends Iter { return this.inner === undefined ? DONE : this.clear(this.inner.nextBack()); } - override nthItem(n: number, drop?: Drop): T | Done { - return this.inner === undefined ? DONE : this.clear(this.inner.nthItem(n, drop)); - } - - override nthBackItem(n: number, drop?: Drop): T | Done { - return this.inner === undefined ? DONE : this.clear(this.inner.nthBackItem(n, drop)); - } - - override advanceBy(n: number, drop?: Drop): number { - if (this.inner === undefined) return n; - const left = this.inner.advanceBy(n, drop); - if (left > 0) this.clear(DONE); - return left; - } - - override advanceBackBy(n: number, drop?: Drop): number { - if (this.inner === undefined) return n; - const left = this.inner.advanceBackBy(n, drop); - if (left > 0) this.clear(DONE); - return left; - } - - override countItems(drop?: Drop): number { - const inner = this.inner; - this.inner = undefined; - return inner === undefined ? 0 : consumed(inner, () => inner.countItems(drop)); - } - - override lastItem(drop?: Drop): T | Done { - const inner = this.inner; - this.inner = undefined; - return inner === undefined ? DONE : consumed(inner, () => inner.lastItem(drop)); - } - override len(): number { return this.inner === undefined ? 0 : this.inner.len(); } - override [Symbol.dispose](): void { + [Symbol.dispose](): void { const inner = this.inner; this.inner = undefined; - inner?.[Symbol.dispose](); + dispose(inner); } } @@ -1578,12 +1862,12 @@ class FuseIter extends Iter { * `Flatten` and `FlatMap`: the iterator of each item it reads, which drops once it ends, * as does its source unless it is `fused`. */ -class FlattenIter extends Iter { - private outer: Iter | undefined; - private readonly into: (value: T) => Iter; - private readonly fused: boolean; - private front: Iter | undefined; - private back: Iter | undefined; +class FlattenIter extends Iter implements Disposable { + outer: Iter | undefined; + readonly into: (value: T) => Iter; + readonly fused: boolean; + front: Iter | undefined; + back: Iter | undefined; constructor(outer: Iter, into: (value: T) => Iter, fused: boolean) { super(); @@ -1599,7 +1883,7 @@ class FlattenIter extends Iter { const item = back ? outer.nextBack() : outer.next(); if (item === DONE && !this.fused) { this.outer = undefined; - outer[Symbol.dispose](); + dispose(outer); } return item; } @@ -1607,7 +1891,7 @@ class FlattenIter extends Iter { /** `it`'s next item, from the back if `back`, dropping it if it ended. */ private static step(it: Iter, back: boolean): V | Done { const item = back ? it.nextBack() : it.next(); - if (item === DONE) it[Symbol.dispose](); + if (item === DONE) dispose(it); return item; } @@ -1648,146 +1932,19 @@ class FlattenIter extends Iter { } /** Hold `it` as the front iterator, dropping the one it held, as std's `insert` does. */ - private setFront(it: Iter | undefined): void { + setFront(it: Iter | undefined): void { const old = this.front; this.front = it; - old?.[Symbol.dispose](); + dispose(old); } - private setBack(it: Iter | undefined): void { + setBack(it: Iter | undefined): void { const old = this.back; this.back = it; - old?.[Symbol.dispose](); - } - - /** - * std's, by `try_fold`: each iterator in turn advanced by its own `advance_by`, one that - * falls short dropped only as the next replaces it, and the source dropped once it ends - * unless it is fused. - */ - override advanceBy(n: number, drop?: Drop): number { - if (this.front !== undefined) { - n = this.front.advanceBy(n, drop); - if (n === 0) return 0; - } - this.setFront(undefined); - const outer = this.outer; - if (outer !== undefined) { - for (let inner = outer.next(); inner !== DONE; inner = outer.next()) { - const it = this.into(inner); - this.setFront(it); - n = it.advanceBy(n, drop); - if (n === 0) return 0; - } - if (!this.fused) { - this.outer = undefined; - outer[Symbol.dispose](); - } - } - this.setFront(undefined); - if (this.back !== undefined) { - n = this.back.advanceBy(n, drop); - if (n === 0) return 0; - } - this.setBack(undefined); - return n; + dispose(old); } - override advanceBackBy(n: number, drop?: Drop): number { - if (this.back !== undefined) { - n = this.back.advanceBackBy(n, drop); - if (n === 0) return 0; - } - this.setBack(undefined); - const outer = this.outer; - if (outer !== undefined) { - for (let inner = outer.nextBack(); inner !== DONE; inner = outer.nextBack()) { - const it = this.into(inner); - this.setBack(it); - n = it.advanceBackBy(n, drop); - if (n === 0) return 0; - } - if (!this.fused) { - this.outer = undefined; - outer[Symbol.dispose](); - } - } - this.setBack(undefined); - if (this.front !== undefined) { - n = this.front.advanceBackBy(n, drop); - if (n === 0) return 0; - } - this.setFront(undefined); - return n; - } - - /** std's: each iterator's own `count` in turn, each dropped once counted. */ - override countItems(drop?: Drop): number { - let n = 0; - const count = (it: Iter): void => { - n += consumed(it, () => it.countItems(drop)); - }; - this.consume(count); - return n; - } - - /** - * Run `f` on each iterator in turn, the front, each of the source's, and the back, as - * std's `fold` takes them by value; the source drops once read through. - */ - private consume(f: (it: Iter) => void, onPanic?: () => void): void { - const front = this.front; - this.front = undefined; - if (front !== undefined) f(front); - const outer = this.outer; - this.outer = undefined; - if (outer !== undefined) { - consumed(outer, () => { - for (;;) { - let inner: T | Done; - try { - inner = outer.next(); - } catch (e) { - onPanic?.(); - throw e; - } - if (inner === DONE) return; - f(this.into(inner)); - } - }); - } - const back = this.back; - this.back = undefined; - if (back !== undefined) f(back); - } - - /** - * std's: the last of each iterator in turn, each dropped once read, and the last so far - * dropped once a later one has one. - */ - override lastItem(drop?: Drop): V | Done { - let last: V | Done = DONE; - const take = (it: Iter): void => { - let item: V | Done; - try { - item = consumed(it, () => it.lastItem(drop)); - } catch (e) { - if (last !== DONE) drop?.(last); - throw e; - } - if (item === DONE) return; - const prev = last; - last = item; - // A panic here leaks the later one, as std's unwinding does a returned value. - if (prev !== DONE) drop?.(prev); - }; - this.consume(take, () => { - if (last !== DONE) drop?.(last); - }); - return last; - } - - override [Symbol.dispose](): void { + [Symbol.dispose](): void { const outer = this.outer; const front = this.front; const back = this.back; @@ -1795,11 +1952,11 @@ class FlattenIter extends Iter { this.front = undefined; this.back = undefined; both( - () => outer?.[Symbol.dispose](), + () => dispose(outer), () => both( - () => front?.[Symbol.dispose](), - () => back?.[Symbol.dispose](), + () => dispose(front), + () => dispose(back), ), ); } @@ -1817,7 +1974,7 @@ export class Peekable extends Adaptor { } /** The item it peeked, if any, which it no longer holds. */ - private take(): T | Done { + take(): T | Done { this.peeked = false; const item = this.item; this.item = DONE; @@ -1840,56 +1997,6 @@ export class Peekable extends Adaptor { return peeked; } - /** std's: the item it peeked drops after what its iterator skips. */ - override nthItem(n: number, drop?: Drop): T | Done { - if (!this.peeked) return this.inner.nthItem(n, drop); - const peeked = this.take(); - if (peeked === DONE) return DONE; - if (n === 0) return peeked; - let item: T | Done; - try { - item = this.inner.nthItem(n - 1, drop); - } catch (e) { - drop?.(peeked); - throw e; - } - // A panic here leaks the item, as std's unwinding does a returned value. - drop?.(peeked); - return item; - } - - /** std's: the item it peeked drops after its iterator is counted. */ - override countItems(drop?: Drop): number { - if (!this.peeked) return consumed(this.inner, () => this.inner.countItems(drop)); - const peeked = this.take(); - if (peeked === DONE) return 0; - try { - return 1 + consumed(this.inner, () => this.inner.countItems(drop)); - } finally { - drop?.(peeked); - } - } - - /** std's: the item it peeked, unless its iterator has a last, which drops it after. */ - override lastItem(drop?: Drop): T | Done { - let peeked: T | Done = DONE; - if (this.peeked) { - peeked = this.take(); - if (peeked === DONE) return DONE; - } - let last: T | Done; - try { - last = consumed(this.inner, () => this.inner.lastItem(drop)); - } catch (e) { - if (peeked !== DONE) drop?.(peeked); - throw e; - } - if (last === DONE) return peeked; - // A panic here leaks the last, as std's unwinding does a returned value. - if (peeked !== DONE) drop?.(peeked); - return last; - } - override len(): number { if (!this.peeked) return this.inner.len(); return this.item === DONE ? 0 : this.inner.len() + 1; @@ -1897,7 +2004,7 @@ export class Peekable extends Adaptor { override [Symbol.dispose](): void { both( - () => this.inner[Symbol.dispose](), + () => dispose(this.inner), () => { const item = this.take(); if (item !== DONE) this.drop?.(item); diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 4f2174490..d8a6bd0c6 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -300,7 +300,10 @@ pub fn call<'tcx>( "next_back" => recv.member("nextBack").call(Vec::new()), _ => { let dropper = b.t.dropper(item, span); - recv.member("nthBackItem").call(tail(rest, vec![dropper])) + if !undefined(&dropper) { + return Some(Expr::rt("ownedNthBack", [vec![recv], rest, vec![dropper]].concat())); + } + recv.member("nthBackItem").call(rest) } }; return Some(Expr::rt("iterToOption", vec![item])); @@ -319,6 +322,12 @@ pub fn call<'tcx>( }; Some(Expr::rt_of(of, name).call([vec![recv.clone()], args].concat())) }; + // `rt.owned`, which drops by `droppers` as std's own does, where any drops: else + // `rt.iter`, so a bundle that never drops doesn't carry it. + let owned = |name: &str, args: Vec, droppers: Vec| match droppers.iter().all(undefined) { + true => method(name, args), + false => Some(Expr::rt_of("owned", name).call([vec![recv.clone()], args, tail(Vec::new(), droppers)].concat())), + }; // Each consumer that takes the iterator by value drops it, by `fold` but for `nth`'s. if matches!( name, @@ -332,17 +341,21 @@ pub fn call<'tcx>( method(&camel, rest) } // What each drops: an item it skips or rejects, or one it peeked. - "filter" | "skip" | "take" | "skip_while" | "take_while" | "step_by" | "inspect" | "peekable" => { + "filter" | "skip_while" | "take_while" | "inspect" | "peekable" => { let dropper = b.t.dropper(item, span); method(&camel, tail(rest, vec![dropper])) } + "skip" | "take" | "step_by" => { + let dropper = b.t.dropper(item, span); + owned(&camel, rest, vec![dropper]) + } "fuse" => { let fused = fused(b, self_ty); method(name, tail(rest, vec![fused])) } "count" => { let droppers = vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)]; - method(name, tail(rest, droppers)) + owned(name, rest, droppers) } "for_each" => { let dropper = iter_dropper(b, self_ty, span); @@ -364,11 +377,18 @@ pub fn call<'tcx>( } // `ExactSizeIterator::len` is each iterator's own. "len" => Some(recv.member("len").call(rest)), - "last" | "nth" | "find" | "peek" | "next_if" => { + "last" | "nth" => { option_ok(b, item, span); let droppers = match name { "last" => vec![iter_dropper(b, self_ty, span), b.t.dropper(item, span)], - "nth" | "find" => vec![b.t.dropper(item, span)], + _ => vec![b.t.dropper(item, span)], + }; + owned(&camel, rest, droppers) + } + "find" | "peek" | "next_if" => { + option_ok(b, item, span); + let droppers = match name { + "find" => vec![b.t.dropper(item, span)], _ => Vec::new(), }; method(&camel, tail(rest, droppers)) @@ -484,6 +504,11 @@ pub(super) fn tail(mut args: Vec, mut tail: Vec) -> Vec { args } +/// Whether `e` is `undefined`, as the dropper of what doesn't drop is. +fn undefined(e: &Expr) -> bool { + matches!(e, Expr::Lit(l) if l == "undefined") +} + /// Whether an iterator of type `ty` that drops is a `FusedIterator`, which std's `fuse` and /// `flatten` keep once it ends rather than drop: `true` or `false`. fn fused<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> Expr { From ff5f56c2080a724b60bd9f213a0dadf3e383763c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:19:37 -0700 Subject: [PATCH 14/18] fix(ts): a panicking collect drops collected items only by their dropper Of items that drop nothing, `iterToArray` passed `undefined` to `dropAll`, whose default is `rt.drop`: a collect of references from a source that drops disposed what they pointed to as a panic unwound. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 351 +++++++++++++---------- ts/fixtures/task/src/drops/iters.rs | 13 +- ts/runtime/rt/iter.ts | 8 +- 3 files changed, 212 insertions(+), 160 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index c297aa933..4f7e56db1 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -898,18 +898,19 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { let v6!: Guard.Guard[]; let tree!: rt.BTreeMap; let v7!: [rt.u32, Guard.Guard][]; - let queue!: rt.VecDeque; let v8!: Guard.Guard[]; + let queue!: rt.VecDeque; + let v9!: Guard.Guard[]; let hashed!: rt.HashMap; - let v9!: [rt.u32, Guard.Guard][]; + let v10!: [rt.u32, Guard.Guard][]; let set!: rt.HashSet; - let v10!: Key.Key[]; - let _291!: boolean; - let _292!: boolean; + let v11!: Key.Key[]; + let _320!: boolean; + let _321!: boolean; let unwind: number = 0; try { - _292 = false; - _291 = false; + _321 = false; + _320 = false; const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; @@ -918,12 +919,12 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { }; const check: (a0: rt.u8) => void = (point: rt.u8): void => { if (point === at) { - const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; - rt.panicFmt(["d", args12[0], " at ", args12[1]]); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args14[0], " at ", args14[1]]); } }; v = []; - unwind = 149; + unwind = 165; const _18: Guard.Guard = guard(1); v.push(_18); const _23: Guard.Guard = guard(2); @@ -948,16 +949,16 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e2; } }), true, rt.drop, rt.drop); - unwind = 148; + unwind = 164; v2 = []; - unwind = 147; + unwind = 163; const _41: Guard.Guard = guard(4); v2.push(_41); const _46: Guard.Guard = guard(5); v2.push(_46); const _51: Guard.Guard = guard(6); v2.push(_51); - unwind = 148; + unwind = 164; wider = rt.iterToArray(rt.iterMap(rt.iterSlice(v2, rt.drop), (g2: Guard.Guard): [Guard.Guard, rt.u32] => { let unwind3: number = 0; try { @@ -974,27 +975,27 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e3; } }), false, rt.drop, drop$Guard_u32); - unwind = 146; + unwind = 162; v3 = []; - unwind = 145; + unwind = 161; const _65: Guard.Guard = guard(7); v3.push(_65); - unwind = 146; + unwind = 162; _60 = rt.iterSlice(v3, rt.drop); - unwind = 154; - _292 = true; + unwind = 170; + _321 = true; v4 = []; - unwind = 144; + unwind = 160; const _72: Guard.Guard = guard(8); v4.push(_72); const _77: Guard.Guard = guard(9); v4.push(_77); - unwind = 154; + unwind = 170; const _68: Guard.Guard[] = v4; - _292 = false; + _321 = false; const _59: rt.Iter = rt.iterChain(_60, rt.iterSlice(_68, rt.drop)); - unwind = 146; - _292 = false; + unwind = 162; + _321 = false; chained = rt.iterToArray(rt.iterMap(_59, (g3: Guard.Guard): Guard.Guard => { let unwind4: number = 0; try { @@ -1012,21 +1013,21 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e4; } }), false, rt.drop, rt.drop); - unwind = 143; + unwind = 159; const _89: rt.usize = same.length; const _92: rt.usize = wider.length; const _95: rt.usize = chained.length; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_89, f), (f: rt.Formatter) => rt.usizeDisplay(_92, f), (f: rt.Formatter) => rt.usizeDisplay(_95, f)]; Log.note(log, rt.fmtFormat(["vecs ", args2[0], " ", args2[1], " ", args2[2]])); v5 = []; - unwind = 142; + unwind = 158; const _110: Guard.Guard = guard(10); v5.push(_110); const _115: Guard.Guard = guard(11); v5.push(_115); const _120: Guard.Guard = guard(12); v5.push(_120); - unwind = 143; + unwind = 159; results = rt.iterCollectResult(rt.iterMap(rt.iterSlice(v5, rt.drop), (g4: Guard.Guard): rt.Result => { let unwind5: number = 0; try { @@ -1043,22 +1044,22 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e5; } }), (values: rt.Iter) => rt.iterToArray(values, true, rt.drop, rt.drop), drop$Vec_Guard, rt.drop); - unwind = 152; - _291 = true; + unwind = 168; + _320 = true; const part = results.ok; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(part, f)]; Log.note(log, rt.fmtFormat(["result ", args4[0]])); - _291 = false; + _320 = false; drop$Result_Vec_Guard_Guard(results); v6 = []; - unwind = 141; + unwind = 157; const _146: Guard.Guard = guard(13); v6.push(_146); const _151: Guard.Guard = guard(14); v6.push(_151); const _156: Guard.Guard = guard(15); v6.push(_156); - unwind = 152; + unwind = 168; const part2 = rt.optionMapOr(rt.iterCollectOption(rt.iterMap(rt.iterSlice(v6, rt.drop), (g5: Guard.Guard): Guard.Guard | undefined => { let unwind6: number = 0; try { @@ -1075,56 +1076,57 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(g5); throw e6; } - }), (values: rt.Iter) => rt.iterToArray(values, true, rt.drop, rt.drop), drop$Vec_Guard), 0, (v11: Guard.Guard[]): rt.usize => { + }), (values: rt.Iter) => rt.iterToArray(values, true, rt.drop, rt.drop), drop$Vec_Guard), 0, (v12: Guard.Guard[]): rt.usize => { let unwind7: number = 0; try { unwind7 = 4; - const _08: rt.usize = v11.length; + const _08: rt.usize = v12.length; unwind7 = 0; - rt.dropAll(v11); + rt.dropAll(v12); return _08; } catch (e7) { if (unwind7 === 0) { throw e7; } - rt.dropAll(v11); + rt.dropAll(v12); throw e7; } }); const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part2, f)]; Log.note(log, rt.fmtFormat(["option ", args6[0]])); v7 = []; - unwind = 140; + unwind = 156; const _179: [rt.u32, Guard.Guard] = [2, guard(16)]; v7.push(_179); const _185: [rt.u32, Guard.Guard] = [1, guard(17)]; v7.push(_185); const _191: [rt.u32, Guard.Guard] = [2, guard(18)]; v7.push(_191); - unwind = 152; + unwind = 168; const _174: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterSlice(v7, drop$u32_Guard); tree = rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_174, true, rt.drop, drop$u32_Guard), undefined, rt.drop); - unwind = 139; + unwind = 155; const part3 = rt.btreeLen(tree); const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part3, f)]; Log.note(log, rt.fmtFormat(["tree ", args8[0]])); - check(5); v8 = []; - unwind = 138; - const _217: Guard.Guard = guard(19); - v8.push(_217); - const _222: Guard.Guard = guard(20); - v8.push(_222); - unwind = 139; - const _211: rt.Iter = rt.iterMap(rt.iterSlice(v8, rt.drop), (g6: Guard.Guard): Guard.Guard => { + unwind = 154; + const _214: Guard.Guard = guard(24); + v8.push(_214); + const _219: Guard.Guard = guard(25); + v8.push(_219); + unwind = 155; + const refs: Guard.Guard[] = rt.iterToArray(rt.iterMap(rt.iterSlice(v8, rt.drop), (g6: Guard.Guard): Guard.Guard => { let unwind8: number = 0; try { - unwind8 = 6; - if (Guard.id(g6) === rt.u32Add(id, 20)) { - check(6); - return g6; + unwind8 = 8; + if (Guard.id(g6) === rt.u32Add(id, 25)) { + check(5); } - return g6; + const at2 = rt.idx(same, 0); + unwind8 = 0; + rt.drop(g6); + return same[at2]; } catch (e8) { if (unwind8 === 0) { throw e8; @@ -1132,62 +1134,90 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(g6); throw e8; } - }); - queue = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, rt.iterSlice(rt.iterToArray(_211, true, rt.drop, rt.drop))); - unwind = 137; + }), true, rt.drop); + unwind = 153; + const part4 = refs.length; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part4, f)]; + Log.note(log, rt.fmtFormat(["refs ", args10[0]])); v9 = []; - unwind = 136; - const _235: [rt.u32, Guard.Guard] = [1, guard(21)]; - v9.push(_235); - const _241: [rt.u32, Guard.Guard] = [1, guard(22)]; - v9.push(_241); - unwind = 137; - const _229: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterMap(rt.iterSlice(v9, drop$u32_Guard), (e9: [rt.u32, Guard.Guard]): [rt.u32, Guard.Guard] => { + unwind = 152; + const _245: Guard.Guard = guard(19); + v9.push(_245); + const _250: Guard.Guard = guard(20); + v9.push(_250); + unwind = 153; + const _239: rt.Iter = rt.iterMap(rt.iterSlice(v9, rt.drop), (g7: Guard.Guard): Guard.Guard => { let unwind9: number = 0; try { unwind9 = 6; - if (Guard.id(e9[1]) === rt.u32Add(id, 22)) { - check(7); - return e9; + if (Guard.id(g7) === rt.u32Add(id, 20)) { + check(6); + return g7; } - return e9; - } catch (e10) { + return g7; + } catch (e9) { if (unwind9 === 0) { - throw e10; + throw e9; } - drop$u32_Guard(e9); - throw e10; + rt.drop(g7); + throw e9; } }); - hashed = rt.hashExtend(rt.hashNew() as rt.HashMap, _229, undefined, rt.drop, rt.drop, true); - unwind = 135; + queue = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, rt.iterSlice(rt.iterToArray(_239, true, rt.drop, rt.drop))); + unwind = 151; v10 = []; - unwind = 134; - const _254: Key.Key = key(23); - v10.push(_254); - const _259: Key.Key = key(23); - v10.push(_259); - unwind = 135; - const _249: rt.Iter = rt.iterSlice(v10, rt.drop); - set = rt.hashExtendKeys(rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashSet, _249, rt.drop, rt.drop, true); - unwind = 133; - const _268: rt.usize = queue.n; - const _271: rt.usize = rt.hashLen(hashed); - const _274: rt.usize = rt.hashLen(set); - const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_268, f), (f: rt.Formatter) => rt.usizeDisplay(_271, f), (f: rt.Formatter) => rt.usizeDisplay(_274, f)]; - Log.note(log, rt.fmtFormat(["collected ", args10[0], " ", args10[1], " ", args10[2]])); - unwind = 135; + unwind = 150; + const _263: [rt.u32, Guard.Guard] = [1, guard(21)]; + v10.push(_263); + const _269: [rt.u32, Guard.Guard] = [1, guard(22)]; + v10.push(_269); + unwind = 151; + const _257: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterMap(rt.iterSlice(v10, drop$u32_Guard), (e10: [rt.u32, Guard.Guard]): [rt.u32, Guard.Guard] => { + let unwind10: number = 0; + try { + unwind10 = 6; + if (Guard.id(e10[1]) === rt.u32Add(id, 22)) { + check(7); + return e10; + } + return e10; + } catch (e11) { + if (unwind10 === 0) { + throw e11; + } + drop$u32_Guard(e10); + throw e11; + } + }); + hashed = rt.hashExtend(rt.hashNew() as rt.HashMap, _257, undefined, rt.drop, rt.drop, true); + unwind = 149; + v11 = []; + unwind = 148; + const _282: Key.Key = key(23); + v11.push(_282); + const _287: Key.Key = key(23); + v11.push(_287); + unwind = 149; + const _277: rt.Iter = rt.iterSlice(v11, rt.drop); + set = rt.hashExtendKeys(rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashSet, _277, rt.drop, rt.drop, true); + unwind = 147; + const _296: rt.usize = queue.n; + const _299: rt.usize = rt.hashLen(hashed); + const _302: rt.usize = rt.hashLen(set); + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_296, f), (f: rt.Formatter) => rt.usizeDisplay(_299, f), (f: rt.Formatter) => rt.usizeDisplay(_302, f)]; + Log.note(log, rt.fmtFormat(["collected ", args12[0], " ", args12[1], " ", args12[2]])); + unwind = 149; rt.hashDrop(set, rt.drop); - unwind = 137; + unwind = 151; rt.hashDrop(hashed, undefined, rt.drop); - unwind = 139; + unwind = 153; rt.dequeDrop(queue, rt.drop); - unwind = 152; + unwind = 168; rt.btreeDrop(tree, undefined, rt.drop); - unwind = 146; - _291 = false; + unwind = 162; + _320 = false; rt.dropAll(chained); - unwind = 148; + unwind = 164; rt.dropAll(wider, drop$Guard_u32); unwind = 0; rt.dropAll(same); @@ -1200,87 +1230,96 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { b5: { b6: { b7: { - if (unwind === 0) { - throw e; - } - if (unwind === 133) { - rt.hashDrop(set, rt.drop); - break b7; - } - if (unwind === 134) { - rt.dropAll(v10); - break b7; - } - if (unwind === 135) { - break b7; - } - if (unwind === 136) { - rt.dropAll(v9, drop$u32_Guard); - break b6; - } - if (unwind === 137) { - break b6; - } - if (unwind === 138) { - rt.dropAll(v8); - break b5; - } - if (unwind === 139) { - break b5; - } - if (unwind === 140) { - rt.dropAll(v7, drop$u32_Guard); - break b4; - } - if (unwind === 141) { - rt.dropAll(v6); - break b4; - } - if (unwind === 142) { - rt.dropAll(v5); - break b3; - } - if (unwind === 143) { - break b3; - } - if (unwind === 144) { - rt.dropAll(v4); - } else { - if (unwind === 145) { - rt.dropAll(v3); - break b2; - } - if (unwind === 146) { - break b2; + b8: { + if (unwind === 0) { + throw e; } if (unwind === 147) { - rt.dropAll(v2); - break b1; + rt.hashDrop(set, rt.drop); + break b8; } if (unwind === 148) { - break b1; + rt.dropAll(v11); + break b8; } if (unwind === 149) { - rt.dropAll(v); - break b0; + break b8; + } + if (unwind === 150) { + rt.dropAll(v10, drop$u32_Guard); + break b7; + } + if (unwind === 151) { + break b7; } if (unwind === 152) { + rt.dropAll(v9); + break b6; + } + if (unwind === 153) { + break b6; + } + if (unwind === 154) { + rt.dropAll(v8); + break b5; + } + if (unwind === 155) { + break b5; + } + if (unwind === 156) { + rt.dropAll(v7, drop$u32_Guard); break b4; } - } - if (!_292) { + if (unwind === 157) { + rt.dropAll(v6); + break b4; + } + if (unwind === 158) { + rt.dropAll(v5); + break b3; + } + if (unwind === 159) { + break b3; + } + if (unwind === 160) { + rt.dropAll(v4); + } else { + if (unwind === 161) { + rt.dropAll(v3); + break b2; + } + if (unwind === 162) { + break b2; + } + if (unwind === 163) { + rt.dropAll(v2); + break b1; + } + if (unwind === 164) { + break b1; + } + if (unwind === 165) { + rt.dropAll(v); + break b0; + } + if (unwind === 168) { + break b4; + } + } + if (!_321) { + break b2; + } + rt.drop(_60); break b2; } - rt.drop(_60); - break b2; + rt.hashDrop(hashed, undefined, rt.drop); } - rt.hashDrop(hashed, undefined, rt.drop); + rt.dequeDrop(queue, rt.drop); } - rt.dequeDrop(queue, rt.drop); } rt.btreeDrop(tree, undefined, rt.drop); } - if (_291) { + if (_320) { drop$Result_Vec_Guard_Guard(results); } } diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index 048d9d3e0..6672d05fe 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -181,7 +181,18 @@ pub(super) fn collected(log: &Log, id: u32, at: u8) { .into_iter() .collect(); log.note(format!("tree {}", tree.len())); - check(5); + // Collected references to values that drop: a panic drops the source, not what they + // point to. + let refs: Vec<&Guard> = list![guard(24), guard(25)] + .into_iter() + .map(|g| { + if g.id() == id + 25 { + check(5); + } + &same[0] + }) + .collect(); + log.note(format!("refs {}", refs.len())); let queue: VecDeque = list![guard(19), guard(20)] .into_iter() .map(|g| { diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index b0371f34c..b572ac1a9 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -497,17 +497,19 @@ export function iterToArray(it: Iter, inPlace = false, dropIt?: Drop drop !== undefined && dropAll(out, drop); try { for (let item = it.next(); item !== DONE; item = it.next()) out.push(item); } catch (e) { - if (inPlace) both(() => dropAll(out, drop), () => dropIt?.(it)); - else both(() => dropIt?.(it), () => dropAll(out, drop)); + if (inPlace) both(collected, () => dropIt?.(it)); + else both(() => dropIt?.(it), collected); throw e; } try { dropIt?.(it); } catch (e) { - dropAll(out, drop); + collected(); throw e; } return out; From 405151c946116f6efe27db4e245410947f0a7843 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:19:37 -0700 Subject: [PATCH 15/18] chore(quest): add ts-iter-nth for std's skips without drops Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 + quest/m2/ts-iter-nth.md | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 quest/m2/ts-iter-nth.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 5d89d936f..d9b88f837 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -35,6 +35,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Share what the crate never changes in place](/quest/m2/ts-shared-read.md) - copies of `Copy` aggregates no one writes into in place go away, recovering #83's decode cost - [Matches TypeScript has already narrowed](/quest/m2/ts-narrow-test.md) - an inner match on a value an outer match decided passes `tsc` - [Small std gaps](/quest/m2/ts-std-gaps.md) - `bool::then`, `iter::successors`, `usize::from(bool)`, and `None.ok_or` narrowing +- [Iterator skips that read as std's](/quest/m2/ts-iter-nth.md) - `nth` and `nth_back` of what drops nothing read the items std's do - [Copy-on-write strings](/quest/m2/ts-cow-str.md) - `Cow` translates, finishing `ietf/namespace.rs` - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM - [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm diff --git a/quest/m2/ts-iter-nth.md b/quest/m2/ts-iter-nth.md new file mode 100644 index 000000000..65aa0ad4c --- /dev/null +++ b/quest/m2/ts-iter-nth.md @@ -0,0 +1,23 @@ +# [S] Iterator skips that read as std's + +## Goal + +rust2-ts's `nth`, `nth_back`, and the adaptors built on them read the same items std's +do of an iterator that drops nothing, so a `by_ref` source or an `inspect` closure sees +std's reads, proven by differential tests against native Rust. + +## Plan + +Found by review of [#101](https://github.com/kixelated/rust2/pull/101) on 2026-10-27. +Without a dropper, `rt.iterNth` and `nthBackItem` are `main`'s methods, which only +`Enumerate`, `Rev`, `Take`, `Range`, and the `by_ref` wrapper override. std's `Fuse`, +`Skip`, `Chain`, `StepBy`, `Peekable`, `Flatten`, and `Copied` forward to +what they wrap, and `Take`'s `nth_back` and `advance_back_by` read past its limit, so +`(0..3).by_ref().take(0).fuse().nth_back(0)` leaves the range empty in Rust but not here. +#101's `rt.owned*` dispatchers already follow std's order where an item drops. + +- Weigh calling those dispatchers without a dropper against methods on each class: the + codec's bundle carries every class a dispatcher names. +- Cover `by_ref` and `inspect` sources under each adaptor. + +Public API: the translator's output. From a390d5c4f064374c553a98c0991d6e85b825342e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:33:48 -0700 Subject: [PATCH 16/18] fix(ts): split a skip's nth past a usize's greatest as std's does `Skip::nth` of items that drop passed what it skips plus `n` in one step even past `usize::MAX`, where std reads what it skips in one `nth` and `n` in another: a panicking drop of the first left nothing in the iterator here, and the rest in std's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops/iters.ts | 296 ++++++++++++----------- ts/fixtures/task/src/drops/iters.rs | 8 +- ts/runtime/rt/iter.ts | 11 +- 3 files changed, 171 insertions(+), 144 deletions(-) diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 4f7e56db1..2eef18f5f 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -2210,36 +2210,37 @@ export function extended(log: Log.Log, id: rt.u32, at: rt.u8): void { export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { let it!: rt.Iter; let v!: Bomb.Bomb[]; - let _32!: rt.Iter; + let it2!: rt.Iter; let v2!: Bomb.Bomb[]; + let _after!: Bomb.Bomb; let v3!: Bomb.Bomb[]; let map!: rt.BTreeMap; - let _70!: rt.u32; - let it2!: rt.Iter<[rt.u32, Bomb.Bomb]>; + let _79!: rt.u32; + let it3!: rt.Iter<[rt.u32, Bomb.Bomb]>; let queue!: rt.VecDeque; - let _91!: rt.u32; + let _100!: rt.u32; let v4!: [rt.u32, Bomb.Bomb][]; let v5!: Bomb.Bomb[]; let flat!: rt.Iter; let v6!: Bomb.Bomb[][]; let v7!: Bomb.Bomb[]; let v8!: Bomb.Bomb[]; - let _183!: boolean; - let _184!: boolean; - let _185!: boolean; - let _186!: boolean; + let _192!: boolean; + let _193!: boolean; + let _194!: boolean; + let _195!: boolean; let unwind: number = 0; try { - _186 = false; - _185 = false; - _184 = false; - _183 = false; + _195 = false; + _194 = false; + _193 = false; + _192 = false; const bomb: (a0: rt.u32, a1: boolean) => Bomb.Bomb = (n3: rt.u32, blows: boolean): Bomb.Bomb => { return new Bomb.Bomb({ id: rt.u32Add(id, n3), log: Log.clone$Clone(log), blows }); }; if (at === 0) { v = []; - unwind = 111; + unwind = 116; const _12: Bomb.Bomb = bomb(1, false); v.push(_12); const _17: Bomb.Bomb = bomb(2, true); @@ -2248,189 +2249,202 @@ export function bombed(log: Log.Log, id: rt.u32, at: rt.u8): void { v.push(_22); unwind = 0; it = rt.iterSlice(v, rt.drop); - unwind = 120; - _186 = true; + unwind = 125; + _195 = true; rt.drop(rt.iterToOption(it.next())); - _186 = false; + _195 = false; rt.drop(it); - _186 = false; + _195 = false; } else if (at === 1) { v2 = []; - unwind = 110; - const _38: Bomb.Bomb = bomb(1, true); - v2.push(_38); - const _43: Bomb.Bomb = bomb(2, false); - v2.push(_43); + unwind = 115; + const _36: Bomb.Bomb = bomb(1, true); + v2.push(_36); + const _41: Bomb.Bomb = bomb(2, false); + v2.push(_41); + const _46: Bomb.Bomb = bomb(3, false); + v2.push(_46); unwind = 0; - _32 = rt.ownedSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); - unwind = 109; - rt.drop(rt.iterToOption(_32.next())); + it2 = rt.ownedSkip(rt.iterSlice(v2, rt.drop), 1, rt.drop); + unwind = 114; + _after = bomb(4, false); + unwind = 113; + rt.drop(rt.ownedNth(it2, 4294967295, rt.drop)); + unwind = 114; + rt.drop(_after); unwind = 0; - rt.drop(_32); + rt.drop(it2); } else if (at === 2) { v3 = []; - unwind = 108; - const _53: Bomb.Bomb = bomb(1, false); - v3.push(_53); - const _58: Bomb.Bomb = bomb(2, true); - v3.push(_58); - const _63: Bomb.Bomb = bomb(3, false); - v3.push(_63); + unwind = 112; + const _62: Bomb.Bomb = bomb(1, false); + v3.push(_62); + const _67: Bomb.Bomb = bomb(2, true); + v3.push(_67); + const _72: Bomb.Bomb = bomb(3, false); + v3.push(_72); unwind = 0; rt.ownedCount(rt.iterFilter(rt.iterSlice(v3, rt.drop), (b: Bomb.Bomb): boolean => { return !b.blows; }, rt.drop), rt.drop, rt.drop); } else if (at === 3) { - _185 = true; + _194 = true; map = rt.btreeNew(rt.cmp) as rt.BTreeMap; - unwind = 118; + unwind = 123; let iterStart: rt.u32 = 1; const iterEnd: rt.u32 = 4; - while ((_70 = iterStart++) < iterEnd) { - const n: rt.u32 = _70; - const _76: Bomb.Bomb = bomb(n, n === 2); - rt.drop(rt.btreeInsert(map, n, _76, undefined, rt.drop)); + while ((_79 = iterStart++) < iterEnd) { + const n: rt.u32 = _79; + const _85: Bomb.Bomb = bomb(n, n === 2); + rt.drop(rt.btreeInsert(map, n, _85, undefined, rt.drop)); } - _185 = false; - it2 = rt.btreeIter(map, undefined, rt.drop); - unwind = 116; - _184 = true; - drop$Option_u32_Bomb(rt.iterToOption(it2.next())); - _184 = false; - rt.drop(it2); - _184 = false; - _185 = false; + _194 = false; + it3 = rt.btreeIter(map, undefined, rt.drop); + unwind = 121; + _193 = true; + drop$Option_u32_Bomb(rt.iterToOption(it3.next())); + _193 = false; + rt.drop(it3); + _193 = false; + _194 = false; } else if (at === 4) { queue = rt.dequeNew() as rt.VecDeque; - unwind = 107; + unwind = 111; let iterStart2: rt.u32 = 1; const iterEnd2: rt.u32 = 5; - while ((_91 = iterStart2++) < iterEnd2) { - const n2: rt.u32 = _91; - const _97: Bomb.Bomb = bomb(n2, n2 === 2); - rt.dequePushBack(queue, _97); + while ((_100 = iterStart2++) < iterEnd2) { + const n2: rt.u32 = _100; + const _106: Bomb.Bomb = bomb(n2, n2 === 2); + rt.dequePushBack(queue, _106); } rt.drop(rt.dequeDrain(queue, { end: 3 }, rt.drop)); unwind = 0; rt.dequeDrop(queue, rt.drop); } else if (at === 5) { v4 = []; - unwind = 106; - const _111: [rt.u32, Bomb.Bomb] = [1, bomb(1, true)]; - v4.push(_111); - const _117: [rt.u32, Bomb.Bomb] = [1, bomb(2, false)]; - v4.push(_117); - const _123: [rt.u32, Bomb.Bomb] = [2, bomb(3, false)]; - v4.push(_123); + unwind = 110; + const _120: [rt.u32, Bomb.Bomb] = [1, bomb(1, true)]; + v4.push(_120); + const _126: [rt.u32, Bomb.Bomb] = [1, bomb(2, false)]; + v4.push(_126); + const _132: [rt.u32, Bomb.Bomb] = [2, bomb(3, false)]; + v4.push(_132); unwind = 0; - const _106: rt.Iter<[rt.u32, Bomb.Bomb]> = rt.iterSlice(v4, drop$u32_Bomb); - rt.btreeDrop(rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_106, true, rt.drop, drop$u32_Bomb), undefined, rt.drop), undefined, rt.drop); + const _115: rt.Iter<[rt.u32, Bomb.Bomb]> = rt.iterSlice(v4, drop$u32_Bomb); + rt.btreeDrop(rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_115, true, rt.drop, drop$u32_Bomb), undefined, rt.drop), undefined, rt.drop); } else if (at === 6) { v5 = []; - unwind = 105; - const _134: Bomb.Bomb = bomb(1, false); - v5.push(_134); - const _139: Bomb.Bomb = bomb(2, true); - v5.push(_139); - const _144: Bomb.Bomb = bomb(3, false); - v5.push(_144); + unwind = 109; + const _143: Bomb.Bomb = bomb(1, false); + v5.push(_143); + const _148: Bomb.Bomb = bomb(2, true); + v5.push(_148); + const _153: Bomb.Bomb = bomb(3, false); + v5.push(_153); unwind = 0; rt.ownedCount(rt.ownedTake(rt.iterSlice(v5, rt.drop), 2, rt.drop), rt.drop, rt.drop); } else { v6 = []; - unwind = 104; + unwind = 108; v7 = []; - unwind = 103; - const _157: Bomb.Bomb = bomb(1, false); - v7.push(_157); - unwind = 104; + unwind = 107; + const _166: Bomb.Bomb = bomb(1, false); + v7.push(_166); + unwind = 108; v6.push(v7); v8 = []; - unwind = 102; - const _166: Bomb.Bomb = bomb(2, true); - v8.push(_166); - const _171: Bomb.Bomb = bomb(3, false); - v8.push(_171); - unwind = 104; + unwind = 106; + const _175: Bomb.Bomb = bomb(2, true); + v8.push(_175); + const _180: Bomb.Bomb = bomb(3, false); + v8.push(_180); + unwind = 108; v6.push(v8); unwind = 0; flat = rt.iterFlatten(rt.iterSlice(v6, drop$Vec_Bomb), (value: Bomb.Bomb[]) => rt.iterSlice(value, rt.drop), true); - unwind = 114; - _183 = true; + unwind = 119; + _192 = true; rt.drop(rt.iterToOption(flat.next())); - _183 = false; + _192 = false; rt.drop(flat); - _183 = false; + _192 = false; } unwind = 0; Log.note(log, rt.fmtFormat(["unreached"])); } catch (e) { b5: { b6: { - if (unwind === 0) { - throw e; - } - if (unwind === 102) { - rt.dropAll(v8); - break b6; - } - if (unwind === 103) { - rt.dropAll(v7); - break b6; - } - if (unwind === 104) { - break b6; - } - if (unwind === 105) { - rt.dropAll(v5); - break b5; - } - if (unwind === 106) { - rt.dropAll(v4, drop$u32_Bomb); - break b5; - } - if (unwind === 107) { - rt.dequeDrop(queue, rt.drop); - break b5; - } - if (unwind === 108) { - rt.dropAll(v3); - break b5; - } - if (unwind === 109) { - rt.drop(_32); - break b5; - } - if (unwind === 110) { - rt.dropAll(v2); - break b5; - } - if (unwind === 111) { - rt.dropAll(v); - break b5; - } - if (unwind === 114) { - if (!_183) { + b7: { + if (unwind === 0) { + throw e; + } + if (unwind === 106) { + rt.dropAll(v8); + break b6; + } + if (unwind === 107) { + rt.dropAll(v7); + break b6; + } + if (unwind === 108) { + break b6; + } + if (unwind === 109) { + rt.dropAll(v5); break b5; } - rt.drop(flat); - break b5; - } - if (unwind === 116) { - if (_184) { - rt.drop(it2); + if (unwind === 110) { + rt.dropAll(v4, drop$u32_Bomb); + break b5; } - } else if (unwind !== 118) { - if (!_186) { + if (unwind === 111) { + rt.dequeDrop(queue, rt.drop); break b5; } - rt.drop(it); - break b5; - } - if (!_185) { + if (unwind === 112) { + rt.dropAll(v3); + break b5; + } + if (unwind === 113) { + rt.drop(_after); + break b7; + } + if (unwind === 114) { + break b7; + } + if (unwind === 115) { + rt.dropAll(v2); + break b5; + } + if (unwind === 116) { + rt.dropAll(v); + break b5; + } + if (unwind === 119) { + if (!_192) { + break b5; + } + rt.drop(flat); + break b5; + } + if (unwind === 121) { + if (_193) { + rt.drop(it3); + } + } else if (unwind !== 123) { + if (!_195) { + break b5; + } + rt.drop(it); + break b5; + } + if (!_194) { + break b5; + } + rt.btreeDrop(map, undefined, rt.drop); break b5; } - rt.btreeDrop(map, undefined, rt.drop); + rt.drop(it2); break b5; } rt.dropAll(v6, drop$Vec_Bomb); diff --git a/ts/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs index 6672d05fe..6c39f219e 100644 --- a/ts/fixtures/task/src/drops/iters.rs +++ b/ts/fixtures/task/src/drops/iters.rs @@ -373,7 +373,13 @@ pub(super) fn bombed(log: &Log, id: u32, at: u8) { drop(it.next()); drop(it); } - 1 => drop(list![bomb(1, true), bomb(2, false)].into_iter().skip(1).next()), + 1 => { + // Past a `usize`'s greatest, it reads what it skips apart, leaving the rest in + // the iterator, which drops after what was made after it. + let mut it = list![bomb(1, true), bomb(2, false), bomb(3, false)].into_iter().skip(1); + let _after = bomb(4, false); + drop(it.nth(usize::MAX)); + } 2 => drop( list![bomb(1, false), bomb(2, true), bomb(3, false)] .into_iter() diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index b572ac1a9..1e7b376ae 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -640,6 +640,8 @@ function advance(it: Iter, n: number, drop: Drop | undefined): number { } if (it instanceof RevIter) return advanceBack(it.inner, n, drop); if (it instanceof SkipIter) { + // std's: what it skips and `n` more in one step. Past a `usize`'s greatest, std's + // splits it, but no iterator that drops holds that many. const skip = it.n; const left = advance(it.inner, skip + n, drop); const advanced = skip + n - left; @@ -741,10 +743,15 @@ function nth(it: Iter, n: number, drop: Drop | undefined): T | Done { } if (it instanceof RevIter) return nthBack(it.inner, n, drop); if (it instanceof SkipIter) { - // std's: what it still skips and then `n` more, in one step. + // std's: what it still skips and then `n` more, in one step, or past a `usize`'s + // greatest, what it skips in one and `n` in another. const skip = it.n; it.n = 0; - return nth(it.inner, skip + n, drop); + if (skip + n <= USIZE_MAX) return nth(it.inner, skip + n, drop); + const item = nth(it.inner, skip - 1, drop); + if (item === DONE) return DONE; + drop(item); + return nth(it.inner, n, drop); } if (it instanceof TakeIter) { // std's: past the limit, it reads the rest of the limit through, drops it, and ends. From 44e7b25710b2a0a00d41225757cafa9762ecb6c6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:50:18 -0700 Subject: [PATCH 17/18] fix(ts): glue for a field generic over lifetimes or a tuple of parameters A generic class's glue drops each field at its declared type. One generic over lifetimes alone, as moq-net's `path::Repr<'a>` is, found no glue, since rustc's is per instance; lifetimes don't change a drop, so it now drops by the glue of its erased type. A tuple of type parameters, as a generic map's `(K, V)` entries are, now drops each element in order, the rest still dropping after one panics, as rustc's glue for a tuple does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/drops.Entries.ts | 33 + ts/fixtures/task/expected/drops.Named.ts | 19 + ts/fixtures/task/expected/drops.Text.ts | 11 + ts/fixtures/task/expected/drops.ts | 974 +++++++++++---------- ts/fixtures/task/expected/lib.ts | 26 +- ts/fixtures/task/src/drops.rs | 22 +- ts/src/lower/drop.rs | 28 + 7 files changed, 651 insertions(+), 462 deletions(-) create mode 100644 ts/fixtures/task/expected/drops.Entries.ts create mode 100644 ts/fixtures/task/expected/drops.Named.ts create mode 100644 ts/fixtures/task/expected/drops.Text.ts diff --git a/ts/fixtures/task/expected/drops.Entries.ts b/ts/fixtures/task/expected/drops.Entries.ts new file mode 100644 index 000000000..3b21face0 --- /dev/null +++ b/ts/fixtures/task/expected/drops.Entries.ts @@ -0,0 +1,33 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** + * Pairs of its type parameters, as a map's entries are: each pair drops its halves in + * order, the second after the first panics. + */ +export class Entries { + _0: [K, V][]; + + constructor(_0: [K, V][]) { + this._0 = _0; + } + + [Symbol.dispose](): void { + rt.dropAll(this._0, (value: [K, V]): void => { + let dropped: number = 0; + try { + rt.drop(value[0]); + dropped = 1; + rt.drop(value[1]); + } catch (e) { + if (dropped < 1) { + rt.drop(value[1]); + } + throw e; + } + }); + } +} + +//# sourceMappingURL=drops.Entries.ts.map diff --git a/ts/fixtures/task/expected/drops.Named.ts b/ts/fixtures/task/expected/drops.Named.ts new file mode 100644 index 000000000..16f45f02e --- /dev/null +++ b/ts/fixtures/task/expected/drops.Named.ts @@ -0,0 +1,19 @@ +// Generated by rust2-ts. Do not edit. + +import { drop$Text } from "./lib.ts"; +import type * as Text from "./drops.Text.ts"; + +/** A type generic over a lifetime alone, holding one that is. */ +export class Named { + _0: Text.Text; + + constructor(_0: Text.Text) { + this._0 = _0; + } + + [Symbol.dispose](): void { + drop$Text(this._0); + } +} + +//# sourceMappingURL=drops.Named.ts.map diff --git a/ts/fixtures/task/expected/drops.Text.ts b/ts/fixtures/task/expected/drops.Text.ts new file mode 100644 index 000000000..b51489a95 --- /dev/null +++ b/ts/fixtures/task/expected/drops.Text.ts @@ -0,0 +1,11 @@ +// Generated by rust2-ts. Do not edit. + +import type * as Guard from "./model.Guard.ts"; + +/** + * Borrowed text or a value that drops, as moq-net's `path::Repr` is: generic over a + * lifetime alone. + */ +export type Text = { tag: "Borrowed"; _0: string } | { tag: "Owned"; _0: Guard.Guard }; + +//# sourceMappingURL=drops.Text.ts.map diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 56b22e9c6..b63243b39 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -1,14 +1,17 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Guard_Bomb_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; +import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Bomb_Guard, drop$Guard_Entries_Bomb_Guard_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; import { looped, collected, drained, extended, bombed, spent } from "./drops/iters.ts"; import * as Bomb from "./drops.Bomb.ts"; +import * as Entries from "./drops.Entries.ts"; import type * as Fault from "./drops.Fault.ts"; 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 Shell from "./drops.Shell.ts"; +import type * as Text from "./drops.Text.ts"; import * as Wrap from "./drops.Wrap.ts"; import { recvFuture } from "./kio.ts"; import type * as Consumer from "./kio.Consumer.ts"; @@ -42,41 +45,43 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { let v3!: Pair.Pair[]; let _166!: Guard.Guard; let _175!: Guard.Guard; + let _borrowed!: Named.Named; + let _owned!: Named.Named; let nested!: Wrap.Wrap[]>; - let _187!: Log.Log; - let v4!: Wrap.Wrap[]; let _195!: Log.Log; + let v4!: Wrap.Wrap[]; + let _203!: Log.Log; let shared2!: rt.Arc>>; - let _245!: Log.Log; - let _247!: Held.Held; + let _253!: Log.Log; + let _255!: Held.Held; let clones!: rt.Arc>>[]; let v5!: rt.Arc>>[]; let arc2!: rt.Arc>; - let _300!: Guard.Guard; + let _308!: Guard.Guard; let other!: rt.Arc>; let lent!: Guard.Guard; let borrowed!: rt.Arc; let again!: rt.Arc; - let _370!: boolean; - let _371!: boolean; - let _372!: boolean; - let _373!: boolean; - let _374!: boolean; - let _375!: boolean; - let _376!: boolean; - let _377!: boolean; let _378!: boolean; + let _379!: boolean; + let _380!: boolean; + let _381!: boolean; + let _382!: boolean; + let _383!: boolean; + let _384!: boolean; + let _385!: boolean; + let _386!: boolean; let unwind: number = 0; try { + _386 = false; + _385 = false; + _384 = false; + _383 = false; + _382 = false; + _381 = false; + _380 = false; + _379 = false; _378 = false; - _377 = false; - _376 = false; - _375 = false; - _374 = false; - _373 = false; - _372 = false; - _371 = false; - _370 = false; const at: rt.u8 = rt.u8Rem(rt.u8Div(arg, 19), 8); const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); @@ -120,167 +125,175 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { grown(log, id, at, false); } else if (_13 === 0) { v = []; - unwind = 211; + unwind = 216; const _19: Held.Held = { tag: "One", _0: guard(1) }; v.push(_19); v.push({ tag: "Empty" } as Held.Held); _29 = guard(2); - unwind = 210; + unwind = 215; const _32: Guard.Guard = guard(3); - unwind = 211; + unwind = 216; v.push({ tag: "Two", _0: _29, _1: _32 } as Held.Held); - unwind = 209; + unwind = 214; held_ = v; check(1); arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); - unwind = 230; - _378 = true; + unwind = 235; + _386 = true; shared = rt.arcClone(arc); - unwind = 208; - _378 = false; + unwind = 213; + _386 = false; rt.arcDrop(arc, drop$Held); const part4 = shared.strong; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part4, f)]; Log.note(log, rt.fmtFormat(["arc ", args2[0]])); const part5 = shared.strong; cloned = rt.arcClone(shared); - unwind = 228; - _377 = true; + unwind = 233; + _385 = true; const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part5, f)]; Log.note(log, rt.fmtFormat(["counted ", args4[0]])); - _377 = false; + _385 = false; rt.arcDrop(cloned, drop$Held); check(2); v2 = []; - unwind = 207; + unwind = 212; const _85: Held.Held = { tag: "One", _0: guard(5) }; v2.push(_85); - unwind = 228; + unwind = 233; mutex = new rt.Mutex(v2); - unwind = 226; - _376 = true; + unwind = 231; + _384 = true; _91 = guard(6); - unwind = 206; + unwind = 211; const _94: Guard.Guard = guard(7); - unwind = 226; + unwind = 231; boxed = { tag: "Two", _0: _91, _1: _94 } as Held.Held; - unwind = 224; - _375 = true; + unwind = 229; + _383 = true; const _98: Held.Held = { tag: "One", _0: guard(8) }; - unwind = 205; + unwind = 210; maybe = _98; check(3); const _112: rt.usize = held_.length; const _115: boolean = maybe !== undefined; const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_112, f), (f: rt.Formatter) => rt.fmtBool(_115, f)]; Log.note(log, rt.fmtFormat(["held ", args6[0], " ", args6[1]])); - _375 = false; + _383 = false; drop$Held(boxed); check(4); - _376 = false; + _384 = false; rt.dropAll(mutex.value, drop$Held); check(5); - unwind = 224; + unwind = 229; drop$Option_Box_Held(maybe); - unwind = 230; - _375 = false; - _376 = false; - _377 = false; + unwind = 235; + _383 = false; + _384 = false; + _385 = false; rt.arcDrop(shared, drop$Held); unwind = 0; - _378 = false; + _386 = false; rt.dropAll(held_, drop$Held); } else if (_13 === 1) { const _133: rt.u32 = rt.u32Add(id, 10); _135 = Log.clone$Clone(log); - unwind = 204; + unwind = 209; const _137: Guard.Guard = guard(11); - unwind = 203; + unwind = 208; wrapped = new Wrap.Wrap({ id: _133, log: _135, inner: { tag: "One", _0: _137 } as Held.Held }); const _141: rt.u32 = rt.u32Add(id, 20); _143 = Log.clone$Clone(log); - unwind = 202; + unwind = 207; const _144: Guard.Guard = guard(21); - unwind = 201; + unwind = 206; guarded = new Wrap.Wrap({ id: _141, log: _143, inner: _144 }); check(1); _152 = guard(31); - unwind = 200; + unwind = 205; const _155: Guard.Guard = guard(32); - unwind = 199; + unwind = 204; _151 = { tag: "Two", _0: _152, _1: _155 } as Held.Held; const _158: Guard.Guard = guard(33); - unwind = 222; - _374 = true; + unwind = 227; + _382 = true; pair = new Pair.Pair({ first: _151, second: _158 }); v3 = []; - unwind = 198; + unwind = 203; _166 = guard(41); - unwind = 197; + unwind = 202; const _169: Guard.Guard = guard(42); - unwind = 198; + unwind = 203; v3.push(new Pair.Pair({ first: _166, second: _169 })); _175 = guard(43); - unwind = 196; + unwind = 201; const _178: Guard.Guard = guard(44); - unwind = 198; + unwind = 203; v3.push(new Pair.Pair({ first: _175, second: _178 })); - unwind = 195; + unwind = 199; pairs = v3; + _borrowed = new Named.Named({ tag: "Borrowed", _0: "text" } as Text.Text); + const _186: Guard.Guard = guard(45); + unwind = 198; + _owned = new Named.Named({ tag: "Owned", _0: _186 } as Text.Text); check(2); - const _185: rt.u32 = rt.u32Add(id, 50); - _187 = Log.clone$Clone(log); - unwind = 194; - v4 = []; - unwind = 193; - const _193: rt.u32 = rt.u32Add(id, 60); + const _193: rt.u32 = rt.u32Add(id, 50); _195 = Log.clone$Clone(log); - unwind = 192; - const _197: Guard.Guard = guard(61); - unwind = 193; - v4.push(new Wrap.Wrap({ id: _193, log: _195, inner: { tag: "One", _0: _197 } as Held.Held })); - unwind = 191; - nested = new Wrap.Wrap({ id: _185, log: _187, inner: v4 }); + unwind = 197; + v4 = []; + unwind = 196; + const _201: rt.u32 = rt.u32Add(id, 60); + _203 = Log.clone$Clone(log); + unwind = 195; + const _205: Guard.Guard = guard(61); + unwind = 196; + v4.push(new Wrap.Wrap({ id: _201, log: _203, inner: { tag: "One", _0: _205 } as Held.Held })); + unwind = 194; + nested = new Wrap.Wrap({ id: _193, log: _195, inner: v4 }); check(3); - _374 = false; + _382 = false; drop$Pair_Held(pair); check(4); - const _214: boolean = Held.isSome(wrapped.inner); - const _217: rt.u32 = Guard.id(guarded.inner); - const _220: rt.u32 = rt.u32Add(rt.u32Add(Guard.id(pairs[rt.idx(pairs, 1)].first), Guard.id(pairs[rt.idx(pairs, 0)].second)), nested.inner.length as rt.u32); - const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_214, f), (f: rt.Formatter) => rt.u32Display(_217, f), (f: rt.Formatter) => rt.u32Display(_220, f)]; + const _222: boolean = Held.isSome(wrapped.inner); + const _225: rt.u32 = Guard.id(guarded.inner); + const _228: rt.u32 = rt.u32Add(rt.u32Add(Guard.id(pairs[rt.idx(pairs, 1)].first), Guard.id(pairs[rt.idx(pairs, 0)].second)), nested.inner.length as rt.u32); + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_222, f), (f: rt.Formatter) => rt.u32Display(_225, f), (f: rt.Formatter) => rt.u32Display(_228, f)]; Log.note(log, rt.fmtFormat(["wraps ", args8[0], " ", args8[1], " ", args8[2]])); - unwind = 195; + unwind = 198; drop$Wrap_Vec_Wrap_Held(nested); - unwind = 222; + unwind = 199; + rt.drop(_owned); + unwind = 200; + rt.drop(_borrowed); + unwind = 227; rt.dropAll(pairs); - unwind = 203; - _374 = false; + unwind = 208; + _382 = false; drop$Wrap_Guard(guarded); unwind = 0; drop$Wrap_Held(wrapped); } else if (_13 === 2) { - const _243: rt.u32 = rt.u32Add(id, 70); - _245 = Log.clone$Clone(log); - unwind = 190; - const _248: Guard.Guard = guard(71); - unwind = 189; - _247 = { tag: "One", _0: _248 } as Held.Held; - const _251: Guard.Guard = guard(72); + const _251: rt.u32 = rt.u32Add(id, 70); + _253 = Log.clone$Clone(log); + unwind = 193; + const _256: Guard.Guard = guard(71); + unwind = 192; + _255 = { tag: "One", _0: _256 } as Held.Held; + const _259: Guard.Guard = guard(72); unwind = 0; - shared2 = new rt.Arc(new Wrap.Wrap({ id: _243, log: _245, inner: new Pair.Pair({ first: _247, second: _251 }) })); - unwind = 220; - _373 = true; + shared2 = new rt.Arc(new Wrap.Wrap({ id: _251, log: _253, inner: new Pair.Pair({ first: _255, second: _259 }) })); + unwind = 225; + _381 = true; v5 = []; - unwind = 188; - const _258: rt.Arc>> = rt.arcClone(shared2); - v5.push(_258); - const _262: rt.Arc>> = rt.arcClone(shared2); - v5.push(_262); - unwind = 187; + unwind = 191; + const _266: rt.Arc>> = rt.arcClone(shared2); + v5.push(_266); + const _270: rt.Arc>> = rt.arcClone(shared2); + v5.push(_270); + unwind = 190; clones = v5; check(1); - _373 = false; + _381 = false; rt.arcDrop(shared2, drop$Wrap_Pair_Held); const part2 = clones.length; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part2, f)]; @@ -289,52 +302,52 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { const part3 = !bail(log, id, at).ok; const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(part3, f)]; Log.note(log, rt.fmtFormat(["bailed ", args12[0]])); - unwind = 220; + unwind = 225; rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); - _373 = false; + _381 = false; } else { - _300 = guard(81); - unwind = 186; - const _303: Guard.Guard = guard(82); + _308 = guard(81); + unwind = 189; + const _311: Guard.Guard = guard(82); unwind = 0; - arc2 = new rt.Arc(new rt.Mutex({ tag: "Two", _0: _300, _1: _303 } as Held.Held)); - unwind = 218; - _372 = true; + arc2 = new rt.Arc(new rt.Mutex({ tag: "Two", _0: _308, _1: _311 } as Held.Held)); + unwind = 223; + _380 = true; other = rt.arcClone(arc2); - unwind = 185; + unwind = 188; check(1); - _372 = false; + _380 = false; rt.arcDrop(arc2, drop$Mutex_Held); check(2); - const _319: rt.Mutex = other.value; - unwind = 184; - const held2: boolean = Held.isSome(_319.value); - unwind = 185; + const _327: rt.Mutex = other.value; + unwind = 187; + const held2: boolean = Held.isSome(_327.value); + unwind = 188; const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(held2, f)]; Log.note(log, rt.fmtFormat(["locked ", args14[0]])); lent = guard(83); - unwind = 183; + unwind = 186; borrowed = new rt.Arc(lent); - unwind = 216; - _371 = true; + unwind = 221; + _379 = true; again = rt.arcClone(borrowed); - unwind = 214; - _370 = true; - _371 = false; + unwind = 219; + _378 = true; + _379 = false; rt.arcDrop(borrowed); check(3); - _370 = false; + _378 = false; rt.arcDrop(again); const part = Guard.id(lent); const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; Log.note(log, rt.fmtFormat(["lent ", args16[0]])); - unwind = 185; - _370 = false; - _371 = false; + unwind = 188; + _378 = false; + _379 = false; rt.drop(lent); - unwind = 218; + unwind = 223; rt.arcDrop(other, drop$Mutex_Held); - _372 = false; + _380 = false; } } catch (e) { b1: { @@ -357,177 +370,189 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { b18: { b19: { b20: { - if (unwind === 0) { - throw e; - } - if (unwind === 183) { - break b4; - } - if (unwind === 184) { - break b3; - } - if (unwind === 185) { - break b3; - } - if (unwind === 186) { - rt.drop(_300); - break b1; - } - if (unwind === 187) { - rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); - break b5; - } - if (unwind === 188) { - rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); - break b5; - } - if (unwind === 189) { - drop$Held(_247); - break b6; - } - if (unwind === 190) { - break b6; - } - if (unwind === 191) { - drop$Wrap_Vec_Wrap_Held(nested); - break b10; - } - if (unwind === 192) { - rt.drop(_195); - break b12; - } - if (unwind === 193) { - break b12; - } - if (unwind === 194) { - break b11; - } - if (unwind === 195) { - break b10; - } - if (unwind === 196) { - rt.drop(_175); - break b13; - } - if (unwind === 197) { - rt.drop(_166); - break b13; - } - if (unwind === 198) { - break b13; - } - if (unwind === 199) { - drop$Held(_151); - break b8; - } - if (unwind === 200) { - rt.drop(_152); - break b8; - } - if (unwind === 201) { - break b8; - } - if (unwind === 202) { - rt.drop(_143); - break b7; - } - if (unwind === 203) { - break b7; - } - if (unwind === 204) { - rt.drop(_135); - break b1; - } - if (unwind === 205) { - drop$Option_Box_Held(maybe); - break b19; - } - if (unwind === 206) { - rt.drop(_91); - break b18; - } - if (unwind === 207) { - rt.dropAll(v2, drop$Held); - break b17; - } - if (unwind === 208) { - break b16; - } - if (unwind === 209) { - break b14; - } - if (unwind === 210) { - rt.drop(_29); - break b20; - } - if (unwind === 211) { - break b20; - } - if (unwind === 214) { - if (_370) { - rt.arcDrop(again); + b21: { + b22: { + if (unwind === 0) { + throw e; + } + if (unwind === 186) { + break b4; + } + if (unwind === 187) { + break b3; + } + if (unwind === 188) { + break b3; + } + if (unwind === 189) { + rt.drop(_308); + break b1; + } + if (unwind === 190) { + rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); + break b5; + } + if (unwind === 191) { + rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); + break b5; + } + if (unwind === 192) { + drop$Held(_255); + break b6; + } + if (unwind === 193) { + break b6; + } + if (unwind === 194) { + drop$Wrap_Vec_Wrap_Held(nested); + break b12; + } + if (unwind === 195) { + rt.drop(_203); + break b14; + } + if (unwind === 196) { + break b14; + } + if (unwind === 197) { + break b13; + } + if (unwind === 198) { + break b12; + } + if (unwind === 199) { + break b11; + } + if (unwind === 200) { + break b10; + } + if (unwind === 201) { + rt.drop(_175); + break b15; + } + if (unwind === 202) { + rt.drop(_166); + break b15; + } + if (unwind === 203) { + break b15; + } + if (unwind === 204) { + drop$Held(_151); + break b8; + } + if (unwind === 205) { + rt.drop(_152); + break b8; + } + if (unwind === 206) { + break b8; + } + if (unwind === 207) { + rt.drop(_143); + break b7; + } + if (unwind === 208) { + break b7; + } + if (unwind === 209) { + rt.drop(_135); + break b1; + } + if (unwind === 210) { + drop$Option_Box_Held(maybe); + break b21; + } + if (unwind === 211) { + rt.drop(_91); + break b20; + } + if (unwind === 212) { + rt.dropAll(v2, drop$Held); + break b19; + } + if (unwind === 213) { + break b18; + } + if (unwind === 214) { + break b16; + } + if (unwind === 215) { + rt.drop(_29); + break b22; + } + if (unwind === 216) { + break b22; + } + if (unwind === 219) { + if (_378) { + rt.arcDrop(again); + } + } else if (unwind !== 221) { + if (unwind === 223) { + break b2; + } + if (unwind === 225) { + break b5; + } + if (unwind === 227) { + break b9; + } + if (unwind === 229) { + break b21; + } + if (unwind === 231) { + break b20; + } + if (unwind === 233) { + break b19; + } + break b17; + } + if (!_379) { + break b4; + } + rt.arcDrop(borrowed); + break b4; } - } else if (unwind !== 216) { - if (unwind === 218) { - break b2; - } - if (unwind === 220) { - break b5; - } - if (unwind === 222) { - break b9; - } - if (unwind === 224) { - break b19; - } - if (unwind === 226) { - break b18; - } - if (unwind === 228) { - break b17; - } - break b15; + rt.dropAll(v, drop$Held); + break b1; } - if (!_371) { - break b4; + if (_383) { + drop$Held(boxed); } - rt.arcDrop(borrowed); - break b4; } - rt.dropAll(v, drop$Held); - break b1; + if (_384) { + rt.dropAll(mutex.value, drop$Held); + } } - if (_375) { - drop$Held(boxed); + if (_385) { + rt.arcDrop(cloned, drop$Held); } } - if (_376) { - rt.dropAll(mutex.value, drop$Held); - } + rt.arcDrop(shared, drop$Held); } - if (_377) { - rt.arcDrop(cloned, drop$Held); + if (_386) { + rt.arcDrop(arc, drop$Held); } } - rt.arcDrop(shared, drop$Held); - } - if (_378) { - rt.arcDrop(arc, drop$Held); + rt.dropAll(held_, drop$Held); + break b1; } + rt.dropAll(v3); + break b9; } - rt.dropAll(held_, drop$Held); - break b1; + rt.dropAll(v4, drop$Wrap_Held); } - rt.dropAll(v3); - break b9; + rt.drop(_195); } - rt.dropAll(v4, drop$Wrap_Held); + rt.drop(_owned); } - rt.drop(_187); + rt.drop(_borrowed); } rt.dropAll(pairs); } - if (_374) { + if (_382) { drop$Pair_Held(pair); } } @@ -536,10 +561,10 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { drop$Wrap_Held(wrapped); break b1; } - rt.drop(_245); + rt.drop(_253); break b1; } - if (!_373) { + if (!_381) { break b1; } rt.arcDrop(shared2, drop$Wrap_Pair_Held); @@ -549,7 +574,7 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { } rt.arcDrop(other, drop$Mutex_Held); } - if (_372) { + if (_380) { rt.arcDrop(arc2, drop$Mutex_Held); } } @@ -2066,37 +2091,40 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { let _37!: Log.Log; let _38!: Bomb.Bomb; let _45!: Guard.Guard; - let _48!: Bomb.Bomb; + let _48!: Entries.Entries; + let v2!: [Bomb.Bomb, Guard.Guard][]; + let _54!: Bomb.Bomb; + let _63!: Bomb.Bomb; let map!: rt.BTreeMap; - let _58!: Key.Key; - let _67!: Key.Key; let _76!: Key.Key; + let _85!: Key.Key; + let _94!: Key.Key; let map2!: rt.BTreeMap; - let _88!: Key.Key; - let _97!: Key.Key; let _106!: Key.Key; + let _115!: Key.Key; + let _124!: Key.Key; let queue!: rt.VecDeque; - let _119!: rt.u32; + let _137!: rt.u32; let map3!: rt.HashMap; - let _139!: Key.Key; - let _152!: boolean; - let _153!: boolean; - let _154!: boolean; - let _155!: boolean; - let _156!: boolean; - let _157!: boolean; - let _158!: boolean; - let _159!: boolean; + 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 unwind: number = 0; try { - _159 = false; - _158 = false; - _157 = false; - _156 = false; - _155 = false; - _154 = false; - _153 = false; - _152 = false; + _177 = false; + _176 = false; + _175 = false; + _174 = false; + _173 = false; + _172 = false; + _171 = false; + _170 = 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 }); }; @@ -2108,7 +2136,7 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { }; if (at === 0) { v = []; - unwind = 85; + unwind = 94; const _15: Bomb.Bomb = bomb(1, false); v.push(_15); const _20: Bomb.Bomb = bomb(2, true); @@ -2119,122 +2147,134 @@ 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 = 84; + unwind = 93; _30 = bomb(1, false); - unwind = 83; + unwind = 92; 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 = 82; + unwind = 91; _38 = bomb(1, true); - unwind = 81; + unwind = 90; 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 = 80; - _48 = bomb(2, true); - unwind = 79; - const _52: Guard.Guard = guard(3); + unwind = 89; + v2 = []; + unwind = 88; + _54 = bomb(2, true); + unwind = 87; + const _57: Guard.Guard = guard(3); + unwind = 88; + v2.push([_54, _57] as [Bomb.Bomb, Guard.Guard]); + _63 = bomb(4, false); + unwind = 86; + const _66: Guard.Guard = guard(5); + unwind = 88; + v2.push([_63, _66] as [Bomb.Bomb, Guard.Guard]); + unwind = 85; + _48 = new Entries.Entries(v2); + const _70: Guard.Guard = guard(6); unwind = 0; - drop$Guard_Bomb_Held([_45, _48, { tag: "One", _0: _52 } as Held.Held] as [Guard.Guard, Bomb.Bomb, Held.Held]); + 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 = 78; - _58 = key(1, "Sound" as Fault.Fault); - unwind = 102; - _159 = true; - const _62: Bomb.Bomb = bomb(1, false); - _159 = false; - const _56: Bomb.Bomb | undefined = rt.btreeInsert(map, _58, _62, rt.drop, rt.drop); - unwind = 78; - _159 = false; - rt.drop(_56); - _67 = key(2, "Sound" as Fault.Fault); - unwind = 100; - _158 = true; - const _71: Bomb.Bomb = bomb(2, true); - _158 = false; - const _65: Bomb.Bomb | undefined = rt.btreeInsert(map, _67, _71, rt.drop, rt.drop); - unwind = 78; - _158 = false; - rt.drop(_65); - _76 = key(3, "Sound" as Fault.Fault); - unwind = 98; - _157 = true; - const _80: Bomb.Bomb = bomb(3, false); - _157 = false; + unwind = 84; + _76 = key(1, "Sound" as Fault.Fault); + unwind = 111; + _177 = true; + const _80: Bomb.Bomb = bomb(1, false); + _177 = false; const _74: Bomb.Bomb | undefined = rt.btreeInsert(map, _76, _80, rt.drop, rt.drop); - unwind = 78; - _157 = false; + unwind = 84; + _177 = false; rt.drop(_74); + _85 = key(2, "Sound" as Fault.Fault); + unwind = 109; + _176 = true; + const _89: Bomb.Bomb = bomb(2, true); + _176 = false; + const _83: Bomb.Bomb | undefined = rt.btreeInsert(map, _85, _89, rt.drop, rt.drop); + unwind = 84; + _176 = false; + rt.drop(_83); + _94 = key(3, "Sound" as Fault.Fault); + unwind = 107; + _175 = true; + const _98: Bomb.Bomb = bomb(3, false); + _175 = false; + const _92: Bomb.Bomb | undefined = rt.btreeInsert(map, _94, _98, rt.drop, rt.drop); + unwind = 84; + _175 = false; + rt.drop(_92); rt.btreeClear(map, rt.drop, rt.drop); unwind = 0; rt.btreeDrop(map, rt.drop, rt.drop); } else if (at === 5) { - _156 = true; + _174 = true; map2 = rt.btreeNew(Key.cmp$Ord) as rt.BTreeMap; - unwind = 96; - _88 = key(1, "Sound" as Fault.Fault); - unwind = 94; - _155 = true; - const _92: Guard.Guard = guard(1); - _155 = false; - const _86: Guard.Guard | undefined = rt.btreeInsert(map2, _88, _92, rt.drop, rt.drop); - unwind = 96; - _155 = false; - rt.drop(_86); - _97 = key(2, "Blows" as Fault.Fault); - unwind = 92; - _154 = true; - const _101: Guard.Guard = guard(2); - _154 = false; - const _95: Guard.Guard | undefined = rt.btreeInsert(map2, _97, _101, rt.drop, rt.drop); - unwind = 96; - _154 = false; - rt.drop(_95); - _106 = key(3, "Sound" as Fault.Fault); - unwind = 90; - _153 = true; - const _110: Guard.Guard = guard(3); - _153 = false; + unwind = 105; + _106 = key(1, "Sound" as Fault.Fault); + unwind = 103; + _173 = true; + const _110: Guard.Guard = guard(1); + _173 = false; const _104: Guard.Guard | undefined = rt.btreeInsert(map2, _106, _110, rt.drop, rt.drop); - unwind = 96; - _153 = false; + unwind = 105; + _173 = false; rt.drop(_104); - _156 = false; + _115 = key(2, "Blows" as Fault.Fault); + unwind = 101; + _172 = true; + const _119: Guard.Guard = guard(2); + _172 = false; + const _113: Guard.Guard | undefined = rt.btreeInsert(map2, _115, _119, rt.drop, rt.drop); + unwind = 105; + _172 = false; + rt.drop(_113); + _124 = key(3, "Sound" as Fault.Fault); + unwind = 99; + _171 = true; + const _128: Guard.Guard = guard(3); + _171 = false; + const _122: Guard.Guard | undefined = rt.btreeInsert(map2, _124, _128, rt.drop, rt.drop); + unwind = 105; + _171 = false; + rt.drop(_122); + _174 = false; rt.btreeDrop(map2, rt.drop, rt.drop); - _156 = false; + _174 = false; } else if (at === 6) { queue = rt.dequeNew() as rt.VecDeque; - unwind = 77; + unwind = 83; let iterStart: rt.u32 = 1; const iterEnd: rt.u32 = 5; - while ((_119 = iterStart++) < iterEnd) { - const n: rt.u32 = _119; - const _125: Bomb.Bomb = bomb(n, n === 2); - rt.dequePushBack(queue, _125); + while ((_137 = iterStart++) < iterEnd) { + const n: rt.u32 = _137; + const _143: Bomb.Bomb = bomb(n, n === 2); + rt.dequePushBack(queue, _143); } - const _131: Bomb.Bomb = bomb(0, false); - rt.dequePushFront(queue, _131); + const _149: Bomb.Bomb = bomb(0, false); + rt.dequePushFront(queue, _149); rt.dequeTruncate(queue, 1, rt.drop); unwind = 0; rt.dequeDrop(queue, rt.drop); } else { map3 = rt.hashNew(rt.hashing(Key.hash$Hash_DefaultHasher, Key.eq$PartialEq)) as rt.HashMap; - unwind = 76; - _139 = key(1, "Blows" as Fault.Fault); - unwind = 88; - _152 = true; - const _143: Guard.Guard = guard(1); - _152 = false; - const _137: Guard.Guard | undefined = rt.hashInsert(map3, _139, _143, rt.drop, rt.drop); - unwind = 76; - _152 = false; - rt.drop(_137); + unwind = 82; + _157 = key(1, "Blows" as Fault.Fault); + unwind = 97; + _170 = true; + const _161: Guard.Guard = guard(1); + _170 = false; + const _155: Guard.Guard | undefined = rt.hashInsert(map3, _157, _161, rt.drop, rt.drop); + unwind = 82; + _170 = false; + rt.drop(_155); rt.hashClear(map3, rt.drop, rt.drop); unwind = 0; rt.hashDrop(map3, rt.drop, rt.drop); @@ -2248,95 +2288,109 @@ export function blown(log: Log.Log, id: rt.u32, at: rt.u8): void { b6: { b7: { b8: { - if (unwind === 0) { - throw e; - } - if (unwind === 76) { - break b4; - } - if (unwind === 77) { - rt.dequeDrop(queue, rt.drop); - break b3; - } - if (unwind === 78) { - break b5; - } - if (unwind === 79) { - rt.drop(_48); - break b6; - } - if (unwind === 80) { - break b6; - } - if (unwind === 81) { - rt.drop(_38); - break b7; - } - if (unwind === 82) { - break b7; - } - if (unwind === 83) { - rt.drop(_30); - break b8; - } - if (unwind === 84) { - break b8; - } - if (unwind === 85) { - rt.dropAll(v); - break b3; - } - if (unwind === 88) { - if (!_152) { + b9: { + if (unwind === 0) { + throw e; + } + if (unwind === 82) { break b4; } - rt.drop(_139); - break b4; - } - if (unwind === 90) { - if (_153) { - rt.drop(_106); + if (unwind === 83) { + rt.dequeDrop(queue, rt.drop); + break b3; + } + if (unwind === 84) { + break b5; } - } else if (unwind === 92) { - if (_154) { - rt.drop(_97); + if (unwind === 85) { + rt.drop(_48); + break b6; } - } else if (unwind === 94) { - if (_155) { - rt.drop(_88); + if (unwind === 86) { + rt.drop(_63); + break b7; } - } else if (unwind !== 96) { - if (unwind === 98) { - if (!_157) { - break b5; + 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(_76); - break b5; + rt.drop(_157); + break b4; } - if (unwind === 100) { - if (!_158) { + 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; + } + rt.drop(_85); break b5; } - rt.drop(_67); + if (!_177) { + break b5; + } + rt.drop(_76); break b5; } - if (!_159) { - break b5; + if (!_174) { + break b3; } - rt.drop(_58); - break b5; - } - if (!_156) { + rt.btreeDrop(map2, rt.drop, rt.drop); break b3; } - rt.btreeDrop(map2, rt.drop, rt.drop); + rt.drop(_29); break b3; } - rt.drop(_29); + rt.drop(_37); break b3; } - rt.drop(_37); - break b3; + rt.dropAll(v2, drop$Bomb_Guard); } rt.drop(_45); break b3; diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index dff38654c..3acc1c90d 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -3,9 +3,11 @@ import * as rt from "./rt.ts"; import type * as First from "./drops/iters.First.ts"; import type * as Bomb from "./drops.Bomb.ts"; +import type * as Entries from "./drops.Entries.ts"; import type * as Held from "./drops.Held.ts"; import type * as Key from "./drops.Key.ts"; import type * as Pair from "./drops.Pair.ts"; +import type * as Text from "./drops.Text.ts"; import * as Wrap from "./drops.Wrap.ts"; import type * as Guard from "./model.Guard.ts"; import type * as Tally from "./model.Tally.ts"; @@ -34,13 +36,29 @@ export function drop$Arc_str_Arc_str(_1: [rt.Arc, rt.Arc]): void } } +export function drop$Bomb_Guard(_1: [Bomb.Bomb, Guard.Guard]): void { + let unwind: number = 0; + try { + unwind = 4; + rt.drop(_1[0]); + unwind = 0; + rt.drop(_1[1]); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(_1[1]); + throw e; + } +} + export function drop$ControlFlow_Guard_u32(_1: rt.Result): void { if (!_1.ok) { rt.drop(_1.error); } } -export function drop$Guard_Bomb_Held(_1: [Guard.Guard, Bomb.Bomb, Held.Held]): void { +export function drop$Guard_Entries_Bomb_Guard_Held(_1: [Guard.Guard, Entries.Entries, Held.Held]): void { let unwind: number = 0; try { unwind = 5; @@ -189,6 +207,12 @@ export function drop$Result_u8_Key(_1: rt.Result): void { } } +export function drop$Text(_1: Text.Text): void { + if (_1.tag !== "Borrowed") { + rt.drop(_1._0); + } +} + export function drop$Vec_Bomb(value: Bomb.Bomb[]): void { rt.dropAll(value); } diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index ce577f09c..621e7caa8 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -49,6 +49,20 @@ pub struct Pair { second: Guard, } +/// Borrowed text or a value that drops, as moq-net's `path::Repr` is: generic over a +/// lifetime alone. +pub enum Text<'a> { + Borrowed(&'a str), + Owned(Guard), +} + +/// A type generic over a lifetime alone, holding one that is. +pub struct Named<'a>(Text<'a>); + +/// Pairs of its type parameters, as a map's entries are: each pair drops its halves in +/// order, the second after the first panics. +pub struct Entries(Vec<(K, V)>); + /// Run scenario `arg % 19`, panicking at the point `arg / 19 % 8` names, if any: what /// every value std holds drops, where Rust drops it, and in Rust's order. pub fn run(log: &Log, id: u32, arg: u8) { @@ -125,6 +139,8 @@ pub fn run(log: &Log, id: u32, arg: u8) { second: guard(44), }, ]; + let _borrowed = Named(Text::Borrowed("text")); + let _owned = Named(Text::Owned(guard(45))); check(2); let nested = Wrap { id: id + 50, @@ -595,7 +611,11 @@ fn blown(log: &Log, id: u32, at: u8) { first: bomb(1, true), second: guard(2), }), - 3 => drop((guard(1), bomb(2, true), Held::One(guard(3)))), + 3 => drop(( + guard(1), + Entries(list![(bomb(2, true), guard(3)), (bomb(4, false), guard(5))]), + Held::One(guard(6)), + )), 4 => { let mut map = BTreeMap::new(); map.insert(key(1, Fault::Sound), bomb(1, false)); diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 1f4fe34bc..9be63375e 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -209,6 +209,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { /// What drops the `ty` in `value`, or `None` if JS would see nothing drop. pub fn drop_value(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Option { + // Lifetimes don't change how a value drops, so a type generic over them alone, as a + // class's field may be, has the glue of any instance. + let ty = self.tcx.erase_and_anonymize_regions(ty); if !self.drops(ty) { return None; } @@ -282,6 +285,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { if rustc && let Some(sym) = super::mir::glue::shim(self, ty, span) { return Some(super::mir::glue::call(sym, value)); } + if let ty::Tuple(_) = ty.kind() + && ty.has_param() + { + return Some(self.drop_fn(ty, span)?.call(vec![value])); + } // A census lowers a generic function over its type parameters, where only an // instance can say what the glue is. if rustc && self.refusals.is_some() && (ty.has_param() || ty.has_aliases()) { @@ -294,12 +302,32 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { /// A function dropping a `ty`, or `None` if JS would see nothing drop or translation /// refused it: `rt.drop` for a value with `[Symbol.dispose]`, or else its glue. pub fn drop_fn(&mut self, ty: Ty<'tcx>, span: Span) -> Option { + let ty = self.tcx.erase_and_anonymize_regions(ty); if !self.drops(ty) { return None; } if self.disposable(ty, span) { return Some(Expr::Rt("drop".into())); } + // A tuple over type parameters, as a generic class's glue holds, has no glue of + // rustc's until an instance: each element in order, as that glue drops them. + if let ty::Tuple(tys) = ty.kind() + && ty.has_param() + { + let value = Expr::ident("value"); + let mut steps = Vec::new(); + for (i, elem) in tys.iter().enumerate() { + let element = value.clone().index(Expr::lit(i.to_string())); + if let Some(dropped) = self.drop_value(element, elem, span) { + steps.push((dropped, self.drop_panics(elem, &mut Default::default()))); + } + } + let param = Param { + name: "value".into(), + ty: Some(self.ty(ty, span)), + }; + return Some(Expr::Arrow(vec![param], Type::Builtin("void"), unwinding(steps))); + } // Over type parameters, as a generic class's glue is, a function of its own. if ty.has_param() || ty.has_aliases() { let param = Param { From 1572755c55becfd2ce1ecf6cdf643029ebd00268 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:36:59 -0700 Subject: [PATCH 18/18] test(ts): cover rt.once through bool::then Core's MIR now calls a closure std's Option and Result consume through rt.callOnce, which left rt.once, still bool::then's, untested. A named closure that Fn calls, given to then on true and on false, covers its call and its discard. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3 --- ts/fixtures/task/expected/drops/closures.ts | 434 +++++++++++--------- ts/fixtures/task/src/drops/closures.rs | 4 + 2 files changed, 250 insertions(+), 188 deletions(-) diff --git a/ts/fixtures/task/expected/drops/closures.ts b/ts/fixtures/task/expected/drops/closures.ts index 835e315f4..ece40ccd6 100644 --- a/ts/fixtures/task/expected/drops/closures.ts +++ b/ts/fixtures/task/expected/drops/closures.ts @@ -363,49 +363,59 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { let p!: Guard.Guard; let _177!: Guard.Guard; let other!: (a0: rt.u32) => rt.u32; - let _233!: boolean; - let _234!: boolean; - let _235!: boolean; - let _236!: boolean; - let _237!: boolean; - let _238!: boolean; - let _239!: boolean; - let _240!: boolean; - let _241!: boolean; - let _242!: boolean; - let _243!: boolean; - let _244!: boolean; - let _245!: boolean; - let _246!: boolean; - let _247!: boolean; - let _248!: boolean; - let _249!: boolean; + let r!: Guard.Guard; + let s!: Guard.Guard; + let _205!: Guard.Guard; + let skipped!: () => rt.u32; + 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 _271!: boolean; + let _272!: boolean; + let _273!: boolean; + let _274!: boolean; + let _275!: boolean; + let _276!: boolean; + let _277!: boolean; + let _278!: boolean; + let _279!: boolean; + let _280!: boolean; + let _281!: boolean; let unwind: number = 0; try { - _249 = false; - _248 = false; - _247 = false; - _246 = false; - _245 = false; - _244 = false; - _243 = false; - _242 = false; - _241 = false; - _240 = false; - _239 = false; - _238 = false; - _237 = false; - _236 = false; - _235 = false; - _234 = false; - _233 = false; + _281 = false; + _280 = false; + _279 = false; + _278 = false; + _277 = false; + _276 = false; + _275 = false; + _274 = false; + _273 = false; + _272 = false; + _271 = false; + _270 = false; + _269 = false; + _268 = false; + _267 = false; + _266 = false; + _265 = false; + _264 = false; + _263 = false; + _262 = false; const guard: (a0: rt.u32) => Guard.Guard = (n2: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n2), Log.clone$Clone(log)); }; const check: (a0: rt.u8) => void = (point: rt.u8): void => { if (point === at) { - const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; - rt.panicFmt(["d", args16[0], " at ", args16[1]]); + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args18[0], " at ", args18[1]]); } }; if (!(at < 8)) { @@ -419,15 +429,15 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { none = id; } _16 = guard(1); - unwind = 101; + unwind = 114; const _19: Guard.Guard = guard(2); - unwind = 125; - _249 = true; + unwind = 142; + _281 = true; a = _16; - _248 = true; + _280 = true; b = _19; const _23: rt.u32 | undefined = some; - _249 = false; + _281 = false; const captured = check; const captured2 = a; const mapped: rt.u32 | undefined = map$Option_u32_u32_blasted_closure3(_23, rt.closure((n3: rt.u32): rt.u32 => { @@ -449,7 +459,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured2); })); - _248 = false; + _280 = false; const captured3 = b; const unmapped: rt.u32 | undefined = map$Option_u32_u32_blasted_closure3(none, rt.closure((n4: rt.u32): rt.u32 => { let unwind3: number = 0; @@ -474,22 +484,22 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { const ok: rt.Result = rt.Ok(id); const err: rt.Result = rt.Err(id); _47 = guard(3); - unwind = 99; + unwind = 112; _50 = guard(4); - unwind = 98; + unwind = 111; _53 = guard(5); - unwind = 97; + unwind = 110; const _56: Guard.Guard = guard(6); - unwind = 120; - _247 = true; + unwind = 137; + _279 = true; c = _47; - _246 = true; + _278 = true; d = _50; - _245 = true; + _277 = true; e = _53; - _244 = true; + _276 = true; f = _56; - _247 = false; + _279 = false; const captured4 = c; const _60: rt.Result = map$Result_u32_u32_u32_discarded_closure4(ok, rt.closure((n5: rt.u32): rt.u32 => { let unwind4: number = 0; @@ -509,7 +519,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured4); })); - _246 = false; + _278 = false; const captured5 = d; const values: [rt.Result, rt.Result] = [_60, map$Result_u32_u32_u32_discarded_closure4(err, rt.closure((n6: rt.u32): rt.u32 => { let unwind5: number = 0; @@ -529,7 +539,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured5); }))]; - _245 = false; + _277 = false; const captured6 = e; const _65: rt.Result = mapErr$Result_u32_u32_u32_discarded_closure6(ok, rt.closure((n7: rt.u32): rt.u32 => { let unwind6: number = 0; @@ -549,7 +559,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured6); })); - _244 = false; + _276 = false; const captured7 = check; const captured8 = f; const errors: [rt.Result, rt.Result] = [_65, mapErr$Result_u32_u32_u32_discarded_closure6(err, rt.closure((n8: rt.u32): rt.u32 => { @@ -574,14 +584,14 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(values[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(values[1], f, rt.u32Display, rt.u32Display)], f), (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(errors[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(errors[1], f, rt.u32Display, rt.u32Display)], f)]; Log.note(log, rt.fmtFormat(["result ", args4[0], " ", args4[1]])); _84 = guard(7); - unwind = 93; + unwind = 106; const _87: Guard.Guard = guard(8); - unwind = 117; - _243 = true; + unwind = 134; + _275 = true; g = _84; - _242 = true; + _274 = true; h = _87; - _243 = false; + _275 = false; const captured9 = g; const _91: rt.Result = andThen$Result_u32_u32_u32_discarded_closure8(ok, rt.closure((n9: rt.u32): rt.Result => { let unwind8: number = 0; @@ -602,7 +612,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured9); })); - _242 = false; + _274 = false; const captured10 = h; const chained: [rt.Result, rt.Result] = [_91, andThen$Result_u32_u32_u32_discarded_closure8(err, rt.closure((n10: rt.u32): rt.Result => { let unwind9: number = 0; @@ -624,22 +634,22 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(captured10); }))]; _98 = guard(9); - unwind = 91; + unwind = 104; const _101: Guard.Guard = guard(10); - unwind = 114; - _241 = true; + unwind = 131; + _273 = true; i = _98; - _240 = true; + _272 = true; j = _101; - _241 = false; + _273 = false; const captured11 = i; const _105: rt.Result = inspectErr$Result_u32_u32_discarded_closure10(ok, rt.closure((_2: rt.u32): void => { let unwind10: number = 0; try { unwind10 = 9; const part = Guard.id(captured11); - const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; - Log.note(log, rt.fmtFormat(["inspect ", args18[0]])); + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; + Log.note(log, rt.fmtFormat(["inspect ", args20[0]])); unwind10 = 0; rt.drop(captured11); } catch (e11) { @@ -652,7 +662,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured11); })); - _240 = false; + _272 = false; const captured12 = check; const captured13 = j; const inspected: [rt.Result, rt.Result] = [_105, inspectErr$Result_u32_u32_discarded_closure10(err, rt.closure((_22: rt.u32): void => { @@ -661,8 +671,8 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind11 = 10; captured12(3); const part2 = Guard.id(captured13); - const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part2, f)]; - Log.note(log, rt.fmtFormat(["inspect ", args20[0]])); + const args22: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part2, f)]; + Log.note(log, rt.fmtFormat(["inspect ", args22[0]])); unwind11 = 0; rt.drop(captured13); } catch (e12) { @@ -678,15 +688,15 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(chained[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(chained[1], f, rt.u32Display, rt.u32Display)], f), (f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtResult(inspected[0], f, rt.u32Display, rt.u32Display), (f: rt.Formatter) => rt.fmtResult(inspected[1], f, rt.u32Display, rt.u32Display)], f)]; Log.note(log, rt.fmtFormat(["chained ", args6[0], " ", args6[1]])); _124 = guard(11); - unwind = 89; + unwind = 102; const _127: Guard.Guard = guard(12); - unwind = 111; - _239 = true; + unwind = 128; + _271 = true; k = _124; - _238 = true; + _270 = true; l = _127; const _132: rt.u32 | undefined = some; - _239 = false; + _271 = false; const captured14 = check; const captured15 = k; const _131: rt.u32 = mapOr$Option_u32_u32_discarded_closure12(_132, 0, rt.closure((n11: rt.u32): rt.u32 => { @@ -708,7 +718,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured15); })); - _238 = false; + _270 = false; const captured16 = l; const part3 = [_131, mapOr$Option_u32_u32_discarded_closure12(none, 0, rt.closure((n12: rt.u32): rt.u32 => { let unwind13: number = 0; @@ -731,15 +741,15 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.u32Display(part3[0], f), (f: rt.Formatter) => rt.u32Display(part3[1], f)], f)]; Log.note(log, rt.fmtFormat(["map_or ", args8[0]])); _150 = guard(13); - unwind = 87; + unwind = 100; const _153: Guard.Guard = guard(14); - unwind = 108; - _237 = true; + unwind = 125; + _269 = true; m = _150; - _236 = true; + _268 = true; n = _153; const yes: boolean = some !== undefined; - _237 = false; + _269 = false; const captured17 = m; const _159: rt.u32 | undefined = rt.boolThen(yes, rt.closure((): rt.u32 => { let unwind14: number = 0; @@ -759,7 +769,7 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured17); }), rt.drop); - _236 = false; + _268 = false; const captured18 = n; const part4 = [_159, rt.boolThen(!yes, rt.closure((): rt.u32 => { let unwind15: number = 0; @@ -782,14 +792,14 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtTuple([(f: rt.Formatter) => rt.fmtOption(part4[0], f, rt.u32Display), (f: rt.Formatter) => rt.fmtOption(part4[1], f, rt.u32Display)], f)]; Log.note(log, rt.fmtFormat(["then ", args10[0]])); _177 = guard(15); - unwind = 85; + unwind = 98; const _180: Guard.Guard = guard(16); - unwind = 104; - _235 = true; + unwind = 121; + _267 = true; o = _177; - _234 = true; + _266 = true; p = _180; - _235 = false; + _267 = false; const captured19 = check; const captured20 = o; const plus: (a0: rt.u32) => rt.u32 = rt.closure((n13: rt.u32): rt.u32 => { @@ -798,8 +808,8 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { }, (): void => { rt.drop(captured20); }); - _234 = false; - _233 = true; + _266 = false; + _265 = true; const captured21 = p; other = rt.closure((n14: rt.u32): rt.u32 => { return rt.u32Add(n14, Guard.id(captured21)); @@ -807,57 +817,87 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(captured21); }); const _191: rt.u32 | undefined = map$Option_u32_u32_discarded_closure16(some, plus); - _233 = false; + _265 = false; const _194: rt.u32 | undefined = map$Option_u32_u32_discarded_closure16(none, other); const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(_191, f, rt.u32Display), (f: rt.Formatter) => rt.fmtOption(_194, f, rt.u32Display)]; Log.note(log, rt.fmtFormat(["by ref ", args12[0], " ", args12[1]])); - const captured22 = guard(17); - const _213: rt.u32 | undefined = some; - const captured23 = check; - const captured24 = rt.closure((n15: rt.u32): rt.u32 => { - return rt.u32Add(n15, Guard.id(captured22)); + _205 = guard(18); + unwind = 95; + const _208: Guard.Guard = guard(19); + unwind = 117; + _264 = true; + r = _205; + _263 = true; + s = _208; + _264 = false; + const captured22 = r; + _263 = false; + _262 = true; + const captured23 = s; + skipped = rt.closure((): rt.u32 => { + return Guard.id(captured23); + }, (): void => { + rt.drop(captured23); + }); + const _219: rt.u32 | undefined = rt.boolThen(yes, rt.once(rt.closure((): rt.u32 => { + return Guard.id(captured22); }, (): void => { rt.drop(captured22); + })), rt.drop); + _262 = false; + const _221: rt.u32 | undefined = rt.boolThen(!yes, rt.once(skipped), rt.drop); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(_219, f, rt.u32Display), (f: rt.Formatter) => rt.fmtOption(_221, f, rt.u32Display)]; + Log.note(log, rt.fmtFormat(["then by ref ", args14[0], " ", args14[1]])); + const captured24 = guard(17); + const _240: rt.u32 | undefined = some; + const captured25 = check; + const captured26 = rt.closure((n15: rt.u32): rt.u32 => { + return rt.u32Add(n15, Guard.id(captured24)); + }, (): void => { + rt.drop(captured24); }); - const part5 = map$Option_u32_u32_blasted_closure3(_213, rt.closure((n16: rt.u32): rt.u32 => { + const part5 = map$Option_u32_u32_blasted_closure3(_240, rt.closure((n16: rt.u32): rt.u32 => { let unwind16: number = 0; try { unwind16 = 5; - captured23(6); - const _017: rt.u32 = captured24(n16); + captured25(6); + const _019: rt.u32 = captured26(n16); unwind16 = 0; - rt.drop(captured24); - return _017; + rt.drop(captured26); + return _019; } catch (e17) { if (unwind16 === 0) { throw e17; } - rt.drop(captured24); + rt.drop(captured26); throw e17; } }, (): void => { - rt.drop(captured24); + rt.drop(captured26); })); - const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part5, f, rt.u32Display)]; - Log.note(log, rt.fmtFormat(["nested ", args14[0]])); + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part5, f, rt.u32Display)]; + Log.note(log, rt.fmtFormat(["nested ", args16[0]])); check(7); - _233 = false; - _234 = false; - _235 = false; - _236 = false; - _237 = false; - _238 = false; - _239 = false; - _240 = false; - _241 = false; - _242 = false; - _243 = false; - _244 = false; - _245 = false; - _246 = false; - _247 = false; - _248 = false; - _249 = false; + _262 = false; + _263 = false; + _264 = false; + _265 = false; + _266 = false; + _267 = false; + _268 = false; + _269 = false; + _270 = false; + _271 = false; + _272 = false; + _273 = false; + _274 = false; + _275 = false; + _276 = false; + _277 = false; + _278 = false; + _279 = false; + _280 = false; + _281 = false; } catch (e2) { b2: { b3: { @@ -867,119 +907,137 @@ export function discarded(log: Log.Log, id: rt.u32, at: rt.u8): void { b7: { b8: { b9: { - if (unwind === 0) { - throw e2; - } - if (unwind === 85) { - rt.drop(_177); - break b8; - } - if (unwind === 87) { - rt.drop(_150); - break b7; - } - if (unwind === 89) { - rt.drop(_124); - break b6; - } - if (unwind === 91) { - rt.drop(_98); - break b5; - } - if (unwind === 93) { - rt.drop(_84); - break b4; - } - if (unwind === 97) { - rt.drop(_53); - } else if (unwind !== 98) { - if (unwind === 99) { - break b9; + b10: { + if (unwind === 0) { + throw e2; } - if (unwind === 101) { - rt.drop(_16); - break b2; - } - if (unwind === 104) { - if (_233) { - rt.drop(other); - } - if (_234) { - rt.drop(p); - } - if (!_235) { - break b8; - } - rt.drop(o); - break b8; + if (unwind === 95) { + rt.drop(_205); + break b9; } - if (unwind === 108) { + if (unwind === 98) { + rt.drop(_177); break b8; } - if (unwind === 111) { + if (unwind === 100) { + rt.drop(_150); break b7; } - if (unwind === 114) { + if (unwind === 102) { + rt.drop(_124); break b6; } - if (unwind === 117) { + if (unwind === 104) { + rt.drop(_98); break b5; } - if (unwind === 120) { + if (unwind === 106) { + rt.drop(_84); break b4; } - break b3; + if (unwind === 110) { + rt.drop(_53); + } else if (unwind !== 111) { + if (unwind === 112) { + break b10; + } + if (unwind === 114) { + rt.drop(_16); + break b2; + } + if (unwind === 117) { + if (_262) { + rt.drop(skipped); + } + if (_263) { + rt.drop(s); + } + if (!_264) { + break b9; + } + rt.drop(r); + break b9; + } + if (unwind === 121) { + break b9; + } + if (unwind === 125) { + break b8; + } + if (unwind === 128) { + break b7; + } + if (unwind === 131) { + break b6; + } + if (unwind === 134) { + break b5; + } + if (unwind === 137) { + break b4; + } + break b3; + } + rt.drop(_50); } - rt.drop(_50); + rt.drop(_47); + break b3; + } + if (_265) { + rt.drop(other); + } + if (_266) { + rt.drop(p); + } + if (_267) { + rt.drop(o); } - rt.drop(_47); - break b3; } - if (_236) { + if (_268) { rt.drop(n); } - if (_237) { + if (_269) { rt.drop(m); } } - if (_238) { + if (_270) { rt.drop(l); } - if (_239) { + if (_271) { rt.drop(k); } } - if (_240) { + if (_272) { rt.drop(j); } - if (_241) { + if (_273) { rt.drop(i); } } - if (_242) { + if (_274) { rt.drop(h); } - if (_243) { + if (_275) { rt.drop(g); } } - if (_244) { + if (_276) { rt.drop(f); } - if (_245) { + if (_277) { rt.drop(e); } - if (_246) { + if (_278) { rt.drop(d); } - if (_247) { + if (_279) { rt.drop(c); } } - if (_248) { + if (_280) { rt.drop(b); } - if (_249) { + if (_281) { rt.drop(a); } } diff --git a/ts/fixtures/task/src/drops/closures.rs b/ts/fixtures/task/src/drops/closures.rs index 26ac4416f..e773f30ef 100644 --- a/ts/fixtures/task/src/drops/closures.rs +++ b/ts/fixtures/task/src/drops/closures.rs @@ -161,6 +161,10 @@ pub(super) fn discarded(log: &Log, id: u32, at: u8) { }; let other = move |n: u32| n + p.id(); log.note(format!("by ref {:?} {:?}", some.map(plus), none.map(other))); + let (r, s) = (guard(18), guard(19)); + let kept = move || r.id(); + let skipped = move || s.id(); + log.note(format!("then by ref {:?} {:?}", yes.then(kept), (!yes).then(skipped))); // A closure that owns one that owns a guard, as a helper's would. let q = guard(17); let inner = move |n: u32| n + q.id();