diff --git a/driver/src/cargo.rs b/driver/src/cargo.rs index 79697a1e3..5d7c861bb 100644 --- a/driver/src/cargo.rs +++ b/driver/src/cargo.rs @@ -96,7 +96,7 @@ pub struct Check<'a> { pub target: Option<&'a str>, /// Passed on to `cargo check`, such as `--features`. pub args: &'a [String], - /// The environment the wrapper reads its job from. + /// The environment cargo runs in, which the wrapper reads its job from. pub env: &'a [(&'a str, &'a OsStr)], } @@ -110,7 +110,7 @@ impl Check<'_> { let cargo = |subcommand: &str| { let mut cmd = cargo(); // Cargo reads its config from where it runs, so run where the package is. - cmd.current_dir(package_dir); + cmd.current_dir(package_dir).envs(self.env.iter().copied()); cmd.arg(subcommand) .arg("--manifest-path") .arg(self.manifest) @@ -137,7 +137,6 @@ impl Check<'_> { .args(self.args) .env("RUSTC_WRAPPER", &exe) .env(crate::rustc::RAN, &ran) - .envs(self.env.iter().copied()) .status() .map_err(|err| format!("running cargo: {err}"))?; if !status.success() { diff --git a/quest/m2/ts-model/README.md b/quest/m2/ts-model/README.md index 39ee019c8..a316ab1d1 100644 --- a/quest/m2/ts-model/README.md +++ b/quest/m2/ts-model/README.md @@ -47,7 +47,6 @@ Public API: the translator's output for moq-net's model. - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - kio closes a channel when its last producer drops - [Shared ownership](/quest/m2/ts-shared.md) - kio's waiters are `Arc`/`Weak` with observable counts, and its atomics and locks are plain values - [Translate safe dependencies with the package](/quest/m2/ts-model/crates.md) - kio, moq-clock, moq-pattern, and rangemap translate as one program with moq-net -- [Std combinators from core's MIR](/quest/m2/ts-model/core-mir.md) - `Option`'s and `Result`'s combinators lower from core's own bodies - [Std gaps the model reaches](/quest/m2/ts-model/std-more.md) - ranges, wrappers, and `Vec`'s editing methods - [Options of values that can be undefined](/quest/m2/ts-model/nested-option.md) - `Option>` and `Option<()>` keep `None` apart from `Some(None)` - [Mutable references to values JS copies](/quest/m2/ts-model/mut-place.md) - a `&mut` to a number or an `Option` passed on or kept diff --git a/quest/m2/ts-model/core-mir.md b/quest/m2/ts-model/core-mir.md deleted file mode 100644 index 64c8571f4..000000000 --- a/quest/m2/ts-model/core-mir.md +++ /dev/null @@ -1,44 +0,0 @@ -# [M] Std combinators from core's MIR - -## Goal - -rust2-ts lowers `Option`'s and `Result`'s combinators that take `self` or `&self` -(`is_some_and`, `is_none_or`, `and_then`, `filter`, `or_else`, `map_or_else`, -`unwrap_or_default`, `zip`, `Clone`, and the ones `library` maps today) from core's own -MIR instead of a runtime function each, with drops and unwinding exact, proven by -differential tests against native Rust, and `just ts bench` and the codec's bundle no -worse than today's. - -## Plan - -Spiked on 2026-10-27 on a local branch: lowering these from core's MIR as the crate's own -instances passed the differential tests, cut moq-net's refusals of these calls from 1,175 -to 225, and tied the runtime in Chrome, Node, and Bun once an `Ok(x)` rebuilt from an -`Ok(x)` reused the object (Node measured 1.31x slower without that). - -Decided with the maintainer on 2026-10-27: - -- Build std from source for exact unwinding: the wasm32 sysroot is `panic=abort`, so - core's MIR has no cleanup blocks, and lowered as is, `task`'s unwinding scripts lose - drops. Pass `-Zbuild-std=core,alloc,std,panic_unwind,panic_abort`, with - `-Cpanic=unwind -Zalways-encode-mir` on core, alloc, and std through cargo's profiles - (`-Zprofile-rustflags`) so cargo's fingerprint sees them. `panic_abort` stays aborting, - since a `cdylib` dependency such as `tracing-wasm` links it. The driver's `cargo clean` - needs `CARGO_UNSTABLE_PROFILE_RUSTFLAGS=true`. The spike measured moq-net's cold - check 42 s against 33 s, and warm unchanged. -- Keep one instance per closure, so each call site stays monomorphic, and merge - functions whose output is identical: an instance per closure grew moq-net's census - from 4,922 to 6,385 functions. -- `Option` and `Result` only. `Bound`, `Reverse`, `NonZero`, and `Duration` need core's - types translated, with pattern types and niche transmutes. - -Also: - -- Integer methods stay in the runtime: core's plain MIR `Add` wraps, and the translator - lowers it as checked. `UbChecks` is false, `cold_path` is nothing, and a - `precondition_check` block is unreachable. -- Refusals inside a core body point at the crate's call site. -- `&mut self` methods (`take`, `replace`, `insert`, `get_or_insert*`, `as_mut`), `unwrap` - and `expect`, and the single-expression mappings (`is_some`, `as_ref`) keep `library`'s. - -Public API: the translator's output; the translation's build compiles std from source. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index 729622694..ad1fc755c 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -2,6 +2,12 @@ ## Unreleased +- Translation builds std from source for `wasm32-unknown-unknown`, so the toolchain needs + its `rust-src` component, as the flake's has, and the first run compiles std. +- `Option`'s and `Result`'s combinators lower from core's MIR into `core/option.ts` and + `core/result.ts`, so the runtime no longer exports `optionMap`, `optionMapOr`, + `optionUnwrapOr`, `optionOkOr`, `resultOk`, `resultErr`, `resultMap`, `resultMapErr`, + `resultAndThen`, `resultInspectErr`, or `resultUnwrapOr`. - `--census` starts from the config's roots, as translation does. For the census of every item, census with a config that names no roots: `roots = []`. - A struct is a plain object typed by an interface, unless it may drop: build one as a diff --git a/ts/README.md b/ts/README.md index 4ae488da6..93678e0e4 100644 --- a/ts/README.md +++ b/ts/README.md @@ -7,8 +7,9 @@ rust2-ts --config ts.toml (--out dir | --census file.md) [--manifest-path Cargo. ``` It runs `cargo check` on the package with itself as `RUSTC_WRAPPER`, for -`wasm32-unknown-unknown`. Every crate compiles as rustc would; the configured library is -also translated, after type and borrow checking, starting from its roots and following +`wasm32-unknown-unknown`, with std built from source for it, unwinding and with every +function's MIR, which needs the toolchain's `rust-src`. Every crate compiles as rustc +would; the configured library is also translated, after type and borrow checking, starting from its roots and following what they reach. A construct outside the subset is a compile error with its span, and then nothing is written. A type without a JS value is refused where a value of it is made or received, such as a parameter, a field, or a call, rather than again at each variable @@ -60,7 +61,9 @@ and each type a module of its own beside it, holding the type and its functions from. `rt.ts` beside them is the runtime: what std does that JS does not, with iterators in `rt/iter.ts`, `str`'s searches in `rt/str.ts`, collections in `rt/collections.ts`, ownership and async in -`rt/task.ts`, and `Duration` in `rt/time.ts`. +`rt/task.ts`, and `Duration` in `rt/time.ts`. What translates from std's own MIR, +`Option`'s and `Result`'s combinators, goes in a module under its crate's name, as +`core/option.ts` holds `map$Option_u64_u64_rescale_closure0`. | Rust | TypeScript | | --- | --- | @@ -188,12 +191,14 @@ elaboration put it. A panic unwinds: a function with cleanup to run catches `rt. runs the cleanup blocks MIR has under `-C panic=unwind`, and throws it on, so what a panic drops matches native Rust's. A value without `[Symbol.dispose]` of its own, such as an enum or a tuple, drops through glue lowered from rustc's `drop_in_place` shim, a -function of its type's own (`drop$Held`). The runtime functions for std's collections, -`Arc`, and the std functions that may discard an operand (`unwrap_or`, a map's `insert`) -take what drops each value they may drop, and drop it where std's do. So do iterators: one -that owns its items, as a `Vec`'s `into_iter` or a map's `drain` does, drops those it still -holds by `[Symbol.dispose]`, an adaptor drops what it skips or rejects, and a consumer that -takes an iterator by value drops it, a panic included. A `Drop` impl that +function of its type's own (`drop$Held`). `Option`'s and `Result`'s combinators lower +from core's MIR, so they drop what core's do, where core's do. The runtime functions for +std's collections, `Arc`, and the std functions that may discard an operand +(`then_some`, a map's `insert`) take what drops each value they may drop, and drop it +where std's do. So do iterators: one that owns its items, as a `Vec`'s `into_iter` or a +map's `drain` does, drops those it still holds by `[Symbol.dispose]`, an adaptor drops +what it skips or rejects, and a consumer that takes an iterator by value drops it, a +panic included. A `Drop` impl that panics leaves the rest to drop as Rust's does: a class's glue and the runtime's droppers go on to the rest of the value and its container, but a hash table leaks its other entries, as std's does. @@ -379,6 +384,15 @@ they need. in the middle and becomes a loop over a `switch` on the next block. Temporaries assigned once and read once fold back into the expression that reads them unless that would reorder an effect. +- `Option`'s and `Result`'s combinators lower from core's own MIR rather than runtime + functions, each of which restated core's drops and unwinding by hand. The wasm32 + sysroot aborts on panic, so its MIR has no cleanups: std builds from source with + `-C panic=unwind`, which took a cold check from 33 to 42 seconds. Each closure gets + its own instance, keeping call sites monomorphic, and instances that print the same are + merged into one. An `Ok` rebuilt from a stable `Result`'s payload is that `Result`, + without which Node ran the codec 1.31x slower. Against the runtime functions, the codec + and async handoff bundles are within 25 bytes gzipped, and `just ts bench` measures + them within the A/A route's spread in Node, Bun, Chrome, and Firefox. ## Never @@ -402,7 +416,8 @@ format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), wri what it captured, `mem::swap`, `replace`, or `take` of a reference's whole pointee, assigning an `Arc`, a waker, a `MutexGuard`, a pinned reference, or a future through a reference, a switch on or a field of another crate's type without a mapping, and std -functions without a mapping in `src/lower/library.rs`. +functions without a mapping in `src/lower/library.rs`, but for `Option`'s and `Result`'s +methods that take no `&mut`, which lower from core's MIR. ## Tests @@ -430,7 +445,8 @@ built natively for wasm32 and run beside its translation on the same inputs by only in another module, behind a type parameter, or through a box, formatting, methods on generic types, iterators, with closures that log what each - adaptor reads, and std's collections, over keys whose own `Hash`, `Eq`, and `Ord` + adaptor reads, `Option`'s and `Result`'s combinators, with closures that log each call, + and std's collections, over keys whose own `Hash`, `Eq`, and `Ord` disagree with JS's, and `vec![x; n]` of types whose `Clone` counts its clones. Its differential test runs through `caller.ts`, a hand-written caller that also prints a `printable` error nothing translated prints, and adds every 64- and 128-bit case over each pair of values next to a power of two, diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 562b36d48..6d3d28124 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -9,6 +9,7 @@ import type * as EncodeError from "./coding/encode.EncodeError.ts"; import * as Encoder from "./coding/encode.Encoder.ts"; import { zigzag, unzigzag } from "./coding/varint.ts"; import * as Form from "./coding/varint.Form.ts"; +import { unwrapOr$Option_u32, map$Option_u64_u64_encode_msg_closure0 } from "./core/option.ts"; import { form, liteVersion, putU64, putUsize, takeU64, decodeError, encodeError } from "./harness.ts"; import * as Group from "./lite/group.Group.ts"; import type * as Version from "./lite/version.Version.ts"; @@ -222,7 +223,7 @@ export function decodeSplit(data: rt.ByteSlice, version: Version.Version, out: r short = rt.usizeAdd(short, 1); continue l2; } - return rt.Err(_32.error); + return _32 as rt.Result; } } } @@ -283,7 +284,7 @@ export function ordered(data: rt.ByteSlice, out: rt.ByteVec): void { const iterEnd2: rt.u32 = count2; while ((_28 = iterStart2++) < iterEnd2) { const _38: rt.u32 = _10(rt.u32Sub(rt.u32Sub(count2, 1), _28)); - sum = rt.u64Add(sum, rt.optionUnwrapOr(rt.btreeGet(map, _38), 0) as rt.u64); + sum = rt.u64Add(sum, unwrapOr$Option_u32(rt.btreeGet(map, _38), 0) as rt.u64); } const _49: rt.Range = new rt.Range(1 << 14, 2 << 14); const iter3: rt.Iter<[rt.u32, rt.u32]> = rt.btreeRange(map, _49); @@ -380,7 +381,7 @@ export function rescale(selector: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): v scaled = bounded(rt.u128Div(_36, rt.u128Cast(from))); } } else { - const _44: rt.u64 | undefined = rt.optionMap(rt.u64CheckedMul(value, to), (scaled3: rt.u64): rt.u64 => { + const _44: rt.u64 | undefined = map$Option_u64_u64_encode_msg_closure0(rt.u64CheckedMul(value, to), (scaled3: rt.u64): rt.u64 => { return rt.u64Div(scaled3, from); }); if (_44 !== undefined) { diff --git a/ts/fixtures/codec/expected/coding/decode.Decoder.ts b/ts/fixtures/codec/expected/coding/decode.Decoder.ts index 61c6c7814..efe7fe5c2 100644 --- a/ts/fixtures/codec/expected/coding/decode.Decoder.ts +++ b/ts/fixtures/codec/expected/coding/decode.Decoder.ts @@ -4,6 +4,7 @@ import * as rt from "../rt.ts"; import * as DecodeError from "../coding/decode.DecodeError.ts"; import { read } from "../coding/varint.ts"; import type * as Form from "../coding/varint.Form.ts"; +import { mapErr$Result_usize_TryFromIntError_DecodeError_bytes_closure0, inspectErr$Result_u8s_DecodeError_bytes_closure1 } from "../core/result.ts"; import type * as Control from "../stats.Control.ts"; /** @@ -134,7 +135,7 @@ export function varint(self: Decoder): rt.Result; } return _0; } @@ -153,11 +154,11 @@ export function bytes(self: Decoder): rt.Result = varint(self); if (_6.ok) { - const _3: rt.Result = rt.resultMapErr(rt.usizeTryFrom(_6.value), (_2: rt.TryFromIntError): DecodeError.DecodeError => { + const _3: rt.Result = mapErr$Result_usize_TryFromIntError_DecodeError_bytes_closure0(rt.usizeTryFrom(_6.value), (_2: rt.TryFromIntError): DecodeError.DecodeError => { return { tag: "BoundsExceeded" } as DecodeError.DecodeError; }); if (_3.ok) { - return rt.resultInspectErr(slice(self, _3.value), (_22: DecodeError.DecodeError): void => { + return inspectErr$Result_u8s_DecodeError_bytes_closure1(slice(self, _3.value), (_22: DecodeError.DecodeError): void => { self.buf = start; }); } diff --git a/ts/fixtures/codec/expected/coding/encode.Encoder.ts b/ts/fixtures/codec/expected/coding/encode.Encoder.ts index 762443e0f..85498266b 100644 --- a/ts/fixtures/codec/expected/coding/encode.Encoder.ts +++ b/ts/fixtures/codec/expected/coding/encode.Encoder.ts @@ -6,6 +6,8 @@ import type * as Prefix from "../coding/encode.Prefix.ts"; import type * as PrefixKind from "../coding/encode.PrefixKind.ts"; import { write } from "../coding/varint.ts"; import type * as Form from "../coding/varint.Form.ts"; +import { okOr$Option_u64_EncodeError } from "../core/option.ts"; +import { mapErr$Result_u16_TryFromIntError_EncodeError_fill_closure0 } from "../core/result.ts"; import type * as Control from "../stats.Control.ts"; /** @@ -58,7 +60,7 @@ export function varintOpt(self: Encoder, v: rt.u64 | undefined): rt.Result = rt.optionOkOr(rt.u64CheckedAdd(v, 1), "TooLarge" as EncodeError.EncodeError); + const _6: rt.Result = okOr$Option_u64_EncodeError(rt.u64CheckedAdd(v, 1), "TooLarge" as EncodeError.EncodeError); if (_6.ok) { v2 = _6.value; } else { @@ -144,7 +146,7 @@ export function fill(self: Encoder, prefix: Prefix.Prefix): rt.Result = rt.resultMapErr(rt.u16TryFrom(rt.usizeSub(end, body)), (_2: rt.TryFromIntError): EncodeError.EncodeError => { + const _7: rt.Result = mapErr$Result_u16_TryFromIntError_EncodeError_fill_closure0(rt.u16TryFrom(rt.usizeSub(end, body)), (_2: rt.TryFromIntError): EncodeError.EncodeError => { return "TooLarge" as EncodeError.EncodeError; }); if (_7.ok) { diff --git a/ts/fixtures/codec/expected/coding/varint.ts b/ts/fixtures/codec/expected/coding/varint.ts index 26d28f931..af943c1eb 100644 --- a/ts/fixtures/codec/expected/coding/varint.ts +++ b/ts/fixtures/codec/expected/coding/varint.ts @@ -4,6 +4,7 @@ import * as rt from "../rt.ts"; import type * as DecodeError from "../coding/decode.DecodeError.ts"; import type * as BoundsExceeded from "../coding/varint.BoundsExceeded.ts"; import type * as Form from "../coding/varint.Form.ts"; +import { okOr$Option_u8s_u8s_DecodeError } from "../core/option.ts"; /** The high and low 32 bits: the only place the codec splits a `u64`. */ export function toHalves(value: rt.u64): [rt.u32, rt.u32] { @@ -205,21 +206,21 @@ export function readQuic(buf: rt.ByteSlice): rt.Result<[rt.u64, rt.ByteSlice], D if (!(first < 64)) { if (!(first < 128)) { if (!(first < 192)) { - const _54: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); + const _54: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); if (_54.ok) { const val3: [rt.ByteSlice, rt.ByteSlice] = _54.value; return rt.Ok([fromHalves((((val3[0].data[val3[0].start] & 63) << 24) | (val3[0].data[val3[0].start + 1] << 16) | (val3[0].data[val3[0].start + 2] << 8) | val3[0].data[val3[0].start + 3]) >>> 0, ((val3[0].data[val3[0].start + 4] << 24) | (val3[0].data[val3[0].start + 5] << 16) | (val3[0].data[val3[0].start + 6] << 8) | val3[0].data[val3[0].start + 7]) >>> 0), val3[1]] as [rt.u64, rt.ByteSlice]); } return _54; } - const _33: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 4), { tag: "Short" } as DecodeError.DecodeError); + const _33: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 4), { tag: "Short" } as DecodeError.DecodeError); if (_33.ok) { const val2: [rt.ByteSlice, rt.ByteSlice] = _33.value; return rt.Ok([(((val2[0].data[val2[0].start] & 63) << 24) | (val2[0].data[val2[0].start + 1] << 16) | (val2[0].data[val2[0].start + 2] << 8) | val2[0].data[val2[0].start + 3]) >>> 0 as rt.u64, val2[1]] as [rt.u64, rt.ByteSlice]); } return _33; } - const _14: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 2), { tag: "Short" } as DecodeError.DecodeError); + const _14: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 2), { tag: "Short" } as DecodeError.DecodeError); if (_14.ok) { const val: [rt.ByteSlice, rt.ByteSlice] = _14.value; return rt.Ok([(((val[0].data[val[0].start] & 63) << 8) | val[0].data[val[0].start + 1]) as rt.u64, val[1]] as [rt.u64, rt.ByteSlice]); @@ -240,7 +241,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r if (_9 === 0) { _8 = [first as rt.u64, _6[1]] as [rt.u64, rt.ByteSlice]; } else if (_9 === 1) { - const _14: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 2), { tag: "Short" } as DecodeError.DecodeError); + const _14: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 2), { tag: "Short" } as DecodeError.DecodeError); if (_14.ok) { const val: [rt.ByteSlice, rt.ByteSlice] = _14.value; _8 = [(((val[0].data[val[0].start] & 63) << 8) | val[0].data[val[0].start + 1]) as rt.u64, val[1]] as [rt.u64, rt.ByteSlice]; @@ -248,7 +249,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _14; } } else if (_9 === 2) { - const _30: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 3), { tag: "Short" } as DecodeError.DecodeError); + const _30: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 3), { tag: "Short" } as DecodeError.DecodeError); if (_30.ok) { const val2: [rt.ByteSlice, rt.ByteSlice] = _30.value; _8 = [(((val2[0].data[val2[0].start] & 31) << 16) | (val2[0].data[val2[0].start + 1] << 8) | val2[0].data[val2[0].start + 2]) as rt.u64, val2[1]] as [rt.u64, rt.ByteSlice]; @@ -256,7 +257,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _30; } } else if (_9 === 3) { - const _48: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 4), { tag: "Short" } as DecodeError.DecodeError); + const _48: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 4), { tag: "Short" } as DecodeError.DecodeError); if (_48.ok) { const val3: [rt.ByteSlice, rt.ByteSlice] = _48.value; _8 = [(((val3[0].data[val3[0].start] & 15) << 24) | (val3[0].data[val3[0].start + 1] << 16) | (val3[0].data[val3[0].start + 2] << 8) | val3[0].data[val3[0].start + 3]) >>> 0 as rt.u64, val3[1]] as [rt.u64, rt.ByteSlice]; @@ -264,7 +265,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _48; } } else if (_9 === 4) { - const _65: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 5), { tag: "Short" } as DecodeError.DecodeError); + const _65: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 5), { tag: "Short" } as DecodeError.DecodeError); if (_65.ok) { const val4: [rt.ByteSlice, rt.ByteSlice] = _65.value; _8 = [fromHalves(((val4[0].data[val4[0].start] & 7)) as rt.u32, ((val4[0].data[val4[0].start + 1] << 24) | (val4[0].data[val4[0].start + 2] << 16) | (val4[0].data[val4[0].start + 3] << 8) | val4[0].data[val4[0].start + 4]) >>> 0), val4[1]] as [rt.u64, rt.ByteSlice]; @@ -272,7 +273,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _65; } } else if (_9 === 5) { - const _81: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 6), { tag: "Short" } as DecodeError.DecodeError); + const _81: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 6), { tag: "Short" } as DecodeError.DecodeError); if (_81.ok) { const val5: [rt.ByteSlice, rt.ByteSlice] = _81.value; _8 = [fromHalves(((val5[0].data[val5[0].start] & 3) << 8) | val5[0].data[val5[0].start + 1], ((val5[0].data[val5[0].start + 2] << 24) | (val5[0].data[val5[0].start + 3] << 16) | (val5[0].data[val5[0].start + 4] << 8) | val5[0].data[val5[0].start + 5]) >>> 0), val5[1]] as [rt.u64, rt.ByteSlice]; @@ -283,7 +284,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r if (!seven) { return rt.Err({ tag: "InvalidValue" } as DecodeError.DecodeError); } - const _101: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 7), { tag: "Short" } as DecodeError.DecodeError); + const _101: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 7), { tag: "Short" } as DecodeError.DecodeError); if (_101.ok) { const val6: [rt.ByteSlice, rt.ByteSlice] = _101.value; _8 = [fromHalves(((val6[0].data[val6[0].start] & 1) << 16) | (val6[0].data[val6[0].start + 1] << 8) | val6[0].data[val6[0].start + 2], ((val6[0].data[val6[0].start + 3] << 24) | (val6[0].data[val6[0].start + 4] << 16) | (val6[0].data[val6[0].start + 5] << 8) | val6[0].data[val6[0].start + 6]) >>> 0), val6[1]] as [rt.u64, rt.ByteSlice]; @@ -291,7 +292,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _101; } } else if (_9 === 7) { - const _121: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); + const _121: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 8), { tag: "Short" } as DecodeError.DecodeError); if (_121.ok) { const val7: [rt.ByteSlice, rt.ByteSlice] = _121.value; _8 = [fromHalves((val7[0].data[val7[0].start + 1] << 16) | (val7[0].data[val7[0].start + 2] << 8) | val7[0].data[val7[0].start + 3], ((val7[0].data[val7[0].start + 4] << 24) | (val7[0].data[val7[0].start + 5] << 16) | (val7[0].data[val7[0].start + 6] << 8) | val7[0].data[val7[0].start + 7]) >>> 0), val7[1]] as [rt.u64, rt.ByteSlice]; @@ -299,7 +300,7 @@ export function readLeadingOnes(buf: rt.ByteSlice, seven: boolean): rt.Result<[r return _121; } } else { - const _142: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = rt.optionOkOr(rt.byteSliceSplitFirstChunk(buf, 9), { tag: "Short" } as DecodeError.DecodeError); + const _142: rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> = okOr$Option_u8s_u8s_DecodeError(rt.byteSliceSplitFirstChunk(buf, 9), { tag: "Short" } as DecodeError.DecodeError); if (_142.ok) { const val8: [rt.ByteSlice, rt.ByteSlice] = _142.value; _8 = [fromHalves(((val8[0].data[val8[0].start + 1] << 24) | (val8[0].data[val8[0].start + 2] << 16) | (val8[0].data[val8[0].start + 3] << 8) | val8[0].data[val8[0].start + 4]) >>> 0, ((val8[0].data[val8[0].start + 5] << 24) | (val8[0].data[val8[0].start + 6] << 16) | (val8[0].data[val8[0].start + 7] << 8) | val8[0].data[val8[0].start + 8]) >>> 0), val8[1]] as [rt.u64, rt.ByteSlice]; diff --git a/ts/fixtures/codec/expected/core/option.ts b/ts/fixtures/codec/expected/core/option.ts new file mode 100644 index 000000000..d142187ab --- /dev/null +++ b/ts/fixtures/codec/expected/core/option.ts @@ -0,0 +1,42 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as DecodeError from "../coding/decode.DecodeError.ts"; +import type * as EncodeError from "../coding/encode.EncodeError.ts"; + +export function unwrapOr$Option_u32(self: rt.u32 | undefined, default_: rt.u32): rt.u32 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_u64(self: rt.u64 | undefined, default_: rt.u64): rt.u64 { + if (self === undefined) { + return default_; + } + return self; +} + +export function map$Option_u64_u64_encode_msg_closure0(self: rt.u64 | undefined, f: (a0: rt.u64) => rt.u64): rt.u64 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function okOr$Option_u64_EncodeError(self: rt.u64 | undefined, err: EncodeError.EncodeError): rt.Result { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +export function okOr$Option_u8s_u8s_DecodeError(self: [rt.ByteSlice, rt.ByteSlice] | undefined, err: DecodeError.DecodeError): rt.Result<[rt.ByteSlice, rt.ByteSlice], DecodeError.DecodeError> { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/codec/expected/core/result.ts b/ts/fixtures/codec/expected/core/result.ts new file mode 100644 index 000000000..ca607c936 --- /dev/null +++ b/ts/fixtures/codec/expected/core/result.ts @@ -0,0 +1,65 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import * as DecodeError from "../coding/decode.DecodeError.ts"; +import type * as EncodeError from "../coding/encode.EncodeError.ts"; +import type * as Group from "../lite/group.Group.ts"; +import type * as Probe from "../lite/probe.Probe.ts"; + +export function mapErr$Result_Group_DecodeError_DecodeError_complete(self: rt.Result, _: (a0: DecodeError.DecodeError) => DecodeError.DecodeError): rt.Result { + if (self.ok) { + return self; + } + return rt.Err(DecodeError.complete(self.error)); +} + +export function mapErr$Result_Probe_DecodeError_DecodeError_complete(self: rt.Result, _: (a0: DecodeError.DecodeError) => DecodeError.DecodeError): rt.Result { + if (self.ok) { + return self; + } + return rt.Err(DecodeError.complete(self.error)); +} + +export function mapErr$Result_u16_TryFromIntError_EncodeError_fill_closure0(self: rt.Result, op: (a0: rt.TryFromIntError) => EncodeError.EncodeError): rt.Result { + if (self.ok) { + return self as rt.Result; + } + return rt.Err(op(self.error)); +} + +export function mapErr$Result_usize_TryFromIntError_DecodeError_bytes_closure0(self: rt.Result, op: (a0: rt.TryFromIntError) => DecodeError.DecodeError): rt.Result { + if (self.ok) { + return self as rt.Result; + } + return rt.Err(op(self.error)); +} + +export function inspectErr$Result_u8s_DecodeError_bytes_closure1(self: rt.Result, f: (a0: DecodeError.DecodeError) => void): rt.Result { + if (!self.ok) { + f(self.error); + } + return self; +} + +export function andThen$Result_Group_DecodeError_Group_decode_with_closure0(self: rt.Result, op: (a0: Group.Group) => rt.Result): rt.Result { + if (self.ok) { + return op(self.value); + } + return self; +} + +export function andThen$Result_Probe_DecodeError_Probe_decode_with_closure0(self: rt.Result, op: (a0: Probe.Probe) => rt.Result): rt.Result { + if (self.ok) { + return op(self.value); + } + return self; +} + +export function unwrapOr$Result_usize_TryFromIntError(self: rt.Result, default_: rt.usize): rt.usize { + if (self.ok) { + return self.value; + } + return default_; +} + +//# sourceMappingURL=result.ts.map diff --git a/ts/fixtures/codec/expected/lite/message.ts b/ts/fixtures/codec/expected/lite/message.ts index 69b00de5c..624e59dc3 100644 --- a/ts/fixtures/codec/expected/lite/message.ts +++ b/ts/fixtures/codec/expected/lite/message.ts @@ -3,6 +3,7 @@ import * as rt from "../rt.ts"; import * as DecodeError from "../coding/decode.DecodeError.ts"; import * as Decoder from "../coding/decode.Decoder.ts"; +import { mapErr$Result_Group_DecodeError_DecodeError_complete, mapErr$Result_Probe_DecodeError_DecodeError_complete, andThen$Result_Group_DecodeError_Group_decode_with_closure0, andThen$Result_Probe_DecodeError_Probe_decode_with_closure0, unwrapOr$Result_usize_TryFromIntError } from "../core/result.ts"; import type * as Group from "../lite/group.Group.ts"; import type * as Probe from "../lite/probe.Probe.ts"; import type * as Control from "../stats.Control.ts"; @@ -15,10 +16,10 @@ export function decodeSize(r: Decoder.Decoder, max: rt.usize): rt.Result = rt.usizeTryFrom(size); if (_8.ok) { if (_8.value <= max) { - return rt.Ok(_8.value); + return _8 as rt.Result; } } - return rt.Err({ tag: "MessageTooLarge", size: rt.resultUnwrapOr(rt.usizeTryFrom(size), 4294967295), max } as DecodeError.DecodeError); + return rt.Err({ tag: "MessageTooLarge", size: unwrapOr$Result_usize_TryFromIntError(rt.usizeTryFrom(size), 4294967295), max } as DecodeError.DecodeError); } return _3; } @@ -33,7 +34,7 @@ export function decodeWith$Group_decode_closure0(r: Decoder.Decoder, decode: (a0 const _9: rt.Result = Decoder.sub(r, _3.value); if (_9.ok) { const body: Decoder.Decoder = _9.value; - const result: rt.Result = rt.resultAndThen(rt.resultMapErr(decode(body), DecodeError.complete), (msg: Group.Group): rt.Result => { + const result: rt.Result = andThen$Result_Group_DecodeError_Group_decode_with_closure0(mapErr$Result_Group_DecodeError_DecodeError_complete(decode(body), DecodeError.complete), (msg: Group.Group): rt.Result => { if (!Decoder.isEmpty(body)) { return rt.Err({ tag: "Long" } as DecodeError.DecodeError); } @@ -59,7 +60,7 @@ export function decodeWith$Probe_decode_closure0(r: Decoder.Decoder, decode: (a0 const _9: rt.Result = Decoder.sub(r, _3.value); if (_9.ok) { const body: Decoder.Decoder = _9.value; - const result: rt.Result = rt.resultAndThen(rt.resultMapErr(decode(body), DecodeError.complete), (msg: Probe.Probe): rt.Result => { + const result: rt.Result = andThen$Result_Probe_DecodeError_Probe_decode_with_closure0(mapErr$Result_Probe_DecodeError_DecodeError_complete(decode(body), DecodeError.complete), (msg: Probe.Probe): rt.Result => { if (!Decoder.isEmpty(body)) { return rt.Err({ tag: "Long" } as DecodeError.DecodeError); } diff --git a/ts/fixtures/codec/expected/lite/probe.Probe.ts b/ts/fixtures/codec/expected/lite/probe.Probe.ts index 20ff188df..ad182b2d3 100644 --- a/ts/fixtures/codec/expected/lite/probe.Probe.ts +++ b/ts/fixtures/codec/expected/lite/probe.Probe.ts @@ -7,6 +7,7 @@ import type * as EncodeError from "../coding/encode.EncodeError.ts"; import * as Encoder from "../coding/encode.Encoder.ts"; import type * as Prefix from "../coding/encode.Prefix.ts"; import * as Form from "../coding/varint.Form.ts"; +import { unwrapOr$Option_u64, map$Option_u64_u64_encode_msg_closure0 } from "../core/option.ts"; import { decodeWith$Probe_decode_closure0 } from "../lite/message.ts"; import * as Version from "../lite/version.Version.ts"; import type * as Control from "../stats.Control.ts"; @@ -98,12 +99,12 @@ export function encodeMsg$Message(self: Probe, w: Encoder.Encoder, version: Vers if (version === "Lite01" || version === "Lite02") { return rt.Err("Version" as EncodeError.EncodeError); } - const _9: rt.Result = Encoder.varint(w, rt.optionUnwrapOr(rt.optionMap(self.bitrate, (v: rt.u64): rt.u64 => { + const _9: rt.Result = Encoder.varint(w, unwrapOr$Option_u64(map$Option_u64_u64_encode_msg_closure0(self.bitrate, (v: rt.u64): rt.u64 => { return rt.u64Max(v, 1); }), 0)); if (_9.ok) { if (Version.hasProbeRtt(version)) { - const _17: rt.Result = Encoder.varint(w, rt.optionUnwrapOr(rt.optionMap(self.rtt, (v2: rt.u64): rt.u64 => { + const _17: rt.Result = Encoder.varint(w, unwrapOr$Option_u64(map$Option_u64_u64_encode_msg_closure0(self.rtt, (v2: rt.u64): rt.u64 => { return rt.u64Max(v2, 1); }), 0)); if (!_17.ok) { diff --git a/ts/fixtures/lang/expected/chars.ts b/ts/fixtures/lang/expected/chars.ts index e3b88c382..52f986a5e 100644 --- a/ts/fixtures/lang/expected/chars.ts +++ b/ts/fixtures/lang/expected/chars.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_char } from "./core/option.ts"; import { put } from "./fmt.ts"; /** The scalars to try: the edges, then each big-endian `u32` in `data`, zero-padded. */ @@ -79,7 +80,7 @@ export function chars(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } } else if (_4 === 1) { for (const n2 of scalars(data)) { - const c2: rt.char = rt.optionUnwrapOr(rt.charFromU32(n2), (n2 & 0xff) as rt.char); + const c2: rt.char = unwrapOr$Option_char(rt.charFromU32(n2), (n2 & 0xff) as rt.char); rt.byteVecPush(out, c2 & 0xff); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(c2 & 0xffff))); rt.byteVecPush(out, ((c2 << 24) >> 24) & 0xff); diff --git a/ts/fixtures/lang/expected/chunks.ts b/ts/fixtures/lang/expected/chunks.ts index b97338907..6b066dd30 100644 --- a/ts/fixtures/lang/expected/chunks.ts +++ b/ts/fixtures/lang/expected/chunks.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import type * as Header from "./chunks.Header.ts"; +import { mapOr$Option_u8s_u8s_u8s_chunks_closure0, okOr$Option_u8s_u8s_u8 } from "./core/option.ts"; export function header(data: rt.ByteSlice): Header.Header | undefined { const _4: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitFirstChunk(data, 2); @@ -13,7 +14,7 @@ export function header(data: rt.ByteSlice): Header.Header | undefined { } export function take4(data: rt.ByteSlice): rt.Result<[rt.ByteSlice, rt.ByteSlice], rt.u8> { - return rt.optionOkOr(rt.byteSliceSplitFirstChunk(data, 4), data.length & 0xff); + return okOr$Option_u8s_u8s_u8(rt.byteSliceSplitFirstChunk(data, 4), data.length & 0xff); } export function word(chunk: rt.ByteSlice): rt.u32 { @@ -101,7 +102,7 @@ export function chunks(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } else if (_4 === 2) { const _101: [rt.ByteSlice, rt.ByteSlice] | undefined = rt.byteSliceSplitFirstChunk(data, 2); if (_101 !== undefined) { - const b: rt.ByteSlice = rt.optionMapOr(rt.byteSliceSplitFirstChunk(_101[1], 2), _101[0], (_22: [rt.ByteSlice, rt.ByteSlice]): rt.ByteSlice => { + const b: rt.ByteSlice = mapOr$Option_u8s_u8s_u8s_chunks_closure0(rt.byteSliceSplitFirstChunk(_101[1], 2), _101[0], (_22: [rt.ByteSlice, rt.ByteSlice]): rt.ByteSlice => { return _22[0]; }); const part2 = _101[0]; diff --git a/ts/fixtures/lang/expected/collections.ts b/ts/fixtures/lang/expected/collections.ts index 513fbc583..e99447aed 100644 --- a/ts/fixtures/lang/expected/collections.ts +++ b/ts/fixtures/lang/expected/collections.ts @@ -11,6 +11,7 @@ import * as Nibble from "./collections.Nibble.ts"; import * as Pair from "./collections.Pair.ts"; import * as Rank from "./collections.Rank.ts"; import * as Tally from "./collections.Tally.ts"; +import { unwrapOr$Option_u16, unwrapOr$Option_u8, mapOr$Option_Nibble_u8_sets_closure4, mapOr$Option_Rank_Tally_u8_hash_maps_closure11, mapOr$Option_Tally_u8_hash_maps_closure10, mapOr$Option_u16_u8_hash_maps_closure0, mapOr$Option_u8_u8_u8_btree_maps_closure0, mapOr$Option_u8_u8_u8s_stores_closure2_closure0 } from "./core/option.ts"; import * as Bumped from "./iters.Bumped.ts"; /** A 64-bit key: small, or past 2^53, where it is no longer a JS number. */ @@ -68,22 +69,22 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void } const i: rt.usize = _13; rt.idx(data, i); - const _19: [rt.u8, rt.u16] = [rt.u8Rem(data.data[data.start + i], 16), rt.optionUnwrapOr(rt.byteSliceGet(data, rt.usizeAdd(i, 1)), 0) as rt.u16]; + const _19: [rt.u8, rt.u16] = [rt.u8Rem(data.data[data.start + i], 16), unwrapOr$Option_u8(rt.byteSliceGet(data, rt.usizeAdd(i, 1)), 0) as rt.u16]; const k: rt.u8 = _19[0]; const v: rt.u16 = _19[1]; const _31: rt.u16 = rt.u16Rem(v, 5); if (_31 === 0) { - rt.byteVecPush(out, rt.optionMapOr(rt.hashRemove(map, k), 238, (old2: rt.u16): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u16_u8_hash_maps_closure0(rt.hashRemove(map, k), 238, (old2: rt.u16): rt.u8 => { return old2 & 0xff; })); } else if (_31 === 1) { rt.byteVecPush(out, rt.hashContains(map, k) ? 1 : 0); } else if (_31 === 2) { - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(map, k), 221, (v4: rt.u16): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u16_u8_hash_maps_closure0(rt.hashGet(map, k), 221, (v4: rt.u16): rt.u8 => { return v4 & 0xff; })); } else { - rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(map, k, rt.u16Mul(v, 3)), 204, (old: rt.u16): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u16_u8_hash_maps_closure0(rt.hashInsert(map, k, rt.u16Mul(v, 3)), 204, (old: rt.u16): rt.u8 => { return old & 0xff; })); } @@ -123,11 +124,11 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const k2: rt.u64 = wide(rt.u8Rem(b, 12)); const _118: rt.u8 = rt.u8Rem(rt.u8Div(b, 12), 4); if (_118 === 0) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashRemove(map2, k2), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashRemove(map2, k2), 238)); } else if (_118 === 1) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashGet(map2, k2), 221)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashGet(map2, k2), 221)); } else { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(map2, k2, i2 & 0xff), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashInsert(map2, k2, i2 & 0xff), 204)); } } const _136: rt.Iter = rt.hashKeys(map2); @@ -161,7 +162,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const _180: [rt.u8, rt.u8] = [_181, data.data[data.start + i3]]; const a: rt.u8 = _181; const b3: rt.u8 = _180[1]; - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(map3, { _0: a }, b3), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashInsert(map3, { _0: a }, b3), 204)); const pair: Pair.Pair = { a: rt.u8Rem(a, 4), b: rt.u16Rem(b3 as rt.u16, 3) }; const t: Tally.Tally = rt.entryOrInsertWith(rt.entry(pairs, pair), Tally.default$Default); t.n = rt.u16Add(t.n, 1); @@ -178,7 +179,7 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _220); } const t2: [rt.u8, string] = [_216, ["", "a", "ab", "b", "é", "", "￿", "𐀀"][_220]]; - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashRemove(tuples, t2), 187)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashRemove(tuples, t2), 187)); if (rt.u8Rem(a, 2) === 0) { rt.hashInsert(tuples, copy$u8_str(t2), a); } @@ -253,13 +254,13 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void if (_340 !== undefined) { _340.n = 119; } - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(ranks, { tag: "Low" } as Rank.Rank), 255, (t10: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(ranks, { tag: "Low" } as Rank.Rank), 255, (t10: Tally.Tally): rt.u8 => { return t10.n & 0xff; })); - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(copy, { tag: "Low" } as Rank.Rank), 255, (t11: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(copy, { tag: "Low" } as Rank.Rank), 255, (t11: Tally.Tally): rt.u8 => { return t11.n & 0xff; })); - rt.byteVecPush(out, rt.optionMapOr(rt.hashRemoveEntry(copy, { tag: "Mid", _0: 1 } as Rank.Rank), 255, (_218: [Rank.Rank, Tally.Tally]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Rank_Tally_u8_hash_maps_closure11(rt.hashRemoveEntry(copy, { tag: "Mid", _0: 1 } as Rank.Rank), 255, (_218: [Rank.Rank, Tally.Tally]): rt.u8 => { const k10: Rank.Rank = _218[0]; const t12: Tally.Tally = _218[1]; return rankByte(k10) ^ (t12.n & 0xff); @@ -282,10 +283,10 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const iterEnd3: rt.u8 = 8; while ((_377 = iterStart3++) < iterEnd3) { const k4: rt.u8 = _377; - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(bytes, k4), 255, (t13: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(bytes, k4), 255, (t13: Tally.Tally): rt.u8 => { return t13.n & 0xff; })); - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(copy2, k4), 255, (t14: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(copy2, k4), 255, (t14: Tally.Tally): rt.u8 => { return t14.n & 0xff; })); } @@ -310,14 +311,14 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const iterEnd4: rt.u8 = 8; while ((_429 = iterStart4++) < iterEnd4) { const k5: rt.u8 = _429; - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(bytes, k5), 255, (t15: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(bytes, k5), 255, (t15: Tally.Tally): rt.u8 => { return t15.n & 0xff; })); - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(extended, k5), 255, (t16: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(extended, k5), 255, (t16: Tally.Tally): rt.u8 => { return t16.n & 0xff; })); } - const first: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); + const first: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); rt.byteVecPush(out, rt.u64Eq(_443({ _0: first }), _443({ _0: first ^ 240 })) ? 1 : 0); const _461: [rt.Hasher, Tally.Tally] = [rt.hasher(), { n: first as rt.u16 }]; const h: rt.Hasher = _461[0]; @@ -391,15 +392,15 @@ export function hashMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void const k6: Clash.Clash = { _0: rt.u8Rem(b7, 8) }; const _576: rt.u8 = rt.u8Rem(rt.u8Div(b7, 8), 4); if (_576 === 0) { - rt.byteVecPush(out, rt.optionMapOr(rt.hashRemove(clashes, k6), 238, (t7: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashRemove(clashes, k6), 238, (t7: Tally.Tally): rt.u8 => { return t7.n & 0xff; })); } else if (_576 === 1) { - rt.byteVecPush(out, rt.optionMapOr(rt.hashGet(clashes, k6), 221, (t6: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashGet(clashes, k6), 221, (t6: Tally.Tally): rt.u8 => { return t6.n & 0xff; })); } else { - rt.byteVecPush(out, rt.optionMapOr(rt.hashInsert(clashes, k6, { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Tally_u8_hash_maps_closure10(rt.hashInsert(clashes, k6, { n: i5 & 0xffff }), 204, (t5: Tally.Tally): rt.u8 => { return t5.n & 0xff; })); } @@ -481,8 +482,8 @@ export function sets(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, _62 & 0xff); } - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeFirstKey(sorted), 255) & 0xff); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeFirstKey(sorted, true), 255) & 0xff); + rt.byteVecPush(out, unwrapOr$Option_u16(rt.btreeFirstKey(sorted), 255) & 0xff); + rt.byteVecPush(out, unwrapOr$Option_u16(rt.btreeFirstKey(sorted, true), 255) & 0xff); rt.byteVecPush(out, rt.iterToArray(rt.btreeRangeKeys(sorted, new rt.Range(4, 12))).length & 0xff); rt.hashRetain(hashed, (v3: rt.u16): boolean => { return rt.u16Rem(v3, 3) !== 0; @@ -514,7 +515,7 @@ export function sets(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { if (_129 !== undefined) { rt.byteVecPush(out, _129._0); if (rt.usizeRem(rt.btreeLen(nibbles), 2) === 0) { - rt.byteVecPush(out, rt.optionMapOr(rt.btreePopKey(nibbles), 238, (n2: Nibble.Nibble): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Nibble_u8_sets_closure4(rt.btreePopKey(nibbles), 238, (n2: Nibble.Nibble): rt.u8 => { return n2._0; })); } @@ -581,18 +582,18 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi } const i: rt.usize = _13; rt.idx(data, i); - const _19: [rt.u8, rt.u8] = [rt.u8Rem(data.data[data.start + i], 32), rt.optionUnwrapOr(rt.byteSliceGet(data, rt.usizeAdd(i, 1)), 0)]; + const _19: [rt.u8, rt.u8] = [rt.u8Rem(data.data[data.start + i], 32), unwrapOr$Option_u8(rt.byteSliceGet(data, rt.usizeAdd(i, 1)), 0)]; const k: rt.u8 = _19[0]; const v: rt.u8 = _19[1]; const _30: rt.u8 = rt.u8Rem(v, 6); if (_30 === 0) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeRemove(map, k), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeRemove(map, k), 238)); } else if (_30 === 1) { - rt.byteVecPush(out, rt.optionMapOr(rt.btreePop(map), 221, (_219: [rt.u8, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(rt.btreePop(map), 221, (_219: [rt.u8, rt.u8]): rt.u8 => { return _219[0] ^ _219[1]; })); } else if (_30 === 2) { - rt.byteVecPush(out, rt.optionMapOr(rt.btreePop(map, true), 220, (_216: [rt.u8, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(rt.btreePop(map, true), 220, (_216: [rt.u8, rt.u8]): rt.u8 => { return _216[0] ^ _216[1]; })); } else if (_30 === 3) { @@ -601,15 +602,15 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi const _50: rt.u8 = rt.u8WrappingAdd(_42, 1); rt.btreeInsert(map, k, _50); } - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeGet(map, k), 219)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeGet(map, k), 219)); } else { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(map, k, v), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeInsert(map, k, v), 204)); } } - rt.byteVecPush(out, rt.optionMapOr(rt.btreeFirst(map), 255, (_223: [rt.u8, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(rt.btreeFirst(map), 255, (_223: [rt.u8, rt.u8]): rt.u8 => { return _223[0]; })); - rt.byteVecPush(out, rt.optionMapOr(rt.btreeFirst(map, true), 255, (_224: [rt.u8, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(rt.btreeFirst(map, true), 255, (_224: [rt.u8, rt.u8]): rt.u8 => { return _224[0]; })); const iter2: rt.Iter<[rt.u8, rt.u8]> = rt.btreeRange(map, new rt.Range(8, 24)); @@ -644,8 +645,8 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi rt.btreeRemove(map, 3); rt.byteVecPush(out, rt.btreeLen(map) & 0xff); rt.byteVecPush(out, rt.btreeContains(map, 3) ? 1 : 0); - const lo: rt.u8 = rt.u8Rem(rt.optionUnwrapOr(rt.byteSliceFirst(data), 0), 32); - const hi: rt.u8 = rt.u8Rem(rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0), 32); + const lo: rt.u8 = rt.u8Rem(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0), 32); + const hi: rt.u8 = rt.u8Rem(unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0), 32); const _137: rt.u8 = rt.u8Rem(lo, 3); if (_137 === 0) { within = rt.iterToByteVec(rt.iterMap(rt.btreeRange(map, new rt.Range(lo, hi)), (_238: [rt.u8, rt.u8]): rt.u8 => { @@ -748,7 +749,7 @@ export function btreeMaps(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi const nibbles: rt.BTreeMap = rt.btreeNew(Nibble.cmp$Ord) as rt.BTreeMap; const words: rt.BTreeMap = rt.btreeNew(rt.cmpStr) as rt.BTreeMap; for (const b3 of rt.byteSliceView(data)) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(nibbles, { _0: b3 }, b3), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeInsert(nibbles, { _0: b3 }, b3), 204)); const _320: rt.usize = rt.usizeRem(b3 as rt.usize, ["", "a", "ab", "b", "é", "", "￿", "𐀀"].length); if (!(_320 < 8)) { rt.panic("index out of bounds: the len is " + 8 + " but the index is " + _320); @@ -852,15 +853,15 @@ export function deques(data: rt.ByteSlice, out: rt.ByteVec): void { for (const b of rt.byteSliceView(data)) { const _12: rt.u8 = rt.u8Rem(b, 7); if (_12 === 0) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequePopFront(q), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequePopFront(q), 238)); } else if (_12 === 1) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequePopBack(q), 237)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequePopBack(q), 237)); } else if (_12 === 2) { rt.dequePushFront(q, b); } else if (_12 === 3) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeEnd(q), 236)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeEnd(q, true), 235)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeGet(q, rt.usizeRem(b as rt.usize, 5)), 234)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequeEnd(q), 236)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequeEnd(q, true), 235)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequeGet(q, rt.usizeRem(b as rt.usize, 5)), 234)); } else { rt.dequePushBack(q, b); } @@ -921,12 +922,12 @@ export function deques(data: rt.ByteSlice, out: rt.ByteVec): void { const _135: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); rt.dequeExtend(q, _135); rt.dequeInsert(q, rt.usizeDiv(q.n, 2), 66); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.dequeRemove(q, 1), 233)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.dequeRemove(q, 1), 233)); rt.dequeTruncate(q, 5); rt.byteVecPush(out, rt.dequeContains(q, 66, rt.same) ? 1 : 0); rt.iterExtendBytes(out, rt.iterRev(rt.dequeIter(q))); - const a: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.byteSliceFirst(data), 0) as rt.usize, 8); - const b2: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0) as rt.usize, 8); + const a: rt.usize = rt.usizeRem(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0) as rt.usize, 8); + const b2: rt.usize = rt.usizeRem(unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0) as rt.usize, 8); const _171: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); const q2: rt.VecDeque = rt.dequeExtend(rt.dequeNew() as rt.VecDeque, _171); const _174: rt.usize = rt.usizeRem(a, 4); @@ -948,9 +949,9 @@ export function deques(data: rt.ByteSlice, out: rt.ByteVec): void { /** `vec![a, b]` and `vec![x; n]`, of bytes, numbers, `Copy` tuples, and types that clone. */ export function vecs(data: rt.ByteSlice, out: rt.ByteVec): void { let name!: string; - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); - const b: rt.u8 = rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0); - const n: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.byteSliceGet(data, 2), 0) as rt.usize, 5); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); + const b: rt.u8 = unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0); + const n: rt.usize = rt.usizeRem(unwrapOr$Option_u8(rt.byteSliceGet(data, 2), 0) as rt.usize, 5); const _16: rt.Result = rt.stringFromUtf8(rt.byteSliceToByteVec(data)); if (_16.ok) { name = _16.value; @@ -1040,8 +1041,8 @@ export function hold(pair: [rt.u8, rt.u8]): Holder.Holder { * one stored element leaves the value it came from and the other elements as they were. */ export function stores(data: rt.ByteSlice, out: rt.ByteVec): void { - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); - const b: rt.u8 = rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); + const b: rt.u8 = unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0); const pair: [rt.u8, rt.u8] = same([a, b] as [rt.u8, rt.u8]); const changed: [rt.u8, rt.u8] = [b, a]; changed[0] = changed[0] ^ 16; @@ -1104,7 +1105,7 @@ export function stores(data: rt.ByteSlice, out: rt.ByteVec): void { const place = rt.entryOrInsertMut(rt.entry(hash, 2), copy$u8_u8(pair)); place.v[1] = place.v[1] ^ 2; rt.iterExtendBytes(out, rt.iterFlatMap(new rt.Range(0, 3), (k: rt.u8): Uint8Array => { - return rt.optionMapOr(rt.hashGet(hash, k), rt.bytes(2).fill(255), (p2: [rt.u8, rt.u8]): Uint8Array => { + return mapOr$Option_u8_u8_u8s_stores_closure2_closure0(rt.hashGet(hash, k), rt.bytes(2).fill(255), (p2: [rt.u8, rt.u8]): Uint8Array => { return Uint8Array.of(p2[0], p2[1]); }); }, (value: Uint8Array) => rt.iterSlice(value))); diff --git a/ts/fixtures/lang/expected/combinators.ts b/ts/fixtures/lang/expected/combinators.ts new file mode 100644 index 000000000..e2f5a3d05 --- /dev/null +++ b/ts/fixtures/lang/expected/combinators.ts @@ -0,0 +1,246 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$Result_u32s_u16, copy$u32s } from "./lib.ts"; +import { isSomeAnd$Option_u8_options_closure0, isNoneOr$Option_u8_options_closure1, unwrapOr$Option_u8, unwrapOrElse$Option_String_owned_closure3, unwrapOrElse$Option_u8_options_closure9, unwrapOrDefault$Option_String, unwrapOrDefault$Option_Vec_u8, unwrapOrDefault$Option_u8, map$Option_u8_String_owned_closure0, map$Option_u8_Vec_u8_owned_closure4, map$Option_u8_u32s_owned_closure9, map$Option_u8_u8_options_closure3_closure0, inspect$Option_u8_options_closure11, mapOr$Option_u16_u8_hash_maps_closure0, mapOr$Option_u8_u8_options_closure5, mapOr$Option_u8_u8_u8_btree_maps_closure0, mapOrElse$Option_u8_u8_options_closure7_options_closure8, okOr$Option_u32s_u8, okOr$Option_u8_u16, okOr$Option_u8_u8, okOrElse$Option_Vec_u8_String_owned_closure5, okOrElse$Option_u8_u16_options_closure12, and$Option_u8_u8, andThen$Option_u8_u8_options_closure2, filter$Option_String_owned_closure1, filter$Option_u8_combinators_closure0, or$Option_u8, orElse$Option_String_owned_closure2, orElse$Option_u8_options_closure6, xor$Option_u8, zip$Option_u8_u8, clone$Clone_Option_String } from "./core/option.ts"; +import { isOkAnd$Result_u8_u16_results_closure5, isErrAnd$Result_u8_u16_results_closure6, ok$Result_u8_u16, err$Result_u8_u16, asRef$Result_u8_u16, map$Result_Vec_u8_String_Vec_u8_owned_closure6, map$Result_u8_u16_u8_options_closure13, mapOr$Result_u8_u16_u8_results_closure7, mapOrElse$Result_u8_u16_u8_results_closure8_results_closure9, mapErr$Result_u32s_u8_u16_from, mapErr$Result_u8_u16_u16_results_closure14, inspect$Result_u8_u16_results_closure12, inspectErr$Result_u8_u16_results_closure13, unwrapOrDefault$Result_u8_u16, and$Result_u8_u16_u8, andThen$Result_u8_u16_u8_results_closure3, or$Result_u8_u16_u16, orElse$Result_u8_u16_u16_results_closure4, unwrapOr$Result_u8_u16, unwrapOrElse$Result_u8_u16_results_closure11, unwrapOrElse$Result_u8_u8_panics_closure1, copied$Result_u8_u16, clone$Clone_Result_Vec_u8_String } 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 { + const a: rt.u8 | undefined = filter$Option_u8_combinators_closure0(rt.byteSliceFirst(data), (x: rt.u8): boolean => { + return rt.u8Rem(x, 3) !== 0; + }); + const b: rt.u8 | undefined = filter$Option_u8_combinators_closure0(rt.byteSliceGet(data, 1), (x2: rt.u8): boolean => { + return rt.u8Rem(x2, 5) !== 0; + }); + const limit: rt.u8 = unwrapOr$Option_u8(rt.byteSliceGet(data, 2), 128); + const _13: rt.u8 = rt.u8Rem(kind, 4); + if (_13 === 0) { + options(a, b, limit, out); + } else if (_13 === 1) { + results(a, b, limit, out); + } else if (_13 === 2) { + owned(a, b, out); + } else { + panics(a, b, limit, out); + } +} + +export function options(a: rt.u8 | undefined, b: rt.u8 | undefined, limit: rt.u8, out: rt.ByteVec): void { + rt.byteVecPush(out, isSomeAnd$Option_u8_options_closure0(a, (x: rt.u8): boolean => { + rt.byteVecPush(out, 160); + return x > limit; + }) ? 1 : 0); + rt.byteVecPush(out, isNoneOr$Option_u8_options_closure1(b, (x2: rt.u8): boolean => { + rt.byteVecPush(out, 161); + return x2 < limit; + }) ? 1 : 0); + rt.byteVecPush(out, unwrapOr$Option_u8(andThen$Option_u8_u8_options_closure2(andThen$Option_u8_u8_options_closure2(a, (x3: rt.u8): rt.u8 | undefined => { + return rt.u8CheckedAdd(x3, limit); + }), (x4: rt.u8): rt.u8 | undefined => { + rt.byteVecPush(out, 162); + return map$Option_u8_u8_options_closure3_closure0(b, (y: rt.u8): rt.u8 => { + return x4 ^ y; + }); + }), 238)); + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(filter$Option_u8_combinators_closure0(a, (x5: rt.u8): boolean => { + rt.byteVecPush(out, 163); + return x5 > limit; + }), 221, (x6: rt.u8): rt.u8 => { + return rt.u8Div(x6, 3); + })); + rt.byteVecPush(out, mapOrElse$Option_u8_u8_options_closure7_options_closure8(orElse$Option_u8_options_closure6(a, (): rt.u8 | undefined => { + rt.byteVecPush(out, 164); + return b; + }), (): rt.u8 => { + rt.byteVecPush(out, 165); + return 204; + }, (x7: rt.u8): rt.u8 => { + return rt.u8WrappingAdd(x7, 3); + })); + rt.byteVecPush(out, unwrapOrDefault$Option_u8(xor$Option_u8(a, b))); + rt.byteVecPush(out, unwrapOrElse$Option_u8_options_closure9(and$Option_u8_u8(a, b), (): rt.u8 => { + rt.byteVecPush(out, 166); + return 187; + })); + rt.byteVecPush(out, unwrapOr$Option_u8(or$Option_u8(a, b), 170)); + rt.byteVecPush(out, mapOr$Option_u8_u8_u8_btree_maps_closure0(zip$Option_u8_u8(a, b), 0, (_2: [rt.u8, rt.u8]): rt.u8 => { + return rt.u8WrappingAdd(_2[0], _2[1]); + })); + rt.byteVecPush(out, inspect$Option_u8_options_closure11(a, (x9: rt.u8): void => { + rt.byteVecPush(out, x9); + }) !== undefined ? 1 : 0); + push(map$Result_u8_u16_u8_options_closure13(okOrElse$Option_u8_u16_options_closure12(b, (): rt.u16 => { + rt.byteVecPush(out, 167); + return (((limit as rt.u16)) << 1) & 0xffff; + }), (x10: rt.u8): rt.u8 => { + return x10 ^ limit; + }), out); +} + +export function results(a: rt.u8 | undefined, b: rt.u8 | undefined, limit: rt.u8, out: rt.ByteVec): void { + const r: rt.Result = okOr$Option_u8_u16(a, rt.u16Mul(limit as rt.u16, 3)); + const s: rt.Result = okOrElse$Option_u8_u16_options_closure12(b, (): rt.u16 => { + return 511; + }); + push(mapErr$Result_u8_u16_u16_results_closure14(map$Result_u8_u16_u8_options_closure13(r, (x: rt.u8): rt.u8 => { + rt.byteVecPush(out, 177); + return rt.u8WrappingAdd(x, limit); + }), (e: rt.u16): rt.u16 => { + rt.byteVecPush(out, 178); + return rt.u16WrappingAdd(e, 1); + }), out); + push(orElse$Result_u8_u16_u16_results_closure4(andThen$Result_u8_u16_u8_results_closure3(r, (x2: rt.u8): rt.Result => { + return okOr$Option_u8_u16(rt.u8CheckedMul(x2, limit), 7); + }), (e2: rt.u16): rt.Result => { + rt.byteVecPush(out, 179); + if (rt.u16Rem(e2, 2) === 0) { + return rt.Ok(1); + } + return rt.Err(e2); + }), out); + rt.byteVecPush(out, isOkAnd$Result_u8_u16_results_closure5(r, (v: rt.u8): boolean => { + return v > 3; + }) ? 1 : 0); + rt.byteVecPush(out, isErrAnd$Result_u8_u16_results_closure6(s, (e3: rt.u16): boolean => { + rt.byteVecPush(out, 180); + return e3 > 256; + }) ? 1 : 0); + rt.byteVecPush(out, mapOr$Result_u8_u16_u8_results_closure7(r, 17, (v2: rt.u8): rt.u8 => { + return rt.u8Div(v2, 2); + })); + rt.byteVecPush(out, mapOrElse$Result_u8_u16_u8_results_closure8_results_closure9(s, (e4: rt.u16): rt.u8 => { + return e4 & 0xff; + }, (v3: rt.u8): rt.u8 => { + return v3 ^ 85; + })); + rt.byteVecPush(out, unwrapOr$Option_u8(ok$Result_u8_u16(r), 0)); + rt.byteVecPush(out, mapOr$Option_u16_u8_hash_maps_closure0(err$Result_u8_u16(s), 0, (e5: rt.u16): rt.u8 => { + return (e5 >> 8) & 0xff; + })); + rt.byteVecPush(out, unwrapOrDefault$Result_u8_u16(and$Result_u8_u16_u8(r, s))); + rt.byteVecPush(out, unwrapOrElse$Result_u8_u16_results_closure11(or$Result_u8_u16_u16(r, s), (e6: rt.u16): rt.u8 => { + return e6 & 0xff; + })); + rt.byteVecPush(out, inspectErr$Result_u8_u16_results_closure13(inspect$Result_u8_u16_results_closure12(s, (v4: rt.u8): void => { + rt.byteVecPush(out, v4); + }), (e7: rt.u16): void => { + rt.byteVecPush(out, e7 & 0xff); + }).ok ? 1 : 0); + rt.byteVecPush(out, unwrapOr$Result_u8_u16(copied$Result_u8_u16(mapErr$Result_u8_u16_u16_results_closure14(asRef$Result_u8_u16(r), (e8: rt.u16): rt.u16 => { + return e8; + })), 34)); +} + +/** Values JS shares where Rust clones or moves them. */ +export function owned(a: rt.u8 | undefined, b: rt.u8 | undefined, out: rt.ByteVec): void { + let matched!: rt.Result; + const s: string | undefined = map$Option_u8_String_owned_closure0(a, (x2: rt.u8): string => { + return rt.fmtToString((f: rt.Formatter) => rt.u8Display(x2, f)); + }); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(unwrapOrDefault$Option_String(filter$Option_String_owned_closure1(clone$Clone_Option_String(s), (s2: string): boolean => { + return rt.stringLen(s2) > 1; + })))); + rt.byteVecPush(out, 124); + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(unwrapOrElse$Option_String_owned_closure3(orElse$Option_String_owned_closure2(s, (): string | undefined => { + return map$Option_u8_String_owned_closure0(b, (y2: rt.u8): string => { + return rt.fmtToString((f: rt.Formatter) => rt.u8Display(y2, f)); + }); + }), (): string => { + return "-"; + }))); + rt.byteVecPush(out, 124); + const v: rt.Result = okOrElse$Option_Vec_u8_String_owned_closure5(map$Option_u8_Vec_u8_owned_closure4(a, (x3: rt.u8): rt.ByteVec => { + return rt.byteVecOf(x3, 2); + }), (): string => { + return "none"; + }); + const copy: rt.Result = clone$Clone_Result_Vec_u8_String(v); + if (copy.ok) { + rt.byteVecPush(copy.value, 7); + } + const grown: rt.Result = map$Result_Vec_u8_String_Vec_u8_owned_closure6(clone$Clone_Result_Vec_u8_String(v), (v3: rt.ByteVec): rt.ByteVec => { + rt.byteVecPush(v3, 9); + return v3; + }); + const iter: rt.Iter> = rt.iterSlice([v, copy, grown]); + while (true) { + const _38: rt.Result | rt.Done = iter.next(); + if (_38 === rt.DONE) { + break; + } + const r: rt.Result = _38; + if (r.ok) { + rt.byteVecExtendFromSlice(out, rt.byteVecSlice(r.value)); + } else { + rt.byteVecExtendFromSlice(out, rt.stringAsBytes(r.error)); + } + rt.byteVecPush(out, 124); + } + rt.byteVecPush(out, unwrapOrDefault$Option_Vec_u8(map$Option_u8_Vec_u8_owned_closure4(filter$Option_u8_combinators_closure0(b, (y3: rt.u8): boolean => { + return rt.u8Rem(y3, 2) === 0; + }), (y4: rt.u8): rt.ByteVec => { + return rt.byteVecFrom(Uint8Array.of(y4)); + })).length & 0xff); + const pair: rt.Result = okOr$Option_u32s_u8(map$Option_u8_u32s_owned_closure9(a, (x4: rt.u8): rt.u32[] => { + return [x4 as rt.u32, 2]; + }), 3); + const wide: rt.Result = copy$Result_u32s_u16(mapErr$Result_u32s_u8_u16_from(pair, (a0: rt.u8): rt.u16 => { + return a0 as rt.u16; + })); + if (wide.ok) { + wide.value[0] = 9; + } + if (pair.ok) { + matched = rt.Ok(copy$u32s(pair.value)); + } else { + matched = rt.Err(pair.error as rt.u16); + } + if (matched.ok) { + matched.value[1] = 8; + } + const iter2: rt.Iter> = rt.iterSlice([copy$Result_u32s_u16(mapErr$Result_u32s_u8_u16_from(pair, (a02: rt.u8): rt.u16 => { + return a02 as rt.u16; + })), copy$Result_u32s_u16(wide), copy$Result_u32s_u16(matched)]); + while (true) { + const _81: rt.Result | rt.Done = iter2.next(); + if (_81 === rt.DONE) { + break; + } + const r2: rt.Result = _81; + if (r2.ok) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(r2.value[0] & 0xff, r2.value[1] & 0xff))); + } else { + rt.byteVecPush(out, r2.error & 0xff); + } + } +} + +/** A panic inside a closure std calls. */ +export function panics(a: rt.u8 | undefined, b: rt.u8 | undefined, limit: rt.u8, out: rt.ByteVec): void { + rt.byteVecPush(out, unwrapOr$Option_u8(andThen$Option_u8_u8_options_closure2(a, (x: rt.u8): rt.u8 | undefined => { + if (!(x === limit)) { + return b; + } + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(x, f)]; + rt.panicFmt(["closure saw ", args2[0]]); + }), 1)); + rt.byteVecPush(out, unwrapOrElse$Result_u8_u8_panics_closure1(okOr$Option_u8_u8(b, limit), (e: rt.u8): rt.u8 => { + if (rt.u8Rem(e, 4) === 0) { + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(e, f)]; + rt.panicFmt(["error ", args4[0]]); + } else { + return e; + } + })); +} + +export function push(r: rt.Result, out: rt.ByteVec): void { + if (r.ok) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(1, r.value))); + } else { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(r.error))); + } +} + +//# sourceMappingURL=combinators.ts.map diff --git a/ts/fixtures/lang/expected/core/option.ts b/ts/fixtures/lang/expected/core/option.ts new file mode 100644 index 000000000..25964ec17 --- /dev/null +++ b/ts/fixtures/lang/expected/core/option.ts @@ -0,0 +1,495 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as Nibble from "../collections.Nibble.ts"; +import type * as Rank from "../collections.Rank.ts"; +import type * as Tally from "../collections.Tally.ts"; +import { side, order } from "../keys.ts"; +import type * as Hop from "../keys.Hop.ts"; +import type * as Side from "../keys.Side.ts"; +import type * as Way from "../keys.Way.ts"; +import { from$From_Dir_u8 } from "../shapes.ts"; +import type * as Dir from "../shapes.Dir.ts"; +import type * as Meters from "../shapes.Meters.ts"; +import type * as Point from "../shapes.Point.ts"; +import type * as Shape from "../shapes.Shape.ts"; + +export function isSomeAnd$Option_u8_options_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => boolean): boolean { + if (self === undefined) { + return false; + } + return f(self); +} + +export function isNoneOr$Option_u8_options_closure1(self: rt.u8 | undefined, f: (a0: rt.u8) => boolean): boolean { + if (self === undefined) { + return true; + } + return f(self); +} + +export function unwrapOr$Option_Cow_str(self: string | undefined, default_: string): string { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_char(self: rt.char | undefined, default_: rt.char): rt.char { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_i64(self: rt.i64 | undefined, default_: rt.i64): rt.i64 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_u16(self: rt.u16 | undefined, default_: rt.u16): rt.u16 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_u64(self: rt.u64 | undefined, default_: rt.u64): rt.u64 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_u8(self: rt.u8 | undefined, default_: rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOr$Option_usize_u8(self: [rt.usize, rt.u8] | undefined, default_: [rt.usize, rt.u8]): [rt.usize, rt.u8] { + if (self === undefined) { + return default_; + } + return self; +} + +export function unwrapOrElse$Option_String_owned_closure3(self: string | undefined, f: () => string): string { + if (self === undefined) { + return f(); + } + return self; +} + +export function unwrapOrElse$Option_u8_options_closure9(self: rt.u8 | undefined, f: () => rt.u8): rt.u8 { + if (self === undefined) { + return f(); + } + return self; +} + +export function unwrapOrDefault$Option_String(self: string | undefined): string { + if (self === undefined) { + return ""; + } + return self; +} + +export function unwrapOrDefault$Option_Vec_u8(self: rt.ByteVec | undefined): rt.ByteVec { + if (self === undefined) { + return new rt.ByteVec(); + } + return self; +} + +export function unwrapOrDefault$Option_u8(self: rt.u8 | undefined): rt.u8 { + if (self === undefined) { + return 0; + } + return self; +} + +export function map$Option_Dir_Shape_rematched_closure1(self: Dir.Dir | undefined, f: (a0: Dir.Dir) => Shape.Shape): Shape.Shape | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_Dir_u8_from(self: Dir.Dir | undefined, _: (a0: Dir.Dir) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return from$From_Dir_u8(self); +} + +export function map$Option_Hop_u64_defaults_closure0(self: Hop.Hop | undefined, f: (a0: Hop.Hop) => rt.u64): rt.u64 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_Hop_u64_u64_options_closure0(self: Hop.Hop | undefined, f: (a0: Hop.Hop) => [rt.u64, rt.u64]): [rt.u64, rt.u64] | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_Way_bool_defaults_closure2(self: Way.Way | undefined, f: (a0: Way.Way) => boolean): boolean | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_str_Cow_str_Borrowed(self: string | undefined, _: (a0: string) => string): string | undefined { + if (self === undefined) { + return undefined; + } + return self; +} + +export function map$Option_u8_Side_side(self: rt.u8 | undefined, _: (a0: rt.u8) => Side.Side): Side.Side | undefined { + if (self === undefined) { + return undefined; + } + return side(self); +} + +export function map$Option_u8_String_owned_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => string): string | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_u8_Vec_u8_owned_closure4(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.ByteVec): rt.ByteVec | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_u8_u32s_owned_closure9(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u32[]): rt.u32[] | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_u8_u8_options_closure3_closure0(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u8): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function map$Option_usize_str_str_slices_closure2(self: [rt.usize, string] | undefined, f: (a0: [rt.usize, string]) => string): string | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function inspect$Option_u8_options_closure11(self: rt.u8 | undefined, f: (a0: rt.u8) => void): rt.u8 | undefined { + if (self !== undefined) { + f(self); + } + return self; +} + +export function mapOr$Option_Hop_u64_options_closure2(self: Hop.Hop | undefined, default_: rt.u64, f: (a0: Hop.Hop) => rt.u64): rt.u64 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Meters_u64_copies_closure0(self: Meters.Meters | undefined, default_: rt.u64, f: (a0: Meters.Meters) => rt.u64): rt.u64 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Mutex_u8_u8_u8_shares_closure0(self: [rt.Mutex, rt.u8] | undefined, default_: rt.u8, f: (a0: [rt.Mutex, rt.u8]) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Nibble_u8_sets_closure4(self: Nibble.Nibble | undefined, default_: rt.u8, f: (a0: Nibble.Nibble) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Ordering_u8_order(self: rt.Ordering | undefined, default_: rt.u8, _: (a0: rt.Ordering) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return order(self); +} + +export function mapOr$Option_Point_u8_known_closure0_closure0(self: Point.Point | undefined, default_: rt.u8, f: (a0: Point.Point) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Rank_Tally_u8_hash_maps_closure11(self: [Rank.Rank, Tally.Tally] | undefined, default_: rt.u8, f: (a0: [Rank.Rank, Tally.Tally]) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Shape_u8_rematched_closure0(self: Shape.Shape | undefined, default_: rt.u8, f: (a0: Shape.Shape) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Tally_u8_hash_maps_closure10(self: Tally.Tally | undefined, default_: rt.u8, f: (a0: Tally.Tally) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Vec_u16_u8_consumers_closure23(self: rt.u16[] | undefined, default_: rt.u8, f: (a0: rt.u16[]) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Vec_u8_u8_library_closure5(self: rt.ByteVec | undefined, default_: rt.u8, f: (a0: rt.ByteVec) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u16_u8_hash_maps_closure0(self: rt.u16 | undefined, default_: rt.u8, f: (a0: rt.u16) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u8_u8_options_closure5(self: rt.u8 | undefined, default_: rt.u8, f: (a0: rt.u8) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u8_u8_u8_btree_maps_closure0(self: [rt.u8, rt.u8] | undefined, default_: rt.u8, f: (a0: [rt.u8, rt.u8]) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u8_u8_u8s_stores_closure2_closure0(self: [rt.u8, rt.u8] | undefined, default_: Uint8Array, f: (a0: [rt.u8, rt.u8]) => Uint8Array): Uint8Array { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u8_usize_shares_closure1(self: rt.u8 | undefined, default_: rt.usize, f: (a0: rt.u8) => rt.usize): rt.usize { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u8s_u8s_u8s_chunks_closure0(self: [rt.ByteSlice, rt.ByteSlice] | undefined, default_: rt.ByteSlice, f: (a0: [rt.ByteSlice, rt.ByteSlice]) => rt.ByteSlice): rt.ByteSlice { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_usize_str_slices_closure1_closure0_closure0(self: rt.usize | undefined, default_: string, f: (a0: rt.usize) => string): string { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_usize_str_usize_slices_closure3(self: [rt.usize, string] | undefined, default_: rt.usize, f: (a0: [rt.usize, string]) => rt.usize): rt.usize { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_usize_u8_consumers_closure8(self: rt.usize | undefined, default_: rt.u8, f: (a0: rt.usize) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_usize_u8_u8_ranges_closure0(self: [rt.usize, rt.u8] | undefined, default_: rt.u8, f: (a0: [rt.usize, rt.u8]) => rt.u8): rt.u8 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOrElse$Option_u8_u8_options_closure7_options_closure8(self: rt.u8 | undefined, default_: () => rt.u8, f: (a0: rt.u8) => rt.u8): rt.u8 { + if (self === undefined) { + return default_(); + } + return f(self); +} + +export function okOr$Option_u32s_u8(self: rt.u32[] | undefined, err: rt.u8): rt.Result { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +export function okOr$Option_u8_u16(self: rt.u8 | undefined, err: rt.u16): rt.Result { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +export function okOr$Option_u8_u8(self: rt.u8 | undefined, err: rt.u8): rt.Result { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +export function okOr$Option_u8s_u8s_u8(self: [rt.ByteSlice, rt.ByteSlice] | undefined, err: rt.u8): rt.Result<[rt.ByteSlice, rt.ByteSlice], rt.u8> { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + +export function okOrElse$Option_Vec_u8_String_owned_closure5(self: rt.ByteVec | undefined, err: () => string): rt.Result { + if (self === undefined) { + return rt.Err(err()); + } + return rt.Ok(self); +} + +export function okOrElse$Option_u8_u16_options_closure12(self: rt.u8 | undefined, err: () => rt.u16): rt.Result { + if (self === undefined) { + return rt.Err(err()); + } + return rt.Ok(self); +} + +export function and$Option_u8_u8(self: rt.u8 | undefined, optb: rt.u8 | undefined): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return optb; +} + +export function andThen$Option_u8_u8_options_closure2(self: rt.u8 | undefined, f: (a0: rt.u8) => rt.u8 | undefined): rt.u8 | undefined { + if (self === undefined) { + return undefined; + } + return f(self); +} + +export function filter$Option_String_owned_closure1(self: string | undefined, predicate: (a0: string) => boolean): string | undefined { + if (self !== undefined) { + const x: string = self; + if (predicate(x)) { + return x; + } + } + return undefined; +} + +export function filter$Option_u8_combinators_closure0(self: rt.u8 | undefined, predicate: (a0: rt.u8) => boolean): rt.u8 | undefined { + if (self !== undefined) { + const x: rt.u8 = self; + if (predicate(x)) { + return x; + } + } + return undefined; +} + +export function or$Option_u8(self: rt.u8 | undefined, optb: rt.u8 | undefined): rt.u8 | undefined { + if (self === undefined) { + return optb; + } + return self; +} + +export function orElse$Option_String_owned_closure2(self: string | undefined, f: () => string | undefined): string | undefined { + if (self === undefined) { + return f(); + } + return self; +} + +export function orElse$Option_u8_options_closure6(self: rt.u8 | undefined, f: () => rt.u8 | undefined): rt.u8 | undefined { + if (self === undefined) { + return f(); + } + return self; +} + +export function xor$Option_u8(self: rt.u8 | undefined, optb: rt.u8 | undefined): rt.u8 | undefined { + let _0!: rt.u8 | undefined; + b0: { + if (self === undefined) { + if (optb !== undefined) { + _0 = optb; + break b0; + } + } else if (optb === undefined) { + _0 = self; + break b0; + } + _0 = undefined; + } + return _0; +} + +export function zip$Option_u8_u8(self: rt.u8 | undefined, other: rt.u8 | undefined): [rt.u8, rt.u8] | undefined { + let _0!: [rt.u8, rt.u8] | undefined; + b0: { + if (self !== undefined) { + if (other !== undefined) { + _0 = [self, other] as [rt.u8, rt.u8]; + break b0; + } + } + _0 = undefined; + } + return _0; +} + +export function clone$Clone_Option_String(self: string | undefined): string | undefined { + if (self === undefined) { + return undefined; + } + return self; +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/lang/expected/core/result.ts b/ts/fixtures/lang/expected/core/result.ts new file mode 100644 index 000000000..0128f8e0b --- /dev/null +++ b/ts/fixtures/lang/expected/core/result.ts @@ -0,0 +1,180 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; + +export function isOkAnd$Result_u8_u16_results_closure5(self: rt.Result, f: (a0: rt.u8) => boolean): boolean { + if (self.ok) { + return f(self.value); + } + return false; +} + +export function isErrAnd$Result_u8_u16_results_closure6(self: rt.Result, f: (a0: rt.u16) => boolean): boolean { + if (self.ok) { + return false; + } + return f(self.error); +} + +export function ok$Result_u8_u16(self: rt.Result): rt.u8 | undefined { + if (self.ok) { + return self.value; + } + return undefined; +} + +export function err$Result_u8_u16(self: rt.Result): rt.u16 | undefined { + if (self.ok) { + return undefined; + } + return self.error; +} + +export function asRef$Result_u8_u16(self: rt.Result): rt.Result { + if (self.ok) { + return rt.Ok(self.value); + } + return rt.Err(self.error); +} + +export function map$Result_Vec_u8_String_Vec_u8_owned_closure6(self: rt.Result, op: (a0: rt.ByteVec) => rt.ByteVec): rt.Result { + if (self.ok) { + return rt.Ok(op(self.value)); + } + return self; +} + +export function map$Result_u8_str_u8_library_closure1(self: rt.Result, op: (a0: rt.u8) => rt.u8): rt.Result { + if (self.ok) { + return rt.Ok(op(self.value)); + } + return self; +} + +export function map$Result_u8_u16_u8_options_closure13(self: rt.Result, op: (a0: rt.u8) => rt.u8): rt.Result { + if (self.ok) { + return rt.Ok(op(self.value)); + } + return self; +} + +export function mapOr$Result_u8_u16_u8_results_closure7(self: rt.Result, default_: rt.u8, f: (a0: rt.u8) => rt.u8): rt.u8 { + if (self.ok) { + return f(self.value); + } + return default_; +} + +export function mapOrElse$Result_u8_u16_u8_results_closure8_results_closure9(self: rt.Result, default_: (a0: rt.u16) => rt.u8, f: (a0: rt.u8) => rt.u8): rt.u8 { + if (self.ok) { + return f(self.value); + } + return default_(self.error); +} + +export function mapErr$Result_u32s_u8_u16_from(self: rt.Result, _: (a0: rt.u8) => rt.u16): rt.Result { + if (self.ok) { + return self as rt.Result; + } + return rt.Err(self.error as rt.u16); +} + +export function mapErr$Result_u8_str_u8_library_closure2(self: rt.Result, op: (a0: string) => rt.u8): rt.Result { + if (self.ok) { + return self as rt.Result; + } + return rt.Err(op(self.error)); +} + +export function mapErr$Result_u8_u16_u16_results_closure14(self: rt.Result, op: (a0: rt.u16) => rt.u16): rt.Result { + if (self.ok) { + return self; + } + return rt.Err(op(self.error)); +} + +export function inspect$Result_u8_u16_results_closure12(self: rt.Result, f: (a0: rt.u8) => void): rt.Result { + if (self.ok) { + f(self.value); + } + return self; +} + +export function inspectErr$Result_u8_u16_results_closure13(self: rt.Result, f: (a0: rt.u16) => void): rt.Result { + if (!self.ok) { + f(self.error); + } + return self; +} + +export function unwrapOrDefault$Result_u8_u16(self: rt.Result): rt.u8 { + if (self.ok) { + return self.value; + } + return 0; +} + +export function and$Result_u8_u16_u8(self: rt.Result, res: rt.Result): rt.Result { + if (self.ok) { + return res; + } + return self; +} + +export function andThen$Result_u8_u16_u8_results_closure3(self: rt.Result, op: (a0: rt.u8) => rt.Result): rt.Result { + if (self.ok) { + return op(self.value); + } + return self; +} + +export function or$Result_u8_u16_u16(self: rt.Result, res: rt.Result): rt.Result { + if (self.ok) { + return self; + } + return res; +} + +export function orElse$Result_u8_u16_u16_results_closure4(self: rt.Result, op: (a0: rt.u16) => rt.Result): rt.Result { + if (self.ok) { + return self; + } + return op(self.error); +} + +export function unwrapOr$Result_u8_u16(self: rt.Result, default_: rt.u8): rt.u8 { + if (self.ok) { + return self.value; + } + return default_; +} + +export function unwrapOrElse$Result_u8_u16_results_closure11(self: rt.Result, op: (a0: rt.u16) => rt.u8): rt.u8 { + if (self.ok) { + return self.value; + } + return op(self.error); +} + +export function unwrapOrElse$Result_u8_u8_panics_closure1(self: rt.Result, op: (a0: rt.u8) => rt.u8): rt.u8 { + if (self.ok) { + return self.value; + } + return op(self.error); +} + +export function copied$Result_u8_u16(self: rt.Result): rt.Result { + if (self.ok) { + return rt.Ok(self.value); + } + return self; +} + +export function clone$Clone_Result_Vec_u8_String(self: rt.Result): rt.Result { + if (self.ok) { + return rt.Ok(rt.byteVecFrom(rt.byteVecView(self.value))); + } + return rt.Err(self.error); +} + +//# sourceMappingURL=result.ts.map diff --git a/ts/fixtures/lang/expected/cows.ts b/ts/fixtures/lang/expected/cows.ts index e2b791c0c..56d1393cf 100644 --- a/ts/fixtures/lang/expected/cows.ts +++ b/ts/fixtures/lang/expected/cows.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_Cow_str, unwrapOr$Option_u8, map$Option_str_Cow_str_Borrowed } from "./core/option.ts"; import * as Named from "./cows.Named.ts"; import { put } from "./fmt.ts"; import { text } from "./strs.ts"; @@ -27,7 +28,7 @@ export function cows(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { try { const s: string = text(data); const owned: boolean = (kind & 128) !== 0; - const first: string = rt.optionUnwrapOr(rt.iterToOption(rt.strSplit(s, "/").next()), ""); + const first: string = unwrapOr$Option_Cow_str(rt.iterToOption(rt.strSplit(s, "/").next()), ""); const _14: rt.u8 = rt.u8Rem(kind, 6); if (_14 === 0) { const c: string = cow(s, owned); @@ -45,7 +46,7 @@ export function cows(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { shared = new rt.Arc(s); unwind = 267; put(out, shared.value); - const part: string = rt.optionUnwrapOr(rt.optionMap(rt.iterNth(rt.strSplit(s, "\\"), 1), (a03: string): string => { + const part: string = unwrapOr$Option_Cow_str(map$Option_str_Cow_str_Borrowed(rt.iterNth(rt.strSplit(s, "\\"), 1), (a03: string): string => { return a03; }), "fallback"); unwind = 266; @@ -130,7 +131,7 @@ export function cows(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { put(out, _288[0]); rt.byteVecPush(out, _288[1]); } - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeGet(counts, first), 255)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeGet(counts, first), 255)); const names: rt.HashSet = rt.hashNew(rt.hashing(Named.hash$Hash_DefaultHasher, Named.eq$PartialEq)) as rt.HashSet; const iter5: rt.Iter = rt.strSplit(s, "/"); while (true) { diff --git a/ts/fixtures/lang/expected/fmt.Fault.ts b/ts/fixtures/lang/expected/fmt.Fault.ts index aff9630c9..3b48094e1 100644 --- a/ts/fixtures/lang/expected/fmt.Fault.ts +++ b/ts/fixtures/lang/expected/fmt.Fault.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; import * as Pair from "./fmt.Pair.ts"; export function fmt$Debug(self: Fault, f: rt.Formatter): rt.Result { @@ -59,7 +60,7 @@ export function fmt$Display(self: Fault, f: rt.Formatter): rt.Result rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const _3: rt.u8 = rt.u8Rem(at(0), 4); if (_3 === 0) { diff --git a/ts/fixtures/lang/expected/fmt.ts b/ts/fixtures/lang/expected/fmt.ts index 7005d0eb4..75e14999c 100644 --- a/ts/fixtures/lang/expected/fmt.ts +++ b/ts/fixtures/lang/expected/fmt.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; import * as Bare from "./fmt.Bare.ts"; import * as Braced from "./fmt.Braced.ts"; import * as Fails from "./fmt.Fails.ts"; @@ -180,7 +181,7 @@ export function nested(data: rt.ByteSlice): Nested.Nested { let _61!: rt.Result; let _90!: Kind.Kind; const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const _5: rt.usize = rt.usizeRem(at(0) as rt.usize, ["", "a", "héllo", "日本語", "tab\tnew\nline\r", "quote\"back\\slash'", "\u0000\u0001\u001f", "€Ÿ ­", "é", "‍ᅟ\u2028 ", "͸􏿽", "😀 🇦", "゙゚ン", "{}"].length); if (!(_5 < 14)) { @@ -227,7 +228,7 @@ export function nested(data: rt.ByteSlice): Nested.Nested { /** Derived `Debug` of every shape, compact and pretty, with options passed to fields. */ export function derived(data: rt.ByteSlice, out: rt.ByteVec): void { const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const value: Nested.Nested = nested(data); const args2: rt.Fmt[] = [(f: rt.Formatter) => Nested.fmt$Debug(value, f)]; @@ -289,7 +290,7 @@ export function logged(log: rt.ByteVec, data: rt.ByteSlice): string { export function written(data: rt.ByteSlice, out: rt.ByteVec): void { let _100!: rt.u8 | undefined; const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const hex: Hex.Hex = { _0: rt.u32Mul(at(0) as rt.u32, 4097) }; const args2: rt.Fmt[] = [(f: rt.Formatter) => Hex.fmt$Display(hex, f), (f: rt.Formatter) => Hex.fmt$Debug(hex, f)]; @@ -360,7 +361,7 @@ export function panics(kind: rt.u8, rest: rt.ByteSlice, out: rt.ByteVec): void { let r2!: rt.Result; let r4!: rt.Result; let r5!: rt.Result; - const n: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(rest), 0); + const n: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(rest), 0); const _7: rt.u8 = rt.u8Rem(kind, 20); if (_7 === 0) { const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u8Display(n, f), (f: rt.Formatter) => rt.fmtList(rt.byteSliceView(rest), f, rt.u8Display)]; @@ -459,7 +460,7 @@ export function panics(kind: rt.u8, rest: rt.ByteSlice, out: rt.ByteVec): void { const buf2: Uint8Array = Uint8Array.of(1, 2, 3, 4); const part2 = rt.u8Rem(n, 6) as rt.usize; const part3 = rt.u8Rem(rt.u8Div(n, 6), 6) as rt.usize; - const dest: rt.usize = rt.usizeRem(rt.optionUnwrapOr(rt.byteSliceGet(rest, 1), 0) as rt.usize, 4); + const dest: rt.usize = rt.usizeRem(unwrapOr$Option_u8(rt.byteSliceGet(rest, 1), 0) as rt.usize, 4); rt.byteSliceCopyWithin(rt.byteSliceFrom(buf2), part2, part3, dest); const part4 = rt.byteSliceFrom(buf2); const args20: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtList(rt.byteSliceView(part4), f, rt.u8Display)]; diff --git a/ts/fixtures/lang/expected/generics.ts b/ts/fixtures/lang/expected/generics.ts index 5ca04ef80..2f5330e19 100644 --- a/ts/fixtures/lang/expected/generics.ts +++ b/ts/fixtures/lang/expected/generics.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import { copy$Either_u8_Points, copy$Gauge, copy$Wrap_Point, copy$Wrap_i16, copy$Wrap_u8 } from "./lib.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; import { put } from "./fmt.ts"; import type * as Pair from "./fmt.Pair.ts"; import * as Either from "./generics.Either.ts"; @@ -16,7 +17,7 @@ import type * as Track from "./shapes.Track.ts"; /** Each method once per instance: `Wrap` of a struct, an enum, a number, and itself. */ export function methods(data: rt.ByteSlice, out: rt.ByteVec): void { const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const point: Wrap.Wrap = copy$Wrap_Point(Wrap.new$Point({ x: at(0) as rt.i32, y: -2 })); Wrap.bump$Point(point); @@ -64,7 +65,7 @@ export function methods(data: rt.ByteSlice, out: rt.ByteVec): void { const none: Wrap.Wrap = new Wrap.Wrap({ value: undefined, count: 0 }); const some: Wrap.Wrap = Wrap.new$Option_u8(rt.byteSliceGet(data, 11)); const err: Wrap.Wrap> = new Wrap.Wrap({ value: rt.Err({ tag: "Dot" } as Shape.Shape), count: 2 }); - const _193: rt.u8 = rt.optionUnwrapOr(Wrap.get$Option_u8(none), some.count); + const _193: rt.u8 = unwrapOr$Option_u8(Wrap.get$Option_u8(none), some.count); const args10: rt.Fmt[] = [(f: rt.Formatter) => Wrap.fmt$Debug_Vec_u16(list, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(none, f), (f: rt.Formatter) => Wrap.fmt$Debug_Option_u8(some, f), (f: rt.Formatter) => Wrap.fmt$Debug_Result_u8_Shape(err, f), (f: rt.Formatter) => rt.u8Display(_193, f)]; put(out, rt.fmtFormat([args10[0], " ", args10[1], " ", args10[2], " ", args10[3], " ", args10[4]])); const tagged: Tagged.Tagged, rt.i16> = new Tagged.Tagged({ key: { tag: "Right", value: 500 } as Either.Either, inner: Wrap.new$i16(rt.i16Sub(at(8) as rt.i16, 100)), all: [Wrap.new$i16(-1), Wrap.new$i16(at(9) as rt.i16)].map(copy$Wrap_i16) }); @@ -72,7 +73,7 @@ export function methods(data: rt.ByteSlice, out: rt.ByteVec): void { const args12: rt.Fmt[] = [(f: rt.Formatter) => Tagged.fmt$Debug_Either_u8_u16_i16(tagged, f), (f: rt.Formatter) => rt.fmtOption(_237, f, (value: Wrap.Wrap, f: rt.Formatter) => Wrap.fmt$Debug_i16(value, f))]; put(out, rt.fmtFormat([args12[0], " ", args12[1]])); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.i16ToBeBytes(tagged.inner.value))); - rt.byteVecPush(out, rt.optionUnwrapOr(Either.left$u8_u16(tagged.key), 0)); + rt.byteVecPush(out, unwrapOr$Option_u8(Either.left$u8_u16(tagged.key), 0)); } /** diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 85220d1d6..1e1a364af 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -4,6 +4,7 @@ import * as rt from "./rt.ts"; import { chars } from "./chars.ts"; import { chunks } from "./chunks.ts"; import { hashMaps, sets, btreeMaps, deques, vecs, stores } from "./collections.ts"; +import { combinators } from "./combinators.ts"; import { cows } from "./cows.ts"; import { durations } from "./durations.ts"; import { ints, strings, derived, written, panics } from "./fmt.ts"; @@ -23,7 +24,7 @@ export function run(input: rt.ByteSlice): rt.ByteVec { const _10: [rt.u8, rt.u8] = [input.data[input.start], input.data[input.start + 1]]; const op: rt.u8 = _10[0]; const kind: rt.u8 = _10[1]; - const _14: rt.u8 = rt.u8Rem(op, 48); + const _14: rt.u8 = rt.u8Rem(op, 49); if (_14 === 0) { u8Op(kind, rt.byteSliceRange(input, 2), out); } else if (_14 === 1) { @@ -136,8 +137,10 @@ export function run(input: rt.ByteSlice): rt.ByteVec { chunks(kind, rt.byteSliceRange(input, 2), out); } else if (_14 === 46) { cows(kind, rt.byteSliceRange(input, 2), out); - } else { + } else if (_14 === 47) { durations(kind, rt.byteSliceRange(input, 2), out); + } else { + combinators(kind, rt.byteSliceRange(input, 2), out); } return out; } diff --git a/ts/fixtures/lang/expected/ints.ts b/ts/fixtures/lang/expected/ints.ts index fe76bf97b..9abf18060 100644 --- a/ts/fixtures/lang/expected/ints.ts +++ b/ts/fixtures/lang/expected/ints.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; /** Apply operation `op` to operands taken from `data`. */ export function u8Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { @@ -29,7 +30,7 @@ export function u8Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.u8 = rt.u8FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.u8 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 8); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.u8Add(a, b)); @@ -135,7 +136,7 @@ export function u16Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.u16 = rt.u16FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.u16 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 16); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.u16Add(a, b)); @@ -241,7 +242,7 @@ export function u32Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.u32 = rt.u32FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.u32 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.u32Add(a, b)); @@ -347,7 +348,7 @@ export function u64Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.u64 = rt.u64FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.u64 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 64); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.u64Add(a, b)); @@ -453,7 +454,7 @@ export function u128Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.u128 = rt.u128FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.u128 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 128); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.u128Add(a, b)); @@ -559,7 +560,7 @@ export function usizeOp(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.usize = rt.usizeFromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.usize = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.usizeAdd(a, b)); @@ -665,7 +666,7 @@ export function i8Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.i8 = rt.i8FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.i8 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 8); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 8); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.i8Add(a, b)); @@ -771,7 +772,7 @@ export function i16Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.i16 = rt.i16FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.i16 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 16); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 16); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.i16Add(a, b)); @@ -877,7 +878,7 @@ export function i32Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.i32 = rt.i32FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.i32 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.i32Add(a, b)); @@ -983,7 +984,7 @@ export function i64Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.i64 = rt.i64FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.i64 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 64); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 64); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.i64Add(a, b)); @@ -1089,7 +1090,7 @@ export function i128Op(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.i128 = rt.i128FromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.i128 = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 128); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 128); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.i128Add(a, b)); @@ -1195,7 +1196,7 @@ export function isizeOp(op: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const _38: rt.isize = rt.isizeFromBeBytes(buf2); const _40: rt.ByteSlice = rt.byteSliceRange(_21, n2); const b: rt.isize = _38; - const shift: rt.u32 = rt.u32Rem(rt.optionUnwrapOr(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); + const shift: rt.u32 = rt.u32Rem(unwrapOr$Option_u8(rt.byteSliceFirst(_40), 0) as rt.u32, 2 * 32); const _52: rt.u8 = rt.u8Rem(op, 25); if (_52 === 0) { _50(out, rt.isizeAdd(a, b)); diff --git a/ts/fixtures/lang/expected/iters.Held.ts b/ts/fixtures/lang/expected/iters.Held.ts index 9847eedb8..734a8f1b1 100644 --- a/ts/fixtures/lang/expected/iters.Held.ts +++ b/ts/fixtures/lang/expected/iters.Held.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_u8 } from "./core/option.ts"; /** An iterator in a field. */ export interface Held { @@ -9,7 +10,7 @@ export interface Held { export function skipOne(self: Held): rt.u8 { self.it.next(); - return rt.optionUnwrapOr(rt.iterToOption(self.it.next()), 187); + return unwrapOr$Option_u8(rt.iterToOption(self.it.next()), 187); } //# sourceMappingURL=iters.Held.ts.map diff --git a/ts/fixtures/lang/expected/iters.ts b/ts/fixtures/lang/expected/iters.ts index 001cac8a1..014f3bc5d 100644 --- a/ts/fixtures/lang/expected/iters.ts +++ b/ts/fixtures/lang/expected/iters.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import { copy$Bumped } from "./lib.ts"; +import { unwrapOr$Option_i64, unwrapOr$Option_u64, unwrapOr$Option_u8, unwrapOr$Option_usize_u8, map$Option_u8_u8_options_closure3_closure0, mapOr$Option_Vec_u16_u8_consumers_closure23, mapOr$Option_u8_u8_options_closure5, mapOr$Option_usize_u8_consumers_closure8, mapOr$Option_usize_u8_u8_ranges_closure0 } from "./core/option.ts"; import * as Bumped from "./iters.Bumped.ts"; import * as Countdown from "./iters.Countdown.ts"; import * as Doubled from "./iters.Doubled.ts"; @@ -182,19 +183,19 @@ export function consumers(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi return rt.u8Rem(_231, 2) === 0; })) & 0xff); } else if (_5 === 1) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFind(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_220: rt.u8): void => { + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterFind(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_220: rt.u8): void => { rt.byteVecPush(log, _220); }), (_221: rt.u8): boolean => { return rt.u8Rem(_221, 7) === 3; }), 255)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterFindMap(rt.iterSlice(rt.byteSliceView(data)), (_222: rt.u8): rt.u8 | undefined => { + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterFindMap(rt.iterSlice(rt.byteSliceView(data)), (_222: rt.u8): rt.u8 | undefined => { const b14: rt.u8 = _222; if (!(b14 > 80)) { return undefined; } return rt.u8CheckedMul(b14, 3); }), 0)); - rt.byteVecPush(out, rt.optionMapOr(rt.iterPosition(rt.iterSlice(rt.byteSliceView(data)), (_223: rt.u8): boolean => { + rt.byteVecPush(out, mapOr$Option_usize_u8_consumers_closure8(rt.iterPosition(rt.iterSlice(rt.byteSliceView(data)), (_223: rt.u8): boolean => { return _223 === 64; }), 255, (p: rt.usize): rt.u8 => { return p & 0xff; @@ -241,24 +242,24 @@ export function consumers(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi } rt.byteVecPush(out, back.len() & 0xff); } else if (_5 === 2) { - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterMax(rt.iterSlice(rt.byteSliceView(data))), 0)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterMin(rt.iterSlice(rt.byteSliceView(data))), 255)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterMaxByKey(rt.iterSlice(rt.byteSliceView(data)), (_218: rt.u8): rt.u8 => { + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterMax(rt.iterSlice(rt.byteSliceView(data))), 0)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterMin(rt.iterSlice(rt.byteSliceView(data))), 255)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterMaxByKey(rt.iterSlice(rt.byteSliceView(data)), (_218: rt.u8): rt.u8 => { return rt.u8Rem(_218, 16); }), 238)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterMinByKey(rt.iterSlice(rt.byteSliceView(data)), (_219: rt.u8): rt.u8 => { + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterMinByKey(rt.iterSlice(rt.byteSliceView(data)), (_219: rt.u8): rt.u8 => { return rt.u8Div(_219, 16); }), 238)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterLast(rt.iterSlice(rt.byteSliceView(data))), 221)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterSlice(rt.byteSliceView(data)), 3), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterLast(rt.iterSlice(rt.byteSliceView(data))), 221)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNth(rt.iterSlice(rt.byteSliceView(data)), 3), 204)); const it: rt.Iter = rt.iterSlice(rt.byteSliceView(data)); const _148: rt.Iter = it; const _150: rt.usize = rt.usizeRem(data.length, 3); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(rt.iterTake(rt.iterBorrow(_148), _150).nthBackItem(1)), 187)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterToOption(rt.iterTake(rt.iterBorrow(_148), _150).nthBackItem(1)), 187)); rt.byteVecPush(out, it.len() & 0xff); const _163: rt.Iter = it; const _165: rt.usize = rt.usizeRem(data.length, 5); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterTake(rt.iterBorrow(_163), _165), 2), 187)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNth(rt.iterTake(rt.iterBorrow(_163), _165), 2), 187)); rt.byteVecPush(out, it.len() & 0xff); } else if (_5 === 3) { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.iterSum(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (_214: rt.u8): rt.u64 => { @@ -288,7 +289,7 @@ export function consumers(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi } else { rt.byteVecPush(out, parsed.error); } - rt.byteVecPush(out, rt.optionMapOr(rt.iterCollectOption(rt.iterMap(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_24: rt.u8): void => { + rt.byteVecPush(out, mapOr$Option_Vec_u16_u8_consumers_closure23(rt.iterCollectOption(rt.iterMap(rt.iterInspect(rt.iterSlice(rt.byteSliceView(data)), (_24: rt.u8): void => { rt.byteVecPush(log, _24); }), (_29: rt.u8): rt.u16 | undefined => { const b5: rt.u8 = _29; @@ -306,15 +307,15 @@ export function rotateFree$RotateFree_u8(self: rt.u8): rt.u8 { /** Ranges as values and as iterators. */ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); - const b: rt.u8 = rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); + const b: rt.u8 = unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0); const range: rt.Range = new rt.Range(a, b); rt.byteVecPush(out, a); rt.byteVecPush(out, b); rt.byteVecPush(out, rt.rangeIsEmpty(range) ? 1 : 0); rt.byteVecPush(out, rt.rangeContains(range, 64) ? 1 : 0); const copy: rt.Range = rt.rangeClone(range); - rt.byteVecPush(out, rt.optionUnwrapOr(copy.start < copy.end ? copy.start++ : undefined, 255)); + rt.byteVecPush(out, unwrapOr$Option_u8(copy.start < copy.end ? copy.start++ : undefined, 255)); rt.byteVecPush(out, range.len() & 0xff); const iter: rt.Iter = rt.iterStepBy(rt.iterRev(range), 3); while (true) { @@ -332,7 +333,7 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, _47); } - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(new rt.Range(a, b), 5), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNth(new rt.Range(a, b), 5), 238)); rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.iterToByteVec(new rt.RangeInclusive(rt.max(a, 250), 255, rt.u8Step)))); const inclusive: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); rt.byteVecPush(out, rt.rangeInclusiveStart(inclusive)); @@ -340,26 +341,26 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.rangeInclusiveContains(inclusive, b) ? 1 : 0); rt.byteVecPush(out, rt.rangeInclusiveContains(new rt.RangeInclusive(32, 127, rt.u64Step), a as rt.u64) ? 1 : 0); const near: rt.RangeInclusive = new rt.RangeInclusive(rt.max(a, 200), 255, rt.u8Step); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(near, b as rt.usize), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNth(near, b as rt.usize), 238)); rt.byteVecPush(out, rt.rangeInclusiveStart(near)); rt.byteVecPush(out, rt.rangeInclusiveIsEmpty(near) ? 1 : 0); rt.byteVecPush(out, rt.rangeInclusiveContains(near, 255) ? 1 : 0); rt.byteVecPush(out, rt.rangeInclusiveContains(near, 100) ? 1 : 0); const low: rt.RangeInclusive = new rt.RangeInclusive(0, b, rt.u8Step); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(low.nthBackItem(rt.usizeRem(a as rt.usize, 16))), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterToOption(low.nthBackItem(rt.usizeRem(a as rt.usize, 16))), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(low)); rt.byteVecPush(out, rt.rangeInclusiveContains(low, rt.u8Div(b, 2)) ? 1 : 0); const reversed: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterNth(rt.iterRev(rt.iterBorrow(reversed)), a as rt.usize), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterNth(rt.iterRev(rt.iterBorrow(reversed)), a as rt.usize), 238)); rt.byteVecPush(out, rt.rangeInclusiveEnd(reversed)); rt.byteVecPush(out, rt.rangeInclusiveContains(reversed, a) ? 1 : 0); const counted: rt.Iter<[rt.usize, rt.u8]> = rt.iterEnumerate(new rt.RangeInclusive(a, b, rt.u8Step)); - const _149: [rt.usize, rt.u8] = rt.optionUnwrapOr(rt.iterNth(counted, rt.usizeDiv(b as rt.usize, 4)), [221, 221] as [rt.usize, rt.u8]); + const _149: [rt.usize, rt.u8] = unwrapOr$Option_usize_u8(rt.iterNth(counted, rt.usizeDiv(b as rt.usize, 4)), [221, 221] as [rt.usize, rt.u8]); const i3: rt.usize = _149[0]; const n: rt.u8 = _149[1]; rt.byteVecPush(out, i3 & 0xff); rt.byteVecPush(out, n); - rt.byteVecPush(out, rt.optionMapOr(rt.iterToOption(counted.next()), 204, (_2: [rt.usize, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_usize_u8_u8_ranges_closure0(rt.iterToOption(counted.next()), 204, (_2: [rt.usize, rt.u8]): rt.u8 => { return _2[0] & 0xff; })); const stepped: rt.RangeInclusive = new rt.RangeInclusive(a, b, rt.u8Step); @@ -378,16 +379,16 @@ export function ranges(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.iterSum(new rt.Range(0, a as rt.u64, rt.u64Step), rt.u64Add, 0)))); const edge: rt.u64 = rt.u64Add(rt.u64Sub({ hi: 0x200000, lo: 0 } as rt.u64, 2), rt.u64Rem(a as rt.u64, 4)); const past: rt.Range = new rt.Range(edge, rt.u64Add(edge, 4), rt.u64Step); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(past, rt.usizeRem(b as rt.usize, 3)), 0)))); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterToOption(past.nextBack()), 0)))); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterNth(new rt.RangeInclusive(edge, rt.u64Add(edge, 3), rt.u64Step), rt.usizeRem(b as rt.usize, 5)), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(unwrapOr$Option_u64(rt.iterNth(past, rt.usizeRem(b as rt.usize, 3)), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(unwrapOr$Option_u64(rt.iterToOption(past.nextBack()), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(unwrapOr$Option_u64(rt.iterNth(new rt.RangeInclusive(edge, rt.u64Add(edge, 3), rt.u64Step), rt.usizeRem(b as rt.usize, 5)), 0)))); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.iterSum(rt.iterMap(new rt.RangeInclusive(rt.u64Sub({ hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Rem(a as rt.u64, 3)), { hi: 0xffffffff, lo: 0xffffffff } as rt.u64, rt.u64Step), (n4: rt.u64): rt.u64 => { return rt.u64Rem(n4, 7); }), rt.u64Add, 0)))); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionUnwrapOr(rt.iterMaxByKey(rt.iterRev(new rt.RangeInclusive(edge, rt.u64Add(edge, 2), rt.u64Step)), (_24: rt.u64): rt.u64 => { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(unwrapOr$Option_u64(rt.iterMaxByKey(rt.iterRev(new rt.RangeInclusive(edge, rt.u64Add(edge, 2), rt.u64Step)), (_24: rt.u64): rt.u64 => { return _24; }), 0)))); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.i64ToBeBytes(rt.optionUnwrapOr(rt.iterMin(new rt.Range(rt.i64Sub(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Add(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Step)), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.i64ToBeBytes(unwrapOr$Option_i64(rt.iterMin(new rt.Range(rt.i64Sub(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Add(rt.i64Neg({ hi: 0x200000, lo: 0 } as rt.i64), 1), rt.i64Step)), 0)))); for (const _295 of rt.iterToArray(rt.iterRev(rt.iterStepBy(new rt.Range(0, 48), 8)))) { rt.byteVecPush(out, _295 & 0xff); } @@ -447,7 +448,7 @@ export function fullRange(out: rt.ByteVec): undefined { export function options(data: rt.ByteSlice, out: rt.ByteVec): void { const _83: (a0: rt.u8, a1: rt.ByteVec) => rt.u8 | undefined = (b2: rt.u8, calls2: rt.ByteVec): rt.u8 | undefined => { rt.byteVecPush(calls2, b2); - return rt.optionMap(rt.u8CheckedSub(b2, 1), (b3: rt.u8): rt.u8 => { + return map$Option_u8_u8_options_closure3_closure0(rt.u8CheckedSub(b2, 1), (b3: rt.u8): rt.u8 => { return rt.u8Div(b3, 2); }); }; @@ -485,7 +486,7 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecPush(out, rt.iterCount(rt.iterFilter(rt.iterSlice(all), (o: rt.u8 | undefined): boolean => { return o !== undefined; })) & 0xff); - rt.byteVecPush(out, rt.optionUnwrapOr(second$Map_Iter_u8_options_closure0(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (b7: rt.u8): rt.u8 | undefined => { + rt.byteVecPush(out, unwrapOr$Option_u8(second$Map_Iter_u8_options_closure0(rt.iterMap(rt.iterSlice(rt.byteSliceView(data)), (b7: rt.u8): rt.u8 | undefined => { if (!(rt.u8Rem(b7, 3) === 0)) { return b7; } @@ -516,7 +517,7 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { }); const gappy: rt.Iter = rt.iterChain(rt.iterEmpty(), _70); rt.byteVecPush(out, rt.iterCount(rt.iterBorrow(gappy)) & 0xff); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.iterToOption(gappy.next()), 238)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.iterToOption(gappy.next()), 238)); const calls: rt.ByteVec = new rt.ByteVec(); const first2: rt.u8 | undefined = rt.byteSliceFirst(data); rt.byteVecExtendFromSlice(out, rt.byteVecSlice(rt.iterToByteVec(rt.iterTake(rt.iterSuccessors(first2, (b8: rt.u8): rt.u8 | undefined => { @@ -533,7 +534,7 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { if (_114 === rt.DONE) { break; } - rt.byteVecPush(out, rt.optionMapOr(_114, 170, (b10: rt.u8): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_u8_u8_options_closure5(_114, 170, (b10: rt.u8): rt.u8 => { return b10; })); } @@ -544,7 +545,7 @@ export function second$Map_Iter_u8_options_closure0(items: rt.Iter { + const _130: rt.u64 | undefined = map$Option_Hop_u64_defaults_closure0(g, (h2: Hop.Hop): rt.u64 => { return h2._0; }); - const _132: rt.u64 | undefined = rt.optionMap(h, (h3: Hop.Hop): rt.u64 => { + const _132: rt.u64 | undefined = map$Option_Hop_u64_defaults_closure0(h, (h3: Hop.Hop): rt.u64 => { return h3._0; }); rt.byteVecPush(out, _123 | (((rt.cmpOption(rt.cmp)(_130, _132) === 1 ? 1 : 0) << 5) & 0xff)); @@ -336,7 +337,7 @@ export function defaults(data: rt.ByteSlice, out: rt.ByteVec): void { const _194: rt.u8 = !Side.eq$PartialEq(side(rt.u8Rem(c, 2)), side(rt.u8Rem(d, 2))) ? 1 : 0; const _208: Way.Way | undefined = way(c); const _210: Way.Way | undefined = way(d); - rt.byteVecPush(out, _194 | (((!rt.eqOption(Way.eq$PartialEq)(_208, _210) ? 1 : 0) << 1) & 0xff) | (((rt.optionMap(way(c), (w: Way.Way): boolean => { + rt.byteVecPush(out, _194 | (((!rt.eqOption(Way.eq$PartialEq)(_208, _210) ? 1 : 0) << 1) & 0xff) | (((map$Option_Way_bool_defaults_closure2(way(c), (w: Way.Way): boolean => { return !Way.eq$PartialEq(w, "Top" as Way.Way); }) === true ? 1 : 0) << 2) & 0xff)); const _225: rt.ByteSlice = rt.byteSliceRange(data, 0, i); @@ -502,16 +503,16 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { const _75: [rt.u8 | undefined, rt.u8 | undefined] = [small(c), small(d)]; const x: rt.u8 | undefined = _75[0]; const y: rt.u8 | undefined = _75[1]; - const _80: [Side.Side | undefined, Side.Side | undefined] = [rt.optionMap(x, side), rt.optionMap(y, side)]; + const _80: [Side.Side | undefined, Side.Side | undefined] = [map$Option_u8_Side_side(x, side), map$Option_u8_Side_side(y, side)]; const s: Side.Side | undefined = _80[0]; const t: Side.Side | undefined = _80[1]; const _85: rt.u8 = (x === y ? 1 : 0) | (((rt.eqOption(Side.eq$PartialEq)(s, t) ? 1 : 0) << 1) & 0xff); const _101: Side.Side | undefined = s; const _104: Side.Side | undefined = t; rt.byteVecPush(out, _85 | (((!rt.eqOption(Side.eq$PartialEq)(_101, _104) ? 1 : 0) << 2) & 0xff)); - const pairs: [[rt.u64, rt.u64] | undefined, [rt.u64, rt.u64] | undefined] = [rt.optionMap(a, (h2: Hop.Hop): [rt.u64, rt.u64] => { + const pairs: [[rt.u64, rt.u64] | undefined, [rt.u64, rt.u64] | undefined] = [map$Option_Hop_u64_u64_options_closure0(a, (h2: Hop.Hop): [rt.u64, rt.u64] => { return [h2._0, d as rt.u64] as [rt.u64, rt.u64]; - }), rt.optionMap(b, (h3: Hop.Hop): [rt.u64, rt.u64] => { + }), map$Option_Hop_u64_u64_options_closure0(b, (h3: Hop.Hop): [rt.u64, rt.u64] => { return [h3._0, c as rt.u64] as [rt.u64, rt.u64]; })]; const _119: [rt.u64, rt.u64] | undefined = rt.ordMax(pairs[0], pairs[1], rt.cmpOption(rt.cmpTuple([rt.cmp, rt.cmp]))); @@ -546,12 +547,12 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { const key: [rt.u8, Horizon.Horizon] = [rt.u8Rem(c, 3), { exclude: a, local: rt.u8Rem(d, 2) === 0 }]; const _269: rt.u8 | undefined = rt.hashInsert(hashed, copy$u8_Horizon(key), i & 0xff); unwind = 133; - rt.byteVecPush(out, rt.optionUnwrapOr(_269, 204)); - rt.byteVecPush(out, rt.optionUnwrapOr(rt.btreeInsert(sorted, copy$u8_Horizon(key), i & 0xff), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(_269, 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.btreeInsert(sorted, copy$u8_Horizon(key), i & 0xff), 204)); const _281: [Way.Way | undefined, boolean] = [way(c), c < 128]; - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashInsert(ways, _281, i & 0xff), 204)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashInsert(ways, _281, i & 0xff), 204)); const _291: [Way.Way | undefined, boolean] = [way(d), d < 128]; - rt.byteVecPush(out, rt.optionUnwrapOr(rt.hashGet(ways, _291), 221)); + rt.byteVecPush(out, unwrapOr$Option_u8(rt.hashGet(ways, _291), 221)); rt.byteVecPush(out, rt.hashLen(ways) & 0xff); const _303: [rt.u8, Horizon.Horizon] = [rt.u8Rem(d, 3), { exclude: b, local: false }]; rt.byteVecPush(out, rt.hashContains(hashed, _303) ? 1 : 0); @@ -571,7 +572,7 @@ export function options(data: rt.ByteSlice, out: rt.ByteVec): void { break; } rt.byteVecPush(out, _310[0][0]); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionMapOr(_310[0][1].exclude, 0, (h4: Hop.Hop): rt.u64 => { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(mapOr$Option_Hop_u64_options_closure2(_310[0][1].exclude, 0, (h4: Hop.Hop): rt.u64 => { return h4._0; })))); rt.byteVecPush(out, (_310[0][1].exclude !== undefined ? 1 : 0) | (((_310[0][1].local ? 1 : 0) << 1) & 0xff)); @@ -913,7 +914,7 @@ export function places(data: rt.ByteSlice, out: rt.ByteVec): void { let iterStart2: rt.u8 = 0; const iterEnd2: rt.u8 = 7; while ((_257 = iterStart2++) < iterEnd2) { - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionUnwrapOr(rt.hashGet(wide, _257), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(unwrapOr$Option_u64(rt.hashGet(wide, _257), 0)))); } const iter6: rt.Range = new rt.Range(0, 6, rt.u64Step); while (true) { @@ -921,7 +922,7 @@ export function places(data: rt.ByteSlice, out: rt.ByteVec): void { if (_273 === rt.DONE) { break; } - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(rt.optionUnwrapOr(rt.hashGet(hops, { _0: _273 }), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(unwrapOr$Option_u16(rt.hashGet(hops, { _0: _273 }), 0)))); } const iter7: rt.Iter<[Hop.Hop, [rt.u8, rt.u8]]> = rt.btreeIter(pairs); while (true) { diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index 6dba18ef6..d5e2a3d7d 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -114,6 +114,10 @@ export function copy$Result_Mutex_u8_u8_u8(v: rt.Result<[rt.Mutex, rt.u8] return v.ok ? rt.Ok(copy$Mutex_u8_u8(v.value)) : rt.Err(v.error); } +export function copy$Result_u32s_u16(v: rt.Result): rt.Result { + return v.ok ? rt.Ok(copy$u32s(v.value)) : rt.Err(v.error); +} + export function copy$Shape(v: Shape.Shape): Shape.Shape { if (v.tag === "Line") { return { tag: "Line", _0: copy$Point(v._0), _1: copy$Point(v._1) }; @@ -144,6 +148,10 @@ export function copy$Wrap_u8(v: Wrap.Wrap): Wrap.Wrap { return new Wrap.Wrap({ value: v.value, count: v.count }); } +export function copy$u32s(v: rt.u32[]): rt.u32[] { + return v.slice(); +} + export function copy$u8_Horizon(v: [rt.u8, Horizon.Horizon]): [rt.u8, Horizon.Horizon] { return [v[0], copy$Horizon(v[1])]; } diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 0fd77e575..b1e5ea86a 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -2,6 +2,8 @@ import * as rt from "./rt.ts"; import { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Gauge, copy$Held, copy$Lens, copy$Level, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, copy$Option_Shape, copy$Point, copy$Point_u8, copy$Points, copy$Poll_u8s, copy$Result_Mutex_u8_u8_u8, copy$Shape, copy$u8_u8, copy$u8s } from "./lib.ts"; +import { unwrapOr$Option_u8, map$Option_Dir_Shape_rematched_closure1, map$Option_Dir_u8_from, mapOr$Option_Meters_u64_copies_closure0, mapOr$Option_Mutex_u8_u8_u8_shares_closure0, mapOr$Option_Point_u8_known_closure0_closure0, mapOr$Option_Shape_u8_rematched_closure0, mapOr$Option_Vec_u8_u8_library_closure5, mapOr$Option_u8_usize_shares_closure1, okOr$Option_u8_u8 } from "./core/option.ts"; +import { map$Result_u8_str_u8_library_closure1, mapErr$Result_u8_str_u8_library_closure2 } from "./core/result.ts"; import * as Pair from "./fmt.Pair.ts"; import { advance, reset$Gauge } from "./generics.ts"; import type * as Dir from "./shapes.Dir.ts"; @@ -77,7 +79,7 @@ export function shape(data: rt.ByteSlice): Shape.Shape { if (_4 !== undefined) { const kind: rt.u8 = _4[0]; const at: (a0: rt.usize) => rt.i32 = (i: rt.usize): rt.i32 => { - return rt.i32Sub(rt.optionUnwrapOr(rt.byteSliceGet(_4[1], i), 0) as rt.i32, 128); + return rt.i32Sub(unwrapOr$Option_u8(rt.byteSliceGet(_4[1], i), 0) as rt.i32, 128); }; const _7: rt.u8 = rt.u8Rem(kind, 3); if (_7 === 0) { @@ -86,7 +88,7 @@ export function shape(data: rt.ByteSlice): Shape.Shape { if (_7 === 1) { return { tag: "Line", _0: Point.new(at(0), at(1)), _1: Point.new(at(2), at(3)) } as Shape.Shape; } - return { tag: "Rect", corner: Point.new(at(0), at(1)), width: rt.u16Mul(rt.optionUnwrapOr(rt.byteSliceGet(_4[1], 2), 0) as rt.u16, 300), height: rt.optionUnwrapOr(rt.byteSliceGet(_4[1], 3), 0) as rt.u16 } as Shape.Shape; + return { tag: "Rect", corner: Point.new(at(0), at(1)), width: rt.u16Mul(unwrapOr$Option_u8(rt.byteSliceGet(_4[1], 2), 0) as rt.u16, 300), height: unwrapOr$Option_u8(rt.byteSliceGet(_4[1], 3), 0) as rt.u16 } as Shape.Shape; } return { tag: "Dot" } as Shape.Shape; } @@ -96,7 +98,7 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { let _211!: Uint8Array; let poll!: rt.Poll; let _246!: rt.u8; - const p: Point.Point = Point.new(rt.optionUnwrapOr(rt.byteSliceFirst(data), 0) as rt.i32, 7); + const p: Point.Point = Point.new(unwrapOr$Option_u8(rt.byteSliceFirst(data), 0) as rt.i32, 7); const q: Point.Point = copy$Point(p); q.x = rt.i32Add(q.x, 100); Point.bump(q); @@ -160,7 +162,7 @@ export function copies(data: rt.ByteSlice, out: rt.ByteVec): void { opt = undefined; const taken: Meters.Meters | undefined = taken2; rt.byteVecPush(out, opt === undefined ? 1 : 0); - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.optionMapOr(taken, 0, (m: Meters.Meters): rt.u64 => { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(mapOr$Option_Meters_u64_copies_closure0(taken, 0, (m: Meters.Meters): rt.u64 => { return m._0; })))); const res: rt.Result = rt.Ok(p); @@ -277,7 +279,7 @@ export function shares(data: rt.ByteSlice, out: rt.ByteVec): void { let flow!: rt.Result>; let unwind: number = 0; try { - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); const slot: rt.Mutex = new rt.Mutex(a); const other: rt.Mutex = new rt.Mutex(0); const pair: [rt.Mutex, rt.u8] = [slot, a]; @@ -308,7 +310,7 @@ export function shares(data: rt.ByteSlice, out: rt.ByteVec): void { if (_51 === rt.DONE) { break; } - rt.byteVecPush(out, rt.optionMapOr(_51, 0, (_2: [rt.Mutex, rt.u8]): rt.u8 => { + rt.byteVecPush(out, mapOr$Option_Mutex_u8_u8_u8_shares_closure0(_51, 0, (_2: [rt.Mutex, rt.u8]): rt.u8 => { return _2[1]; })); } @@ -388,7 +390,7 @@ export function shares(data: rt.ByteSlice, out: rt.ByteVec): void { const bytes: Uint8Array = Uint8Array.of(a, 1); rt.byteVecPush(out, unsizedCopy(rt.byteSliceFrom(bytes))); rt.byteVecPush(out, bytes[0]); - const at: rt.usize = rt.optionMapOr(rt.byteSliceGet(data, 1), 0, (_22: rt.u8): rt.usize => { + const at: rt.usize = mapOr$Option_u8_usize_shares_closure1(rt.byteSliceGet(data, 1), 0, (_22: rt.u8): rt.usize => { return rt.usizeRem(_22 as rt.usize, 3); }); rt.byteVecPush(out, writeAt(rt.byteSliceFrom(bytes), at, a)); @@ -541,7 +543,7 @@ export function order(data: rt.ByteSlice, out: rt.ByteVec): void { let taken!: Shape.Shape; let _75!: rt.usize; const at: (a0: rt.usize) => rt.u8 = (i2: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i2), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i2), 0); }; const _5: rt.u16 = mark(out, at(0)) & 0xffff; const _10: rt.u16 = mark(out, at(1)) & 0xffff; @@ -599,7 +601,7 @@ export function order(data: rt.ByteSlice, out: rt.ByteVec): void { */ export function indexed(data: rt.ByteSlice, out: rt.ByteVec): void { const at: (a0: rt.usize) => rt.u8 = (i: rt.usize): rt.u8 => { - return rt.optionUnwrapOr(rt.byteSliceGet(data, i), 0); + return unwrapOr$Option_u8(rt.byteSliceGet(data, i), 0); }; const _7: rt.ByteVec = listed(out, at(0)); rt.byteVecPush(out, 225); @@ -647,7 +649,7 @@ export function indexed(data: rt.ByteSlice, out: rt.ByteVec): void { /** Each part's length and first byte. */ export function ends(parts: rt.ByteSlice[], out: rt.ByteVec): void { for (const _5 of parts) { - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_5.length & 0xff, rt.optionUnwrapOr(rt.byteSliceFirst(_5), 0)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(_5.length & 0xff, unwrapOr$Option_u8(rt.byteSliceFirst(_5), 0)))); } } @@ -864,7 +866,7 @@ export function diverging(data: rt.ByteSlice, out: rt.ByteVec): void { rt.panicFmt(["closure ", args2[0]]); }; const head: rt.ByteSlice = rt.byteSliceRange(data, 0, rt.min(data.length, 2)); - const b: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(head), 0); + const b: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(head), 0); rt.byteVecPush(out, returnedNever(b, data.length)); rt.byteVecPush(out, brokenNever(head)); rt.byteVecPush(out, _15(b)); @@ -1456,7 +1458,7 @@ export function payloads(data: rt.ByteSlice, out: rt.ByteVec): void { if (taken.ok) { const taken2 = taken.value; taken = rt.OK; - rt.byteVecPush(out, rt.optionUnwrapOr(taken2, 67)); + rt.byteVecPush(out, unwrapOr$Option_u8(taken2, 67)); } if (nested !== rt.Pending) { if (nested !== undefined) { @@ -1470,7 +1472,7 @@ export function payloads(data: rt.ByteSlice, out: rt.ByteVec): void { } } if (taken.ok) { - _109 = rt.optionUnwrapOr(taken.value, 68); + _109 = unwrapOr$Option_u8(taken.value, 68); } else { _109 = taken.error; } @@ -1500,7 +1502,7 @@ export function payloads(data: rt.ByteSlice, out: rt.ByteVec): void { } else { _143 = flow.error; } - const _147: rt.u8 = rt.optionUnwrapOr(opt, 0); + const _147: rt.u8 = unwrapOr$Option_u8(opt, 0); if (poll !== rt.Pending) { _149 = poll; } else { @@ -1596,7 +1598,7 @@ export function known(data: rt.ByteSlice, out: rt.ByteVec): void { } else { a = 0; } - return a ^ rt.optionMapOr(noneLater, 16, (p4: Point.Point): rt.u8 => { + return a ^ mapOr$Option_Point_u8_known_closure0_closure0(noneLater, 16, (p4: Point.Point): rt.u8 => { return p4.x & 0xff; }); })()); @@ -1698,7 +1700,7 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { if ((flow as rt.Result).ok) { _76 = ((flow as rt.Result) as { ok: true; value: rt.u16 }).value & 0xff; } else { - _76 = rt.optionUnwrapOr(((flow as rt.Result) as { ok: false; error: rt.u8 | undefined }).error, 33); + _76 = unwrapOr$Option_u8(((flow as rt.Result) as { ok: false; error: rt.u8 | undefined }).error, 33); } rt.byteVecPush(out, _76); } @@ -1737,7 +1739,7 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { held = undefined; const taken: Shape.Shape | undefined = taken2; if ((held as Shape.Shape | undefined) === undefined) { - _118 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { + _118 = mapOr$Option_Shape_u8_rematched_closure0(taken, 22, (t: Shape.Shape): rt.u8 => { return rt.u64Low(Shape.area$Area(t)) & 0xff; }); } else { @@ -1768,7 +1770,7 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { while (iterStart2++ < iterEnd2) { rt.byteVecPush(out, Machine.run(machine, data.length & 0xff)); } - const filled: Filled.Filled = { shape: copy$Option_Shape(rt.optionMap(dir(data.length & 0xff), (_2: Dir.Dir): Shape.Shape => { + const filled: Filled.Filled = { shape: copy$Option_Shape(map$Option_Dir_Shape_rematched_closure1(dir(data.length & 0xff), (_2: Dir.Dir): Shape.Shape => { return copy$Shape(s); })) }; let iterStart3: rt.i32 = 0; @@ -1924,7 +1926,7 @@ export function closures(data: rt.ByteSlice, out: rt.ByteVec): void { } const tags: rt.ByteVec = new rt.ByteVec(); for (const _64 of parsed) { - const _70: rt.u8 = rt.optionUnwrapOr(rt.optionMap(_64, from$From_Dir_u8), 0); + const _70: rt.u8 = unwrapOr$Option_u8(map$Option_Dir_u8_from(_64, from$From_Dir_u8), 0); rt.byteVecPush(tags, _70); } rt.byteVecExtendFromSlice(out, rt.byteVecSlice(tags)); @@ -1973,15 +1975,15 @@ export function library(data: rt.ByteSlice, out: rt.ByteVec): void { } return rt.Err(from$From_Dir_u8((_132 as { ok: false; error: Dir.Dir }).error)); }; - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); - const b: rt.u8 = rt.optionUnwrapOr(rt.byteSliceGet(data, 1), 0); - rt.byteVecPush(out, rt.optionUnwrapOr(_3(a, b), 255)); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); + const b: rt.u8 = unwrapOr$Option_u8(rt.byteSliceGet(data, 1), 0); + rt.byteVecPush(out, unwrapOr$Option_u8(_3(a, b), 255)); if (a === 0) { parsed = rt.Err("zero"); } else { parsed = rt.Ok(a); } - const mapped: rt.Result = rt.resultMapErr(rt.resultMap(parsed, (n7: rt.u8): rt.u8 => { + const mapped: rt.Result = mapErr$Result_u8_str_u8_library_closure2(map$Result_u8_str_u8_library_closure1(parsed, (n7: rt.u8): rt.u8 => { return rt.u8Div(n7, 2); }), (e4: string): rt.u8 => { return rt.stringLen(e4) & 0xff; @@ -2018,11 +2020,11 @@ export function library(data: rt.ByteSlice, out: rt.ByteVec): void { break; } const x: rt.u8 = _66; - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(rt.optionUnwrapOr(rt.boolThen(rt.u8Rem(x, 2) === 0, (): rt.u8 => { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(unwrapOr$Option_u8(rt.boolThen(rt.u8Rem(x, 2) === 0, (): rt.u8 => { calls = rt.u8Add(calls, 1); return rt.u8Div(x, 2); }), 238), calls))); - rt.byteVecPush(out, rt.optionMapOr(rt.boolThen(x > 128, (): rt.ByteVec => { + rt.byteVecPush(out, mapOr$Option_Vec_u8_u8_library_closure5(rt.boolThen(x > 128, (): rt.ByteVec => { return new rt.ByteVec(); }), 2, (v: rt.ByteVec): rt.u8 => { return v.length & 0xff; @@ -2033,13 +2035,13 @@ export function library(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(flag ? 1 : 0))); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.i64ToBeBytes(flag ? 1 : 0))); } - const _117: rt.Result = rt.optionOkOr(undefined as rt.u8 | undefined, a); + const _117: rt.Result = okOr$Option_u8_u8(undefined as rt.u8 | undefined, a); if (_117.ok) { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(5, _117.value))); } else { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(6, _117.error))); } - const iter2: rt.Iter> = rt.iterSlice([rt.optionOkOr(undefined as rt.u8 | undefined, b), rt.optionOkOr(undefined as rt.u8 | undefined, a)]); + const iter2: rt.Iter> = rt.iterSlice([okOr$Option_u8_u8(undefined as rt.u8 | undefined, b), okOr$Option_u8_u8(undefined, a)]); while (true) { const _134: rt.Result | rt.Done = iter2.next(); if (_134 === rt.DONE) { @@ -2121,7 +2123,7 @@ export function flows(data: rt.ByteSlice, out: rt.ByteVec): void { } } rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(total))); - const a: rt.u8 = rt.optionUnwrapOr(rt.byteSliceFirst(data), 0); + const a: rt.u8 = unwrapOr$Option_u8(rt.byteSliceFirst(data), 0); if (rt.u8Rem(a, 3) === 0) { result = rt.Err(a) as rt.Result; } else { @@ -2202,7 +2204,7 @@ export function flows(data: rt.ByteSlice, out: rt.ByteVec): void { held.value = x2; } } - rt.byteVecPush(out, rt.optionUnwrapOr(slot.value, 252)); + rt.byteVecPush(out, unwrapOr$Option_u8(slot.value, 252)); } //# sourceMappingURL=shapes.ts.map diff --git a/ts/fixtures/lang/expected/strs.ts b/ts/fixtures/lang/expected/strs.ts index f46c757c7..7d63fb879 100644 --- a/ts/fixtures/lang/expected/strs.ts +++ b/ts/fixtures/lang/expected/strs.ts @@ -1,6 +1,7 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; +import { unwrapOr$Option_Cow_str, map$Option_usize_str_str_slices_closure2, mapOr$Option_usize_str_slices_closure1_closure0_closure0, mapOr$Option_usize_str_usize_slices_closure3 } from "./core/option.ts"; import { put } from "./fmt.ts"; import * as Named from "./strs.Named.ts"; @@ -115,7 +116,7 @@ export function strs(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { i2 = rt.usizeAdd(i2, 1); } else { rt.byteVecPush(out, i2 & 0xff); - put(out, rt.optionUnwrapOr(rt.iterToOption(rt.strSplit(s, String.fromCodePoint(sep)).next()), "none")); + put(out, unwrapOr$Option_Cow_str(rt.iterToOption(rt.strSplit(s, String.fromCodePoint(sep)).next()), "none")); break b0; } } @@ -291,7 +292,7 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { n = rt.i32Add(n, 1); } rt.byteVecPush(out, n & 0xff); - put(out, rt.optionUnwrapOr(rt.iterLast(rt.strSplit(s, p)), "none")); + put(out, unwrapOr$Option_Cow_str(rt.iterLast(rt.strSplit(s, p)), "none")); } else { if (_8 === 1) { const iter2: rt.Iter<[rt.usize, string]> = rt.strMatchIndices(s, p); @@ -327,7 +328,7 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { const iter3: rt.Iter = rt.iterSuccessors(s, (path: string): string | undefined => { const _73: string = path; return rt.boolThen(!((path.length === 0)), (): string => { - return rt.optionMapOr(rt.strRfind(_73, "/"), "", (slash: rt.usize): string => { + return mapOr$Option_usize_str_slices_closure1_closure0_closure0(rt.strRfind(_73, "/"), "", (slash: rt.usize): string => { return rt.strSlice(_73, 0, slash); }); }); @@ -342,10 +343,10 @@ export function slices(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): void { } if (_8 === 4) { const keep: rt.usize = rt.usizeAdd(rt.u8Rem(rt.u8Div(kind, 8), 4) as rt.usize, 1); - put(out, rt.optionUnwrapOr(rt.optionMap(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), (_2: [rt.usize, string]): string => { + put(out, unwrapOr$Option_Cow_str(map$Option_usize_str_str_slices_closure2(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), (_2: [rt.usize, string]): string => { return rt.strSlice(s, 0, _2[0]); }), "none")); - const part5 = rt.optionMapOr(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), rt.stringLen(s), (_22: [rt.usize, string]): rt.usize => { + const part5 = mapOr$Option_usize_str_usize_slices_closure3(rt.iterNth(rt.strMatchIndices(s, "/"), rt.usizeSub(keep, 1)), rt.stringLen(s), (_22: [rt.usize, string]): rt.usize => { return rt.usizeAdd(_22[0], 1); }); put(out, rt.strSlice(s, part5)); diff --git a/ts/fixtures/lang/src/combinators.rs b/ts/fixtures/lang/src/combinators.rs new file mode 100644 index 000000000..7e94600a7 --- /dev/null +++ b/ts/fixtures/lang/src/combinators.rs @@ -0,0 +1,176 @@ +//! `Option`'s and `Result`'s combinators, which lower from core's own MIR. Each closure +//! logs that std called it, so the output shows which ran, in what order, and how often. + +/// Run case `kind % 4` over `data`, whose bytes pick each `Some` or `None`, `Ok` or `Err`. +pub fn combinators(kind: u8, data: &[u8], out: &mut Vec) { + let a = data.first().copied().filter(|x| x % 3 != 0); + let b = data.get(1).copied().filter(|x| x % 5 != 0); + let limit = data.get(2).copied().unwrap_or(0x80); + match kind % 4 { + 0 => options(a, b, limit, out), + 1 => results(a, b, limit, out), + 2 => owned(a, b, out), + _ => panics(a, b, limit, out), + } +} + +fn options(a: Option, b: Option, limit: u8, out: &mut Vec) { + let some = a.is_some_and(|x| { + out.push(0xa0); + x > limit + }); + out.push(some as u8); + let none_or = b.is_none_or(|x| { + out.push(0xa1); + x < limit + }); + out.push(none_or as u8); + let chained = a.and_then(|x| x.checked_add(limit)).and_then(|x| { + out.push(0xa2); + b.map(|y| x ^ y) + }); + out.push(chained.unwrap_or(0xee)); + let kept = a.filter(|x| { + out.push(0xa3); + *x > limit + }); + out.push(kept.map_or(0xdd, |x| x / 3)); + let either = a.or_else(|| { + out.push(0xa4); + b + }); + let shown = either.map_or_else( + || { + out.push(0xa5); + 0xcc + }, + |x| x.wrapping_add(3), + ); + out.push(shown); + out.push(a.xor(b).unwrap_or_default()); + let both = a.and(b).unwrap_or_else(|| { + out.push(0xa6); + 0xbb + }); + out.push(both); + out.push(a.or(b).unwrap_or(0xaa)); + out.push(a.zip(b).map_or(0, |(x, y)| x.wrapping_add(y))); + let seen = a.inspect(|x| out.push(*x)); + out.push(seen.is_some() as u8); + let error = b.ok_or_else(|| { + out.push(0xa7); + u16::from(limit) << 1 + }); + push(error.map(|x| x ^ limit), out); +} + +fn results(a: Option, b: Option, limit: u8, out: &mut Vec) { + let r: Result = a.ok_or(u16::from(limit) * 3); + let s: Result = b.ok_or_else(|| 0x1ff); + let mapped = r + .map(|x| { + out.push(0xb1); + x.wrapping_add(limit) + }) + .map_err(|e| { + out.push(0xb2); + e.wrapping_add(1) + }); + push(mapped, out); + let chained = r.and_then(|x| x.checked_mul(limit).ok_or(7)).or_else(|e| { + out.push(0xb3); + match e % 2 { + 0 => Ok(1), + _ => Err(e), + } + }); + push(chained, out); + out.push(r.is_ok_and(|v| v > 3) as u8); + let large = s.is_err_and(|e| { + out.push(0xb4); + e > 0x100 + }); + out.push(large as u8); + out.push(r.map_or(0x11, |v| v / 2)); + out.push(s.map_or_else(|e| e as u8, |v| v ^ 0x55)); + out.push(r.ok().unwrap_or(0)); + out.push(s.err().map_or(0, |e| (e >> 8) as u8)); + out.push(r.and(s).unwrap_or_default()); + out.push(r.or(s).unwrap_or_else(|e| e as u8)); + let inspected = s.inspect(|v| out.push(*v)).inspect_err(|e| out.push(*e as u8)); + out.push(inspected.is_ok() as u8); + // `copied` maps by a closure of core's own. + let by_ref: Result<&u8, u16> = r.as_ref().map_err(|e| *e); + out.push(by_ref.copied().unwrap_or(0x22)); +} + +/// Values JS shares where Rust clones or moves them. +fn owned(a: Option, b: Option, out: &mut Vec) { + let s: Option = a.map(|x| x.to_string()); + let kept = s.clone().filter(|s| s.len() > 1); + out.extend_from_slice(kept.unwrap_or_default().as_bytes()); + out.push(b'|'); + let other = s.or_else(|| b.map(|y| y.to_string())); + out.extend_from_slice(other.unwrap_or_else(|| "-".to_string()).as_bytes()); + out.push(b'|'); + let v: Result, String> = a.map(|x| vec![x; 2]).ok_or_else(|| "none".to_string()); + // A clone changed in place leaves the original as it was. + let mut copy = v.clone(); + if let Ok(inner) = &mut copy { + inner.push(7); + } + let grown = v.clone().map(|mut v| { + v.push(9); + v + }); + for r in [v, copy, grown] { + match r { + Ok(v) => out.extend_from_slice(&v), + Err(e) => out.extend_from_slice(e.as_bytes()), + } + out.push(b'|'); + } + let empty: Option> = b.filter(|y| y % 2 == 0).map(|y| vec![y]); + out.push(empty.unwrap_or_default().len() as u8); + // A `Copy` payload rebuilt into another `Result` and changed there leaves the first's. + let pair: Result<[u32; 2], u8> = a.map(|x| [u32::from(x), 2]).ok_or(3); + let mut wide = pair.map_err(u16::from); + if let Ok(ref mut p) = wide { + p[0] = 9; + } + let mut matched: Result<[u32; 2], u16> = match pair { + Ok(p) => Ok(p), + Err(e) => Err(e.into()), + }; + if let Ok(ref mut p) = matched { + p[1] = 8; + } + for r in [pair.map_err(u16::from), wide, matched] { + match r { + Ok([x, y]) => out.extend_from_slice(&[x as u8, y as u8]), + Err(e) => out.push(e as u8), + } + } +} + +/// A panic inside a closure std calls. +fn panics(a: Option, b: Option, limit: u8, out: &mut Vec) { + let v = a.and_then(|x| match x == limit { + true => panic!("closure saw {x}"), + false => b, + }); + out.push(v.unwrap_or(1)); + let r: Result = b.ok_or(limit); + let w = r.unwrap_or_else(|e| match e % 4 { + 0 => panic!("error {e}"), + _ => e, + }); + out.push(w); +} + +fn push(r: Result, out: &mut Vec) { + match r { + Ok(v) => out.extend_from_slice(&[1, v]), + Err(e) => out.extend_from_slice(&e.to_be_bytes()), + } +} diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 932ea78c6..94da4203a 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -1,7 +1,7 @@ //! The entry point both sides of the differential test run. The first byte picks a //! case and the rest is its input. -use crate::{chars, chunks, collections, cows, durations, fmt, generics, ints, iters, keys, shapes, strs}; +use crate::{chars, chunks, collections, combinators, cows, durations, fmt, generics, ints, iters, keys, shapes, strs}; /// The native side's entry: [`run`], except that a case starting with 0xff prints a /// [`fmt::Fault`], which the translated side prints from TypeScript in `caller.ts`. @@ -19,7 +19,7 @@ pub fn run(input: &[u8]) -> Vec { return out; }; let (op, kind) = (*op, *kind); - match op % 48 { + match op % 49 { 0 => ints::u8_op(kind, data, &mut out), 1 => ints::u16_op(kind, data, &mut out), 2 => ints::u32_op(kind, data, &mut out), @@ -77,7 +77,8 @@ pub fn run(input: &[u8]) -> Vec { 44 => collections::stores(data, &mut out), 45 => chunks::chunks(kind, data, &mut out), 46 => cows::cows(kind, data, &mut out), - _ => durations::durations(kind, data, &mut out), + 47 => durations::durations(kind, data, &mut out), + _ => combinators::combinators(kind, data, &mut out), } out } diff --git a/ts/fixtures/lang/src/lib.rs b/ts/fixtures/lang/src/lib.rs index 0bcfbeb96..f7b561175 100644 --- a/ts/fixtures/lang/src/lib.rs +++ b/ts/fixtures/lang/src/lib.rs @@ -1,7 +1,8 @@ //! The language the driver translates, exercised against native Rust: every integer //! width's arithmetic and casts, `char`s and the `str` methods over them, `Cow`, //! `Duration`, control flow, patterns, `Copy` aggregates, closures, traits, generic types, formatting, -//! collections, and the standard library calls it maps. +//! collections, the standard library calls it maps, and `Option`'s and `Result`'s +//! combinators from core's MIR. //! //! `harness::run` is the entry point both sides of the differential test run, and //! `fmt::Fault` an error only `caller.ts` prints. @@ -9,6 +10,7 @@ mod chars; mod chunks; mod collections; +mod combinators; mod cows; mod durations; mod fmt; diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 3e2f33df6..68354a069 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 92 -- Function instances: 69 +- Refusals: 94 +- Function instances: 75 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -12,28 +12,30 @@ | 7 | an assignment through a reference to `_` | fixtures/reject/src/lib.rs:17:2 | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:28:15 | | 6 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:16:13 | -| 6 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:1 | -| 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:422:2 | +| 4 | a variant of `_`, which is not supported: either is the same JS string | fixtures/reject/src/lib.rs:427:2 | +| 4 | dropping a closure that owns a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:1 | | 4 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:108:2 | | 4 | unsupported type `_` | fixtures/reject/src/lib.rs:7:14 | +| 3 | dropping a closure that owns a value that drops, which is not supported yet, in `_` | fixtures/reject/src/lib.rs:398:12 | | 2 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:128:20 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:280:16 | | 2 | a field of `_` | fixtures/reject/src/lib.rs:296:7 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:187:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:173:23 | -| 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:414:79 | +| 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:419:79 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:167:2 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:85:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:87:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:86:3 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:90:3 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | fixtures/reject/src/lib.rs:301:6 | -| 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:433:18 | +| 1 | `_` is not supported yet | fixtures/reject/src/lib.rs:438:18 | | 1 | `_` of `_` by `_`, which is not supported yet | fixtures/reject/src/lib.rs:324:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | fixtures/reject/src/lib.rs:56:13 | | 1 | `_` through a held type's own, which is not supported yet | fixtures/reject/src/lib.rs:356:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | fixtures/reject/src/lib.rs:366:6 | | 1 | `_`, which is not supported yet | fixtures/reject/src/lib.rs:332:9 | +| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it, in `_` | fixtures/reject/src/lib.rs:366:18 | | 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | fixtures/reject/src/lib.rs:249:26 | | 1 | a `_` cast from `_` to `_` | fixtures/reject/src/lib.rs:119:2 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:254:30 | @@ -47,10 +49,10 @@ | 1 | a scalar constant of type `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:89:3 | | 1 | a zero-sized constant of type `_` | fixtures/reject/src/lib.rs:75:2 | -| 1 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:416:13 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:421:13 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:8:2 | | 1 | comparing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:306:52 | -| 1 | constructing `_` | fixtures/reject/src/lib.rs:440:53 | +| 1 | constructing `_` | fixtures/reject/src/lib.rs:445:53 | | 1 | hashing `_` as a key, which is not supported yet | fixtures/reject/src/lib.rs:306:52 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:88:3 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:83:3 | @@ -62,10 +64,11 @@ The type or module each refused type or path belongs to. | Count | API | First | | ---: | --- | --- | -| 7 | `std::borrow::Cow` | fixtures/reject/src/lib.rs:422:2 | +| 7 | `std::borrow::Cow` | fixtures/reject/src/lib.rs:427:2 | +| 7 | `u8` | fixtures/reject/src/lib.rs:65:10 | | 6 | `Option` | fixtures/reject/src/lib.rs:28:15 | | 6 | `f64` | fixtures/reject/src/lib.rs:7:14 | -| 6 | `u8` | fixtures/reject/src/lib.rs:65:10 | +| 4 | `std::option::Option` | fixtures/reject/src/lib.rs:301:6 | | 4 | `std::string::String` | fixtures/reject/src/lib.rs:95:16 | | 4 | `u32` | fixtures/reject/src/lib.rs:16:13 | | 3 | `std::collections::HashMap` | fixtures/reject/src/lib.rs:56:13 | @@ -76,10 +79,10 @@ The type or module each refused type or path belongs to. | 2 | `Poll` | fixtures/reject/src/lib.rs:128:20 | | 2 | `std::iter::Iterator` | fixtures/reject/src/lib.rs:280:16 | | 2 | `std::iter::Map` | fixtures/reject/src/lib.rs:173:23 | -| 2 | `std::iter::Take` | fixtures/reject/src/lib.rs:414:79 | +| 2 | `std::iter::Take` | fixtures/reject/src/lib.rs:419:79 | | 2 | `std::ops::Range` | fixtures/reject/src/lib.rs:208:8 | -| 2 | `std::option::Option` | fixtures/reject/src/lib.rs:301:6 | | 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:144:2 | +| 2 | `std::result::Result` | fixtures/reject/src/lib.rs:402:12 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:33:4 | | 2 | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | | 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:187:1 | @@ -99,7 +102,7 @@ The type or module each refused type or path belongs to. | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:154:11 | | 1 | `std::str` | fixtures/reject/src/lib.rs:390:4 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:149:2 | -| 1 | `std::time::Duration` | fixtures/reject/src/lib.rs:448:2 | +| 1 | `std::time::Duration` | fixtures/reject/src/lib.rs:453:2 | | 1 | `u64` | fixtures/reject/src/lib.rs:119:2 | | 1 | `{async closure}` | fixtures/reject/src/lib.rs:75:2 | @@ -108,7 +111,7 @@ The type or module each refused type or path belongs to. | Count | Construct | Type or path | First | | ---: | --- | --- | --- | | 6 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:28:15 | -| 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:422:2 | +| 4 | a variant of `_`, which is not supported: either is the same JS string | `std::borrow::Cow` | fixtures/reject/src/lib.rs:427:2 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:128:20 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:95:16 | @@ -116,10 +119,10 @@ The type or module each refused type or path belongs to. | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u8`, `u8` | fixtures/reject/src/lib.rs:65:10 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:144:2 | | 2 | an assignment through a reference to `_` | `u8` | fixtures/reject/src/lib.rs:66:3 | -| 2 | dropping `_`, which is not supported yet | `std::iter::Take` | fixtures/reject/src/lib.rs:414:79 | +| 2 | dropping `_`, which is not supported yet | `std::iter::Take` | fixtures/reject/src/lib.rs:419:79 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:108:2 | | 1 | `_` holds `_`, which is `undefined` as `None` is, which is not supported | `std::collections::HashMap`, `std::option::Option` | fixtures/reject/src/lib.rs:301:6 | -| 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:433:18 | +| 1 | `_` is not supported yet | `std::borrow::Cow` | fixtures/reject/src/lib.rs:438:18 | | 1 | `_` of `_` by `_`, which is not supported yet | `HashMap::contains_key`, `std::collections::HashMap`, `u8` | fixtures/reject/src/lib.rs:324:6 | | 1 | `_` of `_`, which drops `_`, which is not supported yet | `into_keys`, `std::collections::HashMap`, `Noisy` | fixtures/reject/src/lib.rs:56:13 | | 1 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | `std::iter::Iterator::count` | fixtures/reject/src/lib.rs:280:38 | @@ -127,6 +130,7 @@ The type or module each refused type or path belongs to. | 1 | `_` through a held type's own, which is not supported yet | `::ne` | fixtures/reject/src/lib.rs:356:2 | | 1 | `_`, a mutable reference to a value a map holds, kept other than to read and write it | `std::option::Option` | fixtures/reject/src/lib.rs:366:6 | | 1 | `_`, which is not supported yet | `Hasher::write` | fixtures/reject/src/lib.rs:332:9 | +| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it, in `_` | `&mut u8`, `u8`, `std::option::Option::map_or` | fixtures/reject/src/lib.rs:366:18 | | 1 | `fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet | `std::iter::Flatten` | fixtures/reject/src/lib.rs:249:26 | | 1 | a `_` cast from `_` to `_` | `IntToFloat`, `u64`, `f64` | fixtures/reject/src/lib.rs:119:2 | | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:254:30 | @@ -143,21 +147,24 @@ The type or module each refused type or path belongs to. | 1 | an assignment through a reference to `_` | `u32` | fixtures/reject/src/lib.rs:17:2 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:187:1 | | 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:241:1 | -| 1 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:416:13 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:421:13 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:8:2 | | 1 | comparing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | -| 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:440:53 | +| 1 | constructing `_` | `std::borrow::Cow` | fixtures/reject/src/lib.rs:445:53 | | 1 | constructing `_` from another crate | `std::iter::Map` | fixtures/reject/src/lib.rs:173:23 | | 1 | constructing `_` from another crate | `std::iter::Rev` | fixtures/reject/src/lib.rs:194:14 | +| 1 | dropping a closure that owns a value that drops, which is not supported yet, in `_` | `std::option::Option::map` | fixtures/reject/src/lib.rs:398:12 | +| 1 | dropping a closure that owns a value that drops, which is not supported yet, in `_` | `std::result::Result::and_then` | fixtures/reject/src/lib.rs:406:12 | +| 1 | dropping a closure that owns a value that drops, which is not supported yet, in `_` | `std::result::Result::map_err` | fixtures/reject/src/lib.rs:402:12 | | 1 | hashing `_` as a key, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:306:52 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:167:2 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:221:2 | | 1 | replacing the value behind a reference to `_` | `[u16; 1]` | fixtures/reject/src/lib.rs:273:22 | | 1 | replacing the value behind a reference to `_` | `std::string::String` | fixtures/reject/src/lib.rs:384:4 | -| 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:434:2 | +| 1 | unsupported call to `_` | `::deref` | fixtures/reject/src/lib.rs:439:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:154:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:97:10 | -| 1 | unsupported call to `_` | `::add_assign` | fixtures/reject/src/lib.rs:448:2 | +| 1 | unsupported call to `_` | `::add_assign` | fixtures/reject/src/lib.rs:453:2 | | 1 | unsupported call to `_` | `std::mem::size_of_val` | fixtures/reject/src/lib.rs:49:18 | | 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:208:8 | | 1 | unsupported call to `_` | `std::slice::copy_within` | fixtures/reject/src/lib.rs:374:4 | @@ -176,8 +183,8 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:208:8: unsupported call to `std::ops::Range::::contains::` - fixtures/reject/src/lib.rs:374:4: unsupported call to `core::slice::::copy_within::>` - fixtures/reject/src/lib.rs:390:4: unsupported call to `core::str::::split::<[char; 2]>` -- fixtures/reject/src/lib.rs:434:2: unsupported call to ` as std::ops::Deref>::deref` -- fixtures/reject/src/lib.rs:448:2: unsupported call to `::add_assign` +- fixtures/reject/src/lib.rs:439:2: unsupported call to ` as std::ops::Deref>::deref` +- fixtures/reject/src/lib.rs:453:2: unsupported call to `::add_assign` @@ -215,23 +222,21 @@ The type or module each refused type or path belongs to. -
dropping a closure that owns a value that drops, which is not supported yet (6) +
a variant of `_`, which is not supported: either is the same JS string (4) -- fixtures/reject/src/lib.rs:51:1: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:397:12: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:401:12: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:412:18: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:414:15: dropping a closure that owns a value that drops, which is not supported yet -- fixtures/reject/src/lib.rs:415:13: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:427:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:428:30: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:429:27: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:434:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string
-
a variant of `_`, which is not supported: either is the same JS string (4) +
dropping a closure that owns a value that drops, which is not supported yet (4) -- fixtures/reject/src/lib.rs:422:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:423:30: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:424:27: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string -- fixtures/reject/src/lib.rs:429:2: a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string +- fixtures/reject/src/lib.rs:51:1: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:417:18: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:419:15: dropping a closure that owns a value that drops, which is not supported yet +- fixtures/reject/src/lib.rs:420:13: dropping a closure that owns a value that drops, which is not supported yet
@@ -253,6 +258,14 @@ The type or module each refused type or path belongs to.
+
dropping a closure that owns a value that drops, which is not supported yet, in `_` (3) + +- fixtures/reject/src/lib.rs:398:12: dropping a closure that owns a value that drops, which is not supported yet, in `std::option::Option::::map` +- fixtures/reject/src/lib.rs:402:12: dropping a closure that owns a value that drops, which is not supported yet, in `std::result::Result::::map_err` +- fixtures/reject/src/lib.rs:406:12: dropping a closure that owns a value that drops, which is not supported yet, in `std::result::Result::::and_then` + +
+
`_` is not supported: it would be pending two ways with one value (2) - fixtures/reject/src/lib.rs:128:20: `Poll>>` is not supported: it would be pending two ways with one value @@ -290,8 +303,8 @@ The type or module each refused type or path belongs to.
dropping `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:414:79: dropping `std::iter::Take>`, which is not supported yet -- fixtures/reject/src/lib.rs:415:62: dropping `std::iter::Take>`, which is not supported yet +- fixtures/reject/src/lib.rs:419:79: dropping `std::iter::Take>`, which is not supported yet +- fixtures/reject/src/lib.rs:420:62: dropping `std::iter::Take>`, which is not supported yet
@@ -334,7 +347,7 @@ The type or module each refused type or path belongs to.
`_` is not supported yet (1) -- fixtures/reject/src/lib.rs:433:18: `std::borrow::Cow<'_, [u8]>` is not supported yet +- fixtures/reject/src/lib.rs:438:18: `std::borrow::Cow<'_, [u8]>` is not supported yet
@@ -368,6 +381,12 @@ The type or module each refused type or path belongs to.
+
`_`: a JS value of `_` is a copy, so a reference can't change it, in `_` (1) + +- fixtures/reject/src/lib.rs:366:18: `&mut u8`: a JS value of `u8` is a copy, so a reference can't change it, in `std::option::Option::::map_or` + +
+
`fold` of `_`, which folds a `flatten` whose source and iterators both drop, which is not supported yet (1) - fixtures/reject/src/lib.rs:249:26: `fold` of `std::iter::Flatten>>`, which folds a `flatten` whose source and iterators both drop, which is not supported yet @@ -448,7 +467,7 @@ The type or module each refused type or path belongs to.
an iterator that owns `_`, which drops, which is not supported yet (1) -- fixtures/reject/src/lib.rs:416:13: an iterator that owns `Noisy`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:421:13: an iterator that owns `Noisy`, which drops, which is not supported yet
@@ -466,7 +485,7 @@ The type or module each refused type or path belongs to.
constructing `_` (1) -- fixtures/reject/src/lib.rs:440:53: constructing `std::borrow::Cow<'_, std::sync::Arc>` +- fixtures/reject/src/lib.rs:445:53: constructing `std::borrow::Cow<'_, std::sync::Arc>`
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 9c991b1dd..099ea7dcb 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -63,27 +63,28 @@ comparing `std::vec::Vec` as a key, which is not supported yet at fixtures/r `HashMap::contains_key` of `std::collections::HashMap` by `u8`, which is not supported yet at fixtures/reject/src/lib.rs:324:6 unsupported call to `core::slice::::copy_within::>` at fixtures/reject/src/lib.rs:374:4 a coercion to `std::sync::Arc<[u8]>` at fixtures/reject/src/lib.rs:379:2 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:422:2 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:424:27 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:423:30 -a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:429:2 -`std::borrow::Cow<'_, [u8]>` is not supported yet at fixtures/reject/src/lib.rs:433:18 -unsupported call to ` as std::ops::Deref>::deref` at fixtures/reject/src/lib.rs:434:2 -constructing `std::borrow::Cow<'_, std::sync::Arc>` at fixtures/reject/src/lib.rs:440:53 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:427:2 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:429:27 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:428:30 +a variant of `std::borrow::Cow<'_, str>`, which is not supported: either is the same JS string at fixtures/reject/src/lib.rs:434:2 +`std::borrow::Cow<'_, [u8]>` is not supported yet at fixtures/reject/src/lib.rs:438:18 +unsupported call to ` as std::ops::Deref>::deref` at fixtures/reject/src/lib.rs:439:2 +constructing `std::borrow::Cow<'_, std::sync::Arc>` at fixtures/reject/src/lib.rs:445:53 `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:383:15 replacing the value behind a reference to `std::string::String` at fixtures/reject/src/lib.rs:384:4 unsupported call to `core::str::::split::<[char; 2]>` at fixtures/reject/src/lib.rs:390:4 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:397:12 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:401:12 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:412:18 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:414:15 -dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:414:79 -dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:415:13 -dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:415:62 -an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:416:13 -unsupported call to `::add_assign` at fixtures/reject/src/lib.rs:448:2 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:417:18 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:419:15 +dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:419:79 +dropping a closure that owns a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:420:13 +dropping `std::iter::Take>`, which is not supported yet at fixtures/reject/src/lib.rs:420:62 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:421:13 +unsupported call to `::add_assign` at fixtures/reject/src/lib.rs:453:2 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:167:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:187:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:221:2 an iterator of the crate implementing `FusedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:241:1 `Hasher::write`, which is not supported yet at fixtures/reject/src/lib.rs:332:9 +dropping a closure that owns a value that drops, which is not supported yet, in `std::option::Option::::map` at fixtures/reject/src/lib.rs:398:12 +dropping a closure that owns a value that drops, which is not supported yet, in `std::result::Result::::map_err` at fixtures/reject/src/lib.rs:402:12 +dropping a closure that owns a value that drops, which is not supported yet, in `std::result::Result::::and_then` at fixtures/reject/src/lib.rs:406:12 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 4c124bc4d..b95c21600 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -390,19 +390,24 @@ pub fn split_chars(s: &str) -> usize { s.split(['a', 'b']).count() } -/// `Option::map` drops its closure on `None`, as `Result::map_err` does on `Ok`, and with -/// it what it captured, which lives in an arrow function. +/// `Option::map` drops its closure on `None`, as `Result::map_err` does on `Ok` and +/// `Result::and_then` on `Err`, and with it what it captured, which lives in an arrow +/// function. pub fn discarded_closure(a: Option, b: Result) -> u8 { - let (m, n) = (Noisy(1), Noisy(2)); + let (m, n, o) = (Noisy(1), Noisy(2), Noisy(3)); let a = a.map(move |x| { drop(m); x }); - let b = b.map_err(move |e| { + let c = b.map_err(move |e| { drop(n); e }); - a.unwrap_or(0) + b.unwrap_or(0) + let d = b.and_then(move |v| { + drop(o); + Ok(v) + }); + a.unwrap_or(0) + c.unwrap_or(0) + d.unwrap_or(0) } /// Each drops its closure, and the `Noisy` it owns, when it is done with it, as diff --git a/ts/fixtures/task/expected/core/option.ts b/ts/fixtures/task/expected/core/option.ts new file mode 100644 index 000000000..ed016ac19 --- /dev/null +++ b/ts/fixtures/task/expected/core/option.ts @@ -0,0 +1,219 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import type * as Key from "../drops.Key.ts"; +import type * as Guard from "../model.Guard.ts"; + +export function isSomeAnd$Option_Guard_options_closure7(self: Guard.Guard | undefined, f: (a0: Guard.Guard) => boolean): boolean { + if (self === undefined) { + return false; + } + return f(self); +} + +export function unwrapOr$Option_Guard(self: Guard.Guard | undefined, default_: Guard.Guard): Guard.Guard { + let _0!: Guard.Guard; + let _5: boolean = false; + _5 = true; + if (self === undefined) { + _5 = false; + _0 = default_; + } else { + _0 = self; + } + if (_5) { + rt.drop(default_); + return _0; + } + return _0; +} + +export function unwrapOr$Option_u64(self: rt.u64 | undefined, default_: rt.u64): rt.u64 { + if (self === undefined) { + return default_; + } + return self; +} + +export function mapOr$Option_Guard_u32_drained_closure4(self: Guard.Guard | undefined, default_: rt.u32, f: (a0: Guard.Guard) => rt.u32): rt.u32 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Key_u32_drained_closure5(self: Key.Key | undefined, default_: rt.u32, f: (a0: Key.Key) => rt.u32): rt.u32 { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_Vec_Guard_usize_collected_closure11(self: Guard.Guard[] | undefined, default_: rt.usize, f: (a0: Guard.Guard[]) => rt.usize): rt.usize { + if (self === undefined) { + return default_; + } + return f(self); +} + +export function mapOr$Option_u32_Guard_options_closure2(self: rt.u32 | undefined, default_: Guard.Guard, f: (a0: rt.u32) => Guard.Guard): Guard.Guard { + let _0!: Guard.Guard; + let _9!: boolean; + let unwind: number = 0; + try { + _9 = false; + _9 = true; + if (self === undefined) { + _9 = false; + _0 = default_; + } else { + unwind = 12; + _0 = f(self); + } + if (_9) { + unwind = 0; + rt.drop(default_); + return _0; + } + return _0; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (_9) { + rt.drop(default_); + } + throw e; + } +} + +export function okOr$Option_Guard_Guard(self: Guard.Guard | undefined, err: Guard.Guard): rt.Result { + let _0!: rt.Result; + let _6: boolean = false; + _6 = true; + if (self === undefined) { + _6 = false; + _0 = rt.Err(err); + } else { + _0 = rt.Ok(self); + } + if (_6) { + rt.drop(err); + return _0; + } + return _0; +} + +export function filter$Option_Guard_options_closure4(self: Guard.Guard | undefined, predicate: (a0: Guard.Guard) => boolean): Guard.Guard | undefined { + let x!: Guard.Guard; + let unwind: number = 0; + try { + if (self !== undefined) { + unwind = 8; + x = self; + if (!predicate(x)) { + unwind = 0; + rt.drop(x); + } else { + return x; + } + } + return undefined; + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(x); + throw e; + } +} + +export function orElse$Option_Guard_options_closure6(self: Guard.Guard | undefined, f: () => Guard.Guard | undefined): Guard.Guard | undefined { + let _0!: Guard.Guard | undefined; + let _7!: boolean; + let unwind: number = 0; + try { + _7 = false; + _7 = true; + if (self === undefined) { + unwind = 12; + _0 = f(); + } else { + _7 = false; + _0 = self; + } + if (_7) { + unwind = 0; + rt.drop(self); + return _0; + } + return _0; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (_7) { + rt.drop(self); + } + throw e; + } +} + +export function zip$Option_Guard_Guard(self: Guard.Guard | undefined, other: Guard.Guard | undefined): [Guard.Guard, Guard.Guard] | undefined { + let _0!: [Guard.Guard, Guard.Guard] | undefined; + let _9!: boolean; + let _10!: boolean; + let unwind: number = 0; + try { + b0: { + _10 = false; + _9 = false; + _9 = true; + _10 = true; + if (self !== undefined) { + if (other !== undefined) { + _10 = false; + const a: Guard.Guard = self; + _9 = false; + _0 = [a, other] as [Guard.Guard, Guard.Guard]; + break b0; + } + } + _0 = undefined; + } + if (self !== undefined) { + if (_10) { + unwind = 7; + rt.drop(self); + } + } + if (other !== undefined) { + if (_9) { + unwind = 0; + rt.drop(other); + } + } + _9 = false; + _10 = false; + return _0; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (other !== undefined) { + if (_9) { + rt.drop(other); + } + } + throw e; + } +} + +export function clone$Clone_Option_Arc_Guard(self: rt.Arc | undefined): rt.Arc | undefined { + if (self === undefined) { + return undefined; + } + return rt.arcClone(self); +} + +//# sourceMappingURL=option.ts.map diff --git a/ts/fixtures/task/expected/core/result.ts b/ts/fixtures/task/expected/core/result.ts new file mode 100644 index 000000000..7c3d3e2ea --- /dev/null +++ b/ts/fixtures/task/expected/core/result.ts @@ -0,0 +1,106 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../rt.ts"; +import { drop$Result_Guard_Guard, drop$Result_u8_Key } from "../lib.ts"; +import type * as Key from "../drops.Key.ts"; +import type * as Guard from "../model.Guard.ts"; + +export function ok$Result_Guard_Guard(self: rt.Result): Guard.Guard | undefined { + let _0!: Guard.Guard | undefined; + if (self.ok) { + _0 = self.value; + } else { + _0 = undefined; + } + if (!self.ok) { + drop$Result_Guard_Guard(self); + return _0; + } + return _0; +} + +export function err$Result_Guard_Guard(self: rt.Result): Guard.Guard | undefined { + let _0!: Guard.Guard | undefined; + if (self.ok) { + _0 = undefined; + } else { + _0 = self.error; + } + if (self.ok) { + drop$Result_Guard_Guard(self); + return _0; + } + return _0; +} + +export function mapOrElse$Result_Guard_Guard_u32_options_closure9_options_closure10(self: rt.Result, default_: (a0: Guard.Guard) => rt.u32, f: (a0: Guard.Guard) => rt.u32): rt.u32 { + if (self.ok) { + return f(self.value); + } + return default_(self.error); +} + +export function inspectErr$Result_u8_Key_tripped_closure6(self: rt.Result, f: (a0: Key.Key) => void): rt.Result { + let _9!: boolean; + let unwind: number = 0; + try { + _9 = false; + _9 = true; + if (!self.ok) { + unwind = 8; + f(self.error); + } + _9 = false; + return self; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (_9) { + drop$Result_u8_Key(self); + } + throw e; + } +} + +export function andThen$Result_Guard_Guard_Guard_options_closure8(self: rt.Result, op: (a0: Guard.Guard) => rt.Result): rt.Result { + if (self.ok) { + return op(self.value); + } + return self; +} + +export function unwrapOr$Result_Guard_Guard(self: rt.Result, default_: Guard.Guard): Guard.Guard { + let _0!: Guard.Guard; + let unwind: number = 0; + try { + let _5: boolean = false; + _5 = true; + if (self.ok) { + _0 = self.value; + } else { + _5 = false; + _0 = default_; + } + if (_5) { + unwind = 7; + rt.drop(default_); + } + if (!self.ok) { + unwind = 0; + drop$Result_Guard_Guard(self); + return _0; + } + return _0; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (!self.ok) { + drop$Result_Guard_Guard(self); + } + throw e; + } +} + +//# sourceMappingURL=result.ts.map diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 8a16837c3..7cced3029 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -1,7 +1,9 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Bomb_Guard, drop$Guard_Entries_Bomb_Guard_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; +import { drop$Arc_Wrap_Pair_Held, drop$Arc_str_Arc_str, drop$Bomb_Guard, drop$Guard_Entries_Bomb_Guard_Held, drop$Held, drop$Mutex_Held, drop$Option_Box_Held, drop$Option_Guard_Guard, drop$Option_Held, drop$Pair_Held, drop$Result_Guard_Guard, drop$Result_u8_Key, drop$Wrap_Arc_Held, drop$Wrap_Guard, drop$Wrap_Held, drop$Wrap_Pair_Held, drop$Wrap_Vec_Wrap_Held } from "./lib.ts"; +import { isSomeAnd$Option_Guard_options_closure7, unwrapOr$Option_Guard, unwrapOr$Option_u64, mapOr$Option_u32_Guard_options_closure2, okOr$Option_Guard_Guard, filter$Option_Guard_options_closure4, orElse$Option_Guard_options_closure6, zip$Option_Guard_Guard, clone$Clone_Option_Arc_Guard } from "./core/option.ts"; +import { ok$Result_Guard_Guard, err$Result_Guard_Guard, mapOrElse$Result_Guard_Guard_u32_options_closure9_options_closure10, inspectErr$Result_u8_Key_tripped_closure6, andThen$Result_Guard_Guard_Guard_options_closure8, unwrapOr$Result_Guard_Guard } from "./core/result.ts"; import { looped, collected, drained, extended, bombed, spent } from "./drops/iters.ts"; import * as Bomb from "./drops.Bomb.ts"; import * as Entries from "./drops.Entries.ts"; @@ -757,7 +759,7 @@ export class heldFuture { unwind = 43; const result: rt.u64 | undefined = _36; rt.drop(this.#awaitee); - const value: rt.u64 = rt.optionUnwrapOr(result, 0); + const value: rt.u64 = unwrapOr$Option_u64(result, 0); const _51: rt.usize = this.#held.length; const _54: boolean = Held.isSome(this.#wrap.inner.value); const arg = this.#id; @@ -1607,63 +1609,74 @@ export function options(log: Log.Log, id: rt.u32, at: rt.u8): void { let unmapped!: Guard.Guard; let then!: Guard.Guard | undefined; let never!: Guard.Guard | undefined; - let _213!: boolean; - let _214!: boolean; - let _215!: boolean; - let _216!: boolean; - let _217!: boolean; - let _218!: boolean; + let kept2!: Guard.Guard | undefined; + let dropped!: Guard.Guard | undefined; + let zipped!: [Guard.Guard, Guard.Guard] | undefined; + let _213!: Guard.Guard | undefined; + let _217!: Guard.Guard | undefined; + let other!: Guard.Guard | undefined; + let chained!: rt.Result; + let cloned!: rt.Arc | undefined; + let _275!: rt.Arc | undefined; + let _319!: boolean; + let _320!: boolean; + let _321!: boolean; + let _322!: boolean; + let _323!: boolean; + let _324!: boolean; + let _325!: boolean; let unwind: number = 0; try { - _218 = false; - _217 = false; - _216 = false; - _215 = false; - _214 = false; - _213 = false; + _325 = false; + _324 = false; + _323 = false; + _322 = false; + _321 = false; + _320 = false; + _319 = false; const guard: (a0: rt.u32) => Guard.Guard = (n: rt.u32): Guard.Guard => { return Guard.new(rt.u32Add(id, n), Log.clone$Clone(log)); }; const check: (a0: rt.u8) => void = (point: rt.u8): void => { if (point === at) { - const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; - rt.panicFmt(["d", args12[0], " at ", args12[1]]); + const args16: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(id, f), (f: rt.Formatter) => rt.u8Display(point, f)]; + rt.panicFmt(["d", args16[0], " at ", args16[1]]); } }; const _11: Guard.Guard = guard(1); - unwind = 126; - _218 = true; + unwind = 185; + _325 = true; _10 = _11; const _14: Guard.Guard = guard(2); - _218 = false; - some = rt.optionOkOr(_10, _14, rt.drop); - _218 = false; + _325 = false; + some = okOr$Option_Guard_Guard(_10, _14); + _325 = false; if (!(at > 8)) { - _217 = true; + _324 = true; _18 = undefined as Guard.Guard | undefined; } else { - unwind = 113; + unwind = 170; const _20: Guard.Guard = guard(0); - _217 = true; + _324 = true; _18 = _20; } - unwind = 124; + unwind = 183; const _23: Guard.Guard = guard(3); - _217 = false; - none = rt.optionOkOr(_18, _23, rt.drop); - unwind = 112; - _217 = false; + _324 = false; + none = okOr$Option_Guard_Guard(_18, _23); + unwind = 169; + _324 = false; const _32: boolean = some.ok; const _35: boolean = none.ok; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_32, f), (f: rt.Formatter) => rt.fmtBool(_35, f)]; Log.note(log, rt.fmtFormat(["ok_or ", args2[0], " ", args2[1]])); check(1); - ok = rt.resultOk(rt.Ok(guard(4)), rt.drop); - unwind = 111; - err = rt.resultOk(rt.Err(guard(5)), rt.drop); - unwind = 110; - flipped = rt.resultErr(rt.Ok(guard(6)), rt.drop); - unwind = 109; + ok = ok$Result_Guard_Guard(rt.Ok(guard(4))); + unwind = 168; + err = ok$Result_Guard_Guard(rt.Err(guard(5))); + unwind = 167; + flipped = err$Result_Guard_Guard(rt.Ok(guard(6))); + unwind = 166; const _66: boolean = ok !== undefined; const _69: boolean = err !== undefined; const _72: boolean = flipped !== undefined; @@ -1671,39 +1684,39 @@ export function options(log: Log.Log, id: rt.u32, at: rt.u8): void { Log.note(log, rt.fmtFormat(["ok ", args4[0], " ", args4[1], " ", args4[2]])); check(2); const _85: Guard.Guard = guard(7); - unwind = 122; - _216 = true; + unwind = 181; + _323 = true; _84 = _85; const _88: Guard.Guard = guard(8); - _216 = false; - kept = rt.optionUnwrapOr(_84, _88, rt.drop); - unwind = 120; - _216 = false; - _215 = true; + _323 = false; + kept = unwrapOr$Option_Guard(_84, _88); + unwind = 179; + _323 = false; + _322 = true; _92 = undefined as Guard.Guard | undefined; const _93: Guard.Guard = guard(9); - _215 = false; - fallback = rt.optionUnwrapOr(_92, _93, rt.drop); - unwind = 107; - _215 = false; + _322 = false; + fallback = unwrapOr$Option_Guard(_92, _93); + unwind = 164; + _322 = false; const _98: Guard.Guard = guard(10); - unwind = 118; - _214 = true; + unwind = 177; + _321 = true; _97 = rt.Ok(_98); const _101: Guard.Guard = guard(11); - _214 = false; - value = rt.resultUnwrapOr(_97, _101, rt.drop, rt.drop); - unwind = 106; - _214 = false; + _321 = false; + value = unwrapOr$Result_Guard_Guard(_97, _101); + unwind = 163; + _321 = false; const _106: Guard.Guard = guard(12); - unwind = 116; - _213 = true; + unwind = 175; + _320 = true; _105 = rt.Err(_106); const _109: Guard.Guard = guard(13); - _213 = false; - error = rt.resultUnwrapOr(_105, _109, rt.drop, rt.drop); - unwind = 105; - _213 = false; + _320 = false; + error = unwrapOr$Result_Guard_Guard(_105, _109); + unwind = 162; + _320 = false; const _118: rt.u32 = Guard.id(kept); const _121: rt.u32 = Guard.id(fallback); const _124: rt.u32 = Guard.id(value); @@ -1711,147 +1724,309 @@ export function options(log: Log.Log, id: rt.u32, at: rt.u8): void { const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_118, f), (f: rt.Formatter) => rt.u32Display(_121, f), (f: rt.Formatter) => rt.u32Display(_124, f), (f: rt.Formatter) => rt.u32Display(_127, f)]; Log.note(log, rt.fmtFormat(["unwrap_or ", args6[0], " ", args6[1], " ", args6[2], " ", args6[3]])); check(3); - mapped = rt.optionMapOr(id, guard(14), (n2: rt.u32): Guard.Guard => { + mapped = mapOr$Option_u32_Guard_options_closure2(id, guard(14), (n2: rt.u32): Guard.Guard => { Log.note(log, rt.fmtFormat(["mapped"])); return Guard.new(rt.u32Add(n2, 15), Log.clone$Clone(log)); - }, rt.drop); - unwind = 104; - unmapped = rt.optionMapOr(undefined as rt.u32 | undefined, guard(16), (n3: rt.u32): Guard.Guard => { + }); + unwind = 161; + unmapped = mapOr$Option_u32_Guard_options_closure2(undefined as rt.u32 | undefined, guard(16), (n3: rt.u32): Guard.Guard => { return Guard.new(n3, Log.clone$Clone(log)); - }, rt.drop); - unwind = 103; + }); + unwind = 160; const _157: rt.u32 = Guard.id(mapped); const _160: rt.u32 = Guard.id(unmapped); const args8: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(_157, f), (f: rt.Formatter) => rt.u32Display(_160, f)]; Log.note(log, rt.fmtFormat(["map_or ", args8[0], " ", args8[1]])); check(4); then = rt.thenSome(rt.u8Rem(at, 2) === 0, guard(17), rt.drop); - unwind = 102; + unwind = 159; never = rt.thenSome(false, guard(18), rt.drop); - unwind = 101; + unwind = 158; const _187: boolean = then !== undefined; const _190: boolean = never !== undefined; const args10: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_187, f), (f: rt.Formatter) => rt.fmtBool(_190, f)]; Log.note(log, rt.fmtFormat(["then_some ", args10[0], " ", args10[1]])); check(5); - unwind = 102; + kept2 = filter$Option_Guard_options_closure4(guard(19), (g: Guard.Guard): boolean => { + check(6); + return rt.u32Rem(Guard.id(g), 2) === 0; + }); + unwind = 157; + dropped = filter$Option_Guard_options_closure4(guard(20), (_2: Guard.Guard): boolean => { + return false; + }); + unwind = 156; + const _214: Guard.Guard = guard(21); + unwind = 173; + _319 = true; + _213 = _214; + if (!(rt.u8Rem(at, 2) === 0)) { + _217 = undefined as Guard.Guard | undefined; + } else { + _217 = guard(22); + } + _319 = false; + zipped = zip$Option_Guard_Guard(_213, _217); + unwind = 155; + _319 = false; + other = orElse$Option_Guard_options_closure6(undefined as Guard.Guard | undefined, (): Guard.Guard | undefined => { + return guard(23); + }); + unwind = 154; + const flag: boolean = isSomeAnd$Option_Guard_options_closure7(guard(24), (g2: Guard.Guard): boolean => { + let unwind2: number = 0; + try { + unwind2 = 4; + const _37: rt.u32 = Guard.id(g2); + unwind2 = 0; + const _06: boolean = _37 > id; + rt.drop(g2); + return _06; + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + rt.drop(g2); + throw e2; + } + }); + const _241: boolean = kept2 !== undefined; + const _244: boolean = dropped !== undefined; + const _247: boolean = zipped !== undefined; + const _250: boolean = other !== undefined; + const args12: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_241, f), (f: rt.Formatter) => rt.fmtBool(_244, f), (f: rt.Formatter) => rt.fmtBool(_247, f), (f: rt.Formatter) => rt.fmtBool(_250, f), (f: rt.Formatter) => rt.fmtBool(flag, f)]; + Log.note(log, rt.fmtFormat(["filter ", args12[0], " ", args12[1], " zip ", args12[2], " or_else ", args12[3], " is_some_and ", args12[4]])); + chained = andThen$Result_Guard_Guard_Guard_options_closure8(rt.Ok(guard(25)), (g3: Guard.Guard): rt.Result => { + let unwind3: number = 0; + try { + unwind3 = 3; + check(7); + return rt.Err(g3); + } catch (e3) { + if (unwind3 === 0) { + throw e3; + } + rt.drop(g3); + throw e3; + } + }); + unwind = 153; + const error2: rt.u32 = mapOrElse$Result_Guard_Guard_u32_options_closure9_options_closure10(rt.Err(guard(26)), (e4: Guard.Guard): rt.u32 => { + let unwind4: number = 0; + try { + unwind4 = 4; + const _08: rt.u32 = Guard.id(e4); + unwind4 = 0; + rt.drop(e4); + return _08; + } catch (e5) { + if (unwind4 === 0) { + throw e5; + } + rt.drop(e4); + throw e5; + } + }, (v: Guard.Guard): rt.u32 => { + let unwind5: number = 0; + try { + unwind5 = 4; + const _09: rt.u32 = Guard.id(v); + unwind5 = 0; + rt.drop(v); + return _09; + } catch (e6) { + if (unwind5 === 0) { + throw e6; + } + rt.drop(v); + throw e6; + } + }); + const _276: rt.Arc = new rt.Arc(guard(27)); + unwind = 152; + _275 = _276; + cloned = clone$Clone_Option_Arc_Guard(_275); + unwind = 151; + rt.drop(_275); + const _286: boolean = chained.ok; + const _289: boolean = cloned !== undefined; + const args14: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_286, f), (f: rt.Formatter) => rt.u32Display(error2, f), (f: rt.Formatter) => rt.fmtBool(_289, f)]; + Log.note(log, rt.fmtFormat(["and_then ", args14[0], " map_or_else ", args14[1], " clone ", args14[2]])); + unwind = 153; + rt.drop(cloned); + unwind = 154; + drop$Result_Guard_Guard(chained); + unwind = 155; + rt.drop(other); + unwind = 156; + drop$Option_Guard_Guard(zipped); + unwind = 157; + rt.drop(dropped); + unwind = 158; + rt.drop(kept2); + unwind = 159; rt.drop(never); - unwind = 103; + unwind = 160; rt.drop(then); - unwind = 104; + unwind = 161; rt.drop(unmapped); - unwind = 105; + unwind = 162; rt.drop(mapped); - unwind = 106; + unwind = 163; rt.drop(error); - unwind = 107; + unwind = 164; rt.drop(value); - unwind = 108; + unwind = 165; rt.drop(fallback); - unwind = 109; + unwind = 166; rt.drop(kept); - unwind = 110; + unwind = 167; rt.drop(flipped); - unwind = 111; + unwind = 168; rt.drop(err); - unwind = 112; + unwind = 169; rt.drop(ok); - unwind = 113; + unwind = 170; drop$Result_Guard_Guard(none); unwind = 0; drop$Result_Guard_Guard(some); } catch (e) { - b1: { - b2: { - b3: { - b4: { - b5: { - b6: { - b7: { - b8: { - b9: { - b10: { - b11: { - b12: { - if (unwind === 0) { - throw e; - } - if (unwind === 101) { - rt.drop(never); - } else if (unwind !== 102) { - if (unwind === 103) { - break b12; - } - if (unwind === 104) { - break b11; - } - if (unwind === 105) { - break b10; - } - if (unwind === 106) { - break b9; - } - if (unwind === 107) { - break b8; - } - if (unwind === 108) { - break b7; - } - if (unwind === 109) { - break b6; - } - if (unwind === 110) { - break b5; - } - if (unwind === 111) { - break b4; - } - if (unwind === 112) { - break b3; - } - if (unwind === 113) { - break b2; - } - if (unwind === 116) { - if (!_213) { - break b9; - } - drop$Result_Guard_Guard(_105); - break b9; - } - if (unwind === 118) { - if (!_214) { - break b8; - } - drop$Result_Guard_Guard(_97); - break b8; - } - if (unwind === 120) { - if (!_215) { - break b7; - } - rt.drop(_92); - break b7; - } - if (unwind === 122) { - if (!_216) { - break b6; - } - rt.drop(_84); - break b6; - } - if (unwind === 124) { - if (!_217) { - break b2; + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + b15: { + b16: { + b17: { + b18: { + b19: { + if (unwind === 0) { + throw e; + } + if (unwind === 151) { + rt.drop(cloned); + } else if (unwind === 152) { + rt.drop(_275); + } else if (unwind !== 153) { + if (unwind === 154) { + break b19; + } + if (unwind === 155) { + break b18; + } + if (unwind === 156) { + break b17; + } + if (unwind === 157) { + break b16; + } + if (unwind === 158) { + break b15; + } + if (unwind === 159) { + break b14; + } + if (unwind === 160) { + break b13; + } + if (unwind === 161) { + break b12; + } + if (unwind === 162) { + break b11; + } + if (unwind === 163) { + break b10; + } + if (unwind === 164) { + break b9; + } + if (unwind === 165) { + break b8; + } + if (unwind === 166) { + break b7; + } + if (unwind === 167) { + break b6; + } + if (unwind === 168) { + break b5; + } + if (unwind === 169) { + break b4; + } + if (unwind === 170) { + break b3; + } + if (unwind === 173) { + if (!_319) { + break b17; + } + rt.drop(_213); + break b17; + } + if (unwind === 175) { + if (!_320) { + break b10; + } + drop$Result_Guard_Guard(_105); + break b10; + } + if (unwind === 177) { + if (!_321) { + break b9; + } + drop$Result_Guard_Guard(_97); + break b9; + } + if (unwind === 179) { + if (!_322) { + break b8; + } + rt.drop(_92); + break b8; + } + if (unwind === 181) { + if (!_323) { + break b7; + } + rt.drop(_84); + break b7; + } + if (unwind === 183) { + if (!_324) { + break b3; + } + rt.drop(_18); + break b3; + } + if (!_325) { + break b2; + } + rt.drop(_10); + break b2; + } + drop$Result_Guard_Guard(chained); + } + rt.drop(other); + } + drop$Option_Guard_Guard(zipped); + } + rt.drop(dropped); } - rt.drop(_18); - break b2; - } - if (!_218) { - break b1; + rt.drop(kept2); } - rt.drop(_10); - break b1; + rt.drop(never); } rt.drop(then); } @@ -2561,10 +2736,10 @@ export function tripped(log: Log.Log, id: rt.u32, at: rt.u8, tree: boolean): voi _155 = false; rt.drop(_109); } else { - rt.drop(rt.optionMapOr(id, guard(3), (n4: rt.u32): Guard.Guard => { + rt.drop(mapOr$Option_u32_Guard_options_closure2(id, guard(3), (n4: rt.u32): Guard.Guard => { const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(n4, f)]; rt.panicFmt(["d", args4[0], " mapped"]); - }, rt.drop)); + })); } } else if (at === 5) { if (!tree) { @@ -2574,11 +2749,11 @@ export function tripped(log: Log.Log, id: rt.u32, at: rt.u8, tree: boolean): voi } } else if (at === 6) { if (!tree) { - drop$Result_u8_Key(rt.resultInspectErr(rt.Err(key(3)), (k: Key.Key): void => { + drop$Result_u8_Key(inspectErr$Result_u8_Key_tripped_closure6(rt.Err(key(3)), (k: Key.Key): void => { const arg = k.id; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(arg, f)]; rt.panicFmt(["k", args2[0], " inspected"]); - }, rt.drop)); + })); } else { rt.resultUnwrapErr(rt.Ok(key(3)), (value: Key.Key, f: rt.Formatter) => Key.fmt$Debug(value, f), rt.drop); } diff --git a/ts/fixtures/task/expected/drops/iters.ts b/ts/fixtures/task/expected/drops/iters.ts index 957b79b8c..da21180eb 100644 --- a/ts/fixtures/task/expected/drops/iters.ts +++ b/ts/fixtures/task/expected/drops/iters.ts @@ -2,6 +2,7 @@ import * as rt from "../rt.ts"; import { drop$Guard_Guard, drop$Guard_u32, drop$Key_Guard, drop$Option_Key_Guard, drop$Option_u32_Bomb, drop$Result_Vec_Guard_Guard, drop$Vec_Bomb, drop$Vec_Guard, drop$u32_Bomb, drop$u32_First, drop$u32_Guard } from "../lib.ts"; +import { mapOr$Option_Guard_u32_drained_closure4, mapOr$Option_Key_u32_drained_closure5, mapOr$Option_Vec_Guard_usize_collected_closure11 } from "../core/option.ts"; import * as Count from "../drops/iters.Count.ts"; import * as First from "../drops/iters.First.ts"; import * as Bomb from "../drops.Bomb.ts"; @@ -199,7 +200,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { rest = rt.ownedTake(rt.ownedSkip(rt.iterSlice(v3, rt.drop), 1, rt.drop), 3, rt.drop); unwind = 356; _610 = true; - const part4 = rt.optionMapOr(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { + const part4 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(rest.next()), 0, (g5: Guard.Guard): rt.u32 => { let unwind2: number = 0; try { unwind2 = 4; @@ -299,7 +300,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _606 = true; rt.drop(_275); _606 = false; - const part7 = rt.optionMapOr(nth, 0, (g8: Guard.Guard): rt.u32 => { + const part7 = mapOr$Option_Guard_u32_drained_closure4(nth, 0, (g8: Guard.Guard): rt.u32 => { let unwind3: number = 0; try { unwind3 = 4; @@ -350,7 +351,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 314; rt.drop(_333); _605 = false; - const _366: rt.u32 = rt.optionMapOr(best, 0, (g11: Guard.Guard): rt.u32 => { + const _366: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(best, 0, (g11: Guard.Guard): rt.u32 => { let unwind4: number = 0; try { unwind4 = 4; @@ -407,7 +408,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { const _418: Guard.Guard = guard(38); v12.push(_418); unwind = 314; - const _427: rt.u32 = rt.optionMapOr(rt.ownedLast(rt.ownedStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { + const _427: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedLast(rt.ownedStepBy(rt.iterSlice(v12, rt.drop), 2, rt.drop), rt.drop, rt.drop), 0, (g13: Guard.Guard): rt.u32 => { let unwind6: number = 0; try { unwind6 = 4; @@ -453,7 +454,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { flat = rt.iterFlatten(rt.iterSlice(v13, drop$Vec_Guard), (value: Guard.Guard[]) => rt.iterSlice(value, rt.drop), true); unwind = 344; _604 = true; - const front: rt.u32 = rt.optionMapOr(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { + const front: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(flat.next()), 0, (g14: Guard.Guard): rt.u32 => { let unwind7: number = 0; try { unwind7 = 4; @@ -469,7 +470,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { throw e7; } }); - const back: rt.u32 = rt.optionMapOr(rt.iterToOption(flat.nextBack()), 0, (g15: Guard.Guard): rt.u32 => { + const back: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(flat.nextBack()), 0, (g15: Guard.Guard): rt.u32 => { let unwind8: number = 0; try { unwind8 = 4; @@ -525,7 +526,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(_501); _509 = rt.ownedStepBy(rt.iterSlice(five(49), rt.drop), 2, rt.drop); unwind = 305; - const stepped: rt.u32 = rt.optionMapOr(rt.ownedNthBack(_509, 1, rt.drop), 0, (g16: Guard.Guard): rt.u32 => { + const stepped: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNthBack(_509, 1, rt.drop), 0, (g16: Guard.Guard): rt.u32 => { let unwind10: number = 0; try { unwind10 = 4; @@ -551,7 +552,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _517 = rt.iterChain(_518, rt.iterSlice(_524, rt.drop)); unwind = 304; _603 = false; - const taken: rt.u32 = rt.optionMapOr(rt.ownedNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { + const taken: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_517, 1, rt.drop), 0, (g17: Guard.Guard): rt.u32 => { let unwind11: number = 0; try { unwind11 = 4; @@ -577,7 +578,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { _528 = rt.iterChain(_529, rt.iterSlice(_535, rt.drop)); unwind = 303; _602 = false; - const passed: rt.u32 = rt.optionMapOr(rt.ownedNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { + const passed: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_528, 2, rt.drop), 0, (g18: Guard.Guard): rt.u32 => { let unwind12: number = 0; try { unwind12 = 4; @@ -597,7 +598,7 @@ export function looped(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(_528); _539 = rt.ownedStepBy(rt.iterRev(rt.iterSlice(five(69), rt.drop)), 2, rt.drop); unwind = 302; - const strode: rt.u32 = rt.optionMapOr(rt.ownedNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { + const strode: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.ownedNth(_539, 2, rt.drop), 0, (g19: Guard.Guard): rt.u32 => { let unwind13: number = 0; try { unwind13 = 4; @@ -1060,7 +1061,7 @@ export function collected(log: Log.Log, id: rt.u32, at: rt.u8): void { const _156: Guard.Guard = guard(15); v6.push(_156); unwind = 168; - const part2 = rt.optionMapOr(rt.iterCollectOption(rt.iterMap(rt.iterSlice(v6, rt.drop), (g5: Guard.Guard): Guard.Guard | undefined => { + const part2 = mapOr$Option_Vec_Guard_usize_collected_closure11(rt.iterCollectOption(rt.iterMap(rt.iterSlice(v6, rt.drop), (g5: Guard.Guard): Guard.Guard | undefined => { let unwind6: number = 0; try { unwind6 = 6; @@ -1467,7 +1468,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { unwind = 180; _299 = true; const _49: rt.usize = keys.length; - const _52: rt.u32 = rt.optionMapOr(rt.iterToOption(values.next()), 0, (g: Guard.Guard): rt.u32 => { + const _52: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(values.next()), 0, (g: Guard.Guard): rt.u32 => { let unwind3: number = 0; try { unwind3 = 4; @@ -1498,7 +1499,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { _298 = false; _85 = rt.btreeKeys(set, rt.drop); unwind = 158; - const part = rt.optionMapOr(rt.iterToOption(_85.next()), 0, (k: Key.Key): rt.u32 => { + const part = mapOr$Option_Key_u32_drained_closure5(rt.iterToOption(_85.next()), 0, (k: Key.Key): rt.u32 => { const _05: rt.u32 = k.id; rt.drop(k); return _05; @@ -1520,7 +1521,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { range = rt.dequeDrain(queue, new rt.Range(1, 4), rt.drop); unwind = 174; _296 = true; - const part2 = rt.optionMapOr(rt.iterToOption(range.next()), 0, (g2: Guard.Guard): rt.u32 => { + const part2 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(range.next()), 0, (g2: Guard.Guard): rt.u32 => { let unwind4: number = 0; try { unwind4 = 4; @@ -1545,7 +1546,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { _297 = false; _137 = rt.dequeIter(queue, rt.drop); unwind = 157; - const _134: rt.u32 = rt.optionMapOr(rt.iterToOption(_137.next()), 0, (g3: Guard.Guard): rt.u32 => { + const _134: rt.u32 = mapOr$Option_Guard_u32_drained_closure4(rt.iterToOption(_137.next()), 0, (g3: Guard.Guard): rt.u32 => { let unwind5: number = 0; try { unwind5 = 4; @@ -1612,7 +1613,7 @@ export function drained(log: Log.Log, id: rt.u32, at: rt.u8): void { taken = rt.hashDrainKeys(set2, rt.drop); unwind = 152; check(6); - const part5 = rt.optionMapOr(rt.iterToOption(taken.next()), 0, (k2: Key.Key): rt.u32 => { + const part5 = mapOr$Option_Key_u32_drained_closure5(rt.iterToOption(taken.next()), 0, (k2: Key.Key): rt.u32 => { const _08: rt.u32 = k2.id; rt.drop(k2); return _08; diff --git a/ts/fixtures/task/expected/lib.ts b/ts/fixtures/task/expected/lib.ts index 3acc1c90d..be2d4be3a 100644 --- a/ts/fixtures/task/expected/lib.ts +++ b/ts/fixtures/task/expected/lib.ts @@ -145,6 +145,12 @@ export function drop$Option_Box_Held(_1: Held.Held | undefined): void { } } +export function drop$Option_Guard_Guard(_1: [Guard.Guard, Guard.Guard] | undefined): void { + if (_1 !== undefined) { + drop$Guard_Guard(_1); + } +} + export function drop$Option_Held(_1: Held.Held | undefined): void { if (_1 !== undefined) { drop$Held(_1); diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index bad498315..b04594cca 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -2,6 +2,7 @@ import * as rt from "./rt.ts"; import { copy$Tally, drop$ControlFlow_Guard_u32, drop$Result_u32_Guard } from "./lib.ts"; +import { unwrapOr$Option_u64 } from "./core/option.ts"; import { recvFuture } from "./kio.ts"; import type * as Consumer from "./kio.Consumer.ts"; import * as Log from "./log.Log.ts"; @@ -1152,7 +1153,7 @@ export class blocksFuture$8 { /** `v`, or 0, plus the id of `guard`, which it drops. */ export function consume(guard: Guard.Guard, v: rt.u64 | undefined): rt.u64 { - return rt.u64Add(Guard.finish(guard, "consumed") as rt.u64, rt.optionUnwrapOr(v, 0)); + return rt.u64Add(Guard.finish(guard, "consumed") as rt.u64, unwrapOr$Option_u64(v, 0)); } export class slotFuture { diff --git a/ts/fixtures/task/src/drops.rs b/ts/fixtures/task/src/drops.rs index 621e7caa8..d6b637a91 100644 --- a/ts/fixtures/task/src/drops.rs +++ b/ts/fixtures/task/src/drops.rs @@ -500,6 +500,33 @@ fn options(log: &Log, id: u32, at: u8) { let never = false.then_some(guard(18)); log.note(format!("then_some {} {}", then.is_some(), never.is_some())); check(5); + // Lowered from core's MIR, whose cleanups drop what a panic in a closure leaves. + let kept = Some(guard(19)).filter(|g| { + check(6); + g.id() % 2 == 0 + }); + let dropped = Some(guard(20)).filter(|_| false); + let zipped = Some(guard(21)).zip(if at % 2 == 0 { Some(guard(22)) } else { None }); + let other = None.or_else(|| Some(guard(23))); + let flag = Some(guard(24)).is_some_and(|g| g.id() > id); + log.note(format!( + "filter {} {} zip {} or_else {} is_some_and {flag}", + kept.is_some(), + dropped.is_some(), + zipped.is_some(), + other.is_some() + )); + let chained = Ok::(guard(25)).and_then(|g| { + check(7); + Err::(g) + }); + let error = Err::(guard(26)).map_or_else(|e| e.id(), |v| v.id()); + let cloned = Some(Arc::new(guard(27))).clone(); + log.note(format!( + "and_then {} map_or_else {error} clone {}", + chained.is_ok(), + cloned.is_some() + )); } /// What maps keyed by `Arc` drop of the keys they are given or hold, and `max` and diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 9dcce522e..541f427b7 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -107,57 +107,6 @@ function unwrapFailed(message: string, value: T, debug: Debug, drop?: (val // drops it, and drops it where std's does: as it returns, after any closure it calls, or // as a panic in that closure unwinds. -/** `Result::ok`: the value, or `undefined` for an error, which drops. */ -export function resultOk(r: Result, drop?: (error: E) => void): T | undefined { - if (r.ok) return r.value; - drop?.(r.error); - return undefined; -} - -/** `Result::err`: the error, or `undefined` for a value, which drops. */ -export function resultErr(r: Result, drop?: (value: T) => void): E | undefined { - if (!r.ok) return r.error; - drop?.(r.value); - return undefined; -} - -/** `Result::map`. */ -export function resultMap(r: Result, f: (value: T) => U): Result { - return r.ok ? Ok(f(r.value)) : r; -} - -/** `Result::map_err`. */ -export function resultMapErr(r: Result, f: (error: E) => F): Result { - return r.ok ? r : Err(f(r.error)); -} - -/** `Result::and_then`. */ -export function resultAndThen(r: Result, f: (value: T) => Result): Result { - return r.ok ? f(r.value) : r; -} - -/** `Result::inspect_err`, whose error drops if `f` panics. */ -export function resultInspectErr(r: Result, f: (error: E) => void, drop?: (error: E) => void): Result { - if (r.ok) return r; - try { - f(r.error); - } catch (e) { - drop?.(r.error); - throw e; - } - return r; -} - -/** `Result::unwrap_or`: the value, and the fallback drops, or else the fallback, and the error drops. */ -export function resultUnwrapOr(r: Result, fallback: T, value?: (value: T) => void, error?: (error: E) => void): T { - if (r.ok) { - value?.(fallback); - return r.value; - } - error?.(r.error); - return fallback; -} - /** `unwrap`, which shows the error with `debug`, and drops it as the panic unwinds. */ export function resultUnwrap(r: Result, debug: Debug, drop?: (error: E) => void): T { if (!r.ok) unwrapFailed("called `Result::unwrap()` on an `Err` value", r.error, debug, drop); @@ -178,41 +127,6 @@ export function resultUnwrapErr(r: Result, debug: Debug, drop?: ( // Options, which are `T | undefined`. -/** `Option::map`. */ -export function optionMap(o: T | undefined, f: (value: T) => U): U | undefined { - return o === undefined ? undefined : f(o); -} - -/** `Option::unwrap_or`: the value, and the fallback drops, or else the fallback. */ -export function optionUnwrapOr(o: T | undefined, fallback: T, drop?: (value: T) => void): T { - if (o === undefined) return fallback; - drop?.(fallback); - return o; -} - -// `f` decides `U`, since a literal fallback would infer a literal type. -/** `Option::map_or`: `f` of the value, and the fallback drops, or else the fallback, and `f` drops. */ -export function optionMapOr(o: T | undefined, fallback: NoInfer, f: (value: T) => U, drop?: (value: U) => void, dropF?: (f: (value: T) => U) => void): U { - if (o === undefined) { - dropF?.(f); - return fallback; - } - let mapped: U; - try { - mapped = f(o); - } finally { - drop?.(fallback); - } - return mapped; -} - -/** `Option::ok_or`: the value, and the error drops, or else the error. */ -export function optionOkOr(o: T | undefined, error: E, drop?: (error: E) => void): Result { - if (o === undefined) return Err(error); - drop?.(error); - return Ok(o); -} - /** `Option::unwrap`: the value, or a panic. */ export function optionUnwrap(o: T | undefined): T { if (o === undefined) panic("called `Option::unwrap()` on a `None` value"); diff --git a/ts/src/cli.rs b/ts/src/cli.rs index bba1152c9..34f93b681 100644 --- a/ts/src/cli.rs +++ b/ts/src/cli.rs @@ -38,14 +38,37 @@ fn try_run(args: &[String]) -> Result { Output::Dir(out) => (config::env::OUT, out.as_os_str()), Output::Census(census) => (config::env::CENSUS, census.as_os_str()), }; - let env = [(config::env::CONFIG, args.config.as_os_str()), output]; + // `cargo clean` reads the profiles too. + let env = [ + (config::env::CONFIG, args.config.as_os_str()), + output, + ("CARGO_UNSTABLE_PROFILE_RUSTFLAGS", "true".as_ref()), + ]; + let mut cargo = std_from_source(); + cargo.extend(args.cargo); Check { tool: "rust2-ts", manifest: &args.manifest, package: &config.package, target: Some(TARGET), - args: &args.cargo, + args: &cargo, env: &env, } .run() } + +/// Cargo args that build std from source, unwinding and with every function's MIR, so +/// the bodies of std's combinators lower as the crate's do, cleanups included: the +/// target's prebuilt std aborts, so its MIR has none. Set through the profile, which +/// cargo's fingerprint sees. `panic_abort` keeps aborting, since a `cdylib` dependency +/// links it. +fn std_from_source() -> Vec { + let mut args = vec!["-Zbuild-std=core,alloc,std,panic_unwind,panic_abort".to_string()]; + for krate in ["core", "alloc", "std"] { + args.push("--config".into()); + args.push(format!( + "profile.dev.package.{krate}.rustflags=[\"-Cpanic=unwind\", \"-Zalways-encode-mir\"]" + )); + } + args +} diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 10700c699..95f8cfb92 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -108,14 +108,14 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { return future.member("poll").call(values); } if let ty::InstanceKind::Item(did) = instance.def - && did.is_local() + && self.t.lowers(instance) { let values: Vec = args.into_iter().map(Expr::typed).collect(); // An `async fn` that only makes its future: the future, made here. if let Some(class) = super::mir::coroutine::of_async_fn(self.t, instance, span) { return Expr::New(Box::new(Expr::Sym(class)), values); } - let sym = self.t.instance(instance); + let sym = self.t.callee(instance, span); let call = Expr::Sym(sym).call(values); // The crate's own `next` returns an item or `rt.DONE`, and its caller an `Option`. if super::iter::is_next(tcx, did) { @@ -213,17 +213,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let sig = tcx.instantiate_bound_regions_with_erased(tcx.fn_sig(def_id).instantiate(tcx, gargs).skip_norm_wip()); let names: Vec = (0..sig.inputs().len()).map(|i| self.fresh(&format!("a{i}"))).collect(); let values: Vec = names.iter().map(Expr::ident).collect(); - // A local function or a binding's is named directly. + // A binding's export, or a function whose body translates, is named directly. if !matches!(tcx.def_kind(def_id), rustc_hir::def::DefKind::Ctor(..)) && let Ok(Some(instance)) = Instance::try_resolve(tcx, self.t.typing_env_pub(), def_id, gargs) { if let Some(sym) = self.t.bound_fn(instance, span) { return Expr::Sym(sym); } - if let ty::InstanceKind::Item(did) = instance.def - && did.is_local() - { - return Expr::Sym(self.t.instance(instance)); + if self.t.lowers(instance) { + return Expr::Sym(self.t.callee(instance, span)); } } let mut body = Vec::new(); diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 4a0747810..3ed9457c5 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -5,6 +5,7 @@ //! (`slice::split_first`), a trait method by its trait (`From::from`), and a free //! function by its module (`mem::take`). +use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, GenericArgsRef, Instance, Ty, TyCtxt}; use rustc_span::Span; @@ -394,6 +395,54 @@ pub fn inherent_std(tcx: TyCtxt<'_>, def_id: DefId) -> Option { } } +/// Whether std's `instance` lowers from its own MIR, as the crate's functions do, rather +/// than mapping here: a method of `Option` or `Result`, or their `Clone`. Not one taking a +/// `&mut` or a raw pointer, whose writes the crate's analysis of what it writes into +/// would miss, nor an `unsafe` one, nor one mapped below as one expression or as the +/// runtime's panic. +pub fn from_mir<'tcx>(t: &Translator<'_, 'tcx>, instance: Instance<'tcx>) -> bool { + let tcx = t.tcx; + let ty::InstanceKind::Item(did) = instance.def else { + return false; + }; + if !is_std(tcx, did) || tcx.def_kind(did) != DefKind::AssocFn { + return false; + } + let Some(imp) = tcx.impl_of_assoc(did) else { + return false; + }; + let ty::Adt(adt, _) = tcx.type_of(imp).instantiate_identity().skip_norm_wip().kind() else { + return false; + }; + let Some(std @ (Std::Option | Std::Result)) = Std::of(tcx, adt.did()) else { + return false; + }; + let sig = tcx.fn_sig(did).instantiate_identity().skip_norm_wip().skip_binder(); + let writes = |ty: Ty<'tcx>| { + ty.walk() + .filter_map(|arg| arg.as_type()) + .any(|t| matches!(t.kind(), ty::Ref(_, _, ty::Mutability::Mut) | ty::RawPtr(..))) + }; + if sig.safety().is_unsafe() || sig.inputs().iter().any(|&ty| writes(ty)) { + return false; + } + let name = tcx.item_name(did); + if let Some(tr) = tcx.trait_impl_of_assoc(did).map(|imp| tcx.impl_trait_id(imp)) { + // A `Clone` that only copies is the copy. + return tcx.is_lang_item(tr, rustc_attr_ir::LangItem::Clone) + && name == rustc_span::sym::clone + && t.self_ty(instance) + .is_none_or(|ty| !(t.is_copy(ty) && clone_copies(t, ty))); + } + !matches!( + (std, name.as_str()), + ( + Std::Option, + "unwrap" | "expect" | "is_some" | "is_none" | "as_ref" | "copied" | "cloned" | "iter" + ) | (Std::Result, "unwrap" | "expect" | "unwrap_err" | "is_ok" | "is_err") + ) +} + pub struct Call<'tcx> { /// The function as written, before resolving a trait method to its impl. pub def_id: DefId, @@ -416,23 +465,8 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { | ("hint", "must_use") | ("From", "from") | ("Into", "into") => &[], - // `Option::ok_or::` drops its error, `unwrap_or` its fallback, and - // `map_or::` its fallback or its closure. - ("Option", "ok_or") => &[1], - ("Option", "unwrap_or") => &[0], - ("Option", "map_or") => &[1, 2], - // `Option::map::` drops its closure on `None`, and `Result`'s - // `map::` and `and_then::` on an error, as `map_err::` on a value. - ("Option", "map") => &[2], - ("Result", "map" | "map_err" | "and_then") => &[3], - // `Result::ok` drops an error, `err` a value, and `unwrap_or` its fallback or - // the error. - ("Result", "ok") => &[1], - ("Result", "err") => &[0], - ("Result", "unwrap_or") => &[0, 1], - // `unwrap` and `expect` drop the error they panic with, `unwrap_err` the value, and - // `inspect_err` its error if its closure panics. - ("Result", "unwrap" | "expect" | "inspect_err") => &[1], + // `unwrap` and `expect` drop the error they panic with, and `unwrap_err` the value. + ("Result", "unwrap" | "expect") => &[1], ("Result", "unwrap_err") => &[0], // `then_some::` drops its value when false, and `then::` its function. ("bool", "then_some") => &[0], @@ -664,11 +698,7 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec } ("Default", "default") => default_value(b, targ(gargs, 0))?, - // Options. - ("Option", "map") => rt2(args, "option", "map"), - ("Option", "map_or") => rt2(args, "option", "mapOr"), - ("Option", "unwrap_or") => rt2(args, "option", "unwrapOr"), - ("Option", "ok_or") => rt2(args, "option", "okOr"), + // Options, whose other combinators lower from core's MIR. ("Option", "unwrap") => rt2(args, "option", "unwrap"), ("Option", "expect") => rt2(args, "option", "expect"), ("Option", "is_some") => args.pop()?.binary("!==", Expr::undefined()), @@ -681,15 +711,9 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec b.t.copied(value, option, span) } - // Results. - ("Result", "map") => rt2(args, "result", "map"), - ("Result", "map_err") => rt2(args, "result", "mapErr"), - ("Result", "and_then") => rt2(args, "result", "andThen"), - ("Result", "inspect_err") => rt2(args, "result", "inspectErr"), + // Results, whose other combinators lower from core's MIR. ("Result", "is_ok") => args.pop()?.member("ok"), ("Result", "is_err") => args.pop()?.member("ok").not(), - ("Result", "ok") => rt2(args, "result", "ok"), - ("Result", "err") => rt2(args, "result", "err"), // Their panics show the other side with its `Debug`. ("Result", "unwrap" | "expect" | "unwrap_err") => { let (method, shown) = match name.as_str() { @@ -701,7 +725,6 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Vec values.push(b.fmt_fn(fmt::Trait::Debug, shown, span)); Expr::rt_of("result", method).call(values) } - ("Result", "unwrap_or") => rt2(args, "result", "unwrapOr"), ("ControlFlow", "is_continue" | "is_break") => Flow::of(tcx, gargs).test(args.pop()?, name == "is_continue"), diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index f1d7e4d4c..e03c27af8 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -78,10 +78,52 @@ fn instance_mir<'tcx>(t: &mut Translator<'_, 'tcx>, instance: Instance<'tcx>, sp let mut body = instance.instantiate_mir_and_normalize_erasing_regions(tcx, t.typing_env_pub(), EarlyBinder::bind(tcx, body)); vec::literals(tcx, &mut body); + if !def_id.is_local() + && let Some(why) = std_refused(tcx, &body) + { + t.err(span, why); + return None; + } decided::fold(tcx, &mut body); Some(body) } +/// Why a body of std's can't lower as the crate's do, if it can't. The crate's analysis of +/// what it writes into reads only its own bodies, so one must change nothing in place: no +/// assignment through a projection or a reference, and no mutable borrow or pointer. And +/// core's plain integer arithmetic wraps, as `wrapping_add` lowers, where the crate's is +/// checked. +fn std_refused<'tcx>(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) -> Option<&'static str> { + const WRITE: &str = "a change in place, which a body of std's is not supported to make"; + const WRAP: &str = "arithmetic that wraps, which a body of std's is not supported to do"; + for bb in body.basic_blocks.iter() { + for stmt in &bb.statements { + match &stmt.kind { + StatementKind::Assign(assign) if !assign.0.projection.is_empty() => return Some(WRITE), + StatementKind::Assign(assign) => match &assign.1 { + Rvalue::Ref(_, mir::BorrowKind::Mut { .. }, _) | Rvalue::RawPtr(mir::RawPtrKind::Mut, _) => { + return Some(WRITE); + } + Rvalue::BinaryOp(mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul, operands) + if operands.0.ty(body, tcx).is_integral() => + { + return Some(WRAP); + } + _ => {} + }, + StatementKind::SetDiscriminant { .. } => return Some(WRITE), + _ => {} + } + } + if let TerminatorKind::Call { destination, .. } = &bb.terminator().kind + && !destination.projection.is_empty() + { + return Some(WRITE); + } + } + None +} + /// What `_1` is. #[derive(Clone)] pub enum Env { diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 9cc669201..0940d27cb 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -319,12 +319,88 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { if active.is_some() { return Some(self.err(span, "unions are not supported")); } + if let Some(same) = self.rebuilt_result(kind, ops, &values, ty, span, out) { + return Some(same); + } self.adt(*def_id, *variant, args, values, ty, span) } _ => unreachable!(), }) } + /// The `Result` a variant of one is rebuilt from, if it takes what that same variant of + /// another held, as `map_err` returns its `Ok`: that one's object, since a write into + /// an `rt.Result`'s payload replaces the result, so none changes in place. The payload, + /// held back for this one read, goes unread. + fn rebuilt_result( + &mut self, + kind: &AggregateKind<'tcx>, + ops: &IndexVec>, + values: &[Expr], + ty: Ty<'tcx>, + span: Span, + out: &mut Vec, + ) -> Option { + let &AggregateKind::Adt(def_id, variant, ..) = kind else { + return None; + }; + if Std::of(self.tcx, def_id) != Some(Std::Result) { + return None; + } + let ([Operand::Copy(place) | Operand::Move(place)], [value]) = (&ops.raw[..], values) else { + return None; + }; + let (place, temp) = match self.def_rvalue(place.local) { + Some(Rvalue::Use(Operand::Copy(from) | Operand::Move(from), _)) if place.projection.is_empty() => { + (*from, Some(place.local)) + } + _ => (*place, None), + }; + let [ + ref outer @ .., + mir::ProjectionElem::Downcast(_, from), + mir::ProjectionElem::Field(..), + ] = place.projection[..] + else { + return None; + }; + let whole = Place { + local: place.local, + projection: self.tcx.mk_place_elems(outer), + }; + // What the place holds now is what the payload was read from. + let stable = self.frozen(whole) && self.defs[whole.local] + u32::from(self.is_arg(whole.local)) <= 1; + let held = match variant.index() { + 0 => "value", + _ => "error", + }; + let payload = |e: &Expr| matches!(e, Expr::Member(_, Key::Name(field)) if field == held); + // Only the payload read as it is: a copy the operand made must still be made. + let pending = match (temp.and_then(|temp| self.var(temp)), value) { + (_, value) if payload(value) => None, + (Some(name), Expr::Ident(read)) if name == *read => Some( + self.pending + .iter() + .position(|p| p.name == name && !p.effect && payload(&p.value))?, + ), + _ => return None, + }; + let whole_ty = whole.ty(&self.mir.local_decls, self.tcx).ty; + if from != variant || !stable || self.b.t.std_of(whole_ty) != Some(Std::Result) { + return None; + } + if let Some(i) = pending { + self.pending.remove(i); + } + let same = self.place_expr(whole, span, out); + let ts_ty = self.b.t.ty(ty, span); + Some(match self.b.t.ty(whole_ty, span) == ts_ty { + true => same, + // Of the variant both share. + false => Expr::As(Box::new(same), ts_ty), + }) + } + pub(super) fn adt( &mut self, def_id: rustc_hir::def_id::DefId, diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index eae55bafd..0f471dd28 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -48,6 +48,7 @@ pub fn translate<'tcx>(tcx: TyCtxt<'tcx>, config: &Config) -> Option { if t.failed { return None; } + t.program.merge(); t.program.name(); Some(t.program) } @@ -186,6 +187,11 @@ pub struct Translator<'a, 'tcx> { pub coroutines: rustc_data_structures::fx::FxHashMap, mir::coroutine::Info<'tcx>>, /// Whether [`Self::ty`] is typing a variable: see [`Self::held_ty`]. held: bool, + /// Where the crate first reached each instance of std's that lowers from its MIR, which + /// refuses there: its own spans are std's. + sites: rustc_data_structures::fx::FxHashMap, Span>, + /// While such an instance lowers, that span and its function. + site: Option<(Span, DefId)>, /// The hand-written TypeScript the config binds items to. bindings: bind::Bindings<'tcx>, } @@ -254,6 +260,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { // Once the bindings are known. writes: Default::default(), held: false, + sites: Default::default(), + site: None, bindings: Default::default(), }) } @@ -293,12 +301,16 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } } - /// Refuse a construct outside the subset. + /// Refuse a construct outside the subset: inside a body of std's, at the crate's call. pub fn err(&mut self, span: Span, msg: impl Into) { self.failed = true; + let (span, msg) = match self.site { + Some((site, def_id)) => (site, format!("{}, in `{}`", msg.into(), self.tcx.def_path_str(def_id))), + None => (span, msg.into()), + }; match &mut self.refusals { - Some(refusals) => refusals.push((span, msg.into())), - None => _ = self.tcx.dcx().span_err(span, format!("rust2-ts: {}", msg.into())), + Some(refusals) => refusals.push((span, msg)), + None => _ = self.tcx.dcx().span_err(span, format!("rust2-ts: {msg}")), } } @@ -532,6 +544,16 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { sym } + /// The symbol of an instance a call at `span` reaches, noting where the crate first + /// reached one of std's. + pub fn callee(&mut self, instance: Instance<'tcx>, span: Span) -> SymId { + if !instance.def_id().is_local() { + let site = self.site.map_or(span, |(site, _)| site); + self.sites.entry(instance).or_insert(site); + } + self.instance(instance) + } + /// The type an associated function's impl or trait is for. pub fn self_ty(&self, instance: Instance<'tcx>) -> Option> { let def_id = instance.def_id(); @@ -597,17 +619,22 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { parts.join("_") } - /// The Rust module `def_id` is in. + /// The Rust module `def_id` is in, from the crate root; another crate's is under a + /// directory of its name, as `core/option` for `Option::map`. pub fn module_of(&self, def_id: DefId) -> Vec { - let Some(local) = def_id.as_local() else { - return Vec::new(); - }; - let module = self.tcx.parent_module_from_def_id(local).to_def_id(); - self.tcx - .def_path(module) - .data - .iter() - .filter_map(|part| part.data.get_opt_name().map(|name| name.to_string())) + let tcx = self.tcx; + let mut module = tcx.parent(def_id); + while tcx.def_kind(module) != DefKind::Mod { + module = tcx.parent(module); + } + let krate = (!def_id.is_local()).then(|| tcx.crate_name(def_id.krate).to_string()); + let path = tcx.def_path(module).data; + krate + .into_iter() + .chain( + path.iter() + .filter_map(|part| part.data.get_opt_name().map(|name| name.to_string())), + ) .collect() } @@ -675,13 +702,21 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty) } - /// Whether a call of `def_id` with `args` runs a function of the crate, which it - /// translates, rather than std's. + /// Whether a call of `def_id` with `args` runs a function whose body translates, the + /// crate's own or std's from its MIR, rather than a mapping. pub fn translated(&self, def_id: DefId, args: GenericArgsRef<'tcx>) -> bool { match Instance::try_resolve(self.tcx, self.typing_env(), def_id, args) { - Ok(Some(instance)) => { - matches!(instance.def, InstanceKind::Item(did) if did.is_local()) - && self.bound_module(instance).is_none() + Ok(Some(instance)) => self.lowers(instance), + _ => false, + } + } + + /// Whether `instance`'s body lowers from its MIR: the crate's own function, unless a + /// binding stands in for it, or one of std's that `library` leaves to its MIR. + pub fn lowers(&self, instance: Instance<'tcx>) -> bool { + match instance.def { + InstanceKind::Item(did) => { + self.bound_module(instance).is_none() && (did.is_local() || library::from_mir(self, instance)) } _ => false, } @@ -1232,20 +1267,46 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { self.err(span, format!("unsupported function `{}`", tcx.def_path_str(def_id))); return; }; - if !def_id.is_local() { + if !self.lowers(instance) { self.err(span, format!("`{}` is from another crate", tcx.def_path_str(def_id))); return; } - let Some(mut function) = mir::function(self, instance) else { - return; - }; + let site = (!def_id.is_local()).then(|| (self.sites.get(&instance).copied().unwrap_or(span), def_id)); + let outer = std::mem::replace(&mut self.site, site); + let function = self.lower_function(instance, sym, span); + self.site = outer; + if let Some(function) = function { + if !def_id.is_local() { + self.program.std.insert(sym); + } + self.program.items.push(Item::Function(function)); + } + } + + fn lower_function(&mut self, instance: Instance<'tcx>, sym: SymId, span: Span) -> Option { + let tcx = self.tcx; + let def_id = instance.def_id(); + // Without unwinding, std's MIR has none of the cleanups a panic runs. + if !def_id.is_local() + && tcx.required_panic_strategy(def_id.krate) == Some(rustc_target::spec::PanicStrategy::Abort) + { + self.err( + span, + format!( + "`{}` was built to abort on panic, so its MIR drops nothing a panic unwinds through: rust2-ts builds std from source to unwind", + tcx.crate_name(def_id.krate) + ), + ); + return None; + } + let mut function = mir::function(self, instance)?; function.sym = sym; function.loc = self.loc(span); // A trait method's impl often leaves its docs to the trait. function.doc = self .doc(def_id) .or_else(|| tcx.trait_item_of(def_id).and_then(|item| self.doc(item))); - self.program.items.push(Item::Function(function)); + Some(function) } /// The doc comment on an item, as written. diff --git a/ts/src/main.rs b/ts/src/main.rs index 725885c93..7cbf30f85 100644 --- a/ts/src/main.rs +++ b/ts/src/main.rs @@ -18,6 +18,7 @@ extern crate rustc_infer; extern crate rustc_interface; extern crate rustc_middle; extern crate rustc_span; +extern crate rustc_target; extern crate rustc_trait_selection; mod census; diff --git a/ts/src/program.rs b/ts/src/program.rs index e06e4d97d..eb17d11d5 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; use crate::print; -use crate::ts::{FieldId, Function, Item, SymId}; +use crate::ts::{self, FieldId, Function, Item, SymId}; /// The runtime every module imports helpers from, written beside the crate root: each /// file's path from there, and its text. @@ -91,6 +91,10 @@ pub struct Program { pub methods: HashMap>, /// The structs whose values are plain objects; the others are classes. pub plain: HashSet, + /// The instances of std's functions, which [`Program::merge`] merges. + pub std: HashSet, + /// Those merged into another, which have no name of their own. + merged: HashSet, pub sources: Vec, /// The hand-written files that bindings reach, copied into the output, by module. pub bound: BTreeMap, @@ -135,6 +139,59 @@ impl Program { self.fields.len() - 1 } + /// Make one function of the instances of a std function whose output is the same, as + /// those over closures of one signature are: the first in order, which the others' + /// callers then call. Each merge can make their callers the same too. + pub fn merge(&mut self) { + loop { + let mut same: HashMap = HashMap::new(); + let mut kept: HashMap = HashMap::new(); + let mut functions: Vec<&Function> = (self.items.iter()) + .filter_map(|item| match item { + Item::Function(f) if self.std.contains(&f.sym) => Some(f), + _ => None, + }) + .collect(); + functions.sort_by_key(|f| self.syms[f.sym].key()); + for f in functions { + let sym = &self.syms[f.sym]; + let key = (&sym.module, sym.base.as_str(), &f.params[..], &f.ret, &f.body[..]); + let first = *kept.entry(key).or_insert(f.sym); + if first != f.sym { + same.insert(f.sym, first); + } + } + if same.is_empty() { + return; + } + self.items + .retain(|item| !matches!(item, Item::Function(f) if same.contains_key(&f.sym))); + let mut rename = |id: &mut SymId| { + if let Some(&to) = same.get(id) { + *id = to; + } + }; + let functions = self.items.iter_mut().filter_map(|item| match item { + Item::Function(f) => Some(f), + _ => None, + }); + for f in functions.chain(self.methods.values_mut().flatten()) { + ts::syms_mut(&mut f.body, &mut rename); + } + for item in &mut self.items { + if let Item::Struct { fields, .. } = item { + for field in fields { + if let ts::FieldInit::Value(e) = &mut field.init { + e.syms_mut(&mut rename); + } + } + } + } + self.std.retain(|id| !same.contains_key(id)); + self.merged.extend(same.into_keys()); + } + } + /// Put every item and method in order, and name every symbol and field, resolving /// collisions within each scope in that order. pub fn name(&mut self) { @@ -147,6 +204,9 @@ impl Program { let mut scopes: BTreeMap> = BTreeMap::new(); for (id, sym) in self.syms.iter().enumerate() { + if self.merged.contains(&id) { + continue; + } let scope = match sym.owner { Some(owner) => Scope::Owner(owner), None => Scope::Module(sym.module.clone()), @@ -276,6 +336,10 @@ impl Program { } } +/// What a function of a module prints as, but for its own name: its item, parameters, +/// return type, and body. +type Output<'a> = (&'a ModPath, &'a str, &'a [ts::Param], &'a ts::Type, &'a [ts::Stmt]); + #[derive(PartialEq, Eq, PartialOrd, Ord)] enum Scope { Module(ModPath), diff --git a/ts/src/ts.rs b/ts/src/ts.rs index fe1e0f6c8..47e472aa4 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -10,7 +10,7 @@ pub type SymId = usize; pub type FieldId = usize; /// A position in a Rust source file, for the source map. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Loc { /// An index into the program's source files. pub file: u32, @@ -20,7 +20,7 @@ pub struct Loc { pub col: u32, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Expr { Ident(String), This, @@ -54,7 +54,7 @@ pub enum Expr { } /// A property name. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Key { Name(String), Field(FieldId), @@ -198,19 +198,19 @@ fn wide(ty: &Type) -> bool { matches!(ty, Type::Rt("u64" | "i64" | "u128" | "i128", _)) } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Param { pub name: String, pub ty: Option, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Stmt { pub kind: StmtKind, pub loc: Option, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum StmtKind { Expr(Expr), Decl { @@ -303,6 +303,73 @@ impl Stmt { } } +/// Each item `stmts` name as a value, to rename. +pub fn syms_mut(stmts: &mut [Stmt], f: &mut impl FnMut(&mut SymId)) { + for stmt in stmts { + match &mut stmt.kind { + StmtKind::Expr(e) | StmtKind::Throw(e) | StmtKind::Return(Some(e)) => e.syms_mut(f), + StmtKind::Decl { init, .. } => init.iter_mut().for_each(|e| e.syms_mut(f)), + StmtKind::If { cond, then, els } => { + cond.syms_mut(f); + syms_mut(then, f); + syms_mut(els, f); + } + StmtKind::While { cond: e, body, .. } | StmtKind::ForOf { iter: e, body, .. } => { + e.syms_mut(f); + syms_mut(body, f); + } + StmtKind::Block { body, .. } => syms_mut(body, f), + StmtKind::Catch { body, handler, .. } => { + syms_mut(body, f); + syms_mut(handler, f); + } + StmtKind::Switch { + disc, cases, default, .. + } => { + disc.syms_mut(f); + for (case, body) in cases { + case.syms_mut(f); + syms_mut(body, f); + } + syms_mut(default, f); + } + StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Declare { .. } => {} + } + } +} + +impl Expr { + /// Each item the expression names as a value, to rename. + pub fn syms_mut(&mut self, f: &mut impl FnMut(&mut SymId)) { + match self { + Expr::Sym(id) => f(id), + Expr::Arrow(_, _, body) => syms_mut(body, f), + Expr::Lambda(_, e) + | Expr::Member(e, _) + | Expr::Unary(_, e) + | Expr::Postfix(e, _) + | Expr::As(e, _) + | Expr::Located(_, e) => e.syms_mut(f), + Expr::Array(es) => es.iter_mut().for_each(|e| e.syms_mut(f)), + Expr::Object(props) => props.iter_mut().for_each(|(_, e)| e.syms_mut(f)), + Expr::Index(a, b) | Expr::Binary(a, _, b) | Expr::Assign(a, b) => { + a.syms_mut(f); + b.syms_mut(f); + } + Expr::Call(callee, args) | Expr::New(callee, args) => { + callee.syms_mut(f); + args.iter_mut().for_each(|e| e.syms_mut(f)); + } + Expr::Cond(a, b, c) => { + a.syms_mut(f); + b.syms_mut(f); + c.syms_mut(f); + } + Expr::Ident(_) | Expr::This | Expr::Rt(_) | Expr::Lit(_) | Expr::Str(_) => {} + } + } +} + /// Whether a `break` in `stmts` targets the loop that holds them, labeled `label`. /// Inside a `nested` loop, only a labeled `break` can. A `break` to any other label /// skips the loop's next statement too.