diff --git a/quest/m2/ts-async.md b/quest/m2/ts-async.md index 2906b5b23..d337a4729 100644 --- a/quest/m2/ts-async.md +++ b/quest/m2/ts-async.md @@ -18,21 +18,17 @@ A handoff through 1, 4, and 16 async functions measured 1.5-2.7x faster than #16 generators in Node, 1.8-5.5x in Bun, and 1.4-3.5x in Chrome, and past depth 1 faster than moq's hand-written promises. `rt.spawn` stays. -What moq-net still needs, by its census from MIR at the pinned revision: +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: -- `Poll`'s helpers (about 340 calls: `is_ready`, `is_pending`, `map`, `map_ok`, - `map_err`), `pin!` (50 with `PinMacroHelper`), `poll_fn` (31), `future::pending` - (5), and `Box::pin` (29, a boxed future that binds to hand-written TS at the - boundary, per the [model](/quest/m2/ts-model/README.md)). +- `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. - 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). - -The model itself (its census of 2026-10-27) needs only `Poll`'s helpers and -`Waker::from(Arc)`, 61 refusals; `pin!`, `poll_fn`, `Box::pin`, and async closures are -in moq-net's session, lite, and ietf layers. - 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/ts/README.md b/ts/README.md index 30f8d8dad..4163ab7d9 100644 --- a/ts/README.md +++ b/ts/README.md @@ -62,7 +62,7 @@ from. `rt.ts` beside them is the runtime: what std does that JS does not, with iterators in `rt/iter.ts`, `str`'s searches in `rt/str.ts`, collections in `rt/collections.ts`, ownership and async in `rt/task.ts`, and `Duration` in `rt/time.ts`. What translates from std's own MIR, -`Option`'s and `Result`'s combinators, goes in a module under its crate's name, as +`Option`'s, `Result`'s, and `Poll`'s methods, goes in a module under its crate's name, as `core/option.ts` holds `map$Option_u64_u64_rescale_closure0`. | Rust | TypeScript | @@ -92,6 +92,7 @@ in `rt/str.ts`, collections in `rt/collections.ts`, ownership and async in | `Arc`, `Weak`, `Mutex` | `rt.Arc`, counted; `rt.Weak`; `rt.Mutex`, its own guard | | `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` | `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 @@ -204,7 +205,7 @@ elaboration put it. A panic unwinds: a function with cleanup to run catches `rt. runs the cleanup blocks MIR has under `-C panic=unwind`, and throws it on, so what a panic drops matches native Rust's. A value without `[Symbol.dispose]` of its own, such as an enum or a tuple, drops through glue lowered from rustc's `drop_in_place` shim, a -function of its type's own (`drop$Held`). `Option`'s and `Result`'s combinators lower +function of its type's own (`drop$Held`). `Option`'s, `Result`'s, and `Poll`'s methods lower from core's MIR, so they drop what core's do, where core's do. The runtime functions for std's collections, `Arc`, and the std functions that may discard an operand (`then_some`, a map's `insert`) take what drops each value they may drop, and drop it @@ -221,7 +222,9 @@ own (`sumFuture`), the state machine MIR's coroutine transform makes. Its fields arguments and the locals held across an `.await`, and its `poll` resumes at the state it stopped in. A poll after the future returned panics, and dropping it cancels it, dropping what its state holds. `rt.spawn(future)` runs one as a promise, polling woken tasks in a batch from a -microtask and yielding to a macrotask after 128 polls. +microtask and yielding to a macrotask after 128 polls. `Waker::from(arc)`, of an `Arc` of +the crate's `Wake` impl, is an `rt.ArcWaker`, which holds a count of the `Arc` and wakes +through the impl, and `Waker::noop()` is `rt.NOOP_WAKER`. A file's items follow the Rust source, whatever order translation reaches them in, so adding a root moves nothing it does not reach. @@ -499,7 +502,8 @@ built natively for wasm32 and run beside its translation on the same inputs by byte array overwritten whole through a type parameter, or, under its features, by std called directly or through a pointer a generic function calls. - `task` trims moq's kio to a channel of `Arc`ed state, waiters, and wakers, under async - functions, beside values that drop inside std's types. Its caller is hand-written TS (`tests/task.ts`): a FIFO executor that runs a + functions and std's future helpers, with wakers of the crate's `Wake` impls, beside + values that drop inside std's types. Its caller is hand-written TS (`tests/task.ts`): a FIFO executor that runs a script of spawns, sends, polls, and drops, and logs every poll, wake, and drop, as the fixture's native executor does. The logs must match byte for byte. `tests/unwind.ts` also runs the scripts natively on the host (`examples/unwind.rs`), where a panic diff --git a/ts/fixtures/task/expected/core/option.ts b/ts/fixtures/task/expected/core/option.ts index 1398aa065..642357007 100644 --- a/ts/fixtures/task/expected/core/option.ts +++ b/ts/fixtures/task/expected/core/option.ts @@ -165,6 +165,13 @@ export function okOr$Option_Guard_Guard(self: Guard.Guard | undefined, err: Guar return _0; } +export function okOr$Option_u64_u64(self: rt.u64 | undefined, err: rt.u64): rt.Result { + if (self === undefined) { + return rt.Err(err); + } + return rt.Ok(self); +} + export function filter$Option_Guard_options_closure4(self: Guard.Guard | undefined, predicate: (a0: Guard.Guard) => boolean): Guard.Guard | undefined { let x!: Guard.Guard; let unwind: number = 0; diff --git a/ts/fixtures/task/expected/core/task/poll.ts b/ts/fixtures/task/expected/core/task/poll.ts new file mode 100644 index 000000000..8903d63da --- /dev/null +++ b/ts/fixtures/task/expected/core/task/poll.ts @@ -0,0 +1,54 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "../../rt.ts"; + +export function map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0(self: rt.Poll, f: (a0: rt.u64 | undefined) => rt.Result): 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; + } + return false; +} + +export function isReady$Poll_u64(self: rt.Poll): boolean { + if (self !== rt.Pending) { + return true; + } + return false; +} + +export function isPending$Poll_Option_u64(self: rt.Poll): boolean { + return !isReady$Poll_Option_u64(self); +} + +export function isPending$Poll_u64(self: rt.Poll): boolean { + return !isReady$Poll_u64(self); +} + +export function mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1(self: rt.Poll>, f: (a0: rt.u64) => rt.u64): rt.Poll> { + if (self !== rt.Pending) { + if (self.ok) { + return rt.Ok(f(self.value)); + } + return self; + } + return rt.Pending; +} + +export function mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2(self: rt.Poll>, f: (a0: rt.u64) => rt.u64): rt.Poll> { + if (self !== rt.Pending) { + if (self.ok) { + return self; + } + return rt.Err(f(self.error)); + } + return rt.Pending; +} + +//# sourceMappingURL=poll.ts.map diff --git a/ts/fixtures/task/expected/drops/closures.ts b/ts/fixtures/task/expected/drops/closures.ts index babab9f37..7d7d6d794 100644 --- a/ts/fixtures/task/expected/drops/closures.ts +++ b/ts/fixtures/task/expected/drops/closures.ts @@ -255,7 +255,7 @@ export function scoped(log: Log.Log, id: rt.u32, at: rt.u8): void { const held: Guard.Guard[] = []; unwind = 77; _179 = true; - const captured13 = held; + let captured13 = held; push = rt.closure((g2: Guard.Guard): rt.usize => { captured13.push(g2); return captured13.length; diff --git a/ts/fixtures/task/expected/futures.Blast.ts b/ts/fixtures/task/expected/futures.Blast.ts new file mode 100644 index 000000000..c3e455e1a --- /dev/null +++ b/ts/fixtures/task/expected/futures.Blast.ts @@ -0,0 +1,39 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Guard from "./model.Guard.ts"; + +/** Panics as its last waker drops, after which its guard drops. */ +export class Blast { + _0: Guard.Guard; + + constructor(_0: Guard.Guard) { + this._0 = _0; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + drop$Drop(this); + dropped = 1; + rt.drop(this._0); + } catch (e) { + if (dropped < 1) { + rt.drop(this._0); + } + throw e; + } + } +} + +export function wake$Wake(self: rt.Arc): void { + rt.drop(self); +} + +export function drop$Drop(self: Blast): void { + const part = Guard.id(self._0); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; + rt.panicFmt(["g", args2[0], " blew"]); +} + +//# sourceMappingURL=futures.Blast.ts.map diff --git a/ts/fixtures/task/expected/futures.Fused.ts b/ts/fixtures/task/expected/futures.Fused.ts new file mode 100644 index 000000000..7afddc69f --- /dev/null +++ b/ts/fixtures/task/expected/futures.Fused.ts @@ -0,0 +1,34 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Guard from "./model.Guard.ts"; + +/** + * A waker, then a guard: glue that drops the waker first must still drop the guard when + * the waker's drop panics. + */ +export class Fused { + waker: rt.Waker; + after: Guard.Guard; + + constructor(fields: { waker: rt.Waker; after: Guard.Guard }) { + this.waker = fields.waker; + this.after = fields.after; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + rt.drop(this.waker); + dropped = 1; + rt.drop(this.after); + } catch (e) { + if (dropped < 1) { + rt.drop(this.after); + } + throw e; + } + } +} + +//# sourceMappingURL=futures.Fused.ts.map diff --git a/ts/fixtures/task/expected/futures.Plain.ts b/ts/fixtures/task/expected/futures.Plain.ts new file mode 100644 index 000000000..aa7316d3e --- /dev/null +++ b/ts/fixtures/task/expected/futures.Plain.ts @@ -0,0 +1,37 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import type * as Relay from "./futures.Relay.ts"; +import * as Guard from "./model.Guard.ts"; + +/** A relay without its own `wake_by_ref`. */ +export class Plain { + _0: Relay.Relay; + + constructor(_0: Relay.Relay) { + this._0 = _0; + } + + [Symbol.dispose](): void { + rt.drop(this._0); + } +} + +export function wake$Wake(self: rt.Arc): void { + let unwind: number = 0; + try { + unwind = 7; + Guard.note(self.value._0.guard, "plain wake"); + self.value._0.task.wakeByRef(); + unwind = 0; + rt.drop(self); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(self); + throw e; + } +} + +//# sourceMappingURL=futures.Plain.ts.map diff --git a/ts/fixtures/task/expected/futures.Relay.ts b/ts/fixtures/task/expected/futures.Relay.ts new file mode 100644 index 000000000..f059444ce --- /dev/null +++ b/ts/fixtures/task/expected/futures.Relay.ts @@ -0,0 +1,53 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import * as Guard from "./model.Guard.ts"; + +/** Wakes `task`, logging through `guard`, which logs the relay's drop. */ +export class Relay { + task: rt.Waker; + guard: Guard.Guard; + + constructor(fields: { task: rt.Waker; guard: Guard.Guard }) { + this.task = fields.task; + this.guard = fields.guard; + } + + [Symbol.dispose](): void { + let dropped: number = 0; + try { + rt.drop(this.task); + dropped = 1; + rt.drop(this.guard); + } catch (e) { + if (dropped < 1) { + rt.drop(this.guard); + } + throw e; + } + } +} + +export function wake$Wake(self: rt.Arc): void { + let unwind: number = 0; + try { + unwind = 7; + Guard.note(self.value.guard, "relay wake"); + self.value.task.wakeByRef(); + unwind = 0; + rt.drop(self); + } catch (e) { + if (unwind === 0) { + throw e; + } + rt.drop(self); + throw e; + } +} + +export function wakeByRef$Wake(self: rt.Arc): void { + Guard.note(self.value.guard, "relay wake_by_ref"); + self.value.task.wakeByRef(); +} + +//# sourceMappingURL=futures.Relay.ts.map diff --git a/ts/fixtures/task/expected/futures.ts b/ts/fixtures/task/expected/futures.ts new file mode 100644 index 000000000..9b872495e --- /dev/null +++ b/ts/fixtures/task/expected/futures.ts @@ -0,0 +1,384 @@ +// 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 * as Blast from "./futures.Blast.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 * as Log from "./log.Log.ts"; +import * as Guard from "./model.Guard.ts"; + +/** + * Every value until the channel closes, summed through std's helpers: a pinned `recv` + * polled by hand from a `poll_fn` that owns a guard, which a cancel drops with the + * `poll_fn`; a pinned `future::pending` polled first with `Waker::noop`, which never + * wakes; and `Poll`'s methods on what each poll returns. `recv` wakes the task through + * a relay, a waker the `poll_fn` makes on its first poll from an `Arc` of a `Wake` impl, + * which an even value also wakes by value, and which logs its own drop. It stops at a + * value of 77, and panics on 99 inside the `poll_fn`. First, a `poll_fn` of a borrowed + * function drops in an `Arc` without dropping the function, and for one guard in eight, + * a waker whose last drop panics goes before a guard that unwinding still drops. + */ +export function helpers(rx: Consumer.Consumer, guard: Guard.Guard): rt.Future { + return new helpersFuture(rx, guard); +} + +export class helpersFuture { + #state: number = 0; + #rx: Consumer.Consumer; + #guard: Guard.Guard; + #lend!: (a0: rt.Context) => rt.Poll; + #total!: rt.u64; + #pinned!: rt.Future; + #pinned$2!: rt.Future; + #awaitee!: rt.Future>; + #saved!: boolean; + #saved$2!: 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 = 27; + rt.drop(this.#rx); + unwind = 0; + rt.drop(this.#guard); + } else if (this.#state === 3) { + unwind = 15; + rt.drop(this.#awaitee); + unwind = 18; + rt.drop(this.#pinned$2); + this.#saved = false; + this.#saved$2 = false; + unwind = 23; + rt.drop(this.#guard); + unwind = 0; + rt.drop(this.#rx); + } + } catch (e) { + b0: { + b1: { + if (unwind === 0) { + throw e; + } + if (unwind === 15) { + rt.drop(this.#pinned$2); + } else if (unwind !== 18) { + if (unwind === 23) { + break b1; + } + rt.drop(this.#guard); + break b0; + } + this.#saved = false; + this.#saved$2 = false; + rt.drop(this.#guard); + } + rt.drop(this.#rx); + } + throw e; + } + } + + poll(_2: rt.Context): rt.Poll { + let _36!: rt.Waker; + let owned!: Guard.Guard; + let _77!: rt.u64; + let unwind: number = 0; + try { + let bb0: number = 0; + while (true) { + switch (bb0) { + case 0: + if (this.#state === 0) { + unwind = 64; + this.#saved$2 = false; + this.#saved = false; + const lent: Guard.Guard = Guard.new(rt.u32Add(Guard.id(this.#guard), 900), Log.clone$Clone(Guard.log(this.#guard))); + unwind = 68; + this.#saved$2 = true; + const captured = lent; + this.#lend = rt.closure((_23: rt.Context): rt.Poll => { + return Guard.id(captured); + }, (): void => { + rt.drop(captured); + }); + rt.drop(new rt.Arc(new rt.PollFn(this.#lend))); + Guard.note(this.#guard, "lent"); + this.#saved$2 = false; + rt.drop(this.#lend); + if (!(rt.u32Rem(Guard.id(this.#guard), 8) === 7)) { + bb0 = 26; + continue; + } + _36 = new rt.ArcWaker(new rt.Arc(new Blast.Blast(Guard.new(rt.u32Add(Guard.id(this.#guard), 700), Log.clone$Clone(Guard.log(this.#guard))))), Blast.wake$Wake, (arc: rt.Arc) => rt.drop(arc)); + unwind = 62; + const _42: rt.u32 = rt.u32Add(Guard.id(this.#guard), 800); + unwind = 61; + const _38: Guard.Guard = Guard.new(_42, Log.clone$Clone(Guard.log(this.#guard))); + unwind = 68; + rt.drop(new Fused.Fused({ waker: _36, after: _38 })); + bb0 = 26; + continue; + } + if (this.#state === 1) { + rt.asyncFnResumed(); + } else if (this.#state === 2) { + rt.asyncFnResumedPanic(); + } else { + bb0 = 39; + continue; + } + case 26: + this.#total = 0; + bb0 = 27; + continue; + case 27: + unwind = 60; + owned = Guard.new(rt.u32Add(Guard.id(this.#guard), 500), Log.clone$Clone(Guard.log(this.#guard))); + unwind = 59; + this.#saved = true; + this.#pinned = rt.NEVER; + const never: rt.Future = this.#pinned; + const _58: rt.Future = new recvFuture(this.#rx); + unwind = 58; + this.#pinned$2 = _58; + const next: rt.Future = this.#pinned$2; + this.#saved = false; + let captured2 = never; + let captured3 = undefined as rt.Waker | undefined; + const captured4 = owned; + let captured5 = next; + const captured6 = this.#total; + this.#awaitee = new rt.PollFn(rt.closure((cx: rt.Context): rt.Poll> => { + let _152!: Log.Log; + let _81!: boolean; + let unwind2: number = 0; + try { + _81 = false; + const waiting: rt.Poll = captured2.poll(rt.NOOP_WAKER); + if (captured3 === undefined) { + const _132: rt.Waker = cx; + const _16: Log.Log = Guard.log(captured4); + _81 = true; + _152 = Log.clone$Clone(_16); + unwind2 = 51; + const _18: rt.u32 = rt.u32Add(Guard.id(captured4), 100); + _81 = false; + const _122: rt.Waker = relayed(_132, _152, _18); + unwind2 = 0; + _81 = false; + const _11: rt.Waker | undefined = _122; + rt.drop(captured3); + captured3 = _11; + } + const relay2: rt.Waker = rt.optionUnwrap(captured3); + const polled: rt.Poll = captured5.poll(relay2); + const _392: boolean = isPending$Poll_u64(waiting); + const _422: boolean = isReady$Poll_Option_u64(polled); + const _452: boolean = isPending$Poll_Option_u64(polled); + const args2: rt.Fmt[] = [(f: rt.Formatter) => rt.fmtBool(_392, f), (f: rt.Formatter) => rt.fmtBool(_422, f), (f: rt.Formatter) => rt.fmtBool(_452, f)]; + Guard.note(captured4, rt.fmtFormat(["pending ", args2[0], " ready ", args2[1], " pending ", args2[2]])); + if (polled !== rt.Pending) { + if (polled !== undefined) { + if (polled === 99) { + const part = Guard.id(captured4); + const args4: rt.Fmt[] = [(f: rt.Formatter) => rt.u32Display(part, f)]; + rt.panicFmt(["g", args4[0], " poisoned"]); + } else if (rt.u64Rem(polled, 2) === 0) { + relay2.clone().wake(); + } + } + } + return mapErr$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure2(mapOk$Poll_Result_u64_u64_u64_helpers_closure0_closure1_closure1(map$Poll_Option_u64_Result_u64_u64_helpers_closure0_closure1_closure0(polled, (value3: rt.u64 | undefined): rt.Result => { + return okOr$Option_u64_u64(value3, captured6); + }), (value4: rt.u64): rt.u64 => { + return rt.u64Mul(value4, 2); + }), (total: rt.u64): rt.u64 => { + return rt.u64Add(total, 1); + }); + } catch (e2) { + if (unwind2 === 0) { + throw e2; + } + if (_81) { + rt.drop(_152); + } + throw e2; + } + }, (): void => { + let dropped: number = 0; + try { + rt.drop(captured3); + dropped = 1; + rt.drop(captured4); + } catch (e) { + if (dropped < 1) { + rt.drop(captured4); + } + throw e; + } + }), rt.drop); + bb0 = 39; + continue; + case 39: + unwind = 57; + const _65: rt.Poll> = this.#awaitee.poll(_2); + if (_65 !== rt.Pending) { + unwind = 58; + const read: rt.Result = _65; + rt.drop(this.#awaitee); + if (read.ok) { + if (read.value === 154) { + _77 = this.#total; + bb0 = 52; + continue; + } + const _75: rt.u64 = rt.u64Add(this.#total, read.value); + unwind = 59; + this.#total = _75; + rt.drop(this.#pinned$2); + this.#saved = false; + bb0 = 27; + continue; + } + _77 = read.error; + bb0 = 52; + continue; + } + this.#state = 3; + return rt.Pending; + case 52: + unwind = 59; + rt.drop(this.#pinned$2); + unwind = 65; + this.#saved = false; + this.#saved$2 = false; + rt.drop(this.#guard); + unwind = 69; + rt.drop(this.#rx); + this.#state = 1; + return _77; + } + } + } catch (e) { + b1: { + b2: { + b3: { + b4: { + b5: { + b6: { + if (unwind === 0) { + throw e; + } + if (unwind === 57) { + rt.drop(this.#awaitee); + } else if (unwind !== 58) { + if (unwind === 59) { + break b6; + } + if (unwind === 60) { + break b5; + } + if (unwind === 61) { + rt.drop(_36); + break b4; + } + if (unwind === 62) { + rt.drop(_36); + break b4; + } + if (unwind === 64) { + break b3; + } + if (unwind === 65) { + break b2; + } + if (unwind === 68) { + break b4; + } + break b1; + } + rt.drop(this.#pinned$2); + } + if (this.#saved) { + rt.drop(owned); + } + } + this.#saved = false; + } + if (this.#saved$2) { + rt.drop(this.#lend); + } + this.#saved$2 = false; + } + rt.drop(this.#guard); + } + rt.drop(this.#rx); + } + this.#state = 2; + throw e; + } + } +} + +/** + * A waker relaying to `task`, through a `Wake` impl with its own `wake_by_ref` for an + * even `id`, and `Wake`'s default otherwise. + */ +export function relayed(task: rt.Waker, log: Log.Log, id: rt.u32): rt.Waker { + let _0!: rt.Waker; + let relay!: Relay.Relay; + let _5!: rt.Waker; + let _15!: boolean; + let _16!: boolean; + let unwind: number = 0; + try { + unwind = 15; + _16 = false; + _15 = false; + _16 = true; + _5 = task.clone(); + unwind = 10; + _16 = false; + const _6: Guard.Guard = Guard.new(id, log); + unwind = 13; + _15 = true; + relay = new Relay.Relay({ task: _5, guard: _6 }); + if (rt.u32Rem(id, 2) === 0) { + _15 = false; + _0 = new rt.ArcWaker(new rt.Arc(relay), Relay.wake$Wake, (arc2: rt.Arc) => rt.drop(arc2), Relay.wakeByRef$Wake); + } else { + _15 = false; + _0 = new rt.ArcWaker(new rt.Arc(new Plain.Plain(relay)), Plain.wake$Wake, (arc: rt.Arc) => rt.drop(arc)); + } + _15 = false; + return _0; + } catch (e) { + if (unwind === 0) { + throw e; + } + if (unwind === 10) { + rt.drop(_5); + } else if (unwind === 13) { + if (_15) { + rt.drop(relay); + } + } + if (_16) { + rt.drop(log); + } + throw e; + } +} + +//# sourceMappingURL=futures.ts.map diff --git a/ts/fixtures/task/expected/kio.Waiter.ts b/ts/fixtures/task/expected/kio.Waiter.ts index c69a77ef6..3e1eee364 100644 --- a/ts/fixtures/task/expected/kio.Waiter.ts +++ b/ts/fixtures/task/expected/kio.Waiter.ts @@ -14,8 +14,17 @@ export class Waiter { } [Symbol.dispose](): void { - rt.drop(this.waker); - rt.drop(this.shared); + let dropped: number = 0; + try { + rt.drop(this.waker); + dropped = 1; + rt.drop(this.shared); + } catch (e) { + if (dropped < 1) { + rt.drop(this.shared); + } + throw e; + } } } diff --git a/ts/fixtures/task/src/futures.rs b/ts/fixtures/task/src/futures.rs new file mode 100644 index 000000000..f8c07e6c6 --- /dev/null +++ b/ts/fixtures/task/src/futures.rs @@ -0,0 +1,132 @@ +//! std's future helpers over a channel: `pin!`, `poll_fn`, `future::pending`, `Poll`'s +//! methods, and wakers from `Arc` and `Waker::noop`. + +use std::future::{self, Future}; +use std::pin::pin; +use std::sync::Arc; +use std::task::{Context, Poll, Wake, Waker}; + +use crate::kio::Consumer; +use crate::log::Log; +use crate::model::Guard; + +/// Every value until the channel closes, summed through std's helpers: a pinned `recv` +/// polled by hand from a `poll_fn` that owns a guard, which a cancel drops with the +/// `poll_fn`; a pinned `future::pending` polled first with `Waker::noop`, which never +/// wakes; and `Poll`'s methods on what each poll returns. `recv` wakes the task through +/// a relay, a waker the `poll_fn` makes on its first poll from an `Arc` of a `Wake` impl, +/// which an even value also wakes by value, and which logs its own drop. It stops at a +/// value of 77, and panics on 99 inside the `poll_fn`. First, a `poll_fn` of a borrowed +/// function drops in an `Arc` without dropping the function, and for one guard in eight, +/// a waker whose last drop panics goes before a guard that unwinding still drops. +pub async fn helpers(mut rx: Consumer, guard: Guard) -> u64 { + let lent = Guard::new(guard.id() + 900, guard.log().clone()); + let mut lend = move |_: &mut Context<'_>| Poll::Ready(lent.id()); + drop(Arc::new(future::poll_fn(&mut lend))); + guard.note("lent"); + drop(lend); + if guard.id() % 8 == 7 { + let blast = Blast(Guard::new(guard.id() + 700, guard.log().clone())); + drop(Fused { + waker: Waker::from(Arc::new(blast)), + after: Guard::new(guard.id() + 800, guard.log().clone()), + }); + } + let mut total = 0; + loop { + let owned = Guard::new(guard.id() + 500, guard.log().clone()); + let mut never = pin!(future::pending::()); + let mut next = pin!(rx.recv()); + let mut relay: Option = None; + let read = future::poll_fn(move |cx| { + let waiting = never.as_mut().poll(&mut Context::from_waker(Waker::noop())); + if relay.is_none() { + relay = Some(relayed(cx.waker(), owned.log().clone(), owned.id() + 100)); + } + let relay = relay.as_ref().unwrap(); + let polled = next.as_mut().poll(&mut Context::from_waker(relay)); + owned.note(&format!( + "pending {} ready {} pending {}", + waiting.is_pending(), + polled.is_ready(), + polled.is_pending() + )); + match polled { + Poll::Ready(Some(99)) => panic!("g{} poisoned", owned.id()), + Poll::Ready(Some(value)) if value % 2 == 0 => relay.clone().wake(), + _ => {} + } + polled + .map(|value| value.ok_or(total)) + .map_ok(|value| value * 2) + .map_err(|total| total + 1) + }) + .await; + match read { + Ok(154) => return total, + Ok(value) => total += value, + Err(end) => return end, + } + } +} + +/// A waker relaying to `task`, through a `Wake` impl with its own `wake_by_ref` for an +/// even `id`, and `Wake`'s default otherwise. +fn relayed(task: &Waker, log: Log, id: u32) -> Waker { + let relay = Relay { + task: task.clone(), + guard: Guard::new(id, log), + }; + match id % 2 { + 0 => Waker::from(Arc::new(relay)), + _ => Waker::from(Arc::new(Plain(relay))), + } +} + +/// Wakes `task`, logging through `guard`, which logs the relay's drop. +struct Relay { + task: Waker, + guard: Guard, +} + +impl Wake for Relay { + fn wake(self: Arc) { + self.guard.note("relay wake"); + self.task.wake_by_ref(); + } + + fn wake_by_ref(self: &Arc) { + self.guard.note("relay wake_by_ref"); + self.task.wake_by_ref(); + } +} + +/// A relay without its own `wake_by_ref`. +struct Plain(Relay); + +impl Wake for Plain { + fn wake(self: Arc) { + self.0.guard.note("plain wake"); + self.0.task.wake_by_ref(); + } +} + +/// A waker, then a guard: glue that drops the waker first must still drop the guard when +/// the waker's drop panics. +struct Fused { + waker: Waker, + after: Guard, +} + +/// Panics as its last waker drops, after which its guard drops. +struct Blast(Guard); + +impl Wake for Blast { + fn wake(self: Arc) {} +} + +impl Drop for Blast { + fn drop(&mut self) { + panic!("g{} blew", self.0.id()); + } +} diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs index e41ca0443..0ad135688 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -10,6 +10,7 @@ use crate::drops; use crate::exec::Executor; +use crate::futures; use crate::log::Log; use crate::model::{self, Channel, Guard}; @@ -48,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 % 14 { + match op % 15 { 0 => { log.note(format!("c{} open", channels.len())); channels.push(Channel::open()); @@ -110,6 +111,12 @@ fn run_step(log: &Log, exec: &mut Executor, channels: &mut Vec, op: u8, exec.spawn(drops::held(channels[c].consumer(), guard)); } } - _ => drops::edited(log, 1000 * exec.len() as u32, arg % 8), + 13 => drops::edited(log, 1000 * exec.len() as u32, arg % 8), + _ => { + 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)); + } + } } } diff --git a/ts/fixtures/task/src/lib.rs b/ts/fixtures/task/src/lib.rs index e55165dc9..f8e3771b6 100644 --- a/ts/fixtures/task/src/lib.rs +++ b/ts/fixtures/task/src/lib.rs @@ -5,15 +5,17 @@ //! //! `kio` trims moq's kio to what its futures hinge on: a `Waiter` holding the task's //! waker behind an `Arc` that `WaiterList`s hold weakly, `wait`, and a channel whose -//! last producer closes it on drop. `model` holds the async functions. `exec` is a -//! deterministic FIFO executor that logs every poll, wake, and waker clone and drop, and -//! `harness` runs a script of executor steps through it; `tests/task.ts` runs the same -//! script on the translation with its own executor. `bench` holds the handoff `just ts -//! bench` times. None of `exec`, `harness`, and `bench` is translated. +//! last producer closes it on drop. `model` holds the async functions, and `futures` one +//! over std's future helpers. `exec` is a deterministic FIFO executor that logs every +//! poll, wake, and waker clone and drop, and `harness` runs a script of executor steps +//! through it; `tests/task.ts` runs the same script on the translation with its own +//! executor. `bench` holds the handoff `just ts bench` times. None of `exec`, `harness`, +//! and `bench` is translated. pub mod bench; pub mod drops; pub mod exec; +pub mod futures; pub mod harness; pub mod kio; pub mod log; diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 42a244cb7..d6c24317e 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -79,7 +79,7 @@ impl Guard { } /// Log `event` as this guard's. - fn note(&self, event: &str) { + pub(crate) fn note(&self, event: &str) { self.log.note(format!("g{} {event}", self.id)); } diff --git a/ts/fixtures/task/ts.toml b/ts/fixtures/task/ts.toml index bcb1d420c..6705526a5 100644 --- a/ts/fixtures/task/ts.toml +++ b/ts/fixtures/task/ts.toml @@ -1,4 +1,15 @@ package = "task-fixture" # What the hand-written harness, tests/task.ts, calls: the futures it spawns, and the # channels and log it drives them with. -roots = ["log::Log", "model::Channel", "model::Guard", "model::sum", "model::drain", "model::blocks", "drops::run", "drops::held", "drops::edited"] +roots = [ + "log::Log", + "model::Channel", + "model::Guard", + "model::sum", + "model::drain", + "model::blocks", + "drops::run", + "drops::held", + "drops::edited", + "futures::helpers", +] diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 14d520737..91f9562af 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -150,6 +150,71 @@ export interface Waker extends Disposable { willWake(other: Waker): boolean; } +/** + * `Waker::from(arc)`: a waker that holds a count of `arc` and wakes through its `Wake` + * impl, `wake` taking that count. Without a `wakeByRef` of its own, one wakes a clone, as + * `Wake`'s default does. + */ +export class ArcWaker implements Waker { + readonly #arc: Arc; + readonly #wake: (arc: Arc) => void; + readonly #drop: (arc: Arc) => void; + readonly #wakeByRef: ((arc: Arc) => void) | undefined; + + constructor( + arc: Arc, + wake: (arc: Arc) => void, + drop: (arc: Arc) => void, + wakeByRef?: (arc: Arc) => void, + ) { + this.#arc = arc; + this.#wake = wake; + this.#drop = drop; + this.#wakeByRef = wakeByRef; + } + + wake(): void { + this.#wake(this.#arc); + } + + wakeByRef(): void { + if (this.#wakeByRef === undefined) this.#wake(arcClone(this.#arc)); + else this.#wakeByRef(this.#arc); + } + + clone(): Waker { + return new ArcWaker(arcClone(this.#arc), this.#wake, this.#drop, this.#wakeByRef); + } + + willWake(other: Waker): boolean { + return other instanceof ArcWaker && other.#arc === this.#arc; + } + + [Symbol.dispose](): void { + this.#drop(this.#arc); + } +} + +/** `Waker::noop()`'s waker, which does nothing. */ +class NoopWaker implements Waker { + wake(): void {} + + wakeByRef(): void {} + + clone(): Waker { + return this; + } + + willWake(other: Waker): boolean { + return other === this; + } + + [Symbol.dispose](): void {} +} + +/** `Waker::noop()`: one waker for every call. */ +export const NOOP_WAKER: Waker = /* @__PURE__ */ new NoopWaker(); + /** `Context`, which carries only its waker. */ export type Context = Waker; @@ -158,6 +223,40 @@ export interface Future extends Disposable { poll(cx: Context): Poll; } +/** + * `future::poll_fn`'s future: each poll calls `f`, which drops with it by `drop`, if it + * drops at all: a borrowed `f` does not. + */ +export class PollFn implements Future { + readonly #f: (cx: Context) => Poll; + readonly #drop: ((f: (cx: Context) => Poll) => void) | undefined; + + constructor(f: (cx: Context) => Poll, drop?: (f: (cx: Context) => Poll) => void) { + this.#f = f; + this.#drop = drop; + } + + poll(cx: Context): Poll { + return this.#f(cx); + } + + [Symbol.dispose](): void { + this.#drop?.(this.#f); + } +} + +/** `future::Pending`: never ready, and drops as nothing. */ +class Never implements Future { + poll(): Poll { + return Pending; + } + + [Symbol.dispose](): void {} +} + +/** `future::pending()`: one future for every call, since none holds anything. */ +export const NEVER: Future = /* @__PURE__ */ new Never(); + /** An `async fn` polled again after it returned. */ export function asyncFnResumed(): never { throw new Panic("`async fn` resumed after completion"); diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 99174180e..97f311b00 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -41,6 +41,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { | Std::Mutex | Std::Poll | Std::Pin + | Std::PollFn | Std::HashMap | Std::HashSet | Std::BTreeMap @@ -116,7 +117,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { // Its binding's `[Symbol.dispose]`. ty::Adt(adt, _) if self.bound_drops(adt.did()).is_some() => true, ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { - Some(Std::Waker) => true, + // Each drops by what it was given. + Some(Std::Waker | Std::PollFn) => true, Some(Std::Arc | Std::Mutex | Std::Option | Std::Box | Std::Pin | Std::Reverse) => { self.disposable(args.type_at(0), span) } @@ -164,7 +166,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { match ty.kind() { ty::Adt(adt, _) if let Some(drops) = self.bound_drops(adt.did()) => drops, ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { - Some(Std::Waker) => false, + // One from an `Arc` runs the crate's `Drop`, which a waker's type doesn't name. + Some(Std::Waker) => true, // What it holds of its own, or of its items. None | Some(Std::Peekable) if self.std_iter(ty) => { args.types().any(|t| self.drop_panics(t, seen)) diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 7cd61801b..966a04a2b 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -61,8 +61,12 @@ pub enum Std { Context, /// `rt.Poll`: `T` itself, or `rt.Pending`. Poll, - /// Its pointer. + /// Its pointer, or the value `pin!` pins in a `PinMacroHelper`. Pin, + /// `rt.PollFn`: `poll_fn`'s future, which owns its function. + PollFn, + /// `future::Pending`: `rt.NEVER`, a future never ready. + Pending, /// `rt.Range`, an iterator with `start` and `end` fields. Range, /// `rt.RangeInclusive`. @@ -138,6 +142,7 @@ impl Std { (sym::Mutex, Self::Mutex), (sym::MutexGuard, Self::MutexGuard), (rustc_span::Symbol::intern("Waker"), Self::Waker), + (rustc_span::Symbol::intern("PinMacroHelper"), Self::Pin), (rustc_span::Symbol::intern("HashMap"), Self::HashMap), (rustc_span::Symbol::intern("HashSet"), Self::HashSet), (rustc_span::Symbol::intern("BTreeMap"), Self::BTreeMap), @@ -189,6 +194,8 @@ impl Std { ["ops", "control_flow", "ControlFlow"] => Some(Self::ControlFlow), ["fmt", "rt", "Argument"] => Some(Self::Argument), ["ptr", "non_null", "NonNull"] => Some(Self::NonNull), + ["future", "poll_fn", "PollFn"] => Some(Self::PollFn), + ["future", "pending", "Pending"] => Some(Self::Pending), ["convert", "Infallible"] => Some(Self::Infallible), ["cmp", "Ordering"] => Some(Self::Ordering), ["cmp", "Reverse"] => Some(Self::Reverse), @@ -449,7 +456,7 @@ pub fn inherent_std(tcx: TyCtxt<'_>, def_id: DefId) -> Option { } /// Whether std's `instance` lowers from its own MIR, as the crate's functions do, rather -/// than mapping here: a method of `Option` or `Result`, or their `Clone`. Not one taking a +/// than mapping here: a method of `Option`, `Result`, or `Poll`, or their `Clone`. Not one taking a /// `&mut` or a raw pointer, whose writes the crate's analysis of what it writes into /// would miss, nor an `unsafe` one, nor one mapped below as one expression or as the /// runtime's panic. @@ -467,7 +474,7 @@ pub fn from_mir<'tcx>(t: &Translator<'_, 'tcx>, instance: Instance<'tcx>) -> boo let ty::Adt(adt, _) = tcx.type_of(imp).instantiate_identity().skip_norm_wip().kind() else { return false; }; - let Some(std @ (Std::Option | Std::Result)) = Std::of(tcx, adt.did()) else { + let Some(std @ (Std::Option | Std::Result | Std::Poll)) = Std::of(tcx, adt.did()) else { return false; }; let sig = tcx.fn_sig(did).instantiate_identity().skip_norm_wip().skip_binder(); @@ -636,8 +643,10 @@ fn called_closures<'tcx>( } let mentions = |t: Ty<'tcx>| t.walk().any(|a| a.as_type() == Some(input)); if mentions(output) { + // An `rt.Iter` or `rt.PollFn` drops the closure it holds. let held = matches!(output.kind(), ty::Adt(adt, args) - if super::iter::holds_closure(tcx, adt.did()) && args.types().any(|a| a == input)); + if (super::iter::holds_closure(tcx, adt.did()) || Std::of(tcx, adt.did()) == Some(Std::PollFn)) + && args.types().any(|a| a == input)); if !held { closures.leaked = closures.leaked.or(Some(ty)); } diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index cafd7a457..7079dde44 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -1,7 +1,9 @@ //! Rvalues: arithmetic, casts, aggregates, and closures. use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_data_structures::fx::FxHashSet; use rustc_index::IndexVec; +use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{self, AggregateKind, BinOp, CastKind, Operand, Place, Rvalue, UnOp}; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::{self, Instance, Ty}; @@ -438,7 +440,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return match (std, variant.index()) { (Std::Option, 0) => self.b.t.none(args.type_at(0)), (Std::Poll, 1) => Expr::Rt("Pending".into()), - (Std::Option | Std::Poll, _) => values.pop().unwrap(), + (Std::Option | Std::Poll | Std::Pin, _) => values.pop().unwrap(), // Either variant is its text. (Std::Cow, _) if crate::lower::library::string(tcx, ty) => values.pop().unwrap(), (Std::Result, i) => Expr::result(i == 0, values.pop().unwrap()), @@ -545,10 +547,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { out: &mut Vec, ) -> Expr { let tcx = self.tcx; + let instance = Instance::new_raw(def_id, args); + let Some(mir) = super::instance_mir(self.b.t, instance, span) else { + return Expr::undefined(); + }; + let rebound = rebound_captures(&mir); // A capture by reference reads the place it borrows; one by value is the value as - // it was when the closure was made, a reference held in a variable included. + // it was when the closure was made, a reference held in a variable included, which + // a closure that assigns it whole reassigns. let mut captures = Vec::with_capacity(ops.len()); - for op in ops.iter() { + for (field, op) in ops.iter_enumerated() { let ty = op.ty(&self.mir.local_decls, tcx); // A `&mut` to a borrowed place the closure reads and writes as a JS closure does. if let Some(local) = op.place().and_then(|p| p.as_local()) @@ -574,17 +582,13 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { false => value, true => { let name = self.b.fresh("captured"); - let stmt = StmtKind::decl(false, name.clone(), None, Some(value)).at(None); + let stmt = StmtKind::decl(rebound.contains(&field), name.clone(), None, Some(value)).at(None); self.emit(vec![stmt], None, false, out); Expr::ident(name) } }; captures.push(Capture { value, pointee: false }); } - let instance = Instance::new_raw(def_id, args); - let Some(mir) = super::instance_mir(self.b.t, instance, span) else { - return Expr::undefined(); - }; let sig = tcx.instantiate_bound_regions_with_erased(args.as_closure().sig()); let ret = self .b @@ -607,6 +611,32 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } +/// The captures a closure's body `mir` assigns whole or borrows mutably, other than to +/// drop them: what JS rebinds where Rust writes the closure's own copy. +fn rebound_captures(mir: &mir::Body<'_>) -> FxHashSet { + struct Rebound(FxHashSet); + impl<'tcx> Visitor<'tcx> for Rebound { + fn visit_place(&mut self, place: &Place<'tcx>, cx: PlaceContext, _: mir::Location) { + if place.local.as_u32() != 1 + || !cx.is_mutating_use() + || cx == PlaceContext::MutatingUse(MutatingUseContext::Drop) + { + return; + } + let projection = match place.projection.as_slice() { + [mir::ProjectionElem::Deref, rest @ ..] => rest, + all => all, + }; + if let [mir::ProjectionElem::Field(field, _)] = projection { + self.0.insert(*field); + } + } + } + let mut rebound = Rebound(FxHashSet::default()); + rebound.visit_body(mir); + rebound.0 +} + /// Whether a `ty`'s JS value is the task's context: `&mut Context`, or the `ResumeTy` and /// `NonNull` an async body passes it in. pub(super) fn context_like<'tcx>(fx: &Fx<'_, '_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index f80537383..00d2ab504 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -954,6 +954,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { | library::Std::Waker | library::Std::Context | library::Std::Pin + | library::Std::PollFn + | library::Std::Pending | library::Std::Range | library::Std::RangeInclusive | library::Std::Peekable @@ -1220,6 +1222,10 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { Type::Rt("Poll", vec![self.ty(args.type_at(0), span)]) } library::Std::Pin => self.ty(args.type_at(0), span), + library::Std::PollFn | library::Std::Pending => { + let output = self.future_output(Ty::new_adt(tcx, adt, args), span); + Type::Rt("Future", vec![self.ty(output, span)]) + } library::Std::Range => Type::Rt("Range", vec![self.ty(args.type_at(0), span)]), library::Std::RangeInclusive => Type::Rt("RangeInclusive", vec![self.ty(args.type_at(0), span)]), library::Std::RangeTo => Type::Object(vec![("end".into(), self.ty(args.type_at(0), span))]), diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs index b4cb1e3c1..6b0004edb 100644 --- a/ts/src/lower/task.rs +++ b/ts/src/lower/task.rs @@ -1,11 +1,29 @@ //! The standard library's ownership and async types, as `rt/task.ts` gives them: `Arc`, -//! `Weak`, `Mutex`, `Waker`, `Context`, `Poll`, and `Pin`. +//! `Weak`, `Mutex`, `Waker`, `Context`, `Poll`, `Pin`, and std's futures. -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, Instance, Ty}; +use rustc_span::{Span, Symbol}; +use super::Translator; use super::body::Body; use super::library::{self, Call, Std}; -use crate::ts::Expr; +use crate::ts::{Expr, Param}; + +impl<'tcx> Translator<'_, 'tcx> { + /// `Future::Output` of `ty`, a future. + pub fn future_output(&mut self, ty: Ty<'tcx>, span: Span) -> Ty<'tcx> { + let tcx = self.tcx; + let output = tcx.lang_items().future_output().and_then(|item| { + let projection = Ty::new_projection(tcx, ty::IsRigid::No, item, [ty]); + tcx.try_normalize_erasing_regions(self.typing_env_pub(), ty::Unnormalized::new_wip(projection)) + .ok() + }); + output.unwrap_or_else(|| { + self.err(span, format!("`{ty}` is not a future")); + tcx.types.unit + }) + } +} /// A call of a standard library function on these types, or its arguments back if it is /// none of theirs. `Ok(None)` refuses it. @@ -35,6 +53,15 @@ pub fn call<'tcx>( { Expr::New(Box::new(Expr::Rt("Arc".into())), args) } + // A waker over the crate's `Wake` impl. + ("From", "from") + if let [_, from] = call.args.as_slice() + && self_std == Some(Std::Waker) + && std_of(from.expect_ty()) == Some(Std::Arc) => + { + arc_waker(b, from.expect_ty(), first(args), call.span) + } + ("Waker", "noop") => Expr::Rt("NOOP_WAKER".into()), ("AsRef", "as_ref") if self_std == Some(Std::Arc) => first(args).member("value"), ("Arc", "downgrade") => Expr::New(Box::new(Expr::Rt("Weak".into())), args), ("Arc", "strong_count") => first(args).member("strong"), @@ -69,8 +96,23 @@ pub fn call<'tcx>( let [l, r] = two(args); l.member("willWake").call(vec![r]) } + // With what drops its function, unless that is borrowed. + ("poll_fn", "poll_fn") => { + let dropper = b.t.drop_fn(call.args.type_at(1), call.span); + Expr::New( + Box::new(Expr::Rt("PollFn".into())), + args.into_iter().chain(dropper).collect(), + ) + } + ("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]) + } ("Context", "waker" | "from_waker") | ("Pin", "new" | "new_unchecked" | "as_mut" | "get_mut" | "get_unchecked_mut") + | ("pin", "pin_new_unchecked_in_helper") | ("future", "get_context") | ("IntoFuture", "into_future") => first(args), ("mem", "drop") => { @@ -87,6 +129,42 @@ pub fn call<'tcx>( Ok(Some(e)) } +/// `Waker::from(arc)`, an `Arc`: an `rt.ArcWaker` over `W`'s `Wake::wake`, what drops +/// the `Arc`, and `W`'s own `wake_by_ref` if it overrides the default. +fn arc_waker<'tcx>(b: &mut Body<'_, '_, 'tcx>, arc: Ty<'tcx>, value: Expr, span: Span) -> Expr { + let tcx = b.t.tcx; + let ty::Adt(_, arc_args) = arc.kind() else { + unreachable!("an Arc is a struct") + }; + let wake_trait = tcx + .get_diagnostic_item(Symbol::intern("Wake")) + .expect("Waker::from bounds its Arc by Wake"); + let items = tcx.associated_items(wake_trait); + let item = |name: &str| { + items + .filter_by_name_unhygienic(Symbol::intern(name)) + .next() + .expect("a method of Wake") + .def_id + }; + let (wake, by_ref) = (item("wake"), item("wake_by_ref")); + let w = tcx.mk_args(&[arc_args.type_at(0).into()]); + let arc_param = b.fresh("arc"); + let dropped = b.t.drop_value(Expr::ident(arc_param.clone()), arc, span); + let param = Param { + name: arc_param, + ty: Some(b.t.ty(arc, span)), + }; + let drop = Expr::Lambda(vec![param], Box::new(dropped.unwrap_or_else(Expr::undefined))); + let mut args = vec![value, b.fn_value(wake, w, span), drop]; + if let Ok(Some(instance)) = Instance::try_resolve(tcx, b.t.typing_env_pub(), by_ref, w) + && instance.def_id() != by_ref + { + args.push(b.fn_value(by_ref, w, span)); + } + Expr::New(Box::new(Expr::Rt("ArcWaker".into())), args) +} + fn first(args: Vec) -> Expr { args.into_iter().next().unwrap_or_else(Expr::undefined) } diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 2b24929ae..7f13efeab 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -420,10 +420,11 @@ import * as Channel from "./model.Channel.ts"; import * as Guard from "./model.Guard.ts"; import {{ blocks, drain, sum }} from "./model.ts"; import * as drops from "./drops.ts"; +import * as futures from "./futures.ts"; import {{ harness }} from {harness:?}; export {{ cases }} from {harness:?}; -const fixture = {{ Pending: rt.Pending, u64: {{ of: rt.u64Of }}, Log, Channel, Guard, sum, drain, blocks, drops }}; +const fixture = {{ Pending: rt.Pending, u64: {{ of: rt.u64Of }}, Log, Channel, Guard, sum, drain, blocks, drops, futures }}; const script = harness(fixture); export const run = (input: rt.ByteSlice) => script(rt.byteSliceView(input)); export const unwind = harness(fixture, true); diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 76fce1de5..3a3f76dbd 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -51,6 +51,7 @@ export interface Fixture { held(rx: Consumer, guard: Guard): Future; edited(log: Log, id: number, at: number): void; }; + futures: { helpers(rx: Consumer, guard: Guard): Future }; } /** What every waker of one task points at. */ @@ -201,7 +202,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 % 14) { + switch (op % 15) { case 0: note(`c${channels.length} open`); channels.push(f.Channel.open()); @@ -257,8 +258,11 @@ export function harness(f: Fixture, unwind = false): (input: Uint8Array) = case 12: if (c !== undefined) exec.spawn(f.drops.held(f.Channel.consumer(channels[c]), f.Guard.new(exec.tasks.length, f.Log.clone$Clone(log)))); break; - default: + case 13: f.drops.edited(log, 1000 * exec.tasks.length, arg % 8); + break; + default: + if (c !== undefined) exec.spawn(f.futures.helpers(f.Channel.consumer(channels[c]), f.Guard.new(exec.tasks.length, f.Log.clone$Clone(log)))); } } }; @@ -287,6 +291,11 @@ export const cases: Uint8Array[] = [ // Values std holds that drop, held across an await: returned, and cancelled. [0, 0, 12, 0, 6, 0, 3, 5, 6, 0], [0, 0, 12, 0, 12, 1, 6, 0, 9, 1, 9, 0], + // std's helpers: a `poll_fn` over a pinned `recv` and `future::pending`, returning, + // cancelled with the guard it owns, and panicking inside it. + [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], // 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. diff --git a/ts/tests/unwind.ts b/ts/tests/unwind.ts index 9f2fbc761..5312334df 100644 --- a/ts/tests/unwind.ts +++ b/ts/tests/unwind.ts @@ -31,7 +31,7 @@ for (let i = 0; i < count; i++) { const steps = 4 + (next() % 20); const script = new Uint8Array(steps * 2); for (let s = 0; s < steps; s++) { - script[2 * s] = next() % 14; + script[2 * s] = next() % 15; // A send of 99 panics the `sum` reading it. script[2 * s + 1] = next() % 4 === 0 ? 99 : next() % 256; }