diff --git a/quest/m2/README.md b/quest/m2/README.md index f8886e6ba..861fbdbc6 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -30,6 +30,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values +- [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 - [Share constant aggregates](/quest/m2/ts-const-share.md) - `Ok(())` and other constants nothing writes into are one frozen object - [Translate moq-net's model to TypeScript](/quest/m2/ts-model/README.md) - the model translates with kio, moq-clock, and moq-pattern, 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-drop.md b/quest/m2/ts-drop.md index a78ec7fe0..00fb28c76 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,27 @@ 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 (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 +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/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. diff --git a/ts/README.md b/ts/README.md index 234a972a9..22d9a3168 100644 --- a/ts/README.md +++ b/ts/README.md @@ -182,7 +182,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/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index 0ab82426d..513fbc583 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(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); }), 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,48 +152,48 @@ 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, 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, 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); } @@ -199,56 +202,56 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void rt.hashInsert(pairs, key, copy$Tally(local)); 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 = 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 = 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 = rank(data.data[data.start + i4], 0); - const e: rt.Entry = rt.entry(ranks, _313); + const _326: Rank.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, undefined, 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; @@ -261,24 +264,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; })); @@ -297,16 +300,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; })); @@ -315,12 +318,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); @@ -330,47 +333,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 [_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 [_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; @@ -379,19 +382,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; })); @@ -407,10 +410,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, undefined, 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/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index b6e473738..001cac8a1 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) { @@ -252,9 +252,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 => { @@ -346,7 +350,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)); @@ -359,13 +363,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; @@ -441,7 +445,7 @@ export function fullRange(out: rt.ByteVec): undefined { /** Iterators of `Option`, which keep each `None` apart from their end. */ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { - const _68: (a0: rt.u8, a1: rt.ByteVec) => rt.u8 | undefined = (b2: rt.u8, calls2: rt.ByteVec): rt.u8 | undefined => { + const _83: (a0: rt.u8, a1: rt.ByteVec) => rt.u8 | undefined = (b2: rt.u8, calls2: rt.ByteVec): rt.u8 | undefined => { rt.byteVecPush(calls2, b2); return rt.optionMap(rt.u8CheckedSub(b2, 1), (b3: rt.u8): rt.u8 => { return rt.u8Div(b3, 2); @@ -504,23 +508,32 @@ 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 calls: rt.ByteVec = new rt.ByteVec(); const first2: rt.u8 | undefined = rt.byteSliceFirst(data); rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.iterToByteVec(rt.iterTake(rt.iterSuccessors(first2, (b8: rt.u8): rt.u8 | undefined => { - return _68(b8, calls); + return _83(b8, calls); }), rt.usizeRem(data.length, 4))))); rt.byteVecExtendFromSlice(out, rt.byteVecSlice(calls)); rt.byteVecPush(out, rt.iterCount(rt.iterSuccessors(first2, (b9: rt.u8): rt.u8 | undefined => { - return _68(b9, calls); + return _83(b9, calls); })) & 0xff); rt.byteVecExtendFromSlice(out, rt.byteVecSlice(calls)); const iter3: Gaps.Gaps = { data, at: 0 }; while (true) { - const _99: rt.u8 | undefined | rt.Done = Gaps.next$Iterator(iter3); - if (_99 === rt.DONE) { + const _114: rt.u8 | undefined | rt.Done = Gaps.next$Iterator(iter3); + if (_114 === rt.DONE) { break; } - rt.byteVecPush(out, rt.optionMapOr(_99, 170, (b10: rt.u8): rt.u8 => { + rt.byteVecPush(out, rt.optionMapOr(_114, 170, (b10: rt.u8): rt.u8 => { return b10; })); } 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/fixtures/lang/src/iters.rs b/ts/fixtures/lang/src/iters.rs index a049156ff..42f821f7e 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)); // `successors` calls its closure on each item as it yields it, and never again once // it returned `None`. let mut calls = Vec::new(); diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 6588d6663..3e2f33df6 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 87 -- Function instances: 68 +- Refusals: 92 +- Function instances: 69 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -12,8 +12,8 @@ | 7 | an assignment through a reference to `_` | fixtures/reject/src/lib.rs:17:2 | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:28:15 | | 6 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:16:13 | -| 5 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:56:2 | -| 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:405:2 | +| 6 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:1 | +| 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:422:2 | | 4 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:108:2 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:128:20 | @@ -21,19 +21,22 @@ | 2 | a field of `_` | fixtures/reject/src/lib.rs:296:7 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:187:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:173:23 | -| 2 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:1 | +| 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:414:79 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:167:2 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:85:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:87:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:86:3 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:90:3 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | fixtures/reject/src/lib.rs:301:6 | -| 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:416:18 | +| 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:433:18 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:324:6 | +| 1 | `_` of `_`, which drops `_`, which is not supported yet | fixtures/reject/src/lib.rs:56:13 | | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:356:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | fixtures/reject/src/lib.rs:366:6 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:332:9 | +| 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | fixtures/reject/src/lib.rs:249:26 | | 1 | a `_` cast from `_` to `_` | fixtures/reject/src/lib.rs:119: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:254:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:200:51 | | 1 | a coercion to `_` | fixtures/reject/src/lib.rs:379:2 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:103:2 | @@ -44,9 +47,10 @@ | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:89:3 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:75:2 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:416:13 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:306:52 | -| 1 | constructing `_` | fixtures/reject/src/lib.rs:423:53 | +| 1 | constructing `_` | fixtures/reject/src/lib.rs:440:53 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:306:52 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:88:3 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:83:3 | @@ -58,42 +62,44 @@ The type or module each refused type or path belongs to. | Count | API | First | | ---: | --- | --- | -| 7 | `std::borrow::Cow` | fixtures/reject/src/lib.rs:405:2 | +| 7 | `std::borrow::Cow` | fixtures/reject/src/lib.rs:422:2 | | 6 | `Option` | fixtures/reject/src/lib.rs:28:15 | | 6 | `f64` | fixtures/reject/src/lib.rs:7:14 | | 6 | `u8` | fixtures/reject/src/lib.rs:65:10 | | 4 | `std::string::String` | fixtures/reject/src/lib.rs:95:16 | -| 4 | `std::vec::Vec` | fixtures/reject/src/lib.rs:56:2 | | 4 | `u32` | fixtures/reject/src/lib.rs:16:13 | +| 3 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:56:13 | | 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:124:2 | | 2 | `Iterator` | fixtures/reject/src/lib.rs:167:2 | | 2 | `Meters` | fixtures/reject/src/lib.rs:108:2 | +| 2 | `Noisy` | fixtures/reject/src/lib.rs:56:13 | | 2 | `Poll` | fixtures/reject/src/lib.rs:128:20 | -| 2 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:301:6 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:280:16 | +| 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:173:23 | +| 2 | `std::iter::Take` | fixtures/reject/src/lib.rs:414:79 | +| 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:208:8 | | 2 | `std::option::Option` | fixtures/reject/src/lib.rs:301:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:144:2 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:33:4 | -| 2 | `{closure}` | fixtures/reject/src/lib.rs:398:15 | +| 2 | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:187:1 | | 1 | `FusedIterator` | fixtures/reject/src/lib.rs:241:1 | | 1 | `HashMap` | fixtures/reject/src/lib.rs:324:6 | | 1 | `Hasher` | fixtures/reject/src/lib.rs:332:9 | | 1 | `IntToFloat` | fixtures/reject/src/lib.rs:119:2 | -| 1 | `Noisy` | fixtures/reject/src/lib.rs:254:20 | | 1 | `[u16; 1]` | fixtures/reject/src/lib.rs:273:22 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:11:16 | +| 1 | `into_keys` | fixtures/reject/src/lib.rs:56:13 | | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:200:51 | -| 1 | `std::iter::Map` | fixtures/reject/src/lib.rs:173:23 | +| 1 | `std::iter::Flatten` | fixtures/reject/src/lib.rs:249:26 | | 1 | `std::iter::Rev` | fixtures/reject/src/lib.rs:194:14 | | 1 | `std::mem` | fixtures/reject/src/lib.rs:49:18 | | 1 | `std::ops::RangeFrom` | fixtures/reject/src/lib.rs:296:48 | | 1 | `std::ops::RangeTo` | fixtures/reject/src/lib.rs:296:7 | -| 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:208:8 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:154:11 | | 1 | `std::str` | fixtures/reject/src/lib.rs:390:4 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:149:2 | -| 1 | `std::time::Duration` | fixtures/reject/src/lib.rs:431:2 | +| 1 | `std::time::Duration` | fixtures/reject/src/lib.rs:448:2 | | 1 | `u64` | fixtures/reject/src/lib.rs:119:2 | | 1 | `{async closure}` | fixtures/reject/src/lib.rs:75:2 | @@ -102,7 +108,7 @@ The type or module each refused type or path belongs to. | Count | Construct | Type or path | First | | ---: | --- | --- | --- | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:28:15 | -| 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:405:2 | +| 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:422:2 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:128:20 | | 2 | `_`: 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:95:16 | @@ -110,18 +116,20 @@ 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:65:10 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:144:2 | | 2 | an assignment through a reference to `_` | `u8` | fixtures/reject/src/lib.rs:66:3 | -| 2 | an iterator that owns `_`, which drops, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:56:2 | -| 2 | an iterator that owns `_`, which drops, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:398:15 | +| 2 | dropping `_`, which is not supported yet | `std::iter::Take` | fixtures/reject/src/lib.rs:414:79 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:108:2 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | `std::collections::HashMap`, `std::option::Option` | fixtures/reject/src/lib.rs:301:6 | -| 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:416:18 | +| 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:433:18 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:324:6 | +| 1 | `_` of `_`, which drops `_`, which is not supported yet | `into_keys`, `std::collections::HashMap`, `Noisy` | fixtures/reject/src/lib.rs:56:13 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::count` | fixtures/reject/src/lib.rs:280:38 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::filter` | fixtures/reject/src/lib.rs:280:16 | | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:356: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:366:6 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:332:9 | +| 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:249:26 | | 1 | a `_` cast from `_` to `_` | `IntToFloat`, `u64`, `f64` | fixtures/reject/src/lib.rs:119: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:254: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:200:51 | | 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:379:2 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:103:2 | @@ -135,10 +143,10 @@ The type or module each refused type or path belongs to. | 1 | an assignment through a reference to `_` | `u32` | fixtures/reject/src/lib.rs:17:2 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:187:1 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:241:1 | -| 1 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:254:20 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:416:13 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:8:2 | | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | -| 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:423:53 | +| 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:440:53 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:173:23 | | 1 | constructing `_` from another crate | `std::iter::Rev` | fixtures/reject/src/lib.rs:194:14 | | 1 | hashing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | @@ -146,10 +154,10 @@ The type or module each refused type or path belongs to. | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:221:2 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:273:22 | | 1 | replacing the value behind a reference to `_` | `std::string::String` | fixtures/reject/src/lib.rs:384:4 | -| 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:417:2 | +| 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:434:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:154:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:97:10 | -| 1 | unsupported call to `_` | `::add_assign` | fixtures/reject/src/lib.rs:431:2 | +| 1 | unsupported call to `_` | `::add_assign` | fixtures/reject/src/lib.rs:448:2 | | 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:49:18 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:208:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:374:4 | @@ -168,8 +176,8 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:208:8: unsupported call to `std::ops::Range::::contains::` - fixtures/reject/src/lib.rs:374:4: unsupported call to `core::slice::::copy_within::>` - fixtures/reject/src/lib.rs:390:4: unsupported call to `core::str::::split::<[char; 2]>` -- fixtures/reject/src/lib.rs:417:2: unsupported call to ` as std::ops::Deref>::deref` -- fixtures/reject/src/lib.rs:431:2: unsupported call to `::add_assign` +- fixtures/reject/src/lib.rs:434:2: unsupported call to ` as std::ops::Deref>::deref` +- fixtures/reject/src/lib.rs:448:2: unsupported call to `::add_assign` @@ -207,22 +215,23 @@ The type or module each refused type or path belongs to. -
an iterator that owns `_`, which drops, which is not supported yet (5) +
dropping a closure that owns a value that drops, which is not supported yet (6) -- fixtures/reject/src/lib.rs:56:2: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:249:4: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:254:20: an iterator that owns `Noisy`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:398:15: an iterator that owns `{closure@fixtures/reject/src/lib.rs:398:48: 398:56}`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:399:13: an iterator that owns `{closure@fixtures/reject/src/lib.rs:399:32: 399:39}`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:51:1: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:397:12: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:401:12: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:412:18: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:414:15: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:415:13: dropping a closure that owns a value that drops, which is not supported yet
a variant of `_`, which is not supported: either is the same JS string (4) -- fixtures/reject/src/lib.rs:405:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:406:30: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:407:27: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:412:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:422:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:423:30: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:424:27: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:429:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string
@@ -279,10 +288,10 @@ 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 (2) +
dropping `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:51:1: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:396:18: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:414:79: dropping `std::iter::Take>`, which is not supported yet +- fixtures/reject/src/lib.rs:415:62: dropping `std::iter::Take>`, which is not supported yet
@@ -325,7 +334,7 @@ The type or module each refused type or path belongs to.
`_` is not supported yet (1) -- fixtures/reject/src/lib.rs:416:18: `std::borrow::Cow<'_, [u8]>` is not supported yet +- fixtures/reject/src/lib.rs:433:18: `std::borrow::Cow<'_, [u8]>` is not supported yet
@@ -335,6 +344,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:56: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:356:2: ` as PartialEq>::ne` through a held type's own, which is not supported yet @@ -353,12 +368,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:249: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:119: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:254:30: a `zip` of `std::iter::Map, {closure@fixtures/reject/src/lib.rs:254:15: 254: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:200:51: a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:200:15: 200:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` @@ -419,6 +446,12 @@ The type or module each refused type or path belongs to.
+
an iterator that owns `_`, which drops, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:416:13: an iterator that owns `Noisy`, which drops, which is not supported yet + +
+
arithmetic on `_` (1) - fixtures/reject/src/lib.rs:8:2: arithmetic on `f64` @@ -433,7 +466,7 @@ The type or module each refused type or path belongs to.
constructing `_` (1) -- fixtures/reject/src/lib.rs:423:53: constructing `std::borrow::Cow<'_, std::sync::Arc>` +- fixtures/reject/src/lib.rs:440:53: constructing `std::borrow::Cow<'_, std::sync::Arc>`
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index c766a70c2..9c991b1dd 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:37:42 unsupported call to `std::mem::size_of_val::` at fixtures/reject/src/lib.rs:49:18 dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:51:1 -an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:56:11 +`into_keys` of `std::collections::HashMap`, which drops `Noisy`, which is not supported yet at fixtures/reject/src/lib.rs:56:13 `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:65:10 an assignment through a reference to `u8` at fixtures/reject/src/lib.rs:66:3 a zero-sized constant of type `{async closure@fixtures/reject/src/lib.rs:74:10: 74:18}` at fixtures/reject/src/lib.rs:75:2 @@ -46,8 +46,8 @@ constructing `std::iter::Map` from another crate at fixtures/reject/src/lib.rs:194:14 a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:200:15: 200:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` at fixtures/reject/src/lib.rs:200:51 unsupported call to `std::ops::Range::::contains::` at fixtures/reject/src/lib.rs:208:8 -an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:249:4 -an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:254: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:249:26 +a `zip` of `std::iter::Map, {closure@fixtures/reject/src/lib.rs:254:15: 254: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:254:30 a mutable borrow of a subslice of `u32`, which JS would copy, having no views at fixtures/reject/src/lib.rs:259:13 an assignment through a reference to `std::pin::Pin<&mut Noisy>` at fixtures/reject/src/lib.rs:267:2 replacing the value behind a reference to `[u16; 1]` at fixtures/reject/src/lib.rs:273:22 @@ -63,20 +63,25 @@ comparing `std::vec::Vec` as a key, which is not supported yet at fixtures/r `HashMap::contains_key` of `std::collections::HashMap` by `u8`, which is not supported yet at fixtures/reject/src/lib.rs:324:6 unsupported call to `core::slice::::copy_within::>` at fixtures/reject/src/lib.rs:374:4 a coercion to `std::sync::Arc<[u8]>` at fixtures/reject/src/lib.rs:379:2 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:405:2 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:407:27 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:406:30 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:412:2 -`std::borrow::Cow<'_, [u8]>` is not supported yet at fixtures/reject/src/lib.rs:416:18 -unsupported call to ` as std::ops::Deref>::deref` at fixtures/reject/src/lib.rs:417:2 -constructing `std::borrow::Cow<'_, std::sync::Arc>` at fixtures/reject/src/lib.rs:423:53 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:422:2 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:424:27 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:423:30 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:429:2 +`std::borrow::Cow<'_, [u8]>` is not supported yet at fixtures/reject/src/lib.rs:433:18 +unsupported call to ` as std::ops::Deref>::deref` at fixtures/reject/src/lib.rs:434:2 +constructing `std::borrow::Cow<'_, std::sync::Arc>` at fixtures/reject/src/lib.rs:440:53 `&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:383:15 replacing the value behind a reference to `std::string::String` at fixtures/reject/src/lib.rs:384:4 unsupported call to `core::str::::split::<[char; 2]>` at fixtures/reject/src/lib.rs:390:4 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:396:18 -an iterator that owns `{closure@fixtures/reject/src/lib.rs:398:48: 398:56}`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:398:15 -an iterator that owns `{closure@fixtures/reject/src/lib.rs:399:32: 399:39}`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:399:13 -unsupported call to `::add_assign` at fixtures/reject/src/lib.rs:431:2 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:397:12 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:401:12 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:412:18 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:414:15 +dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:414:79 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:415:13 +dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:415:62 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:416:13 +unsupported call to `::add_assign` at fixtures/reject/src/lib.rs:448:2 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:167:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:187:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:221:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index a8ac6c866..4c124bc4d 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -50,11 +50,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 } @@ -244,14 +244,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. @@ -390,14 +390,31 @@ pub fn split_chars(s: &str) -> usize { s.split(['a', 'b']).count() } -/// Each drops its closure, and the `Noisy` it owns, when it is done with it. +/// `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) +} + +/// Each drops its closure, and the `Noisy` it owns, when it is done with it, as +/// `successors` does the item it holds next. pub fn owning_lazy(cond: bool) -> usize { let (a, b, c) = (Noisy(1), Noisy(2), Noisy(3)); let then = cond.then(move || a).is_some() as usize; // Through a reference, each owns its `Noisy` whole rather than a copy of its field. let walked = std::iter::successors(Some(0u8), move |_| Some((&b).0)).take(2).count(); let made = std::iter::from_fn(move || Some((&c).0)).take(2).count(); - then + walked + made + let held = std::iter::successors(Some(Noisy(4)), |_| None).count(); + then + walked + made + held } /// A `Cow` is a JS string, which keeps no variant to match on or ask about. diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index b073cc738..be3d062ed 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", @@ -51,6 +51,7 @@ roots = [ "cow_made", "pushed", "split_chars", + "discarded_closure", "owning_lazy", "duration_assign", "missing", 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 8face4d27..8a16837c3 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -1,13 +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"; @@ -15,7 +19,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 % 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 { @@ -41,42 +45,44 @@ 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, 13), 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)); }; @@ -86,8 +92,20 @@ export function run(log: Log.Log, id: rt.u32, arg: rt.u8): void { rt.panicFmt(["d", args18[0], " at ", args18[1]]); } }; - const _13: rt.u8 = rt.u8Rem(arg, 13); - if (_13 === 4) { + const _13: rt.u8 = rt.u8Rem(arg, 19); + 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 === 18) { + spent(log, id, at); + } else if (_13 === 4) { ordered(log, id, at); } else if (_13 === 5) { hashed(log, id, at); @@ -107,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 = 205; + unwind = 216; const _19 = { tag: "One", _0: guard(1) } as Held.Held; v.push(_19); v.push({ tag: "Empty" } as Held.Held); _29 = guard(2); - unwind = 204; + unwind = 215; const _32: Guard.Guard = guard(3); - unwind = 205; + unwind = 216; v.push({ tag: "Two", _0: _29, _1: _32 } as Held.Held); - unwind = 203; + unwind = 214; held_ = v; check(1); arc = new rt.Arc({ tag: "One", _0: guard(4) } as Held.Held); - unwind = 224; - _378 = true; + unwind = 235; + _386 = true; shared = rt.arcClone(arc); - unwind = 202; - _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 = 222; - _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 = 201; + unwind = 212; const _85 = { tag: "One", _0: guard(5) } as Held.Held; v2.push(_85); - unwind = 222; + unwind = 233; mutex = new rt.Mutex(v2); - unwind = 220; - _376 = true; + unwind = 231; + _384 = true; _91 = guard(6); - unwind = 200; + unwind = 211; const _94: Guard.Guard = guard(7); - unwind = 220; + unwind = 231; boxed = { tag: "Two", _0: _91, _1: _94 } as Held.Held; - unwind = 218; - _375 = true; + unwind = 229; + _383 = true; const _98: Held.Held = { tag: "One", _0: guard(8) }; - unwind = 199; + 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 = 218; + unwind = 229; drop$Option_Box_Held(maybe); - unwind = 224; - _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 = 198; + unwind = 209; const _137: Guard.Guard = guard(11); - unwind = 197; + 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 = 196; + unwind = 207; const _144: Guard.Guard = guard(21); - unwind = 195; + unwind = 206; guarded = new Wrap.Wrap({ id: _141, log: _143, inner: _144 }); check(1); _152 = guard(31); - unwind = 194; + unwind = 205; const _155: Guard.Guard = guard(32); - unwind = 193; + unwind = 204; _151 = { tag: "Two", _0: _152, _1: _155 } as Held.Held; const _158: Guard.Guard = guard(33); - unwind = 216; - _374 = true; + unwind = 227; + _382 = true; pair = new Pair.Pair({ first: _151, second: _158 }); v3 = []; - unwind = 192; + unwind = 203; _166 = guard(41); - unwind = 191; + unwind = 202; const _169: Guard.Guard = guard(42); - unwind = 192; + unwind = 203; v3.push(new Pair.Pair({ first: _166, second: _169 })); _175 = guard(43); - unwind = 190; + unwind = 201; const _178: Guard.Guard = guard(44); - unwind = 192; + unwind = 203; v3.push(new Pair.Pair({ first: _175, second: _178 })); - unwind = 189; + 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 = 188; - v4 = []; - unwind = 187; - const _193: rt.u32 = rt.u32Add(id, 60); + const _193: rt.u32 = rt.u32Add(id, 50); _195 = Log.clone$Clone(log); - unwind = 186; - const _197: Guard.Guard = guard(61); - unwind = 187; - v4.push(new Wrap.Wrap({ id: _193, log: _195, inner: { tag: "One", _0: _197 } as Held.Held })); - unwind = 185; - 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 = 189; + unwind = 198; drop$Wrap_Vec_Wrap_Held(nested); - unwind = 216; + unwind = 199; + rt.drop(_owned); + unwind = 200; + rt.drop(_borrowed); + unwind = 227; rt.dropAll(pairs); - unwind = 197; - _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 = 184; - const _248: Guard.Guard = guard(71); - unwind = 183; - _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 = 214; - _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 = 182; - const _258: rt.Arc>> = rt.arcClone(shared2); - v5.push(_258); - const _262: rt.Arc>> = rt.arcClone(shared2); - v5.push(_262); - unwind = 181; + 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)]; @@ -276,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 = 214; + unwind = 225; rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); - _373 = false; + _381 = false; } else { - _300 = guard(81); - unwind = 180; - 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 = 212; - _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 = 179; + unwind = 188; check(1); - _372 = false; + _380 = false; rt.arcDrop(arc2, drop$Mutex_Held); check(2); - const _319: rt.Mutex = other.value; - unwind = 178; - const held2: boolean = Held.isSome(_319.value); - unwind = 179; + 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 = 177; + unwind = 186; borrowed = new rt.Arc(lent); - unwind = 210; - _371 = true; + unwind = 221; + _379 = true; again = rt.arcClone(borrowed); - unwind = 208; - _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 = 179; - _370 = false; - _371 = false; + unwind = 188; + _378 = false; + _379 = false; rt.drop(lent); - unwind = 212; + unwind = 223; rt.arcDrop(other, drop$Mutex_Held); - _372 = false; + _380 = false; } } catch (e) { b1: { @@ -344,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 === 177) { - break b4; - } - if (unwind === 178) { - break b3; - } - if (unwind === 179) { - break b3; - } - if (unwind === 180) { - rt.drop(_300); - break b1; - } - if (unwind === 181) { - rt.dropAll(clones, drop$Arc_Wrap_Pair_Held); - break b5; - } - if (unwind === 182) { - rt.dropAll(v5, drop$Arc_Wrap_Pair_Held); - break b5; - } - if (unwind === 183) { - drop$Held(_247); - break b6; - } - if (unwind === 184) { - break b6; - } - if (unwind === 185) { - drop$Wrap_Vec_Wrap_Held(nested); - break b10; - } - if (unwind === 186) { - rt.drop(_195); - break b12; - } - if (unwind === 187) { - break b12; - } - if (unwind === 188) { - break b11; - } - if (unwind === 189) { - break b10; - } - if (unwind === 190) { - rt.drop(_175); - break b13; - } - if (unwind === 191) { - rt.drop(_166); - break b13; - } - if (unwind === 192) { - break b13; - } - if (unwind === 193) { - drop$Held(_151); - break b8; - } - if (unwind === 194) { - rt.drop(_152); - break b8; - } - if (unwind === 195) { - break b8; - } - if (unwind === 196) { - rt.drop(_143); - break b7; - } - if (unwind === 197) { - break b7; - } - if (unwind === 198) { - rt.drop(_135); - break b1; - } - if (unwind === 199) { - drop$Option_Box_Held(maybe); - break b19; - } - if (unwind === 200) { - rt.drop(_91); - break b18; - } - if (unwind === 201) { - rt.dropAll(v2, drop$Held); - break b17; - } - if (unwind === 202) { - break b16; - } - if (unwind === 203) { - break b14; - } - if (unwind === 204) { - rt.drop(_29); - break b20; - } - if (unwind === 205) { - break b20; - } - if (unwind === 208) { - if (_370) { - rt.arcDrop(again); - } - } else if (unwind !== 210) { - if (unwind === 212) { - break b2; - } - if (unwind === 214) { - break b5; + 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; } - if (unwind === 216) { - break b9; - } - if (unwind === 218) { - break b19; - } - if (unwind === 220) { - break b18; - } - if (unwind === 222) { - 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); } } @@ -523,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); @@ -536,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); } } @@ -2053,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 }); }; @@ -2095,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); @@ -2106,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); @@ -2235,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; } - } else if (unwind === 92) { - if (_154) { - rt.drop(_97); + if (unwind === 84) { + break b5; } - } else if (unwind === 94) { - if (_155) { - rt.drop(_88); + if (unwind === 85) { + rt.drop(_48); + break b6; } - } else if (unwind !== 96) { - if (unwind === 98) { - if (!_157) { - break b5; + if (unwind === 86) { + rt.drop(_63); + break b7; + } + if (unwind === 87) { + rt.drop(_54); + break b7; + } + if (unwind === 88) { + break b7; + } + if (unwind === 89) { + break b6; + } + if (unwind === 90) { + rt.drop(_38); + break b8; + } + if (unwind === 91) { + break b8; + } + if (unwind === 92) { + rt.drop(_30); + break b9; + } + if (unwind === 93) { + break b9; + } + if (unwind === 94) { + rt.dropAll(v); + break b3; + } + if (unwind === 97) { + if (!_170) { + break b4; } - rt.drop(_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/drops/iters.Count.ts b/ts/fixtures/task/expected/drops/iters.Count.ts new file mode 100644 index 000000000..7d75599f3 --- /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 part = rt.iterCount(rt.iterFilter(rt.iterSlice(rt.byteSliceView(rt.byteVecSlice(Log.text(self.sink)))), (_2: rt.u8): boolean => { + return _2 === 10; + })); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part, 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 new file mode 100644 index 000000000..957b79b8c --- /dev/null +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -0,0 +1,2716 @@ +// 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_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"; +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 _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 _539!: rt.Iter; + 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 { + _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)); + }; + const check: (a0: rt.u8) => void = (point: rt.u8): void => { + if (point === at) { + 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 = 337; + 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 = 336; + const _28: Guard.Guard | rt.Done = iterI < iterS.length ? iterS[iterI++] : rt.DONE; + if (_28 === rt.DONE) { + break; + } + unwind = 335; + g = _28; + if (!(Guard.id(g) === rt.u32Add(id, 2))) { + unwind = 336; + rt.drop(g); + } else { + unwind = 336; + rt.drop(g); + break; + } + } + unwind = 0; + rt.dropAll(iterS, rt.drop, iterI); + _39 = guard(4); + unwind = 334; + _42 = guard(5); + unwind = 333; + const _45: Guard.Guard = guard(6); + unwind = 0; + iter2 = rt.iterSlice([_39, _42, _45], rt.drop); + while (true) { + unwind = 332; + const _49: Guard.Guard | rt.Done = iter2.next(); + if (_49 === rt.DONE) { + break; + } + unwind = 331; + g2 = _49; + const part = Guard.id(g2); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; + Log.note(log, rt.fmtFormat(["array ", args2[0]])); + if (Guard.id(g2) === rt.u32Add(id, 5)) { + check(1); + } + unwind = 332; + rt.drop(g2); + } + unwind = 0; + rt.drop(iter2); + iter3 = rt.iterOption(guard(7), rt.drop); + while (true) { + unwind = 330; + const _79: Guard.Guard | rt.Done = iter3.next(); + if (_79 === rt.DONE) { + break; + } + unwind = 329; + g3 = _79; + const part2 = Guard.id(g3); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part2, f)]; + Log.note(log, rt.fmtFormat(["option ", args4[0]])); + unwind = 330; + rt.drop(g3); + } + unwind = 0; + rt.drop(iter3); + v2 = []; + unwind = 328; + 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 = 327; + const part3 = even.length; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part3, f)]; + Log.note(log, rt.fmtFormat(["even ", args6[0]])); + v3 = []; + unwind = 326; + 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 = 327; + rest = rt.ownedTake(rt.ownedSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); + unwind = 356; + _610 = true; + const part4 = 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; + } + }); + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part4, f)]; + Log.note(log, rt.fmtFormat(["next ", args8[0]])); + check(3); + _610 = false; + const part5 = rt.ownedCount(rest, rt.drop, rt.drop); + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part5, f)]; + Log.note(log, rt.fmtFormat(["count ", args10[0]])); + v4 = []; + unwind = 325; + const _199: Guard.Guard = guard(17); + v4.push(_199); + const _204: Guard.Guard = guard(18); + v4.push(_204); + unwind = 356; + peek = rt.iterPeekable(rt.iterSlice(v4, rt.drop), rt.drop); + unwind = 354; + _609 = true; + first = rt.peekableNextIf(peek, (g6: Guard.Guard): boolean => { + return Guard.id(g6) === rt.u32Add(id, 17); + }); + unwind = 324; + second = rt.peekableNextIf(peek, (g7: Guard.Guard): boolean => { + return Guard.id(g7) === rt.u32Add(id, 99); + }); + unwind = 323; + const _221: boolean = first !== undefined; + const _224: boolean = second !== undefined; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_221, f), (f: rt.Formatter) => rt.fmtBool(_224, f)]; + Log.note(log, rt.fmtFormat(["peek ", args12[0], " ", args12[1]])); + check(4); + _609 = false; + rt.drop(peek); + v5 = []; + 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 = 323; + _237 = rt.iterSlice(v5, rt.drop); + unwind = 352; + _608 = true; + v6 = []; + unwind = 321; + const _259: Guard.Guard = guard(23); + v6.push(_259); + unwind = 352; + const _255: Guard.Guard[] = v6; + _608 = false; + 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 part6 = rt.ownedCount(pairs, rt.drop, drop$Guard_Guard); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part6, f)]; + Log.note(log, rt.fmtFormat(["zip ", args14[0]])); + v7 = []; + unwind = 320; + const _282: Guard.Guard = guard(24); + v7.push(_282); + unwind = 323; + _277 = rt.iterSlice(v7, rt.drop); + unwind = 350; + _607 = true; + v8 = []; + unwind = 319; + const _289: Guard.Guard = guard(25); + v8.push(_289); + const _294: Guard.Guard = guard(26); + v8.push(_294); + unwind = 350; + const _285: Guard.Guard[] = v8; + _607 = false; + const _276: rt.Iter = rt.iterChain(_277, rt.iterSlice(_285, rt.drop)); + unwind = 323; + _607 = false; + _275 = rt.iterRev(_276); + unwind = 318; + nth = rt.ownedNth(_275, 1, rt.drop); + unwind = 348; + _606 = true; + rt.drop(_275); + _606 = false; + const part7 = 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; + } + }); + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part7, f)]; + Log.note(log, rt.fmtFormat(["nth ", args16[0]])); + check(5); + v9 = []; + 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 = 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 = 346; + _605 = true; + v10 = []; + unwind = 316; + const _339: Guard.Guard | undefined = guard(30); + v10.push(_339); + v10.push(undefined as Guard.Guard | undefined); + const _348: Guard.Guard | undefined = guard(31); + v10.push(_348); + const _354: Guard.Guard | undefined = guard(32); + v10.push(_354); + unwind = 346; + _333 = rt.iterFlatten(rt.iterSlice(v10, rt.drop), (value: Guard.Guard | undefined) => rt.iterOption(value, rt.drop), true); + unwind = 315; + found = rt.iterFind(_333, (g10: Guard.Guard): boolean => { + return Guard.id(g10) === rt.u32Add(id, 31); + }, rt.drop); + unwind = 314; + rt.drop(_333); + _605 = false; + const _366: rt.u32 = 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; + } + }); + const _369: boolean = found !== undefined; + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_366, f), (f: rt.Formatter) => rt.fmtBool(_369, f)]; + Log.note(log, rt.fmtFormat(["found ", args18[0], " ", args18[1]])); + check(6); + v11 = []; + 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 = 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 { + 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 = 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 = 314; + 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; + 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; + } + }); + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(folded, f), (f: rt.Formatter) => rt.u32Display(_427, f)]; + Log.note(log, rt.fmtFormat(["fold ", args20[0], " ", args20[1]])); + v13 = []; + unwind = 311; + v14 = []; + unwind = 310; + const _444: Guard.Guard = guard(39); + v14.push(_444); + const _449: Guard.Guard = guard(40); + v14.push(_449); + unwind = 311; + v13.push(v14); + v15 = []; + unwind = 309; + const _458: Guard.Guard = guard(41); + v15.push(_458); + unwind = 311; + v13.push(v15); + v16 = []; + unwind = 308; + const _467: Guard.Guard = guard(42); + v16.push(_467); + const _472: Guard.Guard = guard(43); + v16.push(_472); + unwind = 311; + v13.push(v16); + unwind = 314; + flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); + unwind = 344; + _604 = true; + const front: 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; + } + }); + const back: rt.u32 = 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 args22: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(front, f), (f: rt.Formatter) => rt.u32Display(back, f)]; + Log.note(log, rt.fmtFormat(["flat ", args22[0], " ", args22[1]])); + _604 = false; + rt.drop(flat); + 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 _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)); + 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.ownedSkip(rt.iterSlice(five(44), rt.drop), 2, rt.drop); + unwind = 307; + _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.ownedStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); + unwind = 305; + 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; + 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 = 344; + rt.drop(_509); + _518 = rt.iterRev(rt.ownedTake(rt.iterSlice(five(59), rt.drop), 3, rt.drop)); + unwind = 342; + _603 = true; + const _524: Guard.Guard[] = []; + _603 = false; + _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); + unwind = 304; + _603 = false; + 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; + 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 = 344; + rt.drop(_517); + _529 = rt.iterRev(rt.ownedSkip(rt.iterSlice(five(64), rt.drop), 2, rt.drop)); + unwind = 340; + _602 = true; + const _535: Guard.Guard[] = []; + _602 = false; + _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); + unwind = 303; + _602 = false; + 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; + 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 = 344; + rt.drop(_528); + _539 = rt.ownedStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); + unwind = 302; + 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; + 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 = 344; + rt.drop(_539); + 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]])); + unwind = 346; + _604 = false; + rt.drop(found); + unwind = 324; + _605 = false; + _606 = false; + rt.drop(second); + unwind = 354; + rt.drop(first); + unwind = 0; + _609 = false; + _610 = false; + rt.dropAll(even); + } catch (e) { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + b19: { + b20: { + b21: { + b22: { + b23: { + if (unwind === 0) { + throw e; + } + if (unwind === 302) { + rt.drop(_539); + break b16; + } + if (unwind === 303) { + rt.drop(_528); + break b16; + } + if (unwind === 304) { + rt.drop(_517); + break b16; + } + if (unwind === 305) { + rt.drop(_509); + break b16; + } + if (unwind === 306) { + rt.drop(_499); + break b17; + } + if (unwind === 307) { + break b17; + } + if (unwind === 308) { + rt.dropAll(v16); + break b18; + } + if (unwind === 309) { + rt.dropAll(v15); + break b18; + } + if (unwind === 310) { + rt.dropAll(v14); + break b18; + } + if (unwind === 311) { + break b18; + } + if (unwind === 312) { + rt.dropAll(v12); + break b15; + } + if (unwind === 313) { + rt.dropAll(v11); + break b15; + } + if (unwind === 314) { + break b15; + } + if (unwind === 315) { + rt.drop(_333); + break b14; + } + if (unwind === 316) { + rt.dropAll(v10); + break b14; + } + if (unwind === 317) { + rt.dropAll(v9); + break b13; + } + if (unwind === 318) { + rt.drop(_275); + break b12; + } + if (unwind === 319) { + rt.dropAll(v8); + break b19; + } + if (unwind === 320) { + rt.dropAll(v7); + break b12; + } + if (unwind === 321) { + rt.dropAll(v6); + break b20; + } + if (unwind === 322) { + rt.dropAll(v5); + break b12; + } + if (unwind === 323) { + break b12; + } + if (unwind === 324) { + break b11; + } + if (unwind === 325) { + rt.dropAll(v4); + break b9; + } + if (unwind === 326) { + rt.dropAll(v3); + break b8; + } + if (unwind === 327) { + break b8; + } + if (unwind === 328) { + rt.dropAll(v2); + break b7; + } + if (unwind === 329) { + rt.drop(g3); + break b21; + } + if (unwind === 330) { + break b21; + } + if (unwind === 331) { + rt.drop(g2); + break b22; + } + if (unwind === 332) { + break b22; + } + if (unwind === 333) { + rt.drop(_42); + break b23; + } + if (unwind === 334) { + break b23; + } + if (unwind === 335) { + rt.drop(g); + } else if (unwind !== 336) { + if (unwind === 337) { + rt.dropAll(v); + break b7; + } + if (unwind === 340) { + if (!_602) { + break b16; + } + rt.drop(_529); + break b16; + } + if (unwind === 342) { + if (!_603) { + break b16; + } + rt.drop(_518); + break b16; + } + if (unwind === 344) { + break b16; + } + if (unwind === 346) { + break b14; + } + if (unwind === 348) { + break b13; + } + if (unwind === 350) { + break b19; + } + if (unwind === 352) { + break b20; + } + if (unwind === 354) { + 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 (!_608) { + break b12; + } + rt.drop(_237); + break b12; + } + if (!_607) { + break b12; + } + rt.drop(_277); + break b12; + } + rt.dropAll(v13, drop$Vec_Guard); + break b15; + } + rt.drop(_501); + } + if (_604) { + rt.drop(flat); + } + } + rt.drop(found); + } + if (_605) { + rt.drop(best); + } + } + if (_606) { + rt.drop(nth); + } + } + rt.drop(second); + } + rt.drop(first); + } + if (_609) { + rt.drop(peek); + } + } + if (_610) { + 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 v8!: Guard.Guard[]; + let queue!: rt.VecDeque; + let v9!: Guard.Guard[]; + let hashed!: rt.HashMap; + let v10!: [rt.u32, Guard.Guard][]; + let set!: rt.HashSet; + let v11!: Key.Key[]; + let _320!: boolean; + let _321!: boolean; + let unwind: number = 0; + try { + _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)); + }; + 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 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 = 165; + 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 = 164; + v2 = []; + 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 = 164; + 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 = 162; + v3 = []; + unwind = 161; + const _65: Guard.Guard = guard(7); + v3.push(_65); + unwind = 162; + _60 = rt.iterSlice(v3, rt.drop); + unwind = 170; + _321 = true; + v4 = []; + unwind = 160; + const _72: Guard.Guard = guard(8); + v4.push(_72); + const _77: Guard.Guard = guard(9); + v4.push(_77); + unwind = 170; + const _68: Guard.Guard[] = v4; + _321 = false; + const _59: rt.Iter = rt.iterChain(_60, rt.iterSlice(_68, rt.drop)); + unwind = 162; + _321 = 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 = 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 = 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 = 159; + 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 = 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]])); + _320 = false; + drop$Result_Vec_Guard_Guard(results); + v6 = []; + 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 = 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 { + 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, (v12: Guard.Guard[]): rt.usize => { + let unwind7: number = 0; + try { + unwind7 = 4; + const _08: rt.usize = v12.length; + unwind7 = 0; + rt.dropAll(v12); + return _08; + } catch (e7) { + if (unwind7 === 0) { + throw e7; + } + 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 = 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 = 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 = 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]])); + v8 = []; + 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 = 8; + if (Guard.id(g6) === rt.u32Add(id, 25)) { + check(5); + } + const at2 = rt.idx(same, 0); + unwind8 = 0; + rt.drop(g6); + return same[at2]; + } catch (e8) { + if (unwind8 === 0) { + throw e8; + } + rt.drop(g6); + throw e8; + } + }), 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 = 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(g7) === rt.u32Add(id, 20)) { + check(6); + return g7; + } + return g7; + } catch (e9) { + if (unwind9 === 0) { + throw e9; + } + rt.drop(g7); + throw e9; + } + }); + queue = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, rt.iterSlice(rt.iterToArray(_239, true, rt.drop, rt.drop))); + unwind = 151; + v10 = []; + 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 = 151; + rt.hashDrop(hashed, undefined, rt.drop); + unwind = 153; + rt.dequeDrop(queue, rt.drop); + unwind = 168; + rt.btreeDrop(tree, undefined, rt.drop); + unwind = 162; + _320 = false; + rt.dropAll(chained); + unwind = 164; + rt.dropAll(wider, drop$Guard_u32); + unwind = 0; + rt.dropAll(same); + } catch (e) { + b0: { + b1: { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + b8: { + if (unwind === 0) { + throw e; + } + if (unwind === 147) { + rt.hashDrop(set, rt.drop); + break b8; + } + if (unwind === 148) { + rt.dropAll(v11); + break b8; + } + if (unwind === 149) { + 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 (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.hashDrop(hashed, undefined, rt.drop); + } + rt.dequeDrop(queue, rt.drop); + } + } + rt.btreeDrop(tree, undefined, rt.drop); + } + if (_320) { + 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 _49: rt.usize = keys.length; + const _52: rt.u32 = 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 args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_49, f), (f: rt.Formatter) => rt.u32Display(_52, 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 part = rt.optionMapOr(rt.iterToOption(_85.next()), 0, (k: Key.Key): rt.u32 => { + const _05: rt.u32 = k.id; + rt.drop(k); + return _05; + }); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, 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 part2 = 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; + } + }); + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part2, 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 _134: rt.u32 = 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 args8: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_131, f), (f: rt.Formatter) => rt.u32Display(_134, 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 part3 = _166 !== undefined; + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(part3, 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 part4 = rt.hashLen(map2); + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part4, 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 part5 = rt.optionMapOr(rt.iterToOption(taken.next()), 0, (k2: Key.Key): rt.u32 => { + const _08: rt.u32 = k2.id; + rt.drop(k2); + return _08; + }); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part5, 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 _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]])); + _290 = false; + rt.drop(one); + const _272: rt.ByteVec = Log.text(sink); + unwind = 150; + const part6 = rt.iterSum(rt.iterMap(rt.iterSlice(rt.byteSliceView(rt.byteVecSlice(_272))), (_2: rt.u8): rt.u32 => { + return _2 as rt.u32; + }), rt.u32Add, 0); + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part6, 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 part = list.length; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(part, 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 _140: rt.usize = rt.hashLen(map); + const _143: rt.usize = rt.hashLen(set); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_140, f), (f: rt.Formatter) => rt.usizeDisplay(_143, 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 _252: rt.usize = rt.btreeLen(tree); + const _255: rt.usize = rt.btreeLen(ordered); + const _258: rt.usize = queue.n; + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_252, f), (f: rt.Formatter) => rt.usizeDisplay(_255, f), (f: rt.Formatter) => rt.usizeDisplay(_258, 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 it2!: rt.Iter; + let v2!: Bomb.Bomb[]; + let _after!: Bomb.Bomb; + let v3!: Bomb.Bomb[]; + let map!: rt.BTreeMap; + let _79!: rt.u32; + let it3!: rt.Iter<[rt.u32, Bomb.Bomb]>; + let queue!: rt.VecDeque; + 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 _192!: boolean; + let _193!: boolean; + let _194!: boolean; + let _195!: boolean; + let unwind: number = 0; + try { + _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 = 116; + 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 = 125; + _195 = true; + rt.drop(rt.iterToOption(it.next())); + _195 = false; + rt.drop(it); + _195 = false; + } else if (at === 1) { + v2 = []; + 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; + 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(it2); + } else if (at === 2) { + v3 = []; + 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) { + _194 = true; + map = rt.btreeNew(rt.cmp) as rt.BTreeMap; + unwind = 123; + let iterStart: rt.u32 = 1; + const iterEnd: rt.u32 = 4; + 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)); + } + _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 = 111; + let iterStart2: rt.u32 = 1; + const iterEnd2: rt.u32 = 5; + 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 = 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 _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 = 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 = 108; + v7 = []; + unwind = 107; + const _166: Bomb.Bomb = bomb(1, false); + v7.push(_166); + unwind = 108; + v6.push(v7); + v8 = []; + 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 = 119; + _192 = true; + rt.drop(rt.iterToOption(flat.next())); + _192 = false; + rt.drop(flat); + _192 = false; + } + unwind = 0; + Log.note(log, rt.fmtFormat(["unreached"])); + } catch (e) { + b5: { + b6: { + 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; + } + if (unwind === 110) { + rt.dropAll(v4, drop$u32_Bomb); + break b5; + } + if (unwind === 111) { + rt.dequeDrop(queue, rt.drop); + break b5; + } + 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.drop(it2); + break b5; + } + rt.dropAll(v6, drop$Vec_Bomb); + } + throw e; + } +} + +/** + * 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.ownedCount(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.ownedCount(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.ownedCount(rt.ownedSkip(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.ownedCount(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.ownedCount(_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.ownedCount(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.ownedCount(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.ownedCount(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 e1bbe24ba..3acc1c90d 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -1,10 +1,13 @@ // 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 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"; @@ -33,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; @@ -60,6 +79,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 +119,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 +151,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 +187,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 +207,20 @@ 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); +} + +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 +326,16 @@ 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_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]); +} + //# sourceMappingURL=lib.ts.map diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index b8c3e0cf5..621e7caa8 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,37 @@ pub struct Pair { second: Guard, } -/// Run scenario `arg % 13`, panicking at the point `arg / 13 % 8` names, if any: what +/// 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) { - let at = arg / 13 % 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 % 13 { + 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), @@ -117,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, @@ -587,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/fixtures/task/src/drops/iters.rs b/ts/fixtures/task/src/drops/iters.rs new file mode 100644 index 000000000..6c39f219e --- /dev/null +++ b/ts/fixtures/task/src/drops/iters.rs @@ -0,0 +1,529 @@ +//! 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 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()); + 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(); + // 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 +/// 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())); + // 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| { + 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 => { + // 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() + .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")); +} + +/// 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 e1b53884c..8edcc3842 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, type RangeInclusive } from "./iter.ts"; +import { DONE, type Done, Iter, iterSlice, type RangeInclusive } from "./iter.ts"; import { type Arc, dropAll } from "./task.ts"; // Ordering @@ -568,64 +568,94 @@ const ENTRIES = 0; const KEYS = 1; const VALUES = 2; -/** An iterator of a hash collection: `iter`, `keys`, `values`, `drain`, and the rest. */ -class HashIter extends Iter { +/** + * 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. + */ +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. */ + 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; } + + [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. + 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); + } + } } -/** `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 +667,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,9 +1197,11 @@ 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 { +export class BTreeIter extends Iter implements Disposable { fl: Leaf; fi: number; bl: Leaf; @@ -1140,8 +1209,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. */ + 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 +1230,71 @@ 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; } + + [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 +1302,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); } /** @@ -1265,63 +1375,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[] = []; @@ -1667,17 +1809,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`. */ -class DequeIter extends Iter { +/** + * 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 implements Disposable { 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 { @@ -1691,15 +1838,28 @@ class DequeIter extends Iter { override len(): number { return this.back - this.front; } + + [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}`); @@ -1712,13 +1872,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 eb739dea5..96a292a87 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -7,9 +7,20 @@ // 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. 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 { 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"); @@ -17,6 +28,12 @@ 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; + /** * What only the iterators std implements these traits for have, which Rust calls only * there: declared, not stubbed, so no bundle carries a stub. @@ -33,13 +50,13 @@ export abstract class Iter implements Iterable { /** The next item, or `DONE`. */ abstract next(): T | Done; - /** `nth`, as `next` returns it. */ + /** `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(); } - /** `nth_back`, as `next_back` returns it. */ + /** `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(); @@ -51,6 +68,29 @@ export abstract class Iter implements Iterable { } } +/** An adaptor of `inner`, which drops with it. */ +abstract class Adaptor extends Iter implements Disposable { + readonly inner: Iter; + + constructor(inner: Iter) { + super(); + this.inner = inner; + } + + [Symbol.dispose](): void { + dispose(this.inner); + } +} + +/** 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; @@ -63,19 +103,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`. */ @@ -101,19 +141,36 @@ export function iterSuccessors(first: T | undefined, succ: (item: T) => T | u }); } -/** 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); } -/** `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); +/** 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`, 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 @@ -123,9 +180,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`. */ @@ -144,12 +201,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`. */ @@ -157,24 +215,24 @@ export function iterRev(it: Iter): Iter { return new RevIter(it); } -/** `Iterator::skip`. */ +/** `Iterator::skip` of items that don't drop. */ export function iterSkip(it: Iter, n: number): Iter { return new SkipIter(it, n); } -/** `Iterator::take`. */ +/** `Iterator::take` of items that don't drop. */ export function iterTake(it: Iter, n: number): Iter { return new TakeIter(it, n); } -/** `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`. */ @@ -182,57 +240,64 @@ export function iterMapWhile(it: Iter, f: (item: T) => U | undefined): return new MapWhileIter(it, f); } -/** `Iterator::step_by`, panicking on a step of 0. */ +/** `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`. */ -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`. */ +/** `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`. */ +/** `Iterator::last` of an iterator that drops nothing. */ export function iterLast(it: Iter): T | undefined { - let last: T | undefined; + let last: T | Done = DONE; for (let item = it.next(); item !== DONE; item = it.next()) last = item; - return last; + return iterToOption(last); } -/** `Iterator::nth`. */ +/** `Iterator::nth` of items that don't drop. */ export function iterNth(it: Iter, n: number): T | undefined { return iterToOption(it.nthItem(n)); } @@ -249,21 +314,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`. */ @@ -285,100 +370,834 @@ 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; + } + // Not `dropAll`'s default, which would drop what a collected reference points to. + const collected = () => drop !== undefined && dropAll(out, drop); + try { + for (let item = it.next(); item !== DONE; item = it.next()) out.push(item); + } catch (e) { + if (inPlace) both(collected, () => dropIt?.(it)); + else both(() => dropIt?.(it), collected); + throw e; + } + try { + dropIt?.(it); + } catch (e) { + collected(); + 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); + 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 { + 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; +} + +// 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) { + // 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; + 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, or past a `usize`'s + // greatest, what it skips in one and `n` in another. + const skip = it.n; + it.n = 0; + 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. + 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; } -class SliceIter extends Iter { - private readonly s: ArrayLike; - private front = 0; - private back: number; +// 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; - constructor(s: ArrayLike) { + constructor(s: ArrayLike, drop?: Drop) { super(); this.s = s; this.back = s.length; + this.drop = drop; } next(): T | Done { @@ -392,17 +1211,26 @@ class SliceIter extends Iter { override len(): number { return this.back - this.front; } + + [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 { +class OptionIter extends Iter implements Disposable { 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 { @@ -420,31 +1248,76 @@ class OptionIter extends Iter { override len(): number { return this.some ? 1 : 0; } + + [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. */ -class FromNext extends Iter { +/** An iterator whose `next` is a function of its source, which `drop` drops. */ +class FromNext extends Iter implements Disposable { 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); } + + [Symbol.dispose](): void { + const drop = this.drop; + this.drop = undefined; + drop?.(this.source); + } } -class MapIter extends Iter { - private readonly inner: Iter; - private readonly f: (item: T) => U; +/** + * 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, f: (item: T) => U) { + constructor(inner: Iter) { super(); this.inner = inner; + } + + next(): T | Done { + return this.inner.next(); + } + + override nextBack(): T | Done { + return this.inner.nextBack(); + } + + override len(): number { + return this.inner.len(); + } + + override nthItem(n: number): T | Done { + return this.inner.nthItem(n); + } + + override nthBackItem(n: number): T | Done { + return this.inner.nthBackItem(n); + } +} + +class MapIter extends Adaptor { + private readonly f: (item: T) => U; + + constructor(inner: Iter, f: (item: T) => U) { + super(inner); this.f = f; } @@ -463,32 +1336,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; } @@ -509,14 +1380,8 @@ class FilterMapIter extends Iter { } } -class EnumerateIter extends Iter<[number, T]> { - private readonly inner: Iter; - private index = 0; - - constructor(inner: Iter) { - super(); - this.inner = inner; - } +class EnumerateIter extends Adaptor { + index = 0; next(): [number, T] | Done { const item = this.inner.next(); @@ -547,10 +1412,13 @@ class EnumerateIter extends Iter<[number, T]> { } } -/** `Chain`, which stops reading its first iterator once it ends, but not its second. */ -class ChainIter extends Iter { - private a: Iter | undefined; - private b: Iter | undefined; +/** + * `Chain`, which drops its first iterator once it ends, but not its second, as std's + * stops reading it. + */ +class ChainIter extends Iter implements Disposable { + a: Iter | undefined; + b: Iter | undefined; constructor(a: Iter, b: Iter) { super(); @@ -558,11 +1426,25 @@ class ChainIter extends Iter { this.b = b; } + /** Drop `a`, which ended. */ + endA(): void { + const a = this.a; + this.a = undefined; + dispose(a); + } + + /** Drop `b`, which ended from the back. */ + endB(): void { + const b = this.b; + this.b = undefined; + dispose(b); + } + 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(); } @@ -571,37 +1453,69 @@ 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(); } + + [Symbol.dispose](): void { + both( + () => this.endA(), + () => this.endB(), + ); + } } -class ZipIter extends Iter<[A, B]> { - private readonly a: Iter; - private readonly b: Iter; +class ZipIter extends Iter<[A, B]> implements Disposable { + 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]; @@ -610,6 +1524,13 @@ class ZipIter extends Iter<[A, B]> { override len(): number { return Math.min(this.a.len(), this.b.len()); } + + [Symbol.dispose](): void { + both( + () => dispose(this.a), + () => dispose(this.b), + ); + } } /** std's `Zip` of two `TrustedRandomAccess` iterators, which counts the pairs it reads. */ @@ -639,14 +1560,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(); } @@ -668,13 +1582,11 @@ class RevIter extends Iter { } } -class SkipIter extends Iter { - private readonly inner: Iter; - private n: number; +class SkipIter extends Adaptor { + n: number; constructor(inner: Iter, n: number) { - super(); - this.inner = inner; + super(inner); this.n = n; } @@ -694,13 +1606,28 @@ class SkipIter extends Iter { } } -class TakeIter extends Iter { - private readonly inner: Iter; - private n: number; +/** `Skip` of items that drop, which drop as its iterator's own `nth` skips them. */ +class OwnedSkip extends SkipIter { + private readonly drop: Drop; + + constructor(inner: Iter, n: number, drop: Drop) { + super(inner, n); + this.drop = drop; + } + + override next(): T | Done { + if (this.n === 0) return this.inner.next(); + const n = this.n; + this.n = 0; + return nth(this.inner, n, this.drop); + } +} + +class TakeIter extends Adaptor { + n: number; constructor(inner: Iter, n: number) { - super(); - this.inner = inner; + super(inner); this.n = n; } @@ -710,6 +1637,7 @@ class TakeIter extends Iter { return this.inner.next(); } + /** 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--; @@ -746,57 +1674,76 @@ class TakeIter extends Iter { } } -class SkipWhileIter extends Iter { - private readonly inner: Iter; +/** `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; + + constructor(inner: Iter, n: number, drop: Drop) { + super(inner, n); + this.drop = drop; + } + + 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); + } +} + +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; } @@ -806,15 +1753,17 @@ class MapWhileIter extends Iter { } } -class StepByIter extends Iter { - private readonly inner: Iter; - private readonly step: number; - private firstTake = true; +class StepByIter extends Adaptor { + readonly step: number; + firstTake = true; constructor(inner: Iter, step: number) { - super(); - if (step === 0) panic("assertion failed: step != 0"); - this.inner = inner; + super(inner); + // The iterator it was given drops as the panic unwinds. + if (step === 0) { + dispose(inner); + panic("assertion failed: step != 0"); + } this.step = step - 1; } @@ -825,9 +1774,13 @@ class StepByIter extends Iter { } override nextBack(): T | Done { + return this.inner.nthBackItem(this.backIndex()); + } + + /** How far from the back its last item is. */ + 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); + return this.firstTake ? (rem === 0 ? this.step : rem - 1) : rem; } override len(): number { @@ -837,25 +1790,49 @@ class StepByIter extends Iter { } } -class InspectIter extends Iter { - private readonly inner: Iter; +/** `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; - 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; } @@ -864,58 +1841,94 @@ class InspectIter extends Iter { } } -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; - 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. */ + clear(item: T | Done): T | Done { + if (item === DONE && !this.fused) { + const inner = this.inner; + this.inner = undefined; + dispose(inner); + } 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 len(): number { return this.inner === undefined ? 0 : this.inner.len(); } -} -/** `Flatten` and `FlatMap`, which stop reading their outer iterator once it ends. */ -class FlattenIter extends Iter { - private outer: Iter | undefined; - private readonly into: (value: T) => Iter; - private front: Iter | undefined; - private back: Iter | undefined; + [Symbol.dispose](): void { + const inner = this.inner; + this.inner = undefined; + dispose(inner); + } +} - constructor(outer: Iter, into: (value: T) => 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 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(); 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; + dispose(outer); + } + 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) dispose(it); + 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; } @@ -926,38 +1939,74 @@ 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. */ + setFront(it: Iter | undefined): void { + const old = this.front; + this.front = it; + dispose(old); + } + + setBack(it: Iter | undefined): void { + const old = this.back; + this.back = it; + dispose(old); + } + + [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( + () => dispose(outer), + () => + both( + () => dispose(front), + () => dispose(back), + ), + ); + } } -/** `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. */ + 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 { @@ -975,6 +2024,16 @@ export class Peekable extends Iter { if (!this.peeked) return this.inner.len(); return this.item === DONE ? 0 : this.inner.len() + 1; } + + override [Symbol.dispose](): void { + both( + () => dispose(this.inner), + () => { + const item = this.take(); + if (item !== DONE) this.drop?.(item); + }, + ); + } } /** `Peekable::peek`. */ @@ -986,25 +2045,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(); @@ -1016,15 +2069,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 198a97580..746eb30fa 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`. @@ -938,9 +1078,10 @@ pub fn trait_fn(tcx: ty::TyCtxt<'_>, tr: &str, item: &str) -> rustc_hir::def_id: } /// 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", @@ -948,11 +1089,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( @@ -960,22 +1105,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..9be63375e 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(); @@ -182,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; } @@ -255,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()) { @@ -267,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 { @@ -288,6 +343,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 7146eed13..4502d2f87 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,11 +127,26 @@ 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, 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, }); } + // 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 + }; // Items borrowed from what `ty` points at. let items = |iter: Expr, elem: Ty<'tcx>| match ty.is_ref() { true => by_ref(iter, elem), @@ -138,18 +154,19 @@ pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, sp }; match ty.peel_refs().kind() { ty::Slice(elem) | ty::Array(elem, _) => { - Some(items(Expr::rt("iterSlice", vec![library::elements(value, ty)]), *elem)) + let values = each(b, *elem, vec![library::elements(value, ty)]); + Some(items(Expr::rt("iterSlice", values), *elem)) } ty::Adt(adt, args) => match Std::of(tcx, adt.did())? { - Std::Vec => Some(items( - Expr::rt("iterSlice", vec![library::elements(value, ty)]), - args.type_at(0), - )), + Std::Vec => { + let values = each(b, args.type_at(0), vec![library::elements(value, ty)]); + Some(items(Expr::rt("iterSlice", values), args.type_at(0))) + } 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, } @@ -166,24 +183,38 @@ fn by_ref(iter: Expr, elem: Ty<'_>) -> Expr { /// 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) { +/// `::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 `closure`, which an iterator owns, if it owns a value that drops: its captures +/// live in an arrow function's scope, where nothing outside can drop them. +fn closure_no_drops<'tcx>(b: &mut Body<'_, '_, 'tcx>, closure: Ty<'tcx>, span: Span) { + if b.t.drops(closure) { b.t.err( span, - format!("an iterator that owns `{ty}`, which drops, which is not supported yet"), + "dropping a closure that owns a value that drops, which is not supported yet", ); } } @@ -198,7 +229,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>, @@ -232,24 +265,31 @@ 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())), - // Each owns its closure, `F`, which it drops with itself. + // Each owns its closure, `F`, which the runtime's never drops. ["iter", "sources", "from_fn", "from_fn"] => { - no_drops(b, targ(1)?, span); + closure_no_drops(b, targ(1)?, span); return Some(Expr::rt("iterFromFn", args)); } ["iter", "sources", "successors", "successors"] => { - no_drops(b, targ(0)?, span); - no_drops(b, targ(1)?, span); + // `rt.iterSuccessors` would leave the item it holds next undropped. + let item = targ(0)?; + if b.t.drops(item) { + b.t.err( + span, + format!("an iterator that owns `{item}`, which drops, which is not supported yet"), + ); + } + closure_no_drops(b, targ(1)?, span); return Some(Expr::rt("iterSuccessors", 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 { @@ -259,6 +299,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) @@ -270,7 +315,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) { @@ -283,10 +329,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(); @@ -297,7 +339,13 @@ 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); + 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])); } @@ -315,30 +363,103 @@ 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, + "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_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)]; + owned(name, 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" => { + "last" | "nth" => { 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)], + _ => 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)) } "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(), @@ -347,20 +468,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 { @@ -387,19 +528,114 @@ 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 `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 { + 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. @@ -435,35 +671,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) => { @@ -475,20 +731,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/library.rs b/ts/src/lower/library.rs index 325f41134..f682e2573 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -407,8 +407,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") @@ -420,6 +419,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], diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index cde8f76db..694272f45 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -860,9 +860,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(library::elements(value, ty)), ty::Adt(adt, _) if Std::of(tcx, adt.did()) == Some(Std::Vec) => Some(library::elements(value, ty)), diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 422784587..28e2b4a8d 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2280,7 +2280,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/step.rs b/ts/src/lower/mir/step.rs index a2469ef15..0044d56fd 100644 --- a/ts/src/lower/mir/step.rs +++ b/ts/src/lower/mir/step.rs @@ -268,15 +268,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 => { @@ -301,6 +303,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..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: 104 }, (_, arg) => [11, arg]), + ...Array.from({ length: 152 }, (_, arg) => [11, arg]), ].map((script) => Uint8Array.from(script));