From 060450291ef9b054bbebbc9052228c978f65b9db Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:26:06 -0700 Subject: [PATCH 1/2] chore(quest): claim quest/m3/ts-uninhabited-switch.md Quest-Claim: 3b5c14ab7924d823 From fb76607f6937d6646c62588c528fd9825bb1e128 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:37:42 -0700 Subject: [PATCH 2/2] fix(ts): read no scrutinee for a switch whose other variants can't exist A pattern on a part of a non-path place, such as `let (Ok(a), Ok(b)) = (wide, wider);` of two `Result<_, Infallible>`s, switches to `unreachable` for each part's other variant. Lowering drops that one-way switch, but its discriminant read was already spilled to an unused `const scrutinee`, which `tsc` refuses. Such a read now runs only for its effects. A switch's narrowing is also keyed by the enum it tests, so `Some(Ok(r))` of an `Option>`, whose `Some` is the path itself, still casts to `Ok`. Co-Authored-By: Claude Opus 5.5 --- quest/m3/README.md | 1 - quest/m3/ts-uninhabited-switch.md | 24 -------- ts/fixtures/lang/expected/core/bool.ts | 8 +++ ts/fixtures/lang/expected/harness.ts | 8 ++- ts/fixtures/lang/expected/ints.ts | 10 ++-- ts/fixtures/lang/expected/shapes.Partial.ts | 9 +++ ts/fixtures/lang/expected/shapes.Parts.ts | 12 ++++ ts/fixtures/lang/expected/shapes.ts | 57 +++++++++++++++++- ts/fixtures/lang/src/harness.rs | 1 + ts/fixtures/lang/src/ints.rs | 4 +- ts/fixtures/lang/src/shapes.rs | 66 +++++++++++++++++++++ ts/src/lower/mir/mod.rs | 34 +++++++++-- ts/src/lower/mir/place.rs | 2 +- 13 files changed, 191 insertions(+), 45 deletions(-) delete mode 100644 quest/m3/ts-uninhabited-switch.md create mode 100644 ts/fixtures/lang/expected/shapes.Partial.ts create mode 100644 ts/fixtures/lang/expected/shapes.Parts.ts diff --git a/quest/m3/README.md b/quest/m3/README.md index e2b7da99a..d09dabbd1 100644 --- a/quest/m3/README.md +++ b/quest/m3/README.md @@ -34,5 +34,4 @@ generic std gap is planned here even when moq never calls it. - [Peekable::next_if_eq against another type](/quest/m3/ts-next-if-eq-other.md) - `next_if_eq` with an expected value of another type than the item, such as a `&str` of `String` items, translates - [Waiting: a slice object for a mutable part of other values](/quest/m3/ts-slice-object.md) - waits on a moq profile showing the `Proxy` view's traps matter, then decides on an `rt.ByteSlice`-like form - [Port the workflow guard to kixelated/quest](/quest/m3/quest-workflow-guard.md) - quest's environment guard parses YAML as this repository's does -- [A switch whose other variants are uninhabited](/quest/m3/ts-uninhabited-switch.md) - a tuple's `Result<_, Infallible>`s matched or bound by `let` type-checks, its discriminant reads no longer left unused - [A parameter read only where lowering leaves nothing](/quest/m3/ts-unread-params.md) - an instance whose lowering drops every read of a parameter marks it unused, so `tsc` accepts it diff --git a/quest/m3/ts-uninhabited-switch.md b/quest/m3/ts-uninhabited-switch.md deleted file mode 100644 index b63709727..000000000 --- a/quest/m3/ts-uninhabited-switch.md +++ /dev/null @@ -1,24 +0,0 @@ -# [S] A switch whose other variants are uninhabited - -## Goal - -[rust2-ts](/ts/README.md) translates a match or `let` that tests a part of a tuple or -other non-path place whose other variants can't exist, such as -`let (Ok(a), Ok(b)) = (wide, wider);` of two `Result<_, Infallible>`s, without leaving the -discriminant it read unused, so `tsc` accepts it, proven by differential tests against -native Rust. - -## Plan - -Found by the quest that typed an infallible `try_from` by its `Infallible`, on 2026-10-30: -MIR reads each part's discriminant and switches to `unreachable` otherwise; lowering drops -that one-way switch, but the read was already spilled to a `const scrutinee` (the -`Slot::Discr` assignment in `ts/src/lower/mir/mod.rs`), which `noUnusedLocals` refuses. -A single `match` or `let Ok(x) = r` of such a `Result` already type-checks. No consumer -hits it at the pin. - -Public API: the translator's output. - -## Related - -- [A parameter read only where lowering leaves nothing](/quest/m3/ts-unread-params.md) - the same kind of read lowering leaves unused, of a parameter diff --git a/ts/fixtures/lang/expected/core/bool.ts b/ts/fixtures/lang/expected/core/bool.ts index a7a5a0c55..e04f0b6d3 100644 --- a/ts/fixtures/lang/expected/core/bool.ts +++ b/ts/fixtures/lang/expected/core/bool.ts @@ -2,6 +2,7 @@ import * as rt from "../rt.ts"; import * as Made from "../defaults.Made.ts"; +import type * as Void from "../shapes.Void.ts"; export function thenSome$1jqdi5p(self: boolean, t: rt.Duration): rt.Duration | undefined { if (!self) { @@ -17,6 +18,13 @@ export function thenSome$1d6toqn(self: boolean, t: undefined): undefined | rt.No return t; } +export function thenSome$0ztng9q(self: boolean, t: rt.Result): rt.Result | undefined { + if (!self) { + return undefined; + } + return t; +} + export function thenSome$0kwiij6(self: boolean, t: rt.i16): rt.i16 | undefined { if (!self) { return undefined; diff --git a/ts/fixtures/lang/expected/harness.ts b/ts/fixtures/lang/expected/harness.ts index 22487a7bf..f5a000130 100644 --- a/ts/fixtures/lang/expected/harness.ts +++ b/ts/fixtures/lang/expected/harness.ts @@ -33,7 +33,7 @@ import { objects } from "./objects.ts"; import { orders, bytes as orders_bytes } from "./orders.ts"; import { lists, shared as pointers_shared, places, unchecked, nested as pointers_nested, copies as pointers_copies, sentinels, cells as pointers_cells, rebound, writers, made } from "./pointers.ts"; import { refs, toRefs } from "./refs.ts"; -import { copies as shapes_copies, order, discriminants, loops, patterns, closures, library, flows } from "./shapes.ts"; +import { copies as shapes_copies, order, discriminants, loops, patterns, uninhabited, closures, library, flows } from "./shapes.ts"; import { parts, chunked, subslices, drains, ranges as slices_ranges, edits as slices_edits } from "./slices.ts"; import { splits } from "./splits.ts"; import { statics, cells as statics_cells, onces } from "./statics.ts"; @@ -90,7 +90,7 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) refs(data21, out21); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::counts", (_2121: rt.u8, data22: rt.ByteSlice, out22: rt.ByteVec): void => { counts(data22, out22); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _396: rt.ByteSlice, out23: rt.ByteVec): void => { + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["fmt::rounding", (_2122: rt.u8, _399: rt.ByteSlice, out23: rt.ByteVec): void => { rounding(out23); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["iters::skips", skips] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["wrappers::wrappers", wrappers] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["edits::edits", edits] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["utf8::decodes", decodes] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["floats::floats", floats] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["atomics::atomics", atomics] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["keys::overrides", overrides] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["dyns::dyns", (_2123: rt.u8, data23: rt.ByteSlice, out24: rt.ByteVec): void => { dyns(data23, out24); @@ -180,7 +180,9 @@ export function cases(): [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) made(data65, out66); }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["arrays::as_slices", (_2166: rt.u8, data66: rt.ByteSlice, out67: rt.ByteVec): void => { asSlices(data66, out67); - }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["ints::widenings", widenings] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]; + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["ints::widenings", widenings] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void], ["shapes::uninhabited", (_2167: rt.u8, data67: rt.ByteSlice, out68: rt.ByteVec): void => { + uninhabited(data67, out68); + }] as [string, (a0: rt.u8, a1: rt.ByteSlice, a2: rt.ByteVec) => void]]; } /** Run one case. */ diff --git a/ts/fixtures/lang/expected/ints.ts b/ts/fixtures/lang/expected/ints.ts index 68baf82bb..046353f16 100644 --- a/ts/fixtures/lang/expected/ints.ts +++ b/ts/fixtures/lang/expected/ints.ts @@ -5805,12 +5805,10 @@ export function widenings(kind: rt.u8, data: rt.ByteSlice, out: rt.ByteVec): voi break; } const c2: rt.char = _1371; - const wide: rt.Result = rt.Ok(c2 as rt.u32); - const wider: rt.Result = rt.Ok(c2 as rt.u64); - const widest: rt.Result = rt.Ok(c2 as rt.u128); - const a: rt.u32 = (wide as { ok: true; value: rt.u32 }).value; - const b3: rt.u64 = (wider as { ok: true; value: rt.u64 }).value; - const c3: rt.u128 = (widest as { ok: true; value: rt.u128 }).value; + const _1381: [rt.Result, rt.Result, rt.Result] = [rt.Ok(c2 as rt.u32), rt.Ok(c2 as rt.u64), rt.Ok(c2 as rt.u128)]; + const a: rt.u32 = (_1381[0] as { ok: true; value: rt.u32 }).value; + const b3: rt.u64 = (_1381[1] as { ok: true; value: rt.u64 }).value; + const c3: rt.u128 = (_1381[2] as { ok: true; value: rt.u128 }).value; rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u32ToBeBytes(a))); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u64ToBeBytes(b3))); rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u128ToBeBytes(c3))); diff --git a/ts/fixtures/lang/expected/shapes.Partial.ts b/ts/fixtures/lang/expected/shapes.Partial.ts new file mode 100644 index 000000000..f5b65acea --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Partial.ts @@ -0,0 +1,9 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Void from "./shapes.Void.ts"; + +/** An enum whose other variant holds a value that can't exist. */ +export type Partial = { tag: "Real"; _0: rt.u8 } | { tag: "Never"; _0: Void.Void }; + +//# sourceMappingURL=shapes.Partial.ts.map diff --git a/ts/fixtures/lang/expected/shapes.Parts.ts b/ts/fixtures/lang/expected/shapes.Parts.ts new file mode 100644 index 000000000..5bcc4fc8d --- /dev/null +++ b/ts/fixtures/lang/expected/shapes.Parts.ts @@ -0,0 +1,12 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Void from "./shapes.Void.ts"; + +/** A struct whose fields' other variants can't exist. */ +export interface Parts { + left: rt.Result; + right: rt.Result | undefined; +} + +//# sourceMappingURL=shapes.Parts.ts.map diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index cdbd437cc..7709d90f6 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -2,7 +2,7 @@ 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$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 { then$1i9qaz4, then$1btzga3 } from "./core/bool.ts"; +import { thenSome$0ztng9q, then$1i9qaz4, then$1btzga3 } from "./core/bool.ts"; import { unwrapOr$0r2bmpr, map$0600mq0, map$076et51, mapOr$1ybqvup, mapOr$1hjjwvv, mapOr$0rtdylj, mapOr$0aserv9, mapOr$1a3irjf, mapOr$1t0muvr, okOr$1vxk0yk } from "./core/option.ts"; import { map$1dbyvzi, mapErr$0dzqwjy } from "./core/result.ts"; import * as Pair from "./fmt.Pair.ts"; @@ -18,6 +18,8 @@ import type * as Mark from "./shapes.Mark.ts"; import * as Meters from "./shapes.Meters.ts"; import * as Moved from "./shapes.Moved.ts"; import type * as Mover from "./shapes.Mover.ts"; +import type * as Partial from "./shapes.Partial.ts"; +import type * as Parts from "./shapes.Parts.ts"; import * as Point from "./shapes.Point.ts"; import * as Shape from "./shapes.Shape.ts"; import type * as Signed from "./shapes.Signed.ts"; @@ -2120,6 +2122,57 @@ export function early(n: rt.u8): rt.u8 { return rt.u8WrappingAdd(n, 1); } +/** A `Result` that can't fail, which counts its calls so their order shows. */ +export function counted(calls: rt.Place, b: rt.u8): rt.Result { + calls.v = rt.u8WrappingAdd(calls.v, 1); + return rt.Ok(rt.u8WrappingMul(b, calls.v)); +} + +/** + * Patterns on parts of a place whose other variants can't exist, which test nothing + * there, while what they read still runs in order. + */ +export function uninhabited(data: rt.ByteSlice, out: rt.ByteVec): void { + const a: rt.u8 = unwrapOr$0r2bmpr(rt.byteSliceFirst(data), 0); + const b: rt.u8 = unwrapOr$0r2bmpr(rt.byteSliceGet(data, 1), 0); + let calls: rt.u8 = 0; + const _13: rt.Result = counted(rt.place(() => calls, (value) => calls = value), a); + const _12: [rt.Result, rt.Result] = [_13, counted(rt.place(() => calls, (value2) => calls = value2), b)]; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((_13 as { ok: true; value: rt.u8 }).value, (_12[1] as { ok: true; value: rt.u8 }).value, calls))); + const _26: rt.Result[] = [counted(rt.place(() => calls, (value3) => calls = value3), b), counted(rt.place(() => calls, (value4) => calls = value4), a)]; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((_26[0] as { ok: true; value: rt.u8 }).value, (_26[1] as { ok: true; value: rt.u8 }).value, calls))); + counted(rt.place(() => calls, (value5) => calls = value5), a); + rt.byteVecPush(out, calls); + counted(rt.place(() => calls, (value6) => calls = value6), a); + rt.byteVecPush(out, calls); + [counted(rt.place(() => calls, (value7) => calls = value7), a), [counted(rt.place(() => calls, (value8) => calls = value8), b)] as [rt.Result]] as [rt.Result, [rt.Result]]; + rt.byteVecPush(out, calls); + const pair: [rt.Result, Partial.Partial] = [counted(rt.place(() => calls, (value9) => calls = value9), a), { tag: "Real", _0: b } as Partial.Partial]; + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((pair[0] as { ok: true; value: rt.u8 }).value, (pair[1] as { tag: "Real"; _0: rt.u8 })._0))); + const held: Parts.Parts = { left: rt.Ok(a), right: thenSome$0ztng9q(rt.u8Rem(b, 2) === 0, rt.Ok((((b as rt.u16)) << 4) & 0xffff)) }; + const l: rt.u8 = (held.left as { ok: true; value: rt.u8 }).value; + const right: rt.Result | undefined = held.right; + if (right === undefined) { + rt.byteVecPush(out, l); + } else { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes((right as { ok: true; value: rt.u16 }).value))); + } + const _93: [Partial.Partial, rt.Result] = [{ tag: "Real", _0: a } as Partial.Partial, held.left]; + rt.byteVecPush(out, (_93[0] as { tag: "Real"; _0: rt.u8 })._0 ^ (_93[1] as { ok: true; value: rt.u8 }).value); + const _101: [rt.Result, rt.u8 | undefined] = [counted(rt.place(() => calls, (value10) => calls = value10), a), rt.byteSliceGet(data, 2)]; + if (_101[1] !== undefined) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((_101[0] as { ok: true; value: rt.u8 }).value, _101[1]))); + } else { + rt.byteVecPush(out, calls); + } + const _119: [rt.Result, rt.u8 | undefined] = [counted(rt.place(() => calls, (value11) => calls = value11), b), rt.byteSliceGet(data, 3)]; + if (_119[1] !== undefined) { + rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(Uint8Array.of((_119[0] as { ok: true; value: rt.u8 }).value, _119[1], calls))); + } else { + rt.byteVecPush(out, calls); + } +} + /** Closures capturing by reference and by move, and functions as values. */ export function closures(data: rt.ByteSlice, out: rt.ByteVec): void { let sum: rt.u32 = 0; @@ -2358,7 +2411,7 @@ export function flows(data: rt.ByteSlice, out: rt.ByteVec): void { if (result.ok) { rt.byteVecExtendFromSlice(out, rt.byteSliceFrom(rt.u16ToBeBytes(result.value))); } else { - rt.byteVecPush(out, result.error); + rt.byteVecPush(out, (result as { ok: false; error: rt.u8 }).error); } if (rt.u8Rem(a, 5) === 0) { option = undefined as rt.u8 | undefined; diff --git a/ts/fixtures/lang/src/harness.rs b/ts/fixtures/lang/src/harness.rs index 3313e4eca..813a3a45f 100644 --- a/ts/fixtures/lang/src/harness.rs +++ b/ts/fixtures/lang/src/harness.rs @@ -154,6 +154,7 @@ fn cases() -> Vec<(&'static str, Case)> { ("pointers::made", |_, data, out| pointers::made(data, out)), ("arrays::as_slices", |_, data, out| arrays::as_slices(data, out)), ("ints::widenings", ints::widenings), + ("shapes::uninhabited", |_, data, out| shapes::uninhabited(data, out)), ] } diff --git a/ts/fixtures/lang/src/ints.rs b/ts/fixtures/lang/src/ints.rs index 8d6940811..87b0d7636 100644 --- a/ts/fixtures/lang/src/ints.rs +++ b/ts/fixtures/lang/src/ints.rs @@ -500,9 +500,7 @@ pub fn widenings(kind: u8, data: &[u8], out: &mut Vec) { let wide: Result = u32::try_from(c); let wider: Result = c.try_into(); let widest: Result = c.try_into(); - let Ok(a) = wide; - let Ok(b) = wider; - let Ok(c) = widest; + let (Ok(a), Ok(b), Ok(c)) = (wide, wider, widest); out.extend_from_slice(&a.to_be_bytes()); out.extend_from_slice(&b.to_be_bytes()); out.extend_from_slice(&c.to_be_bytes()); diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index a757be661..a9a525aaf 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -1971,6 +1971,72 @@ fn early(n: u8) -> u8 { match return n.wrapping_add(1) {} } +/// A struct whose fields' other variants can't exist. +struct Parts { + left: Result, + right: Option>, +} + +/// An enum whose other variant holds a value that can't exist. +enum Partial { + Real(u8), + #[allow(dead_code)] + Never(Void), +} + +/// A `Result` that can't fail, which counts its calls so their order shows. +fn counted(calls: &mut u8, b: u8) -> Result { + *calls = calls.wrapping_add(1); + Ok(b.wrapping_mul(*calls)) +} + +/// Patterns on parts of a place whose other variants can't exist, which test nothing +/// there, while what they read still runs in order. +pub fn uninhabited(data: &[u8], out: &mut Vec) { + let a = data.first().copied().unwrap_or(0); + let b = data.get(1).copied().unwrap_or(0); + let mut calls = 0; + let (Ok(x), Ok(y)) = (counted(&mut calls, a), counted(&mut calls, b)); + out.extend_from_slice(&[x, y, calls]); + let [Ok(x), Ok(y)] = [counted(&mut calls, b), counted(&mut calls, a)]; + out.extend_from_slice(&[x, y, calls]); + // A call's result read only to find its one variant. + let Ok(_) = counted(&mut calls, a); + out.push(calls); + let (Ok(_),) = (counted(&mut calls, a),); + out.push(calls); + let (Ok(_), (Ok(_),)) = (counted(&mut calls, a), (counted(&mut calls, b),)); + out.push(calls); + let pair = (counted(&mut calls, a), Partial::Real(b)); + let (Ok(x), Partial::Real(y)) = pair; + out.extend_from_slice(&[x, y]); + + let held = Parts { + left: Ok(a), + right: (b % 2 == 0).then_some(Ok(u16::from(b) << 4)), + }; + let Parts { left: Ok(l), right } = held; + match right { + Some(Ok(r)) => out.extend_from_slice(&r.to_be_bytes()), + None => out.push(l), + } + match (Partial::Real(a), held.left) { + (Partial::Real(p), Ok(q)) => out.push(p ^ q), + } + + // The other part can fail. + if let (Ok(x), Some(&y)) = (counted(&mut calls, a), data.get(2)) { + out.extend_from_slice(&[x, y]); + } else { + out.push(calls); + } + let (Ok(x), Some(&y)) = (counted(&mut calls, b), data.get(3)) else { + out.push(calls); + return; + }; + out.extend_from_slice(&[x, y, calls]); +} + /// Closures capturing by reference and by move, and functions as values. pub fn closures(data: &[u8], out: &mut Vec) { let mut sum = 0u32; diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index ea19aff36..5f4861268 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -305,9 +305,10 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { halves: FxHashMap, &'m Operand<'tcx>)>, /// Temporaries of those joins, whose assignments go unlowered. joined: FxHashSet, - /// The paths a switch lowered so far tests the variant of, which `tsc` narrows in - /// its arms. - switched: FxHashSet, + /// The paths a switch lowered so far tests the variant of, with the enum it tests, + /// which `tsc` narrows in its arms. An `Option`'s `Some` is the path itself, so it + /// may be tested as both. + switched: FxHashSet<(String, Ty<'tcx>)>, /// Locals whose variant some switch tests, or that std takes, directly or through a /// reference to them. tested: IndexVec, @@ -1383,6 +1384,18 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { assigned && switched } + /// Whether the switch on the discriminant `local` tests it, rather than going the one + /// way its type leaves. + fn discr_tested(&self, local: Local) -> bool { + self.mir.basic_blocks.iter().any(|data| { + matches!( + &data.terminator().kind, + TerminatorKind::SwitchInt { discr: Operand::Move(p) | Operand::Copy(p), targets } + if p.as_local() == Some(local) && !self.switch_targets(targets).0.is_empty() + ) + }) + } + /// The parameters: `_1` through the argument count, but a closure's environment or a /// coroutine's `this`. pub fn params(&mut self) -> Vec { @@ -2286,7 +2299,18 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }; let ty = p.ty(&self.mir.local_decls, self.tcx).ty; let target = self.place_expr(*p, span, out); - let target = self.path(target, "scrutinee", out); + // A switch whose other variants can't exist tests nothing, so the read + // runs only for its effects. + let target = match self.discr_tested(local) { + true => self.path(target, "scrutinee", out), + false => { + let target = self.fold_exprs(Vec::new(), vec![target], false, out).remove(0); + if self.part_reads(&target).0 { + self.emit(vec![StmtKind::Expr(target).at(None)], false, out); + } + Expr::undefined() + } + }; self.slots[local] = Slot::Discr(Some((target, ty))); return; } @@ -2564,7 +2588,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let tests: Vec<(Expr, BasicBlock)> = match discr_local.map(|l| self.slots[l].clone()) { Some(Slot::Discr(Some((scrut, ty)))) => { if !arms.is_empty() && whole.is_none() { - self.switched.extend(scrut.path_key()); + self.switched.extend(scrut.path_key().map(|key| (key, ty))); } let tests: Vec = arms .iter() diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 120c9f6f7..c0dfa031e 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -214,7 +214,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }; 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)) { + } else if !e.path_key().is_some_and(|key| self.switched.contains(&(key, ty))) { e = self.as_variant(e, ty, variant, span); } }