diff --git a/quest/m3/README.md b/quest/m3/README.md index 3296ee492..a4f44d106 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -23,12 +23,12 @@ generic std gap is planned here even when moq never calls it. - [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, flattens, and collects drop as std's do - [Fresh writes in a body generic over a type](/quest/m3/ts-fresh-type-params.md) - a whole write into fresh memory holding a type parameter's values fills it, as one generic over a length alone does -- [Result's iterators](/quest/m3/ts-result-iters.md) - `Result::iter`, `iter_mut`, `into_iter`, and `flatten` over `Result`s translate - [A generic type's bytes at u8](/quest/m3/ts-generic-byte-fields.md) - a `[T; N]`, `Vec`, or `&[T]` field of a generic type is typed as its `u8` instance holds it, or refused - [std's conversions of a reference](/quest/m3/ts-ref-conversions.md) - `to_owned`, `clone_from`, `binary_search`, `size_of_val`, `from_ref`/`from_mut`, and `AsRef`/`Borrow` as a slice translate - [Waiting: a slice object for a mutable part of other values](/quest/m3/ts-slice-object.md) - waits on a moq profile showing the `Proxy` view's traps matter, then decides on an `rt.ByteSlice`-like form - [Port the workflow guard to kixelated/quest](/quest/m3/quest-workflow-guard.md) - quest's environment guard parses YAML as this repository's does - [A deque's two slices](/quest/m3/ts-deque-slices.md) - `VecDeque::as_slices` and `{:?}` of a deque's `Iter`, `IterMut`, and `Drain` translate, split where std's are +- [Places through an adaptor's argument](/quest/m3/ts-adaptor-places.md) - `iter.zip(&mut v)` of values JS copies lends places as `for x in &mut v` does - [std's sorts call their tests in std's order](/quest/m3/ts-sort-order.md) - `slice::sort` and a B-tree's `collect` call `lt` or `cmp` as std's driftsort does past 16 elements - [A B-tree's searches call Ord as std's do](/quest/m3/ts-btree-search-order.md) - a B-tree's lookups and inserts call a key's own `Ord` in std's order and number - [The rest of a guard's maps](/quest/m3/ts-guard-maps.md) - `RefMut::map`, the guards' `filter_map` and `map_split`, and an `RwLock` guard's `map` translate diff --git a/quest/m3/ts-adaptor-places.md b/quest/m3/ts-adaptor-places.md new file mode 100644 index 000000000..ce9ab36a6 --- /dev/null +++ b/quest/m3/ts-adaptor-places.md @@ -0,0 +1,18 @@ +# [S] Places through an adaptor's argument + +## Goal + +[rust2-ts](/ts/README.md) translates an adaptor given a `&mut` to a collection of values +JS copies, as `iter.zip(&mut v)` or `iter.chain(&mut res)` where `iter` yields no places, +proven by a differential test against native Rust that writes through each. + +## Plan + +Found writing [Result's iterators](https://github.com/moq-dev/rust2/pull/381): such a +call is refused as "a mutable reference to a value JS copies, which its mapping would +copy", while `for x in &mut v` and `v.iter_mut().zip(&mut w)` translate. `std_places` in +`ts/src/lower/mir/call.rs` accepts places only from a listed mapping or from what the +adaptor's receiver yields. Accepting every generic `IntoIterator` argument is too broad: +`iter.eq(&mut v)` would compare places, not values, so check each adaptor's mapping. + +Public API: the translator's output. diff --git a/quest/m3/ts-result-iters.md b/quest/m3/ts-result-iters.md deleted file mode 100644 index 4bfe5d916..000000000 --- a/quest/m3/ts-result-iters.md +++ /dev/null @@ -1,16 +0,0 @@ -# [S] Result's iterators - -## Goal - -[rust2-ts](/ts/README.md) translates `Result::iter`, `iter_mut`, and `into_iter`, by value -and through a reference, and `flatten` over `Result`s, for every `T`, `[u8; N]` lent as an -`rt.ByteSlice` as an `Option`'s is, proven by a differential test against native Rust. - -## Plan - -Found by [moq-dev/rust2#366](https://github.com/moq-dev/rust2/pull/366): `res.iter()` is -refused as "constructing `std::result::Iter` from another crate", and -`results.iter().flatten()` and `iter.chain(&res)` as unsupported calls. `iter::into_iter` -and `iter::call` map an `Option`'s iterators but not a `Result`'s. - -Public API: the translator's output. diff --git a/ts/fixtures/lang/expected/boxes.ts b/ts/fixtures/lang/expected/boxes.ts index 48d67251c..73c7f9a89 100644 --- a/ts/fixtures/lang/expected/boxes.ts +++ b/ts/fixtures/lang/expected/boxes.ts @@ -7,7 +7,7 @@ import * as boxes_Logged from "./boxes.Logged.ts"; import type * as Owner from "./boxes.Owner.ts"; import { then$0ea5h05 } from "./core/bool.ts"; import { unwrapOr$1iemzn8 as option_unwrapOr$1iemzn8, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOr$1j4op5y as option_unwrapOr$1j4op5y, unwrapOr$11c0we2 as option_unwrapOr$11c0we2, mapOr$1e4a1e0 as option_mapOr$1e4a1e0, asDeref$0w8at8i as option_asDeref$0w8at8i, asDeref$0w2m0zn as option_asDeref$0w2m0zn, asDeref$0avuzwv as option_asDeref$0avuzwv, flatten$08boupk as option_flatten$08boupk } from "./core/option.ts"; -import { map$0nfi04k as result_map$0nfi04k, asDeref$1fldd5d as result_asDeref$1fldd5d, asDeref$04i8i5u as result_asDeref$04i8i5u, unwrapOr$0e4foht as result_unwrapOr$0e4foht, copied$0bbq7yi } from "./core/result.ts"; +import { map$0nfi04k as result_map$0nfi04k, asDeref$1fldd5d as result_asDeref$1fldd5d, asDeref$04i8i5u as result_asDeref$04i8i5u, unwrapOr$0e4foht as result_unwrapOr$0e4foht, copied$0bbq7yi as result_copied$0bbq7yi } from "./core/result.ts"; import { put as fmt_put } from "./fmt.ts"; import { text } from "./strs.ts"; @@ -691,7 +691,7 @@ export function places(_1: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { return rt.u32ToBeBytes(b).reverse(); }, (value: Uint8Array) => rt.iterSlice(value), false, 4), undefined, true); rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(option_unwrapOr$11c0we2(option_asDeref$0avuzwv(o), 238)).reverse()), undefined, true); - rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.u32ToBeBytes(result_unwrapOr$0e4foht(result_copied$0bbq7yi(result_asDeref$04i8i5u(res)), 238)).reverse()), undefined, true); const _298: rt.Result = said; if (_298.ok) { fmt_put(out, _298.value); diff --git a/ts/fixtures/lang/expected/combinators.ts b/ts/fixtures/lang/expected/combinators.ts index 47b0ae87b..4af277ba7 100644 --- a/ts/fixtures/lang/expected/combinators.ts +++ b/ts/fixtures/lang/expected/combinators.ts @@ -3,7 +3,7 @@ import * as rt from "./rt.ts"; import { copy$Result_array2_u32_u16, copy$array_u32 } from "./lib.ts"; import { isSomeAnd$09tpccf, isNoneOr$1s1o3ss, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, unwrapOrElse$1badkpb as option_unwrapOrElse$1badkpb, unwrapOrElse$13moxzl as option_unwrapOrElse$13moxzl, unwrapOrDefault$165pyh5 as option_unwrapOrDefault$165pyh5, unwrapOrDefault$0wx44sw as option_unwrapOrDefault$0wx44sw, unwrapOrDefault$1q0ps0j as option_unwrapOrDefault$1q0ps0j, map$0oc32h1 as option_map$0oc32h1, map$0ejznqm as option_map$0ejznqm, map$0jg2jop as option_map$0jg2jop, map$0cs071d as option_map$0cs071d, inspect$0di0vx1 as option_inspect$0di0vx1, mapOr$1surhce as option_mapOr$1surhce, mapOr$099335t as option_mapOr$099335t, mapOr$0mmpeqx as option_mapOr$0mmpeqx, mapOrElse$1g6d36t as option_mapOrElse$1g6d36t, okOr$07zal2e as option_okOr$07zal2e, okOr$0m6xlfp as option_okOr$0m6xlfp, okOr$1vxk0yk as option_okOr$1vxk0yk, okOrElse$0awp3vn as option_okOrElse$0awp3vn, okOrElse$1v98j0a as option_okOrElse$1v98j0a, and$06om98g as option_and$06om98g, andThen$17ch833 as option_andThen$17ch833, filter$1855tjj, filter$0v80fk8, or$1loyskh as option_or$1loyskh, orElse$05gzawv as option_orElse$05gzawv, orElse$15bv4ho as option_orElse$15bv4ho, xor$0kctyix, zip$1deudzj, clone$14nprly as option_clone$14nprly } from "./core/option.ts"; -import { isOkAnd$0jj0nkw, isErrAnd$0b01a39, ok$1c77lmd, err$05f656d, asRef$1glrxiq, map$1qqg34g as result_map$1qqg34g, map$132mdj8 as result_map$132mdj8, mapOr$1mu5bvh as result_mapOr$1mu5bvh, mapOrElse$0jxx67n as result_mapOrElse$0jxx67n, mapErr$12w1s5x as result_mapErr$12w1s5x, mapErr$1lsqfgi as result_mapErr$1lsqfgi, inspect$16o3gle as result_inspect$16o3gle, inspectErr$06tv5sa, unwrapOrDefault$1exw7nd as result_unwrapOrDefault$1exw7nd, and$0l7ltae as result_and$0l7ltae, andThen$0hd6ik8 as result_andThen$0hd6ik8, or$1xcfx3w as result_or$1xcfx3w, orElse$13ay4um as result_orElse$13ay4um, unwrapOr$0a4h2e7 as result_unwrapOr$0a4h2e7, unwrapOrElse$1reohq9 as result_unwrapOrElse$1reohq9, unwrapOrElse$009ibtw as result_unwrapOrElse$009ibtw, copied$0ma6p21, clone$04fntvl as result_clone$04fntvl } from "./core/result.ts"; +import { isOkAnd$0jj0nkw, isErrAnd$0b01a39, ok$1c77lmd, err$05f656d, asRef$1glrxiq, map$1qqg34g as result_map$1qqg34g, map$132mdj8 as result_map$132mdj8, mapOr$1mu5bvh as result_mapOr$1mu5bvh, mapOrElse$0jxx67n as result_mapOrElse$0jxx67n, mapErr$12w1s5x as result_mapErr$12w1s5x, mapErr$1lsqfgi as result_mapErr$1lsqfgi, inspect$16o3gle as result_inspect$16o3gle, inspectErr$06tv5sa, unwrapOrDefault$1exw7nd as result_unwrapOrDefault$1exw7nd, and$0l7ltae as result_and$0l7ltae, andThen$0hd6ik8 as result_andThen$0hd6ik8, or$1xcfx3w as result_or$1xcfx3w, orElse$13ay4um as result_orElse$13ay4um, unwrapOr$0a4h2e7 as result_unwrapOr$0a4h2e7, unwrapOrElse$1reohq9 as result_unwrapOrElse$1reohq9, unwrapOrElse$009ibtw as result_unwrapOrElse$009ibtw, copied$0ma6p21 as result_copied$0ma6p21, clone$04fntvl as result_clone$04fntvl } from "./core/result.ts"; /** Run case `kind % 4` over `data`, whose bytes pick each `Some` or `None`, `Ok` or `Err`. */ export function combinators(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { @@ -127,7 +127,7 @@ export function results(a: rt.u8 | undefined, b: rt.u8 | undefined, limit: rt.u8 }), (e7: rt.u16): undefined => { rt.byteVecPush(out, e7 & 0xff); }).ok ? 1 : 0); - rt.byteVecPush(out, result_unwrapOr$0a4h2e7(copied$0ma6p21(result_mapErr$1lsqfgi(asRef$1glrxiq(r), (e8: rt.u16): rt.u16 => { + rt.byteVecPush(out, result_unwrapOr$0a4h2e7(result_copied$0ma6p21(result_mapErr$1lsqfgi(asRef$1glrxiq(r), (e8: rt.u16): rt.u16 => { return e8; })), 34)); } diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts index 2c1e2ab2f..6a672d6df 100644 --- a/ts/fixtures/lang/expected/core/option.ts +++ b/ts/fixtures/lang/expected/core/option.ts @@ -79,6 +79,13 @@ export function unwrapOr$1kxjsqb(self: rt.u8 | undefined | rt.None, default_: rt return self; } +export function unwrapOr$17ntxfo(self: rt.Result | undefined, default_: rt.Result): rt.Result { + if (self === undefined) { + return default_; + } + return self; +} + export function unwrapOr$1la41a6(self: Uint8Array | undefined, default_: Uint8Array): Uint8Array { if (self === undefined) { return default_; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index f8d14c4fe..1b1bfd7d7 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -34,7 +34,7 @@ import { holds } from "./holds.ts"; import { u8Op, u16Op, u32Op, u64Op, u128Op, usizeOp, i8Op, i16Op, i32Op, i64Op, i128Op, isizeOp, i8Neg, i16Neg, i32Neg, i64Neg, i128Neg, isizeNeg, cast as ints_cast, convert, parses as ints_parses, widenings } from "./ints.ts"; import { adaptors, consumers as iters_consumers, reducers, peekedOthers, skips, ranked as iters_ranked, ranges as iters_ranges, options as iters_options, optionItems, own as iters_own, values as iters_values, returned, zips, zipsBack, rangeFroms, rangeMethods, compares } from "./iters.ts"; import { joins } from "./joins.ts"; -import { keys as keys_keys, overrides, bytes as keys_bytes, lentKeys, lentValues, arrays, byteRefs } from "./keys.ts"; +import { keys as keys_keys, overrides, bytes as keys_bytes, lentKeys, lentValues, arrays as keys_arrays, byteRefs } from "./keys.ts"; import { lengths } from "./lengths.ts"; import { lists as lists_lists } from "./lists.ts"; import { locals } from "./locals.ts"; @@ -45,6 +45,7 @@ import { objects } from "./objects.ts"; import { orders, bytes as orders_bytes, tuples as orders_tuples, held as orders_held, btrees } from "./orders.ts"; import { lists as pointers_lists, shared as pointers_shared, places as pointers_places, unchecked, nested as pointers_nested, copies as pointers_copies, sentinels, cells as pointers_cells, rebound as pointers_rebound, lapsed, writers, made as pointers_made, segments, uninitRuns, iteratedRuns, besideWritten, waiters, taken as pointers_taken, bytes as pointers_bytes, loaded, reattached, partWritten, aimed } from "./pointers.ts"; import { refs, toRefs } from "./refs.ts"; +import { results as results_results } from "./results.ts"; import { returns } from "./returns.ts"; import { u8s as saturates_u8s, u16s as saturates_u16s, u32s as saturates_u32s, u64s as saturates_u64s, u128s as saturates_u128s, usizes as saturates_usizes, i8s as saturates_i8s, i16s as saturates_i16s, i32s as saturates_i32s, i64s as saturates_i64s, i128s as saturates_i128s, isizes as saturates_isizes } from "./saturates.ts"; import { separated } from "./separated.ts"; @@ -215,7 +216,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) arrays_lent(data70, out71); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["floats::mul_adds", floats_mulAdds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["singles::mul_adds", singles_mulAdds as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fmt::collections", (_2171: rt.u8, data71: rt.ByteSlice, out72: rt.ByteVec): undefined => { collections(data71, out72); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::unlike_eqs", unlikeEqs as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::impls", impls as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::keys", zeros_keys as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::arrays", arrays as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::zips", zips as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::zips_back", zipsBack as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::own_nes", ownNes as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fmt::iters", (_2172: rt.u8, data72: rt.ByteSlice, out73: rt.ByteVec): undefined => { + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::unlike_eqs", unlikeEqs as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::impls", impls as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::keys", zeros_keys as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["keys::arrays", keys_arrays as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::zips", zips as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::zips_back", zipsBack as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::own_nes", ownNes as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fmt::iters", (_2172: rt.u8, data72: rt.ByteSlice, out73: rt.ByteVec): undefined => { fmt_iters(data72, out73); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["zeros::unread", unread as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::range_froms", rangeFroms as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::range_methods", rangeMethods as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["clones::iters", clones_iters as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::cell_eqs", cellEqs as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["iters::compares", compares as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::unlike_compares", unlikeCompares as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["collections::ref_orders", refOrders as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["cycles::cycles", cycles as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["pointers::lapsed", (_2173: rt.u8, data73: rt.ByteSlice, out74: rt.ByteVec): undefined => { lapsed(data73, out74); @@ -253,7 +254,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) aimed(data88, out89); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["ascii::parts", ascii_parts as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["boxes::places", boxes_places as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["arrays::flattened", arrays_flattened as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["args::args", args as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["returns::returns", returns as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["borrows::guards", (_2189: rt.u8, data89: rt.ByteSlice, out90: rt.ByteVec): undefined => { guards(data89, out90); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fields::fields", fields_fields as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["strs::gets", gets as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["results::results", results_results as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["fields::fields", fields_fields as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined], ["strs::gets", gets as (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => undefined]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index ca337b259..1c4afedfa 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -37,6 +37,7 @@ import * as List from "./pointers.List.ts"; import type * as Outer from "./pointers.Outer.ts"; import type * as pointers_Pair from "./pointers.Pair.ts"; import type * as Paired from "./pointers.Paired.ts"; +import type * as results_Logged from "./results.Logged.ts"; import * as saturates_Gauge from "./saturates.Gauge.ts"; import type * as shapes_Gauge from "./shapes.Gauge.ts"; import type * as shapes_Held from "./shapes.Held.ts"; @@ -178,10 +179,22 @@ export function copy$Option_tuple2_u8_u8(v: [rt.u8, rt.u8] | undefined): [rt.u8, return v === undefined ? v : copy$tuple2_u8_u8(v); } +export function copy$Result_array0_u8_u8(v: rt.Result): rt.Result { + return v.ok ? rt.Ok(copy$array_u8(v.value)) : rt.Err(v.error); +} + +export function copy$Result_array1_u8_u8(v: rt.Result): rt.Result { + return v.ok ? rt.Ok(copy$array_u8(v.value)) : rt.Err(v.error); +} + export function copy$Result_array2_u32_u16(v: rt.Result): rt.Result { return v.ok ? rt.Ok(copy$array_u32(v.value)) : rt.Err(v.error); } +export function copy$Result_array5_u8_u8(v: rt.Result): rt.Result { + return v.ok ? rt.Ok(copy$array_u8(v.value)) : rt.Err(v.error); +} + export function copy$Result_tuple2_ref_sync_Mutex_u8_u8_u8(v: rt.Result<[rt.Mutex, rt.u8], rt.u8>): rt.Result<[rt.Mutex, rt.u8], rt.u8> { return v.ok ? rt.Ok(copy$tuple2_ref_sync_Mutex_u8_u8(v.value)) : rt.Err(v.error); } @@ -813,6 +826,14 @@ export function drop$Result_cell_Ref_Vec_u8_cell_BorrowError(_1: rt.Result): void { + if (_1.ok) { + _1.value[Symbol.dispose](); + } else { + _1.error[Symbol.dispose](); + } +} + export function drop$Result_sync_MutexGuard_locks_Tally_sync_TryLockError_sync_MutexGuard_locks_Tally(_1: rt.Result, rt.TryLockError>>): void { if (_1.ok) { rt.mutexUnlock(_1.value); diff --git a/ts/fixtures/lang/expected/results.Logged.ts b/ts/fixtures/lang/expected/results.Logged.ts new file mode 100644 index 000000000..54b0528c3 --- /dev/null +++ b/ts/fixtures/lang/expected/results.Logged.ts @@ -0,0 +1,27 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** Logs its id as it drops. */ +export class Logged { + id: rt.u8; + log: rt.Arc>; + + constructor(id: rt.u8, log: rt.Arc>) { + this.id = id; + this.log = log; + } + + [Symbol.dispose](): void { + drop$ops_Drop(this); + this.log[Symbol.dispose](); + } +} + +export function drop$ops_Drop(self: Logged): void { + const _5: rt.RefCell = rt.refCellBorrowMut(self.log.value); + rt.byteVecPush(_5.value, self.id); + rt.refMutRelease(_5); +} + +//# sourceMappingURL=results.Logged.ts.map diff --git a/ts/fixtures/lang/expected/results.ts b/ts/fixtures/lang/expected/results.ts new file mode 100644 index 000000000..e93c1f84f --- /dev/null +++ b/ts/fixtures/lang/expected/results.ts @@ -0,0 +1,643 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$Result_array0_u8_u8, copy$Result_array1_u8_u8, copy$Result_array5_u8_u8, drop$Result_results_Logged_results_Logged } from "./lib.ts"; +import { unwrapOr$17ntxfo as option_unwrapOr$17ntxfo, unwrapOr$0r2bmpr as option_unwrapOr$0r2bmpr, mapOr$1w5qtj7 as option_mapOr$1w5qtj7, mapOr$02k4ito as option_mapOr$02k4ito } from "./core/option.ts"; +import { map$03hz3l7 as result_map$03hz3l7 } from "./core/result.ts"; +import * as results_Logged from "./results.Logged.ts"; + +/** The iterators of `Result`s of each payload `kind` picks. */ +export function results(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { + const _4: rt.u8 = rt.u8Rem(kind, 7); + if (_4 === 0) { + copied(data, out); + } else if (_4 === 1) { + owned(data, out); + } else if (_4 === 2) { + units(data, out); + } else if (_4 === 3) { + nested(data, out); + } else if (_4 === 4) { + arrays$0(data, out); + } else if (_4 === 5) { + arrays$1(data, out); + } else { + arrays$5(data, out); + } +} + +/** `Ok` for a byte not divisible by 3, else `Err`. */ +export function split(b: rt.u8): rt.Result { + if (!(rt.u8Rem(b, 3) === 0)) { + return rt.Ok(b); + } + return rt.Err(b); +} + +/** Of bytes, which JS copies, so a `&mut` lends each as its place. */ +export function copied(data: rt.ByteSlice, out: rt.ByteVec): void { + const results: rt.Result[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.Result => { + return split(_2); + }), undefined, 2, true); + for (const _9 of results) { + rt.iterExtendBytes(out, rt.iterResult(_9), undefined, true); + rt.byteVecPush(out, rt.iterResult(_9).len() & 0xff); + const _22: [rt.usize, rt.usize | undefined] = rt.iterResult(_9).sizeHint(); + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_22[0] & 0xff, option_mapOr$02k4ito(_22[1], 238, (h: rt.usize): rt.u8 => { + return h & 0xff; + }))), undefined, true); + } + const iter2: rt.Iter>> = rt.iterSliceMut(results); + l3: while (true) { + const _34: rt.Place> | rt.Done = iter2.next(); + if (_34 === rt.DONE) { + break; + } + const iter3: rt.Iter> = rt.iterOption(rt.resultAsMut(_34)); + while (true) { + const _41: rt.Place | rt.Done = iter3.next(); + if (_41 === rt.DONE) { + continue l3; + } + _41.v = rt.u8WrappingAdd(_41.v, 1); + } + } + const iter4: rt.Iter>> = rt.iterSliceMut(results); + l6: while (true) { + const _50: rt.Place> | rt.Done = iter4.next(); + if (_50 === rt.DONE) { + break; + } + const iter5: rt.Iter> = rt.iterOption(rt.resultAsMut(_50)); + while (true) { + const _56: rt.Place | rt.Done = iter5.next(); + if (_56 === rt.DONE) { + continue l6; + } + _56.v = _56.v ^ 16; + } + } + rt.iterExtendBytes(out, rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), "next"); + const iter6: rt.Iter> = rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterOption(rt.resultAsMut(value)), false, undefined, true); + while (true) { + const _71: rt.Place | rt.Done = iter6.next(); + if (_71 === rt.DONE) { + break; + } + _71.v = rt.u8WrappingMul(_71.v, 3); + } + rt.iterExtendBytes(out, rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), "next"); + rt.iterExtendBytes(out, rt.iterRev(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true)), "next"); + const it: rt.Iter = rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true); + while (true) { + const _93: [rt.u8 | undefined, rt.u8 | undefined] = [rt.iterToOption(it.next()), rt.iterToOption(it.nextBack())]; + if (_93[0] !== undefined) { + rt.iterExtendBytes(out, rt.iterSlice(Uint8Array.of(_93[0], option_unwrapOr$0r2bmpr(_93[1], 170))), undefined, true); + } else { + break; + } + } + let first: rt.Result = option_unwrapOr$17ntxfo(rt.sliceFirst(results), rt.Err(0)); + rt.iterExtendBytes(out, rt.iterChain(rt.iterChain(rt.iterSlice(rt.byteSliceView(data)), rt.iterResult(first)), rt.iterRev(rt.iterResult(first))), undefined, true); + const iter7: rt.Iter<[rt.u8, rt.u8]> = rt.iterZip(rt.iterTake(rt.iterSlice(rt.byteSliceView(data)), 1), rt.iterResult(first), "len"); + while (true) { + const _126: [rt.u8, rt.u8] | rt.Done = iter7.next(); + if (_126 === rt.DONE) { + break; + } + rt.byteVecPush(out, rt.u8WrappingSub(_126[0], _126[1])); + } + const iter8: rt.Iter> = rt.iterOption(rt.resultAsMut(rt.place(() => first, (value) => first = value))); + while (true) { + const _138: rt.Place | rt.Done = iter8.next(); + if (_138 === rt.DONE) { + break; + } + _138.v = rt.u8WrappingSub(_138.v, 1); + } + rt.iterExtendBytes(out, rt.iterChain(rt.iterResult(first), rt.iterResult(first)), undefined, true); + const it2: rt.Iter = rt.iterResult(first); + const cloned: rt.Iter = it2.clone(); + rt.byteVecPush(out, option_unwrapOr$0r2bmpr(rt.iterToOption(it2.next()), 238)); + rt.byteVecPush(out, rt.iterToOption(it2.next()) === undefined ? 1 : 0); + rt.byteVecPush(out, rt.iterCount(cloned) & 0xff); + const into: rt.Iter = rt.iterResult(first); + const back: rt.Iter = into.clone(); + rt.iterExtendBytes(out, rt.iterSlice(rt.bytesMap([rt.iterToOption(into.next()), rt.iterToOption(back.nextBack()), rt.iterToOption(back.next())], (x: rt.u8 | undefined): rt.u8 => { + return option_unwrapOr$0r2bmpr(x, 221); + })), undefined, true); + rt.iterExtendBytes(out, rt.iterSlice(rt.iterToArray(rt.iterResult(first), undefined, 4, true)), undefined, true); +} + +/** Puts what was logged since the last flush, after a marker. */ +export function flush(log: rt.RefCell, out: rt.ByteVec): void { + rt.byteVecPush(out, 253); + const _8: rt.RefCell = rt.refCellBorrowMut(log); + rt.iterExtendBytes(out, rt.byteVecDrain(_8.value, undefined), "fold", true); + rt.refMutRelease(_8); +} + +/** + * Of objects that drop, each `Ok` and `Err` alike: `into_iter` drops an `Err` as it makes + * the iterator, and the iterator the `Ok` it never yielded. + */ +export function owned(data: rt.ByteSlice, out: rt.ByteVec): void { + const log: rt.Arc> = new rt.Arc(new rt.RefCell(new rt.ByteVec())); + const made: (a0: rt.u8) => rt.Result = (b2: rt.u8): rt.Result => { + const logged: results_Logged.Logged = new results_Logged.Logged(b2, rt.arcClone(log)); + if (!(rt.u8Rem(b2, 3) === 0)) { + return rt.Ok(logged); + } + return rt.Err(logged); + }; + for (const b of rt.byteSliceView(data)) { + const it: rt.Iter = rt.iterResult(made(b), rt.drop, rt.drop); + const _21: rt.RefCell = rt.refCellBorrowMut(log.value); + rt.byteVecPush(_21.value, 254); + rt.refMutRelease(_21); + rt.drop(it); + const iter2: rt.Iter = rt.iterResult(made(b), rt.drop, rt.drop); + while (true) { + const _30: results_Logged.Logged | rt.Done = iter2.next(); + if (_30 === rt.DONE) { + break; + } + const l: results_Logged.Logged = _30; + rt.byteVecPush(out, l.id); + l[Symbol.dispose](); + } + rt.drop(iter2); + flush(log.value, out); + } + const results: rt.Result[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.Result => { + return made(_2); + }), undefined, 12, true); + for (const _47 of results) { + rt.iterExtendBytes(out, rt.iterMap(rt.iterResult(_47), (l3: results_Logged.Logged): rt.u8 => { + return l3.id; + }), undefined, true); + } + const iter4: rt.Iter>> = rt.iterSliceMut(results); + l7: while (true) { + const _59: rt.Place> | rt.Done = iter4.next(); + if (_59 === rt.DONE) { + break; + } + const iter5: rt.Iter = rt.iterResult(_59.v); + while (true) { + const _65: results_Logged.Logged | rt.Done = iter5.next(); + if (_65 === rt.DONE) { + continue l7; + } + _65.id = _65.id ^ 64; + } + } + const iter6: rt.Iter = rt.iterRev(rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterResult(value.v), false, undefined, true)); + while (true) { + const _76: results_Logged.Logged | rt.Done = iter6.next(); + if (_76 === rt.DONE) { + break; + } + _76.id = rt.u8WrappingAdd(_76.id, 1); + } + rt.iterExtendBytes(out, rt.iterMap(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), (l4: results_Logged.Logged): rt.u8 => { + return l4.id; + }), "next"); + flush(log.value, out); + const iter7: rt.Iter = rt.iterTake(rt.iterFlatten(rt.iterSlice(results, drop$Result_results_Logged_results_Logged), (value: rt.Result) => rt.iterResult(value, rt.drop, rt.drop), true, undefined, true), 2, rt.drop); + while (true) { + const _97: results_Logged.Logged | rt.Done = iter7.next(); + if (_97 === rt.DONE) { + break; + } + const l2: results_Logged.Logged = _97; + rt.byteVecPush(out, l2.id); + flush(log.value, out); + l2[Symbol.dispose](); + } + rt.drop(iter7); + flush(log.value, out); + const rest: results_Logged.Logged[] = rt.iterToArray(rt.iterFlatten(rt.iterMap(rt.iterRev(rt.iterSlice(rt.byteSliceView(data))), (_23: rt.u8): rt.Result => { + return made(_23); + }), (value: rt.Result) => rt.iterResult(value, rt.drop, rt.drop), false, undefined, true), "next", 8); + flush(log.value, out); + rt.iterExtendBytes(out, rt.iterMap(rt.iterSlice(rest), (l5: results_Logged.Logged): rt.u8 => { + return l5.id; + }), undefined, true); + rt.dropAll(rest); + flush(log.value, out); + log[Symbol.dispose](); +} + +/** Of `()`, which JS holds as `undefined`, so an `Option` of one is `rt.None`. */ +export function units(data: rt.ByteSlice, out: rt.ByteVec): void { + const results: rt.Result[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.Result => { + return result_map$03hz3l7(split(_2), (_24: rt.u8): undefined => {}); + }), undefined, 2, true); + rt.byteVecPush(out, rt.iterCount(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true)) & 0xff); + const iter: rt.Iter>> = rt.iterSliceMut(results); + while (true) { + const _16: rt.Place> | rt.Done = iter.next(); + if (_16 === rt.DONE) { + break; + } + const it: rt.Iter> = rt.iterOption(rt.resultAsMut(_16)); + rt.byteVecPush(out, rt.iterToOption(it.next()) !== undefined ? 1 : 0); + rt.byteVecPush(out, rt.iterToOption(it.next()) !== undefined ? 1 : 0); + } + for (const _36 of results) { + rt.byteVecPush(out, option_mapOr$1w5qtj7(rt.iterToOption(rt.iterResult(_36).next(), rt.None), 160, (_26: undefined): rt.u8 => { + return 161; + })); + rt.byteVecPush(out, rt.iterToOption(rt.iterResult(_36).nextBack(), rt.None) !== rt.None ? 1 : 0); + } + rt.byteVecPush(out, rt.iterCount(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true)) & 0xff); +} + +/** Of an `Option`, which `flatten` reads into in turn. */ +export function nested(data: rt.ByteSlice, out: rt.ByteVec): void { + let _14!: rt.u8; + const results: rt.Result[] = rt.iterToArray(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_2: rt.u8): rt.Result => { + const b: rt.u8 = _2; + const _42: rt.u8 = rt.u8Rem(b, 4); + if (_42 === 0) { + return rt.Err(b); + } + if (_42 === 1) { + return rt.OK; + } + return rt.Ok(b); + }), undefined, 2, true); + for (const _9 of results) { + const _15: rt.u8 | undefined | rt.Done = rt.iterResult(_9).next(); + if (_15 === rt.DONE) { + _14 = 164; + } else if (_15 === undefined) { + _14 = 163; + } else { + _14 = _15; + } + rt.byteVecPush(out, _14); + } + const iter2: rt.Iter> = rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterOption(rt.resultAsMut(value)), false, undefined, true); + while (true) { + const _27: rt.Place | rt.Done = iter2.next(); + if (_27 === rt.DONE) { + break; + } + if (_27.v === undefined) { + _27.v = 165; + } else { + _27.v = rt.u8WrappingAdd(_27.v, 1); + } + } + rt.iterExtendBytes(out, rt.iterFlatten(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), (value: rt.u8 | undefined) => rt.iterOption(value), false, undefined, true), "next"); + rt.iterExtendBytes(out, rt.iterRev(rt.iterFlatten(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), (value: rt.u8 | undefined) => rt.iterOption(value), false, undefined, true)), "next"); +} + +/** `N` bytes of `data` from `at`, past its end each its index. */ +export function bytesAt$0(data: rt.ByteSlice, at: rt.usize): Uint8Array { + return rt.bytesFromFn(0, (i: rt.usize): rt.u8 => { + return option_unwrapOr$0r2bmpr(rt.byteSliceGet(data, rt.usizeAdd(at, i)), rt.usizeAdd(at, i) & 0xff); + }); +} + +/** `N` bytes of `data` from `at`, past its end each its index. */ +export function bytesAt$1(data: rt.ByteSlice, at: rt.usize): Uint8Array { + return rt.bytesFromFn(1, (i: rt.usize): rt.u8 => { + return option_unwrapOr$0r2bmpr(rt.byteSliceGet(data, rt.usizeAdd(at, i)), rt.usizeAdd(at, i) & 0xff); + }); +} + +/** `N` bytes of `data` from `at`, past its end each its index. */ +export function bytesAt$5(data: rt.ByteSlice, at: rt.usize): Uint8Array { + return rt.bytesFromFn(5, (i: rt.usize): rt.u8 => { + return option_unwrapOr$0r2bmpr(rt.byteSliceGet(data, rt.usizeAdd(at, i)), rt.usizeAdd(at, i) & 0xff); + }); +} + +/** Of arrays of bytes, each lent as a slice of it: of no bytes, one, and many. */ +export function arrays$0(data: rt.ByteSlice, out: rt.ByteVec): void { + const results: rt.Result[] = rt.iterToArray(rt.iterMap(new rt.Range(0, 5), (k: rt.usize): rt.Result => { + if (k === 2 || k === 4) { + return rt.Err(k & 0xff); + } + return rt.Ok(bytesAt$0(data, rt.usizeMul(k, 0))); + }), undefined, 2, true); + const iter: rt.Iter = rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _13: rt.ByteSlice | rt.Done = iter.next(); + if (_13 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _13); + } + const iter2: rt.Iter = rt.iterRev(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _26: rt.ByteSlice | rt.Done = iter2.next(); + if (_26 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _26); + } + const iter3: rt.Iter = rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterLend(rt.iterResult(value.v), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _38: rt.ByteSlice | rt.Done = iter3.next(); + if (_38 === rt.DONE) { + break; + } + rt.byteSliceView(_38).reverse(); + const _44: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(_38)); + if (_44 !== undefined) { + _44.v = _44.v ^ 17; + } + } + const iter4: rt.Iter>> = rt.iterSliceMut(results); + l7: while (true) { + const _51: rt.Place> | rt.Done = iter4.next(); + if (_51 === rt.DONE) { + break; + } + const iter5: rt.Iter = rt.iterLend(rt.iterResult(_51.v), rt.byteSliceFrom); + while (true) { + const _58: rt.ByteSlice | rt.Done = iter5.next(); + if (_58 === rt.DONE) { + continue l7; + } + const _62: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(_58)); + if (_62 !== undefined) { + _62.v = rt.u8WrappingAdd(_62.v, 3); + } + } + } + const first: rt.Result = copy$Result_array0_u8_u8(results[rt.idx(results, 0)]); + const other: rt.Result = copy$Result_array0_u8_u8(results[rt.idx(results, 1)]); + const iter6: rt.Iter = rt.iterChain(rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(other), rt.byteSliceFrom)), rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _85: rt.ByteSlice | rt.Done = iter6.next(); + if (_85 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _85); + } + const iter7: rt.Iter = rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(results[rt.idx(results, 3)]), rt.byteSliceFrom)); + while (true) { + const _98: rt.ByteSlice | rt.Done = iter7.next(); + if (_98 === rt.DONE) { + break; + } + rt.byteSliceFill(_98, 90); + } + const iter8: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _107: rt.ByteSlice | rt.Done = iter8.next(); + if (_107 === rt.DONE) { + break; + } + rt.byteSliceView(_107).reverse(); + } + const iter9: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _116: rt.ByteSlice | rt.Done = iter9.next(); + if (_116 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _116); + } + l18: for (const _125 of results) { + const iter11: rt.Iter = rt.iterLend(rt.iterResult(_125), rt.byteSliceFrom); + while (true) { + const _131: rt.ByteSlice | rt.Done = iter11.next(); + if (_131 === rt.DONE) { + continue l18; + } + rt.byteVecExtendFromSlice(out, _131); + } + } + const iter12: rt.Iter = rt.iterLend(rt.iterSlice(rt.iterToArray(rt.iterChain(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), rt.iterResult(copy$Result_array0_u8_u8(first))), "next", 0)), rt.byteSliceFrom); + while (true) { + const _146: rt.ByteSlice | rt.Done = iter12.next(); + if (_146 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _146); + } +} + +/** Of arrays of bytes, each lent as a slice of it: of no bytes, one, and many. */ +export function arrays$1(data: rt.ByteSlice, out: rt.ByteVec): void { + const results: rt.Result[] = rt.iterToArray(rt.iterMap(new rt.Range(0, 5), (k: rt.usize): rt.Result => { + if (k === 2 || k === 4) { + return rt.Err(k & 0xff); + } + return rt.Ok(bytesAt$1(data, rt.usizeMul(k, 1))); + }), undefined, 2, true); + const iter: rt.Iter = rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _13: rt.ByteSlice | rt.Done = iter.next(); + if (_13 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _13); + } + const iter2: rt.Iter = rt.iterRev(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _26: rt.ByteSlice | rt.Done = iter2.next(); + if (_26 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _26); + } + const iter3: rt.Iter = rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterLend(rt.iterResult(value.v), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _38: rt.ByteSlice | rt.Done = iter3.next(); + if (_38 === rt.DONE) { + break; + } + rt.byteSliceView(_38).reverse(); + const _44: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(_38)); + if (_44 !== undefined) { + _44.v = _44.v ^ 17; + } + } + const iter4: rt.Iter>> = rt.iterSliceMut(results); + l7: while (true) { + const _51: rt.Place> | rt.Done = iter4.next(); + if (_51 === rt.DONE) { + break; + } + const iter5: rt.Iter = rt.iterLend(rt.iterResult(_51.v), rt.byteSliceFrom); + while (true) { + const _58: rt.ByteSlice | rt.Done = iter5.next(); + if (_58 === rt.DONE) { + continue l7; + } + const _62: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(_58)); + if (_62 !== undefined) { + _62.v = rt.u8WrappingAdd(_62.v, 3); + } + } + } + const first: rt.Result = copy$Result_array1_u8_u8(results[rt.idx(results, 0)]); + const other: rt.Result = copy$Result_array1_u8_u8(results[rt.idx(results, 1)]); + const iter6: rt.Iter = rt.iterChain(rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(other), rt.byteSliceFrom)), rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _85: rt.ByteSlice | rt.Done = iter6.next(); + if (_85 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _85); + } + const iter7: rt.Iter = rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(results[rt.idx(results, 3)]), rt.byteSliceFrom)); + while (true) { + const _98: rt.ByteSlice | rt.Done = iter7.next(); + if (_98 === rt.DONE) { + break; + } + rt.byteSliceFill(_98, 90); + } + const iter8: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _107: rt.ByteSlice | rt.Done = iter8.next(); + if (_107 === rt.DONE) { + break; + } + rt.byteSliceView(_107).reverse(); + } + const iter9: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _116: rt.ByteSlice | rt.Done = iter9.next(); + if (_116 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _116); + } + l18: for (const _125 of results) { + const iter11: rt.Iter = rt.iterLend(rt.iterResult(_125), rt.byteSliceFrom); + while (true) { + const _131: rt.ByteSlice | rt.Done = iter11.next(); + if (_131 === rt.DONE) { + continue l18; + } + rt.byteVecExtendFromSlice(out, _131); + } + } + const iter12: rt.Iter = rt.iterLend(rt.iterSlice(rt.iterToArray(rt.iterChain(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), rt.iterResult(copy$Result_array1_u8_u8(first))), "next", 1)), rt.byteSliceFrom); + while (true) { + const _146: rt.ByteSlice | rt.Done = iter12.next(); + if (_146 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _146); + } +} + +/** Of arrays of bytes, each lent as a slice of it: of no bytes, one, and many. */ +export function arrays$5(data: rt.ByteSlice, out: rt.ByteVec): void { + const results: rt.Result[] = rt.iterToArray(rt.iterMap(new rt.Range(0, 5), (k: rt.usize): rt.Result => { + if (k === 2 || k === 4) { + return rt.Err(k & 0xff); + } + return rt.Ok(bytesAt$5(data, rt.usizeMul(k, 5))); + }), undefined, 6, true); + const iter: rt.Iter = rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _13: rt.ByteSlice | rt.Done = iter.next(); + if (_13 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _13); + } + const iter2: rt.Iter = rt.iterRev(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _26: rt.ByteSlice | rt.Done = iter2.next(); + if (_26 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _26); + } + const iter3: rt.Iter = rt.iterFlatten(rt.iterSliceMut(results), (value: rt.Place>) => rt.iterLend(rt.iterResult(value.v), rt.byteSliceFrom), false, undefined, true); + while (true) { + const _38: rt.ByteSlice | rt.Done = iter3.next(); + if (_38 === rt.DONE) { + break; + } + rt.byteSliceView(_38).reverse(); + const _44: rt.Place | undefined = rt.sliceLastMut(rt.byteSliceView(_38)); + if (_44 !== undefined) { + _44.v = _44.v ^ 17; + } + } + const iter4: rt.Iter>> = rt.iterSliceMut(results); + l7: while (true) { + const _51: rt.Place> | rt.Done = iter4.next(); + if (_51 === rt.DONE) { + break; + } + const iter5: rt.Iter = rt.iterLend(rt.iterResult(_51.v), rt.byteSliceFrom); + while (true) { + const _58: rt.ByteSlice | rt.Done = iter5.next(); + if (_58 === rt.DONE) { + continue l7; + } + const _62: rt.Place | undefined = rt.sliceFirstMut(rt.byteSliceView(_58)); + if (_62 !== undefined) { + _62.v = rt.u8WrappingAdd(_62.v, 3); + } + } + } + const first: rt.Result = copy$Result_array5_u8_u8(results[rt.idx(results, 0)]); + const other: rt.Result = copy$Result_array5_u8_u8(results[rt.idx(results, 1)]); + const iter6: rt.Iter = rt.iterChain(rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(other), rt.byteSliceFrom)), rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterLend(rt.iterResult(value), rt.byteSliceFrom), false, undefined, true)); + while (true) { + const _85: rt.ByteSlice | rt.Done = iter6.next(); + if (_85 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _85); + } + const iter7: rt.Iter = rt.iterChain(rt.iterLend(rt.iterResult(first), rt.byteSliceFrom), rt.iterLend(rt.iterResult(results[rt.idx(results, 3)]), rt.byteSliceFrom)); + while (true) { + const _98: rt.ByteSlice | rt.Done = iter7.next(); + if (_98 === rt.DONE) { + break; + } + rt.byteSliceFill(_98, 90); + } + const iter8: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _107: rt.ByteSlice | rt.Done = iter8.next(); + if (_107 === rt.DONE) { + break; + } + rt.byteSliceView(_107).reverse(); + } + const iter9: rt.Iter = rt.iterLend(rt.iterResult(first), rt.byteSliceFrom); + while (true) { + const _116: rt.ByteSlice | rt.Done = iter9.next(); + if (_116 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _116); + } + l18: for (const _125 of results) { + const iter11: rt.Iter = rt.iterLend(rt.iterResult(_125), rt.byteSliceFrom); + while (true) { + const _131: rt.ByteSlice | rt.Done = iter11.next(); + if (_131 === rt.DONE) { + continue l18; + } + rt.byteVecExtendFromSlice(out, _131); + } + } + const iter12: rt.Iter = rt.iterLend(rt.iterSlice(rt.iterToArray(rt.iterChain(rt.iterFlatten(rt.iterSlice(results), (value: rt.Result) => rt.iterResult(value), false, undefined, true), rt.iterResult(copy$Result_array5_u8_u8(first))), "next", 5)), rt.byteSliceFrom); + while (true) { + const _146: rt.ByteSlice | rt.Done = iter12.next(); + if (_146 === rt.DONE) { + break; + } + rt.byteVecExtendFromSlice(out, _146); + } +} + +//# sourceMappingURL=results.ts.map diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 8c699a0c9..4c1c26c90 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -5,8 +5,8 @@ use crate::{ args, arrays, ascii, atomics, borrows, bounds, boxes, captures, cells, chars, chunks, clones, collections, combinators, counts, cows, cycles, defaults, durations, dyns, edits, errors, fields, floats, fmt, folds, generics, hashes, hints, holds, ints, iters, joins, keys, lengths, lists, locals, locks, methods, nested, objects, orders, - pointers, refs, returns, saturates, separated, shapes, singles, slices, splits, statics, strs, tuples, utf8, - wrappers, wraps, zeros, + pointers, refs, results, returns, saturates, separated, shapes, singles, slices, splits, statics, strs, tuples, + utf8, wrappers, wraps, zeros, }; /// The native side's entry: [`run`], except that a case starting with 0xff prints a @@ -269,6 +269,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("args::args", args::args), ("returns::returns", returns::returns), ("borrows::guards", |_, data, out| borrows::guards(data, out)), + ("results::results", results::results), ("fields::fields", fields::fields), ("strs::gets", strs::gets), ] diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index 5f2cb06ba..86026f31f 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -5,7 +5,7 @@ //! aggregates, closures and what they write of what they captured, traits, generic //! types, formatting, collections, `LinkedList`s, UTF-8 decoding, `&mut` to values JS copies, whole //! writes through a `&mut` to an object, the standard library calls it maps, `Option`'s -//! and `Result`'s combinators from core's MIR, `Option`s of values that can already be +//! and `Result`'s combinators from core's MIR, `Result`'s iterators, `Option`s of values that can already be //! `undefined`, atomics, `static` ones included, trait objects, one-time cells, mutexes, //! `Cell`s, `UnsafeCell`s, `RefCell`s, read-write locks, and thread-locals, the defaults //! of std types, the counts of shared pointers, arrays `array::from_fn` and `map` make, @@ -77,6 +77,7 @@ mod objects; mod orders; mod pointers; mod refs; +mod results; mod returns; mod saturates; mod separated; diff --git a/ts/fixtures/lang/src/results.rs b/ts/fixtures/lang/src/results.rs new file mode 100644 index 000000000..1d17975b4 --- /dev/null +++ b/ts/fixtures/lang/src/results.rs @@ -0,0 +1,245 @@ +//! The iterators std makes of a `Result`: `iter`, `iter_mut`, and `into_iter`, by value and +//! through a reference, alone and beside others, and `flatten` over `Result`s, read from +//! both ends and written through. Of payloads JS copies, holds as objects, holds as +//! `undefined`, nests in an `Option`, and lends as a slice, with each `Ok` and `Err` dropped +//! where std drops it. + +use std::cell::RefCell; +use std::rc::Rc; + +/// The iterators of `Result`s of each payload `kind` picks. +pub fn results(kind: u8, data: &[u8], out: &mut Vec) { + match kind % 7 { + 0 => copied(data, out), + 1 => owned(data, out), + 2 => units(data, out), + 3 => nested(data, out), + 4 => arrays::<0>(data, out), + 5 => arrays::<1>(data, out), + _ => arrays::<5>(data, out), + } +} + +/// `Ok` for a byte not divisible by 3, else `Err`. +fn split(b: u8) -> Result { + if b % 3 == 0 { Err(b) } else { Ok(b) } +} + +/// Of bytes, which JS copies, so a `&mut` lends each as its place. +fn copied(data: &[u8], out: &mut Vec) { + let mut results: Vec> = data.iter().map(|&b| split(b)).collect(); + for r in &results { + out.extend(r.iter()); + out.push(r.iter().len() as u8); + let (lo, hi) = r.iter().size_hint(); + out.extend([lo as u8, hi.map_or(0xee, |h| h as u8)]); + } + for r in results.iter_mut() { + for x in r.iter_mut() { + *x = x.wrapping_add(1); + } + } + for r in &mut results { + for x in r { + *x ^= 0x10; + } + } + out.extend(results.iter().flatten()); + for x in results.iter_mut().flatten() { + *x = x.wrapping_mul(3); + } + out.extend(results.iter().copied().flatten()); + out.extend(results.iter().flatten().rev()); + // From both ends at once, until they meet. + let mut it = results.iter().flatten(); + while let (Some(a), b) = (it.next(), it.next_back()) { + out.extend([*a, b.copied().unwrap_or(0xaa)]); + } + // Beside another iterator, through `IntoIterator` of a reference to a `Result`. + let mut first = results.first().copied().unwrap_or(Err(0)); + out.extend(data.iter().chain(&first).chain(first.iter().rev())); + for (a, b) in data.iter().take(1).zip(&first) { + out.push(a.wrapping_sub(*b)); + } + for x in &mut first { + *x = x.wrapping_sub(1); + } + out.extend(first.into_iter().chain(first)); + // One read item by item, and a clone, which reads on independently. + let mut it = first.iter(); + let cloned = it.clone(); + out.push(it.next().copied().unwrap_or(0xee)); + out.push(it.next().is_none() as u8); + out.push(cloned.count() as u8); + let mut into = first.into_iter(); + let mut back = into.clone(); + out.extend([into.next(), back.next_back(), back.next()].map(|x| x.unwrap_or(0xdd))); + let lent: Vec<&u8> = Vec::from_iter(&first); + out.extend(lent.into_iter().copied()); +} + +/// Logs its id as it drops. +struct Logged { + id: u8, + log: Rc>>, +} + +impl Drop for Logged { + fn drop(&mut self) { + self.log.borrow_mut().push(self.id); + } +} + +/// Puts what was logged since the last flush, after a marker. +fn flush(log: &RefCell>, out: &mut Vec) { + out.push(0xfd); + out.extend(log.borrow_mut().drain(..)); +} + +/// Of objects that drop, each `Ok` and `Err` alike: `into_iter` drops an `Err` as it makes +/// the iterator, and the iterator the `Ok` it never yielded. +fn owned(data: &[u8], out: &mut Vec) { + let log = Rc::new(RefCell::new(Vec::new())); + let made = |b: u8| -> Result { + let logged = Logged { + id: b, + log: log.clone(), + }; + if b % 3 == 0 { Err(logged) } else { Ok(logged) } + }; + for &b in data { + let it = made(b).into_iter(); + log.borrow_mut().push(0xfe); + drop(it); + for l in made(b) { + out.push(l.id); + } + flush(&log, out); + } + let mut results: Vec> = data.iter().map(|&b| made(b)).collect(); + for r in &results { + out.extend(r.iter().map(|l| l.id)); + } + for r in results.iter_mut() { + for l in r { + l.id ^= 0x40; + } + } + for l in results.iter_mut().flatten().rev() { + l.id = l.id.wrapping_add(1); + } + out.extend(results.iter().flatten().map(|l| l.id)); + flush(&log, out); + // What a `take` leaves drops with the rest of the source. + for l in results.into_iter().flatten().take(2) { + out.push(l.id); + flush(&log, out); + } + flush(&log, out); + let rest: Vec = data.iter().rev().map(|&b| made(b)).flatten().collect(); + flush(&log, out); + out.extend(rest.iter().map(|l| l.id)); + drop(rest); + flush(&log, out); +} + +/// Of `()`, which JS holds as `undefined`, so an `Option` of one is `rt.None`. +fn units(data: &[u8], out: &mut Vec) { + let mut results: Vec> = data.iter().map(|&b| split(b).map(|_| ())).collect(); + out.push(results.iter().flatten().count() as u8); + for r in &mut results { + let mut it = r.iter_mut(); + out.push(it.next().is_some() as u8); + out.push(it.next().is_some() as u8); + } + for r in &results { + out.push(r.iter().next().map_or(0xa0, |()| 0xa1)); + out.push(r.into_iter().next_back().is_some() as u8); + } + out.push(results.into_iter().flatten().count() as u8); +} + +/// Of an `Option`, which `flatten` reads into in turn. +fn nested(data: &[u8], out: &mut Vec) { + let mut results: Vec, u8>> = data + .iter() + .map(|&b| match b % 4 { + 0 => Err(b), + 1 => Ok(None), + _ => Ok(Some(b)), + }) + .collect(); + for r in &results { + out.push(match r.iter().next() { + Some(Some(b)) => *b, + Some(None) => 0xa3, + None => 0xa4, + }); + } + for o in results.iter_mut().flatten() { + match o { + Some(b) => *b = b.wrapping_add(1), + None => *o = Some(0xa5), + } + } + out.extend(results.iter().flatten().flatten()); + out.extend(results.into_iter().flatten().flatten().rev()); +} + +/// `N` bytes of `data` from `at`, past its end each its index. +fn bytes_at(data: &[u8], at: usize) -> [u8; N] { + std::array::from_fn(|i| data.get(at + i).copied().unwrap_or((at + i) as u8)) +} + +/// Of arrays of bytes, each lent as a slice of it: of no bytes, one, and many. +fn arrays(data: &[u8], out: &mut Vec) { + // An `Err` in the middle and at the end. + let mut results: Vec> = (0..5) + .map(|k| match k { + 2 | 4 => Err(k as u8), + _ => Ok(bytes_at(data, k * N)), + }) + .collect(); + for a in results.iter().flatten() { + out.extend_from_slice(a); + } + for a in results.iter().flatten().rev() { + out.extend_from_slice(a); + } + for a in results.iter_mut().flatten() { + a.reverse(); + if let Some(x) = a.last_mut() { + *x ^= 0x11; + } + } + for r in &mut results { + for a in r.iter_mut() { + if let Some(x) = a.first_mut() { + *x = x.wrapping_add(3); + } + } + } + let mut first = results[0]; + let other = results[1]; + for a in first.iter().chain(&other).chain(results.iter().flatten()) { + out.extend_from_slice(a); + } + for a in first.iter_mut().chain(&mut results[3]) { + a.fill(0x5a); + } + for a in &mut first { + a.reverse(); + } + for a in &first { + out.extend_from_slice(a); + } + for r in &results { + for a in r { + out.extend_from_slice(a); + } + } + let copied: Vec<[u8; N]> = results.into_iter().flatten().chain(first).collect(); + for a in &copied { + out.extend_from_slice(a); + } +} diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index b950c3f66..b0d1a0f40 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -95,6 +95,20 @@ export function optionAsMut(p: Place, none?: None): Pla return p.v === none ? undefined : (p as Place); } +/** + * The payload's place of the `Result` at `p`, while it is `Ok`: writing it makes `p` a + * new `Ok`, as a `Result` is never changed in place. + */ +export function resultAsMut(p: Place>): Place | undefined { + if (!p.v.ok) return undefined; + return place( + () => (p.v as { readonly value: T }).value, + (value) => { + p.v = Ok(value); + }, + ); +} + /** The place `get` reads and `set` writes. */ export function place(get: () => T, set: (value: T) => void): Place { return new Accessed(get, set); diff --git a/ts/runtime/rt/iter.ts b/ts/runtime/rt/iter.ts index 540bd402f..f800962e4 100644 --- a/ts/runtime/rt/iter.ts +++ b/ts/runtime/rt/iter.ts @@ -485,6 +485,16 @@ export function iterOption(o: T | undefined | None, drop?: Drop, none?: No return new OptionIter(o as T, o !== none, drop); } +/** + * `Result::iter`, and with what drops its item, `result::IntoIter`, which drops an `Err` + * by `dropError` as it is made. + */ +export function iterResult(r: Result, drop?: Drop, dropError?: Drop): Iter { + if (r.ok) return new OptionIter(r.value, true, drop); + dropError?.(r.error); + return new OptionIter(undefined, false); +} + /** `iter::once`. */ export function iterOnce(value: T, drop?: Drop): Iter { return new OptionIter(value, true, drop); diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index b1374863c..05d799ffe 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -338,7 +338,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { // std's mappings take a `&mut` they declare that is an `rt.Place` as what it points // at, as a call's operands pass it. let pointees = match self.t.mapped(def_id, gargs) { - true => super::pointer::pointees(tcx, def_id), + true => super::pointer::pointees(self.t, def_id, gargs), false => Vec::new(), }; let values: Vec = std::iter::zip(&names, sig.inputs()) diff --git a/ts/src/lower/iter.rs b/ts/src/lower/iter.rs index 8d56fb345..73205ac10 100644 --- a/ts/src/lower/iter.rs +++ b/ts/src/lower/iter.rs @@ -200,14 +200,30 @@ pub fn into_iter<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, value: Expr, sp } Some(items(Expr::rt("iterOption", values), inner)) } + Std::Result if places(b, args.type_at(0)) => Some(result_places(value)), + // One by value drops its `Err` as it makes the iterator. + Std::Result => { + let (ok, err) = (args.type_at(0), args.type_at(1)); + let mut values = each(b, ok, vec![b.t.pointee_value(ty, value)]); + if owned && b.t.drops(err) { + values.resize(2, Expr::undefined()); + values.push(b.t.dropper(err, span)); + } + Some(items(Expr::rt("iterResult", values), ok)) + } _ => super::collections::into_iter(b, ty, value, span), }, _ => None, } } -/// `iter`, over the elements of a slice or `Vec` of `elem`s or the payload of an `Option`, -/// yielding references to them: a slice of each array of bytes. +/// The iterator of the payload of the `Result` at `place`, an `rt.Place`, as its own place. +fn result_places(place: Expr) -> Expr { + Expr::rt("iterOption", vec![Expr::rt("resultAsMut", vec![place])]) +} + +/// `iter`, over the elements of a slice or `Vec` of `elem`s or the payload of an `Option` +/// or a `Result`, yielding references to them: a slice of each array of bytes. pub(super) fn by_ref(iter: Expr, elem: Ty<'_>) -> Expr { match super::byte_array(elem) { true => Expr::rt("iterLend", vec![iter, Expr::Rt("byteSliceFrom".into())]), @@ -325,6 +341,8 @@ pub fn call<'tcx>( } return Some(Expr::rt("iterOption", args)); } + ("Result", "iter_mut") if b.t.needs_place(targ(0)?) => return Some(result_places(args.pop()?)), + ("Result", "iter" | "iter_mut") => return Some(Expr::rt("iterResult", args)), // A `&mut` to a `&mut` iterator is itself, an `rt.Place` that each use reads through. ("IntoIterator", "into_iter") if through_mut(targ(0)?) => return args.pop(), // So is a `&mut` iterator, which what takes it by value borrows as it does. @@ -966,6 +984,7 @@ fn clones<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Option< | ["ascii", "EscapeDefault"] | ["slice", "ascii", "EscapeAscii"] | ["option", "Iter"] + | ["result", "Iter"] | ["ops", "range", "Range" | "RangeFrom" | "RangeInclusive"] | ["collections", "vec_deque", "iter", "Iter"] | ["collections", "linked_list", "Iter"] @@ -982,6 +1001,7 @@ fn clones<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Option< ["vec", "into_iter", "IntoIter"] | ["array", "iter", "IntoIter"] | ["option", "IntoIter"] + | ["result", "IntoIter"] | ["iter", "sources", "once", "Once"] | ["collections", "vec_deque", "into_iter", "IntoIter"] | ["collections", "linked_list", "IntoIter"] @@ -1078,8 +1098,8 @@ pub(super) fn holds_closure(tcx: ty::TyCtxt<'_>, did: DefId) -> bool { /// 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. +/// `next` drops it as it ends. What std's collections', `Option`'s, and `Result`'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; @@ -1091,6 +1111,7 @@ fn flattens<'tcx>(b: &mut Body<'_, '_, 'tcx>, inner: Ty<'tcx>, span: Span) { ["vec", "into_iter", "IntoIter"] | ["array", "iter", "IntoIter"] | ["option", "IntoIter"] + | ["result", "IntoIter"] | ["iter", "sources", "once", "Once"] | ["collections", "hash", "map", "IntoIter" | "IntoKeys" | "IntoValues"] | ["collections", "hash", "set", "IntoIter"] diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index a99df894a..5a70b9075 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -834,7 +834,7 @@ pub fn may_from_mir(tcx: TyCtxt<'_>, did: DefId) -> bool { "unwrap" | "expect" | "is_some" | "is_none" | "as_ref" | "copied" | "cloned" | "iter" ) | ( Some(Std::Result), - "unwrap" | "expect" | "unwrap_err" | "is_ok" | "is_err" + "unwrap" | "expect" | "unwrap_err" | "is_ok" | "is_err" | "iter" ) | ( Some(Std::LocalKey), "with" | "try_with" | "initialize_with" | "with_borrow_mut" diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index fd9a1befc..0bb2f3acd 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -299,7 +299,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { { return self.err(span, why); } - crate::lower::pointer::pointees(tcx, def_id) + crate::lower::pointer::pointees(self.b.t, def_id, gargs) } }; let mut values = self.operands(local, &pointees, args, result, span, out); @@ -336,7 +336,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let t = &*self.b.t; // Mappings that lend an element JS copies as its place, as a map's `get_mut` does, the // item a `Peekable` peeked, the place a `&mut dyn Any` wraps, a `RefCell` key's value, - // or the value of an `Arc`, a lock, or a cell. + // a `Result`'s payload, or the value of an `Arc`, a lock, or a cell. let lends = match library::key(tcx, def_id) { Some((owner, name)) => match (owner.as_str(), name.as_str()) { ("slice", "get_mut" | "first_mut" | "last_mut" | "iter_mut" | "split_first_mut" | "split_last_mut") @@ -344,6 +344,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { | ("dyn Any", "downcast_mut") | ("Peekable", "peek_mut") | ("LocalKey", "with_borrow_mut") + | ("Result", "iter_mut") | ("Arc" | "Rc", "get_mut" | "make_mut") | ("Mutex" | "RwLock" | "RefCell" | "OnceCell" | "OnceLock", "get_mut") => true, ("IntoIterator", "into_iter") => gargs.types().next().is_some_and(|ty| { @@ -356,6 +357,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Some( Std::Vec | Std::Option + | Std::Result | Std::HashMap | Std::BTreeMap | Std::VecDeque diff --git a/ts/src/lower/pointer.rs b/ts/src/lower/pointer.rs index 77aa09978..8aa6e1c13 100644 --- a/ts/src/lower/pointer.rs +++ b/ts/src/lower/pointer.rs @@ -370,26 +370,37 @@ pub fn keeps<'tcx>(tcx: ty::TyCtxt<'tcx>, def_id: rustc_hir::def_id::DefId, args keeps || from_reference(tcx, def_id, args) } -/// Whether std's `def_id` is one a mapping takes the `rt.Place` a `&mut` is for, rather -/// than what it points at: a `MaybeUninit`'s, which it points into, an `Arc`'s that -/// `make_mut` replaces, a `String`'s that a drain edits as it drops, and a well-known -/// crate's, such as a `Bytes` that `Buf::advance` moves past its front. -pub fn takes_place(tcx: ty::TyCtxt<'_>, def_id: rustc_hir::def_id::DefId) -> bool { +/// Whether std's `def_id` of `args` is one a mapping takes the `rt.Place` a `&mut` is for, +/// rather than what it points at: a `MaybeUninit`'s, which it points into, an `Arc`'s that +/// `make_mut` replaces, a `String`'s that a drain edits as it drops, a `Result`'s whose +/// payload JS copies, which `iter_mut` lends as a place that writes the whole `Result`, +/// and a well-known crate's, such as a `Bytes` that `Buf::advance` moves past its front. +fn takes_place<'tcx>( + t: &Translator<'_, 'tcx>, + def_id: rustc_hir::def_id::DefId, + args: ty::GenericArgsRef<'tcx>, +) -> bool { matches!( - super::library::key(tcx, def_id), + super::library::key(t.tcx, def_id), Some((owner, name)) if owner == "MaybeUninit" || matches!(owner.as_str(), "Arc" | "Rc") && name == "make_mut" || (owner.as_str(), name.as_str()) == ("String", "drain") - ) || super::stock::is_stock(tcx, def_id) + || (owner.as_str(), name.as_str()) == ("Result", "iter_mut") && t.needs_place(args.type_at(0)) + ) || super::stock::is_stock(t.tcx, def_id) } -/// Which of std's `def_id`'s parameters its mapping takes as what the `&mut` it declares -/// points at, rather than the `rt.Place` that `&mut` may be: not a type parameter that -/// one instantiates, as `Pin::new`'s pointer. -pub fn pointees(tcx: ty::TyCtxt<'_>, def_id: rustc_hir::def_id::DefId) -> Vec { - let takes_place = takes_place(tcx, def_id); - let sig = tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); - tcx.instantiate_bound_regions_with_erased(sig) +/// Which of std's `def_id`'s parameters its mapping of `args` takes as what the `&mut` it +/// declares points at, rather than the `rt.Place` that `&mut` may be: not a type parameter +/// that one instantiates, as `Pin::new`'s pointer. +pub fn pointees<'tcx>( + t: &Translator<'_, 'tcx>, + def_id: rustc_hir::def_id::DefId, + args: ty::GenericArgsRef<'tcx>, +) -> Vec { + let takes_place = takes_place(t, def_id, args); + let sig = t.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip(); + t.tcx + .instantiate_bound_regions_with_erased(sig) .inputs() .iter() .map(|t| !takes_place && matches!(t.kind(), ty::Ref(_, _, rustc_ast::Mutability::Mut)))