From 33d2c59bd008f5ccfad6a037748b91c16abd9d8a Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:14:11 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m2/ts-tsc-shapes.md Quest-Claim: 866914512c853de3 From cd41364b8a6098a91b810bfa2eb84f0af3aab094 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:10:04 -0700 Subject: [PATCH 2/2] fix(ts): output tsc accepts for payload writes and variants in sight Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-tsc-shapes.md | 17 -- ts/fixtures/codec/expected/bench.ts | 4 +- ts/fixtures/lang/expected/shapes.Slot.ts | 10 + ts/fixtures/lang/expected/shapes.ts | 247 ++++++++++++++++++++++- ts/fixtures/lang/src/shapes.rs | 176 ++++++++++++++++ ts/src/lower/mir/call.rs | 41 ++-- ts/src/lower/mir/mod.rs | 127 +++++++++++- ts/src/lower/mir/place.rs | 42 ++++ ts/src/lower/mod.rs | 19 ++ 10 files changed, 635 insertions(+), 49 deletions(-) delete mode 100644 quest/m2/ts-tsc-shapes.md create mode 100644 ts/fixtures/lang/expected/shapes.Slot.ts diff --git a/quest/m2/README.md b/quest/m2/README.md index 36996ca94..5a3861413 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -36,7 +36,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Copy what a container stores](/quest/m2/ts-store-alias.md) - `push` and other stores of a `Copy` aggregate copy it instead of sharing it - [str and String methods over char](/quest/m2/ts-str-char.md) - `chars`, `char` patterns, and `String::push` translate, unblocking `ietf/namespace.rs` - [Share a held-back read across a call](/quest/m2/ts-shared-read.md) - `leading-ones` decode recovers what #83's copy fix cost -- [Output tsc accepts for writes through Result and Poll compares](/quest/m2/ts-tsc-shapes.md) - two shapes whose output fails `tsc` type-check - [Translate derived == through references and slice index writes](/quest/m2/ts-ref-shapes.md) - two refused shapes #83's tests hit - [Translate moq-net's model to TypeScript](/quest/m2/ts-model.md) - the driver grows from moq-net's codec to its model, for moq to compare against WASM - [Waiting: Swift 6.4 in nixpkgs-unstable](/quest/m2/uniffi-swift-arm.md) - the nightly UniFFI fixtures move back to arm diff --git a/quest/m2/ts-tsc-shapes.md b/quest/m2/ts-tsc-shapes.md deleted file mode 100644 index a7c6b2efa..000000000 --- a/quest/m2/ts-tsc-shapes.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Output tsc accepts for writes through Result and Poll compares - -## Goal - -Translated code that `tsc` rejects today type-checks and matches native Rust in -differential tests: writing through `if let Err(e) = &mut res { *e += 1 }`, and -comparing a `Poll` whose state TypeScript can see with `rt.Pending`. - -## Plan - -Found by [#83](https://github.com/kixelated/rust2/pull/83)'s tests on 2026-10-26. -The first writes the read-only `rt.Result.error`; the second narrows the `Poll` so -the comparison has no overlap. Both fail `tsc`, so they are loud, not silent. - -- Fix each in the lowering or the runtime's types, not by casting at the call site. - -Public API: the translator's output and `rt`'s types. diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 76cd49842..271387023 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -376,7 +376,7 @@ export function rescale(selector: rt.u8, data: Uint8Array, out: rt.ByteVec): voi if (selector === 0) { const _36: rt.u128 | undefined = rt.u128CheckedMul(rt.u128Cast(value), rt.u128Cast(to)); if (_36 === undefined) { - scaled = undefined; + scaled = undefined as rt.u64 | undefined; } else { scaled = bounded(rt.u128Div(_36, rt.u128Cast(from))); } @@ -390,7 +390,7 @@ export function rescale(selector: rt.u8, data: Uint8Array, out: rt.ByteVec): voi break b2; } } - scaled = undefined; + scaled = undefined as rt.u64 | undefined; } } if (scaled === undefined) { diff --git a/ts/fixtures/lang/expected/shapes.Slot.ts b/ts/fixtures/lang/expected/shapes.Slot.ts new file mode 100644 index 000000000..8d561e9fa --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Slot.ts @@ -0,0 +1,10 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A struct holding an enum, changed through a borrow of its field. */ +export interface Slot { + res: rt.Result; +} + +//# sourceMappingURL=shapes.Slot.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 77a72187c..2b8b792bc 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -12,6 +12,7 @@ import type * as Mover from "./shapes.Mover.ts"; import * as Point from "./shapes.Point.ts"; import * as Shape from "./shapes.Shape.ts"; import type * as Signed from "./shapes.Signed.ts"; +import type * as Slot from "./shapes.Slot.ts"; import * as Void from "./shapes.Void.ts"; import type * as Wide from "./shapes.Wide.ts"; @@ -213,9 +214,9 @@ export function copies(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, _211); } if (rt.usizeRem(data.length, 2) === 0) { - poll = rt.Pending; + poll = rt.Pending as rt.Poll; } else { - poll = copy$u8s(Uint8Array.of(data.length & 0xff)); + poll = copy$u8s(Uint8Array.of(data.length & 0xff)) as rt.Poll; } const polled_: rt.Poll = copy$Poll_u8s(poll); if (poll !== rt.Pending) { @@ -685,7 +686,7 @@ export function loops(data: Uint8Array, out: rt.ByteVec): void { } } rt.byteVecExtendFromSlice(out, rt.u32ToBeBytes(popped)); - let found: [rt.usize, rt.usize] | undefined = undefined; + let found = undefined as [rt.usize, rt.usize] | undefined; let iterStart: rt.usize = 0; const iterEnd: rt.usize = data.length; l3: while ((_24 = iterStart++) < iterEnd) { @@ -1320,6 +1321,240 @@ export function patterns(data: Uint8Array, out: rt.ByteVec): void { const arg = ([parsed] as [rt.Result])[0]; const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtResult(arg, f, rt.u8Display, (value: Void.Void, f: rt.Formatter) => Void.fmt$Debug(value, f))]; rt.byteVecExtendFromSlice(out, rt.stringAsBytes(rt.fmtFormat([args2[0]]))); + payloads(data, out); + known(data, out); +} + +/** `n`'s result: `Ok` for an even `n`. */ +export function parity(n: rt.u8): rt.Result { + if (!(rt.u8Rem(n, 2) === 0)) { + return rt.Err(n); + } + return rt.Ok(n); +} + +/** + * Payloads changed through a borrow, which changes the enum holding them where it is + * and none of its copies. + */ +export function payloads(data: Uint8Array, out: rt.ByteVec): void { + let _91!: rt.u8; + let _96!: rt.u8; + let _115!: Uint8Array; + let _120!: rt.u8; + let _130!: rt.u8; + let _136!: rt.u8; + const n: rt.u8 = data.length & 0xff; + let res: rt.Result = parity(n); + const before: rt.Result = res; + if (!res.ok) { + res = rt.Err(rt.u8WrappingAdd(res.error, 1)); + } + if (res.ok) { + res = rt.Ok(res.value ^ 85); + } + let err: rt.Result = rt.Err(n); + if (!err.ok) { + err = rt.Err(rt.u8WrappingAdd(err.error, 3)); + } + let owned: rt.Result = rt.Ok(n); + if (owned.ok) { + owned = rt.Ok(rt.u8WrappingAdd(owned.value, 2)); + } + const slot: Slot.Slot = { res: parity(rt.u8WrappingAdd(n, 1)) }; + if (!slot.res.ok) { + const _33: rt.u8 = rt.u8WrappingSub(slot.res.error, 4); + slot.res = rt.Err(_33); + } + let flow: rt.Result = rt.Err(n); + if (!flow.ok) { + flow = rt.Err(rt.u8WrappingAdd(flow.error, 9)); + } + let opt: rt.u8 | undefined = n; + if (opt !== undefined) { + opt = rt.u8WrappingAdd(opt, 7); + } + let poll = n as rt.Poll; + if (poll !== rt.Pending) { + poll = rt.u8WrappingSub(poll, 1); + } + let nested = parity(rt.u8WrappingAdd(n, 2)) as rt.Poll | undefined>; + if (nested !== rt.Pending) { + if (nested !== undefined) { + if (!nested.ok) { + nested = rt.Err(rt.u8WrappingAdd(nested.error, 6)); + } + } + } + let caught: rt.Result = parity(rt.u8WrappingAdd(n, 3)); + const bump_: () => void = (): void => { + if (!caught.ok) { + caught = rt.Err(rt.u8WrappingAdd(caught.error, 5)); + } + }; + bump_(); + bump_(); + let replaced: rt.Result = parity(rt.u8WrappingAdd(n, 4)); + if (replaced.ok) { + const old = replaced.value; + replaced = rt.Ok(66); + rt.byteVecPush(out, old); + } + let taken: rt.Result = rt.Ok(rt.u8CheckedSub(n, 1)); + if (taken.ok) { + const taken2 = taken.value; + taken = rt.Ok(undefined); + rt.byteVecPush(out, rt.optionUnwrapOr(taken2, 67)); + } + if (nested !== rt.Pending) { + if (nested !== undefined) { + const r: rt.Result = nested; + if (r.ok) { + _91 = r.value; + } else { + _91 = r.error ^ 128; + } + rt.byteVecPush(out, _91); + } + } + if (taken.ok) { + _96 = rt.optionUnwrapOr(taken.value, 68); + } else { + _96 = taken.error; + } + rt.byteVecPush(out, _96); + const iter: rt.Iter> = rt.iterSlice([before, res, err, slot.res, caught, replaced]); + while (true) { + const _108: rt.Result | rt.Done = iter.next(); + if (_108 === rt.DONE) { + break; + } + const r2: rt.Result = _108; + if (r2.ok) { + _115 = Uint8Array.of(0, r2.value); + } else { + _115 = Uint8Array.of(1, r2.error); + } + rt.byteVecExtendFromSlice(out, _115); + } + if (owned.ok) { + _120 = owned.value; + } else { + _120 = owned.error.length & 0xff; + } + rt.byteVecPush(out, _120); + if (flow.ok) { + _130 = flow.value; + } else { + _130 = flow.error; + } + const _134: rt.u8 = rt.optionUnwrapOr(opt, 0); + if (poll !== rt.Pending) { + _136 = poll; + } else { + _136 = 0; + } + rt.byteVecExtendFromSlice(out, Uint8Array.of(_130, _134, _136)); +} + +/** Enums matched where the variant they were made with is in sight. */ +export function known(data: Uint8Array, out: rt.ByteVec): void { + let _15!: rt.u8; + let _18!: rt.u8; + let _21!: rt.u8; + let _25!: rt.u8; + let _29!: rt.u8; + let _39!: rt.u8; + let _45!: rt.u8; + let _52!: rt.u8; + let _56!: rt.u8; + const n: rt.u8 = data.length & 0xff; + const ready = n as rt.Poll; + const idle = rt.Pending as rt.Poll; + const none = undefined as Point.Point | undefined; + const some: Point.Point | undefined = Point.new(n as rt.i32, 1); + if (ready !== rt.Pending) { + _15 = ready; + } else { + _15 = 0; + } + if (ready !== rt.Pending) { + _18 = rt.u8WrappingAdd(ready, 1); + } else { + _18 = 0; + } + if (idle !== rt.Pending) { + _21 = idle.x & 0xff; + } else { + _21 = 255; + } + if (none === undefined) { + _25 = 254; + } else { + _25 = none.y & 0xff; + } + if (some === undefined) { + _29 = 253; + } else { + _29 = some.x & 0xff; + } + rt.byteVecExtendFromSlice(out, Uint8Array.of(_15, _18, _21, _25, _29)); + const dot = { tag: "Dot" } as Shape.Shape; + const line = { tag: "Line", _0: Point.new(n as rt.i32, 2), _1: Point.new(3, 4) } as Shape.Shape; + if (dot.tag === "Dot") { + _39 = 1; + } else if (dot.tag === "Line") { + _39 = dot._0.x & 0xff; + } else { + _39 = dot.width & 0xff; + } + rt.byteVecPush(out, _39); + if (line.tag === "Dot") { + _45 = 1; + } else if (line.tag === "Line") { + _45 = line._0.x & 0xff; + } else { + _45 = line.width & 0xff; + } + rt.byteVecPush(out, _45); + const east = "East" as Dir.Dir; + if (east === "North") { + _52 = 1; + } else if (east === "East") { + _52 = 2; + } else { + _52 = 3; + } + rt.byteVecPush(out, _52); + const equal = 0 as rt.Ordering; + if (equal === -1) { + _56 = 1; + } else if (equal === 0) { + _56 = 2; + } else { + _56 = 3; + } + rt.byteVecPush(out, _56); + const noneLater = undefined as Point.Point | undefined; + const later = n as rt.Poll; + rt.byteVecPush(out, ((): rt.u8 => { + let a!: rt.u8; + if (later !== rt.Pending) { + a = later; + } else { + a = 0; + } + return a ^ rt.optionMapOr(noneLater, 16, (p4: Point.Point): rt.u8 => { + return p4.x & 0xff; + }); + })()); + const captured = noneLater; + rt.byteVecPush(out, ((): rt.u8 => { + if (captured === undefined) { + return 32; + } + return copy$Point(captured).y & 0xff; + })()); } /** A `match` without arms on a scrutinee that diverges, not on an empty type. */ @@ -1536,7 +1771,7 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u16ToBeBytes(total)); const a: rt.u8 = rt.optionUnwrapOr(rt.sliceFirst(data), 0); if (rt.u8Rem(a, 3) === 0) { - result = rt.Err(a); + result = rt.Err(a) as rt.Result; } else { result = rt.Ok(rt.u16Add(a as rt.u16, 256)); } @@ -1547,9 +1782,9 @@ export function flows(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecPush(out, (result as { ok: false; error: rt.u8 }).error); } if (rt.u8Rem(a, 5) === 0) { - option = undefined; + option = undefined as rt.u8 | undefined; } else { - option = rt.u8Div(a, 5); + option = rt.u8Div(a, 5) as rt.u8 | undefined; } rt.byteVecPush(out, option === undefined ? 1 : 0); if (option !== undefined) { diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 2914e447a..c9aa99610 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1131,6 +1131,182 @@ pub fn patterns(data: &[u8], out: &mut Vec) { }; out.extend_from_slice(&[a, b, c, early(a)]); out.extend_from_slice(format!("{parsed:?}").as_bytes()); + payloads(data, out); + known(data, out); +} + +/// `n`'s result: `Ok` for an even `n`. +#[inline(never)] +fn parity(n: u8) -> Result { + if n % 2 == 0 { Ok(n) } else { Err(n) } +} + +/// A struct holding an enum, changed through a borrow of its field. +struct Slot { + res: Result, +} + +/// Payloads changed through a borrow, which changes the enum holding them where it is +/// and none of its copies. +fn payloads(data: &[u8], out: &mut Vec) { + let n = data.len() as u8; + let mut res = parity(n); + let before = res; + if let Err(e) = &mut res { + *e = e.wrapping_add(1); + } + if let Ok(v) = &mut res { + *v ^= 0x55; + } + let mut err: Result = Err(n); + if let Err(e) = &mut err { + *e = e.wrapping_add(3); + } + let mut owned: Result> = Ok(n); + if let Ok(v) = &mut owned { + *v = v.wrapping_add(2); + } + let mut slot = Slot { + res: parity(n.wrapping_add(1)), + }; + if let Err(e) = &mut slot.res { + *e = e.wrapping_sub(4); + } + let mut flow: ControlFlow = ControlFlow::Break(n); + if let ControlFlow::Break(b) = &mut flow { + *b = b.wrapping_add(9); + } + let mut opt = Some(n); + if let Some(v) = &mut opt { + *v = v.wrapping_add(7); + } + let mut poll = Poll::Ready(n); + if let Poll::Ready(v) = &mut poll { + *v = v.wrapping_sub(1); + } + let mut nested: Poll>> = Poll::Ready(Some(parity(n.wrapping_add(2)))); + if let Poll::Ready(Some(Err(v))) = &mut nested { + *v = v.wrapping_add(6); + } + let mut caught = parity(n.wrapping_add(3)); + let mut bump = || { + if let Err(e) = &mut caught { + *e = e.wrapping_add(5); + } + }; + bump(); + bump(); + let mut replaced = parity(n.wrapping_add(4)); + if let Ok(v) = &mut replaced { + out.push(std::mem::replace(v, 0x42)); + } + let mut taken: Result, u8> = Ok(n.checked_sub(1)); + if let Ok(o) = &mut taken { + out.push(o.take().unwrap_or(0x43)); + } + if let Poll::Ready(Some(r)) = nested { + out.push(match r { + Ok(v) => v, + Err(e) => e ^ 0x80, + }); + } + out.push(match taken { + Ok(o) => o.unwrap_or(0x44), + Err(e) => e, + }); + for r in [before, res, err, slot.res, caught, replaced] { + out.extend_from_slice(&match r { + Ok(v) => [0, v], + Err(e) => [1, e], + }); + } + out.push(match owned { + Ok(v) => v, + Err(e) => e.len() as u8, + }); + out.extend_from_slice(&[ + match flow { + ControlFlow::Break(b) => b, + ControlFlow::Continue(c) => c, + }, + opt.unwrap_or(0), + match poll { + Poll::Ready(v) => v, + Poll::Pending => 0, + }, + ]); +} + +/// Enums matched where the variant they were made with is in sight. +fn known(data: &[u8], out: &mut Vec) { + let n = data.len() as u8; + let ready: Poll = Poll::Ready(n); + let copied = ready; + let idle: Poll = Poll::Pending; + let none: Option = None; + let some = Some(Point::new(n as i32, 1)); + out.extend_from_slice(&[ + match ready { + Poll::Pending => 0, + Poll::Ready(v) => v, + }, + match copied { + Poll::Pending => 0, + Poll::Ready(v) => v.wrapping_add(1), + }, + match idle { + Poll::Pending => 0xff, + Poll::Ready(p) => p.x as u8, + }, + match none { + Some(p) => p.y as u8, + None => 0xfe, + }, + match some { + Some(p) => p.x as u8, + None => 0xfd, + }, + ]); + let dot = Shape::Dot; + let line = Shape::Line(Point::new(n as i32, 2), Point::new(3, 4)); + out.push(match dot { + Shape::Dot => 1, + Shape::Line(from, _) => from.x as u8, + Shape::Rect { width, .. } => width as u8, + }); + out.push(match line { + Shape::Dot => 1, + Shape::Line(from, _) => from.x as u8, + Shape::Rect { width, .. } => width as u8, + }); + let east = Dir::East; + out.push(match east { + Dir::North => 1, + Dir::East => 2, + _ => 3, + }); + let equal = std::cmp::Ordering::Equal; + out.push(match equal { + std::cmp::Ordering::Less => 1, + std::cmp::Ordering::Equal => 2, + std::cmp::Ordering::Greater => 3, + }); + // A closure tests what it captured. + let later = Poll::Ready(n); + let none_later: Option = None; + let read = || { + let a = match later { + Poll::Pending => 0, + Poll::Ready(v) => v, + }; + a ^ none_later.map_or(0x10, |p| p.x as u8) + }; + out.push(read()); + let moved = move || match none_later { + Some(p) => p.y as u8, + None => 0x20, + }; + out.push(moved()); } /// An enum without variants: no value of it exists. diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index dd1bec09a..b729e47b6 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -254,18 +254,21 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ("mem", "take") => { let place = self.borrowed_place(&args[0].node, span)?; let default = library::default_value(self.b, targ(0)?)?; - done(self.swap_out(place, default, "taken", out), true) + done(self.swap_out(place, default, "taken", span, out), true) } ("mem", "replace") => { let place = self.borrowed_place(&args[0].node, span)?; let value = self.operand(&args[1].node, span, out); - done(self.swap_out(place, value, "old", out), true) + done(self.swap_out(place, value, "old", span, out), true) } ("mem", "swap") => { let a = self.borrowed_place(&args[0].node, span)?; let c = self.borrowed_place(&args[1].node, span)?; - let old = self.swap_out(a, c.clone(), "swapped", out); - out.push(StmtKind::Expr(c.assign(old)).at(None)); + let old = self.swap_out(a, c.0.clone(), "swapped", span, out); + match c.1 { + Some(place) => out.extend(self.store(place, old, span)), + None => out.push(StmtKind::Expr(c.0.assign(old)).at(None)), + } done(Expr::undefined(), true) } // A range of numbers steps in place, with nothing between it and the loop. @@ -281,7 +284,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } ("Option", "take") => { let place = self.borrowed_place(&args[0].node, span)?; - done(self.swap_out(place, Expr::undefined(), "taken", out), true) + done(self.swap_out(place, Expr::undefined(), "taken", span, out), true) } // Indexing, whose result a `&mut` reads in place. ("Index" | "IndexMut", "index" | "index_mut") => self.index(&name, gargs, args, dest, span, out), @@ -526,9 +529,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } - /// The place a `&mut` operand borrows, as an assignable path: an alias of a borrowed - /// place, not a copy of a reference, which holds the object it points at. - fn borrowed_place(&mut self, op: &Operand<'tcx>, span: Span) -> Option { + /// The place a `&mut` operand borrows, as an assignable path, and through the + /// reference, which a store resolves: an alias of a borrowed place, not a copy of a + /// reference, which holds the object it points at. + fn borrowed_place(&mut self, op: &Operand<'tcx>, span: Span) -> Option<(Expr, Option>)> { let (Operand::Copy(place) | Operand::Move(place)) = op else { return None; }; @@ -539,11 +543,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Slot::Alias(Some(target)) if (target.is_path() || matches!(target, Expr::Index(..))) && self.alias_of_place(place.local) => { - Some(target.clone()) + Some((target.clone(), Some(self.tcx.mk_place_deref(*place)))) } _ => { let pointee = self.mir.local_decls[place.local].ty.peel_refs(); - Some(self.err(span, format!("replacing the value behind a reference to `{pointee}`"))) + let err = self.err(span, format!("replacing the value behind a reference to `{pointee}`")); + Some((err, None)) } } } @@ -604,10 +609,20 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } /// The value at `place`, after setting `place` to `value`. - fn swap_out(&mut self, place: Expr, value: Expr, base: &str, out: &mut Vec) -> Expr { + fn swap_out( + &mut self, + (read, place): (Expr, Option>), + value: Expr, + base: &str, + span: Span, + out: &mut Vec, + ) -> Expr { let name = self.b.fresh(base); - out.push(StmtKind::decl(false, name.clone(), None, Some(place.clone())).at(None)); - out.push(StmtKind::Expr(place.assign(value)).at(None)); + out.push(StmtKind::decl(false, name.clone(), None, Some(read.clone())).at(None)); + match place { + Some(place) => out.extend(self.store(place, value, span)), + None => out.push(StmtKind::Expr(read.assign(value)).at(None)), + } Expr::ident(name) } diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 80606b4fe..ab3b9787b 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -220,6 +220,10 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { /// it: its `rt.Place` or `undefined`, which is only tested, unwrapped, or taken apart /// into a reference that reads and writes through it. place_opts: FxHashSet, + /// Locals whose variant some switch tests, directly or through a reference to them. + tested: IndexVec, + /// The names of those that hold a value TypeScript would narrow by what it is assigned. + widened: FxHashSet, } impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { @@ -274,6 +278,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { halves: FxHashMap::default(), joined: FxHashSet::default(), place_opts: FxHashSet::default(), + tested: IndexVec::from_elem_n(false, n), + widened: FxHashSet::default(), }; fx.analyze(); fx @@ -425,6 +431,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.b.t.check_erased(held, self.local_span(local)); } } + self.find_tested(); // Names: what debug info calls a local, else its number. let mut named: FxHashMap = FxHashMap::default(); for info in &mir.var_debug_info { @@ -1058,6 +1065,92 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// Mark the locals whose variant a switch tests, or that a closure or async block + /// captures and could test, and what references to them borrow. + fn find_tested(&mut self) { + let mut work = Vec::new(); + for data in self.mir.basic_blocks.iter() { + for stmt in &data.statements { + let StatementKind::Assign(assign) = &stmt.kind else { + continue; + }; + match &assign.1 { + Rvalue::Discriminant(place) => work.push(place.local), + Rvalue::Aggregate(kind, ops) + if matches!( + **kind, + mir::AggregateKind::Closure(..) | mir::AggregateKind::Coroutine(..) + ) => + { + work.extend(ops.iter().filter_map(|op| op.place().map(|p| p.local))); + } + _ => {} + } + } + } + while let Some(local) = work.pop() { + if std::mem::replace(&mut self.tested[local], true) { + continue; + } + if let Slot::Alias(_) = self.slots[local] + && let Some( + Rvalue::Ref(_, _, p) + | Rvalue::Use(Operand::Copy(p) | Operand::Move(p), _) + | Rvalue::CopyForDeref(p) + | Rvalue::Cast(_, Operand::Copy(p) | Operand::Move(p), _), + ) = self.def_rvalue(local) + { + work.push(p.local); + } + } + } + + /// `value`, the `rvalue` assigned to `place`, as a value of its whole type where + /// something tests `place`'s variant: TypeScript narrows a variable to the type of + /// what it was assigned, as a `Poll` made `Ready` to its payload's, and would refuse a + /// test for another variant. + fn widen(&mut self, place: Place<'tcx>, rvalue: &Rvalue<'tcx>, value: Expr, span: Span) -> Expr { + let ty = place.ty(&self.mir.local_decls, self.tcx).ty; + // What is made here, rather than read from a place declared with its type. + let made = matches!(rvalue, Rvalue::Aggregate(..) | Rvalue::Use(Operand::Constant(_), _)); + if !made || !self.tested[place.local] || !self.b.t.narrows(ty) { + return value; + } + // `Some` narrows to its payload's type, which only a test for `None` refutes, and + // that reads nothing of it. + if let Rvalue::Aggregate(kind, _) = rvalue + && let mir::AggregateKind::Adt(def, variant, args, ..) = **kind + && crate::lower::library::Std::of(self.tcx, def) == Some(crate::lower::library::Std::Option) + && variant.index() == 1 + && !self.b.t.narrows(args.type_at(0)) + { + return value; + } + let local = place.as_local(); + let ts_ty = match local { + Some(local) if self.stepped_vars.contains_key(&local) => return value, + Some(local) => self.decl_ty(local), + None => self.b.t.ty(ty, span), + }; + let mut inner = &value; + while let Expr::Located(_, e) = inner { + inner = e; + } + let value = match inner { + Expr::As(_, t) if *t == ts_ty => value, + // `Ok` and `Err` are of the whole type. + Expr::Call(f, _) if matches!(&**f, Expr::Rt(n) if n == "Ok" || n == "Err") => return value, + _ => Expr::As(Box::new(value.typed()), ts_ty), + }; + // Its declaration keeps the `as`. + if let Some(local) = local + && let Slot::Var(name) = &self.slots[local] + { + self.widened.insert(name.clone()); + } + value + } + /// The rvalue a local's one assignment by a statement assigns. fn def_rvalue(&self, local: Local) -> Option<&'m Rvalue<'tcx>> { let (bb, i) = self.def_at[local]?; @@ -1232,7 +1325,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { cfg::strip_return(&mut out); } cfg::hoist_else(&mut out); - declare_in_place(&mut out); + declare_in_place(&mut out, &self.widened); cfg::tidy_loops(&mut out); out } @@ -1908,6 +2001,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { out.extend(pre); return; }; + let value = self.widen(place, rvalue, value, span); // What an `Iterator::next` returns, by the protocol. let value = match ( self.next && place.local == mir::RETURN_PLACE && place.projection.is_empty(), @@ -2619,8 +2713,9 @@ fn strip_assignments(stmts: &mut Vec, unread: &FxHashSet) { /// Declare each variable declared up front at the assignment that first names it, where /// everything else that names it follows in the same block: no path reaches those without -/// passing the assignment. `const` if nothing assigns it again. -fn declare_in_place(stmts: &mut Vec) { +/// passing the assignment. `const` if nothing assigns it again. Those `widened` keep +/// the type their value was given. +fn declare_in_place(stmts: &mut Vec, widened: &FxHashSet) { let declared: Vec<(String, Type)> = stmts .iter() .filter_map(|s| match &s.kind { @@ -2634,15 +2729,17 @@ fn declare_in_place(stmts: &mut Vec) { stmts .iter() .for_each(|s| visit_stmt(s, &mut |e| writes += writes_of(e, &name))); - if total > 0 && place_declaration(stmts, &name, &ty, total, writes > 1) { + let widened = widened.contains(&name); + if total > 0 && place_declaration(stmts, &name, &ty, total, writes > 1, widened) { stmts.retain(|s| !matches!(&s.kind, StmtKind::Declare { name: n, .. } if *n == name)); } } } /// Turn the statement that first names `name` into its declaration, if it assigns it and -/// all `total` statements naming it follow in its block. -fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mutable: bool) -> bool { +/// all `total` statements naming it follow in its block. A `widened` value keeps its +/// `as`, which then types the variable. +fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mutable: bool, widened: bool) -> bool { let Some(i) = stmts.iter().position(|s| stmt_names(s, name) > 0) else { return false; }; @@ -2656,15 +2753,25 @@ fn place_declaration(stmts: &mut [Stmt], name: &str, ty: &Type, total: usize, mu else { unreachable!("checked above") }; - stmts[i].kind = StmtKind::decl(mutable, name, Some(ty.clone()), Some(*value)); + stmts[i].kind = match *value { + Expr::As(_, ref t) if widened && t == ty => StmtKind::decl(mutable, name, None, Some(*value)), + value if widened => StmtKind::Decl { + mutable, + name: name.into(), + ty: Some(ty.clone()), + init: Some(value), + }, + value => StmtKind::decl(mutable, name, Some(ty.clone()), Some(value)), + }; return true; } // Else everything naming it must be in one block of this statement. if stmt_names(&stmts[i], name) != total { return false; } - let place = - |body: &mut Vec| list_names(body, name) == total && place_declaration(body, name, ty, total, mutable); + let place = |body: &mut Vec| { + list_names(body, name) == total && place_declaration(body, name, ty, total, mutable, widened) + }; match &mut stmts[i].kind { StmtKind::If { then, els, .. } => place(then) || place(els), StmtKind::While { body, .. } | StmtKind::Block { body, .. } => place(body), @@ -3146,7 +3253,7 @@ mod tests { .at(None), StmtKind::Expr(arrow.call(Vec::new())).at(None), ]; - declare_in_place(&mut stmts); + declare_in_place(&mut stmts, &FxHashSet::default()); assert!(matches!(&stmts[0].kind, StmtKind::Declare { name, .. } if name == "found")); } } diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index e2f4c869b..78dfb8737 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -294,6 +294,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { /// The statements that assign `value` to `place`, which has projections. pub(super) fn store(&mut self, place: Place<'tcx>, value: Expr, span: Span) -> Vec { + let (place, value) = self.rebuilt(place, value, span); let mut out = Vec::new(); // `*r = v` replaces the object `r` points at in place, which other references and // captures share. An alias of a borrowed place, or of a reference to no object, @@ -331,6 +332,47 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { out } + /// A store of `value` to `place` as a store of the whole value to what holds it, where + /// `place`, or what a reference to it reads, is the payload of an `Option`, `Poll`, + /// `Result`, or `ControlFlow`: JS shares their values as immutable, so a payload + /// changes by making its enum again. + fn rebuilt(&mut self, place: Place<'tcx>, value: Expr, span: Span) -> (Place<'tcx>, Expr) { + let tcx = self.tcx; + let (mut at, mut value, mut rebuilt) = (place, value, false); + loop { + if let [ProjectionElem::Deref, rest @ ..] = at.projection.as_slice() + && self.alias_of_place(at.local) + && let Some(mir::Rvalue::Ref(_, _, borrowed)) = self.def_rvalue(at.local) + { + at = borrowed.project_deeper(rest, tcx); + continue; + } + let [.., ProjectionElem::Downcast(_, variant), ProjectionElem::Field(..)] = at.projection.as_slice() else { + break; + }; + let base = Place { + local: at.local, + projection: tcx.mk_place_elems(&at.projection[..at.projection.len() - 2]), + }; + let ty = base.ty(&self.mir.local_decls, tcx).ty; + let ty::Adt(adt, args) = ty.kind() else { + break; + }; + if !matches!( + Std::of(tcx, adt.did()), + Some(Std::Option | Std::Poll | Std::Result | Std::ControlFlow) + ) { + break; + } + value = self.adt(adt.did(), *variant, args, vec![value], ty, span); + (at, rebuilt) = (base, true); + } + match rebuilt { + true => (at, value), + false => (place, value), + } + } + /// Whether `local` is an alias of a borrowed place, as `&mut x` or `&mut v[i]`, rather /// than a copy of a reference or a reborrow of what one points at. pub(super) fn alias_of_place(&self, local: Local) -> bool { diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index eec276eb4..8f62e14ba 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -799,6 +799,25 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { info } + /// Whether a `ty`'s JS type is a union of its variants', which TypeScript narrows a + /// variable to the member it was assigned. + pub fn narrows(&self, ty: Ty<'tcx>) -> bool { + match ty.kind() { + ty::Adt(adt, _) => match library::Std::of(self.tcx, adt.did()) { + Some( + library::Std::Option + | library::Std::Poll + | library::Std::Result + | library::Std::ControlFlow + | library::Std::Ordering, + ) => true, + Some(_) => false, + None => adt.is_enum() && adt.variants().len() > 1, + }, + _ => false, + } + } + /// What kind of JS object a `&mut` to `ty` can change in place, if any. pub fn object_kind(&self, ty: Ty<'tcx>) -> Option { match ty.kind() {