diff --git a/quest/m2/README.md b/quest/m2/README.md index 6b44edb37..97903411e 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -25,7 +25,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes - [Enum variant field order](/quest/m2/ts-variant-order.md) - a variant's fields evaluate in the order written, not declared - [Stable names](/quest/m2/ts-stable-names.md) - generic instances and trait-impl methods always carry their suffix, so callers' names never shift -- [Diverging calls through closures and generics](/quest/m2/ts-never-edges.md) - closures returning `!` and generics at `!` pass `tsc` - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split - [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster - [Error-path workload](/quest/m2/ts-bench-error-path.md) - the benchmark prices `?` on a frame split across reads diff --git a/quest/m2/ts-never-edges.md b/quest/m2/ts-never-edges.md deleted file mode 100644 index df060d381..000000000 --- a/quest/m2/ts-never-edges.md +++ /dev/null @@ -1,17 +0,0 @@ -# [S] Diverging calls through closures and generics - -## Goal - -[rust2-ts](/ts/README.md) output passes `tsc` and matches native Rust in two cases -[#28](https://github.com/kixelated/rust2/pull/28) left: a call to a closure that -returns `!`, and a generic instantiated at `!`. - -## Plan - -- A closure returning `!` is an unannotated `const` arrow, so `tsc` does not see a - call to it diverge: a tail `f(b)` in a function with a result fails `tsc`. -- A generic instantiated at `!` (edition 2024's fallback, as in `id(panic!())`) - lowers its body with `Dest::Discard` and fails TS2534, and its argument is still - `undefined`. - -Public API: the translator's output for these shapes, which fail `tsc` today. diff --git a/ts/fixtures/lang/caller.ts b/ts/fixtures/lang/caller.ts index 177da7004..db25f8232 100644 --- a/ts/fixtures/lang/caller.ts +++ b/ts/fixtures/lang/caller.ts @@ -23,3 +23,9 @@ export function run(input: Uint8Array): rt.ByteVec { ]); return rt.ByteVec.from(new TextEncoder().encode(text)); } + +/** `shapes::loops` with each first byte that one of its cases of `!` takes, with one more byte and without. */ +export const cases: Uint8Array[] = [0xf1, 0xf3, 0xf4, 0xf5, 0xf6, 0xf9, 0xfa].flatMap((b) => [ + Uint8Array.of(16, 0, b), + Uint8Array.of(16, 0, b, 1), +]); diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 041016e0d..162e34689 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -287,6 +287,82 @@ export function diverging(data: Uint8Array, out: rt.ByteVec): void { out.push(guardedReturn(head)); const found = boundNever(head, out); out.push(found); + out.push(closureNever(b)); + genericNever(b, data.length); +} + +/** + * Calls that never return, through a closure, a function pointer, and a closure a + * function made: a statement, a bound value, and the tail. + */ +export function closureNever(b: rt.u8): rt.u8 { + const fail: (a0: rt.u8) => never = (b2: rt.u8): never => { + rt.panic(["closure failed on ", rt.fmt.spec({ alternate: true }, (f: rt.Formatter) => rt.u8.lowerHex(b2, f))]); + }; + const ptr: (a0: rt.u8) => never = bail; + const made: (a0: rt.u8) => never = madeNever(); + if (b === 0xf5) { + fail(b); + } + let x: rt.u8; + if (b === 0xf4) { + ptr(b); + } else { + x = rt.u8.div(b, 5); + } + if (b === 243) { + fail(b); + } else if (b === 250) { + made(b); + } else { + return x; + } +} + +/** A closure that never returns, made by a function. */ +export function madeNever(): (a0: rt.u8) => never { + return (b: rt.u8): never => { + rt.panic(["made ", (f: rt.Formatter) => rt.u8.display(b, f)]); + }; +} + +/** + * Generic functions instantiated at `!`, which edition 2024 infers for a value that + * never exists: given one, and given an `Option` of none, which then calls one. + */ +export function genericNever(b: rt.u8, len: rt.usize): void { + if (b === 0xf1) { + pass(bail(b)); + } + if (b === 0xf6) { + let value: never; + rt.panic(["passed ", (f: rt.Formatter) => rt.u8.display(b, f)]); + pass(value); + } + if (b === 0xf9) { + let o: never | undefined; + if (len > 1) { + o = undefined; + } else { + let value2: never; + rt.panic(["some ", (f: rt.Formatter) => rt.u8.display(b, f)]); + o = value2; + } + unwrapOrBail(o, b); + } +} + +export function pass(x: never): never { + rt.unreachable(x); +} + +export function unwrapOrBail(o: never | undefined, b: rt.u8): never { + if (o !== undefined) { + const x = o; + pass(rt.unreachable(x)); + } else { + bail(b); + } } /** A function that never returns. */ diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index 476b7742e..27b0963b2 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -363,6 +363,55 @@ fn diverging(data: &[u8], out: &mut Vec) { out.push(guarded_return(head)); let found = bound_never(head, out); out.push(found); + out.push(closure_never(b)); + generic_never(b, data.len()); +} + +/// Calls that never return, through a closure, a function pointer, and a closure a +/// function made: a statement, a bound value, and the tail. +fn closure_never(b: u8) -> u8 { + let fail = |b: u8| -> ! { panic!("closure failed on {b:#x}") }; + let ptr: fn(u8) -> ! = bail; + let made = made_never(); + if b == 0xf5 { + fail(b); + } + let x: u8 = if b == 0xf4 { ptr(b) } else { b / 5 }; + match b { + 0xf3 => fail(b), + 0xfa => made(b), + _ => x, + } +} + +/// A closure that never returns, made by a function. +fn made_never() -> impl Fn(u8) -> ! { + |b| panic!("made {b}") +} + +/// Generic functions instantiated at `!`, which edition 2024 infers for a value that +/// never exists: given one, and given an `Option` of none, which then calls one. +#[allow(unreachable_code, clippy::diverging_sub_expression, reason = "`!` arguments")] +fn generic_never(b: u8, len: usize) { + fn pass(x: T) -> T { + x + } + fn unwrap_or_bail(o: Option, b: u8) -> T { + match o { + Some(x) => pass(x), + None => bail(b), + } + } + if b == 0xf1 { + pass(bail(b)); + } + if b == 0xf6 { + pass(panic!("passed {b}")); + } + if b == 0xf9 { + let o = if len > 1 { None } else { Some(panic!("some {b}")) }; + unwrap_or_bail(o, b); + } } /// A function that never returns. diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index d51a38e63..a2dc8f535 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -583,8 +583,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { if by_value && self.moves(init) { let place = self.place(init, out); let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); - let annotate = mutable.then_some(ty); - self.push(out, StmtKind::decl(mutable, name, annotate, Some(place.clone())), span); + let annotate = mutable || diverges_when_called(pat_ty); + self.push( + out, + StmtKind::decl(mutable, name, annotate.then_some(ty), Some(place.clone())), + span, + ); self.clear(place, out); return; } @@ -593,7 +597,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { false => self.operand(init, out), }; let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); - let annotate = mutable || needs_annotation(&value); + let annotate = mutable || needs_annotation(&value) || diverges_when_called(pat_ty); self.push( out, StmtKind::decl(mutable, name, annotate.then_some(ty), Some(value)), @@ -2028,7 +2032,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ExprKind::ValueTypeAscription { source, .. } | ExprKind::ValueExpr { source } => self.expr(*source, out), // The temp is never assigned: control never gets past the source. ExprKind::NeverToAny { .. } => self.via_temp(id, ty, span, out), - ExprKind::Block { block } if !self.thir[*block].targeted_by_break && !self.block_owns(*block) => { + // A block of type `!` without a value, such as `panic!(..)`, goes through a temp. + ExprKind::Block { block } + if !self.thir[*block].targeted_by_break + && !self.block_owns(*block) + && (self.thir[*block].expr.is_some() || !ty.is_never()) => + { let block = &self.thir[*block]; for &stmt in &block.stmts { self.stmt_item(stmt, out); @@ -2083,6 +2092,19 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { None => call, } } + // A place of type `!`, as in a generic instantiated at `!`, which native code never + // reads: `tsc` sees that through `rt.unreachable`. + ExprKind::VarRef { .. } + | ExprKind::UpvarRef { .. } + | ExprKind::Field { .. } + | ExprKind::Index { .. } + | ExprKind::Deref { .. } + | ExprKind::PlaceTypeAscription { .. } + if ty.is_never() => + { + let place = self.place(id, out); + Expr::rt("unreachable", vec![place]) + } ExprKind::VarRef { .. } | ExprKind::UpvarRef { .. } | ExprKind::Field { .. } @@ -2298,8 +2320,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { i >= 0 && (i as u64) < len } + /// `id` assigned to a new variable, which a value of type `!` leaves unassigned: control + /// never gets past it. fn via_temp(&mut self, id: ExprId, ty: Ty<'tcx>, span: Span, out: &mut Vec) -> Expr { - if ty.is_unit() || ty.is_never() { + if ty.is_unit() { self.stmt(id, Dest::Discard, out); return Expr::undefined(); } @@ -3131,6 +3155,17 @@ fn reads<'tcx>(tcx: ty::TyCtxt<'tcx>, thir: &Thir<'tcx>) -> FxHashSet { read } +/// Whether `ty` is a closure or function pointer that never returns, whose binding `tsc` +/// sees a call to diverge only through a declared type. +fn diverges_when_called(ty: Ty<'_>) -> bool { + let output = match ty.peel_refs().kind() { + ty::Closure(_, args) => args.as_closure().sig().output(), + ty::FnPtr(sig, header) => sig.with(*header).output(), + _ => return false, + }; + output.skip_binder().is_never() +} + /// Whether a declaration's initializer is one TypeScript can't type on its own. fn needs_annotation(value: &Expr) -> bool { match value { diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index 0ca86c085..f740fadbc 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -1369,7 +1369,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { TerminatorKind::FalseEdge { real_target, .. } | TerminatorKind::FalseUnwind { real_target, .. } => { Exit::Goto(real_target.as_usize()) } - TerminatorKind::Return => { + TerminatorKind::Return if !self.mir.local_decls[mir::RETURN_PLACE].ty.is_never() => { let ret = self.mir.local_decls[mir::RETURN_PLACE].ty; let value = match self.zero_sized(ret) { true => None, @@ -1386,7 +1386,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { self.flush(out); Exit::End } - TerminatorKind::Unreachable => { + // A `Return` from a function of type `!`, as a generic instantiated at `!` is, is + // unreachable too: it has no value to return, and `tsc` must see that. + TerminatorKind::Unreachable | TerminatorKind::Return => { self.emit( vec![StmtKind::Expr(Expr::rt("unreachable", vec![Expr::undefined()])).at(None)], None, diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index 59de279bd..d23001ce1 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -28,6 +28,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } match &self.slots[local] { Slot::Var(name) => Expr::ident(name), + // A value of type `!`, as a generic instantiated at `!` reads: native code never + // gets here, and `tsc` sees that through `rt.unreachable`. + Slot::Unit if self.mir.local_decls[local].ty.is_never() => Expr::rt("unreachable", vec![Expr::undefined()]), Slot::Unit => Expr::undefined(), Slot::Alias(Some(target)) => target.clone(), Slot::Alias(None) => self.err(span, "a reference read before its borrow"),