From 058ceb96981f440c9223496850c5d323d8cecfaa Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:48:59 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m2/ts-async.md Quest-Claim: ebf43987b63391ba From 07d5175ce8614eed163529acdb21c4bde59927bb Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:06:32 -0700 Subject: [PATCH 2/3] feat(ts): translate Box::pin and dyn Future Co-Authored-By: Claude Opus 5.5 --- quest/m2/ts-async.md | 10 +- quest/m3/ts-dyn.md | 12 +- ts/MIGRATE.md | 3 + ts/README.md | 5 +- ts/fixtures/task/expected/core/task/poll.ts | 14 + ts/fixtures/task/expected/futures.Forward.ts | 25 + ts/fixtures/task/expected/futures.ts | 509 ++++++++++++++++++- ts/fixtures/task/expected/kio.Pending.ts | 10 + ts/fixtures/task/expected/kio.ts | 34 ++ ts/fixtures/task/src/futures.rs | 93 +++- ts/fixtures/task/src/harness.rs | 10 +- ts/fixtures/task/ts.toml | 1 + ts/runtime/rt/task.ts | 24 + ts/src/census.rs | 1 + ts/src/lower/drop.rs | 5 +- ts/src/lower/library.rs | 4 +- ts/src/lower/mir/rvalue.rs | 43 +- ts/src/lower/mod.rs | 15 + ts/src/lower/task.rs | 81 ++- ts/tests/task.ts | 18 +- 20 files changed, 873 insertions(+), 44 deletions(-) create mode 100644 ts/fixtures/task/expected/futures.Forward.ts diff --git a/quest/m2/ts-async.md b/quest/m2/ts-async.md index d337a4729..dbcb7bc2c 100644 --- a/quest/m2/ts-async.md +++ b/quest/m2/ts-async.md @@ -19,16 +19,14 @@ generators in Node, 1.8-5.5x in Bun, and 1.4-3.5x in Chrome, and past depth 1 fa than moq's hand-written promises. `rt.spawn` stays. std's future helpers translate: `Poll`'s methods, `pin!`, `poll_fn`, `future::pending`, -`Waker::from(Arc)`, and `Waker::noop`. What moq-net still needs, by its census from -MIR at the pinned revision: +`Waker::from(Arc)`, and `Waker::noop`, and so do `Box::pin` and `dyn Future`. What +moq-net still needs, by its census from MIR at the pinned revision: -- `Box::pin` (29, a boxed future that binds to hand-written TS at the boundary, per the - [model](/quest/m2/ts-model/README.md)), and polling a `Pin>`. -- Async closures. +- Async closures, which only moq-net's tests write today. - kio's own API, reached across crates (`Pending`, `Consumer::poll`, `Waiter::poll_future`, `Tasks`), translates through [safe dependencies](/quest/m2/ts-model/crates.md), and kio's `RawWaker` vtable and - `Box` tasks are [bindings](/ts/README.md#bindings). + `Box` tasks are [bindings](/ts/README.md#bindings). - The edge: `rt.spawn`'s shape for callers, and cancelling a spawned task. An async block that captures part of a variable, which THIR refused 47 times, is a diff --git a/quest/m3/ts-dyn.md b/quest/m3/ts-dyn.md index 1e8c6009a..6d41c50ff 100644 --- a/quest/m3/ts-dyn.md +++ b/quest/m3/ts-dyn.md @@ -2,18 +2,16 @@ ## Goal -[rust2-ts](/ts/README.md) translates trait objects (`&dyn Trait`, `Box`, and -`Box`, `Pin`ned or not), with Rust's dispatch and drop order, proven by -differential tests against native Rust, so a consumer neither rewrites nor binds them. +[rust2-ts](/ts/README.md) translates trait objects (`&dyn Trait` and `Box`), with +Rust's dispatch and drop order, proven by differential tests against native Rust, so a +consumer neither rewrites nor binds them. ## Plan Decided with the maintainer on 2026-10-27: a stock crate translates with no annotations or config, so trait objects move from never to not yet. Until this lands, moq rewrites -`dyn Expiry` as an enum and binds its boxed futures ([bindings](/ts/README.md#bindings)). +`dyn Expiry` as an enum and binds its boxed closures ([bindings](/ts/README.md#bindings)). -- `&dyn Debug` and `&dyn Display` already translate; build on how they do. -- A boxed future must keep Rust's laziness and cancellation as - [async](/quest/m2/ts-async.md) defines them. +- `&dyn Debug`, `&dyn Display`, and `dyn Future` already translate; build on how they do. Public API: the translator's output. diff --git a/ts/MIGRATE.md b/ts/MIGRATE.md index 80d157df9..eeefa10f0 100644 --- a/ts/MIGRATE.md +++ b/ts/MIGRATE.md @@ -2,6 +2,9 @@ ## Unreleased +- A trait object in a function's suffix is named for its trait and the types it binds: + `show$dynstdfmtDebug` is `show$dyn_Debug`, and `poll$dyn_Future_u64` is a + `dyn Future`'s. - `rt.FromUtf8Error` holds its `rt.Utf8Error` as std's does: `e.validUpTo` and `e.errorLen` are `e.error.validUpTo` and `e.error.errorLen`. - The runtime no longer exports `ownedNth`, `ownedNthBack`, `ownedSkip`, `ownedTake`, or diff --git a/ts/README.md b/ts/README.md index 4163ab7d9..e85f12732 100644 --- a/ts/README.md +++ b/ts/README.md @@ -93,6 +93,7 @@ in `rt/str.ts`, collections in `rt/collections.ts`, ownership and async in | `async fn` | a function returning `rt.Future`: a class of its own, its coroutine's state machine | | `Poll`, `Waker`, `Context` | `T \| typeof rt.Pending`, refused if `T` can already be pending; `rt.Waker`, which is also the context | | `pin!(x)`, `poll_fn(f)`, `future::pending()` | `x`; `rt.PollFn`, which drops `f` with itself; `rt.NEVER` | +| `Box::pin(x)`, `dyn Future` | `x`; `rt.Future`: an `async` body or std's future as it is, and another future as an `rt.DynFuture` over its `poll`, which drops it with itself unless borrowed | `Vec` storage and `[x; N]` byte arrays up to 1 KiB share 8 KiB `ArrayBuffer`s, as Node's `Buffer` pool does, so the `buffer` behind a view holds other bytes too: read it through @@ -431,8 +432,8 @@ they need. ## Not yet `unsafe` and raw pointers ([unsafe](/quest/m3/ts-unsafe.md)), and trait objects other than -`&dyn Debug` and `&dyn Display` ([trait objects](/quest/m3/ts-dyn.md)), fail translation. -Until they translate, an item that needs one, such as a boxed future, binds to +`&dyn Debug`, `&dyn Display`, and `dyn Future` ([trait objects](/quest/m3/ts-dyn.md)), fail +translation. Until they translate, an item that needs one, such as a boxed closure, binds to hand-written TS ([bindings](#bindings)). These fail translation: floats ([Floats](/quest/m2/ts-model/floats.md)), statics, async closures, a closure that owns a value diff --git a/ts/fixtures/task/expected/core/task/poll.ts b/ts/fixtures/task/expected/core/task/poll.ts index 8903d63da..6d8dd3e37 100644 --- a/ts/fixtures/task/expected/core/task/poll.ts +++ b/ts/fixtures/task/expected/core/task/poll.ts @@ -9,6 +9,20 @@ export function map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_clo return rt.Pending; } +export function map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0(self: rt.Poll, f: (a0: rt.u64 | undefined) => rt.u64): rt.Poll { + if (self !== rt.Pending) { + return f(self); + } + return rt.Pending; +} + +export function map$Poll_u64_u64_boxed_closure0_closure0_closure0(self: rt.Poll, f: (a0: rt.u64) => rt.u64): rt.Poll { + if (self !== rt.Pending) { + return f(self); + } + return rt.Pending; +} + export function isReady$Poll_Option_u64(self: rt.Poll): boolean { if (self !== rt.Pending) { return true; diff --git a/ts/fixtures/task/expected/futures.Forward.ts b/ts/fixtures/task/expected/futures.Forward.ts new file mode 100644 index 000000000..606ade436 --- /dev/null +++ b/ts/fixtures/task/expected/futures.Forward.ts @@ -0,0 +1,25 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** + * A future of the crate's that forwards its polls to a boxed one, as moq's session + * driver does. + */ +export class Forward { + future: rt.Future; + + constructor(fields: { future: rt.Future }) { + this.future = fields.future; + } + + [Symbol.dispose](): void { + rt.drop(this.future); + } +} + +export function poll$Future(self: Forward, cx: rt.Context): rt.Poll { + return self.future.poll(cx); +} + +//# sourceMappingURL=futures.Forward.ts.map diff --git a/ts/fixtures/task/expected/futures.ts b/ts/fixtures/task/expected/futures.ts index 9b872495e..baa632b33 100644 --- a/ts/fixtures/task/expected/futures.ts +++ b/ts/fixtures/task/expected/futures.ts @@ -1,14 +1,17 @@ // Generated by rust2-ts. Do not edit. import * as rt from "./rt.ts"; -import { okOr$Option_u64_u64 } from "./core/option.ts"; -import { map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0, isReady$Poll_Option_u64, isPending$Poll_Option_u64, isPending$Poll_u64, mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1, mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2 } from "./core/task/poll.ts"; +import { unwrapOr$Option_u64, okOr$Option_u64_u64 } from "./core/option.ts"; +import { map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0, map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0, map$Poll_u64_u64_boxed_closure0_closure0_closure0, isReady$Poll_Option_u64, isPending$Poll_Option_u64, isPending$Poll_u64, mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1, mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2 } from "./core/task/poll.ts"; import * as Blast from "./futures.Blast.ts"; +import * as Forward from "./futures.Forward.ts"; import * as Fused from "./futures.Fused.ts"; import * as Plain from "./futures.Plain.ts"; import * as Relay from "./futures.Relay.ts"; -import { recvFuture } from "./kio.ts"; -import type * as Consumer from "./kio.Consumer.ts"; +import { wait$boxed_closure0_closure2_u64, wait$boxed_closure0_closure4_u64, recvFuture } from "./kio.ts"; +import * as Consumer from "./kio.Consumer.ts"; +import * as Pending from "./kio.Pending.ts"; +import type * as Waiter from "./kio.Waiter.ts"; import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; @@ -381,4 +384,502 @@ export function relayed(task: rt.Waker, log: Log.Log, id: rt.u32): rt.Waker { } } +/** + * Boxed futures over a channel: `Box::pin` of an async fn, awaited, then a queue of + * `Pin>`s of an async block, kio's `Pending`, a struct of the crate's, + * and a `poll_fn`, each owning a guard. A `poll_fn` boxed in a [`Forward`] polls the + * queue in turn through [`poll_unsized`], as moq's tasks do through kio's + * `Waiter::poll_future`, dropping each future as it is ready, and a pinned `&mut dyn + * Future` of the crate's struct last. A cancel drops the futures the queue still holds, + * in order, and the async block panics on 99. + */ +export function boxed(rx: Consumer.Consumer, guard: Guard.Guard): rt.Future { + return new boxedFuture(rx, guard); +} + +export class boxedFuture { + #state: number = 0; + #rx: Consumer.Consumer; + #guard: Guard.Guard; + #first!: rt.u64; + #awaitee!: rt.Future; + #log!: Log.Log; + #pinned!: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll>; + #awaitee$2!: Forward.Forward; + #saved!: boolean; + #saved$2!: boolean; + #saved$3!: boolean; + #saved$4!: boolean; + #saved$5!: boolean; + #saved$6!: boolean; + + constructor(rx: Consumer.Consumer, guard: Guard.Guard) { + this.#rx = rx; + this.#guard = guard; + } + + [Symbol.dispose](): void { + let unwind: number = 0; + try { + if (this.#state === 0) { + unwind = 48; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#guard); + return; + } + if (this.#state === 3) { + unwind = 37; + rt.drop(this.#awaitee); + } else if (this.#state === 4) { + unwind = 25; + rt.drop(this.#awaitee$2); + unwind = 28; + rt.drop(this.#pinned); + this.#saved$2 = false; + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + unwind = 36; + rt.drop(this.#log); + } else { + return; + } + unwind = 40; + rt.drop(this.#guard); + if (this.#saved) { + unwind = 0; + rt.drop(this.#rx); + } + this.#saved = false; + } catch (e) { + b2: { + b3: { + b4: { + b5: { + if (unwind === 0) { + throw e; + } + if (unwind === 25) { + rt.drop(this.#pinned); + } else if (unwind !== 28) { + if (unwind === 36) { + break b5; + } + if (unwind === 37) { + break b4; + } + if (unwind === 40) { + break b3; + } + rt.drop(this.#guard); + break b2; + } + this.#saved$2 = false; + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + rt.drop(this.#log); + } + } + rt.drop(this.#guard); + } + if (this.#saved) { + rt.drop(this.#rx); + } + this.#saved = false; + } + throw e; + } + } + + poll(_2: rt.Context): rt.Poll { + let block!: Guard.Guard; + let waiting!: Guard.Guard; + let ready!: Guard.Guard; + let _39!: Guard.Guard; + let _44!: Guard.Guard; + let next!: Consumer.Consumer; + let queue!: rt.Future[]; + let _59!: rt.Future; + let _62!: rt.Future; + let unwind: number = 0; + try { + b0: { + if (this.#state === 0) { + unwind = 81; + this.#saved = false; + this.#saved$6 = false; + this.#saved$5 = false; + this.#saved$4 = false; + this.#saved$3 = false; + this.#saved$2 = false; + this.#saved = true; + this.#awaitee = new recvFuture(this.#rx); + } else if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } else if (this.#state !== 3) { + break b0; + } + unwind = 80; + const _7: rt.Poll = this.#awaitee.poll(_2); + if (_7 !== rt.Pending) { + unwind = 81; + const result: rt.u64 | undefined = _7; + rt.drop(this.#awaitee); + this.#first = unwrapOr$Option_u64(result, 0); + const arg = this.#first; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; + const _19: string = rt.fmtFormat(["first ", args2[0]]); + unwind = 79; + Guard.note(this.#guard, _19); + unwind = 81; + const _30: rt.u32 = Guard.id(this.#guard); + const _32: Log.Log = Log.clone$Clone(Guard.log(this.#guard)); + unwind = 78; + const id: rt.u32 = _30; + this.#log = _32; + _39 = Guard.new(rt.u32Add(id, 500), Log.clone$Clone(this.#log)); + unwind = 77; + _44 = Guard.new(rt.u32Add(id, 600), Log.clone$Clone(this.#log)); + unwind = 76; + const _49: Guard.Guard = Guard.new(rt.u32Add(id, 700), Log.clone$Clone(this.#log)); + unwind = 72; + this.#saved$6 = true; + block = _39; + this.#saved$5 = true; + waiting = _44; + this.#saved$4 = true; + ready = _49; + next = Consumer.clone$Clone(this.#rx); + this.#saved$3 = true; + unwind = 70; + this.#saved = false; + this.#saved$6 = false; + const _60: rt.Future = new boxedFuture$2(this.#rx, block); + unwind = 69; + _59 = _60; + this.#saved$3 = false; + this.#saved$5 = false; + let captured = next; + const captured2 = waiting; + const _63: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure2_u64(rt.closure((waiter: Waiter.Waiter): rt.Poll => { + return map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0(Consumer.pollRecv(captured, waiter), (value: rt.u64 | undefined): rt.u64 => { + Guard.note(captured2, "waited"); + return rt.u64Add(unwrapOr$Option_u64(value, 0), 2); + }); + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured); + dropped = 1; + rt.drop(captured2); + } catch (e) { + if (dropped < 1) { + rt.drop(captured2); + } + throw e; + } + })); + unwind = 68; + _62 = new rt.DynFuture(_63, Pending.poll$Future_boxed_closure0_closure2, rt.drop); + this.#saved$4 = false; + const captured3 = ready; + const _67: rt.Future = new rt.PollFn(rt.closure((_22: rt.Context): rt.Poll => { + Guard.note(captured3, "ready"); + return 3; + }, (): void => { + rt.drop(captured3); + }), rt.drop); + unwind = 71; + queue = [_59, _62, _67]; + unwind = 67; + this.#saved$2 = true; + const captured4 = Guard.new(rt.u32Add(id, 800), Log.clone$Clone(this.#log)); + const _76: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure4_u64(rt.closure((_23: Waiter.Waiter): rt.Poll => { + return Guard.id(captured4) as rt.u64; + }, (): void => { + rt.drop(captured4); + })); + unwind = 66; + this.#pinned = _76; + const last: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = this.#pinned; + this.#saved$2 = false; + let captured5 = queue; + let captured6: rt.u64 = 0; + let captured7 = last; + this.#awaitee$2 = new Forward.Forward({ future: new rt.PollFn(rt.closure((cx: rt.Context): rt.Poll => { + let i: rt.usize = 0; + while (i < captured5.length) { + const _84: rt.Poll = pollUnsized$dyn_Future_u64(captured5[rt.idx(captured5, i)], cx); + if (_84 !== rt.Pending) { + captured6 = rt.u64Add(captured6, _84); + rt.drop(rt.vecSwapRemove(captured5, i)); + } else { + i = rt.usizeAdd(i, 1); + } + } + if (!((captured5.length === 0))) { + return rt.Pending; + } + return map$Poll_u64_u64_boxed_closure0_closure0_closure0(pollUnsized$dyn_Future_u64(new rt.DynFuture(captured7, Pending.poll$Future_boxed_closure0_closure4), cx), (value3: rt.u64): rt.u64 => { + return rt.u64Add(captured6, value3); + }); + }, (): void => { + rt.dropAll(captured5); + }), rt.drop) }); + } else { + this.#state = 3; + return rt.Pending; + } + } + unwind = 65; + const _86: rt.Poll = Forward.poll$Future(this.#awaitee$2, _2); + if (_86 !== rt.Pending) { + unwind = 66; + const total: rt.u64 = _86; + rt.drop(this.#awaitee$2); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(total, f)]; + const _98: string = rt.fmtFormat(["boxed ", args4[0]]); + unwind = 64; + Guard.note(this.#guard, _98); + unwind = 67; + rt.drop(this.#pinned); + unwind = 81; + this.#saved$2 = false; + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + rt.drop(this.#log); + unwind = 89; + rt.drop(this.#guard); + this.#saved = false; + this.#state = 1; + return total; + } + this.#state = 4; + return rt.Pending; + } catch (e) { + b2: { + b3: { + b4: { + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + if (unwind === 0) { + throw e; + } + if (unwind === 64) { + break b8; + } + if (unwind === 65) { + rt.drop(this.#awaitee$2); + break b8; + } + if (unwind === 66) { + break b8; + } + if (unwind === 67) { + break b7; + } + if (unwind === 68) { + rt.drop(_62); + break b10; + } + if (unwind === 69) { + break b10; + } + if (unwind === 70) { + break b9; + } + if (unwind === 71) { + break b6; + } + if (unwind === 72) { + break b5; + } + if (unwind === 76) { + rt.drop(_44); + } else if (unwind !== 77) { + if (unwind === 78) { + break b4; + } + if (unwind === 79) { + break b3; + } + if (unwind === 80) { + rt.drop(this.#awaitee); + break b3; + } + if (unwind === 81) { + break b3; + } + break b2; + } + rt.drop(_39); + break b4; + } + rt.drop(_59); + } + break b6; + } + rt.drop(this.#pinned); + } + if (this.#saved$2) { + rt.dropAll(queue); + } + } + this.#saved$2 = false; + if (this.#saved$3) { + rt.drop(next); + } + } + this.#saved$3 = false; + if (this.#saved$4) { + rt.drop(ready); + } + this.#saved$4 = false; + if (this.#saved$5) { + rt.drop(waiting); + } + this.#saved$5 = false; + if (this.#saved$6) { + rt.drop(block); + } + this.#saved$6 = false; + } + rt.drop(this.#log); + } + rt.drop(this.#guard); + } + if (this.#saved) { + rt.drop(this.#rx); + } + this.#saved = false; + this.#state = 2; + throw e; + } + } +} + +export class boxedFuture$2 { + #state: number = 0; + #rx: Consumer.Consumer; + #block: Guard.Guard; + #awaitee!: rt.Future; + + constructor(rx: Consumer.Consumer, block: Guard.Guard) { + this.#rx = rx; + this.#block = block; + } + + [Symbol.dispose](): void { + let unwind: number = 0; + try { + if (this.#state === 0) { + unwind = 17; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#block); + } else if (this.#state === 3) { + unwind = 8; + rt.drop(this.#awaitee); + unwind = 12; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#block); + } + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 8) { + rt.drop(this.#rx); + rt.drop(this.#block); + } else if (unwind === 12) { + rt.drop(this.#block); + } else { + rt.drop(this.#block); + } + throw e; + } + } + + poll(_2: rt.Context): rt.Poll { + let unwind: number = 0; + try { + if (this.#state === 0) { + unwind = 28; + this.#awaitee = new recvFuture(this.#rx); + } else if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } + unwind = 27; + const _7: rt.Poll = this.#awaitee.poll(_2); + if (_7 !== rt.Pending) { + unwind = 28; + const result: rt.u64 | undefined = _7; + rt.drop(this.#awaitee); + const value: rt.u64 = unwrapOr$Option_u64(result, 0); + if (!(value === 99)) { + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(value, f)]; + const _30: string = rt.fmtFormat(["block ", args4[0]]); + unwind = 26; + Guard.note(this.#block, _30); + unwind = 28; + const _39: rt.u64 = rt.u64Add(value, 1); + unwind = 30; + rt.drop(this.#rx); + unwind = 29; + rt.drop(this.#block); + this.#state = 1; + return _39; + } + const part = Guard.id(this.#block); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; + rt.panicFmt(["g", args2[0], " poisoned"]); + } else { + this.#state = 3; + return rt.Pending; + } + } catch (e) { + b1: { + if (unwind === 0) { + throw e; + } + if (unwind !== 26) { + if (unwind === 27) { + rt.drop(this.#awaitee); + } else if (unwind !== 28) { + if (unwind === 29) { + break b1; + } + rt.drop(this.#block); + break b1; + } + } + rt.drop(this.#rx); + rt.drop(this.#block); + } + this.#state = 2; + throw e; + } + } +} + +/** Polls `future`, sized or not, as kio's `Waiter::poll_future` does. */ +export function pollUnsized$dyn_Future_u64(future: rt.Future, cx: rt.Context): rt.Poll { + return future.poll(cx); +} + //# sourceMappingURL=futures.ts.map diff --git a/ts/fixtures/task/expected/kio.Pending.ts b/ts/fixtures/task/expected/kio.Pending.ts index 27d12fc60..89284edb2 100644 --- a/ts/fixtures/task/expected/kio.Pending.ts +++ b/ts/fixtures/task/expected/kio.Pending.ts @@ -29,6 +29,16 @@ export class Pending { } } +export function poll$Future_boxed_closure0_closure2(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { + const this_: Pending<(a0: Waiter.Waiter) => rt.Poll> = self; + return this_.poll(Park.hold(this_.park, cx)); +} + +export function poll$Future_boxed_closure0_closure4(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { + const this_: Pending<(a0: Waiter.Waiter) => rt.Poll> = self; + return this_.poll(Park.hold(this_.park, cx)); +} + export function poll$Future_recv_closure0_closure0(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { const this_: Pending<(a0: Waiter.Waiter) => rt.Poll> = self; return this_.poll(Park.hold(this_.park, cx)); diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts index d6d5ca6dc..5ef67d918 100644 --- a/ts/fixtures/task/expected/kio.ts +++ b/ts/fixtures/task/expected/kio.ts @@ -6,6 +6,40 @@ import * as Park from "./kio.Park.ts"; import * as Pending from "./kio.Pending.ts"; import type * as Waiter from "./kio.Waiter.ts"; +/** A future from a poll function that receives a [`Waiter`]. */ +export function wait$boxed_closure0_closure2_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { + let _2!: (a0: Waiter.Waiter) => rt.Poll; + let unwind: number = 0; + try { + unwind = 3; + _2 = poll; + return new Pending.Pending({ poll: _2, park: Park.default$Default() }); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(_2); + throw e; + } +} + +/** A future from a poll function that receives a [`Waiter`]. */ +export function wait$boxed_closure0_closure4_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { + let _2!: (a0: Waiter.Waiter) => rt.Poll; + let unwind: number = 0; + try { + unwind = 3; + _2 = poll; + return new Pending.Pending({ poll: _2, park: Park.default$Default() }); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(_2); + throw e; + } +} + /** A future from a poll function that receives a [`Waiter`]. */ export function wait$recv_closure0_closure0_Option_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { return new Pending.Pending({ poll, park: Park.default$Default() }); diff --git a/ts/fixtures/task/src/futures.rs b/ts/fixtures/task/src/futures.rs index f8c07e6c6..14b531a1a 100644 --- a/ts/fixtures/task/src/futures.rs +++ b/ts/fixtures/task/src/futures.rs @@ -1,12 +1,13 @@ //! std's future helpers over a channel: `pin!`, `poll_fn`, `future::pending`, `Poll`'s -//! methods, and wakers from `Arc` and `Waker::noop`. +//! methods, and wakers from `Arc` and `Waker::noop`; and boxed futures, +//! `Pin>` included. use std::future::{self, Future}; -use std::pin::pin; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::task::{Context, Poll, Wake, Waker}; -use crate::kio::Consumer; +use crate::kio::{self, Consumer}; use crate::log::Log; use crate::model::Guard; @@ -130,3 +131,89 @@ impl Drop for Blast { panic!("g{} blew", self.0.id()); } } + +/// A boxed future, as moq's `MaybeSendBox` is. +type Boxed<'a> = Pin + 'a>>; + +/// Boxed futures over a channel: `Box::pin` of an async fn, awaited, then a queue of +/// `Pin>`s of an async block, kio's `Pending`, a struct of the crate's, +/// and a `poll_fn`, each owning a guard. A `poll_fn` boxed in a [`Forward`] polls the +/// queue in turn through [`poll_unsized`], as moq's tasks do through kio's +/// `Waiter::poll_future`, dropping each future as it is ready, and a pinned `&mut dyn +/// Future` of the crate's struct last. A cancel drops the futures the queue still holds, +/// in order, and the async block panics on 99. +pub async fn boxed(mut rx: Consumer, guard: Guard) -> u64 { + let first = Box::pin(rx.recv()).await.unwrap_or(0); + guard.note(&format!("first {first}")); + let (id, log) = (guard.id(), guard.log().clone()); + let (block, waiting, ready) = ( + Guard::new(id + 500, log.clone()), + Guard::new(id + 600, log.clone()), + Guard::new(id + 700, log.clone()), + ); + let mut next = rx.clone(); + let mut queue: Vec = vec![ + Box::pin(async move { + let value = rx.recv().await.unwrap_or(0); + if value == 99 { + panic!("g{} poisoned", block.id()); + } + block.note(&format!("block {value}")); + value + 1 + }), + Box::pin(kio::wait(move |waiter| { + next.poll_recv(waiter).map(|value| { + waiting.note("waited"); + value.unwrap_or(0) + 2 + }) + })), + Box::pin(future::poll_fn(move |_| { + ready.note("ready"); + Poll::Ready(3) + })), + ]; + let tail = Guard::new(id + 800, log.clone()); + let mut last = pin!(kio::wait(move |_| Poll::Ready(u64::from(tail.id())))); + let mut total = 0; + let forward = Forward { + future: Box::pin(future::poll_fn(move |cx| { + let mut i = 0; + while i < queue.len() { + match poll_unsized(queue[i].as_mut(), cx) { + Poll::Ready(value) => { + total += value; + drop(queue.swap_remove(i)); + } + Poll::Pending => i += 1, + } + } + if !queue.is_empty() { + return Poll::Pending; + } + let last: Pin<&mut dyn Future> = last.as_mut(); + poll_unsized(last, cx).map(|value| total + value) + })), + }; + let total = forward.await; + guard.note(&format!("boxed {total}")); + total +} + +/// Polls `future`, sized or not, as kio's `Waiter::poll_future` does. +fn poll_unsized(future: Pin<&mut F>, cx: &mut Context<'_>) -> Poll { + future.poll(cx) +} + +/// A future of the crate's that forwards its polls to a boxed one, as moq's session +/// driver does. +struct Forward<'a> { + future: Boxed<'a>, +} + +impl Future for Forward<'_> { + type Output = u64; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.future.as_mut().poll(cx) + } +} diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs index 0ad135688..b5c174d42 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -49,7 +49,7 @@ pub fn run(input: &[u8]) -> Vec { /// Run one step of a script. fn run_step(log: &Log, exec: &mut Executor, channels: &mut Vec, op: u8, arg: u8) { let pick = |len: usize| (len > 0).then(|| usize::from(arg) % len); - match op % 15 { + match op % 16 { 0 => { log.note(format!("c{} open", channels.len())); channels.push(Channel::open()); @@ -112,11 +112,17 @@ fn run_step(log: &Log, exec: &mut Executor, channels: &mut Vec, op: u8, } } 13 => drops::edited(log, 1000 * exec.len() as u32, arg % 8), - _ => { + 14 => { if let Some(c) = pick(channels.len()) { let guard = Guard::new(exec.len() as u32, log.clone()); exec.spawn(futures::helpers(channels[c].consumer(), guard)); } } + _ => { + if let Some(c) = pick(channels.len()) { + let guard = Guard::new(exec.len() as u32, log.clone()); + exec.spawn(futures::boxed(channels[c].consumer(), guard)); + } + } } } diff --git a/ts/fixtures/task/ts.toml b/ts/fixtures/task/ts.toml index 6705526a5..a59bae47d 100644 --- a/ts/fixtures/task/ts.toml +++ b/ts/fixtures/task/ts.toml @@ -12,4 +12,5 @@ roots = [ "drops::held", "drops::edited", "futures::helpers", + "futures::boxed", ] diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 91f9562af..0c41df72e 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -245,6 +245,30 @@ export class PollFn implements Future { } } +/** + * A `dyn Future` of a type whose `Future` impl is a function: each poll calls `poll` on + * `value`, which drops with it by `drop`, if it drops at all: a borrowed one does not. + */ +export class DynFuture implements Future { + readonly #value: S; + readonly #poll: (value: S, cx: Context) => Poll; + readonly #drop: ((value: S) => void) | undefined; + + constructor(value: S, poll: (value: S, cx: Context) => Poll, drop?: (value: S) => void) { + this.#value = value; + this.#poll = poll; + this.#drop = drop; + } + + poll(cx: Context): Poll { + return this.#poll(this.#value, cx); + } + + [Symbol.dispose](): void { + this.#drop?.(this.#value); + } +} + /** `future::Pending`: never ready, and drops as nothing. */ class Never implements Future { poll(): Poll { diff --git a/ts/src/census.rs b/ts/src/census.rs index 4327b6ac4..bbb50ad79 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -166,6 +166,7 @@ const VERBATIM: &[&str] = &[ "break", "collect", "copy_nonoverlapping", + "dyn Future", "flatten", "fold", "for", diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 97f311b00..847c8643f 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -65,6 +65,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ty::Array(elem, _) => self.drops(*elem), ty::Closure(_, args) => args.as_closure().upvar_tys().iter().any(|t| self.drops(t)), ty::Coroutine(..) | ty::Param(_) => true, + ty::Dynamic(..) => self.dyn_future(ty).is_some(), _ => false, }; self.drops_open.remove(&ty); @@ -136,8 +137,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } None => false, }, - // A closure's `[Symbol.dispose]` drops what it owns. - ty::Closure(..) | ty::Coroutine(..) | ty::Param(_) => true, + // A closure's `[Symbol.dispose]` drops what it owns, and a `dyn Future`'s what it is. + ty::Closure(..) | ty::Coroutine(..) | ty::Param(_) | ty::Dynamic(..) => true, _ => false, } } diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 966a04a2b..3f9a7e001 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -520,7 +520,7 @@ fn discards(owner: &str, name: &str) -> Option<&'static [usize]> { Some(match (owner, name) { ("Option", "unwrap" | "expect") | ("Vec", "push") - | ("Box", "new") + | ("Box", "new" | "pin") | ("mem", "replace" | "take" | "swap") | ("hint", "must_use") | ("From", "from") @@ -801,7 +801,7 @@ fn mapping<'tcx>( let tcx = b.t.tcx; let span = call.span; let gargs = call.args; - let args = match super::task::call(b, call, &owner, &name, args) { + let args = match super::task::call(b, call, &owner, &name, args, out) { Ok(e) => return e, Err(args) => args, }; diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 7079dde44..e37ea869f 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -205,9 +205,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let value = self.path(value, "arg", out); self.b.fmt_value(tr, from, value, span, out) } + // A future, as the `rt.Future` a `dyn Future` is. + PointerCoercion::Unsize + if let Some(part) = unsized_to(from, to) + && self.b.t.dyn_future(part.to).is_some() => + { + let value = self.operand(op, span, out); + self.b.dyn_future(part.from, value, part.borrowed, span) + } PointerCoercion::Unsize if self.b.trait_object(to) => self.err(span, format!("a coercion to `{to}`")), // An array's bytes, as a slice of all of it: a reference to them is one already. - PointerCoercion::Unsize if unsized_to(from, to).is_some_and(super::place::byte_slice) => { + PointerCoercion::Unsize if unsized_to(from, to).is_some_and(|u| super::place::byte_slice(u.to)) => { match to.builtin_deref(true) { Some(pointee) if super::place::byte_slice(pointee) => { let value = self.operand(op, span, out); @@ -578,11 +586,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { ty::Ref(..) => in_var && !self.stable_name(&value), _ => true, }; - let value = match snapshot && !value.is_constant() { + // A constant is its own snapshot, unless the closure reassigns it. + let rebinds = rebound.contains(&field); + let constant = value.is_constant(); + let value = match snapshot && (rebinds || !constant) { false => value, true => { let name = self.b.fresh("captured"); - let stmt = StmtKind::decl(rebound.contains(&field), name.clone(), None, Some(value)).at(None); + // Typed, so a reassigned literal keeps its integer's type. + let ts_ty = constant.then(|| self.b.t.held_ty(ty, span)); + let stmt = StmtKind::decl(rebinds, name.clone(), ts_ty, Some(value)).at(None); self.emit(vec![stmt], None, false, out); Expr::ident(name) } @@ -652,12 +665,28 @@ pub(super) fn context_like<'tcx>(fx: &Fx<'_, '_, '_, 'tcx>, ty: Ty<'tcx>) -> boo } } -/// The part of `to` that unsizing `from` makes unsized, such as `[T]` from `[T; N]`. -fn unsized_to<'tcx>(from: Ty<'tcx>, to: Ty<'tcx>) -> Option> { +/// The part of a type that unsizing makes unsized, such as `[T]` from `[T; N]`. +struct Unsized<'tcx> { + /// What it was. + from: Ty<'tcx>, + /// What it is. + to: Ty<'tcx>, + /// Whether it is behind a reference, which doesn't own it. + borrowed: bool, +} + +/// The part of `to` that unsizing `from` makes unsized. +fn unsized_to<'tcx>(from: Ty<'tcx>, to: Ty<'tcx>) -> Option> { match (from.kind(), to.kind()) { _ if from == to => None, - (ty::Array(..), ty::Slice(_)) | (_, ty::Dynamic(..)) => Some(to), - (ty::Ref(_, a, _) | ty::RawPtr(a, _), ty::Ref(_, b, _) | ty::RawPtr(b, _)) => unsized_to(*a, *b), + (ty::Array(..), ty::Slice(_)) | (_, ty::Dynamic(..)) => Some(Unsized { + from, + to, + borrowed: false, + }), + (ty::Ref(_, a, _) | ty::RawPtr(a, _), ty::Ref(_, b, _) | ty::RawPtr(b, _)) => { + unsized_to(*a, *b).map(|u| Unsized { borrowed: true, ..u }) + } (ty::Adt(a, a_args), ty::Adt(b, b_args)) if a.did() == b.did() => { a_args.types().zip(b_args.types()).find_map(|(a, b)| unsized_to(a, b)) } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 00d2ab504..4dfa20203 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -974,6 +974,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { // Its captures change through it, as a JS function's do. ty::Closure(..) => Some(ObjectKind::Closure), ty::Coroutine(..) => Some(ObjectKind::Class), + ty::Dynamic(..) if self.dyn_future(ty).is_some() => Some(ObjectKind::Class), _ if self.deferred(ty) => Some(ObjectKind::Class), _ => None, } @@ -1065,6 +1066,9 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ty::Adt(adt, args) => self.adt_ty(*adt, args, span), ty::Pat(base, _) => self.ty(*base, span), ty::Coroutine(_, args) => Type::Rt("Future", vec![self.ty(args.as_coroutine().return_ty(), span)]), + ty::Dynamic(..) if let Some(output) = self.dyn_future(ty) => { + Type::Rt("Future", vec![self.ty(output, span)]) + } // `&dyn Debug` and `&dyn Display` are values ready to write. ty::Dynamic(preds, ..) if preds @@ -1518,6 +1522,17 @@ pub fn short_name<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> String { ty::Never => "never".into(), ty::Tuple(tys) => tys.iter().map(|t| short_name(tcx, t)).collect::>().join("_"), ty::Array(elem, _) | ty::Slice(elem) => format!("{}s", short_name(tcx, *elem)), + // By its trait and the types it binds, as `dyn_Future_u64`. + ty::Dynamic(preds, ..) => { + let principal = preds.principal().map(|p| p.skip_binder()); + let args = principal.iter().flat_map(|p| p.args.types()); + let bound = preds.projection_bounds().filter_map(|p| p.skip_binder().term.as_type()); + std::iter::once("dyn".to_string()) + .chain(principal.map(|p| tcx.item_name(p.def_id).to_string())) + .chain(args.chain(bound).map(|t| short_name(tcx, t))) + .collect::>() + .join("_") + } // By where it is defined, not by its span, which code above it moves. ty::Closure(def_id, _) | ty::Coroutine(def_id, _) | ty::CoroutineClosure(def_id, _) | ty::FnDef(def_id, _) => { def_name(tcx, *def_id) diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 6b0004edb..2f93acd9f 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -7,9 +7,21 @@ use rustc_span::{Span, Symbol}; use super::Translator; use super::body::Body; use super::library::{self, Call, Std}; -use crate::ts::{Expr, Param}; +use crate::ts::{Expr, Param, Stmt}; impl<'tcx> Translator<'_, 'tcx> { + /// `Future::Output` of `ty`, if it is a `dyn Future`, whose JS value is an `rt.Future`. + pub fn dyn_future(&self, ty: Ty<'tcx>) -> Option> { + let ty::Dynamic(preds, ..) = ty.kind() else { + return None; + }; + if preds.principal_def_id()? != self.tcx.lang_items().future_trait()? { + return None; + } + let output = preds.projection_bounds().next()?; + self.tcx.instantiate_bound_regions_with_erased(output).term.as_type() + } + /// `Future::Output` of `ty`, a future. pub fn future_output(&mut self, ty: Ty<'tcx>, span: Span) -> Ty<'tcx> { let tcx = self.tcx; @@ -25,6 +37,42 @@ impl<'tcx> Translator<'_, 'tcx> { } } +impl<'tcx> Body<'_, '_, 'tcx> { + /// `value`, a `from` that is a future, as the `rt.Future` a `dyn Future` is: itself if + /// it is one already, and else an `rt.DynFuture` over its `Future` impl, which drops it + /// with itself unless `borrowed`. + pub fn dyn_future(&mut self, from: Ty<'tcx>, value: Expr, borrowed: bool, span: Span) -> Expr { + let tcx = self.t.tcx; + match from.kind() { + ty::Dynamic(..) | ty::Coroutine(..) => return value, + // What a reference or a box points at, which its JS value is. + ty::Ref(_, inner, _) => return self.dyn_future(*inner, value, true, span), + ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { + Some(Std::PollFn | Std::Pending) => return value, + Some(Std::Box | Std::Pin) => return self.dyn_future(args.type_at(0), value, borrowed, span), + _ => {} + }, + _ => {} + } + // What `Future::poll` takes would be an `rt.Place`, which the box doesn't have. + if self.t.needs_place(from) { + return self.err(span, format!("a `dyn Future` of `{from}`, which JS copies")); + } + let future = tcx.lang_items().future_trait().expect("a dyn Future names the trait"); + let poll = tcx + .associated_items(future) + .filter_by_name_unhygienic(Symbol::intern("poll")) + .next() + .expect("Future::poll") + .def_id; + let mut args = vec![value, self.fn_value(poll, tcx.mk_args(&[from.into()]), span)]; + if !borrowed { + args.extend(self.t.drop_fn(from, span)); + } + Expr::New(Box::new(Expr::Rt("DynFuture".into())), args) + } +} + /// A call of a standard library function on these types, or its arguments back if it is /// none of theirs. `Ok(None)` refuses it. pub fn call<'tcx>( @@ -33,6 +81,7 @@ pub fn call<'tcx>( owner: &str, name: &str, args: Vec, + out: &mut Vec, ) -> Result, Vec> { let tcx = b.t.tcx; let std_of = |ty: Ty<'tcx>| match ty.peel_refs().kind() { @@ -105,11 +154,31 @@ pub fn call<'tcx>( ) } ("pending", "pending") => Expr::Rt("NEVER".into()), - // std's futures are the runtime's, which poll themselves. - ("Future", "poll") if matches!(self_std, Some(Std::PollFn | Std::Pending)) => { - let [future, cx] = two(args); - future.member("poll").call(vec![cx]) - } + // A box's JS value is what it holds. + ("Box", "pin") => first(args), + ("Future", "poll") => match self_ty.map(Ty::kind) { + // std's futures and a `dyn Future` are `rt.Future`s, which poll themselves. + _ if matches!(self_std, Some(Std::PollFn | Std::Pending)) + || self_ty.is_some_and(|ty| b.t.dyn_future(ty).is_some()) => + { + let [future, cx] = two(args); + future.member("poll").call(vec![cx]) + } + // A pinned pointer, a box, or a `&mut` polls what it points at, which its JS + // value is. + Some(ty::Adt(adt, adt_args)) if matches!(Std::of(tcx, adt.did()), Some(Std::Pin | Std::Box)) => { + let inner = match Std::of(tcx, adt.did()) { + Some(Std::Pin) => adt_args.type_at(0).builtin_deref(true), + _ => Some(adt_args.type_at(0)), + }; + let Some(inner) = inner else { return Err(args) }; + b.call_def(call.def_id, tcx.mk_args(&[inner.into()]), args, call.span, out) + } + Some(ty::Ref(_, inner, _)) => { + b.call_def(call.def_id, tcx.mk_args(&[(*inner).into()]), args, call.span, out) + } + _ => return Err(args), + }, ("Context", "waker" | "from_waker") | ("Pin", "new" | "new_unchecked" | "as_mut" | "get_mut" | "get_unchecked_mut") | ("pin", "pin_new_unchecked_in_helper") diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 3a3f76dbd..2ce2663f0 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -51,7 +51,10 @@ export interface Fixture { held(rx: Consumer, guard: Guard): Future; edited(log: Log, id: number, at: number): void; }; - futures: { helpers(rx: Consumer, guard: Guard): Future }; + futures: { + helpers(rx: Consumer, guard: Guard): Future; + boxed(rx: Consumer, guard: Guard): Future; + }; } /** What every waker of one task points at. */ @@ -202,7 +205,7 @@ export function harness(f: Fixture, unwind = false): (input: Uint8Array) = function step(op: number, arg: number): void { const pick = (len: number) => (len > 0 ? arg % len : undefined); const c = pick(channels.length); - switch (op % 15) { + switch (op % 16) { case 0: note(`c${channels.length} open`); channels.push(f.Channel.open()); @@ -261,8 +264,11 @@ export function harness(f: Fixture, unwind = false): (input: Uint8Array) = case 13: f.drops.edited(log, 1000 * exec.tasks.length, arg % 8); break; - default: + case 14: if (c !== undefined) exec.spawn(f.futures.helpers(f.Channel.consumer(channels[c]), f.Guard.new(exec.tasks.length, f.Log.clone$Clone(log)))); + break; + default: + if (c !== undefined) exec.spawn(f.futures.boxed(f.Channel.consumer(channels[c]), f.Guard.new(exec.tasks.length, f.Log.clone$Clone(log)))); } } }; @@ -296,6 +302,12 @@ export const cases: Uint8Array[] = [ [0, 0, 14, 0, 6, 0, 3, 5, 6, 0, 3, 77, 6, 0], [0, 0, 14, 0, 14, 1, 6, 0, 3, 4, 7, 0, 9, 1, 9, 0], [0, 0, 14, 0, 6, 0, 3, 99, 6, 0, 8, 0], + // Boxed futures: a boxed `recv` awaited, then a queue of `dyn Future`s polled through a + // boxed `poll_fn`, returning, cancelled with the futures the queue still holds, and + // panicking inside one. + [0, 0, 15, 0, 6, 0, 3, 5, 6, 0, 3, 6, 7, 0, 3, 7, 6, 0], + [0, 0, 15, 0, 15, 1, 6, 0, 3, 4, 6, 0, 9, 1, 3, 5, 7, 0, 9, 0], + [0, 0, 15, 0, 6, 0, 3, 5, 6, 0, 3, 99, 6, 0, 8, 0, 9, 0], // Each scenario of values std holds that drop, panicking at each point or none. ...Array.from({ length: 253 }, (_, arg) => [11, arg]), // Each of a `Vec`'s edits, its and a tuple's `clone`, and `Ord`'s defaults, panicking at each point or none. From 8a4d42a6c70937db71760fd833b1a7636df56fed Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:25:08 -0700 Subject: [PATCH 3/3] fix(ts): keep a boxed borrow from dropping its future, and refuse dyn Future behind an Arc Co-Authored-By: Claude Opus 5.5 --- ts/fixtures/reject/census.md | 23 +- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 16 + ts/fixtures/reject/ts.toml | 1 + ts/fixtures/task/expected/core/task/poll.ts | 4 +- ts/fixtures/task/expected/futures.ts | 606 ++++++++++++-------- ts/fixtures/task/expected/kio.Pending.ts | 4 +- ts/fixtures/task/expected/kio.ts | 4 +- ts/fixtures/task/src/futures.rs | 12 +- ts/runtime/rt/task.ts | 5 + ts/src/lower/mir/rvalue.rs | 31 +- ts/src/lower/task.rs | 58 +- 12 files changed, 462 insertions(+), 303 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 6a5110a07..f82bc1b30 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 76 -- Function instances: 82 +- Refusals: 77 +- Function instances: 84 - Generic functions no instance reached, lowered over their type parameters: 6 ## By construct @@ -19,6 +19,7 @@ | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | fixtures/reject/src/lib.rs:23:15 | | 2 | `_` of `_`, whose `None` is `rt.None`, which is not supported yet | fixtures/reject/src/lib.rs:48:42 | | 2 | `_` of a reference to an array of bytes it is generic over, which its mapping would take as the array, not as a slice of it | fixtures/reject/src/lib.rs:268:16 | +| 2 | a coercion to `_` | fixtures/reject/src/lib.rs:362:2 | | 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:175:1 | | 2 | constructing `_` from another crate | fixtures/reject/src/lib.rs:161:23 | | 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:155:2 | @@ -36,7 +37,6 @@ | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | fixtures/reject/src/lib.rs:242:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:188:51 | | 1 | a cast from `_` to `_` | fixtures/reject/src/lib.rs:112:2 | -| 1 | a coercion to `_` | fixtures/reject/src/lib.rs:362:2 | | 1 | a constant of type `_` | fixtures/reject/src/lib.rs:96:2 | | 1 | a copy of a closure that changes what it captured | fixtures/reject/src/lib.rs:278:14 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | fixtures/reject/src/lib.rs:247:13 | @@ -62,10 +62,10 @@ The type or module each refused type or path belongs to. | 6 | `Option` | fixtures/reject/src/lib.rs:23:15 | | 6 | `f32` | fixtures/reject/src/lib.rs:7:14 | | 4 | `Iterator` | fixtures/reject/src/lib.rs:48:42 | +| 4 | `std::sync::Arc` | fixtures/reject/src/lib.rs:117:2 | | 3 | `PartialOrd` | fixtures/reject/src/lib.rs:381:4 | | 3 | `std::iter::Map` | fixtures/reject/src/lib.rs:63:23 | | 3 | `std::slice` | fixtures/reject/src/lib.rs:28:4 | -| 3 | `std::sync::Arc` | fixtures/reject/src/lib.rs:117:2 | | 3 | `std::vec::Vec` | fixtures/reject/src/lib.rs:289:52 | | 3 | `u8` | fixtures/reject/src/lib.rs:96:2 | | 3 | `{closure}` | fixtures/reject/src/lib.rs:411:13 | @@ -115,6 +115,7 @@ The type or module each refused type or path belongs to. | 3 | unsupported type `_` | `f32` | fixtures/reject/src/lib.rs:7:14 | | 2 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:121:20 | | 2 | `_` is not supported: its `None` and `Some` would both be `rt.None` | `Option` | fixtures/reject/src/lib.rs:23:15 | +| 2 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:362:2 | | 2 | an assignment through a reference to `_` | `std::pin::Pin` | fixtures/reject/src/lib.rs:132:2 | | 2 | comparing `_` through its own `_`, which is not supported yet | `Lopsided`, `PartialOrd::lt` | fixtures/reject/src/lib.rs:381:4 | | 2 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:101:2 | @@ -137,7 +138,6 @@ The type or module each refused type or path belongs to. | 1 | a `zip` of `_` and `_`, which std reads by index, of items that drop, which is not supported yet | `std::iter::Map`, `std::ops::Range` | fixtures/reject/src/lib.rs:242:30 | | 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:188:51 | | 1 | a cast from `_` to `_` | `u64`, `f32` | fixtures/reject/src/lib.rs:112:2 | -| 1 | a coercion to `_` | `std::sync::Arc` | fixtures/reject/src/lib.rs:362:2 | | 1 | a constant of type `_` | `&u8` | fixtures/reject/src/lib.rs:96:2 | | 1 | a mutable borrow of a subslice of `_`, which JS would copy, having no views | `u32` | fixtures/reject/src/lib.rs:247:13 | | 1 | a scalar constant of type `_` | `f32` | fixtures/reject/src/lib.rs:8:2 | @@ -269,6 +269,13 @@ The type or module each refused type or path belongs to. +
a coercion to `_` (2) + +- fixtures/reject/src/lib.rs:362:2: a coercion to `std::sync::Arc<[u8]>` +- fixtures/reject/src/lib.rs:509:2: a coercion to `std::sync::Arc>` + +
+
an iterator of the crate implementing `_`, which is not supported yet (2) - fixtures/reject/src/lib.rs:175:1: an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet @@ -375,12 +382,6 @@ The type or module each refused type or path belongs to.
-
a coercion to `_` (1) - -- fixtures/reject/src/lib.rs:362:2: a coercion to `std::sync::Arc<[u8]>` - -
-
a constant of type `_` (1) - fixtures/reject/src/lib.rs:96:2: a constant of type `&u8` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 67f082f1a..fe102d4f0 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -24,6 +24,7 @@ replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs an assignment through a reference to `std::sync::Arc` at fixtures/reject/src/lib.rs:117:2 `Poll>>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:121:20 `Poll>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:126:54 +a coercion to `std::sync::Arc>` at fixtures/reject/src/lib.rs:509:2 an assignment through a reference to `std::pin::Pin>` at fixtures/reject/src/lib.rs:132:2 an assignment through a reference to `std::sync::MutexGuard<'_, u8>` at fixtures/reject/src/lib.rs:137:2 unsupported call to ` as std::iter::Iterator>::cycle` at fixtures/reject/src/lib.rs:142:11 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 16ca6043b..d4f133e17 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -502,3 +502,19 @@ pub fn fma(a: f64) -> f64 { pub fn float_printed(a: f64) -> String { format!("{a}") } + +/// An `Arc` around a future of the crate's: a `dyn Future` behind it would need the `Arc`'s +/// own count around an `rt.Future`. +pub fn shared_future() -> std::sync::Arc> { + std::sync::Arc::new(Ready(1)) +} + +pub struct Ready(u8); + +impl std::future::Future for Ready { + type Output = u8; + + fn poll(self: std::pin::Pin<&mut Self>, _: &mut std::task::Context<'_>) -> std::task::Poll { + std::task::Poll::Ready(self.0) + } +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index d52c4d686..b75d468a4 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -21,6 +21,7 @@ roots = [ "replace_shared", "nested_poll", "pending_output", + "shared_future", "replace_pinned", "replace_guard", "cycled", diff --git a/ts/fixtures/task/expected/core/task/poll.ts b/ts/fixtures/task/expected/core/task/poll.ts index 6d8dd3e37..c810551bb 100644 --- a/ts/fixtures/task/expected/core/task/poll.ts +++ b/ts/fixtures/task/expected/core/task/poll.ts @@ -9,14 +9,14 @@ export function map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_clo return rt.Pending; } -export function map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0(self: rt.Poll, f: (a0: rt.u64 | undefined) => rt.u64): rt.Poll { +export function map$Poll_Option_u64_u64_boxed_closure0_closure3_closure0(self: rt.Poll, f: (a0: rt.u64 | undefined) => rt.u64): rt.Poll { if (self !== rt.Pending) { return f(self); } return rt.Pending; } -export function map$Poll_u64_u64_boxed_closure0_closure0_closure0(self: rt.Poll, f: (a0: rt.u64) => rt.u64): rt.Poll { +export function map$Poll_u64_u64_boxed_closure0_closure1_closure0(self: rt.Poll, f: (a0: rt.u64) => rt.u64): rt.Poll { if (self !== rt.Pending) { return f(self); } diff --git a/ts/fixtures/task/expected/futures.ts b/ts/fixtures/task/expected/futures.ts index baa632b33..0b8fc4832 100644 --- a/ts/fixtures/task/expected/futures.ts +++ b/ts/fixtures/task/expected/futures.ts @@ -2,13 +2,13 @@ import * as rt from "./rt.ts"; import { unwrapOr$Option_u64, okOr$Option_u64_u64 } from "./core/option.ts"; -import { map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0, map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0, map$Poll_u64_u64_boxed_closure0_closure0_closure0, isReady$Poll_Option_u64, isPending$Poll_Option_u64, isPending$Poll_u64, mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1, mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2 } from "./core/task/poll.ts"; +import { map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0, map$Poll_Option_u64_u64_boxed_closure0_closure3_closure0, map$Poll_u64_u64_boxed_closure0_closure1_closure0, isReady$Poll_Option_u64, isPending$Poll_Option_u64, isPending$Poll_u64, mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1, mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2 } from "./core/task/poll.ts"; import * as Blast from "./futures.Blast.ts"; import * as Forward from "./futures.Forward.ts"; import * as Fused from "./futures.Fused.ts"; import * as Plain from "./futures.Plain.ts"; import * as Relay from "./futures.Relay.ts"; -import { wait$boxed_closure0_closure2_u64, wait$boxed_closure0_closure4_u64, recvFuture } from "./kio.ts"; +import { wait$boxed_closure0_closure3_u64, wait$boxed_closure0_closure5_u64, recvFuture } from "./kio.ts"; import * as Consumer from "./kio.Consumer.ts"; import * as Pending from "./kio.Pending.ts"; import type * as Waiter from "./kio.Waiter.ts"; @@ -385,7 +385,8 @@ export function relayed(task: rt.Waker, log: Log.Log, id: rt.u32): rt.Waker { } /** - * Boxed futures over a channel: `Box::pin` of an async fn, awaited, then a queue of + * Boxed futures over a channel: `Box::pin` of an async fn, awaited, and of a `&mut` to a + * `poll_fn`, whose box drops without dropping it, then a queue of * `Pin>`s of an async block, kio's `Pending`, a struct of the crate's, * and a `poll_fn`, each owning a guard. A `poll_fn` boxed in a [`Forward`] polls the * queue in turn through [`poll_unsized`], as moq's tasks do through kio's @@ -403,15 +404,20 @@ export class boxedFuture { #guard: Guard.Guard; #first!: rt.u64; #awaitee!: rt.Future; + #id!: rt.u32; #log!: Log.Log; + #lend!: rt.Future; + #lent!: rt.u64; + #awaitee$2!: rt.Future; #pinned!: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll>; - #awaitee$2!: Forward.Forward; + #awaitee$3!: Forward.Forward; #saved!: boolean; #saved$2!: boolean; #saved$3!: boolean; #saved$4!: boolean; #saved$5!: boolean; #saved$6!: boolean; + #saved$7!: boolean; constructor(rx: Consumer.Consumer, guard: Guard.Guard) { this.#rx = rx; @@ -421,75 +427,103 @@ export class boxedFuture { [Symbol.dispose](): void { let unwind: number = 0; try { - if (this.#state === 0) { - unwind = 48; - rt.drop(this.#rx); - unwind = 0; - rt.drop(this.#guard); - return; - } - if (this.#state === 3) { - unwind = 37; - rt.drop(this.#awaitee); - } else if (this.#state === 4) { - unwind = 25; - rt.drop(this.#awaitee$2); - unwind = 28; - rt.drop(this.#pinned); - this.#saved$2 = false; - this.#saved$3 = false; - this.#saved$4 = false; - this.#saved$5 = false; - this.#saved$6 = false; - unwind = 36; + b0: { + if (this.#state === 0) { + unwind = 66; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#guard); + return; + } + if (this.#state === 3) { + unwind = 51; + rt.drop(this.#awaitee); + break b0; + } + if (this.#state === 4) { + unwind = 44; + rt.drop(this.#awaitee$2); + } else if (this.#state !== 5) { + if (this.#state === 6) { + unwind = 34; + rt.drop(this.#awaitee$3); + unwind = 37; + rt.drop(this.#pinned); + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + this.#saved$7 = false; + } else { + return; + } + } + if (this.#saved) { + unwind = 48; + rt.drop(this.#lend); + } + this.#saved = false; + unwind = 50; rt.drop(this.#log); - } else { - return; } - unwind = 40; + unwind = 54; rt.drop(this.#guard); - if (this.#saved) { + if (this.#saved$2) { unwind = 0; rt.drop(this.#rx); } - this.#saved = false; + this.#saved$2 = false; } catch (e) { - b2: { - b3: { - b4: { - b5: { - if (unwind === 0) { - throw e; - } - if (unwind === 25) { - rt.drop(this.#pinned); - } else if (unwind !== 28) { - if (unwind === 36) { - break b5; - } - if (unwind === 37) { - break b4; + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + if (unwind === 0) { + throw e; + } + if (unwind === 34) { + rt.drop(this.#pinned); + } else if (unwind !== 37) { + if (unwind === 44) { + break b10; + } + if (unwind === 48) { + break b9; + } + if (unwind === 50) { + break b8; + } + if (unwind === 51) { + break b7; + } + if (unwind === 54) { + break b6; + } + rt.drop(this.#guard); + break b5; + } + this.#saved$3 = false; + this.#saved$4 = false; + this.#saved$5 = false; + this.#saved$6 = false; + this.#saved$7 = false; } - if (unwind === 40) { - break b3; + if (this.#saved) { + rt.drop(this.#lend); } - rt.drop(this.#guard); - break b2; } - this.#saved$2 = false; - this.#saved$3 = false; - this.#saved$4 = false; - this.#saved$5 = false; - this.#saved$6 = false; + this.#saved = false; rt.drop(this.#log); } } rt.drop(this.#guard); } - if (this.#saved) { + if (this.#saved$2) { rt.drop(this.#rx); } - this.#saved = false; + this.#saved$2 = false; } throw e; } @@ -499,271 +533,343 @@ export class boxedFuture { let block!: Guard.Guard; let waiting!: Guard.Guard; let ready!: Guard.Guard; - let _39!: Guard.Guard; - let _44!: Guard.Guard; + let _83!: Guard.Guard; + let _89!: Guard.Guard; let next!: Consumer.Consumer; let queue!: rt.Future[]; - let _59!: rt.Future; - let _62!: rt.Future; + let _106!: rt.Future; + let _109!: rt.Future; let unwind: number = 0; try { b0: { - if (this.#state === 0) { - unwind = 81; - this.#saved = false; - this.#saved$6 = false; - this.#saved$5 = false; - this.#saved$4 = false; - this.#saved$3 = false; - this.#saved$2 = false; - this.#saved = true; - this.#awaitee = new recvFuture(this.#rx); - } else if (this.#state === 1) { - rt.asyncFnResumed(); - } else if (this.#state === 2) { - rt.asyncFnResumedPanic(); - } else if (this.#state !== 3) { - break b0; + b1: { + b2: { + if (this.#state === 0) { + unwind = 112; + this.#saved$2 = false; + this.#saved = false; + this.#saved$7 = false; + this.#saved$6 = false; + this.#saved$5 = false; + this.#saved$4 = false; + this.#saved$3 = false; + this.#saved$2 = true; + this.#awaitee = new recvFuture(this.#rx); + } else if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } else if (this.#state !== 3) { + if (this.#state === 4) { + break b2; + } + if (this.#state === 5) { + break b1; + } + break b0; + } + unwind = 111; + const _7: rt.Poll = this.#awaitee.poll(_2); + if (_7 !== rt.Pending) { + unwind = 112; + const result: rt.u64 | undefined = _7; + rt.drop(this.#awaitee); + this.#first = unwrapOr$Option_u64(result, 0); + const arg = this.#first; + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; + const _19: string = rt.fmtFormat(["first ", args2[0]]); + unwind = 110; + Guard.note(this.#guard, _19); + unwind = 112; + const _29: rt.u32 = Guard.id(this.#guard); + const _31: Log.Log = Log.clone$Clone(Guard.log(this.#guard)); + unwind = 109; + this.#id = _29; + this.#log = _31; + const lent: Guard.Guard = Guard.new(rt.u32Add(this.#id, 900), Log.clone$Clone(this.#log)); + unwind = 108; + const captured = lent; + this.#lend = new rt.PollFn(rt.closure((_22: rt.Context): rt.Poll => { + Guard.note(captured, "lent"); + return 4; + }, (): void => { + rt.drop(captured); + }), rt.drop); + unwind = 107; + this.#saved = true; + this.#awaitee$2 = new rt.DynFuture(this.#lend, rt.futurePoll); + } else { + this.#state = 3; + return rt.Pending; + } + } + unwind = 106; + const _45: rt.Poll = this.#awaitee$2.poll(_2); + if (_45 !== rt.Pending) { + unwind = 107; + this.#lent = _45; + rt.drop(this.#awaitee$2); + this.#awaitee$2 = this.#lend; + } else { + this.#state = 4; + return rt.Pending; + } } - unwind = 80; - const _7: rt.Poll = this.#awaitee.poll(_2); - if (_7 !== rt.Pending) { - unwind = 81; - const result: rt.u64 | undefined = _7; - rt.drop(this.#awaitee); - this.#first = unwrapOr$Option_u64(result, 0); - const arg = this.#first; - const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg, f)]; - const _19: string = rt.fmtFormat(["first ", args2[0]]); - unwind = 79; - Guard.note(this.#guard, _19); - unwind = 81; - const _30: rt.u32 = Guard.id(this.#guard); - const _32: Log.Log = Log.clone$Clone(Guard.log(this.#guard)); - unwind = 78; - const id: rt.u32 = _30; - this.#log = _32; - _39 = Guard.new(rt.u32Add(id, 500), Log.clone$Clone(this.#log)); - unwind = 77; - _44 = Guard.new(rt.u32Add(id, 600), Log.clone$Clone(this.#log)); - unwind = 76; - const _49: Guard.Guard = Guard.new(rt.u32Add(id, 700), Log.clone$Clone(this.#log)); - unwind = 72; + unwind = 107; + const _55: rt.Poll = this.#awaitee$2.poll(_2); + if (_55 !== rt.Pending) { + this.#lent = rt.u64Add(this.#lent, _55); + const arg2 = this.#lent; + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(arg2, f)]; + const _68: string = rt.fmtFormat(["lent ", args4[0]]); + unwind = 105; + Guard.note(this.#guard, _68); + unwind = 107; + this.#saved = false; + rt.drop(this.#lend); + _83 = Guard.new(rt.u32Add(this.#id, 500), Log.clone$Clone(this.#log)); + unwind = 104; + _89 = Guard.new(rt.u32Add(this.#id, 600), Log.clone$Clone(this.#log)); + unwind = 103; + const _95: Guard.Guard = Guard.new(rt.u32Add(this.#id, 700), Log.clone$Clone(this.#log)); + unwind = 99; + this.#saved$7 = true; + block = _83; this.#saved$6 = true; - block = _39; + waiting = _89; this.#saved$5 = true; - waiting = _44; - this.#saved$4 = true; - ready = _49; + ready = _95; next = Consumer.clone$Clone(this.#rx); - this.#saved$3 = true; - unwind = 70; - this.#saved = false; + this.#saved$4 = true; + unwind = 97; + this.#saved$2 = false; + this.#saved$7 = false; + const _107: rt.Future = new boxedFuture$2(this.#rx, block); + unwind = 96; + _106 = _107; + this.#saved$4 = false; this.#saved$6 = false; - const _60: rt.Future = new boxedFuture$2(this.#rx, block); - unwind = 69; - _59 = _60; - this.#saved$3 = false; - this.#saved$5 = false; - let captured = next; - const captured2 = waiting; - const _63: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure2_u64(rt.closure((waiter: Waiter.Waiter): rt.Poll => { - return map$Poll_Option_u64_u64_boxed_closure0_closure2_closure0(Consumer.pollRecv(captured, waiter), (value: rt.u64 | undefined): rt.u64 => { - Guard.note(captured2, "waited"); + let captured2 = next; + const captured3 = waiting; + const _110: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure3_u64(rt.closure((waiter: Waiter.Waiter): rt.Poll => { + return map$Poll_Option_u64_u64_boxed_closure0_closure3_closure0(Consumer.pollRecv(captured2, waiter), (value: rt.u64 | undefined): rt.u64 => { + Guard.note(captured3, "waited"); return rt.u64Add(unwrapOr$Option_u64(value, 0), 2); }); }, (): void => { let dropped: number = 0; try { - rt.drop(captured); - dropped = 1; rt.drop(captured2); + dropped = 1; + rt.drop(captured3); } catch (e) { if (dropped < 1) { - rt.drop(captured2); + rt.drop(captured3); } throw e; } })); - unwind = 68; - _62 = new rt.DynFuture(_63, Pending.poll$Future_boxed_closure0_closure2, rt.drop); - this.#saved$4 = false; - const captured3 = ready; - const _67: rt.Future = new rt.PollFn(rt.closure((_22: rt.Context): rt.Poll => { - Guard.note(captured3, "ready"); + unwind = 95; + _109 = new rt.DynFuture(_110, Pending.poll$Future_boxed_closure0_closure3, rt.drop); + this.#saved$5 = false; + const captured4 = ready; + const _114: rt.Future = new rt.PollFn(rt.closure((_23: rt.Context): rt.Poll => { + Guard.note(captured4, "ready"); return 3; }, (): void => { - rt.drop(captured3); + rt.drop(captured4); }), rt.drop); - unwind = 71; - queue = [_59, _62, _67]; - unwind = 67; - this.#saved$2 = true; - const captured4 = Guard.new(rt.u32Add(id, 800), Log.clone$Clone(this.#log)); - const _76: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure4_u64(rt.closure((_23: Waiter.Waiter): rt.Poll => { - return Guard.id(captured4) as rt.u64; + unwind = 98; + queue = [_106, _109, _114]; + unwind = 94; + this.#saved$3 = true; + const captured5 = Guard.new(rt.u32Add(this.#id, 800), Log.clone$Clone(this.#log)); + const _124: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = wait$boxed_closure0_closure5_u64(rt.closure((_24: Waiter.Waiter): rt.Poll => { + return Guard.id(captured5) as rt.u64; }, (): void => { - rt.drop(captured4); + rt.drop(captured5); })); - unwind = 66; - this.#pinned = _76; + unwind = 93; + this.#pinned = _124; const last: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = this.#pinned; - this.#saved$2 = false; - let captured5 = queue; - let captured6: rt.u64 = 0; - let captured7 = last; - this.#awaitee$2 = new Forward.Forward({ future: new rt.PollFn(rt.closure((cx: rt.Context): rt.Poll => { + this.#saved$3 = false; + let captured6 = queue; + let captured7: rt.u64 = 0; + let captured8 = last; + this.#awaitee$3 = new Forward.Forward({ future: new rt.PollFn(rt.closure((cx: rt.Context): rt.Poll => { let i: rt.usize = 0; - while (i < captured5.length) { - const _84: rt.Poll = pollUnsized$dyn_Future_u64(captured5[rt.idx(captured5, i)], cx); - if (_84 !== rt.Pending) { - captured6 = rt.u64Add(captured6, _84); - rt.drop(rt.vecSwapRemove(captured5, i)); + while (i < captured6.length) { + const _88: rt.Poll = pollUnsized$dyn_Future_u64(captured6[rt.idx(captured6, i)], cx); + if (_88 !== rt.Pending) { + captured7 = rt.u64Add(captured7, _88); + rt.drop(rt.vecSwapRemove(captured6, i)); } else { i = rt.usizeAdd(i, 1); } } - if (!((captured5.length === 0))) { + if (!((captured6.length === 0))) { return rt.Pending; } - return map$Poll_u64_u64_boxed_closure0_closure0_closure0(pollUnsized$dyn_Future_u64(new rt.DynFuture(captured7, Pending.poll$Future_boxed_closure0_closure4), cx), (value3: rt.u64): rt.u64 => { - return rt.u64Add(captured6, value3); + return map$Poll_u64_u64_boxed_closure0_closure1_closure0(pollUnsized$dyn_Future_u64(new rt.DynFuture(captured8, Pending.poll$Future_boxed_closure0_closure5), cx), (value3: rt.u64): rt.u64 => { + return rt.u64Add(captured7, value3); }); }, (): void => { - rt.dropAll(captured5); + rt.dropAll(captured6); }), rt.drop) }); } else { - this.#state = 3; + this.#state = 5; return rt.Pending; } } - unwind = 65; - const _86: rt.Poll = Forward.poll$Future(this.#awaitee$2, _2); - if (_86 !== rt.Pending) { - unwind = 66; - const total: rt.u64 = _86; - rt.drop(this.#awaitee$2); - const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(total, f)]; - const _98: string = rt.fmtFormat(["boxed ", args4[0]]); - unwind = 64; - Guard.note(this.#guard, _98); - unwind = 67; + unwind = 92; + const _134: rt.Poll = Forward.poll$Future(this.#awaitee$3, _2); + if (_134 !== rt.Pending) { + unwind = 93; + const total: rt.u64 = _134; + rt.drop(this.#awaitee$3); + const args6: rt.Fmt[] = [(f: rt.Formatter) => rt.u64Display(total, f)]; + const _146: string = rt.fmtFormat(["boxed ", args6[0]]); + unwind = 91; + Guard.note(this.#guard, _146); + unwind = 94; rt.drop(this.#pinned); - unwind = 81; - this.#saved$2 = false; + unwind = 112; this.#saved$3 = false; this.#saved$4 = false; this.#saved$5 = false; this.#saved$6 = false; + this.#saved$7 = false; + this.#saved = false; rt.drop(this.#log); - unwind = 89; + unwind = 121; rt.drop(this.#guard); - this.#saved = false; + this.#saved$2 = false; this.#state = 1; return total; } - this.#state = 4; + this.#state = 6; return rt.Pending; } catch (e) { - b2: { - b3: { - b4: { - b5: { - b6: { - b7: { - b8: { - b9: { - b10: { - if (unwind === 0) { - throw e; - } - if (unwind === 64) { - break b8; - } - if (unwind === 65) { - rt.drop(this.#awaitee$2); - break b8; - } - if (unwind === 66) { - break b8; - } - if (unwind === 67) { - break b7; - } - if (unwind === 68) { - rt.drop(_62); - break b10; - } - if (unwind === 69) { - break b10; - } - if (unwind === 70) { - break b9; - } - if (unwind === 71) { - break b6; - } - if (unwind === 72) { - break b5; - } - if (unwind === 76) { - rt.drop(_44); - } else if (unwind !== 77) { - if (unwind === 78) { - break b4; - } - if (unwind === 79) { - break b3; - } - if (unwind === 80) { - rt.drop(this.#awaitee); - break b3; + b4: { + b5: { + b6: { + b7: { + b8: { + b9: { + b10: { + b11: { + b12: { + b13: { + b14: { + if (unwind === 0) { + throw e; + } + if (unwind === 91) { + break b12; + } + if (unwind === 92) { + rt.drop(this.#awaitee$3); + break b12; + } + if (unwind === 93) { + break b12; + } + if (unwind === 94) { + break b11; + } + if (unwind === 95) { + rt.drop(_109); + break b14; + } + if (unwind === 96) { + break b14; + } + if (unwind === 97) { + break b13; + } + if (unwind === 98) { + break b10; + } + if (unwind === 99) { + break b9; + } + if (unwind === 103) { + rt.drop(_89); + } else if (unwind !== 104) { + if (unwind === 105) { + break b8; + } + if (unwind === 106) { + rt.drop(this.#awaitee$2); + break b8; + } + if (unwind === 107) { + break b8; + } + if (unwind === 108) { + break b7; + } + if (unwind === 109) { + break b6; + } + if (unwind === 110) { + break b5; + } + if (unwind === 111) { + rt.drop(this.#awaitee); + break b5; + } + if (unwind === 112) { + break b5; + } + break b4; + } + rt.drop(_83); + break b8; } - if (unwind === 81) { - break b3; - } - break b2; + rt.drop(_106); } - rt.drop(_39); - break b4; + break b10; } - rt.drop(_59); + rt.drop(this.#pinned); + } + if (this.#saved$3) { + rt.dropAll(queue); } - break b6; } - rt.drop(this.#pinned); + this.#saved$3 = false; + if (this.#saved$4) { + rt.drop(next); + } + } + this.#saved$4 = false; + if (this.#saved$5) { + rt.drop(ready); } - if (this.#saved$2) { - rt.dropAll(queue); + this.#saved$5 = false; + if (this.#saved$6) { + rt.drop(waiting); } + this.#saved$6 = false; + if (this.#saved$7) { + rt.drop(block); + } + this.#saved$7 = false; } - this.#saved$2 = false; - if (this.#saved$3) { - rt.drop(next); + if (this.#saved) { + rt.drop(this.#lend); } } - this.#saved$3 = false; - if (this.#saved$4) { - rt.drop(ready); - } - this.#saved$4 = false; - if (this.#saved$5) { - rt.drop(waiting); - } - this.#saved$5 = false; - if (this.#saved$6) { - rt.drop(block); - } - this.#saved$6 = false; + this.#saved = false; } rt.drop(this.#log); } rt.drop(this.#guard); } - if (this.#saved) { + if (this.#saved$2) { rt.drop(this.#rx); } - this.#saved = false; + this.#saved$2 = false; this.#state = 2; throw e; } diff --git a/ts/fixtures/task/expected/kio.Pending.ts b/ts/fixtures/task/expected/kio.Pending.ts index 89284edb2..9ac1bae2f 100644 --- a/ts/fixtures/task/expected/kio.Pending.ts +++ b/ts/fixtures/task/expected/kio.Pending.ts @@ -29,12 +29,12 @@ export class Pending { } } -export function poll$Future_boxed_closure0_closure2(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { +export function poll$Future_boxed_closure0_closure3(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { const this_: Pending<(a0: Waiter.Waiter) => rt.Poll> = self; return this_.poll(Park.hold(this_.park, cx)); } -export function poll$Future_boxed_closure0_closure4(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { +export function poll$Future_boxed_closure0_closure5(self: Pending<(a0: Waiter.Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { const this_: Pending<(a0: Waiter.Waiter) => rt.Poll> = self; return this_.poll(Park.hold(this_.park, cx)); } diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts index 5ef67d918..7d3bb89c4 100644 --- a/ts/fixtures/task/expected/kio.ts +++ b/ts/fixtures/task/expected/kio.ts @@ -7,7 +7,7 @@ import * as Pending from "./kio.Pending.ts"; import type * as Waiter from "./kio.Waiter.ts"; /** A future from a poll function that receives a [`Waiter`]. */ -export function wait$boxed_closure0_closure2_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { +export function wait$boxed_closure0_closure3_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { let _2!: (a0: Waiter.Waiter) => rt.Poll; let unwind: number = 0; try { @@ -24,7 +24,7 @@ export function wait$boxed_closure0_closure2_u64(poll: (a0: Waiter.Waiter) => rt } /** A future from a poll function that receives a [`Waiter`]. */ -export function wait$boxed_closure0_closure4_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { +export function wait$boxed_closure0_closure5_u64(poll: (a0: Waiter.Waiter) => rt.Poll): Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> { let _2!: (a0: Waiter.Waiter) => rt.Poll; let unwind: number = 0; try { diff --git a/ts/fixtures/task/src/futures.rs b/ts/fixtures/task/src/futures.rs index 14b531a1a..33b9b4163 100644 --- a/ts/fixtures/task/src/futures.rs +++ b/ts/fixtures/task/src/futures.rs @@ -135,7 +135,8 @@ impl Drop for Blast { /// A boxed future, as moq's `MaybeSendBox` is. type Boxed<'a> = Pin + 'a>>; -/// Boxed futures over a channel: `Box::pin` of an async fn, awaited, then a queue of +/// Boxed futures over a channel: `Box::pin` of an async fn, awaited, and of a `&mut` to a +/// `poll_fn`, whose box drops without dropping it, then a queue of /// `Pin>`s of an async block, kio's `Pending`, a struct of the crate's, /// and a `poll_fn`, each owning a guard. A `poll_fn` boxed in a [`Forward`] polls the /// queue in turn through [`poll_unsized`], as moq's tasks do through kio's @@ -146,6 +147,15 @@ pub async fn boxed(mut rx: Consumer, guard: Guard) -> u64 { let first = Box::pin(rx.recv()).await.unwrap_or(0); guard.note(&format!("first {first}")); let (id, log) = (guard.id(), guard.log().clone()); + let lent = Guard::new(id + 900, log.clone()); + let mut lend = future::poll_fn(move |_| { + lent.note("lent"); + Poll::Ready(4) + }); + let erased: Boxed<'_> = Box::pin(&mut lend); + let lent = erased.await + (&mut lend).await; + guard.note(&format!("lent {lent}")); + drop(lend); let (block, waiting, ready) = ( Guard::new(id + 500, log.clone()), Guard::new(id + 600, log.clone()), diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 0c41df72e..3c9fbc652 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -269,6 +269,11 @@ export class DynFuture implements Future { } } +/** `future.poll(cx)`: the `poll` of an `rt.DynFuture` over a future it borrows. */ +export function futurePoll(future: Future, cx: Context): Poll { + return future.poll(cx); +} + /** `future::Pending`: never ready, and drops as nothing. */ class Never implements Future { poll(): Poll { diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 5d9eb37fe..f928d9a59 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -207,15 +207,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } // A future, as the `rt.Future` a `dyn Future` is. PointerCoercion::Unsize - if let Some(part) = unsized_to(from, to) - && self.b.t.dyn_future(part.to).is_some() => + if unsized_to(from, to).is_some_and(|part| self.b.t.dyn_future(part).is_some()) => { let value = self.operand(op, span, out); - self.b.dyn_future(part.from, value, part.borrowed, span) + self.b.dyn_future(from, to, value, span) } PointerCoercion::Unsize if self.b.trait_object(to) => self.err(span, format!("a coercion to `{to}`")), // An array's bytes, as a slice of all of it: a reference to them is one already. - PointerCoercion::Unsize if unsized_to(from, to).is_some_and(|u| super::place::byte_slice(u.to)) => { + PointerCoercion::Unsize if unsized_to(from, to).is_some_and(super::place::byte_slice) => { match to.builtin_deref(true) { Some(pointee) if super::place::byte_slice(pointee) => { let value = self.operand(op, span, out); @@ -665,28 +664,12 @@ pub(super) fn context_like<'tcx>(fx: &Fx<'_, '_, '_, 'tcx>, ty: Ty<'tcx>) -> boo } } -/// The part of a type that unsizing makes unsized, such as `[T]` from `[T; N]`. -struct Unsized<'tcx> { - /// What it was. - from: Ty<'tcx>, - /// What it is. - to: Ty<'tcx>, - /// Whether it is behind a reference, which doesn't own it. - borrowed: bool, -} - -/// The part of `to` that unsizing `from` makes unsized. -fn unsized_to<'tcx>(from: Ty<'tcx>, to: Ty<'tcx>) -> Option> { +/// The part of `to` that unsizing `from` makes unsized, such as `[T]` from `[T; N]`. +fn unsized_to<'tcx>(from: Ty<'tcx>, to: Ty<'tcx>) -> Option> { match (from.kind(), to.kind()) { _ if from == to => None, - (ty::Array(..), ty::Slice(_)) | (_, ty::Dynamic(..)) => Some(Unsized { - from, - to, - borrowed: false, - }), - (ty::Ref(_, a, _) | ty::RawPtr(a, _), ty::Ref(_, b, _) | ty::RawPtr(b, _)) => { - unsized_to(*a, *b).map(|u| Unsized { borrowed: true, ..u }) - } + (ty::Array(..), ty::Slice(_)) | (_, ty::Dynamic(..)) => Some(to), + (ty::Ref(_, a, _) | ty::RawPtr(a, _), ty::Ref(_, b, _) | ty::RawPtr(b, _)) => unsized_to(*a, *b), (ty::Adt(a, a_args), ty::Adt(b, b_args)) if a.did() == b.did() => { a_args.types().zip(b_args.types()).find_map(|(a, b)| unsized_to(a, b)) } diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index 2f93acd9f..21bde2cf2 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -38,21 +38,57 @@ impl<'tcx> Translator<'_, 'tcx> { } impl<'tcx> Body<'_, '_, 'tcx> { - /// `value`, a `from` that is a future, as the `rt.Future` a `dyn Future` is: itself if - /// it is one already, and else an `rt.DynFuture` over its `Future` impl, which drops it - /// with itself unless `borrowed`. - pub fn dyn_future(&mut self, from: Ty<'tcx>, value: Expr, borrowed: bool, span: Span) -> Expr { + /// `value`, a `from` coerced to `to`, which points at a `dyn Future` through + /// references, boxes, and pins, whose JS value is what they point at. + pub fn dyn_future(&mut self, from: Ty<'tcx>, to: Ty<'tcx>, value: Expr, span: Span) -> Expr { let tcx = self.t.tcx; - match from.kind() { - ty::Dynamic(..) | ty::Coroutine(..) => return value, + let (mut pointee, mut target, mut borrowed) = (from, to, false); + while !matches!(target.kind(), ty::Dynamic(..)) { + (pointee, target) = match (pointee.kind(), target.kind()) { + (ty::Ref(_, a, _), ty::Ref(_, b, _)) => { + borrowed = true; + (*a, *b) + } + (ty::Adt(a, a_args), ty::Adt(b, b_args)) + if a.did() == b.did() && matches!(Std::of(tcx, a.did()), Some(Std::Box | Std::Pin)) => + { + (a_args.type_at(0), b_args.type_at(0)) + } + // Another pointer, such as an `Arc`, is a value of its own around the future. + _ => return self.err(span, format!("a coercion to `{to}`")), + }; + } + // What drops `to` drops the future, unless it was borrowed. + let dropped = self.t.drops(to); + self.future_object(pointee, value, borrowed, dropped, span) + } + + /// `value`, a `from` that is a future, as an `rt.Future`: itself if it is one already, + /// and else an `rt.DynFuture` over its `Future` impl, which drops it with itself unless + /// `borrowed`. A borrowed one that is `dropped` must not drop what it borrows. + fn future_object(&mut self, from: Ty<'tcx>, value: Expr, borrowed: bool, dropped: bool, span: Span) -> Expr { + let tcx = self.t.tcx; + let object = match from.kind() { + ty::Dynamic(..) | ty::Coroutine(..) => true, // What a reference or a box points at, which its JS value is. - ty::Ref(_, inner, _) => return self.dyn_future(*inner, value, true, span), + ty::Ref(_, inner, _) => return self.future_object(*inner, value, true, dropped, span), ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { - Some(Std::PollFn | Std::Pending) => return value, - Some(Std::Box | Std::Pin) => return self.dyn_future(args.type_at(0), value, borrowed, span), - _ => {} + Some(Std::PollFn | Std::Pending) => true, + Some(Std::Box | Std::Pin) => { + return self.future_object(args.type_at(0), value, borrowed, dropped, span); + } + _ => false, }, - _ => {} + _ => false, + }; + if object { + return match borrowed && dropped { + true => Expr::New( + Box::new(Expr::Rt("DynFuture".into())), + vec![value, Expr::Rt("futurePoll".into())], + ), + false => value, + }; } // What `Future::poll` takes would be an `rt.Place`, which the box doesn't have. if self.t.needs_place(from) {