diff --git a/ts/fixtures/lang/expected/lib.ts b/ts/fixtures/lang/expected/lib.ts index d68584d40..6dba18ef6 100644 --- a/ts/fixtures/lang/expected/lib.ts +++ b/ts/fixtures/lang/expected/lib.ts @@ -86,6 +86,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 e3974fb86..c4c1aaa11 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -1,10 +1,11 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { copy$ControlFlow_Arc_u8_u8s, copy$ControlFlow_unit_u8s, copy$Gauge, copy$Held, copy$Lens, copy$Level, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, copy$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$Gauge, copy$Held, copy$Lens, copy$Level, copy$Mutex_u8_u8, copy$Mutex_u8s, copy$Option_Mutex_u8_u8, copy$Option_Shape, copy$Point, copy$Point_u8, copy$Points, copy$Poll_u8s, copy$Result_Mutex_u8_u8_u8, copy$Shape, copy$u8_u8, copy$u8s } from "./lib.ts"; import * as Pair from "./fmt.Pair.ts"; import { advance, reset$Gauge } from "./generics.ts"; import type * as Dir from "./shapes.Dir.ts"; +import * as Filled from "./shapes.Filled.ts"; import type * as Gauge from "./shapes.Gauge.ts"; import type * as Held from "./shapes.Held.ts"; import type * as Lens from "./shapes.Lens.ts"; @@ -1615,11 +1616,16 @@ 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 _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; @@ -1652,55 +1658,108 @@ 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); + } + 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") { - _48 = 18; + _107 = 18; } else { - _48 = 19; + _107 = 19; } } else { - _48 = 20; + _107 = 20; } - rt.byteVecPush(out, _48); + rt.byteVecPush(out, _107); let held = copy$Shape(m) as Shape.Shape | undefined; if (held === undefined) { - _59 = 22; + _118 = 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) { + _118 = rt.optionMapOr(taken, 22, (t: Shape.Shape): rt.u8 => { return rt.u64Low(Shape.area$Area(t)) & 0xff; }); } else { - _59 = 21; + _118 = 21; } } - rt.byteVecPush(out, _59); + rt.byteVecPush(out, _118); 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 ((_127 = iterStart++) < iterEnd) { + const i: rt.u8 = _127; if (cur.tag === "Dot") { - _72 = { 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") { - _72 = { 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)) { - _72 = cur; + _131 = cur; } else { - _72 = { tag: "Dot" } as Shape.Shape; + _131 = { tag: "Dot" } as Shape.Shape; } - cur = _72; + cur = _131; rt.byteVecPush(out, rt.u64Low(Shape.area$Area(cur)) & 0xff); } const machine: Machine.Machine = { state: copy$Shape(s), steps: 0 }; @@ -1709,16 +1768,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; + _189 = 25; } else { - _114 = 26; + _189 = 26; } - rt.byteVecPush(out, _114); + rt.byteVecPush(out, _189); } reseated(data, out); } @@ -1739,7 +1806,7 @@ export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { let r: Shape.Shape = a; if (r.tag === "Dot") { r = b; - if (r.tag === "Line") { + if ((r as Shape.Shape).tag === "Line") { _12 = 27; } else { _12 = 28; @@ -1751,7 +1818,7 @@ export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { let r2: Shape.Shape = a; if (r2.tag === "Dot") { r2 = b; - if (r2.tag === "Line") { + if ((r2 as Shape.Shape).tag === "Line") { _19 = 30; } else { _19 = 31; @@ -1765,7 +1832,7 @@ export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { ((): void => { r3 = b; })(); - if (r3.tag === "Line") { + if ((r3 as Shape.Shape).tag === "Line") { _26 = 36; } else { _26 = 37; @@ -1780,7 +1847,7 @@ export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { const swapped = r4; r4 = other; other = swapped; - if (r4.tag === "Line") { + if ((r4 as Shape.Shape).tag === "Line") { _37 = 39; } else { _37 = 40; @@ -1795,7 +1862,7 @@ export function reseated(data: rt.ByteSlice, out: rt.ByteVec): void { while (iterStart++ < iterEnd) { if (r5.tag === "Dot") { r5 = b; - if (r5.tag === "Line") { + if ((r5 as Shape.Shape).tag === "Line") { _51 = 42; } else { _51 = 43; diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 76ad0edf3..3ae38c6f6 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1483,6 +1483,48 @@ 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), + }); + } + // 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 { @@ -1528,6 +1570,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 { @@ -1666,8 +1714,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(..) => { @@ -1693,6 +1741,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 24999e4c3..441f88900 100644 --- a/ts/src/lower/mir/decided.rs +++ b/ts/src/lower/mir/decided.rs @@ -6,7 +6,13 @@ //! 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::{NonMutatingUseContext, PlaceContext, Visitor}; @@ -14,35 +20,18 @@ 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> { .iter_enumerated() .map(|(local, &w)| w == 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, .. } => { @@ -438,6 +695,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 28e2b4a8d..4df5f56c6 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -239,6 +239,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> { @@ -297,6 +301,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 @@ -1128,12 +1134,12 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } - /// Mark the locals whose variant a switch tests, that a closure or async block - /// captures and could test, or that std takes, whose runtime function infers its type - /// parameters from them, and what references to them borrow. + /// Mark the locals whose variant a switch or a library call's test tests, that a + /// closure or async block captures and could test, or that std takes, whose runtime + /// function infers its type parameters from them, and what references to them borrow. fn find_tested(&mut self) { let tcx = self.tcx; - let mut work = Vec::new(); + let mut work: Vec = self.narrowing.tested().collect(); for data in self.mir.basic_blocks.iter() { if let TerminatorKind::Call { func, args, .. } = &data.terminator().kind && let ty::FnDef(def_id, _) = *func.ty(&self.mir.local_decls, tcx).kind() @@ -1217,6 +1223,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]?; @@ -2035,6 +2052,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); } } @@ -2043,6 +2064,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) } @@ -2356,14 +2381,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. @@ -2404,7 +2448,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(); @@ -2966,6 +3010,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 437add783..2140383dd 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, Pending, Slot}; -use crate::lower::library::Std; +use crate::lower::library::{Flow, Std}; use crate::lower::num::Int; use crate::lower::{AdtRepr, ObjectKind, byte_array, bytes_ref}; use crate::ts::{Expr, Stmt, StmtKind}; @@ -114,7 +114,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { // Whether `e` is an `rt.ByteSlice` of the place's bytes: a `[u8]`, or a `[u8; N]` // behind a reference. let mut in_bytes = false; - for elem in projection { + while let Some(elem) = projection.next() { let ty = pty.ty; in_bytes = in_bytes || byte_slice(ty); match elem { @@ -132,7 +132,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); } } @@ -260,20 +267,91 @@ 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 { + // `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, + 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.