From 589d15c3624c284afe588b188af997c4e6d35877 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:51:05 -0700 Subject: [PATCH 1/8] chore(quest): claim quest/m2/ts-narrow-test.md Quest-Claim: 18dc7136b6607798 From 56158da8ddd6a09f37fb8eefe836197de545b1ab Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:30:14 -0700 Subject: [PATCH 2/8] fix(ts): fold matches an enclosing match decided Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-narrow-test.md | 21 - ts/fixtures/lang/expected/shapes.Machine.ts | 59 +++ ts/fixtures/lang/expected/shapes.ts | 123 ++++- ts/fixtures/lang/src/shapes.rs | 180 ++++++++ ts/fixtures/task/expected/drops.ts | 2 +- ts/src/lower/mir/decided.rs | 469 ++++++++++++++++++++ ts/src/lower/mir/mod.rs | 2 + 8 files changed, 832 insertions(+), 25 deletions(-) delete mode 100644 quest/m2/ts-narrow-test.md create mode 100644 ts/fixtures/lang/expected/shapes.Machine.ts create mode 100644 ts/src/lower/mir/decided.rs diff --git a/quest/m2/README.md b/quest/m2/README.md index a240a1026..de9ceb9b2 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -34,7 +34,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 - [Share what the crate never changes in place](/quest/m2/ts-shared-read.md) - copies of `Copy` aggregates no one writes into in place go away, recovering #83's decode cost -- [Matches TypeScript has already narrowed](/quest/m2/ts-narrow-test.md) - an inner match on a value an outer match decided passes `tsc` - [Default comparison methods](/quest/m2/ts-cmp-defaults.md) - inherited `ne`, `lt`, `le`, `gt`, `ge` and `[u8]` equality translate - [Copy-on-write strings](/quest/m2/ts-cow-str.md) - `Cow` translates, finishing `ietf/namespace.rs` - [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 diff --git a/quest/m2/ts-narrow-test.md b/quest/m2/ts-narrow-test.md deleted file mode 100644 index f449715cd..000000000 --- a/quest/m2/ts-narrow-test.md +++ /dev/null @@ -1,21 +0,0 @@ -# [S] Matches TypeScript has already narrowed - -## Goal - -rust2-ts's output passes `tsc` when a value is matched again where an enclosing match -already decided its variant, such as `match x { Dot => match x { Line(..) => .. } }` or a -match on a copy taken inside the arm, proven by differential tests against native Rust -that also type-check. - -## Plan - -Found by [#100](https://github.com/kixelated/rust2/pull/100) on 2026-10-27, which widens -a local TypeScript narrows by construction but not one it narrows by a test. The inner -test fails `tsc` (TS2367) rather than miscompiling. - -- Fold away a test an enclosing test already decided, so the inner match lowers to its - one reachable arm. -- Where folding can't reach, such as a copy matched in the arm, widen the copy as #100 - widens a constructed local. - -Public API: the translator's output. diff --git a/ts/fixtures/lang/expected/shapes.Machine.ts b/ts/fixtures/lang/expected/shapes.Machine.ts new file mode 100644 index 000000000..774994b81 --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Machine.ts @@ -0,0 +1,59 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$Point } from "./lib.ts"; +import * as Point from "./shapes.Point.ts"; +import * as Shape from "./shapes.Shape.ts"; + +/** A state a method matches, changing it between its matches. */ +export interface Machine { + state: Shape.Shape; + steps: rt.u8; +} + +export function step(self: Machine): void { + let _3!: Shape.Shape; + self.steps = rt.u8Add(self.steps, 1); + if (self.state.tag === "Dot") { + _3 = { tag: "Line", _0: copy$Point(Point.new(1, 2)), _1: copy$Point(Point.new(3, 4)) } as Shape.Shape; + } else if (self.state.tag === "Line") { + _3 = { tag: "Rect", corner: copy$Point(copy$Point(self.state._0)), width: 5, height: 6 } as Shape.Shape; + } else { + _3 = { tag: "Dot" } as Shape.Shape; + } + self.state = _3; +} + +/** Reads the state, which a shared borrow can't change. */ +export function peek(self: Machine): rt.u8 { + return self.steps ^ (rt.u64Low(Shape.area$Area(self.state)) & 0xff); +} + +export function log(self: Machine, v: rt.u8): rt.u8 { + self.steps = rt.u8WrappingAdd(self.steps, v); + return self.steps; +} + +export function run(self: Machine, n: rt.u8): rt.u8 { + if (self.state.tag === "Dot") { + step(self); + if (self.state.tag === "Dot") { + return 27; + } + return self.steps ^ n; + } + if (self.state.tag === "Line") { + const seen: rt.u8 = peek(self); + const _12: rt.u8 = self.state._1.y & 0xff; + return _12 ^ seen; + } + const width: rt.u16 = self.state.width; + const logged: rt.u8 = log(self, self.state.height & 0xff); + step(self); + if (self.state.tag === "Rect") { + return 30; + } + return (width & 0xff) ^ logged; +} + +//# sourceMappingURL=shapes.Machine.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 9f2ec9397..c3e8b35e1 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -6,6 +6,7 @@ import * as Pair from "./fmt.Pair.ts"; import type * as Dir from "./shapes.Dir.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; +import * as Machine from "./shapes.Machine.ts"; import * as Meters from "./shapes.Meters.ts"; import * as Moved from "./shapes.Moved.ts"; import type * as Mover from "./shapes.Mover.ts"; @@ -1392,13 +1393,13 @@ export function patterns(data: rt.ByteSlice, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(rt.u64Add(total$Shape([shape_, { tag: "Dot" } as Shape.Shape], out), total$Meters([{ _0: 3 }, { _0: { hi: 0xffffffff, lo: 0xffffffff } as rt.u64 }], out))))); const parsed: rt.Result = rt.Ok(data.length & 0xff); const a2: rt.u8 = (parsed as { ok: true; value: rt.u8 }).value; - const b3: rt.u8 = (parsed as { ok: true; value: rt.u8 }).value; - rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(a2, b3, (parsed as { ok: true; value: rt.u8 }).value, early(a2)))); + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of(a2, (parsed as { ok: true; value: rt.u8 }).value, (parsed as { ok: true; value: rt.u8 }).value, early(a2)))); 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); + rematched(data, out); } /** `n`'s result: `Ok` for an even `n`. */ @@ -1645,6 +1646,124 @@ export function known(data: rt.ByteSlice, out: rt.ByteVec): void { })()); } +/** Enums matched again where an enclosing match decided their variant. */ +export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { + let _5!: rt.u8; + let _15!: rt.u8; + let _19!: rt.u8; + let _29!: rt.u8; + let _43!: rt.u8; + let _48!: rt.u8; + let _59!: rt.u8; + let _68!: rt.u8; + let _72!: Shape.Shape; + let _114!: rt.u8; + const s: Shape.Shape = shape(data); + if (s.tag === "Dot") { + _5 = 2; + } else if (s.tag === "Line") { + const from: Point.Point = s._0; + const to: Point.Point = s._1; + const _12: rt.i32 = from.x; + _5 = (_12 ^ to.y) & 0xff; + } else { + _5 = 4; + } + rt.byteVecPush(out, _5); + if (s.tag === "Dot") { + _15 = 6; + } else { + _15 = 7; + } + rt.byteVecPush(out, _15); + if (s.tag === "Dot") { + _19 = 8; + } else if (s.tag === "Line") { + _19 = 10; + } else { + _19 = s.width & 0xff; + } + rt.byteVecPush(out, _19); + const d: Dir.Dir | undefined = dir(data.length & 0xff); + if (d === undefined) { + _29 = 15; + } else if (d === "North") { + _29 = 12; + } else { + _29 = { North: 1, East: 2, South: 4, West: 8 }[d] & 0xff; + } + rt.byteVecPush(out, _29); + const order_: rt.Ordering = rt.cmp(data.length & 0xff, 2); + if (order_ === -1) { + _43 = 17; + } else { + _43 = 0; + } + rt.byteVecPush(out, _43); + let m: Shape.Shape = s; + if (m.tag === "Dot") { + m = shape(rt.byteSliceRange(data, rt.min(data.length, 1))); + if (m.tag === "Line") { + _48 = 18; + } else { + _48 = 19; + } + } else { + _48 = 20; + } + rt.byteVecPush(out, _48); + let held = copy$Shape(m) as Shape.Shape | undefined; + if (held === undefined) { + _59 = 22; + } else { + const taken2 = held; + held = undefined; + const taken: Shape.Shape | undefined = taken2; + if (held === undefined) { + _59 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { + return rt.u64Low(Shape.area$Area(t)) & 0xff; + }); + } else { + _59 = 21; + } + } + rt.byteVecPush(out, _59); + let cur: Shape.Shape = s; + let iterStart: rt.u8 = 0; + const iterEnd: rt.u8 = 3; + while ((_68 = iterStart++) < iterEnd) { + const i: rt.u8 = _68; + if (cur.tag === "Dot") { + _72 = { tag: "Line", _0: Point.new(i as rt.i32, 0), _1: Point.new(0, 0) } as Shape.Shape; + } else if (cur.tag === "Line") { + _72 = { tag: "Rect", corner: cur._0, width: rt.u16Add(cur._1.x & 0xffff, 1), height: 2 } as Shape.Shape; + } else if (!(cur.width > 1)) { + _72 = cur; + } else { + _72 = { tag: "Dot" } as Shape.Shape; + } + cur = _72; + rt.byteVecPush(out, rt.u64Low(Shape.area$Area(cur)) & 0xff); + } + const machine: Machine.Machine = { state: copy$Shape(s), steps: 0 }; + let iterStart2: rt.i32 = 0; + const iterEnd2: rt.i32 = 4; + while (iterStart2++ < iterEnd2) { + rt.byteVecPush(out, Machine.run(machine, data.length & 0xff)); + } + let original: Shape.Shape = shape(data); + if (original.tag === "Dot") { + original = shape(rt.byteSliceFrom(Uint8Array.of(1))); + rt.byteVecPush(out, 24); + if (original.tag === "Line") { + _114 = 25; + } else { + _114 = 26; + } + rt.byteVecPush(out, _114); + } +} + /** A `match` without arms on a scrutinee that diverges, not on an empty type. */ export function early(n: rt.u8): rt.u8 { return rt.u8WrappingAdd(n, 1); diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index a7eee77a6..fc5f77f69 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1173,6 +1173,7 @@ pub fn patterns(data: &[u8], out: &mut Vec) { out.extend_from_slice(format!("{parsed:?}").as_bytes()); payloads(data, out); known(data, out); + rematched(data, out); } /// `n`'s result: `Ok` for an even `n`. @@ -1357,6 +1358,185 @@ fn known(data: &[u8], out: &mut Vec) { out.push(moved()); } +/// Enums matched again where an enclosing match decided their variant. +fn rematched(data: &[u8], out: &mut Vec) { + let s = shape(data); + out.push(match s { + Shape::Dot => match s { + Shape::Line(..) => 1, + _ => 2, + }, + Shape::Line(from, _) => match s { + Shape::Line(_, to) => (from.x ^ to.y) as u8, + Shape::Dot | Shape::Rect { .. } => 3, + }, + Shape::Rect { .. } => 4, + }); + out.push(match s { + Shape::Dot => { + let copy = s; + match copy { + Shape::Line(..) => 5, + _ => 6, + } + } + _ => 7, + }); + // An arm that matches what the others left, and a borrow matched as the place. + out.push(match s { + Shape::Dot => 8, + _ => match &s { + Shape::Dot => 9, + Shape::Line(..) => 10, + Shape::Rect { width, .. } => *width as u8, + }, + }); + let d = dir(data.len() as u8); + out.push(match d { + Some(Dir::North) => match d { + Some(Dir::East) => 11, + Some(_) => 12, + None => 13, + }, + Some(d) => match d { + Dir::North => 14, + _ => d as u8, + }, + None => 15, + }); + let order = (data.len() as u8).cmp(&2); + out.push(match order { + std::cmp::Ordering::Less => match order { + std::cmp::Ordering::Equal => 16, + _ => 17, + }, + _ => 0, + }); + // What changes the place between the matches undecides it. + let mut m = s; + out.push(match m { + Shape::Dot => { + m = shape(&data[data.len().min(1)..]); + match m { + Shape::Line(..) => 18, + _ => 19, + } + } + _ => 20, + }); + let mut held = Some(m); + out.push(match held { + Some(_) => { + let taken = held.take(); + match held { + Some(_) => 21, + None => taken.map_or(22, |t| t.area() as u8), + } + } + None => 22, + }); + // What a loop knows on entry is what every way into it knows. + let mut cur = s; + for i in 0..3u8 { + cur = match cur { + Shape::Dot => Shape::Line(Point::new(i as i32, 0), Point::new(0, 0)), + Shape::Line(from, _) => match cur { + Shape::Line(_, to) => Shape::Rect { + corner: from, + width: to.x as u16 + 1, + height: 2, + }, + _ => Shape::Dot, + }, + Shape::Rect { width, .. } if width > 1 => Shape::Dot, + Shape::Rect { .. } => cur, + }; + out.push(cur.area() as u8); + } + let mut machine = Machine { state: s, steps: 0 }; + for _ in 0..4 { + out.push(machine.run(data.len() as u8)); + } + // A copy keeps what was known of its original after the original changes. + let mut original = shape(data); + if let Shape::Dot = original { + let copy = original; + original = shape(&[1]); + out.push(match copy { + Shape::Line(..) => 23, + _ => 24, + }); + out.push(match original { + Shape::Line(..) => 25, + _ => 26, + }); + } +} + +/// A state a method matches, changing it between its matches. +struct Machine { + state: Shape, + steps: u8, +} + +impl Machine { + fn step(&mut self) { + self.steps += 1; + self.state = match self.state { + Shape::Dot => Shape::Line(Point::new(1, 2), Point::new(3, 4)), + Shape::Line(from, _) => Shape::Rect { + corner: from, + width: 5, + height: 6, + }, + Shape::Rect { .. } => Shape::Dot, + }; + } + + /// Reads the state, which a shared borrow can't change. + #[inline(never)] + fn peek(&self) -> u8 { + self.steps ^ self.state.area() as u8 + } + + #[inline(never)] + fn log(&mut self, v: u8) -> u8 { + self.steps = self.steps.wrapping_add(v); + self.steps + } + + fn run(&mut self, n: u8) -> u8 { + match self.state { + Shape::Dot => { + self.step(); + match self.state { + Shape::Dot => 27, + _ => self.steps ^ n, + } + } + Shape::Line(..) => { + let seen = self.peek(); + match &self.state { + Shape::Line(_, to) => to.y as u8 ^ seen, + _ => 28, + } + } + Shape::Rect { width, .. } => { + // A two-phase borrow of `self`, which the match reads past. + let logged = self.log(match self.state { + Shape::Rect { height, .. } => height as u8, + _ => 29, + }); + self.step(); + match self.state { + Shape::Rect { .. } => 30, + _ => width as u8 ^ logged, + } + } + } + } +} + /// An enum without variants: no value of it exists. #[derive(Clone, Copy, Debug)] pub enum Void {} diff --git a/ts/fixtures/task/expected/drops.ts b/ts/fixtures/task/expected/drops.ts index 19f75e51f..709d6fee2 100644 --- a/ts/fixtures/task/expected/drops.ts +++ b/ts/fixtures/task/expected/drops.ts @@ -1393,7 +1393,7 @@ export function hashed(log: Log.Log, id: rt.u32, at: rt.u8): void { rt.drop(rt.entryRemove(_259, rt.drop)); unwind = 134; rt.entryDrop(_259, rt.drop); - } else if (!rt.entryOccupied(_259)) { + } else { rt.entryDrop(_259, rt.drop); } tally("counted"); diff --git a/ts/src/lower/mir/decided.rs b/ts/src/lower/mir/decided.rs new file mode 100644 index 000000000..56d6d124f --- /dev/null +++ b/ts/src/lower/mir/decided.rs @@ -0,0 +1,469 @@ +//! Switches an enclosing switch already decided: `match x { Dot => match x { .. } }` +//! tests `x` again where only `Dot` reaches. TypeScript narrows `x` in the arm and +//! refuses a test for another variant, so each such switch goes straight to the arms +//! that can still match. +//! +//! A forward dataflow over the body finds, at each switch on a place's variant, the +//! variants the place can hold: a switch's edge narrows them, and anything that can +//! change the place forgets them. + +use rustc_data_structures::fx::FxHashSet; +use rustc_index::IndexVec; +use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::{ + self, BasicBlock, BorrowKind, Local, Location, MutBorrowKind, Operand, Place, ProjectionElem, Rvalue, + StatementKind, SwitchTargets, TerminatorKind, +}; +use rustc_middle::ty::{self, Ty, TyCtxt}; + +/// Fold each switch in `body` that an enclosing switch decided. +pub fn fold<'tcx>(tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) { + let flow = Flow::new(tcx, body); + let mut entry: IndexVec>> = IndexVec::from_elem(None, &body.basic_blocks); + entry[mir::START_BLOCK] = Some(Facts::default()); + let mut work = vec![mir::START_BLOCK]; + while let Some(bb) = work.pop() { + let Some(facts) = entry[bb].clone() else { + continue; + }; + for (to, out) in flow.block(body, bb, facts).1 { + let joined = match &entry[to] { + None => out, + Some(old) => old.join(&out), + }; + if entry[to].as_ref() != Some(&joined) { + entry[to] = Some(joined); + work.push(to); + } + } + } + let mut folded = false; + for bb in body.basic_blocks.indices() { + let Some(facts) = entry[bb].clone() else { + continue; + }; + let (Some((def, kept, otherwise)), _) = flow.block(body, bb, facts) else { + continue; + }; + let data = &mut body.basic_blocks_mut()[bb]; + let TerminatorKind::SwitchInt { discr, targets } = &mut data.terminator_mut().kind else { + unreachable!("decided only for a switch") + }; + if kept.len() == targets.iter().count() { + continue; + } + folded = true; + if kept.iter().any(|&(_, t)| t != otherwise) { + *targets = SwitchTargets::new(kept.into_iter(), otherwise); + continue; + } + // A discriminant the switch moved has no other reader. + let moved = matches!(discr, Operand::Move(_)); + data.terminator_mut().kind = TerminatorKind::Goto { + target: otherwise, + loop_hint_attrs: Default::default(), + }; + if moved { + data.statements[def].kind = StatementKind::Nop; + } + } + // What only a folded edge reached is gone, so nothing it does counts as a use. + if folded { + let reachable = mir::traversal::reachable_as_bitset(body); + for (bb, data) in body.basic_blocks_mut().iter_enumerated_mut() { + if !reachable.contains(bb) { + data.statements.clear(); + data.terminator_mut().kind = TerminatorKind::Unreachable; + } + } + } +} + +/// The variants, by discriminant, that each place known so far can hold. +#[derive(Clone, Default, PartialEq)] +struct Facts<'tcx>(Vec<(Place<'tcx>, Vec)>); + +impl<'tcx> Facts<'tcx> { + /// What both `self` and `other` know. + fn join(&self, other: &Self) -> Self { + Self( + self.0 + .iter() + .filter_map(|(p, vs)| { + let (_, theirs) = other.0.iter().find(|(q, _)| q == p)?; + let mut all: Vec = vs.iter().chain(theirs).copied().collect(); + all.sort_unstable(); + all.dedup(); + Some((*p, all)) + }) + .collect(), + ) + } + + /// Forget what `gone` says of a place, and of the discriminants read in this block. + fn forget(&mut self, discrs: &mut Vec<(Local, usize, Place<'tcx>)>, gone: impl Fn(Place<'tcx>) -> bool) { + self.0.retain(|(p, _)| !gone(*p)); + discrs.retain(|(_, _, p)| !gone(*p)); + } +} + +/// A switch's statement that reads its discriminant, and the arms and default that can +/// still match. +type Decided = (usize, Vec<(u128, BasicBlock)>, BasicBlock); + +/// What a body's places are, for the dataflow. +struct Flow<'tcx> { + tcx: TyCtxt<'tcx>, + /// Each reference local's one assignment, as the place it borrows or the place behind + /// the reference it copies. + borrows: IndexVec>>, + /// Parameters assigned nowhere, which keep their value. + kept: IndexVec, + /// Locals something can change behind the dataflow's back, by a raw pointer or a + /// two-phase borrow. + escaped: IndexVec, +} + +impl<'tcx> Flow<'tcx> { + fn new(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) -> Self { + let n = body.local_decls.len(); + let mut defs: IndexVec = IndexVec::from_elem_n(0, n); + let mut rvalues: IndexVec>> = IndexVec::from_elem_n(None, n); + for data in body.basic_blocks.iter() { + for stmt in &data.statements { + if let StatementKind::Assign(assign) = &stmt.kind + && let Some(local) = assign.0.as_local() + { + defs[local] += 1; + rvalues[local] = Some(&assign.1); + } + } + if let TerminatorKind::Call { destination, .. } = &data.terminator().kind + && let Some(local) = destination.as_local() + { + defs[local] += 1; + } + } + let arg = |local: Local| (1..=body.arg_count).contains(&local.as_usize()); + let mut borrows = IndexVec::from_elem_n(None, n); + for (local, rvalue) in rvalues.iter_enumerated() { + if defs[local] != 1 || arg(local) || !body.local_decls[local].ty.is_ref() { + continue; + } + borrows[local] = match rvalue { + Some(Rvalue::Ref(_, _, place)) => Some(*place), + Some(Rvalue::Use(Operand::Copy(p) | Operand::Move(p), _) | Rvalue::CopyForDeref(p)) => { + Some(tcx.mk_place_deref(*p)) + } + _ => None, + }; + } + let kept = defs.iter_enumerated().map(|(local, &d)| d == 0 && arg(local)).collect(); + let mut flow = Self { + tcx, + borrows, + kept, + escaped: IndexVec::from_elem_n(false, n), + }; + for data in body.basic_blocks.iter() { + for stmt in &data.statements { + let StatementKind::Assign(assign) = &stmt.kind else { + continue; + }; + let escapes = match &assign.1 { + Rvalue::RawPtr(_, p) => Some(*p), + // Reads go past a two-phase borrow before it writes, which then forgets + // only what the reference is known to borrow. + Rvalue::Ref( + _, + BorrowKind::Mut { + kind: MutBorrowKind::TwoPhaseBorrow, + }, + p, + ) if flow.canon(tcx.mk_place_deref(assign.0)).local == assign.0.local => Some(*p), + _ => None, + }; + if let Some(p) = escapes { + let local = flow.canon(p).local; + flow.escaped[local] = true; + } + } + } + flow + } + + /// `place`, through each reference it reads that borrows a place that stays put. + fn canon(&self, mut place: Place<'tcx>) -> Place<'tcx> { + while let [ProjectionElem::Deref, rest @ ..] = place.projection.as_slice() + && let Some(borrowed) = self.borrows[place.local] + { + let borrowed = self.canon(borrowed); + let fixed = borrowed.projection.iter().enumerate().all(|(i, elem)| match elem { + ProjectionElem::Deref => i == 0 && self.kept[borrowed.local], + _ => !indexed(elem), + }); + if !fixed { + break; + } + place = borrowed.project_deeper(rest, self.tcx); + } + place + } + + /// Whether the dataflow can follow the variant `place` holds. + fn tracks(&self, body: &mir::Body<'tcx>, place: Place<'tcx>) -> bool { + !self.escaped[place.local] && !place.projection.iter().any(indexed) && variants(self.tcx, body, place).is_some() + } + + /// What a write to `place` makes unknown: `place` and what holds it, but not its own + /// parts, which a variant's payload is. + fn written(&self, place: Place<'tcx>) -> impl Fn(Place<'tcx>) -> bool + use<'tcx> { + let place = self.canon(place); + move |p| prefix(place, p) + } + + /// What a copy of a pointer `place` holds can change: what it points at, and whatever + /// is reached through a pointer it holds. + fn lent(&self, body: &mir::Body<'tcx>, place: Place<'tcx>) -> Option) -> bool + use<'tcx>> { + let ty = place.ty(&body.local_decls, self.tcx).ty; + if !lends(self.tcx, ty) { + return None; + } + let base = self.canon(place); + let pointee = (ty.is_ref() || ty.is_raw_ptr()).then(|| self.canon(self.tcx.mk_place_deref(place))); + Some(move |p: Place<'tcx>| { + pointee.is_some_and(|t| prefix(t, p)) + || p.projection.iter().enumerate().any(|(i, e)| { + matches!(e, ProjectionElem::Deref) + && base.local == p.local + && p.projection[..i].starts_with(base.projection) + }) + }) + } + + /// Run `bb` from `facts`: the switch it decided, if any, and the facts on each edge + /// that can be taken. + fn block( + &self, + body: &mir::Body<'tcx>, + bb: BasicBlock, + mut facts: Facts<'tcx>, + ) -> (Option, Vec<(BasicBlock, Facts<'tcx>)>) { + let data = &body.basic_blocks[bb]; + // The discriminants read in this block so far: their locals, statements, and places. + let mut discrs: Vec<(Local, usize, Place<'tcx>)> = Vec::new(); + for (i, stmt) in data.statements.iter().enumerate() { + let location = Location { + block: bb, + statement_index: i, + }; + for lent in lent_places(|v| v.visit_statement(stmt, location)) { + if let Some(gone) = self.lent(body, lent) { + facts.forget(&mut discrs, gone); + } + } + match &stmt.kind { + StatementKind::Assign(assign) => { + let (place, rvalue) = &**assign; + // A copy holds the variant its original does. + let copied: Vec<(Place<'tcx>, Vec)> = match rvalue { + Rvalue::Use(Operand::Copy(from) | Operand::Move(from), _) | Rvalue::CopyForDeref(from) => { + let (from, to) = (self.canon(*from), self.canon(*place)); + facts + .0 + .iter() + .filter(|(p, _)| prefix(from, *p)) + .map(|(p, vs)| { + let rest = &p.projection[from.projection.len()..]; + (to.project_deeper(rest, self.tcx), vs.clone()) + }) + .filter(|(p, _)| self.tracks(body, *p)) + .collect() + } + _ => Vec::new(), + }; + facts.forget(&mut discrs, self.written(*place)); + discrs.retain(|(d, _, _)| place.local != *d); + // A `&mut` can change what it borrows from then on. + if let Rvalue::Ref(_, BorrowKind::Mut { .. }, borrowed) = rvalue { + facts.forget(&mut discrs, self.written(*borrowed)); + } + facts.0.extend(copied); + if let Rvalue::Discriminant(of) = rvalue + && let Some(local) = place.as_local() + && self.tracks(body, self.canon(*of)) + { + discrs.push((local, i, self.canon(*of))); + } + } + StatementKind::SetDiscriminant { place, .. } => facts.forget(&mut discrs, self.written(**place)), + StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => { + facts.forget(&mut discrs, |p| p.local == *local); + } + _ => {} + } + } + let term = data.terminator(); + let location = Location { + block: bb, + statement_index: data.statements.len(), + }; + for lent in lent_places(|v| v.visit_terminator(term, location)) { + if let Some(gone) = self.lent(body, lent) { + facts.forget(&mut discrs, gone); + } + } + let mut out: Vec<(BasicBlock, Facts<'tcx>)> = Vec::new(); + let mut decided = None; + match &term.kind { + TerminatorKind::SwitchInt { + discr: Operand::Copy(d) | Operand::Move(d), + targets, + } if let Some(&(_, def, of)) = discrs.iter().find(|(l, _, _)| d.as_local() == Some(*l)) => { + let all = variants(self.tcx, body, of).expect("checked where read"); + let known = facts + .0 + .iter() + .find(|(p, _)| *p == of) + .map_or(all.clone(), |(_, vs)| vs.clone()); + let target = |v: u128| { + targets + .iter() + .find(|&(w, _)| w == v) + .map_or(targets.otherwise(), |(_, t)| t) + }; + // Each edge that can be taken, with the variants that take it. + for &v in &known { + match out.iter_mut().find(|(t, _)| *t == target(v)) { + Some((_, facts)) => facts.0.last_mut().expect("pushed below").1.push(v), + None => { + let mut facts = facts.clone(); + facts.0.retain(|(p, _)| *p != of); + facts.0.push((of, vec![v])); + out.push((target(v), facts)); + } + } + } + for (_, facts) in &mut out { + facts.0.last_mut().expect("pushed above").1.sort_unstable(); + } + let mut kept: Vec<(u128, BasicBlock)> = targets.iter().filter(|(v, _)| known.contains(v)).collect(); + let listed = |v: &u128| targets.iter().any(|(w, _)| w == *v); + let mut otherwise = targets.otherwise(); + // Where nothing reaches the default now, the last arm left takes its place. + if all.iter().any(|v| !listed(v)) + && known.iter().all(listed) + && let Some((_, last)) = kept.pop() + { + otherwise = last; + } + decided = Some((def, kept, otherwise)); + } + TerminatorKind::Goto { target, .. } + | TerminatorKind::Assert { target, .. } + | TerminatorKind::FalseEdge { + real_target: target, .. + } + | TerminatorKind::FalseUnwind { + real_target: target, .. + } => out.push((*target, facts.clone())), + TerminatorKind::Call { + destination, + target: Some(target), + .. + } => { + let mut facts = facts.clone(); + facts.forget(&mut discrs, self.written(*destination)); + out.push((*target, facts)); + } + TerminatorKind::Drop { place, target, .. } => { + let mut facts = facts.clone(); + facts.forget(&mut discrs, self.written(*place)); + // Drop glue gets a `&mut` to the value. + if let Some(gone) = self.lent(body, *place) { + facts.forget(&mut discrs, gone); + } + out.push((*target, facts)); + } + _ => {} + } + // Unwinding, and whatever else leaves, knows nothing. + if decided.is_none() { + for to in term.successors() { + if !out.iter().any(|(t, _)| *t == to) { + out.push((to, Facts::default())); + } + } + } + (decided, out) + } +} + +/// The places a statement or terminator copies or moves, and that a `CopyForDeref` +/// reads, as `visit` walks it. +fn lent_places<'tcx>(visit: impl FnOnce(&mut Operands<'tcx>)) -> Vec> { + let mut ops = Operands(Vec::new()); + visit(&mut ops); + ops.0 +} + +struct Operands<'tcx>(Vec>); + +impl<'tcx> Visitor<'tcx> for Operands<'tcx> { + fn visit_operand(&mut self, op: &Operand<'tcx>, _: Location) { + if let Operand::Copy(p) | Operand::Move(p) = op { + self.0.push(*p); + } + } + + fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { + if let Rvalue::CopyForDeref(p) = rvalue { + self.0.push(*p); + } + self.super_rvalue(rvalue, location); + } +} + +/// Whether a value of `ty` can change what it points at: it is or holds a `&mut` or a +/// `*mut`, or hides what it holds. +fn lends<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + let mut seen = FxHashSet::default(); + let mut stack = vec![ty]; + while let Some(ty) = stack.pop() { + for t in ty.walk().filter_map(|arg| arg.as_type()) { + match t.kind() { + ty::Ref(_, _, ty::Mutability::Mut) + | ty::RawPtr(_, ty::Mutability::Mut) + | ty::Dynamic(..) + | ty::Alias(..) + | ty::Param(_) => return true, + ty::Adt(adt, args) if adt.did().is_local() && seen.insert(t) => { + stack.extend(adt.all_fields().map(|field| field.ty(tcx, args).skip_norm_wip())); + } + _ => {} + } + } + } + false +} + +/// Whether `elem` picks an element, which a write to another element can be. +fn indexed(elem: ProjectionElem>) -> bool { + matches!( + elem, + ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } + ) +} + +/// Whether `a` is `b` or holds it. +fn prefix<'tcx>(a: Place<'tcx>, b: Place<'tcx>) -> bool { + a.local == b.local && b.projection.starts_with(a.projection) +} + +/// The discriminants of the enum at `place`, if it is one. +fn variants<'tcx>(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>, place: Place<'tcx>) -> Option> { + match place.ty(&body.local_decls, tcx).ty.kind() { + ty::Adt(adt, _) if adt.is_enum() => Some(adt.discriminants(tcx).map(|(_, d)| d.val).collect()), + _ => None, + } +} diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 5fe395a9c..00e4f7614 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -13,6 +13,7 @@ mod call; mod cfg; pub mod coroutine; +mod decided; pub mod glue; mod place; mod rvalue; @@ -76,6 +77,7 @@ 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); + decided::fold(tcx, &mut body); Some(body) } From 89be5ccffab0b4280d965999016e2f0dee6d56fb Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:32:19 -0700 Subject: [PATCH 3/8] chore(ts): regenerate snapshots after merging main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/shapes.Machine.ts | 3 +-- ts/fixtures/lang/expected/shapes.ts | 8 ++------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/ts/fixtures/lang/expected/shapes.Machine.ts b/ts/fixtures/lang/expected/shapes.Machine.ts index 774994b81..2677d4763 100644 --- a/ts/fixtures/lang/expected/shapes.Machine.ts +++ b/ts/fixtures/lang/expected/shapes.Machine.ts @@ -44,8 +44,7 @@ export function run(self: Machine, n: rt.u8): rt.u8 { } if (self.state.tag === "Line") { const seen: rt.u8 = peek(self); - const _12: rt.u8 = self.state._1.y & 0xff; - return _12 ^ seen; + return (self.state._1.y & 0xff) ^ seen; } const width: rt.u16 = self.state.width; const logged: rt.u8 = log(self, self.state.height & 0xff); diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index e290e869c..d8a68ca8c 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1586,10 +1586,7 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { if (s.tag === "Dot") { _5 = 2; } else if (s.tag === "Line") { - const from: Point.Point = s._0; - const to: Point.Point = s._1; - const _12: rt.i32 = from.x; - _5 = (_12 ^ to.y) & 0xff; + _5 = (s._0.x ^ s._1.y) & 0xff; } else { _5 = 4; } @@ -1617,8 +1614,7 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { _29 = { North: 1, East: 2, South: 4, West: 8 }[d] & 0xff; } rt.byteVecPush(out, _29); - const order_: rt.Ordering = rt.cmp(data.length & 0xff, 2); - if (order_ === -1) { + if (rt.cmp(data.length & 0xff, 2) === -1) { _43 = 17; } else { _43 = 0; From 492e6ce2630badb324f66b7df0daac5dab27f40d Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:31:36 -0700 Subject: [PATCH 4/8] chore(quest): add quest/m2/ts-stale-narrow.md Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 + quest/m2/ts-stale-narrow.md | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 quest/m2/ts-stale-narrow.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 8ad988267..2531aaaed 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -26,6 +26,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); ## Required +- [Tests TypeScript narrowed stale](/quest/m2/ts-stale-narrow.md) - a match after a call that changes its place, or after a library call's test, passes `tsc` - [Byte slices without objects](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` allocates nothing, neither a chunk view nor a `ByteSlice` - [Smaller output from MIR](/quest/m2/ts-mir-size.md) - the codec bundle shrinks back to THIR's gzipped size - [An A/A control that measures noise](/quest/m2/ts-bench-aa.md) - `just ts bench`'s A/A measures only noise, in every engine diff --git a/quest/m2/ts-stale-narrow.md b/quest/m2/ts-stale-narrow.md new file mode 100644 index 000000000..9e7f011ee --- /dev/null +++ b/quest/m2/ts-stale-narrow.md @@ -0,0 +1,17 @@ +# [M] Tests TypeScript narrowed stale + +## Goal + +The TypeScript translation passes `tsc` where TypeScript keeps a narrowing the program +no longer holds or the fold can't see: a match after a call that changes the place, as +`match self.state { Dot => { self.step(); match self.state { Line(..) => .. } } }`, and +a match after a library call's test, as `if order == Ordering::Less { match order { .. } }`. +The emitted JS doesn't change, and differential tests against native Rust that +type-check prove it. + +## Plan + +Found by [#110](https://github.com/kixelated/rust2/pull/110) on 2026-10-27; both fail +before it too. TypeScript keeps a property's narrowing across a call, and `===` narrows +as a switch does, so the test needs a type-only widening, and its payload reads a cast. +Prefer one mechanism beside `decided.rs` over casts per call site. From 13cf40e9e0f532a769620762aeb21c54dd7e2960 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:40:07 -0700 Subject: [PATCH 5/8] fix(ts): widen tests TypeScript narrowed stale Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 1 - quest/m2/ts-stale-narrow.md | 17 - ts/fixtures/lang/expected/lib.ts | 4 + ts/fixtures/lang/expected/shapes.Filled.ts | 49 +++ ts/fixtures/lang/expected/shapes.Machine.ts | 6 +- ts/fixtures/lang/expected/shapes.ts | 103 +++-- ts/fixtures/lang/src/shapes.rs | 79 +++- ts/src/lower/mir/decided.rs | 393 +++++++++++++++++--- ts/src/lower/mir/mod.rs | 73 +++- ts/src/lower/mir/place.rs | 100 ++++- 10 files changed, 700 insertions(+), 125 deletions(-) delete mode 100644 quest/m2/ts-stale-narrow.md create mode 100644 ts/fixtures/lang/expected/shapes.Filled.ts diff --git a/quest/m2/README.md b/quest/m2/README.md index 2531aaaed..8ad988267 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -26,7 +26,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); ## Required -- [Tests TypeScript narrowed stale](/quest/m2/ts-stale-narrow.md) - a match after a call that changes its place, or after a library call's test, passes `tsc` - [Byte slices without objects](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` allocates nothing, neither a chunk view nor a `ByteSlice` - [Smaller output from MIR](/quest/m2/ts-mir-size.md) - the codec bundle shrinks back to THIR's gzipped size - [An A/A control that measures noise](/quest/m2/ts-bench-aa.md) - `just ts bench`'s A/A measures only noise, in every engine diff --git a/quest/m2/ts-stale-narrow.md b/quest/m2/ts-stale-narrow.md deleted file mode 100644 index 9e7f011ee..000000000 --- a/quest/m2/ts-stale-narrow.md +++ /dev/null @@ -1,17 +0,0 @@ -# [M] Tests TypeScript narrowed stale - -## Goal - -The TypeScript translation passes `tsc` where TypeScript keeps a narrowing the program -no longer holds or the fold can't see: a match after a call that changes the place, as -`match self.state { Dot => { self.step(); match self.state { Line(..) => .. } } }`, and -a match after a library call's test, as `if order == Ordering::Less { match order { .. } }`. -The emitted JS doesn't change, and differential tests against native Rust that -type-check prove it. - -## Plan - -Found by [#110](https://github.com/kixelated/rust2/pull/110) on 2026-10-27; both fail -before it too. TypeScript keeps a property's narrowing across a call, and `===` narrows -as a switch does, so the test needs a type-only widening, and its payload reads a cast. -Prefer one mechanism beside `decided.rs` over casts per call site. diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index bc5f8c02c..785dd4ce6 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -78,6 +78,10 @@ export function copy$Option_Mutex_u8_u8(v: [rt.Mutex, rt.u8] | undefined) return v === undefined ? v : copy$Mutex_u8_u8(v); } +export function copy$Option_Shape(v: Shape.Shape | undefined): Shape.Shape | undefined { + return v === undefined ? v : copy$Shape(v); +} + export function copy$Option_Wrap_i16(v: Wrap.Wrap | undefined): Wrap.Wrap | undefined { return v === undefined ? v : copy$Wrap_i16(v); } diff --git a/ts/fixtures/lang/expected/shapes.Filled.ts b/ts/fixtures/lang/expected/shapes.Filled.ts new file mode 100644 index 000000000..7cf6793e3 --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Filled.ts @@ -0,0 +1,49 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { copy$Point } from "./lib.ts"; +import * as Point from "./shapes.Point.ts"; +import type * as Shape from "./shapes.Shape.ts"; + +/** An `Option` a method matches, filling it between its matches. */ +export interface Filled { + shape: Shape.Shape | undefined; +} + +export function fill(self: Filled): void { + let _2!: Shape.Shape | undefined; + if (self.shape === undefined) { + _2 = { tag: "Line", _0: copy$Point(Point.new(5, 6)), _1: copy$Point(Point.new(7, 8)) } as Shape.Shape; + } else if (self.shape.tag === "Dot") { + _2 = { tag: "Line", _0: copy$Point(Point.new(1, 2)), _1: copy$Point(Point.new(3, 4)) } as Shape.Shape; + } else { + _2 = undefined; + } + self.shape = _2; +} + +export function run(self: Filled): rt.u8 { + if (self.shape === undefined) { + fill(self); + if ((self.shape as Shape.Shape | undefined) === undefined) { + return 41; + } + if (((self.shape as Shape.Shape | undefined) as Shape.Shape).tag === "Line") { + return copy$Point((((self.shape as Shape.Shape | undefined) as Shape.Shape) as { tag: "Line"; _0: Point.Point; _1: Point.Point })._1).y & 0xff; + } + return 40; + } + if (self.shape.tag === "Dot") { + fill(self); + if ((self.shape as Shape.Shape | undefined) !== undefined) { + if ((self.shape as Shape.Shape).tag === "Line") { + return copy$Point(((self.shape as Shape.Shape) as { tag: "Line"; _0: Point.Point; _1: Point.Point })._0).x & 0xff; + } + } + return 42; + } + fill(self); + return 43; +} + +//# sourceMappingURL=shapes.Filled.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Machine.ts b/ts/fixtures/lang/expected/shapes.Machine.ts index 2677d4763..6d712088d 100644 --- a/ts/fixtures/lang/expected/shapes.Machine.ts +++ b/ts/fixtures/lang/expected/shapes.Machine.ts @@ -37,10 +37,10 @@ export function log(self: Machine, v: rt.u8): rt.u8 { export function run(self: Machine, n: rt.u8): rt.u8 { if (self.state.tag === "Dot") { step(self); - if (self.state.tag === "Dot") { - return 27; + if ((self.state as Shape.Shape).tag === "Line") { + return (copy$Point(((self.state as Shape.Shape) as { tag: "Line"; _0: Point.Point; _1: Point.Point })._1).x & 0xff) ^ self.steps ^ n; } - return self.steps ^ n; + return 27; } if (self.state.tag === "Line") { const seen: rt.u8 = peek(self); diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index d8a68ca8c..8d7f230bc 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1,9 +1,10 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Held, copy$Lens, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, 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 { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Held, copy$Lens, 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 * as Pair from "./fmt.Pair.ts"; import type * as Dir from "./shapes.Dir.ts"; +import * as Filled from "./shapes.Filled.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; import * as Machine from "./shapes.Machine.ts"; @@ -1577,11 +1578,15 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { let _19!: rt.u8; let _29!: rt.u8; let _43!: rt.u8; - let _48!: rt.u8; - let _59!: rt.u8; - let _68!: rt.u8; - let _72!: Shape.Shape; - let _114!: rt.u8; + let _50!: rt.u8; + let r!: rt.Result; + let _58!: rt.u8; + let _76!: rt.u8; + let _82!: rt.u8; + let _93!: rt.u8; + let _102!: rt.u8; + let _106!: Shape.Shape; + let _164!: rt.u8; const s: Shape.Shape = shape(data); if (s.tag === "Dot") { _5 = 2; @@ -1614,55 +1619,93 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { _29 = { North: 1, East: 2, South: 4, West: 8 }[d] & 0xff; } rt.byteVecPush(out, _29); - if (rt.cmp(data.length & 0xff, 2) === -1) { + const order_: rt.Ordering = rt.cmp(data.length & 0xff, 2); + if (order_ === -1) { _43 = 17; } else { _43 = 0; } rt.byteVecPush(out, _43); + if (order_ === -1) { + if ((order_ as rt.Ordering) === 0) { + _50 = 31; + } else { + _50 = 32; + } + rt.byteVecPush(out, _50); + } + if (!(data.length > 1)) { + r = rt.Err(2); + } else { + r = rt.Ok(1); + } + if (r.ok) { + if ((r as rt.Result).ok) { + _58 = ((r as rt.Result) as { ok: true; value: rt.u8 }).value; + } else { + _58 = ((r as rt.Result) as { ok: false; error: rt.u8 }).error; + } + rt.byteVecPush(out, _58); + } + let assigned = -1 as rt.Ordering; + if (data.length > 3) { + assigned = 1; + } + if (assigned === 0) { + rt.byteVecPush(out, 34); + } + const flow: rt.Result = step(0, data.length & 0xff); + if (!flow.ok) { + 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); + } + rt.byteVecPush(out, _76); + } let m: Shape.Shape = s; if (m.tag === "Dot") { m = shape(rt.byteSliceRange(data, rt.min(data.length, 1))); if (m.tag === "Line") { - _48 = 18; + _82 = 18; } else { - _48 = 19; + _82 = 19; } } else { - _48 = 20; + _82 = 20; } - rt.byteVecPush(out, _48); + rt.byteVecPush(out, _82); let held = copy$Shape(m) as Shape.Shape | undefined; if (held === undefined) { - _59 = 22; + _93 = 22; } else { const taken2 = held; held = undefined; const taken: Shape.Shape | undefined = taken2; - if (held === undefined) { - _59 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { + if ((held as Shape.Shape | undefined) === undefined) { + _93 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { return rt.u64Low(Shape.area$Area(t)) & 0xff; }); } else { - _59 = 21; + _93 = 21; } } - rt.byteVecPush(out, _59); + rt.byteVecPush(out, _93); let cur: Shape.Shape = s; let iterStart: rt.u8 = 0; const iterEnd: rt.u8 = 3; - while ((_68 = iterStart++) < iterEnd) { - const i: rt.u8 = _68; + while ((_102 = iterStart++) < iterEnd) { + const i: rt.u8 = _102; if (cur.tag === "Dot") { - _72 = { tag: "Line", _0: Point.new(i as rt.i32, 0), _1: Point.new(0, 0) } as Shape.Shape; + _106 = { tag: "Line", _0: Point.new(i as rt.i32, 0), _1: Point.new(0, 0) } as Shape.Shape; } else if (cur.tag === "Line") { - _72 = { tag: "Rect", corner: cur._0, width: rt.u16Add(cur._1.x & 0xffff, 1), height: 2 } as Shape.Shape; + _106 = { tag: "Rect", corner: cur._0, width: rt.u16Add(cur._1.x & 0xffff, 1), height: 2 } as Shape.Shape; } else if (!(cur.width > 1)) { - _72 = cur; + _106 = cur; } else { - _72 = { tag: "Dot" } as Shape.Shape; + _106 = { tag: "Dot" } as Shape.Shape; } - cur = _72; + cur = _106; rt.byteVecPush(out, rt.u64Low(Shape.area$Area(cur)) & 0xff); } const machine: Machine.Machine = { state: copy$Shape(s), steps: 0 }; @@ -1671,16 +1714,24 @@ 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 => { + return copy$Shape(s); + })) }; + let iterStart3: rt.i32 = 0; + const iterEnd3: rt.i32 = 3; + while (iterStart3++ < iterEnd3) { + rt.byteVecPush(out, Filled.run(filled)); + } let original: Shape.Shape = shape(data); if (original.tag === "Dot") { original = shape(rt.byteSliceFrom(Uint8Array.of(1))); rt.byteVecPush(out, 24); if (original.tag === "Line") { - _114 = 25; + _164 = 25; } else { - _114 = 26; + _164 = 26; } - rt.byteVecPush(out, _114); + rt.byteVecPush(out, _164); } } diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 321b72334..71e4e131a 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1423,6 +1423,35 @@ fn rematched(data: &[u8], out: &mut Vec) { }, _ => 0, }); + // A library call's test narrows what it reads, as a match would. + if order == std::cmp::Ordering::Less { + out.push(match order { + std::cmp::Ordering::Equal => 31, + _ => 32, + }); + } + let r: Result = if data.len() > 1 { Ok(1) } else { Err(2) }; + if r.is_ok() { + out.push(match r { + Ok(v) => v, + Err(e) => e, + }); + } + // So does what the place was assigned, before such a test. + let mut assigned = std::cmp::Ordering::Less; + if data.len() > 3 { + assigned = std::cmp::Ordering::Greater; + } + if assigned == std::cmp::Ordering::Equal { + out.push(34); + } + let flow = step(0, data.len() as u8); + if flow.is_break() { + out.push(match flow { + ControlFlow::Continue(n) => n as u8, + ControlFlow::Break(b) => b.unwrap_or(33), + }); + } // What changes the place between the matches undecides it. let mut m = s; out.push(match m { @@ -1468,6 +1497,12 @@ fn rematched(data: &[u8], out: &mut Vec) { for _ in 0..4 { out.push(machine.run(data.len() as u8)); } + let mut filled = Filled { + shape: dir(data.len() as u8).map(|_| s), + }; + for _ in 0..3 { + out.push(filled.run()); + } // A copy keeps what was known of its original after the original changes. let mut original = shape(data); if let Shape::Dot = original { @@ -1521,8 +1556,8 @@ impl Machine { Shape::Dot => { self.step(); match self.state { - Shape::Dot => 27, - _ => self.steps ^ n, + Shape::Line(_, to) => to.x as u8 ^ self.steps ^ n, + _ => 27, } } Shape::Line(..) => { @@ -1548,6 +1583,46 @@ impl Machine { } } +/// An `Option` a method matches, filling it between its matches. +struct Filled { + shape: Option, +} + +impl Filled { + #[inline(never)] + fn fill(&mut self) { + self.shape = match self.shape { + None => Some(Shape::Line(Point::new(5, 6), Point::new(7, 8))), + Some(Shape::Dot) => Some(Shape::Line(Point::new(1, 2), Point::new(3, 4))), + Some(_) => None, + }; + } + + fn run(&mut self) -> u8 { + match self.shape { + None => { + self.fill(); + match self.shape { + Some(Shape::Line(_, to)) => to.y as u8, + Some(_) => 40, + None => 41, + } + } + Some(Shape::Dot) => { + self.fill(); + match self.shape { + Some(Shape::Line(from, _)) => from.x as u8, + _ => 42, + } + } + Some(_) => { + self.fill(); + 43 + } + } + } +} + /// An enum without variants: no value of it exists. #[derive(Clone, Copy, Debug)] pub enum Void {} diff --git a/ts/src/lower/mir/decided.rs b/ts/src/lower/mir/decided.rs index 56d6d124f..84974e21f 100644 --- a/ts/src/lower/mir/decided.rs +++ b/ts/src/lower/mir/decided.rs @@ -6,43 +6,32 @@ //! A forward dataflow over the body finds, at each switch on a place's variant, the //! variants the place can hold: a switch's edge narrows them, and anything that can //! change the place forgets them. +//! +//! The same dataflow follows what TypeScript narrowed each place to, which only an +//! assignment it sees undoes. Where a call changed the place since, or a library call's +//! test narrowed it, [`narrowing`] finds the tests and payload reads that must see the +//! place's whole type. +use rustc_abi::VariantIdx; use rustc_data_structures::fx::FxHashSet; use rustc_index::IndexVec; -use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::visit::{PlaceContext, Visitor}; use rustc_middle::mir::{ self, BasicBlock, BorrowKind, Local, Location, MutBorrowKind, Operand, Place, ProjectionElem, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; /// Fold each switch in `body` that an enclosing switch decided. pub fn fold<'tcx>(tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) { let flow = Flow::new(tcx, body); - let mut entry: IndexVec>> = IndexVec::from_elem(None, &body.basic_blocks); - entry[mir::START_BLOCK] = Some(Facts::default()); - let mut work = vec![mir::START_BLOCK]; - while let Some(bb) = work.pop() { - let Some(facts) = entry[bb].clone() else { - continue; - }; - for (to, out) in flow.block(body, bb, facts).1 { - let joined = match &entry[to] { - None => out, - Some(old) => old.join(&out), - }; - if entry[to].as_ref() != Some(&joined) { - entry[to] = Some(joined); - work.push(to); - } - } - } + let entry = flow.solve(body); let mut folded = false; for bb in body.basic_blocks.indices() { let Some(facts) = entry[bb].clone() else { continue; }; - let (Some((def, kept, otherwise)), _) = flow.block(body, bb, facts) else { + let (Some((def, kept, otherwise)), _) = flow.block(body, bb, facts, None) else { continue; }; let data = &mut body.basic_blocks_mut()[bb]; @@ -79,32 +68,113 @@ pub fn fold<'tcx>(tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) { } } -/// The variants, by discriminant, that each place known so far can hold. +/// What the dataflow knows at a point. #[derive(Clone, Default, PartialEq)] -struct Facts<'tcx>(Vec<(Place<'tcx>, Vec)>); +struct Facts<'tcx> { + /// The variants, by discriminant, that each place known so far can hold. + known: Vec<(Place<'tcx>, Vec)>, + /// What TypeScript narrowed each place to since it last saw the place assigned: the + /// variants its tests left, or `None` where a library call's test narrowed it, and + /// what it holds, in a way the dataflow doesn't follow. + narrowed: Vec<(Place<'tcx>, Option>)>, +} impl<'tcx> Facts<'tcx> { - /// What both `self` and `other` know. + /// What both `self` and `other` know, and what either may have narrowed. fn join(&self, other: &Self) -> Self { - Self( - self.0 - .iter() - .filter_map(|(p, vs)| { - let (_, theirs) = other.0.iter().find(|(q, _)| q == p)?; - let mut all: Vec = vs.iter().chain(theirs).copied().collect(); - all.sort_unstable(); - all.dedup(); - Some((*p, all)) - }) - .collect(), - ) + let known = self + .known + .iter() + .filter_map(|(p, vs)| { + let (_, theirs) = other.known.iter().find(|(q, _)| q == p)?; + Some((*p, union(vs, theirs))) + }) + .collect(); + // What one way in left unnarrowed has its whole type. + let narrowed = self + .narrowed + .iter() + .filter_map(|(p, vs)| { + let (_, theirs) = other.narrowed.iter().find(|(q, _)| q == p)?; + Some((*p, vs.as_ref().zip(theirs.as_ref()).map(|(a, b)| union(a, b)))) + }) + .collect(); + Self { known, narrowed } } /// Forget what `gone` says of a place, and of the discriminants read in this block. fn forget(&mut self, discrs: &mut Vec<(Local, usize, Place<'tcx>)>, gone: impl Fn(Place<'tcx>) -> bool) { - self.0.retain(|(p, _)| !gone(*p)); + self.known.retain(|(p, _)| !gone(*p)); discrs.retain(|(_, _, p)| !gone(*p)); } + + /// What TypeScript narrowed `place` to: `Some(None)` where the dataflow can't name it, + /// and `None` where it didn't narrow it. + fn narrowing(&self, place: Place<'tcx>) -> Option> { + if self.narrowed.iter().any(|(p, vs)| vs.is_none() && prefix(*p, place)) { + return Some(None); + } + self.narrowed + .iter() + .find(|(p, _)| *p == place) + .map(|(_, vs)| vs.as_deref()) + } + + /// Record that TypeScript narrowed `place` to `to`. + fn narrow(&mut self, place: Place<'tcx>, to: Option>) { + self.narrowed.retain(|(p, _)| *p != place); + self.narrowed.push((place, to)); + } +} + +/// The tests and payload reads in a body that must see a place's whole type, since +/// TypeScript may have narrowed the place before a change it doesn't see, as a call's, +/// or by a library call's test. +#[derive(Default)] +pub struct Narrowing<'tcx> { + /// The statements reading the discriminant that a widened switch tests. + widened: FxHashSet, + /// Places read as a variant TypeScript may not have narrowed them to, with where. + stale: FxHashSet<(Location, Place<'tcx>)>, + /// The locals whose variant a library call's test reads. + tested: FxHashSet, +} + +impl<'tcx> Narrowing<'tcx> { + /// Whether the switch on the discriminant read `at` tests its place widened. + pub fn widened(&self, at: Location) -> bool { + self.widened.contains(&at) + } + + /// Whether `place`, read `at` as one of its variants, is cast to it. + pub fn stale(&self, at: Location, place: Place<'tcx>) -> bool { + self.stale.contains(&(at, place)) + } + + /// The locals whose variant a library call's test reads, which TypeScript narrows as + /// it does a switch's. + pub fn tested(&self) -> impl Iterator + '_ { + self.tested.iter().copied() + } +} + +/// Where `body`'s tests and payload reads must see a place's whole type. +pub fn narrowing<'tcx>(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) -> Narrowing<'tcx> { + let mut flow = Flow::new(tcx, body); + // A widened test narrows nothing, which can leave a later test to widen too. + loop { + let mut seen = Narrowing::default(); + for (bb, facts) in flow.solve(body).into_iter_enumerated() { + if let Some(facts) = facts { + flow.block(body, bb, facts, Some(&mut seen)); + } + } + let widened: FxHashSet = seen.widened.iter().map(|at| at.block).collect(); + if widened.is_subset(&flow.widened) { + return seen; + } + flow.widened.extend(widened); + } } /// A switch's statement that reads its discriminant, and the arms and default that can @@ -122,6 +192,10 @@ struct Flow<'tcx> { /// Locals something can change behind the dataflow's back, by a raw pointer or a /// two-phase borrow. escaped: IndexVec, + /// The `bool`s a switch branches on, or on the negation of. + conditions: IndexVec, + /// The switches on a variant that test their place widened, which narrows nothing. + widened: FxHashSet, } impl<'tcx> Flow<'tcx> { @@ -159,11 +233,32 @@ impl<'tcx> Flow<'tcx> { }; } let kept = defs.iter_enumerated().map(|(local, &d)| d == 0 && arg(local)).collect(); + let mut conditions: IndexVec = IndexVec::from_elem_n(false, n); + let mut work: Vec = body + .basic_blocks + .iter() + .filter_map(|data| match &data.terminator().kind { + TerminatorKind::SwitchInt { discr, .. } => discr.place()?.as_local(), + _ => None, + }) + .collect(); + while let Some(local) = work.pop() { + if !body.local_decls[local].ty.is_bool() || std::mem::replace(&mut conditions[local], true) { + continue; + } + if let Some(Rvalue::UnaryOp(mir::UnOp::Not, op) | Rvalue::Use(op, _)) = rvalues[local] + && let Some(from) = op.place().and_then(|p| p.as_local()) + { + work.push(from); + } + } let mut flow = Self { tcx, borrows, kept, escaped: IndexVec::from_elem_n(false, n), + conditions, + widened: FxHashSet::default(), }; for data in body.basic_blocks.iter() { for stmt in &data.statements { @@ -192,6 +287,29 @@ impl<'tcx> Flow<'tcx> { flow } + /// What is known as each block is entered, `None` where nothing reaches it. + fn solve(&self, body: &mir::Body<'tcx>) -> IndexVec>> { + let mut entry: IndexVec>> = IndexVec::from_elem(None, &body.basic_blocks); + entry[mir::START_BLOCK] = Some(Facts::default()); + let mut work = vec![mir::START_BLOCK]; + while let Some(bb) = work.pop() { + let Some(facts) = entry[bb].clone() else { + continue; + }; + for (to, out) in self.block(body, bb, facts, None).1 { + let joined = match &entry[to] { + None => out, + Some(old) => old.join(&out), + }; + if entry[to].as_ref() != Some(&joined) { + entry[to] = Some(joined); + work.push(to); + } + } + } + entry + } + /// `place`, through each reference it reads that borrows a place that stays put. fn canon(&self, mut place: Place<'tcx>) -> Place<'tcx> { while let [ProjectionElem::Deref, rest @ ..] = place.projection.as_slice() @@ -241,13 +359,79 @@ impl<'tcx> Flow<'tcx> { }) } + /// Whether TypeScript sees a write to `place` as an assignment to its path. + fn visible(&self, place: Place<'tcx>) -> bool { + self.canon(place) == place && !matches!(place.projection.last(), Some(ProjectionElem::Deref)) + } + + /// Whether a call to `func` may be written out as a test TypeScript narrows what it + /// reads by: a call into the library, as it writes `PartialEq::eq` of an `Ordering` + /// as `===` and `Result::is_ok` as `.ok`, whose result a switch branches on. + fn tests(&self, body: &mir::Body<'tcx>, func: &Operand<'tcx>, destination: Place<'tcx>) -> bool { + let Some((def, args)) = func.const_fn_def() else { + return false; + }; + destination.as_local().is_some_and(|local| self.conditions[local]) + && !matches!( + Instance::try_resolve(self.tcx, body.typing_env(self.tcx), def, args), + Ok(Some(instance)) if instance.def_id().is_local() + ) + } + + /// The enums that `ops` pass by shared reference or by copy. + fn read_places<'o>(&self, body: &mir::Body<'tcx>, ops: impl Iterator>) -> Vec> + where + 'tcx: 'o, + { + ops.filter_map(|op| { + let p = op.place()?; + let read = match p.ty(&body.local_decls, self.tcx).ty.kind() { + ty::Ref(_, _, ty::Mutability::Not) => self.tcx.mk_place_deref(p), + ty::Ref(..) | ty::RawPtr(..) => return None, + _ => p, + }; + Some(self.canon(read)) + }) + .filter(|p| self.tracks(body, *p)) + .collect() + } + + /// Mark what `visit` reads as a variant where TypeScript may not have narrowed it to + /// that variant: narrowed to others, or in a way the dataflow can't name. + fn read_variants( + &self, + body: &mir::Body<'tcx>, + facts: &Facts<'tcx>, + location: Location, + seen: &mut Narrowing<'tcx>, + visit: impl FnOnce(&mut Downcasts<'tcx>), + ) { + let mut reads = Downcasts(self.tcx, Vec::new()); + visit(&mut reads); + for (base, variant) in reads.1 { + let ty::Adt(adt, _) = base.ty(&body.local_decls, self.tcx).ty.kind() else { + continue; + }; + let discr = adt.discriminant_for_variant(self.tcx, variant).val; + let stale = match facts.narrowing(self.canon(base)) { + None => false, + Some(None) => true, + Some(Some(vs)) => vs != [discr], + }; + if stale { + seen.stale.insert((location, base)); + } + } + } + /// Run `bb` from `facts`: the switch it decided, if any, and the facts on each edge - /// that can be taken. + /// that can be taken. With `seen`, record where TypeScript's narrowing is stale. fn block( &self, body: &mir::Body<'tcx>, bb: BasicBlock, mut facts: Facts<'tcx>, + mut seen: Option<&mut Narrowing<'tcx>>, ) -> (Option, Vec<(BasicBlock, Facts<'tcx>)>) { let data = &body.basic_blocks[bb]; // The discriminants read in this block so far: their locals, statements, and places. @@ -257,6 +441,9 @@ impl<'tcx> Flow<'tcx> { block: bb, statement_index: i, }; + if let Some(seen) = seen.as_deref_mut() { + self.read_variants(body, &facts, location, seen, |v| v.visit_statement(stmt, location)); + } for lent in lent_places(|v| v.visit_statement(stmt, location)) { if let Some(gone) = self.lent(body, lent) { facts.forget(&mut discrs, gone); @@ -265,30 +452,48 @@ impl<'tcx> Flow<'tcx> { match &stmt.kind { StatementKind::Assign(assign) => { let (place, rvalue) = &**assign; - // A copy holds the variant its original does. - let copied: Vec<(Place<'tcx>, Vec)> = match rvalue { + // A copy holds the variant its original does, and TypeScript narrows + // what it is assigned to the copy's type. + let (copied, narrowed) = match rvalue { Rvalue::Use(Operand::Copy(from) | Operand::Move(from), _) | Rvalue::CopyForDeref(from) => { let (from, to) = (self.canon(*from), self.canon(*place)); - facts - .0 + let rebase = |p: &Place<'tcx>| { + let rest = &p.projection[from.projection.len()..]; + to.project_deeper(rest, self.tcx) + }; + let copied = facts + .known .iter() .filter(|(p, _)| prefix(from, *p)) - .map(|(p, vs)| { - let rest = &p.projection[from.projection.len()..]; - (to.project_deeper(rest, self.tcx), vs.clone()) - }) + .map(|(p, vs)| (rebase(p), vs.clone())) .filter(|(p, _)| self.tracks(body, *p)) - .collect() + .collect(); + let mut narrowed: Vec<(Place<'tcx>, Option>)> = facts + .narrowed + .iter() + .filter(|(p, _)| prefix(from, *p)) + .map(|(p, vs)| (rebase(p), vs.clone())) + .collect(); + if facts.narrowing(from) == Some(None) { + narrowed.retain(|(p, _)| *p != to); + narrowed.push((to, None)); + } + (copied, narrowed) } - _ => Vec::new(), + _ => (Vec::new(), Vec::new()), }; - facts.forget(&mut discrs, self.written(*place)); + let gone = self.written(*place); + if self.visible(*place) { + facts.narrowed.retain(|(p, _)| !gone(*p)); + facts.narrowed.extend(narrowed); + } + facts.forget(&mut discrs, gone); discrs.retain(|(d, _, _)| place.local != *d); // A `&mut` can change what it borrows from then on. if let Rvalue::Ref(_, BorrowKind::Mut { .. }, borrowed) = rvalue { facts.forget(&mut discrs, self.written(*borrowed)); } - facts.0.extend(copied); + facts.known.extend(copied); if let Rvalue::Discriminant(of) = rvalue && let Some(local) = place.as_local() && self.tracks(body, self.canon(*of)) @@ -308,6 +513,9 @@ impl<'tcx> Flow<'tcx> { block: bb, statement_index: data.statements.len(), }; + if let Some(seen) = seen.as_deref_mut() { + self.read_variants(body, &facts, location, seen, |v| v.visit_terminator(term, location)); + } for lent in lent_places(|v| v.visit_terminator(term, location)) { if let Some(gone) = self.lent(body, lent) { facts.forget(&mut discrs, gone); @@ -322,7 +530,7 @@ impl<'tcx> Flow<'tcx> { } if let Some(&(_, def, of)) = discrs.iter().find(|(l, _, _)| d.as_local() == Some(*l)) => { let all = variants(self.tcx, body, of).expect("checked where read"); let known = facts - .0 + .known .iter() .find(|(p, _)| *p == of) .map_or(all.clone(), |(_, vs)| vs.clone()); @@ -332,20 +540,42 @@ impl<'tcx> Flow<'tcx> { .find(|&(w, _)| w == v) .map_or(targets.otherwise(), |(_, t)| t) }; + // A test for a variant TypeScript narrowed the place away from reads it + // widened. + let narrowed = facts.narrowing(of).map(|vs| vs.map(<[u128]>::to_vec)); + let widened = self.widened.contains(&bb); + let stale = match &narrowed { + None => false, + Some(None) => targets.iter().next().is_some(), + Some(Some(vs)) => targets.iter().any(|(v, _)| !vs.contains(&v)), + }; + if (widened || stale) + && let Some(seen) = seen + { + seen.widened.insert(Location { + block: bb, + statement_index: def, + }); + } // Each edge that can be taken, with the variants that take it. for &v in &known { match out.iter_mut().find(|(t, _)| *t == target(v)) { - Some((_, facts)) => facts.0.last_mut().expect("pushed below").1.push(v), + Some((_, facts)) => facts.known.last_mut().expect("pushed below").1.push(v), None => { let mut facts = facts.clone(); - facts.0.retain(|(p, _)| *p != of); - facts.0.push((of, vec![v])); + facts.known.retain(|(p, _)| *p != of); + facts.known.push((of, vec![v])); out.push((target(v), facts)); } } } - for (_, facts) in &mut out { - facts.0.last_mut().expect("pushed above").1.sort_unstable(); + for (to, facts) in &mut out { + facts.known.last_mut().expect("pushed above").1.sort_unstable(); + // What TypeScript narrowed it to, less what the tests on the way rule out. + if !widened { + let left = narrowed.clone().flatten().unwrap_or_else(|| all.clone()); + facts.narrow(of, Some(left.into_iter().filter(|&v| target(v) == *to).collect())); + } } let mut kept: Vec<(u128, BasicBlock)> = targets.iter().filter(|(v, _)| known.contains(v)).collect(); let listed = |v: &u128| targets.iter().any(|(w, _)| w == *v); @@ -359,6 +589,19 @@ impl<'tcx> Flow<'tcx> { } decided = Some((def, kept, otherwise)); } + // A test of anything else changes nothing. What is known stays with the + // switches on a variant, which fold by it. + TerminatorKind::SwitchInt { targets, .. } => { + let facts = Facts { + known: Vec::new(), + narrowed: facts.narrowed.clone(), + }; + for &to in targets.all_targets() { + if !out.iter().any(|(t, _)| *t == to) { + out.push((to, facts.clone())); + } + } + } TerminatorKind::Goto { target, .. } | TerminatorKind::Assert { target, .. } | TerminatorKind::FalseEdge { @@ -368,12 +611,26 @@ impl<'tcx> Flow<'tcx> { real_target: target, .. } => out.push((*target, facts.clone())), TerminatorKind::Call { + func, + args, destination, target: Some(target), .. } => { let mut facts = facts.clone(); - facts.forget(&mut discrs, self.written(*destination)); + let gone = self.written(*destination); + if self.visible(*destination) { + facts.narrowed.retain(|(p, _)| !gone(*p)); + } + facts.forget(&mut discrs, gone); + if self.tests(body, func, *destination) { + for read in self.read_places(body, args.iter().map(|arg| &arg.node)) { + facts.narrow(read, None); + if let Some(seen) = seen.as_deref_mut() { + seen.tested.insert(read.local); + } + } + } out.push((*target, facts)); } TerminatorKind::Drop { place, target, .. } => { @@ -424,6 +681,28 @@ impl<'tcx> Visitor<'tcx> for Operands<'tcx> { } } +/// The places a statement or terminator reads or writes as one of their variants, with +/// that variant. +struct Downcasts<'tcx>(TyCtxt<'tcx>, Vec<(Place<'tcx>, VariantIdx)>); + +impl<'tcx> Visitor<'tcx> for Downcasts<'tcx> { + fn visit_place(&mut self, place: &Place<'tcx>, _: PlaceContext, _: Location) { + for (base, elem) in place.iter_projections() { + if let ProjectionElem::Downcast(_, variant) = elem { + self.1.push((base.to_place(self.0), variant)); + } + } + } +} + +/// The variants in either of `a` and `b`, in order. +fn union(a: &[u128], b: &[u128]) -> Vec { + let mut all: Vec = a.iter().chain(b).copied().collect(); + all.sort_unstable(); + all.dedup(); + all +} + /// Whether a value of `ty` can change what it points at: it is or holds a `&mut` or a /// `*mut`, or hides what it holds. fn lends<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index b15853a22..4b4cc2602 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -233,6 +233,10 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { tested: IndexVec, /// The names of those that hold a value TypeScript would narrow by what it is assigned. widened: FxHashSet, + /// The tests and payload reads TypeScript may have narrowed stale. + narrowing: decided::Narrowing<'tcx>, + /// The statement or terminator being lowered. + at: mir::Location, } impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { @@ -290,6 +294,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { switched: FxHashSet::default(), tested: IndexVec::from_elem_n(false, n), widened: FxHashSet::default(), + narrowing: decided::narrowing(tcx, mir), + at: mir::START_BLOCK.start_location(), }; fx.analyze(); fx @@ -1115,10 +1121,10 @@ 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. + /// Mark the locals whose variant a switch or a library call's test 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(); + let mut work: Vec = self.narrowing.tested().collect(); for data in self.mir.basic_blocks.iter() { for stmt in &data.statements { let StatementKind::Assign(assign) = &stmt.kind else { @@ -1201,6 +1207,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { value } + /// The whole type of the place whose discriminant `discr` holds. + fn scrutinee_ty(&mut self, discr: Local, span: Span) -> Type { + let Some(Rvalue::Discriminant(place)) = self.def_rvalue(discr) else { + unreachable!("widened only where a discriminant is read") + }; + match place.as_local() { + Some(local) => self.decl_ty(local), + None => self.b.t.ty(place.ty(&self.mir.local_decls, self.tcx).ty, span), + } + } + /// 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]?; @@ -1949,6 +1966,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.set_unwind(data.terminator(), out); for (i, stmt) in data.statements.iter().enumerate() { if !self.in_ignored(stmt.source_info.span) && !self.noops.contains(&(bb, i)) { + self.at = mir::Location { + block: bb, + statement_index: i, + }; self.statement(stmt, out); } } @@ -1957,6 +1978,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { if let Some(&to) = self.redirect.get(&bb) { return Exit::Goto(to.as_usize()); } + self.at = mir::Location { + block: bb, + statement_index: data.statements.len(), + }; self.terminator(data.terminator(), out) } @@ -2235,14 +2260,33 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Operand::Copy(p) | Operand::Move(p) => p.as_local(), _ => None, }; + // A variant TypeScript may have narrowed the place away from is tested on the + // place's whole type. + let whole = discr_local + .filter(|&l| { + self.def_at[l].is_some_and(|(bb, i)| { + self.narrowing.widened(mir::Location { + block: bb, + statement_index: i, + }) + }) + }) + .map(|l| self.scrutinee_ty(l, span)); + let widen = |test: Expr, read: &Expr| match (&whole, read.path_key()) { + (Some(whole), Some(key)) => widen_reads(test, &key, whole), + _ => test, + }; let tests: Vec<(Expr, BasicBlock)> = match discr_local.map(|l| self.slots[l].clone()) { Some(Slot::Discr(Some((scrut, ty)))) => { - if !arms.is_empty() { + if !arms.is_empty() && whole.is_none() { self.switched.extend(scrut.path_key()); } let tests: Vec = arms .iter() - .map(|&(value, _)| self.variant_test(&scrut, ty, value, span)) + .map(|&(value, _)| { + let test = self.variant_test(&scrut, ty, value, span); + widen(test, &scrut) + }) .collect(); // What one test reads that is held back folds into it; of several, all but // the first may not run. @@ -2283,7 +2327,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { None => self.err(span, format!("a switch on `{ty}`")), }, }; - tests.push((test, target)); + tests.push((widen(test, &value), target)); } // What the tests read that is held back folds into them. let targets: Vec = tests.iter().map(|(_, t)| *t).collect(); @@ -2831,6 +2875,23 @@ fn subst(e: &mut Expr, name: &str, value: &Expr) -> bool { } } +/// `test` with each read of the path `key` cast to its whole type `ty`, which TypeScript +/// narrows nothing by. +fn widen_reads(test: Expr, key: &str, ty: &Type) -> Expr { + let widen = |e: Box| Box::new(widen_reads(*e, key, ty)); + match test { + e if e.path_key().as_deref() == Some(key) => Expr::As(Box::new(e), ty.clone()), + Expr::Member(base, k) => Expr::Member(widen(base), k), + Expr::Index(base, index) => Expr::Index(widen(base), widen(index)), + Expr::Call(f, args) => Expr::Call(widen(f), args.into_iter().map(|e| widen_reads(e, key, ty)).collect()), + Expr::Unary(op, e) => Expr::Unary(op, widen(e)), + Expr::Located(loc, e) => Expr::Located(loc, widen(e)), + Expr::Binary(l, op, r) => Expr::Binary(widen(l), op, widen(r)), + Expr::Cond(c, a, b) => Expr::Cond(widen(c), widen(a), widen(b)), + e => e, + } +} + /// Drop the declarations of variables nothing reads, keeping the effects of what was /// assigned to them. fn prune_unread(stmts: &mut Vec) { diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 35e68123b..77197d0f0 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::{self, Instance, Ty}; use rustc_span::Span; use super::{Env, Fx, Slot}; -use crate::lower::library::Std; +use crate::lower::library::{Flow, Std}; use crate::lower::num::Int; use crate::lower::{AdtRepr, ObjectKind}; use crate::ts::{Expr, Stmt, StmtKind}; @@ -97,7 +97,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { _ => unreachable!("a checked pair is a tuple"), }); } - for elem in projection { + while let Some(elem) = projection.next() { let ty = pty.ty; match elem { ProjectionElem::Deref => { @@ -114,7 +114,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { e = self.field(e, ty, pty.variant_index, field, span); } ProjectionElem::Downcast(_, variant) => { - if !e.path_key().is_some_and(|key| self.switched.contains(&key)) { + let read = place.projection.len() - projection.len() - 1; + let base = Place { + local: place.local, + projection: tcx.mk_place_elems(&place.projection[..read]), + }; + if self.narrowing.stale(self.at, base) { + e = self.as_stale_variant(e, base, ty, variant, span); + } else if !e.path_key().is_some_and(|key| self.switched.contains(&key)) { e = self.as_variant(e, ty, variant, span); } } @@ -210,20 +217,87 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { /// others can't be, as a derived `==` reads the other operand after comparing /// discriminants. `tsc` narrows only what a switch tests. fn as_variant(&mut self, base: Expr, ty: Ty<'tcx>, variant: VariantIdx, span: Span) -> Expr { + match ty.kind() { + ty::Adt(adt, _) if adt.did().is_local() => match self.variant_ty(ty, variant, span) { + Some(variant) => Expr::As(Box::new(base), variant), + None => base, + }, + _ => base, + } + } + + /// `base`, the `place` of a `ty`, cast to its `variant` through its whole type: + /// TypeScript may have narrowed it to another before a change it doesn't see. + fn as_stale_variant( + &mut self, + base: Expr, + place: Place<'tcx>, + ty: Ty<'tcx>, + variant: VariantIdx, + span: Span, + ) -> Expr { + let Some(variant) = self.variant_ty(ty, variant, span) else { + return self.err( + span, + format!("a payload of `{ty}` read where TypeScript narrowed it to another variant"), + ); + }; + let whole = match place.as_local() { + Some(local) => self.decl_ty(local), + None => self.b.t.ty(ty, span), + }; + Expr::As(Box::new(Expr::As(Box::new(base), whole)), variant) + } + + /// The JS type of `ty`'s `variant`, for a type whose variants hold their payloads: + /// a union's member, `Result`'s and `ControlFlow`'s, or `Option`'s and `Poll`'s value. + fn variant_ty(&mut self, ty: Ty<'tcx>, variant: VariantIdx, span: Span) -> Option { let tcx = self.tcx; let ty::Adt(adt, args) = ty.kind() else { - return base; + return None; }; - if !adt.did().is_local() || !matches!(self.b.t.adt(*adt, span).repr, AdtRepr::Union) { - return base; - } - let def = adt.variant(variant); - let mut fields = vec![("tag".to_string(), crate::ts::Type::StrLit(def.name.to_string()))]; - for (i, field) in def.fields.iter().enumerate() { - let ty = self.b.t.ty(field.ty(tcx, args).skip_norm_wip(), span); - fields.push((crate::lower::field_name(field.name.as_str(), i), ty)); + // `rt.Result`'s variants. + let result = |ok: bool, payload| { + let (flag, name) = match ok { + true => ("true", "value"), + false => ("false", "error"), + }; + crate::ts::Type::Object(vec![ + ("ok".into(), crate::ts::Type::Builtin(flag)), + (name.into(), payload), + ]) + }; + match Std::of(tcx, adt.did()) { + Some(Std::Option | Std::Poll) => { + let payload = adt.variant(variant).fields.iter().next()?; + Some(self.b.t.ty(payload.ty(tcx, args).skip_norm_wip(), span)) + } + Some(Std::Result) => { + let payload = self.b.t.ty(args.type_at(variant.index()), span); + Some(result(variant.index() == 0, payload)) + } + // What `control_flow_field` reads of each variant. + Some(Std::ControlFlow) => { + let (breaks, continues) = (args.type_at(0), args.type_at(1)); + Some(match (Flow::of(tcx, args), variant.index()) { + (Flow::Option, 0) => self.b.t.ty(continues, span), + (Flow::Option, _) => crate::ts::Type::Builtin("undefined"), + (Flow::Result | Flow::Other, 0) => result(true, self.b.t.ty(continues, span)), + (Flow::Result, _) => self.b.t.ty(breaks, span), + (Flow::Other, _) => result(false, self.b.t.ty(breaks, span)), + }) + } + None if adt.did().is_local() && matches!(self.b.t.adt(*adt, span).repr, AdtRepr::Union) => { + let def = adt.variant(variant); + let mut fields = vec![("tag".to_string(), crate::ts::Type::StrLit(def.name.to_string()))]; + for (i, field) in def.fields.iter().enumerate() { + let ty = self.b.t.ty(field.ty(tcx, args).skip_norm_wip(), span); + fields.push((crate::lower::field_name(field.name.as_str(), i), ty)); + } + Some(crate::ts::Type::Object(fields)) + } + _ => None, } - Expr::As(Box::new(base), crate::ts::Type::Object(fields)) } /// A field of `base`, a `ty`, in `variant` if it was downcast to one. From a94197142d00bc1c2036006416007129c88073ec Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:25:25 -0700 Subject: [PATCH 6/8] fix(ts): follow a reference only while nothing can repoint it `Flow::new` counted a reference local's whole-local assignments and call destinations, so a reference repointed through a `&mut` to it (`*rr = &b`, a reborrow of that, a closure capturing it, `mem::swap`) or a parameter repointed the same way kept its stale referent, and a reachable arm folded away. Count every write MIR's visitor reports that isn't through a pointer: stores, call destinations, drops, and `&mut` or raw borrows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/lang/expected/shapes.ts | 99 +++++++++++++++++++++++++++++ ts/fixtures/lang/src/shapes.rs | 85 +++++++++++++++++++++++++ ts/src/lower/mir/decided.rs | 37 +++++++---- 3 files changed, 208 insertions(+), 13 deletions(-) diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index cf58389d1..e154b8bd1 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1683,6 +1683,105 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, _114); } + reseated(data, out); +} + +/** + * A reference pointed elsewhere without an assignment to it: through a `&mut` to it, + * a reborrow of that, a closure, and a call. + */ +export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { + let _12!: rt.u8; + let _19!: rt.u8; + let _26!: rt.u8; + let _37!: rt.u8; + let _51!: rt.u8; + const _5: [Shape.Shape, Shape.Shape] = [shape(data), shape(rt.byteSliceFrom(Uint8Array.of(1)))]; + const a: Shape.Shape = _5[0]; + const b: Shape.Shape = _5[1]; + let r: Shape.Shape = a; + if (r.tag === "Dot") { + r = b; + if (r.tag === "Line") { + _12 = 27; + } else { + _12 = 28; + } + } else { + _12 = 29; + } + rt.byteVecPush(out, _12); + let r2: Shape.Shape = a; + if (r2.tag === "Dot") { + r2 = b; + if (r2.tag === "Line") { + _19 = 30; + } else { + _19 = 31; + } + } else { + _19 = 32; + } + rt.byteVecPush(out, _19); + let r3: Shape.Shape = a; + if (r3.tag === "Dot") { + ((): void => { + r3 = b; + })(); + if (r3.tag === "Line") { + _26 = 36; + } else { + _26 = 37; + } + } else { + _26 = 38; + } + rt.byteVecPush(out, _26); + let r4: Shape.Shape = a; + let other: Shape.Shape = b; + if (r4.tag === "Dot") { + const swapped = r4; + r4 = other; + other = swapped; + if (r4.tag === "Line") { + _37 = 39; + } else { + _37 = 40; + } + } else { + _37 = 41; + } + rt.byteVecPush(out, _37); + let r5: Shape.Shape = a; + let iterStart: rt.i32 = 0; + const iterEnd: rt.i32 = 2; + while (iterStart++ < iterEnd) { + if (r5.tag === "Dot") { + r5 = b; + if (r5.tag === "Line") { + _51 = 42; + } else { + _51 = 43; + } + } else { + _51 = 44; + } + rt.byteVecPush(out, _51); + } + rt.byteVecPush(out, rebound(a, b)); +} + +/** A parameter pointed elsewhere, after a copy of it that still points where it did. */ +export function rebound(r: Shape.Shape, b: Shape.Shape): rt.u8 { + const kept: Shape.Shape = r; + r = b; + if (r.tag === "Line") { + if (kept.tag === "Line") { + return 45; + } + return 46; + } + return 47; } /** A `match` without arms on a scrutinee that diverges, not on an empty type. */ diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index e75771d11..b34d30265 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1492,6 +1492,91 @@ fn rematched(data: &[u8], out: &mut Vec) { _ => 26, }); } + reseated(data, out); +} + +/// A reference pointed elsewhere without an assignment to it: through a `&mut` to it, +/// a reborrow of that, a closure, and a call. +fn reseated(data: &[u8], out: &mut Vec) { + let (a, b) = (shape(data), shape(&[1])); + let mut r = &a; + out.push(match *r { + Shape::Dot => { + let rr = &mut r; + *rr = &b; + match *r { + Shape::Line(..) => 27, + _ => 28, + } + } + _ => 29, + }); + let mut r = &a; + out.push(match *r { + Shape::Dot => { + let rr = &mut r; + let again = &mut *rr; + *again = &b; + match *r { + Shape::Line(..) => 30, + _ => 31, + } + } + _ => 32, + }); + let mut r = &a; + out.push(match *r { + Shape::Dot => { + let mut point = || r = &b; + point(); + match *r { + Shape::Line(..) => 36, + _ => 37, + } + } + _ => 38, + }); + let mut r = &a; + let mut other = &b; + out.push(match *r { + Shape::Dot => { + std::mem::swap(&mut r, &mut other); + match *r { + Shape::Line(..) => 39, + _ => 40, + } + } + _ => 41, + }); + let mut r = &a; + for _ in 0..2 { + out.push(match *r { + Shape::Dot => { + let rr = &mut r; + *rr = &b; + match *r { + Shape::Line(..) => 42, + _ => 43, + } + } + _ => 44, + }); + } + out.push(rebound(&a, &b)); +} + +/// A parameter pointed elsewhere, after a copy of it that still points where it did. +fn rebound<'a>(mut r: &'a Shape, b: &'a Shape) -> u8 { + let kept = r; + let rr = &mut r; + *rr = b; + match *r { + Shape::Line(..) => match *kept { + Shape::Line(..) => 45, + _ => 46, + }, + _ => 47, + } } /// A state a method matches, changing it between its matches. diff --git a/ts/src/lower/mir/decided.rs b/ts/src/lower/mir/decided.rs index 56d6d124f..3b8f80f9d 100644 --- a/ts/src/lower/mir/decided.rs +++ b/ts/src/lower/mir/decided.rs @@ -9,7 +9,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_index::IndexVec; -use rustc_middle::mir::visit::Visitor; +use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{ self, BasicBlock, BorrowKind, Local, Location, MutBorrowKind, Operand, Place, ProjectionElem, Rvalue, StatementKind, SwitchTargets, TerminatorKind, @@ -114,10 +114,10 @@ type Decided = (usize, Vec<(u128, BasicBlock)>, BasicBlock); /// What a body's places are, for the dataflow. struct Flow<'tcx> { tcx: TyCtxt<'tcx>, - /// Each reference local's one assignment, as the place it borrows or the place behind - /// the reference it copies. + /// Each reference local whose one write is an assignment, as the place it borrows or + /// the place behind the reference it copies. borrows: IndexVec>>, - /// Parameters assigned nowhere, which keep their value. + /// Parameters written nowhere, which keep their value. kept: IndexVec, /// Locals something can change behind the dataflow's back, by a raw pointer or a /// two-phase borrow. @@ -127,27 +127,24 @@ struct Flow<'tcx> { impl<'tcx> Flow<'tcx> { fn new(tcx: TyCtxt<'tcx>, body: &mir::Body<'tcx>) -> Self { let n = body.local_decls.len(); - let mut defs: IndexVec = IndexVec::from_elem_n(0, n); + let mut writes = Writes(IndexVec::from_elem_n(0, n)); + writes.visit_body(body); + let writes = writes.0; let mut rvalues: IndexVec>> = IndexVec::from_elem_n(None, n); for data in body.basic_blocks.iter() { for stmt in &data.statements { if let StatementKind::Assign(assign) = &stmt.kind && let Some(local) = assign.0.as_local() { - defs[local] += 1; rvalues[local] = Some(&assign.1); } } - if let TerminatorKind::Call { destination, .. } = &data.terminator().kind - && let Some(local) = destination.as_local() - { - defs[local] += 1; - } } let arg = |local: Local| (1..=body.arg_count).contains(&local.as_usize()); let mut borrows = IndexVec::from_elem_n(None, n); for (local, rvalue) in rvalues.iter_enumerated() { - if defs[local] != 1 || arg(local) || !body.local_decls[local].ty.is_ref() { + // Its one write is this assignment, so nothing points it elsewhere. + if writes[local] != 1 || arg(local) || !body.local_decls[local].ty.is_ref() { continue; } borrows[local] = match rvalue { @@ -158,7 +155,7 @@ impl<'tcx> Flow<'tcx> { _ => None, }; } - let kept = defs.iter_enumerated().map(|(local, &d)| d == 0 && arg(local)).collect(); + let kept = writes.iter_enumerated().map(|(local, &w)| w == 0 && arg(local)).collect(); let mut flow = Self { tcx, borrows, @@ -399,6 +396,20 @@ impl<'tcx> Flow<'tcx> { } } +/// How often each local is written itself, not through a pointer it holds: assigned, a +/// call's destination, dropped, or borrowed `&mut` or raw, which can write it later. +struct Writes(IndexVec); + +impl<'tcx> Visitor<'tcx> for Writes { + fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _: Location) { + let writes = context.is_mutating_use() + || context == PlaceContext::NonMutatingUse(NonMutatingUseContext::RawBorrow); + if writes && !place.is_indirect() { + self.0[place.local] += 1; + } + } +} + /// The places a statement or terminator copies or moves, and that a `CopyForDeref` /// reads, as `visit` walks it. fn lent_places<'tcx>(visit: impl FnOnce(&mut Operands<'tcx>)) -> Vec> { From 79137f0af56fc4db43e71edd875346ca9295586e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:29:29 -0700 Subject: [PATCH 7/8] style(ts): format decided.rs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/src/lower/mir/decided.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ts/src/lower/mir/decided.rs b/ts/src/lower/mir/decided.rs index 3b8f80f9d..24999e4c3 100644 --- a/ts/src/lower/mir/decided.rs +++ b/ts/src/lower/mir/decided.rs @@ -155,7 +155,10 @@ impl<'tcx> Flow<'tcx> { _ => None, }; } - let kept = writes.iter_enumerated().map(|(local, &w)| w == 0 && arg(local)).collect(); + let kept = writes + .iter_enumerated() + .map(|(local, &w)| w == 0 && arg(local)) + .collect(); let mut flow = Self { tcx, borrows, @@ -402,8 +405,8 @@ struct Writes(IndexVec); impl<'tcx> Visitor<'tcx> for Writes { fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _: Location) { - let writes = context.is_mutating_use() - || context == PlaceContext::NonMutatingUse(NonMutatingUseContext::RawBorrow); + let writes = + context.is_mutating_use() || context == PlaceContext::NonMutatingUse(NonMutatingUseContext::RawBorrow); if writes && !place.is_indirect() { self.0[place.local] += 1; } From 29f9d306c9b173da4dfc1b6bc227ef43b5322391 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:11:06 -0700 Subject: [PATCH 8/8] fix(ts): read a stale map entry's payload without a cast `rt.Entry` is one class for either variant, so TypeScript narrows nothing by its test and a stale payload read needs no cast. It errored instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HRfpGSuhrqBv8bAxEvpXi3 --- ts/fixtures/lang/expected/shapes.ts | 62 ++++++++++++++++++----------- ts/fixtures/lang/src/shapes.rs | 13 ++++++ ts/src/lower/mir/place.rs | 4 ++ 3 files changed, 56 insertions(+), 23 deletions(-) diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 4b4d036ca..c4c1aaa11 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1620,11 +1620,12 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { let r!: rt.Result; let _58!: rt.u8; let _76!: rt.u8; - let _82!: rt.u8; - let _93!: rt.u8; - let _102!: rt.u8; - let _106!: Shape.Shape; - let _164!: rt.u8; + let _97!: rt.u8; + let _107!: rt.u8; + let _118!: rt.u8; + let _127!: rt.u8; + let _131!: Shape.Shape; + let _189!: rt.u8; const s: Shape.Shape = shape(data); if (s.tag === "Dot") { _5 = 2; @@ -1701,49 +1702,64 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { } rt.byteVecPush(out, _76); } + const counts: rt.HashMap = rt.hashNew() as rt.HashMap; + if (rt.usizeRem(data.length, 2) === 0) { + rt.hashInsert(counts, data.length & 0xff, 35); + } + const entry: rt.Entry | undefined = rt.entry(counts, data.length & 0xff); + if (entry !== undefined) { + if ((entry as rt.Entry | undefined) === undefined) { + _97 = 37; + } else if (rt.entryOccupied(((entry as rt.Entry | undefined) as rt.Entry) as rt.Entry)) { + _97 = rt.entryGet((entry as rt.Entry | undefined) as rt.Entry); + } else { + _97 = rt.entryOrInsertMut((entry as rt.Entry | undefined) as rt.Entry, 36).v; + } + rt.byteVecPush(out, _97); + } let m: Shape.Shape = s; if (m.tag === "Dot") { m = shape(rt.byteSliceRange(data, rt.min(data.length, 1))); if (m.tag === "Line") { - _82 = 18; + _107 = 18; } else { - _82 = 19; + _107 = 19; } } else { - _82 = 20; + _107 = 20; } - rt.byteVecPush(out, _82); + rt.byteVecPush(out, _107); let held = copy$Shape(m) as Shape.Shape | undefined; if (held === undefined) { - _93 = 22; + _118 = 22; } else { const taken2 = held; held = undefined; const taken: Shape.Shape | undefined = taken2; if ((held as Shape.Shape | undefined) === undefined) { - _93 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { + _118 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { return rt.u64Low(Shape.area$Area(t)) & 0xff; }); } else { - _93 = 21; + _118 = 21; } } - rt.byteVecPush(out, _93); + rt.byteVecPush(out, _118); let cur: Shape.Shape = s; let iterStart: rt.u8 = 0; const iterEnd: rt.u8 = 3; - while ((_102 = iterStart++) < iterEnd) { - const i: rt.u8 = _102; + while ((_127 = iterStart++) < iterEnd) { + const i: rt.u8 = _127; if (cur.tag === "Dot") { - _106 = { tag: "Line", _0: Point.new(i as rt.i32, 0), _1: Point.new(0, 0) } as Shape.Shape; + _131 = { tag: "Line", _0: Point.new(i as rt.i32, 0), _1: Point.new(0, 0) } as Shape.Shape; } else if (cur.tag === "Line") { - _106 = { tag: "Rect", corner: cur._0, width: rt.u16Add(cur._1.x & 0xffff, 1), height: 2 } as Shape.Shape; + _131 = { tag: "Rect", corner: cur._0, width: rt.u16Add(cur._1.x & 0xffff, 1), height: 2 } as Shape.Shape; } else if (!(cur.width > 1)) { - _106 = cur; + _131 = cur; } else { - _106 = { tag: "Dot" } as Shape.Shape; + _131 = { tag: "Dot" } as Shape.Shape; } - cur = _106; + cur = _131; rt.byteVecPush(out, rt.u64Low(Shape.area$Area(cur)) & 0xff); } const machine: Machine.Machine = { state: copy$Shape(s), steps: 0 }; @@ -1765,11 +1781,11 @@ export function rematched(data: rt.ByteSlice, out: rt.ByteVec): void { original = shape(rt.byteSliceFrom(Uint8Array.of(1))); rt.byteVecPush(out, 24); if (original.tag === "Line") { - _164 = 25; + _189 = 25; } else { - _164 = 26; + _189 = 26; } - rt.byteVecPush(out, _164); + rt.byteVecPush(out, _189); } reseated(data, out); } diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index a21fc4520..3ae38c6f6 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1512,6 +1512,19 @@ fn rematched(data: &[u8], out: &mut Vec) { ControlFlow::Break(b) => b.unwrap_or(33), }); } + // A map's entry is one value for either variant, which TypeScript narrows nothing by. + let mut counts = std::collections::HashMap::new(); + if data.len() % 2 == 0 { + counts.insert(data.len() as u8, 35); + } + let entry = Some(counts.entry(data.len() as u8)); + if entry.is_some() { + out.push(match entry { + Some(std::collections::hash_map::Entry::Occupied(e)) => *e.get(), + Some(std::collections::hash_map::Entry::Vacant(e)) => *e.insert(36), + None => 37, + }); + } // What changes the place between the matches undecides it. let mut m = s; out.push(match m { diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 4f785b940..2140383dd 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -286,6 +286,10 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { variant: VariantIdx, span: Span, ) -> Expr { + // `rt.Entry` is one class for either variant, which TypeScript narrows nothing by. + if matches!(ty.kind(), ty::Adt(adt, _) if matches!(Std::of(self.tcx, adt.did()), Some(Std::Entry))) { + return base; + } let Some(variant) = self.variant_ty(ty, variant, span) else { return self.err( span,