diff --git a/quest/m3/README.md b/quest/m3/README.md index 6a895ac7f..8771d9ab8 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -23,7 +23,6 @@ generic std gap is planned here even when moq never calls it. - [Placeholders written to a crate's own fmt::Write](/quest/m3/ts-fmt-calls.md) - `write!` with placeholders into a crate's own writer translates, its `write_str` seeing each call std makes - [Waiting: drop the lang fixture's mul_add allowance](/quest/m3/ts-fma-allowance.md) - the differential fails on any `mul_add` difference again once wasm32's `fma` rounds exactly - [Waiting: type-check in process with tsrs](/quest/m3/ts-tsrs.md) - rust2-ts checks bindings through tsrs instead of `tsc` once it is a stable library -- [Drop order in std's folds and iterators](/quest/m3/ts-drop-order.md) - the values that drop still refused in std's consumers and collects drop as std's do - [A slice of one value behind any &mut](/quest/m3/ts-slice-of-one.md) - `slice::from_mut` and `array::from_mut` of a `&mut u8`, or of an object no place names, translate - [A function pointer or a boxed closure as a string pattern](/quest/m3/ts-fn-patterns.md) - `s.split(p)` of a `fn(char) -> bool` or a `Box bool>` translates, dropping a box it owns where std does - [std's char methods that have no mapping](/quest/m3/ts-char-methods.md) - `is_alphabetic`, `to_lowercase`, `len_utf8`, the escapes, and the rest of `char` translate, called or as values, by std's Unicode version diff --git a/quest/m3/ts-drop-order.md b/quest/m3/ts-drop-order.md deleted file mode 100644 index 10d5a1447..000000000 --- a/quest/m3/ts-drop-order.md +++ /dev/null @@ -1,35 +0,0 @@ -# [M] Drop order in std's folds and iterators - -## Goal - -[rust2-ts](/ts/README.md) translates the values that drop which it still refuses -inside std's iterators, each dropping where std's does, in std's order, -proven by the task fixture's differential tests against native Rust. None appears in moq's census at the pinned revision; rust2 aims to support -all of std. - -## Plan - -Moved from the m2 drop quest on 2026-10-27, once moq-net, its model, and kio had no -drop refusal left ([#139](https://github.com/moq-dev/rust2/pull/139)). `DebugList::entries`, -ranges of bounds that drop, a drain or a B-tree's `range` of a range that drops, a hash -map's `into_keys` and `into_values`, and the closures `for_each` and `fold` own landed in -[#307](https://github.com/moq-dev/rust2/pull/307), with the task fixture's `inside` step. -The closures `reduce`, `max_by`, `min_by`, their `_by_key` forms, `is_sorted_by_key`, and -a map's entries' `or_insert_with`, `or_insert_with_key`, and `and_modify` own landed in -[#438](https://github.com/moq-dev/rust2/pull/438), with its `released` step. -A `skip` of a zip std reads by index, a zip collected in place, and a `flatten` whose -inner iterators hold items once they end landed in -[#446](https://github.com/moq-dev/rust2/pull/446), with its `indexed` and -`flattened` steps. -Each left is refused with a span where std's order is one JS's can't follow yet: - -- A B-tree's `collect` of entries that drop, sorted and deduplicated by the crate's own - impls, as `v.into_iter().collect::>()` of an `O` whose `Ord`, `PartialOrd`, - or `PartialEq` is its own: one that panics or disagrees with itself leaves equal keys - in the order std's sort does, which decides which of them - drop. - -Each `rt.Iter` has a `fold` and `rfold` that drop what it holds where std's do, and the -by-value consumers std folds go through it: build on those rather than `rt.drop`. - -Public API: the translator's output for values that drop in std's iterators. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index f1342a181..62136ebc8 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -22,6 +22,9 @@ - `rt.iterReduce`, `rt.iterMaxBy`, `rt.iterMinBy`, `rt.iterMaxByKey`, and `rt.iterMinByKey` take whether they own their closure, which they drop where std's do, before the `rt.None` they take last, as in `rt.iterReduce(it, f, drops, owns, none)`. +- `rt.iterMaxByKey` and `rt.iterMinByKey` take what drops each key after whether they own + their function, before the `rt.None` they take last, as in + `rt.iterMaxByKey(it, f, lt, drops, drop, owns, dropKey, none)`. - `rt.Hasher` has `Hasher`'s methods, `write`, `u8` to `isize`, `prefix` (`write_length_prefix`), and `str`, and `ints`, an integer slice's `hash_slice`, in place of `word`. A binding's `hash$Hash` writes a signed or pointer-sized integer diff --git a/ts/README.md b/ts/README.md index 1e2ec1b16..23a57026c 100644 --- a/ts/README.md +++ b/ts/README.md @@ -919,8 +919,7 @@ hand-written TS ([bindings](#bindings)). These fail translation: `f16` and `f128`, a `Poll` of a `Poll` of a `Poll`, a future whose output can be pending, an instance of a generic type whose field is a `Poll` of a type parameter that can be pending, a closure that owns a value that drops given to a std function that keeps it other than in an iterator or a -`poll_fn`, or whose mapping doesn't drop it where std's does, and values that drop in some -iterators ([drop order](/quest/m3/ts-drop-order.md)), a `Cow` of other than `str` or a slice, a std +`poll_fn`, or whose mapping doesn't drop it where std's does, a `Cow` of other than `str` or a slice, a std function without a mapping of its own that makes or reads an `Option` whose `None` is `rt.None`, an `Option` of an `Option` of `()` or another `Option`, an instance of a generic type whose field is an `Option` of a type parameter diff --git a/ts/fixtures/lang/nested/expected/nested.ts b/ts/fixtures/lang/nested/expected/nested.ts index fd85600e0..7a36db2e1 100644 --- a/ts/fixtures/lang/nested/expected/nested.ts +++ b/ts/fixtures/lang/nested/expected/nested.ts @@ -285,22 +285,22 @@ export function consumers(data: rt.ByteSlice, out: rt.ByteVec): void { return option_map$0cs071d(o2, (b4: rt.u8): rt.u8 => { return rt.u8Rem(b4, 4); }); - }, rt.cmpLt(rt.cmpOption(rt.cmp)), undefined, undefined, undefined, rt.None))); + }, rt.cmpLt(rt.cmpOption(rt.cmp)), undefined, undefined, undefined, undefined, rt.None))); rt.byteVecPush(out, code(rt.iterMinByKey(it(), (o3: rt.u8 | undefined): rt.u8 | undefined => { return option_map$0cs071d(o3, (b5: rt.u8): rt.u8 => { return rt.u8Rem(b5, 4); }); - }, rt.cmpLt(rt.cmpOption(rt.cmp)), undefined, undefined, undefined, rt.None))); + }, rt.cmpLt(rt.cmpOption(rt.cmp)), undefined, undefined, undefined, undefined, rt.None))); rt.byteVecPush(out, code(rt.iterMaxByKey(it(), (o4: rt.u8 | undefined): rt.u8 | undefined | rt.None => { return option_map$0rbsrz6(o4, (b6: rt.u8): rt.u8 | undefined => { return thenSome$0d5am30(rt.u8Rem(b6, 4) !== 0, rt.u8Rem(b6, 3)); }); - }, rt.cmpLt(rt.cmpOption(rt.cmpOption(rt.cmp), rt.None)), undefined, undefined, undefined, rt.None))); + }, rt.cmpLt(rt.cmpOption(rt.cmpOption(rt.cmp), rt.None)), undefined, undefined, undefined, undefined, rt.None))); rt.byteVecPush(out, code(rt.iterMinByKey(it(), (o5: rt.u8 | undefined): rt.u8 | undefined | rt.None => { return option_map$0rbsrz6(o5, (b7: rt.u8): rt.u8 | undefined => { return thenSome$0d5am30(rt.u8Rem(b7, 4) !== 0, rt.u8Rem(b7, 3)); }); - }, rt.cmpLt(rt.cmpOption(rt.cmpOption(rt.cmp), rt.None)), undefined, undefined, undefined, rt.None))); + }, rt.cmpLt(rt.cmpOption(rt.cmpOption(rt.cmp), rt.None)), undefined, undefined, undefined, undefined, rt.None))); rt.byteVecPush(out, code(rt.iterFind(rt.iterSlice(items), (o6: rt.u8 | undefined): boolean => { return o6 === undefined; }, undefined, rt.None))); diff --git a/ts/fixtures/reject/census.txt b/ts/fixtures/reject/census.txt index c8b9f7795..028de0d3f 100644 --- a/ts/fixtures/reject/census.txt +++ b/ts/fixtures/reject/census.txt @@ -82,7 +82,6 @@ fixtures/reject/src/keys.rs:keyed_across+1:11: unsupported call to `std::ops::Ra fixtures/reject/src/keys.rs:keyed_across+1:32: unsupported call to ` as std::ops::RangeBounds>::contains::` fixtures/reject/src/keys.rs:place_bounds+1:9: unsupported call to `std::ops::Range::<&mut u8>::is_empty` fixtures/reject/src/keys.rs:places_sorted+1:15: unsupported call to ` as std::iter::Iterator>::is_sorted` -fixtures/reject/src/keys.rs:ranked_cells+1:22: `collect` of `std::collections::BTreeMap, places::Noisy>`, which sorts by `std::cell::Cell`'s own `Ord`, of entries that drop, which is not supported yet fixtures/reject/src/keys.rs:set_keys+1:75: comparing `std::collections::BTreeSet` as a key, which is not supported yet fixtures/reject/src/keys.rs:set_keys+1:75: hashing `std::collections::BTreeSet` as a key, which is not supported yet fixtures/reject/src/objects.rs:any_type_id+1:2: unsupported call to `::eq` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 18cbf1dd0..5141e4a3b 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -83,7 +83,6 @@ fixtures/reject/src/keys.rs:keyed_across+1:11: unsupported call to `std::ops::Ra fixtures/reject/src/keys.rs:keyed_across+1:32: unsupported call to ` as std::ops::RangeBounds>::contains::` fixtures/reject/src/keys.rs:place_bounds+1:9: unsupported call to `std::ops::Range::<&mut u8>::is_empty` fixtures/reject/src/keys.rs:places_sorted+1:15: unsupported call to ` as std::iter::Iterator>::is_sorted` -fixtures/reject/src/keys.rs:ranked_cells+1:22: `collect` of `std::collections::BTreeMap, places::Noisy>`, which sorts by `std::cell::Cell`'s own `Ord`, of entries that drop, which is not supported yet fixtures/reject/src/keys.rs:set_keys+1:75: comparing `std::collections::BTreeSet` as a key, which is not supported yet fixtures/reject/src/keys.rs:set_keys+1:75: hashing `std::collections::BTreeSet` as a key, which is not supported yet fixtures/reject/src/objects.rs:any_type_id+1:2: unsupported call to `::eq` diff --git a/ts/fixtures/reject/src/keys.rs b/ts/fixtures/reject/src/keys.rs index 7948d4664..ceec62429 100644 --- a/ts/fixtures/reject/src/keys.rs +++ b/ts/fixtures/reject/src/keys.rs @@ -1,7 +1,5 @@ //! Keys and orders of the crate's own, which the runtime's collections and comparisons don't call. -use crate::places::Noisy; - /// JS compares objects by identity, not by `PartialOrd`. #[derive(PartialEq, PartialOrd)] pub struct Key(pub u8); @@ -72,36 +70,6 @@ pub fn places_sorted(v: &mut [u8]) -> bool { v.iter_mut().is_sorted() } -/// A key ordered by its own `Ord`. -#[derive(Clone, Copy)] -pub struct Ranked(pub u8); - -impl PartialEq for Ranked { - fn eq(&self, other: &Self) -> bool { - self.0 % 4 == other.0 % 4 - } -} - -impl Eq for Ranked {} - -impl PartialOrd for Ranked { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for Ranked { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - (self.0 % 4).cmp(&(other.0 % 4)) - } -} - -/// Entries that drop, sorted by what a cell holds, whose own `Ord` the runtime's sort -/// calls where std's does not. -pub fn ranked_cells(entries: Vec<(std::cell::Cell, Noisy)>) -> usize { - entries.into_iter().collect::>().len() -} - impl PartialEq for u8 { fn eq(&self, other: &Key) -> bool { *self == other.0 diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 735e2cdb6..b7adcea05 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -70,7 +70,6 @@ roots = [ "keys::keyed_across", "keys::place_bounds", "keys::places_sorted", - "keys::ranked_cells", "keys::set_keys", "lopsided", "missing", diff --git a/ts/fixtures/task/expected/core/option.ts b/ts/fixtures/task/expected/core/option.ts index 32ce161ff..720ca5d8a 100644 --- a/ts/fixtures/task/expected/core/option.ts +++ b/ts/fixtures/task/expected/core/option.ts @@ -3,6 +3,7 @@ import * as rt from "../rt.ts"; import type * as Any from "../core/any.Any.ts"; import type * as Part from "../drops/objects.Part.ts"; +import type * as Ranked from "../drops/orders.Ranked.ts"; import type * as Key from "../drops.Key.ts"; import * as Guard from "../model.Guard.ts"; @@ -72,6 +73,13 @@ export function map$0782hf5(self: Key.Key | undefined, f: (a0: Key.Key) => rt.u3 return f(self); } +export function map$1t2fqxi(self: Ranked.Ranked | undefined, f: (a0: Ranked.Ranked) => rt.u32): rt.u32 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + export function map$1raha9y(self: Guard.Guard | undefined, f: (a0: Guard.Guard) => rt.u32): rt.u32 | undefined { if (self === undefined) { return undefined; diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 829fe1122..b7bdcb61b 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -15,6 +15,7 @@ import { looped, collected, drained, extended, compared as iters_compared } from import { run as lists_run } from "./drops/lists.ts"; import { boxed as objects_boxed, shared, anys, fns } from "./drops/objects.ts"; import { run as once_run } from "./drops/once.ts"; +import { orders as orders_orders } from "./drops/orders.ts"; import { released as released_released } from "./drops/released.ts"; import { searched as searched_searched } from "./drops/searched.ts"; import * as Held from "./drops.Held.ts"; @@ -1321,6 +1322,15 @@ export function released(log: Log.Log, id: rt.u32, arg: rt.u8): void { released_released(log, id, arg); } +/** + * Run scenario `arg % 8` of what std drops as it orders: a B-tree's `collect` and `from` + * of keys whose own impls disagree, `max_by_key` and `min_by_key` by keys that drop, and + * a map's `into_keys`' `max` and `min`. The last panics in the sort. + */ +export function orders(log: Log.Log, id: rt.u32, arg: rt.u8): void { + orders_orders(log, id, arg); +} + /** Run scenario `arg % 3` of where std drops a closure given to a string's search or edit. */ export function searched(log: Log.Log, id: rt.u32, arg: rt.u8): void { searched_searched(log, id, arg); diff --git a/ts/fixtures/task/expected/drops/orders.Rank.ts b/ts/fixtures/task/expected/drops/orders.Rank.ts new file mode 100644 index 000000000..e468194b2 --- /dev/null +++ b/ts/fixtures/task/expected/drops/orders.Rank.ts @@ -0,0 +1,18 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; + +/** A key that copies, so a `Cell` of it orders by it, by its own `Ord` modulo 4. */ +export interface Rank { + _0: rt.u8; +} + +export function eq$cmp_PartialEq(self: Rank, other: Rank): boolean { + return rt.u8Rem(self._0, 4) === rt.u8Rem(other._0, 4); +} + +export function cmp$cmp_Ord(self: Rank, other: Rank): rt.Ordering { + return rt.cmp(rt.u8Rem(self._0, 4), rt.u8Rem(other._0, 4)); +} + +//# sourceMappingURL=orders.Rank.ts.map diff --git a/ts/fixtures/task/expected/drops/orders.Ranked.ts b/ts/fixtures/task/expected/drops/orders.Ranked.ts new file mode 100644 index 000000000..2dd91976d --- /dev/null +++ b/ts/fixtures/task/expected/drops/orders.Ranked.ts @@ -0,0 +1,73 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import * as Log from "../log.Log.ts"; + +/** + * A key that logs its drop and each call to its impls: `cmp` orders by `rank`, + * `partial_cmp` by half of it, and `eq` by it modulo 3. `cmp` panics of a rank of 99. + */ +export class Ranked { + id: rt.u32; + rank: rt.u8; + log: Log.Log; + + constructor(id: rt.u32, rank: rt.u8, log: Log.Log) { + this.id = id; + this.rank = rank; + this.log = log; + } + + [Symbol.dispose](): void { + drop$ops_Drop(this); + this.log[Symbol.dispose](); + } +} + +export function drop$ops_Drop(self: Ranked): void { + const arg = self.id; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; + const _4: string = rt.fmtFormat(["k", args2[0], " drop"]); + Log.note(self.log, _4); +} + +export function eq$cmp_PartialEq(self: Ranked, other: Ranked): boolean { + const arg = self.id; + const _12: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg, f); + const arg2 = other.id; + const args2: rt.Fmt[] = [_12, (f: rt.Formatter) => rt.u32Display(arg2, f)]; + const _5: string = rt.fmtFormat(["eq ", args2[0], " ", args2[1]]); + Log.note(self.log, _5); + return rt.u8Rem(self.rank, 3) === rt.u8Rem(other.rank, 3); +} + +export function partialCmp$cmp_PartialOrd(self: Ranked, other: Ranked): rt.Ordering | undefined { + const arg = self.id; + const _12: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg, f); + const arg2 = other.id; + const args2: rt.Fmt[] = [_12, (f: rt.Formatter) => rt.u32Display(arg2, f)]; + const _5: string = rt.fmtFormat(["partial_cmp ", args2[0], " ", args2[1]]); + Log.note(self.log, _5); + return rt.cmp(rt.u8Div(self.rank, 2), rt.u8Div(other.rank, 2)); +} + +export function cmp$cmp_Ord(self: Ranked, other: Ranked): rt.Ordering { + const arg = self.id; + const _12: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg, f); + const arg2 = other.id; + const args2: rt.Fmt[] = [_12, (f: rt.Formatter) => rt.u32Display(arg2, f)]; + const _5: string = rt.fmtFormat(["cmp ", args2[0], " ", args2[1]]); + Log.note(self.log, _5); + if (self.rank !== 99) { + if (other.rank !== 99) { + return rt.cmp(self.rank, other.rank); + } + } + const arg3 = self.id; + const _26: rt.Fmt = (f: rt.Formatter) => rt.u32Display(arg3, f); + const arg4 = other.id; + const args4: rt.Fmt[] = [_26, (f: rt.Formatter) => rt.u32Display(arg4, f)]; + rt.panicFmt(["cmp of k", args4[0], " with k", args4[1]]); +} + +//# sourceMappingURL=orders.Ranked.ts.map diff --git a/ts/fixtures/task/expected/drops/orders.ts b/ts/fixtures/task/expected/drops/orders.ts new file mode 100644 index 000000000..c80b14266 --- /dev/null +++ b/ts/fixtures/task/expected/drops/orders.ts @@ -0,0 +1,194 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import { drop$tuple2_drops_orders_Ranked_model_Guard as lib_drop$tuple2_drops_orders_Ranked_model_Guard } from "../lib.ts"; +import { map$1t2fqxi as option_map$1t2fqxi, map$1raha9y as option_map$1raha9y } from "../core/option.ts"; +import * as Rank from "../drops/orders.Rank.ts"; +import * as Ranked from "../drops/orders.Ranked.ts"; +import * as Log from "../log.Log.ts"; +import * as Guard from "../model.Guard.ts"; + +/** Run scenario `arg % 8`. The last panics in the sort, which aborts before anything drops. */ +export function orders(log: Log.Log, id: rt.u32, arg: rt.u8): void { + const key: (a0: rt.u32, a1: rt.u8) => Ranked.Ranked = (n: rt.u32, rank: rt.u8): Ranked.Ranked => { + return new Ranked.Ranked(rt.u32Add(id, n), rank, Log.clone$Clone(log)); + }; + const entry: (a0: rt.u32, a1: rt.u8) => [Ranked.Ranked, Guard.Guard] = (n2: rt.u32, rank2: rt.u8): [Ranked.Ranked, Guard.Guard] => { + return [key(n2, rank2), Guard.new(rt.u32Add(rt.u32Add(id, n2), 100), Log.clone$Clone(log))] as [Ranked.Ranked, Guard.Guard]; + }; + const keys: (a0: rt.ByteSlice) => Ranked.Ranked[] = (ranks: rt.ByteSlice): Ranked.Ranked[] => { + return rt.iterToArray(rt.iterMap(rt.iterZip(new rt.RangeFrom(1, rt.u32Step), rt.iterSlice(rt.byteSliceView(ranks)), "len"), (_2: [rt.u32, rt.u8]): Ranked.Ranked => { + return key(_2[0], _2[1]); + }), undefined, 12, true); + }; + const entries: (a0: rt.ByteSlice) => [Ranked.Ranked, Guard.Guard][] = (ranks2: rt.ByteSlice): [Ranked.Ranked, Guard.Guard][] => { + return rt.iterToArray(rt.iterMap(rt.iterZip(new rt.RangeFrom(1, rt.u32Step), rt.iterSlice(rt.byteSliceView(ranks2)), "len"), (_23: [rt.u32, rt.u8]): [Ranked.Ranked, Guard.Guard] => { + return entry(_23[0], _23[1]); + }), undefined, 20, true); + }; + const setIds: (a0: rt.BTreeSet) => string = (s: rt.BTreeSet): string => { + return rt.strsJoin(rt.iterToArray(rt.iterMap(rt.btreeKeys(s), (k: Ranked.Ranked): string => { + const _48: rt.u32 = rt.u32Sub(k.id, id); + return rt.fmtToString((f: rt.Formatter) => rt.u32Display(_48, f)); + }), undefined, 12, true), ","); + }; + const mapIds: (a0: rt.BTreeMap) => string = (m: rt.BTreeMap): string => { + return rt.strsJoin(rt.iterToArray(rt.iterMap(rt.btreeIter(m), (_26: [Ranked.Ranked, Guard.Guard]): string => { + const _97: rt.u32 = rt.u32Sub(_26[0].id, id); + const _144: rt.u32 = rt.u32Sub(Guard.id(_26[1]), id); + const args32: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_97, f), (f: rt.Formatter) => rt.u32Display(_144, f)]; + return rt.fmtFormat([args32[0], ":", args32[1]]); + }), undefined, 12, true), ","); + }; + const short: Uint8Array = Uint8Array.of(3, 1, 3, 2, 1, 5, 4, 0); + const long: rt.ByteVec = rt.iterToByteVec(rt.iterMap(new rt.Range(0, 26), (n5: rt.u8): rt.u8 => { + return rt.u8Rem(rt.u8Mul(n5, 7), 9); + }), undefined, true); + const _21: rt.u8 = rt.u8Rem(arg, 8); + if (_21 === 0) { + const part29 = rt.byteSliceFrom(short); + const _24: rt.Iter = rt.iterSlice(keys(part29), rt.drop); + const set: rt.BTreeSet = rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(_24, "next", 12, true, 12), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop); + const part31 = setIds(set); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part31)]; + Log.note(log, rt.fmtFormat(["set ", args2[0]])); + rt.btreeDrop(set, rt.drop); + const _46: rt.Iter = rt.iterSlice(keys(rt.byteSliceFrom(Uint8Array.of())), rt.drop); + const none: rt.BTreeSet = rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(_46, "next", 12, true, 12), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop); + const _53: rt.Iter = rt.iterSlice(keys(rt.byteSliceFrom(Uint8Array.of(7))), rt.drop); + const one: rt.BTreeSet = rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(_53, "next", 12, true, 12), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop); + const _65: rt.usize = rt.btreeLen(none); + const _68: string = setIds(one); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.usizeDisplay(_65, f), (f: rt.Formatter) => rt.fmtPad(f, _68)]; + Log.note(log, rt.fmtFormat(["small ", args4[0], " ", args4[1]])); + rt.btreeDrop(one, rt.drop); + rt.btreeDrop(none, rt.drop); + } else if (_21 === 1) { + const part26 = rt.byteSliceFrom(short); + const _78: rt.Iter<[Ranked.Ranked, Guard.Guard]> = rt.iterSlice(entries(part26), lib_drop$tuple2_drops_orders_Ranked_model_Guard); + const map: rt.BTreeMap = rt.btreeCollect(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeMap, rt.iterToArray(_78, "next", 20, true, 20), 20, true, Ranked.eq$cmp_PartialEq, rt.drop, rt.drop); + const part28 = mapIds(map); + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part28)]; + Log.note(log, rt.fmtFormat(["map ", args6[0]])); + rt.btreeDrop(map, rt.drop, rt.drop); + } else if (_21 === 2) { + const _99: Ranked.Ranked[] = [key(1, 4), key(2, 2), key(3, 4), key(4, 1), key(5, 2)]; + const set2: rt.BTreeSet = rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(rt.iterSlice(_99, rt.drop), "fold", 12, true), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop); + const part23 = setIds(set2); + const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part23)]; + Log.note(log, rt.fmtFormat(["set ", args8[0]])); + const _130: [Ranked.Ranked, Guard.Guard][] = [entry(1, 4), entry(2, 2), entry(3, 4), entry(4, 1), entry(5, 2)]; + const map2: rt.BTreeMap = rt.btreeCollect(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeMap, rt.iterToArray(rt.iterSlice(_130, lib_drop$tuple2_drops_orders_Ranked_model_Guard), "fold", 20, true), 20, true, Ranked.eq$cmp_PartialEq, rt.drop, rt.drop); + const part25 = mapIds(map2); + const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part25)]; + Log.note(log, rt.fmtFormat(["map ", args10[0]])); + rt.btreeDrop(map2, rt.drop, rt.drop); + rt.btreeDrop(set2, rt.drop); + } else if (_21 === 3) { + const part16 = rt.byteVecSlice(long); + const _161: rt.Iter = rt.iterSlice(keys(part16), rt.drop); + const set3: rt.BTreeSet = rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(_161, "next", 12, true, 12), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop); + const part18 = setIds(set3); + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part18)]; + Log.note(log, rt.fmtFormat(["set ", args12[0]])); + rt.iterForEach(rt.btreeKeys(set3, rt.drop), (a0: Ranked.Ranked): undefined => { + a0[Symbol.dispose](); + }, true); + const part19 = rt.byteVecSlice(long); + const _184: rt.Iter<[Ranked.Ranked, Guard.Guard]> = rt.iterSlice(entries(part19), lib_drop$tuple2_drops_orders_Ranked_model_Guard); + const map3: rt.BTreeMap = rt.btreeCollect(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeMap, rt.iterToArray(_184, "next", 20, true, 20), 20, true, Ranked.eq$cmp_PartialEq, rt.drop, rt.drop); + const part21 = mapIds(map3); + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part21)]; + Log.note(log, rt.fmtFormat(["map ", args14[0]])); + rt.iterForEach(rt.btreeIter(map3, rt.drop, rt.drop), (a02: [Ranked.Ranked, Guard.Guard]): undefined => { + lib_drop$tuple2_drops_orders_Ranked_model_Guard(a02); + }, true); + } else if (_21 === 4) { + const _207: rt.Iter<[rt.Cell, Guard.Guard]> = rt.iterMap(rt.iterZip(rt.iterSlice(rt.byteSliceView(rt.byteSliceFrom(Uint8Array.of(5, 1, 9, 2, 6, 3)))), new rt.RangeFrom(1, rt.u32Step), "len"), (_217: [rt.u8, rt.u32]): [rt.Cell, Guard.Guard] => { + const r: rt.u8 = _217[0]; + const n9: rt.u32 = _217[1]; + return [new rt.Cell({ _0: r }), Guard.new(rt.u32Add(id, n9), Log.clone$Clone(log))] as [rt.Cell, Guard.Guard]; + }); + const map4: rt.BTreeMap, Guard.Guard> = rt.btreeCollect(rt.btreeNew(rt.cellBy(Rank.cmp$cmp_Ord)) as rt.BTreeMap, Guard.Guard>, rt.iterToArray(_207, undefined, 12, true), 12, false, rt.cellBy(Rank.eq$cmp_PartialEq), undefined, rt.drop); + const part15 = rt.strsJoin(rt.iterToArray(rt.iterMap(rt.btreeIter(map4), (_219: [rt.Cell, Guard.Guard]): string => { + const _912: Rank.Rank = _219[0].v; + const _1111: rt.u32 = rt.u32Sub(Guard.id(_219[1]), id); + const arg2 = _912._0; + const args36: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(arg2, f), (f: rt.Formatter) => rt.u32Display(_1111, f)]; + return rt.fmtFormat([args36[0], ":", args36[1]]); + }), undefined, 12, true), ","); + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtPad(f, part15)]; + Log.note(log, rt.fmtFormat(["cells ", args16[0]])); + rt.btreeDrop(map4, undefined, rt.drop); + } else if (_21 === 5) { + const by: (a0: Guard.Guard) => Ranked.Ranked = (g: Guard.Guard): Ranked.Ranked => { + const n7: rt.u32 = rt.u32Sub(Guard.id(g), id); + const args34: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(n7, f)]; + Log.note(log, rt.fmtFormat(["key ", args34[0]])); + return key(rt.u32Add(n7, 50), rt.u8Mul(rt.u32Rem(n7, 3) & 0xff, 2)); + }; + const guards: (a0: rt.u32, a1: rt.u32) => Guard.Guard[] = (from: rt.u32, to: rt.u32): Guard.Guard[] => { + return rt.iterToArray(rt.iterMap(new rt.Range(from, to), (n8: rt.u32): Guard.Guard => { + return Guard.new(rt.u32Add(id, n8), Log.clone$Clone(log)); + }), undefined, 8, true); + }; + const part13 = option_map$1raha9y(rt.iterMaxByKey(rt.iterSlice(guards(1, 6), rt.drop), by, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), true, rt.drop, undefined, rt.drop), (g2: Guard.Guard): rt.u32 => { + const _018: rt.u32 = rt.u32Sub(Guard.id(g2), id); + g2[Symbol.dispose](); + return _018; + }); + const args18: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part13, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["max ", args18[0]])); + const part14 = option_map$1raha9y(rt.iterMinByKey(rt.iterSlice(guards(6, 11), rt.drop), by, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), true, rt.drop, undefined, rt.drop), (g3: Guard.Guard): rt.u32 => { + const _019: rt.u32 = rt.u32Sub(Guard.id(g3), id); + g3[Symbol.dispose](); + return _019; + }); + const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part14, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["min ", args20[0]])); + const one2: Guard.Guard | undefined = rt.iterMaxByKey(rt.iterSlice(guards(11, 12), rt.drop), by, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), true, rt.drop, undefined, rt.drop); + const none2: Guard.Guard | undefined = rt.iterMinByKey(rt.iterSlice(guards(12, 12), rt.drop), by, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), true, rt.drop, undefined, rt.drop); + const _292: rt.u32 | undefined = option_map$1raha9y(one2, (g4: Guard.Guard): rt.u32 => { + const _020: rt.u32 = rt.u32Sub(Guard.id(g4), id); + g4[Symbol.dispose](); + return _020; + }); + const _296: boolean = none2 === undefined; + const args22: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(_292, f, rt.u32Debug), (f: rt.Formatter) => rt.fmtBool(_296, f)]; + Log.note(log, rt.fmtFormat(["one ", args22[0], " ", args22[1]])); + rt.drop(none2); + } else if (_21 === 6) { + const part5 = rt.byteSliceFrom(short); + const _304: rt.Iter<[Ranked.Ranked, Guard.Guard]> = rt.iterSlice(entries(part5), lib_drop$tuple2_drops_orders_Ranked_model_Guard); + const part6 = option_map$1t2fqxi(rt.ownedEnd(rt.btreeKeys(rt.btreeCollect(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeMap, rt.iterToArray(_304, "next", 20, true, 20), 20, true, Ranked.eq$cmp_PartialEq, rt.drop, rt.drop), rt.drop, rt.drop, true), true), (k2: Ranked.Ranked): rt.u32 => { + const _012: rt.u32 = rt.u32Sub(k2.id, id); + k2[Symbol.dispose](); + return _012; + }); + const args24: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part6, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["max ", args24[0]])); + const part7 = rt.byteSliceFrom(short); + const _326: rt.Iter<[Ranked.Ranked, Guard.Guard]> = rt.iterSlice(entries(part7), lib_drop$tuple2_drops_orders_Ranked_model_Guard); + const part8 = option_map$1t2fqxi(rt.ownedEnd(rt.btreeKeys(rt.btreeCollect(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeMap, rt.iterToArray(_326, "next", 20, true, 20), 20, true, Ranked.eq$cmp_PartialEq, rt.drop, rt.drop), rt.drop, rt.drop, true), false), (k3: Ranked.Ranked): rt.u32 => { + const _013: rt.u32 = rt.u32Sub(k3.id, id); + k3[Symbol.dispose](); + return _013; + }); + const args26: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part8, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["min ", args26[0]])); + const _348: rt.Iter<[rt.u32, Guard.Guard]> = rt.iterMap(new rt.Range(1, 5), (n6: rt.u32): [rt.u32, Guard.Guard] => { + return [n6, Guard.new(rt.u32Add(rt.u32Add(id, n6), 200), Log.clone$Clone(log))] as [rt.u32, Guard.Guard]; + }); + const part9 = rt.ownedEnd(rt.btreeKeys(rt.btreeCollect(rt.btreeNew(rt.cmp) as rt.BTreeMap, rt.iterToArray(_348, undefined, 12, true), 12, true, undefined, undefined, rt.drop), undefined, rt.drop, true), true); + const args28: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part9, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["plain ", args28[0]])); + const part10 = rt.ownedEnd(rt.btreeKeys(rt.btreeNew(rt.cmp) as rt.BTreeMap, undefined, rt.drop, true), false); + const args30: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtOption(part10, f, rt.u32Debug)]; + Log.note(log, rt.fmtFormat(["empty ", args30[0]])); + } else { + const _378: rt.Iter = rt.iterSlice(keys(rt.byteSliceFrom(Uint8Array.of(2, 1, 99, 3))), rt.drop); + rt.btreeDrop(rt.btreeCollectKeys(rt.btreeNew(Ranked.cmp$cmp_Ord) as rt.BTreeSet, rt.iterToArray(_378, "next", 12, true, 12), 12, true, rt.cmpLt(Ranked.partialCmp$cmp_PartialOrd), Ranked.eq$cmp_PartialEq, rt.drop), rt.drop); + } +} + +//# sourceMappingURL=orders.ts.map diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index 6ad8831d5..86a8cf950 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -3,6 +3,7 @@ import * as rt from "./rt.ts"; import type * as Any from "./core/any.Any.ts"; import { take$drops_objects_Part_u32 as objects_take$drops_objects_Part_u32, id$drops_objects_Part_u32 } from "./drops/objects.ts"; +import type * as Ranked from "./drops/orders.Ranked.ts"; import * as Held from "./drops.Held.ts"; import type * as Key from "./drops.Key.ts"; import type * as Pair from "./drops.Pair.ts"; @@ -230,6 +231,11 @@ export function drop$tuple2_drops_Key_model_Guard(_1: [Key.Key, Guard.Guard]): v _1[1][Symbol.dispose](); } +export function drop$tuple2_drops_orders_Ranked_model_Guard(_1: [Ranked.Ranked, Guard.Guard]): void { + _1[0][Symbol.dispose](); + _1[1][Symbol.dispose](); +} + export function drop$tuple2_i32_model_Guard(_1: [rt.i32, Guard.Guard]): void { _1[1][Symbol.dispose](); } diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index f2954b37d..f9e25f6e2 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -32,6 +32,7 @@ mod iters; mod lists; mod objects; mod once; +mod orders; mod released; mod searched; @@ -762,6 +763,13 @@ pub fn released(log: &Log, id: u32, arg: u8) { released::released(log, id, arg); } +/// Run scenario `arg % 8` of what std drops as it orders: a B-tree's `collect` and `from` +/// of keys whose own impls disagree, `max_by_key` and `min_by_key` by keys that drop, and +/// a map's `into_keys`' `max` and `min`. The last panics in the sort. +pub fn orders(log: &Log, id: u32, arg: u8) { + orders::orders(log, id, arg); +} + /// Run scenario `arg % 3` of where std drops a closure given to a string's search or edit. pub fn searched(log: &Log, id: u32, arg: u8) { searched::searched(log, id, arg); diff --git a/ts/fixtures/task/src/drops/orders.rs b/ts/fixtures/task/src/drops/orders.rs new file mode 100644 index 000000000..28b1704c8 --- /dev/null +++ b/ts/fixtures/task/src/drops/orders.rs @@ -0,0 +1,177 @@ +//! What std drops as it orders. A B-tree's `collect` and `from`, of keys whose own `Ord`, +//! `PartialOrd`, and `PartialEq` disagree with each other, sort the entries as std's stable +//! sort does, a set's by `lt` and a map's by `cmp`, then keep the last of each run `!=` +//! finds equal, dropping each other one, key then value, as they find it. `max_by_key` and +//! `min_by_key` pair each item with its key, which drops with the item as it loses, and the +//! best's once the fold ends. A map's `into_keys` reads an end for `max` and `min`, and then +//! drops the rest with it. + +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet}; + +use crate::log::Log; +use crate::model::Guard; + +/// A key that logs its drop and each call to its impls: `cmp` orders by `rank`, +/// `partial_cmp` by half of it, and `eq` by it modulo 3. `cmp` panics of a rank of 99. +struct Ranked { + id: u32, + rank: u8, + log: Log, +} + +impl Drop for Ranked { + fn drop(&mut self) { + self.log.note(format!("k{} drop", self.id)); + } +} + +impl PartialEq for Ranked { + fn eq(&self, other: &Self) -> bool { + self.log.note(format!("eq {} {}", self.id, other.id)); + self.rank % 3 == other.rank % 3 + } +} + +impl Eq for Ranked {} + +impl PartialOrd for Ranked { + fn partial_cmp(&self, other: &Self) -> Option { + self.log.note(format!("partial_cmp {} {}", self.id, other.id)); + (self.rank / 2).partial_cmp(&(other.rank / 2)) + } +} + +impl Ord for Ranked { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.log.note(format!("cmp {} {}", self.id, other.id)); + assert!( + self.rank != 99 && other.rank != 99, + "cmp of k{} with k{}", + self.id, + other.id + ); + self.rank.cmp(&other.rank) + } +} + +/// A key that copies, so a `Cell` of it orders by it, by its own `Ord` modulo 4. +#[derive(Clone, Copy)] +struct Rank(u8); + +impl PartialEq for Rank { + fn eq(&self, other: &Self) -> bool { + self.0 % 4 == other.0 % 4 + } +} + +impl Eq for Rank {} + +impl PartialOrd for Rank { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Rank { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + (self.0 % 4).cmp(&(other.0 % 4)) + } +} + +/// Run scenario `arg % 8`. The last panics in the sort, which aborts before anything drops. +pub(super) fn orders(log: &Log, id: u32, arg: u8) { + let key = |n: u32, rank: u8| Ranked { + id: id + n, + rank, + log: log.clone(), + }; + // Each key of `n` and its value, a guard of `n + 100`. + let entry = |n: u32, rank: u8| (key(n, rank), Guard::new(id + n + 100, log.clone())); + // Keys of `ranks`, numbered from 1. + let keys = |ranks: &[u8]| -> Vec { (1..).zip(ranks).map(|(n, &rank)| key(n, rank)).collect() }; + let entries = + |ranks: &[u8]| -> Vec<(Ranked, Guard)> { (1..).zip(ranks).map(|(n, &rank)| entry(n, rank)).collect() }; + let set_ids = |s: &BTreeSet| s.iter().map(|k| (k.id - id).to_string()).collect::>().join(","); + let map_ids = |m: &BTreeMap| { + m.iter() + .map(|(k, g)| format!("{}:{}", k.id - id, g.id() - id)) + .collect::>() + .join(",") + }; + let short = [3, 1, 3, 2, 1, 5, 4, 0]; + // Past the 20 std's insertion sort takes, so its driftsort runs. + let long: Vec = (0..26).map(|n| n * 7 % 9).collect(); + match arg % 8 { + 0 => { + let set: BTreeSet = keys(&short).into_iter().collect(); + log.note(format!("set {}", set_ids(&set))); + drop(set); + let none: BTreeSet = keys(&[]).into_iter().collect(); + let one: BTreeSet = keys(&[7]).into_iter().collect(); + log.note(format!("small {} {}", none.len(), set_ids(&one))); + } + 1 => { + let map: BTreeMap = entries(&short).into_iter().collect(); + log.note(format!("map {}", map_ids(&map))); + } + 2 => { + let set = BTreeSet::from([key(1, 4), key(2, 2), key(3, 4), key(4, 1), key(5, 2)]); + log.note(format!("set {}", set_ids(&set))); + let map = BTreeMap::from([entry(1, 4), entry(2, 2), entry(3, 4), entry(4, 1), entry(5, 2)]); + log.note(format!("map {}", map_ids(&map))); + } + 3 => { + // Each emptied by `into_iter`, in std's order: dropped whole, a tree of more than one + // node drops in the runtime's order, not std's node by node. + let set: BTreeSet = keys(&long).into_iter().collect(); + log.note(format!("set {}", set_ids(&set))); + set.into_iter().for_each(drop); + let map: BTreeMap = entries(&long).into_iter().collect(); + log.note(format!("map {}", map_ids(&map))); + map.into_iter().for_each(drop); + } + 4 => { + // Keys that drop nothing, by a `Cell` of what has its own `Ord`, of values that do. + let map: BTreeMap, Guard> = [5u8, 1, 9, 2, 6, 3] + .iter() + .zip(1..) + .map(|(&r, n)| (Cell::new(Rank(r)), Guard::new(id + n, log.clone()))) + .collect(); + let kept = map.iter().map(|(k, g)| format!("{}:{}", k.get().0, g.id() - id)); + log.note(format!("cells {}", kept.collect::>().join(","))); + } + 5 => { + // Each key made of an item, which says so. + let by = |g: &Guard| { + let n = g.id() - id; + log.note(format!("key {n}")); + key(n + 50, (n % 3) as u8 * 2) + }; + let guards = |from: u32, to: u32| (from..to).map(|n| Guard::new(id + n, log.clone())).collect::>(); + let max = guards(1, 6).into_iter().max_by_key(by); + log.note(format!("max {:?}", max.map(|g| g.id() - id))); + let min = guards(6, 11).into_iter().min_by_key(by); + log.note(format!("min {:?}", min.map(|g| g.id() - id))); + let one = guards(11, 12).into_iter().max_by_key(by); + let none = guards(12, 12).into_iter().min_by_key(by); + log.note(format!("one {:?} {}", one.map(|g| g.id() - id), none.is_none())); + } + 6 => { + // Of keys and values that drop, and of values alone. + let map: BTreeMap = entries(&short).into_iter().collect(); + let max = map.into_keys().max(); + log.note(format!("max {:?}", max.map(|k| k.id - id))); + let map: BTreeMap = entries(&short).into_iter().collect(); + let min = map.into_keys().min(); + log.note(format!("min {:?}", min.map(|k| k.id - id))); + let plain: BTreeMap = (1..5).map(|n| (n, Guard::new(id + n + 200, log.clone()))).collect(); + log.note(format!("plain {:?}", plain.into_keys().max())); + let empty: BTreeMap = BTreeMap::new(); + log.note(format!("empty {:?}", empty.into_keys().min())); + } + _ => { + let _set: BTreeSet = keys(&[2, 1, 99, 3]).into_iter().collect(); + } + } +} diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs index 10767cc6f..d5faa09b6 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -159,6 +159,9 @@ fn steps() -> Vec<(&'static str, Step)> { ("indexed", |log, exec, _, arg| { drops::indexed(log, 1000 * exec.len() as u32, arg) }), + ("orders", |log, exec, _, arg| { + drops::orders(log, 1000 * exec.len() as u32, arg) + }), ("compared", |log, exec, _, arg| { drops::compared(log, 1000 * exec.len() as u32, arg) }), diff --git a/ts/fixtures/task/ts.toml b/ts/fixtures/task/ts.toml index 0baf8b8c9..9cd2f22ac 100644 --- a/ts/fixtures/task/ts.toml +++ b/ts/fixtures/task/ts.toml @@ -22,6 +22,7 @@ roots = [ "drops::flattened", "drops::indexed", "drops::released", + "drops::orders", "drops::compared", "drops::lists", "drops::searched", diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index 8a7cbdac2..79d8afc7f 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -1160,19 +1160,20 @@ export function iterMin(it: Iter, lt: Lt, drops = false, drop?: Drop /** * `max_by_key`, by `lt` of the keys, as `iterMax`, each item's key taken once. If it * `owns` `f`, `f` drops as std's `map` of the iterator by it does: as the fold ends, or - * after `it` if `it` is empty. + * after `it` if `it` is empty. Each key drops by `dropKey`, as std pairs it with its + * item: before the item as that loses, and the best's once the fold ends. */ -export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops?: boolean, drop?: Drop, owns?: boolean): T | undefined; -export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops: boolean | undefined, drop: Drop | undefined, owns: boolean | undefined, none: None): T | None; -export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops = false, drop?: Drop, owns = false, none?: None): T | undefined | None { - return iterToOption(best(it, f, lt, false, drops, drop, owns ? () => dispose(f) : undefined, true), none); +export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops?: boolean, drop?: Drop, owns?: boolean, dropKey?: Drop): T | undefined; +export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops: boolean | undefined, drop: Drop | undefined, owns: boolean | undefined, dropKey: Drop | undefined, none: None): T | None; +export function iterMaxByKey(it: Iter, f: (item: T) => K, lt: Lt, drops = false, drop?: Drop, owns = false, dropKey?: Drop, none?: None): T | undefined | None { + return iterToOption(best(it, f, lt, false, drops, drop, owns ? () => dispose(f) : undefined, true, dropKey), none); } /** `min_by_key`, by `lt` of the keys, as `iterMaxByKey`. */ -export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops?: boolean, drop?: Drop, owns?: boolean): T | undefined; -export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops: boolean | undefined, drop: Drop | undefined, owns: boolean | undefined, none: None): T | None; -export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops = false, drop?: Drop, owns = false, none?: None): T | undefined | None { - return iterToOption(best(it, f, lt, true, drops, drop, owns ? () => dispose(f) : undefined, true), none); +export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops?: boolean, drop?: Drop, owns?: boolean, dropKey?: Drop): T | undefined; +export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops: boolean | undefined, drop: Drop | undefined, owns: boolean | undefined, dropKey: Drop | undefined, none: None): T | None; +export function iterMinByKey(it: Iter, f: (item: T) => K, lt: Lt, drops = false, drop?: Drop, owns = false, dropKey?: Drop, none?: None): T | undefined | None { + return iterToOption(best(it, f, lt, true, drops, drop, owns ? () => dispose(f) : undefined, true, dropKey), none); } /** @@ -1213,7 +1214,8 @@ function byCompare(compare: Compare): Lt { * first, as std's `reduce` by `Ord::max` or `min` keeps it: the first by `next`, and the * rest by `fold`, each tested for `lt` the best's and dropped as it loses. `release` drops * the closure std's reduces by as the fold ends, or if `it` is empty, before `it`, or - * after it if `keyed`, as the `map` std's `_by_key` forms reduce drops its function. + * after it if `keyed`, as the `map` std's `_by_key` forms reduce drops its function. Each + * key drops by `dropKey` just before its item does, and the best's after the fold. */ function best( it: Iter, @@ -1224,8 +1226,9 @@ function best( drop?: Drop, release?: () => void, keyed = false, + dropKey?: Drop, ): T | Done { - if (!drops && drop === undefined) { + if (!drops && drop === undefined && dropKey === undefined) { let best = it.next(); if (best !== DONE) { let key = f(best); @@ -1245,16 +1248,18 @@ function best( if (keyed) release?.(); return DONE; } - const [, item] = it.fold<[K, T]>( + const [key, item] = it.fold<[K, T]>( [f(first), first], (best, item) => { const k = f(item); const wins = least ? lt(k, best[0]) : !lt(k, best[0]); + dropKey?.(wins ? best[0] : k); drop?.(wins ? best[1] : item); return wins ? [k, item] : best; }, release, ); + dropKey?.(key); return item; } @@ -1527,6 +1532,13 @@ export function ownedLast(it: Iter, drop?: Drop, none?: None): T | unde return iterToOption(last(it, drop), none); } +/** `min`, or with `back`, `max`, of a B-tree's `into_keys` that drops what it holds: an end, as std's reads it, and then the rest drop with it. */ +export function ownedEnd(it: Iter, back: boolean): T | undefined; +export function ownedEnd(it: Iter, back: boolean, none: None): T | None; +export function ownedEnd(it: Iter, back: boolean, none?: None): T | undefined | None { + return iterToOption(consumed(it, () => (back ? it.nextBack() : it.next())), none); +} + /** `count`, dropping each item by `drop`, and then `it`, as std's of its kind does. */ function count(it: Iter, drop: Drop | undefined): number { if (it instanceof FromNext && it.own?.count !== undefined) return it.taken(it.own.count); diff --git a/ts/src/lower/collections.rs b/ts/src/lower/collections.rs index 409bc7772..a40ae86e7 100644 --- a/ts/src/lower/collections.rs +++ b/ts/src/lower/collections.rs @@ -1348,15 +1348,6 @@ fn btree_collect<'tcx>( let f = if set { "btreeExtendKeys" } else { "btreeExtend" }; return Expr::rt(f, super::iter::tail(vec![target, source], droppers)); } - // A sort by an impl of the crate's may panic, or leave equal keys in another order. - if own && b.t.drops(coll) { - 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, elem, trusted, span); let mut rest = Vec::from(super::library::sort_of(b, elem, span)); // A set's sort tests `lt`, and a map's `Ord::cmp`; std's sorts no zero-sized one. diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index f17fd6889..356dcca57 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -1069,23 +1069,15 @@ pub fn call<'tcx>( { let by_key = name.ends_with("_by_key"); let key = if by_key { targ(1)? } else { item }; - if by_key && b.t.drops(key) { - return Some(b.err( - span, - format!("`{name}` by `{key}`, which drops, which is not supported yet"), - )); - } - // A `BTreeMap`'s `into_keys` reads the one end and drops the rest with it. - if !by_key - && 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"), + // A B-tree's iterators read an end, comparing nothing, and a map's `into_keys` then + // drops the rest with it. + if !by_key && btree_end(tcx, self_ty, name) && b.t.drops(self_ty) { + let back = Expr::lit((name == "max").to_string()); + return Some(Expr::rt( + "ownedEnd", + [recv.clone(), back].into_iter().chain(none).collect(), )); } - // A B-tree's iterators read an end, comparing nothing. if !by_key && btree_end(tcx, self_ty, name) { let end = match name { "max" => recv.member("nextBack").call(Vec::new()), @@ -1100,13 +1092,14 @@ pub fn call<'tcx>( )); } let lt = super::collections::test_fn(b, key, "lt", span); - let owns = match by_key { - true => Some(flag(b.t.drops(targ(2)?))), - false => None, + // The `_by_key` forms own their function, and drop each key with its item. + let keyed = match by_key { + true => vec![flag(b.t.drops(targ(2)?)), b.t.dropper(key, span)], + false => Vec::new(), }; let droppers = [iter_drops(b, self_ty, span), b.t.dropper(item, span)] .into_iter() - .chain(owns) + .chain(keyed) .chain(none); method(&camel, tail([rest, vec![lt]].concat(), droppers.collect())) } diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 04a3b367f..c5f0d0a4f 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -62,6 +62,7 @@ export interface Fixture { released(log: Log, id: number, arg: number): void; flattened(log: Log, id: number, arg: number): void; indexed(log: Log, id: number, arg: number): void; + orders(log: Log, id: number, arg: number): void; compared(log: Log, id: number, arg: number): void; lists(log: Log, id: number, arg: number): void; searched(log: Log, id: number, arg: number): void; @@ -331,6 +332,7 @@ export const steps: [string, (r: Run, arg: number) => void][] = [ ["released", (r, arg) => r.f.drops.released(r.log, 1000 * r.exec.tasks.length, arg)], ["flattened", (r, arg) => r.f.drops.flattened(r.log, 1000 * r.exec.tasks.length, arg)], ["indexed", (r, arg) => r.f.drops.indexed(r.log, 1000 * r.exec.tasks.length, arg)], + ["orders", (r, arg) => r.f.drops.orders(r.log, 1000 * r.exec.tasks.length, arg)], ["compared", (r, arg) => r.f.drops.compared(r.log, 1000 * r.exec.tasks.length, arg)], [ "wakers", @@ -443,6 +445,8 @@ export const cases: Uint8Array[] = [ ...Array.from({ length: 10 }, (_, arg) => script(["flattened", arg])), // What std drops of a zip it reads by index. ...Array.from({ length: 9 }, (_, arg) => script(["indexed", arg])), + // What std drops as it orders. + ...Array.from({ length: 8 }, (_, arg) => script(["orders", arg])), // What std's comparisons of iterators drop. ...Array.from({ length: 9 }, (_, arg) => script(["compared", arg])), // What a `LinkedList` drops, and when.