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 41283a87d..943ada3dc 100644 --- a/ts/README.md +++ b/ts/README.md @@ -94,6 +94,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 @@ -444,8 +445,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: formatting and parsing an `f64`, and `f64::clamp`, whose panic formats them ([float formatting](/quest/m2/ts-model/floats.md)), `f32` ([`f32`](/quest/m3/ts-f32.md)), statics, async closures, a closure that owns a value 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 8903d63da..c810551bb 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_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_closure1_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..0b8fc4832 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_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 { recvFuture } from "./kio.ts"; -import type * as Consumer from "./kio.Consumer.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"; import * as Log from "./log.Log.ts"; import * as Guard from "./model.Guard.ts"; @@ -381,4 +384,608 @@ 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, 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 + * `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; + #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$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; + this.#guard = guard; + } + + [Symbol.dispose](): void { + let unwind: number = 0; + try { + 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); + } + unwind = 54; + rt.drop(this.#guard); + if (this.#saved$2) { + unwind = 0; + rt.drop(this.#rx); + } + this.#saved$2 = false; + } catch (e) { + 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 (this.#saved) { + rt.drop(this.#lend); + } + } + this.#saved = false; + rt.drop(this.#log); + } + } + rt.drop(this.#guard); + } + if (this.#saved$2) { + rt.drop(this.#rx); + } + this.#saved$2 = false; + } + throw e; + } + } + + poll(_2: rt.Context): rt.Poll { + let block!: Guard.Guard; + let waiting!: Guard.Guard; + let ready!: Guard.Guard; + let _83!: Guard.Guard; + let _89!: Guard.Guard; + let next!: Consumer.Consumer; + let queue!: rt.Future[]; + let _106!: rt.Future; + let _109!: rt.Future; + let unwind: number = 0; + try { + 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 = 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; + waiting = _89; + this.#saved$5 = true; + ready = _95; + next = Consumer.clone$Clone(this.#rx); + 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; + 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(captured2); + dropped = 1; + rt.drop(captured3); + } catch (e) { + if (dropped < 1) { + rt.drop(captured3); + } + throw e; + } + })); + 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(captured4); + }), rt.drop); + 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(captured5); + })); + unwind = 93; + this.#pinned = _124; + const last: Pending.Pending<(a0: Waiter.Waiter) => rt.Poll> = this.#pinned; + 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 < 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 (!((captured6.length === 0))) { + return rt.Pending; + } + 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(captured6); + }), rt.drop) }); + } else { + this.#state = 5; + return rt.Pending; + } + } + 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 = 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 = 121; + rt.drop(this.#guard); + this.#saved$2 = false; + this.#state = 1; + return total; + } + this.#state = 6; + return rt.Pending; + } catch (e) { + 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; + } + rt.drop(_106); + } + break b10; + } + rt.drop(this.#pinned); + } + if (this.#saved$3) { + rt.dropAll(queue); + } + } + this.#saved$3 = false; + if (this.#saved$4) { + rt.drop(next); + } + } + this.#saved$4 = false; + if (this.#saved$5) { + rt.drop(ready); + } + 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; + } + if (this.#saved) { + rt.drop(this.#lend); + } + } + this.#saved = false; + } + rt.drop(this.#log); + } + rt.drop(this.#guard); + } + if (this.#saved$2) { + rt.drop(this.#rx); + } + this.#saved$2 = 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..9ac1bae2f 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_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_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)); +} + 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..7d3bb89c4 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_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 { + 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_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 { + 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..33b9b4163 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,99 @@ 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, 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 +/// `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 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()), + 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 46ec6efca..5b452c872 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -127,6 +127,12 @@ fn steps() -> Vec<(&'static str, Step)> { exec.spawn(futures::helpers(channels[c].consumer(), guard)); } }), + ("boxed", |log, exec, channels, arg| { + if let Some(c) = pick(channels.len(), arg) { + 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..3c9fbc652 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -245,6 +245,35 @@ 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.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/census.rs b/ts/src/census.rs index 8f00d6b4d..330384cfb 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -166,6 +166,7 @@ const VERBATIM: &[&str] = &[ "break", "collect", "copy_nonoverlapping", + "dyn Future", "f64", "f64::mul_add", "flatten", 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 df389e4fb..c48bb16ec 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -522,7 +522,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") @@ -803,7 +803,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 e2cd7f978..f928d9a59 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -205,6 +205,13 @@ 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 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(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(super::place::byte_slice) => { @@ -578,11 +585,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) } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 6199bde5a..55d3dd480 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -975,6 +975,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, } @@ -1067,6 +1068,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 @@ -1521,6 +1525,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..21bde2cf2 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,78 @@ impl<'tcx> Translator<'_, 'tcx> { } } +impl<'tcx> Body<'_, '_, 'tcx> { + /// `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; + 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.future_object(*inner, value, true, dropped, span), + ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { + 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) { + 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 +117,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 +190,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 b18e5d6b6..50edc9308 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. */ @@ -275,6 +278,13 @@ export const steps: [string, (r: Run, arg: number) => void][] = [ if (c !== undefined) r.exec.spawn(r.f.futures.helpers(r.f.Channel.consumer(r.channels[c]), guard(r))); }, ], + [ + "boxed", + (r, arg) => { + const c = pick(r.channels.length, arg); + if (c !== undefined) r.exec.spawn(r.f.futures.boxed(r.f.Channel.consumer(r.channels[c]), guard(r))); + }, + ], ]; /** @@ -349,6 +359,12 @@ export const cases: Uint8Array[] = [ script(["open", 0], ["helpers", 0], ["run", 0], ["send", 5], ["run", 0], ["send", 77], ["run", 0]), script(["open", 0], ["helpers", 0], ["helpers", 1], ["run", 0], ["send", 4], ["step", 0], ["drop", 1], ["drop", 0]), script(["open", 0], ["helpers", 0], ["run", 0], ["send", 99], ["run", 0], ["poll", 0]), + // Boxed futures: a boxed `recv` and a boxed borrow 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. + script(["open", 0], ["boxed", 0], ["run", 0], ["send", 5], ["run", 0], ["send", 6], ["step", 0], ["send", 7], ["run", 0]), + script(["open", 0], ["boxed", 0], ["boxed", 1], ["run", 0], ["send", 4], ["run", 0], ["drop", 1], ["send", 5], ["step", 0], ["drop", 0]), + script(["open", 0], ["boxed", 0], ["run", 0], ["send", 5], ["run", 0], ["send", 99], ["run", 0], ["poll", 0], ["drop", 0]), // Each scenario of values std holds that drop, panicking at each point or none. ...Array.from({ length: 253 }, (_, arg) => script(["drops", arg])), // Each of a `Vec`'s edits, its and a tuple's `clone`, and `Ord`'s defaults, panicking at each point or none.