From c5fdf66be791a9097683e346a3f30d7f5ecc5599 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:29:54 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m2/ts-const-share.md Quest-Claim: d4fa3787aad4e9fe From ae2d7a2699143f47221b4bf5ebe160a39948d629 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:24:10 -0700 Subject: [PATCH 2/2] perf(ts): share Ok(()) and Err(()) as one frozen object A result whose payload is `undefined`, such as `Ok(())`, `Ok(None)`, or `ControlFlow::Continue(())`, is now `rt.OK` or `rt.ERR`, one frozen object of the runtime, instead of a new object per evaluation. Nothing writes into a result in place (a store into its payload makes the result again) and `undefined` holds nothing to write into, so no analysis is needed. `just ts bench` against main: encode at 0.90x in Chrome (A/A within 0.03), 0.75x in Firefox and Bun, Node within noise. Sharing results of other constants, such as `Err(DecodeError::Short)`, measured no faster in an A/B run, so they are made where evaluated. The runtime's private `written` becomes `OK`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3 --- quest/m2/README.md | 1 - quest/m2/ts-const-share.md | 36 ------------- ts/README.md | 11 ++-- ts/fixtures/codec/expected/bench.ts | 12 ++--- .../codec/expected/coding/encode.Encoder.ts | 8 +-- ts/fixtures/codec/expected/coding/varint.ts | 4 +- .../codec/expected/coding/version.Version.ts | 4 +- .../codec/expected/coding/version.Versions.ts | 4 +- ts/fixtures/codec/expected/harness.ts | 14 ++--- .../codec/expected/lite/group.Group.ts | 4 +- .../codec/expected/lite/probe.Probe.ts | 4 +- ts/fixtures/lang/expected/shapes.ts | 54 ++++++++++++++----- ts/fixtures/lang/src/shapes.rs | 19 +++++++ ts/runtime/rt.ts | 24 +++++---- ts/src/lower/body.rs | 3 +- ts/src/lower/consts.rs | 3 +- ts/src/lower/mir/call.rs | 6 +-- ts/src/lower/mir/mod.rs | 12 ++++- ts/src/lower/mir/rvalue.rs | 3 +- ts/src/ts.rs | 13 +++++ 20 files changed, 139 insertions(+), 100 deletions(-) delete mode 100644 quest/m2/ts-const-share.md diff --git a/quest/m2/README.md b/quest/m2/README.md index b34cadcce..6532d62b6 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -31,7 +31,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Matches TypeScript has already narrowed](/quest/m2/ts-narrow-test.md) - an inner match on a value an outer match decided passes `tsc` -- [Share constant aggregates](/quest/m2/ts-const-share.md) - `Ok(())` and other constants nothing writes into are one frozen object - [Translate moq-net's model to TypeScript](/quest/m2/ts-model/README.md) - the model translates with kio, moq-clock, and moq-pattern, for moq to compare against WASM - [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm - [Waiting: ubrn reads UniFFI 0.32](/quest/m2/ubrn-release.md) - the binding benchmark's browser runner pins a ubrn release, not an open PR diff --git a/quest/m2/ts-const-share.md b/quest/m2/ts-const-share.md deleted file mode 100644 index 5560bf341..000000000 --- a/quest/m2/ts-const-share.md +++ /dev/null @@ -1,36 +0,0 @@ -# [M] Share constant aggregates - -## Goal - -rust2-ts lowers a constant aggregate nothing can write into, such as `Ok(())`, to one shared -frozen object rather than a new one per evaluation, so a successful write in moq-net's -encoder allocates no `Result`. `just ts bench`'s encode workloads are faster than A/A's -spread in Chrome, and every differential test still passes. - -## Plan - -Found by the loop-invariant aggregate spike on 2026-10-27: the engines already remove the -aggregates translated loops rebuild, so hoisting them was dropped, but not a constant -returned through a call they don't inline, such as `Encoder::varint`'s and -`varint::write`'s `Ok(())`. Sharing it by hand cut Node's scavenges on 1-byte varint -encode by 95%, and measured 0.96x `translated` on Chrome's encode workloads over three runs -(A/A 0.99-1.05), 0.90-0.93x in Firefox, 0.93x in Bun, and 0.94-0.97x in Node, with the rest -within noise. Freezing it cost nothing measurable. - -Decided with the maintainer on 2026-10-27: all constant aggregates, not only `Ok(())`. - -- `Ok(())` and `Continue(())` need no analysis: the payload is `()`, and a store through - `&mut Result` rebinds the place. -- Other constants (`Err(DecodeError::Short)`, fieldless variants, limb literals, `const` - arrays, `rt.fmtSpec` objects) share only when nothing in the crate writes into their type - in place, the analysis that already shares `Copy` aggregates - ([output](/ts/README.md#output)); a `ref mut` to a payload, as in - `Result, E>`, keeps one object per evaluation. Prove each with such a case. -- Freeze each shared object, so a write the analysis missed throws in strict mode. -- Measure each kind: hoisting `{ tag: "Short" }` and a `u64` limb saved no allocation in - V8, so keep only the kinds that measure. -- Update the README's claim that making no `Ok` objects measured no faster, measured in - [#15](https://github.com/kixelated/rust2/pull/15) under THIR. - -Public API: the translator's output; callers receive the same frozen object for a constant. - diff --git a/ts/README.md b/ts/README.md index df72cc199..4227ace10 100644 --- a/ts/README.md +++ b/ts/README.md @@ -64,7 +64,7 @@ in `rt/str.ts`, collections in `rt/collections.ts`, and ownership and async in | `enum` without data | a union of strings: `"Lite01" \| "Lite02"`, or `never` without variants | | `enum` | a union of objects tagged by variant | | `Option` | `T \| undefined`; refused if `T` can already be `undefined`, as `()` and `Option` can | -| `Result` | `rt.Result`: `{ ok: true, value }` or `{ ok: false, error }` | +| `Result` | `rt.Result`: `{ ok: true, value }` or `{ ok: false, error }`; `rt.OK` or `rt.ERR` where the payload is `undefined`, as in `Ok(())` | | `ControlFlow` | `rt.Result`, `Ok` to continue; what `?` branches on is the value it was applied to | | tuple, `[T; N]`, `&[T]`, `Vec` | an array; for bytes, `Uint8Array` for `[u8; N]`, `rt.ByteSlice` for `&[u8]` and `&[u8; N]`, and `rt.ByteVec` for `Vec` | | `&T`, `&mut T`, `Box` | the value: a `&mut` must point at an object JS can change in place, or at a map's value through an `rt.Place` | @@ -278,8 +278,13 @@ they need. its variant: no `Cow` in moq-net or kio tells its variants apart, and a tag would wrap every value and unwrap it at every read. - `Result` is a plain `{ ok, value } | { ok, error }` object rather than an exception, so - `?` and `match` keep Rust's control flow exactly. Making no `Ok` objects at all measured - no faster on `just ts bench`, in V8 or JavaScriptCore. + `?` and `match` keep Rust's control flow exactly. One whose payload is `undefined`, such + as `Ok(())`, is one frozen object every evaluation shares, since nothing writes into a + result in place and engines don't remove one returned through a call they don't inline: + `just ts bench` measured the codec's encode workloads at 0.90 times their time without + it in Chrome, 0.75 in Firefox, and 0.75 in Bun at the geometric mean, with A/A within + 0.03 in Chrome and Node within its noise. Sharing a result of any other constant, such + as `Err(DecodeError::Short)`, measured no faster on the decodes that return it. - A `&[u8]` is an `rt.ByteSlice` rather than a `Uint8Array` view, since a view costs several times what an object does to make in V8 and JavaScriptCore, and a varint's decode splits its slice once to four times. `just ts bench` measured the codec's decode diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 428131e06..562b36d48 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -80,7 +80,7 @@ export function encodeVarints(data: rt.ByteSlice, form_: Form.Form, out: rt.Byte return _17; } } - return rt.Ok(undefined); + return rt.OK; } /** Every varint on the wire: how many, and the last. */ @@ -99,7 +99,7 @@ export function decodeVarints(wire: rt.ByteSlice, form_: Form.Form, out: rt.Byte } putUsize(out, count); putU64(out, last); - return rt.Ok(undefined); + return rt.OK; } /** @@ -156,7 +156,7 @@ export function encodeFrames(data: rt.ByteSlice, version: Version.Version, out: return _45; } } - return rt.Ok(undefined); + return rt.OK; } /** Every FRAME header on the wire: how many, their total size, and the last delta. */ @@ -183,7 +183,7 @@ export function decodeFrames(wire: rt.ByteSlice, version: Version.Version, out: putUsize(out, count); putU64(out, total); putU64(out, rt.u64Cast(last)); - return rt.Ok(undefined); + return rt.OK; } /** @@ -231,7 +231,7 @@ export function decodeSplit(data: rt.ByteSlice, version: Version.Version, out: r putU64(out, total); putU64(out, rt.u64Cast(last)); putUsize(out, short); - return rt.Ok(undefined); + return rt.OK; } return rt.Err({ tag: "Short" } as DecodeError.DecodeError); } @@ -505,7 +505,7 @@ export function decodeGroup(wire: rt.ByteSlice, version: Version.Version, out: r putU64(out, group.sequence); putU64(out, group.frameStart); putUsize(out, used); - return rt.Ok(undefined); + return rt.OK; } return _6; } diff --git a/ts/fixtures/codec/expected/coding/encode.Encoder.ts b/ts/fixtures/codec/expected/coding/encode.Encoder.ts index 151cf0758..762443e0f 100644 --- a/ts/fixtures/codec/expected/coding/encode.Encoder.ts +++ b/ts/fixtures/codec/expected/coding/encode.Encoder.ts @@ -47,7 +47,7 @@ export function bool(self: Encoder, v: boolean): void { /** Write a varint, or fail with [`EncodeError::BoundsExceeded`] if the form cannot carry it. */ export function varint(self: Encoder, v: rt.u64): rt.Result { if (write(v, self.form, self.buf).ok) { - return rt.Ok(undefined); + return rt.OK; } return rt.Err(EncodeError.from$From_BoundsExceeded({})); } @@ -73,7 +73,7 @@ export function bytes(self: Encoder, v: rt.ByteSlice): rt.Result = varint(self, v.length as rt.u64); if (_3.ok) { slice(self, v); - return rt.Ok(undefined); + return rt.OK; } return _3; } @@ -138,7 +138,7 @@ export function fill(self: Encoder, prefix: Prefix.Prefix): rt.Result { @@ -135,7 +135,7 @@ export function writeQuic(value: rt.u64, out: rt.ByteVec): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0); if (_4.ok) { - return rt.Ok(undefined); + return rt.OK; } return _4; } @@ -35,7 +35,7 @@ export function encode$Encode_Form(self: Version, w: Encoder.Encoder, _3: Form.F export function encode$Encode_Version(self: Version, w: Encoder.Encoder, _3: version_Version.Version): rt.Result { const _4: rt.Result = Encoder.varint(w, self._0); if (_4.ok) { - return rt.Ok(undefined); + return rt.OK; } return _4; } diff --git a/ts/fixtures/codec/expected/coding/version.Versions.ts b/ts/fixtures/codec/expected/coding/version.Versions.ts index 76b0eabd9..30f95c7bb 100644 --- a/ts/fixtures/codec/expected/coding/version.Versions.ts +++ b/ts/fixtures/codec/expected/coding/version.Versions.ts @@ -54,7 +54,7 @@ export function encode$Encode_Form(self: Versions, w: Encoder.Encoder, version: return _18; } } - return rt.Ok(undefined); + return rt.OK; } return _4; } @@ -69,7 +69,7 @@ export function encode$Encode_Version(self: Versions, w: Encoder.Encoder, versio return _18; } } - return rt.Ok(undefined); + return rt.OK; } return _4; } diff --git a/ts/fixtures/codec/expected/harness.ts b/ts/fixtures/codec/expected/harness.ts index 0d3a074a7..515884669 100644 --- a/ts/fixtures/codec/expected/harness.ts +++ b/ts/fixtures/codec/expected/harness.ts @@ -297,7 +297,7 @@ export function decodeStep(r: Decoder.Decoder, step: rt.u8, out: rt.ByteVec): rt } else { putUsize(out, Decoder.rest(r).length); } - return rt.Ok(undefined); + return rt.OK; } /** Write primitives as a script says, taking each value from the data that follows. */ @@ -323,13 +323,13 @@ export function encodeScript(data: rt.ByteSlice, out: rt.ByteVec): void { const _33: rt.u8 = rt.u8Rem(step, 10); if (_33 === 0) { Encoder.u8(w, rt.u64Low(value) & 0xff); - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } else if (_33 === 1) { Encoder.u16(w, rt.u64Low(value) & 0xffff); - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } else if (_33 === 2) { Encoder.bool(w, rt.u64And(value, 1) === 1); - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } else if (_33 === 3) { result = Encoder.varint(w, value); } else if (_33 === 4) { @@ -360,11 +360,11 @@ export function encodeScript(data: rt.ByteSlice, out: rt.ByteVec): void { _74 = Encoder.prefixU16(w); } prefixes.push(_74); - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } else if (_33 === 8) { const _79: Prefix.Prefix | undefined = prefixes.pop(); if (_79 === undefined) { - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } else { const prefix: Prefix.Prefix = _79; putUsize(out, Encoder.since(w, prefix)); @@ -375,7 +375,7 @@ export function encodeScript(data: rt.ByteSlice, out: rt.ByteVec): void { if (_88 !== undefined) { Encoder.discard(w, _88); } - result = rt.Ok(undefined); + result = rt.OK as rt.Result; } if (!result.ok) { encodeFailed(out, result.error); diff --git a/ts/fixtures/codec/expected/lite/group.Group.ts b/ts/fixtures/codec/expected/lite/group.Group.ts index 84905a862..466659227 100644 --- a/ts/fixtures/codec/expected/lite/group.Group.ts +++ b/ts/fixtures/codec/expected/lite/group.Group.ts @@ -68,7 +68,7 @@ export function encodeMsg$Message(self: Group, w: Encoder.Encoder, version: Vers return _15; } } - return rt.Ok(undefined); + return rt.OK; } return _9; } @@ -84,7 +84,7 @@ export function encode$Encode_Version(self: Group, w: Encoder.Encoder, version: const _49: rt.Result = Encoder.fill(w, prefix); if (_49.ok) { w.control = undefined; - return rt.Ok(undefined); + return rt.OK; } return _49; } diff --git a/ts/fixtures/codec/expected/lite/probe.Probe.ts b/ts/fixtures/codec/expected/lite/probe.Probe.ts index 4ea83e2e1..20ff188df 100644 --- a/ts/fixtures/codec/expected/lite/probe.Probe.ts +++ b/ts/fixtures/codec/expected/lite/probe.Probe.ts @@ -30,7 +30,7 @@ export function encode$Encode_Version(self: Probe, w: Encoder.Encoder, version: const _49: rt.Result = Encoder.fill(w, prefix); if (_49.ok) { w.control = "Probe" as Control.Control; - return rt.Ok(undefined); + return rt.OK; } return _49; } @@ -110,7 +110,7 @@ export function encodeMsg$Message(self: Probe, w: Encoder.Encoder, version: Vers return _17; } } - return rt.Ok(undefined); + return rt.OK; } return _9; } diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 231ad86a1..1b2a334f0 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1452,7 +1452,7 @@ export function payloads(data: rt.ByteSlice, out: rt.ByteVec): void { let taken: rt.Result = rt.Ok(rt.u8CheckedSub(n, 1)); if (taken.ok) { const taken2 = taken.value; - taken = rt.Ok(undefined); + taken = rt.OK; rt.byteVecPush(out, rt.optionUnwrapOr(taken2, 67)); } if (nested !== rt.Pending) { @@ -1772,6 +1772,11 @@ export function library(data: rt.ByteSlice, out: rt.ByteVec): void { } } +/** A result with nothing set yet. */ +export function unset(): rt.Result { + return rt.OK; +} + /** Steps a total by `x`: breaks with what it can't take, or continues with the new total. */ export function step(total: rt.u16, x: rt.u8): rt.Result { const _3: rt.u16 | undefined = rt.u16CheckedAdd(total, rt.u16Mul(x as rt.u16, 64)); @@ -1784,7 +1789,7 @@ export function step(total: rt.u16, x: rt.u8): rt.Result; let option!: rt.u8 | undefined; - let _113!: boolean; + let _116!: rt.u8; + let _132!: boolean; let total: rt.u16 = 0; for (const x of rt.byteSliceView(data)) { const flow: rt.Result = step(total, x); @@ -1875,20 +1881,42 @@ export function flows(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(flow3.value)); } } + let set: rt.Result = unset(); + if (set.ok) { + set = rt.Ok(a); + } + const iter3: rt.Iter> = rt.iterSlice([set, unset()]); + while (true) { + const _111: rt.Result | rt.Done = iter3.next(); + if (_111 === rt.DONE) { + break; + } + const result2: rt.Result = _111; + if (result2.ok) { + if (result2.value === undefined) { + _116 = 254; + } else { + _116 = result2.value; + } + } else { + _116 = result2.error; + } + rt.byteVecPush(out, _116); + } const slot: rt.Mutex = new rt.Mutex(undefined as rt.u8 | undefined); for (const x2 of rt.byteSliceView(data)) { const held: rt.Mutex = slot; - const _114: rt.u8 | undefined = held.value; - b12: { - if (_114 !== undefined) { - if (_114 >= x2) { - _113 = true; - break b12; + const _133: rt.u8 | undefined = held.value; + b16: { + if (_133 !== undefined) { + if (_133 >= x2) { + _132 = true; + break b16; } } - _113 = false; + _132 = false; } - if (!_113) { + if (!_132) { held.value = x2; } } diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 5839415cd..5a2ae18b4 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1564,6 +1564,11 @@ pub fn library(data: &[u8], out: &mut Vec) { } } +/// A result with nothing set yet. +fn unset() -> Result, u8> { + Ok(None) +} + /// Steps a total by `x`: breaks with what it can't take, or continues with the new total. fn step(total: u16, x: u8) -> ControlFlow, u16> { match total.checked_add(u16::from(x) * 0x40) { @@ -1637,6 +1642,20 @@ pub fn flows(data: &[u8], out: &mut Vec) { } } + // Every `Ok(None)` is one shared object: a store through a `ref mut` to its payload + // makes the result again, so the next stays `None`. + let mut set = unset(); + if let Ok(ref mut n) = set { + *n = Some(a); + } + for result in [set, unset()] { + out.push(match result { + Ok(Some(n)) => n, + Ok(None) => 0xfe, + Err(e) => e, + }); + } + let slot = Mutex::new(None); for &x in data { let mut held = slot.lock().unwrap(); diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 158fa9ad2..14fd3564c 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -59,6 +59,12 @@ export function Err(error: E): Result { return { ok: false, error }; } +/** `Ok(())`, one frozen object every evaluation shares, as nothing can change it. */ +export const OK: Result = /* @__PURE__ */ Object.freeze({ ok: true, value: undefined }); + +/** `Err(())`, shared as `OK` is. */ +export const ERR: Result = /* @__PURE__ */ Object.freeze({ ok: false, error: undefined }); + /** Panic with `message` and `value`'s `Debug`, and drop `value` as the panic unwinds. */ function unwrapFailed(message: string, value: T, debug: Debug, drop?: (value: T) => void): never { try { @@ -561,8 +567,6 @@ export class FmtError {} /** `fmt::Result`. */ export type FmtResult = Result; -const written: FmtResult = /* @__PURE__ */ Ok(undefined); - /** A value ready to write: `&dyn Display`, `&dyn Debug`, or one placeholder's argument. */ export type Fmt = (f: Formatter) => FmtResult; @@ -593,7 +597,7 @@ class StringWriter implements Write { writeStr(s: string): FmtResult { this.s += s; - return written; + return OK; } } @@ -617,7 +621,7 @@ class PadAdapter implements Write { const r = this.out.writeStr(line); if (!r.ok) return r; } - return written; + return OK; } } @@ -633,7 +637,7 @@ function write(out: Write, args: Arguments): FmtResult { const r = typeof part === "string" ? out.writeStr(part) : part({ out, spec: {} }); if (!r.ok) return r; } - return written; + return OK; } /** The number of chars in `s`, as Rust counts them for padding. */ @@ -738,7 +742,7 @@ export interface DebugStruct { export function debugStructField(b: DebugStruct, name: string, value: Fmt): DebugStruct { if (b.result.ok) { if (fmtAlternate(b.fmt)) { - const head = b.hasFields ? written : b.fmt.out.writeStr(" {\n"); + const head = b.hasFields ? OK : b.fmt.out.writeStr(" {\n"); b.result = head.ok ? pretty(b.fmt, [name, ": ", value, ",\n"]) : head; } else { b.result = b.fmt.out.writeStr((b.hasFields ? ", " : " { ") + name + ": "); @@ -777,7 +781,7 @@ export interface DebugTuple { export function debugTupleField(b: DebugTuple, value: Fmt): DebugTuple { if (b.result.ok) { if (fmtAlternate(b.fmt)) { - const head = b.fields > 0 ? written : b.fmt.out.writeStr("(\n"); + const head = b.fields > 0 ? OK : b.fmt.out.writeStr("(\n"); b.result = head.ok ? pretty(b.fmt, [value, ",\n"]) : head; } else { b.result = b.fmt.out.writeStr(b.fields === 0 ? "(" : ", "); @@ -818,10 +822,10 @@ export interface DebugList { export function debugListEntry(b: DebugList, value: Fmt): DebugList { if (b.result.ok) { if (fmtAlternate(b.fmt)) { - const head = b.hasFields ? written : b.fmt.out.writeStr("\n"); + const head = b.hasFields ? OK : b.fmt.out.writeStr("\n"); b.result = head.ok ? pretty(b.fmt, [value, ",\n"]) : head; } else { - b.result = b.hasFields ? b.fmt.out.writeStr(", ") : written; + b.result = b.hasFields ? b.fmt.out.writeStr(", ") : OK; if (b.result.ok) b.result = value(b.fmt); } } @@ -856,7 +860,7 @@ function pretty(f: Formatter, parts: Arguments): FmtResult { const r = typeof part === "string" ? writer.out.writeStr(part) : part(writer); if (!r.ok) return r; } - return written; + return OK; } /** A pretty builder's `finish_non_exhaustive`: an indented `..`, then `close`. */ diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 51b121031..a34d569e7 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -166,8 +166,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { return match (std, variant.index()) { (library::Std::Option, 1) | (library::Std::Poll, 0) => values.pop().unwrap(), (library::Std::Cow, _) if library::string(tcx, Ty::new_adt(tcx, adt, gargs)) => values.pop().unwrap(), - (library::Std::Result, 0) => Expr::rt("Ok", values), - (library::Std::Result, _) => Expr::rt("Err", values), + (library::Std::Result, i) => Expr::result(i == 0, values.pop().unwrap()), _ => self.err(span, format!("constructing `{}`", tcx.def_path_str(adt_id))), }; } diff --git a/ts/src/lower/consts.rs b/ts/src/lower/consts.rs index ae0ebab73..649185337 100644 --- a/ts/src/lower/consts.rs +++ b/ts/src/lower/consts.rs @@ -107,8 +107,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { (Std::Option, 0) => Expr::undefined(), (Std::Option, _) => values.pop().unwrap(), (Std::Cow, _) if crate::lower::library::string(tcx, ty) => values.pop().unwrap(), - (Std::Result, 0) => Expr::rt("Ok", values), - (Std::Result, _) => Expr::rt("Err", values), + (Std::Result, i) => Expr::result(i == 0, values.pop().unwrap()), // `start..=end`, not yet stepped past its end. (Std::RangeInclusive, _) if values.len() == 3 && matches!(&values[2], Expr::Lit(l) if l == "false") => diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index cde8f76db..933626503 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -578,7 +578,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } }; let converted = self.b.convert(error, from, to, span, out); - done(Expr::rt("Err", vec![converted]), true) + done(Expr::result(false, converted), true) } _ => { self.err(span, format!("`?` from `{residual}` to `{to}`")); @@ -963,9 +963,9 @@ pub fn control_flow<'tcx>( ) -> Expr { let value = values.pop().unwrap_or_else(Expr::undefined); match (flow(fx.tcx, ty), variant.index()) { - (Flow::Result | Flow::Other, 0) => Expr::rt("Ok", vec![value]), + (Flow::Result | Flow::Other, 0) => Expr::result(true, value), (Flow::Result, _) => value, - (Flow::Other, _) => Expr::rt("Err", vec![value]), + (Flow::Other, _) => Expr::result(false, value), (Flow::Option, 0) => value, (Flow::Option, _) => Expr::undefined(), } diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 542533661..d5149eb63 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -2951,7 +2951,17 @@ fn subst(e: &mut Expr, name: &str, value: &Expr) -> bool { Expr::Member(base, _) => subst(base, name, value), Expr::Index(base, index) => subst(base, name, value) || subst(index, name, value), Expr::Call(f, args) | Expr::New(f, args) => { - subst(f, name, value) || args.iter_mut().any(|e| subst(e, name, value)) + if !(subst(f, name, value) || args.iter_mut().any(|e| subst(e, name, value))) { + return false; + } + // A result of what folded in as `undefined` is the shared one. + if let Expr::Call(f, args) = &*e + && let (Expr::Rt(ctor), [arg]) = (&**f, args.as_slice()) + && matches!(ctor.as_str(), "Ok" | "Err") + { + *e = Expr::result(ctor == "Ok", arg.clone()); + } + true } Expr::Unary(_, e) | Expr::Located(_, e) | Expr::As(e, _) | Expr::Postfix(e, _) => subst(e, name, value), Expr::Binary(l, _, r) | Expr::Assign(l, r) => subst(l, name, value) || subst(r, name, value), diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 1b9e441ae..40a5a55bb 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -344,8 +344,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { (Std::Option | Std::Poll, _) => values.pop().unwrap(), // Either variant is its text. (Std::Cow, _) if crate::lower::library::string(tcx, ty) => values.pop().unwrap(), - (Std::Result, 0) => Expr::rt("Ok", values), - (Std::Result, _) => Expr::rt("Err", values), + (Std::Result, i) => Expr::result(i == 0, values.pop().unwrap()), (Std::FmtError, _) => Expr::New(Box::new(Expr::Rt("FmtError".into())), Vec::new()), // `ResumeTy`, an async body's context. (Std::Context, _) => values.pop().unwrap_or_else(Expr::undefined), diff --git a/ts/src/ts.rs b/ts/src/ts.rs index 8198ba1bb..fe1e0f6c8 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -94,6 +94,19 @@ impl Expr { Self::Rt(name.into()).call(args) } + /// `rt.Ok(value)`, or `rt.Err(value)` if not `ok`: for `undefined`, `rt.OK` or `rt.ERR`, + /// one object every evaluation shares, since nothing writes into a result in place and + /// `undefined` holds nothing to write into. + pub fn result(ok: bool, value: Expr) -> Self { + let unit = matches!(&value, Self::Lit(text) if text == "undefined"); + match (ok, unit) { + (true, true) => Self::Rt("OK".into()), + (false, true) => Self::Rt("ERR".into()), + (true, false) => Self::rt("Ok", vec![value]), + (false, false) => Self::rt("Err", vec![value]), + } + } + /// The runtime function `name` of what `of` names: `rt.u8Add` for `("u8", "add")`. pub fn rt_of(of: &str, name: &str) -> Self { let mut chars = name.chars();