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/5] 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/5] 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/5] 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 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 4/5] 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 5/5] 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; }