Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion quest/m2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 0 additions & 17 deletions quest/m2/ts-never-edges.md

This file was deleted.

6 changes: 6 additions & 0 deletions ts/fixtures/lang/caller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]);
76 changes: 76 additions & 0 deletions ts/fixtures/lang/expected/shapes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
49 changes: 49 additions & 0 deletions ts/fixtures/lang/src/shapes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,55 @@ fn diverging(data: &[u8], out: &mut Vec<u8>) {
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<T>(x: T) -> T {
x
}
fn unwrap_or_bail<T>(o: Option<T>, 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.
Expand Down
45 changes: 40 additions & 5 deletions ts/src/lower/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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)),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 { .. }
Expand Down Expand Up @@ -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<Stmt>) -> Expr {
if ty.is_unit() || ty.is_never() {
if ty.is_unit() {
self.stmt(id, Dest::Discard, out);
return Expr::undefined();
}
Expand Down Expand Up @@ -3131,6 +3155,17 @@ fn reads<'tcx>(tcx: ty::TyCtxt<'tcx>, thir: &Thir<'tcx>) -> FxHashSet<HirId> {
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 {
Expand Down
6 changes: 4 additions & 2 deletions ts/src/lower/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions ts/src/lower/mir/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down