From ca4fc85955c7fd19163b0af400cfda04a1b22014 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:53:51 -0700 Subject: [PATCH 01/30] chore(quest): claim quest/m2/ts-async-spike.md Quest-Claim: b76999a56b3a7148 From 5b7106e07bb87e1314ec1b7791b998d861cfdef2 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:31:45 -0700 Subject: [PATCH 02/30] wip(ts): async spike, generators from THIR with drops Checkpoint: the task fixture, its FIFO executors in Rust and TS, and the generator prototype passing the trace differential test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/Cargo.lock | 4 + ts/fixtures/reject/census.md | 20 +- ts/fixtures/reject/expected.txt | 2 - ts/fixtures/task/Cargo.toml | 14 + ts/fixtures/task/expected/kio.ts | 300 ++++++++++++++++ ts/fixtures/task/expected/log.ts | 42 +++ ts/fixtures/task/expected/model.ts | 553 +++++++++++++++++++++++++++++ ts/fixtures/task/src/exec.rs | 162 +++++++++ ts/fixtures/task/src/harness.rs | 79 +++++ ts/fixtures/task/src/kio.rs | 241 +++++++++++++ ts/fixtures/task/src/lib.rs | 20 ++ ts/fixtures/task/src/log.rs | 29 ++ ts/fixtures/task/src/model.rs | 136 +++++++ ts/fixtures/task/ts.toml | 4 + ts/runtime/rt.ts | 2 + ts/runtime/rt/task.ts | 272 ++++++++++++++ ts/runtime/tsconfig.json | 1 + ts/src/census.rs | 2 + ts/src/lower/body.rs | 335 +++++++++++++++-- ts/src/lower/drop.rs | 296 +++++++++++++++ ts/src/lower/library.rs | 43 +++ ts/src/lower/mod.rs | 60 +++- ts/src/lower/pat.rs | 14 +- ts/src/lower/task.rs | 89 +++++ ts/src/print.rs | 38 +- ts/src/program.rs | 12 +- ts/src/ts.rs | 11 +- ts/tests/differential.ts | 2 + ts/tests/fixtures.rs | 27 +- ts/tests/task.ts | 238 +++++++++++++ 30 files changed, 2961 insertions(+), 87 deletions(-) create mode 100644 ts/fixtures/task/Cargo.toml create mode 100644 ts/fixtures/task/expected/kio.ts create mode 100644 ts/fixtures/task/expected/log.ts create mode 100644 ts/fixtures/task/expected/model.ts create mode 100644 ts/fixtures/task/src/exec.rs create mode 100644 ts/fixtures/task/src/harness.rs create mode 100644 ts/fixtures/task/src/kio.rs create mode 100644 ts/fixtures/task/src/lib.rs create mode 100644 ts/fixtures/task/src/log.rs create mode 100644 ts/fixtures/task/src/model.rs create mode 100644 ts/fixtures/task/ts.toml create mode 100644 ts/runtime/rt/task.ts create mode 100644 ts/src/lower/drop.rs create mode 100644 ts/src/lower/task.rs create mode 100644 ts/tests/task.ts diff --git a/ts/Cargo.lock b/ts/Cargo.lock index 77315fae0..2744d27e9 100644 --- a/ts/Cargo.lock +++ b/ts/Cargo.lock @@ -222,6 +222,10 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "task-fixture" +version = "0.0.0" + [[package]] name = "thiserror" version = "2.0.21" diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index c5ba565f8..5d1145ad3 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,6 +1,6 @@ # Census of `reject-fixture` -- Refusals: 38 +- Refusals: 36 - Function instances: 19 - Generic functions no instance reached, lowered over their type parameters: 1 @@ -17,8 +17,6 @@ | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:65:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:64:3 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:68:3 | -| 1 | `_` implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:43:1 | -| 1 | `_` is async, which is not supported yet | fixtures/reject/src/lib.rs:53:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:110:2 | @@ -46,10 +44,8 @@ The type or module each refused type or path belongs to. | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | -| 1 | `Guard` | fixtures/reject/src/lib.rs:43:1 | | 1 | `Option` | fixtures/reject/src/lib.rs:31:15 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | -| 1 | `later` | fixtures/reject/src/lib.rs:53:1 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | @@ -60,8 +56,6 @@ The type or module each refused type or path belongs to. | 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:99:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | -| 1 | `_` implements `Drop`, which is not supported yet | `Guard` | fixtures/reject/src/lib.rs:43:1 | -| 1 | `_` is async, which is not supported yet | `later` | fixtures/reject/src/lib.rs:53:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:73:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | @@ -148,18 +142,6 @@ The type or module each refused type or path belongs to. -
`_` implements `Drop`, which is not supported yet (1) - -- fixtures/reject/src/lib.rs:43:1: `Guard` implements `Drop`, which is not supported yet - -
- -
`_` is async, which is not supported yet (1) - -- fixtures/reject/src/lib.rs:53:1: `later` is async, which is not supported yet - -
-
`_` is not supported: its `None` and `Some` would both be `undefined` (1) - fixtures/reject/src/lib.rs:31:15: `Option>` is not supported: its `None` and `Some` would both be `undefined` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 5fb953862..d9c991bc5 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -15,8 +15,6 @@ unsupported call to `std::slice::::sort` at fixtures/reject/src/lib.r unsupported call to `core::slice::::iter` at fixtures/reject/src/lib.rs:40:4 unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` at fixtures/reject/src/lib.rs:40:11 unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` at fixtures/reject/src/lib.rs:40:31 -`Guard` implements `Drop`, which is not supported yet at fixtures/reject/src/lib.rs:50:2 -`later` is async, which is not supported yet at fixtures/reject/src/lib.rs:53:1 a precision, as in `{:.2}`, is not supported at fixtures/reject/src/lib.rs:60:3 the `+` flag of a format spec is not supported at fixtures/reject/src/lib.rs:61:3 the `-` flag of a format spec is not supported at fixtures/reject/src/lib.rs:62:3 diff --git a/ts/fixtures/task/Cargo.toml b/ts/fixtures/task/Cargo.toml new file mode 100644 index 000000000..f48ec80bc --- /dev/null +++ b/ts/fixtures/task/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "task-fixture" +description = "A kio-shaped channel and async code, to test rust2-ts's futures and drops against native Rust" +version = "0.0.0" +edition.workspace = true +license.workspace = true +publish = false + +[lib] +# The cdylib is the native side of the differential test, built for wasm32. +crate-type = ["lib", "cdylib"] + +[lints] +workspace = true diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts new file mode 100644 index 000000000..af08edeac --- /dev/null +++ b/ts/fixtures/task/expected/kio.ts @@ -0,0 +1,300 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A task's waker, shared weakly with every list it registers on. */ +export class Waiter { + waker: rt.Waker; + shared: rt.Arc; + + constructor(fields: { waker: rt.Waker; shared: rt.Arc }) { + this.waker = fields.waker; + this.shared = fields.shared; + } + + [Symbol.dispose](): void { + rt.drop(this.waker); + rt.drop(this.shared); + } + + /** Register with `list`, a no-op while the list still holds this waiter. */ + register(list: WaiterList): void { + list.register(this); + } + + static new(waker: rt.Waker): Waiter { + try { + let shared = new rt.Arc(waker.clone()); + try { + const waker2 = waker; + waker = undefined!; + const arg = waker2; + const shared2 = shared; + shared = undefined!; + return new Waiter({ waker: arg, shared: shared2 }); + } finally { + rt.drop(shared); + } + } finally { + rt.drop(waker); + } + } +} + +/** Wakers waiting for one event, held weakly. */ +export class WaiterList { + entries: rt.Weak[]; + /** Where the next registration looks for a dead slot to reuse. */ + cursor: number; + + constructor(fields: { entries: rt.Weak[]; cursor: number }) { + this.entries = fields.entries; + this.cursor = fields.cursor; + } + + /** Drain every entry into a new list, leaving this one empty. */ + take(): WaiterList { + this.cursor = 0; + const taken = this.entries; + this.entries = []; + return new WaiterList({ entries: taken, cursor: 0 }); + } + + /** Wake every live waiter, draining the list. */ + wake(): void { + this.cursor = 0; + const taken = this.entries; + this.entries = []; + for (const entry of taken) { + const upgrade = entry.upgrade(); + if (upgrade !== undefined) { + const waker = upgrade; + try { + waker.value.wakeByRef(); + } finally { + rt.drop(waker); + } + } + } + } + + static new(): WaiterList { + return new WaiterList({ entries: [], cursor: 0 }); + } + + register(waiter: Waiter): void { + const weak = new rt.Weak(waiter.shared); + for (const entry of this.entries) { + if (entry.arc === weak.arc) { + return; + } + } + let probes: number = rt.min(this.entries.length, 2); + while (probes > 0) { + if (rt.at(this.entries, this.cursor).arc.strong === 0) { + const value = weak; + this.entries[rt.idx(this.entries, this.cursor)] = value; + return; + } + this.cursor = rt.usize.rem(rt.usize.add(this.cursor, 1), this.entries.length); + probes = rt.usize.sub(probes, 1); + } + if (this.entries.length >= 4) { + let live: rt.Weak[] = []; + const taken = this.entries; + this.entries = []; + for (const entry2 of taken) { + if (entry2.arc.strong > 0) { + live.push(entry2); + } + } + this.entries = live; + this.cursor = 0; + } + this.entries.push(weak); + } +} + +/** Holds a parked waiter between polls, so its registrations outlive the poll. */ +export class Park { + _0: Waiter | undefined; + + constructor(_0: Waiter | undefined) { + this._0 = _0; + } + + [Symbol.dispose](): void { + rt.drop(this._0); + } + + static default(): Park { + return new Park(undefined); + } + + /** + * The waiter for this poll: the one held if it wakes the same task, else a new one, + * dropping the old and so its registrations. + */ + hold(cx: rt.Context): Waiter { + let reuse: boolean; + if (this._0 !== undefined) { + const waiter = this._0; + reuse = cx.willWake(waiter.waker); + } else { + reuse = false; + } + if (!reuse) { + const value = Waiter.new(cx.clone()); + rt.drop(this._0); + this._0 = value; + } + return rt.option.unwrap(this._0); + } +} + +/** A future from a poll function that receives a [`Waiter`]. */ +export function wait(poll: (a0: Waiter) => rt.Poll): Pending<(a0: Waiter) => rt.Poll> { + return new Pending({ _poll: poll, park: Park.default() }); +} + +/** What [`wait`] returns. */ +export class Pending { + _poll: F; + park: Park; + + constructor(fields: { _poll: F; park: Park }) { + this._poll = fields._poll; + this.park = fields.park; + } + + [Symbol.dispose](): void { + rt.drop(this._poll); + rt.drop(this.park); + } + + poll(this: Pending<(a0: Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { + const this_ = this; + const waiter = this_.park.hold(cx); + return this_._poll(waiter); + } +} + +export class State { + queue: bigint[]; + closed: boolean; + producers: number; + waiters: WaiterList; + + constructor(fields: { queue: bigint[]; closed: boolean; producers: number; waiters: WaiterList }) { + this.queue = fields.queue; + this.closed = fields.closed; + this.producers = fields.producers; + this.waiters = fields.waiters; + } +} + +/** The sending side of a channel, which closes when the last one drops. */ +export class Producer { + state: rt.Arc>; + + constructor(fields: { state: rt.Arc> }) { + this.state = fields.state; + } + + [Symbol.dispose](): void { + this.drop(); + rt.drop(this.state); + } + + drop(): void { + let state: rt.Mutex = this.state.value; + state.value.producers = rt.usize.sub(state.value.producers, 1); + if (state.value.producers > 0) { + return; + } + state.value.closed = true; + let waiters: WaiterList = state.value.waiters.take(); + waiters.wake(); + } + + static new(): Producer { + const state = new State({ queue: [], closed: false, producers: 1, waiters: WaiterList.new() }); + return new Producer({ state: new rt.Arc(new rt.Mutex(state)) }); + } + + consume(): Consumer { + return new Consumer({ state: this.state.clone(), next: 0 }); + } + + /** Queue `value` and wake every consumer, after releasing the lock. */ + send(value: bigint): void { + let state: rt.Mutex = this.state.value; + state.value.queue.push(value); + let waiters: WaiterList = state.value.waiters.take(); + waiters.wake(); + } + + clone(): Producer { + this.state.value.value.producers = rt.usize.add(this.state.value.value.producers, 1); + return new Producer({ state: this.state.clone() }); + } +} + +/** The receiving side of a channel: every value sent, in order. */ +export class Consumer { + state: rt.Arc>; + next: number; + + constructor(fields: { state: rt.Arc>; next: number }) { + this.state = fields.state; + this.next = fields.next; + } + + [Symbol.dispose](): void { + rt.drop(this.state); + } + + clone(): Consumer { + return new Consumer({ state: this.state.clone(), next: this.next }); + } + + /** kio's one-line wrapper over a `poll_*` method. */ + recv(): rt.Future { + const self = this; + return rt.future(function* (_taskContext: rt.Context): Generator { + const self2 = self; + let __awaitee: Pending<(a0: Waiter) => rt.Poll> = wait((waiter: Waiter): rt.Poll => { + return self2.pollRecv(waiter); + }); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); + } + + /** The next value, or `None` once the channel closed and every value was read. */ + pollRecv(waiter: Waiter): rt.Poll { + let state: rt.Mutex = this.state.value; + if (this.next < state.value.queue.length) { + const value = rt.at(state.value.queue, this.next); + this.next = rt.usize.add(this.next, 1); + return value; + } + if (state.value.closed) { + return undefined; + } + waiter.register(state.value.waiters); + return rt.Pending; + } +} + +//# sourceMappingURL=kio.ts.map diff --git a/ts/fixtures/task/expected/log.ts b/ts/fixtures/task/expected/log.ts new file mode 100644 index 000000000..526cf98b5 --- /dev/null +++ b/ts/fixtures/task/expected/log.ts @@ -0,0 +1,42 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; + +/** A shared, append-only list of events. */ +export class Log { + _0: rt.Arc>; + + constructor(_0: rt.Arc>) { + this._0 = _0; + } + + [Symbol.dispose](): void { + rt.drop(this._0); + } + + static new(): Log { + return new Log(new rt.Arc(new rt.Mutex([]))); + } + + /** Append one event. */ + note(event: string): void { + this._0.value.value.push(event); + } + + /** Every event so far, one per line. */ + text(): rt.ByteVec { + const events = this._0.value; + let out: rt.ByteVec = new rt.ByteVec(); + for (const event of events.value) { + out.extendFromSlice(rt.string.asBytes(event)); + out.push(10); + } + return out; + } + + clone(): Log { + return new Log(this._0.clone()); + } +} + +//# sourceMappingURL=log.ts.map diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts new file mode 100644 index 000000000..d9f144c95 --- /dev/null +++ b/ts/fixtures/task/expected/model.ts @@ -0,0 +1,553 @@ +// Generated by rust2-ts. Do not edit. + +import * as rt from "./rt.ts"; +import { Producer, type Consumer } from "./kio.ts"; +import { type Log } from "./log.ts"; + +/** A channel's open producers, and a consumer to clone for each task. */ +export class Channel { + producers: Producer[]; + _consumer: Consumer; + + constructor(fields: { producers: Producer[]; _consumer: Consumer }) { + this.producers = fields.producers; + this._consumer = fields._consumer; + } + + [Symbol.dispose](): void { + rt.dropAll(this.producers); + rt.drop(this._consumer); + } + + static open(): Channel { + let producer = Producer.new(); + try { + let consumer = producer.consume(); + try { + let producers: Producer[] = []; + try { + const arg = producers; + const producer2 = producer; + producer = undefined!; + arg.push(producer2); + const producers2 = producers; + producers = undefined!; + const arg2 = producers2; + const consumer2 = consumer; + consumer = undefined!; + return new Channel({ producers: arg2, _consumer: consumer2 }); + } finally { + rt.dropAll(producers); + } + } finally { + rt.drop(consumer); + } + } finally { + rt.drop(producer); + } + } + + /** A consumer that reads every value from the first. */ + consumer(): Consumer { + return this._consumer.clone(); + } + + /** Send `value` through the first producer, if one is open. */ + send(value: bigint): boolean { + const first = rt.slice.first(this.producers); + if (first !== undefined) { + const producer = first; + producer.send(value); + return true; + } else { + return false; + } + } + + /** Drop the last producer, if one is open: the last closes the channel. */ + close(): boolean { + const pop = this.producers.pop(); + if (pop !== undefined) { + let producer = pop; + try { + const producer2 = producer; + producer = undefined!; + rt.drop(producer2); + return true; + } finally { + rt.drop(producer); + } + } else { + return false; + } + } + + /** Open another producer, if one is open to clone. */ + cloneProducer(): boolean { + let clone: Producer = undefined!; + try { + const first = rt.slice.first(this.producers); + if (first !== undefined) { + const producer = first; + clone = producer.clone(); + } else { + return false; + } + const arg = this.producers; + const clone2 = clone; + clone = undefined!; + arg.push(clone2); + return true; + } finally { + rt.drop(clone); + } + } +} + +/** Logs its own drop. */ +export class Guard { + id: number; + log: Log; + + constructor(fields: { id: number; log: Log }) { + this.id = fields.id; + this.log = fields.log; + } + + [Symbol.dispose](): void { + this.drop(); + rt.drop(this.log); + } + + drop(): void { + this.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(this.id, f), " drop"])); + } + + static new(id: number, log: Log): Guard { + try { + const arg = id; + const log2 = log; + log = undefined!; + return new Guard({ id: arg, log: log2 }); + } finally { + rt.drop(log); + } + } +} + +/** + * Every value until the channel closes, summed, holding a guard of its own across + * each await beside the one it was given. + */ +export function sum(rx: Consumer, guard: Guard): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + let rx2: Consumer = rx; + rx = undefined!; + try { + const guard2 = guard; + guard = undefined!; + try { + const inner = Guard.new(rt.u32.add(guard2.id, 100), guard2.log.clone()); + try { + let total: bigint = 0n; + while (true) { + let option: bigint | undefined; + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + option = result; + break; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + if (option !== undefined) { + const value = option; + inner.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(guard2.id, f), " got ", (f: rt.Formatter) => rt.u64.display(value, f)])); + total = rt.u64.add(total, value); + } else { + break; + } + } + return total; + } finally { + rt.drop(inner); + } + } finally { + rt.drop(guard2); + } + } finally { + rt.drop(rx2); + } + }, (): void => { + rt.drop(rx); + rt.drop(guard); + }); +} + +/** + * Every value until the channel closes, summed, each read `depth` async functions + * deep: 1, 4, or 16. + */ +export function drain(rx: Consumer, depth: number): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + let rx2: Consumer = rx; + rx = undefined!; + try { + const depth2 = depth; + let total: bigint = 0n; + while (true) { + let next: bigint | undefined; + if (depth2 === 1) { + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + next = result; + break; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + } else if (depth2 === 4) { + let __awaitee2: rt.Future = level3(rx2); + try { + while (true) { + const poll2 = __awaitee2.poll(_taskContext); + if (poll2 !== rt.Pending) { + const result2 = poll2; + next = result2; + break; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee2); + } + } else { + let __awaitee3: rt.Future = level15(rx2); + try { + while (true) { + const poll3 = __awaitee3.poll(_taskContext); + if (poll3 !== rt.Pending) { + const result3 = poll3; + next = result3; + break; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee3); + } + } + if (next !== undefined) { + const value = next; + total = rt.u64.add(total, value); + } else { + break; + } + } + return total; + } finally { + rt.drop(rx2); + } + }, (): void => { + rt.drop(rx); + }); +} + +export function level1(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level3(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level2(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level15(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level14(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level2(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level1(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level14(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level13(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level13(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level12(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level12(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level11(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level11(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level10(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level10(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level9(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level9(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level8(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level8(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level7(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level7(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level6(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level6(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level5(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level5(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level4(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +export function level4(rx: Consumer): rt.Future { + return rt.future(function* (_taskContext: rt.Context): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level3(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } + }, (): void => {}); +} + +//# sourceMappingURL=model.ts.map diff --git a/ts/fixtures/task/src/exec.rs b/ts/fixtures/task/src/exec.rs new file mode 100644 index 000000000..f880393f3 --- /dev/null +++ b/ts/fixtures/task/src/exec.rs @@ -0,0 +1,162 @@ +//! A deterministic FIFO executor that logs every poll, wake, and waker clone and drop: +//! the native side of the executor `tests/task.ts` runs the translation on, which logs +//! the same events. Not translated: it is the boundary, built on `dyn Future` and a +//! hand-made waker. + +use std::collections::VecDeque; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; + +use crate::log::Log; + +/// What every waker of one task points at. +struct Wake { + task: usize, + log: Log, + queue: Arc>>, + /// Whether the task is in the queue, so a second wake before its poll adds nothing. + queued: Mutex, +} + +impl Wake { + fn schedule(&self) { + let mut queued = self.queued.lock().unwrap(); + if !*queued { + *queued = true; + self.queue.lock().unwrap().push_back(self.task); + } + } +} + +static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop); + +/// # Safety +/// `data` is an `Arc` that `waker` made. +unsafe fn clone(data: *const ()) -> RawWaker { + // SAFETY: the waker being cloned holds a count. + unsafe { Arc::increment_strong_count(data.cast::()) }; + // SAFETY: as above, it is live. + let wake = unsafe { &*data.cast::() }; + wake.log.note(format!("t{} waker clone", wake.task)); + RawWaker::new(data, &VTABLE) +} + +unsafe fn wake(data: *const ()) { + // SAFETY: the waker being consumed holds a count, which this takes. + let wake = unsafe { Arc::from_raw(data.cast::()) }; + wake.log.note(format!("t{} wake", wake.task)); + wake.schedule(); +} + +unsafe fn wake_by_ref(data: *const ()) { + // SAFETY: the waker holds a count. + let wake = unsafe { &*data.cast::() }; + wake.log.note(format!("t{} wake", wake.task)); + wake.schedule(); +} + +unsafe fn drop(data: *const ()) { + // SAFETY: the waker being dropped holds a count, which this releases. + let wake = unsafe { Arc::from_raw(data.cast::()) }; + wake.log.note(format!("t{} waker drop", wake.task)); +} + +fn waker(wake: Arc) -> Waker { + let data = Arc::into_raw(wake).cast::<()>(); + // SAFETY: the vtable's functions treat `data` as the `Arc` it is. + unsafe { Waker::from_raw(RawWaker::new(data, &VTABLE)) } +} + +struct Task { + future: Pin>>, + waker: Waker, + wake: Arc, + done: bool, +} + +/// Runs tasks in the order they were woken. +pub struct Executor { + log: Log, + queue: Arc>>, + /// Every task spawned, by id; `None` once dropped. + tasks: Vec>, +} + +impl Executor { + pub fn new(log: Log) -> Self { + Self { + log, + queue: Arc::new(Mutex::new(VecDeque::new())), + tasks: Vec::new(), + } + } + + /// How many tasks were spawned, dropped ones included. + pub fn len(&self) -> usize { + self.tasks.len() + } + + /// Spawn a task and queue its first poll. + pub fn spawn(&mut self, future: impl Future + 'static) { + let task = self.tasks.len(); + self.log.note(format!("t{task} spawn")); + let wake = Arc::new(Wake { + task, + log: self.log.clone(), + queue: self.queue.clone(), + queued: Mutex::new(false), + }); + wake.schedule(); + self.tasks.push(Some(Task { + future: Box::pin(future), + waker: waker(wake.clone()), + wake, + done: false, + })); + } + + /// Poll queued tasks until none is left. + pub fn run(&mut self) { + while self.step() {} + } + + /// Poll the next queued task, if any. A dropped or finished one is skipped. + pub fn step(&mut self) -> bool { + let Some(task) = self.queue.lock().unwrap().pop_front() else { + return false; + }; + if self.tasks[task].as_ref().is_some_and(|t| !t.done) { + self.poll(task); + } + true + } + + /// Poll a task whether or not it is queued or finished: polling a finished one panics. + pub fn poll(&mut self, task: usize) { + let Some(t) = self.tasks[task].as_mut() else { + return; + }; + *t.wake.queued.lock().unwrap() = false; + self.log.note(format!("t{task} poll")); + let mut cx = Context::from_waker(&t.waker); + match t.future.as_mut().poll(&mut cx) { + Poll::Ready(value) => { + t.done = true; + self.log.note(format!("t{task} ready {value}")); + } + Poll::Pending => self.log.note(format!("t{task} pending")), + } + } + + /// Drop a task's future, then its waker. + pub fn drop(&mut self, task: usize) { + let Some(t) = self.tasks[task].take() else { + return; + }; + self.log.note(format!("t{task} drop")); + std::mem::drop(t.future); + std::mem::drop(t.waker); + } +} diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs new file mode 100644 index 000000000..11e9accb5 --- /dev/null +++ b/ts/fixtures/task/src/harness.rs @@ -0,0 +1,79 @@ +//! Runs a script of executor steps and returns the log: the native side of the +//! differential test, which `tests/task.ts` mirrors step for step on the translation. +//! +//! Each step is two bytes, an op and its argument. Channels and tasks are picked by the +//! argument, modulo how many there are; a step with nothing to pick does nothing. Once +//! the script ends, every task drops in order, then every channel. + +use crate::exec::Executor; +use crate::log::Log; +use crate::model::{self, Channel, Guard}; + +/// Run one script. +pub fn run(input: &[u8]) -> Vec { + let log = Log::new(); + let mut exec = Executor::new(log.clone()); + let mut channels: Vec = Vec::new(); + for step in input.chunks(2) { + let (op, arg) = (step[0], step.get(1).copied().unwrap_or(0)); + let pick = |len: usize| (len > 0).then(|| usize::from(arg) % len); + match op % 10 { + 0 => { + log.note(format!("c{} open", channels.len())); + channels.push(Channel::open()); + } + 1 => { + if let Some(c) = pick(channels.len()) { + let guard = Guard::new(exec.len() as u32, log.clone()); + exec.spawn(model::sum(channels[c].consumer(), guard)); + } + } + 2 => { + if let Some(c) = pick(channels.len()) { + let depth = [1, 4, 16][usize::from(arg / 16) % 3]; + exec.spawn(model::drain(channels[c].consumer(), depth)); + } + } + 3 => { + if let Some(c) = pick(channels.len()) { + log.note(format!("c{c} send {arg}")); + if !channels[c].send(u64::from(arg)) { + log.note(format!("c{c} closed")); + } + } + } + 4 => { + if let Some(c) = pick(channels.len()) { + log.note(format!("c{c} close")); + channels[c].close(); + } + } + 5 => { + if let Some(c) = pick(channels.len()) { + log.note(format!("c{c} clone")); + channels[c].clone_producer(); + } + } + 6 => exec.run(), + 7 => _ = exec.step(), + 8 => { + if let Some(t) = pick(exec.len()) { + exec.poll(t); + } + } + _ => { + if let Some(t) = pick(exec.len()) { + exec.drop(t); + } + } + } + } + for t in 0..exec.len() { + exec.drop(t); + } + for (c, channel) in channels.into_iter().enumerate() { + log.note(format!("c{c} drop")); + drop(channel); + } + log.text() +} diff --git a/ts/fixtures/task/src/kio.rs b/ts/fixtures/task/src/kio.rs new file mode 100644 index 000000000..f14620b99 --- /dev/null +++ b/ts/fixtures/task/src/kio.rs @@ -0,0 +1,241 @@ +//! moq's kio, trimmed to what its futures hinge on, at the moq revision `just ts moq` +//! pins (`rs/kio/src/waiter.rs`, `pending.rs`, `producer.rs`, and `consumer.rs`). +//! +//! A `WaiterList` holds each waiter's waker weakly, so a waiter that drops, as its +//! `Park` replaces it or its future is cancelled, frees its slots with no deregister. +//! The channel closes when its last producer drops. kio's atomics, tag records, and +//! inline storage are left out: they change no event the test logs. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex, Weak}; +use std::task::{Context, Poll, Waker}; + +/// A task's waker, shared weakly with every list it registers on. +pub struct Waiter { + waker: Waker, + shared: Arc, +} + +impl Waiter { + pub fn new(waker: Waker) -> Self { + let shared = Arc::new(waker.clone()); + Self { waker, shared } + } + + /// Register with `list`, a no-op while the list still holds this waiter. + pub fn register(&self, list: &mut WaiterList) { + list.register(self); + } +} + +/// Wakers waiting for one event, held weakly. +pub struct WaiterList { + entries: Vec>, + /// Where the next registration looks for a dead slot to reuse. + cursor: usize, +} + +impl WaiterList { + pub fn new() -> Self { + Self { + entries: Vec::new(), + cursor: 0, + } + } + + pub fn register(&mut self, waiter: &Waiter) { + let weak = Arc::downgrade(&waiter.shared); + for entry in &self.entries { + if Weak::ptr_eq(entry, &weak) { + return; + } + } + // Probe two slots at the cursor for one whose waiter dropped. + let mut probes = self.entries.len().min(2); + while probes > 0 { + if self.entries[self.cursor].strong_count() == 0 { + self.entries[self.cursor] = weak; + return; + } + self.cursor = (self.cursor + 1) % self.entries.len(); + probes -= 1; + } + if self.entries.len() >= 4 { + // Sweep every dead slot before growing. + let mut live = Vec::new(); + for entry in std::mem::take(&mut self.entries) { + if entry.strong_count() > 0 { + live.push(entry); + } + } + self.entries = live; + self.cursor = 0; + } + self.entries.push(weak); + } + + /// Drain every entry into a new list, leaving this one empty. + pub fn take(&mut self) -> Self { + self.cursor = 0; + Self { + entries: std::mem::take(&mut self.entries), + cursor: 0, + } + } + + /// Wake every live waiter, draining the list. + pub fn wake(&mut self) { + self.cursor = 0; + for entry in std::mem::take(&mut self.entries) { + if let Some(waker) = entry.upgrade() { + waker.wake_by_ref(); + } + } + } +} + +/// Holds a parked waiter between polls, so its registrations outlive the poll. +#[derive(Default)] +pub struct Park(Option); + +impl Park { + /// The waiter for this poll: the one held if it wakes the same task, else a new one, + /// dropping the old and so its registrations. + pub fn hold(&mut self, cx: &Context<'_>) -> &Waiter { + let reuse = match &self.0 { + Some(waiter) => cx.waker().will_wake(&waiter.waker), + None => false, + }; + if !reuse { + self.0 = Some(Waiter::new(cx.waker().clone())); + } + self.0.as_ref().unwrap() + } +} + +/// A future from a poll function that receives a [`Waiter`]. +pub fn wait(poll: F) -> Pending +where + F: FnMut(&Waiter) -> Poll + Unpin, +{ + Pending { + poll, + park: Park::default(), + } +} + +/// What [`wait`] returns. +pub struct Pending { + poll: F, + park: Park, +} + +impl Future for Pending +where + F: FnMut(&Waiter) -> Poll + Unpin, +{ + type Output = R; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = &mut *self; + let waiter = this.park.hold(cx); + (this.poll)(waiter) + } +} + +struct State { + queue: Vec, + closed: bool, + producers: usize, + waiters: WaiterList, +} + +/// The sending side of a channel, which closes when the last one drops. +pub struct Producer { + state: Arc>, +} + +impl Producer { + pub fn new() -> Self { + let state = State { + queue: Vec::new(), + closed: false, + producers: 1, + waiters: WaiterList::new(), + }; + Self { + state: Arc::new(Mutex::new(state)), + } + } + + /// Queue `value` and wake every consumer, after releasing the lock. + pub fn send(&self, value: u64) { + let mut waiters = { + let mut state = self.state.lock().unwrap(); + state.queue.push(value); + state.waiters.take() + }; + waiters.wake(); + } + + pub fn consume(&self) -> Consumer { + Consumer { + state: self.state.clone(), + next: 0, + } + } +} + +impl Clone for Producer { + fn clone(&self) -> Self { + self.state.lock().unwrap().producers += 1; + Self { + state: self.state.clone(), + } + } +} + +impl Drop for Producer { + fn drop(&mut self) { + let mut waiters = { + let mut state = self.state.lock().unwrap(); + state.producers -= 1; + if state.producers > 0 { + return; + } + state.closed = true; + state.waiters.take() + }; + waiters.wake(); + } +} + +/// The receiving side of a channel: every value sent, in order. +#[derive(Clone)] +pub struct Consumer { + state: Arc>, + next: usize, +} + +impl Consumer { + /// The next value, or `None` once the channel closed and every value was read. + pub fn poll_recv(&mut self, waiter: &Waiter) -> Poll> { + let mut state = self.state.lock().unwrap(); + if self.next < state.queue.len() { + let value = state.queue[self.next]; + self.next += 1; + return Poll::Ready(Some(value)); + } + if state.closed { + return Poll::Ready(None); + } + waiter.register(&mut state.waiters); + Poll::Pending + } + + /// kio's one-line wrapper over a `poll_*` method. + pub async fn recv(&mut self) -> Option { + wait(|waiter| self.poll_recv(waiter)).await + } +} diff --git a/ts/fixtures/task/src/lib.rs b/ts/fixtures/task/src/lib.rs new file mode 100644 index 000000000..1a478dad3 --- /dev/null +++ b/ts/fixtures/task/src/lib.rs @@ -0,0 +1,20 @@ +//! A kio-shaped channel and the async code moq builds on it, exercised against native +//! Rust: laziness, poll and wake order, and every drop, including a future's on cancel. +//! +//! `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. Neither is translated. + +pub mod exec; +pub mod harness; +pub mod kio; +pub mod log; +pub mod model; +#[cfg(target_arch = "wasm32")] +#[path = "../../wasm.rs"] +mod wasm; +#[cfg(target_arch = "wasm32")] +use harness::run as entry; diff --git a/ts/fixtures/task/src/log.rs b/ts/fixtures/task/src/log.rs new file mode 100644 index 000000000..bcc3c9aa9 --- /dev/null +++ b/ts/fixtures/task/src/log.rs @@ -0,0 +1,29 @@ +//! The trace both sides of the differential test write, one event per line. + +use std::sync::{Arc, Mutex}; + +/// A shared, append-only list of events. +#[derive(Clone, Default)] +pub struct Log(Arc>>); + +impl Log { + pub fn new() -> Self { + Self(Arc::new(Mutex::new(Vec::new()))) + } + + /// Append one event. + pub fn note(&self, event: String) { + self.0.lock().unwrap().push(event); + } + + /// Every event so far, one per line. + pub fn text(&self) -> Vec { + let events = self.0.lock().unwrap(); + let mut out = Vec::new(); + for event in events.iter() { + out.extend_from_slice(event.as_bytes()); + out.push(b'\n'); + } + out + } +} diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs new file mode 100644 index 000000000..721dac846 --- /dev/null +++ b/ts/fixtures/task/src/model.rs @@ -0,0 +1,136 @@ +//! What the harness spawns and drives: a consumer loop holding guards across its awaits, +//! the same loop under a stack of async functions, and the channels they read. + +use crate::kio::{Consumer, Producer}; +use crate::log::Log; + +/// A channel's open producers, and a consumer to clone for each task. +pub struct Channel { + producers: Vec, + consumer: Consumer, +} + +impl Channel { + pub fn open() -> Self { + let producer = Producer::new(); + let consumer = producer.consume(); + let mut producers = Vec::new(); + producers.push(producer); + Self { producers, consumer } + } + + /// A consumer that reads every value from the first. + pub fn consumer(&self) -> Consumer { + self.consumer.clone() + } + + /// Send `value` through the first producer, if one is open. + pub fn send(&self, value: u64) -> bool { + match self.producers.first() { + Some(producer) => { + producer.send(value); + true + } + None => false, + } + } + + /// Drop the last producer, if one is open: the last closes the channel. + pub fn close(&mut self) -> bool { + match self.producers.pop() { + Some(producer) => { + drop(producer); + true + } + None => false, + } + } + + /// Open another producer, if one is open to clone. + pub fn clone_producer(&mut self) -> bool { + let clone = match self.producers.first() { + Some(producer) => producer.clone(), + None => return false, + }; + self.producers.push(clone); + true + } +} + +/// Logs its own drop. +pub struct Guard { + id: u32, + log: Log, +} + +impl Guard { + pub fn new(id: u32, log: Log) -> Self { + Self { id, log } + } +} + +impl Drop for Guard { + fn drop(&mut self) { + self.log.note(format!("g{} drop", self.id)); + } +} + +/// Every value until the channel closes, summed, holding a guard of its own across +/// each await beside the one it was given. +pub async fn sum(mut rx: Consumer, guard: Guard) -> u64 { + let inner = Guard::new(guard.id + 100, guard.log.clone()); + let mut total = 0; + while let Some(value) = rx.recv().await { + inner.log.note(format!("g{} got {value}", guard.id)); + total += value; + } + total +} + +/// Every value until the channel closes, summed, each read `depth` async functions +/// deep: 1, 4, or 16. +pub async fn drain(mut rx: Consumer, depth: u32) -> u64 { + let mut total = 0; + loop { + let next = match depth { + 1 => rx.recv().await, + 4 => level3(&mut rx).await, + _ => level15(&mut rx).await, + }; + match next { + Some(value) => total += value, + None => break, + } + } + total +} + +/// `levelN` reads through N async functions over `recv`. +macro_rules! levels { + ($($name:ident => $next:ident,)*) => { + $(async fn $name(rx: &mut Consumer) -> Option { + $next(rx).await + })* + }; +} + +async fn level1(rx: &mut Consumer) -> Option { + rx.recv().await +} + +levels! { + level2 => level1, + level3 => level2, + level4 => level3, + level5 => level4, + level6 => level5, + level7 => level6, + level8 => level7, + level9 => level8, + level10 => level9, + level11 => level10, + level12 => level11, + level13 => level12, + level14 => level13, + level15 => level14, +} diff --git a/ts/fixtures/task/ts.toml b/ts/fixtures/task/ts.toml new file mode 100644 index 000000000..71edb61d5 --- /dev/null +++ b/ts/fixtures/task/ts.toml @@ -0,0 +1,4 @@ +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"] diff --git a/ts/runtime/rt.ts b/ts/runtime/rt.ts index 6e6291b7c..409571182 100644 --- a/ts/runtime/rt.ts +++ b/ts/runtime/rt.ts @@ -4,6 +4,8 @@ // a debug build checks it: overflow panics, it never wraps silently. Every panic's // message is the one native Rust panics with. +export * from "./rt/task.ts"; + /** A Rust panic. */ export class Panic extends Error { override name = "Panic"; diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts new file mode 100644 index 000000000..b8fd624e4 --- /dev/null +++ b/ts/runtime/rt/task.ts @@ -0,0 +1,272 @@ +// Ownership and async, for rust2-ts output: what Rust's `Drop`, `Arc`, `Mutex`, and +// futures do that plain JS does not. `rt.ts` re-exports all of it. +// +// A value whose drop JS can observe has `[Symbol.dispose]`, which runs its `Drop` impl +// and drops its fields. A moved-out place holds `undefined`, which drops as nothing. + +import { Ok, Panic, panic, type Result } from "../rt.ts"; + +// Drops + +/** Drop `value`: run its `[Symbol.dispose]`, if it has one. */ +export function drop(value: unknown): void { + const dispose = (value as Partial | null | undefined)?.[Symbol.dispose]; + if (dispose !== undefined) dispose.call(value); +} + +/** Drop every element of `values`, in order. */ +export function dropAll(values: readonly unknown[] | undefined): void { + if (values === undefined) return; + for (const value of values) drop(value); +} + +/** `Vec::into_iter` of elements that drop: dropping it drops those not yet reached. */ +export class IntoIter implements Iterable, Disposable { + #items: T[]; + #next = 0; + + constructor(items: T[]) { + this.#items = items; + } + + *[Symbol.iterator](): Iterator { + while (this.#next < this.#items.length) yield this.#items[this.#next++]; + } + + [Symbol.dispose](): void { + while (this.#next < this.#items.length) drop(this.#items[this.#next++]); + } +} + +// Shared ownership + +/** `Arc`: every clone is this one object, counted. */ +export class Arc implements Disposable { + strong = 1; + value: T; + + constructor(value: T) { + this.value = value; + } + + clone(): Arc { + this.strong++; + return this; + } + + [Symbol.dispose](): void { + if (--this.strong === 0) drop(this.value); + } +} + +/** `Weak`, which nothing observes dropping. */ +export class Weak { + readonly arc: Arc; + + constructor(arc: Arc) { + this.arc = arc; + } + + upgrade(): Arc | undefined { + return this.arc.strong > 0 ? this.arc.clone() : undefined; + } + + clone(): Weak { + return new Weak(this.arc); + } +} + +/** + * `Mutex`, which a single thread never contends, and its guard: locking hands out + * the mutex itself, and unlocking is nothing. + */ +export class Mutex implements Disposable { + value: T; + readonly #locked: Result, never>; + + constructor(value: T) { + this.value = value; + this.#locked = Ok(this); + } + + lock(): Result, never> { + return this.#locked; + } + + [Symbol.dispose](): void { + drop(this.value); + } +} + +// Futures + +/** `Poll::Pending`; `Poll::Ready(v)` is `v` itself. */ +export const Pending: unique symbol = Symbol("Pending"); + +/** `Poll`. */ +export type Poll = T | typeof Pending; + +/** `Waker`: what an executor hands a future to wake its task. */ +export interface Waker extends Disposable { + wake(): void; + wakeByRef(): void; + clone(): Waker; + willWake(other: Waker): boolean; +} + +/** `Context`, which carries only its waker. */ +export type Context = Waker; + +/** A future, as executors poll it. Dropping it cancels it. */ +export interface Future extends Disposable { + poll(cx: Context): Poll; +} + +/** The body of an `async fn` or block: it yields at each `.await` that is pending. */ +export type Body = (cx: Context) => Generator; + +const Unresumed = 0; +const Suspended = 1; +const Returned = 2; +const Panicked = 3; + +/** + * An `async fn`'s future, around its body as a generator. Nothing runs until the first + * poll. Dropping it unresumed drops what it captured, and suspended runs the `finally` + * blocks that drop its live locals. + */ +class Async implements Future { + #state = Unresumed; + #body: Body; + #gen: Generator | undefined; + #drop: () => void; + + constructor(body: Body, drop: () => void) { + this.#body = body; + this.#drop = drop; + } + + poll(cx: Context): Poll { + if (this.#state === Returned) panic("`async fn` resumed after completion"); + if (this.#state === Panicked) panic("`async fn` resumed after panicking"); + const state = this.#state; + this.#state = Panicked; + let gen = this.#gen; + let next: IteratorResult; + if (state === Unresumed) { + gen = this.#gen = this.#body(cx); + next = gen.next(); + } else { + next = gen!.next(cx); + } + if (next.done) { + this.#state = Returned; + return next.value; + } + this.#state = Suspended; + return Pending; + } + + [Symbol.dispose](): void { + const state = this.#state; + this.#state = Returned; + if (state === Unresumed) this.#drop(); + else if (state === Suspended) this.#gen!.return(undefined as T); + } +} + +/** An `async fn`'s future: `body` runs at the first poll, and `drop` drops what it captured if it never does. */ +export function future(body: Body, drop: () => void): Future { + return new Async(body, drop); +} + +// Executor + +/** + * Run `future` to completion on the microtask queue, as a promise of its output. A + * panic rejects the promise with the `Panic`. + */ +export function spawn(future: Future): Promise { + return new Promise((resolve, reject) => new Task(future, resolve, reject).schedule()); +} + +/** How many polls one microtask runs before it yields to a macrotask, so a task that keeps waking itself cannot starve I/O. */ +const BUDGET = 128; + +/** Tasks woken since the last run, in order. */ +const queue: { run(): void }[] = []; +let scheduled = false; + +function run(): void { + scheduled = false; + for (let polls = 0; polls < BUDGET; polls++) { + const task = queue.shift(); + if (task === undefined) return; + task.run(); + } + if (queue.length > 0) { + scheduled = true; + setTimeout(run, 0); + } +} + +/** A spawned future, which is also the waker of every poll it gets. */ +class Task implements Waker { + #future: Future | undefined; + #resolve: (value: T) => void; + #reject: (err: unknown) => void; + #queued = false; + + constructor(future: Future, resolve: (value: T) => void, reject: (err: unknown) => void) { + this.#future = future; + this.#resolve = resolve; + this.#reject = reject; + } + + schedule(): void { + if (this.#queued || this.#future === undefined) return; + this.#queued = true; + queue.push(this); + if (!scheduled) { + scheduled = true; + queueMicrotask(run); + } + } + + run(): void { + this.#queued = false; + const future = this.#future; + if (future === undefined) return; + let output: Poll; + try { + output = future.poll(this); + } catch (err) { + this.#future = undefined; + this.#reject(err); + if (!(err instanceof Panic)) throw err; + return; + } + if (output === Pending) return; + this.#future = undefined; + future[Symbol.dispose](); + this.#resolve(output); + } + + wake(): void { + this.schedule(); + } + + wakeByRef(): void { + this.schedule(); + } + + clone(): Waker { + return this; + } + + willWake(other: Waker): boolean { + return other === this; + } + + [Symbol.dispose](): void {} +} diff --git a/ts/runtime/tsconfig.json b/ts/runtime/tsconfig.json index 781df47f4..1dcf03266 100644 --- a/ts/runtime/tsconfig.json +++ b/ts/runtime/tsconfig.json @@ -5,6 +5,7 @@ "noUnusedLocals": true, "noUnusedParameters": true, "target": "es2022", + "lib": ["es2022", "esnext.disposable", "dom"], "module": "esnext", "moduleResolution": "bundler", "allowImportingTsExtensions": true, diff --git a/ts/src/census.rs b/ts/src/census.rs index 98df2b9a6..acdea89a8 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -154,8 +154,10 @@ const VERBATIM: &[&str] = &[ "for", "format_args!", "if", + "if let", "let", "let ... else", + "match", "ref mut", "self", "undefined", diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 96ee6677c..35b981ec2 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -15,6 +15,7 @@ use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::{self, GenericArgsRef, Instance, Ty, TypeVisitableExt}; use rustc_span::{Span, Symbol}; +use super::drop::Owned; use super::library::{self, Args}; use super::{AdtRepr, ObjectKind, Translator, camel, escape}; use crate::program::SymKind; @@ -42,13 +43,17 @@ pub fn function<'a, 'tcx>( breakables: Vec::new(), ret: sig.output(), visited: FxHashSet::default(), + scopes: Vec::new(), + moved: FxHashSet::default(), }; let span = tcx.def_span(def_id); let mut body = Vec::new(); let mut params = Vec::new(); + b.open_scope(); for (i, param) in thir.params.iter().enumerate() { let ty = b.subst(param.ty); - let this = i == 0 && param.self_kind.is_some(); + // An explicit `self: Pin<&mut Self>` has no implicit self kind. + let this = i == 0 && (param.self_kind.is_some() || method); match (¶m.pat, this) { (Some(pat), true) => { let PatKind::Binding { var, .. } = pat.kind else { @@ -70,6 +75,31 @@ pub fn function<'a, 'tcx>( name: name.to_string(), ty: Some(ty), }); + continue; + } + // `this` can't be left `undefined`, as a move out of it would. + if !matches!(ty.kind(), ty::Ref(..)) && b.t.drops(ty) { + b.t.err( + pat.span, + "a method that takes `self` by value that drops, which is not supported yet", + ); + } + // An instance of a generic class: TypeScript reads its fields as the instance's. + let receiver = match ty.kind() { + ty::Adt(adt, args) if library::Std::of(tcx, adt.did()) == Some(library::Std::Pin) => { + args.type_at(0) + } + _ => ty, + } + .peel_refs(); + if let ty::Adt(_, args) = receiver.kind() + && args.types().next().is_some() + { + let ty = b.t.ty(receiver, pat.span); + params.push(Param { + name: name.to_string(), + ty: Some(ty), + }); } } (Some(pat), false) => { @@ -90,6 +120,7 @@ pub fn function<'a, 'tcx>( false => Dest::Return, }; b.stmt(expr, dest, &mut body); + b.close_scope(&mut body, 0, span); let ret = b.t.ret_ty(ret, span); Some(ts::Function { sym: 0, @@ -147,6 +178,10 @@ pub struct Body<'b, 'a, 'tcx> { /// Expressions lowered so far, by THIR and id, so a refused call lowers only the /// arguments its mapping did not. visited: FxHashSet<(*const Thir<'tcx>, ExprId)>, + /// The variables each open scope drops when it closes, innermost last. + pub(super) scopes: Vec>>, + /// The variables a move left `undefined`, which are declared `let` for it. + pub(super) moved: FxHashSet, } /// One `&&`-joined part of an `if` condition. @@ -225,8 +260,8 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } - /// Declare a binding for a Rust variable. - /// Declare a binding for a Rust variable of type `ty`. + /// Declare a binding for a Rust variable of type `ty`, which its scope drops if it + /// `owns` the value rather than borrowing it. pub(super) fn bind_var( &mut self, var: LocalVarId, @@ -234,6 +269,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { mutable: bool, ty: Ty<'tcx>, span: Span, + owns: bool, ) -> String { // A JS variable holding a number is a copy: writing through it reaches nothing. if let ty::Ref(_, inner, rustc_ast::Mutability::Mut) = self.subst(ty).kind() @@ -252,6 +288,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { mutable, }, ); + if owns { + let ty = self.subst(ty); + self.own(&name, ty); + } name } @@ -266,7 +306,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { .. } if mode.0 == rustc_hir::ByRef::No => { let mutable = mode.1 == rustc_ast::Mutability::Mut; - self.bind_var(*var, *name, mutable, pat.ty, pat.span) + self.bind_var(*var, *name, mutable, pat.ty, pat.span, true) } PatKind::Wild => self.fresh("_"), _ => { @@ -333,7 +373,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ExprKind::Loop { body } => self.lp(*region_scope, body, dest, out), _ => self.stmt(*value, dest, out), }, - ExprKind::ValueTypeAscription { source, .. } => self.stmt(*source, dest, out), + ExprKind::ValueTypeAscription { source, .. } | ExprKind::ValueExpr { source } => { + self.stmt(*source, dest, out) + } ExprKind::NeverToAny { source } => self.stmt(*source, Dest::Discard, out), ExprKind::Block { block } => self.block(*block, dest, out), ExprKind::If { @@ -370,6 +412,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ExprKind::AssignOp { op, lhs, rhs } => self.assign_op(*op, *lhs, *rhs, span, out), _ => { let value = self.expr(id, out); + // A value that goes nowhere drops here. + if let Dest::Discard = dest + && let Some(dropped) = self.t.drop_value(value.clone(), ty, span) + { + self.push(out, StmtKind::Expr(dropped), span); + return; + } self.deliver(value, &dest, span, out); } } @@ -399,12 +448,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { fn block_body(&mut self, id: BlockId, dest: Dest, out: &mut Vec) { let block = &self.thir[id]; + let start = out.len(); + self.open_scope(); for &stmt in &block.stmts { self.stmt_item(stmt, out); } if let Some(expr) = block.expr { self.stmt(expr, dest, out); } + self.close_scope(out, start, block.span); } fn stmt_item(&mut self, id: StmtId, out: &mut Vec) { @@ -458,20 +510,30 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.ref_binding(mode.0, pat_ty, pat.span); } let mutable = mode.1 == rustc_ast::Mutability::Mut; + let owns = mode.0 == rustc_hir::ByRef::No; let ty = self.t.ty(pat_ty, pat.span); let Some(init) = init else { - let name = self.bind_var(*var, *name, true, pat_ty, pat.span); + let name = self.bind_var(*var, *name, true, pat_ty, pat.span, owns); self.push(out, StmtKind::decl(true, name, Some(ty), None), span); return; }; if self.needs_dest(init) { - let name = self.bind_var(*var, *name, true, pat_ty, pat.span); + let name = self.bind_var(*var, *name, true, pat_ty, pat.span, owns); self.push(out, StmtKind::decl(true, name.clone(), Some(ty), None), span); self.stmt(init, Dest::Assign(name), out); return; } + // A move from another variable or field: it is left `undefined`. + if self.moves(init) { + let place = self.place(init, out); + let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); + let annotate = mutable.then_some(ty); + self.push(out, StmtKind::decl(mutable, name, annotate, Some(place.clone())), span); + self.clear(place, out); + return; + } let value = self.operand(init, out); - let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span); + let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); let annotate = mutable || needs_annotation(&value); self.push( out, @@ -488,6 +550,19 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } return; }; + // `let _ = value;` drops a value at once, and leaves a place alone. + if let PatKind::Wild = pat.kind + && els.is_none() + && self.t.drops(pat_ty) + { + if !self.is_place(init) { + let value = self.operand(init, out); + if let Some(dropped) = self.t.drop_value(value, pat_ty, span) { + self.push(out, StmtKind::Expr(dropped), span); + } + } + return; + } // `const [a, b] = ...` for a tuple or array of plain bindings. if els.is_none() && self.destructurable(pat, true) { let value = self.operand(init, out); @@ -588,7 +663,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { PatKind::Binding { name, var, mode, .. } => { let is_mut = mode.1 == rustc_ast::Mutability::Mut; *mutable |= is_mut; - Target::Name(self.bind_var(*var, *name, is_mut, pat.ty, pat.span)) + Target::Name(self.bind_var(*var, *name, is_mut, pat.ty, pat.span, mode.0 == rustc_hir::ByRef::No)) } _ => unreachable!("checked by destructurable"), } @@ -809,6 +884,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { match part { CondPart::Bool(id) => Some(self.expr(*id, pre)), CondPart::Let(expr, pat) => { + if !self.is_place(*expr) && self.t.drops(self.ty_of(*expr)) && !takes_all(pat) { + self.t.err( + pat.span, + "an `if let` on a temporary that drops, which it doesn't move out of whole", + ); + } let reads = self.test_reads(pat) + bindings(pat); let (scrut, owned) = self.scrutinee(*expr, reads, pre); let test = self.pat_test(pat, &scrut); @@ -866,8 +947,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { // One condition, as JS writes it. if let [part] = parts.as_slice() { let mut then_stmts = Vec::new(); + self.open_scope(); let test = self.cond_part(part, out, &mut then_stmts); self.stmt(then, dest.clone(), &mut then_stmts); + self.close_scope(&mut then_stmts, 0, span); let mut else_stmts = Vec::new(); if let Some(els) = els { self.stmt(els, dest, &mut else_stmts); @@ -891,12 +974,17 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { // A let chain: each part nests in the last, and any failing runs the else. let label = self.fresh("chain"); let mut levels = Vec::new(); + self.open_scope(); for part in &parts { let mut pre = Vec::new(); let mut binds = Vec::new(); let test = self.cond_part(part, &mut pre, &mut binds); levels.push((pre, test, binds)); } + if self.scope_owns() { + self.t.err(span, "a let chain that binds a value that drops"); + } + self.scopes.pop(); let mut then_stmts = Vec::new(); self.stmt(then, dest.clone(), &mut then_stmts); let mut else_stmts = Vec::new(); @@ -965,6 +1053,32 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } let thir: &'a Thir<'tcx> = self.thir; + // One arm binding the whole value, as `.await` desugars to, is a `let` scoped to it. + if let [arm] = arms + && thir[*arm].guard.is_none() + && let PatKind::Binding { + mode, subpattern: None, .. + } = thir[*arm].pattern.kind + && mode.0 == rustc_hir::ByRef::No + { + let start = out.len(); + self.open_scope(); + self.let_(&thir[*arm].pattern, Some(scrutinee), None, span, out); + self.stmt(thir[*arm].body, dest, out); + self.close_scope(out, start, span); + return; + } + if !self.is_place(scrutinee) + && self.t.drops(self.ty_of(scrutinee)) + && !arms + .iter() + .all(|&arm| thir[arm].guard.is_none() && takes_all(&thir[arm].pattern)) + { + self.t.err( + span, + "a `match` on a temporary that drops, which it doesn't move out of whole", + ); + } let pats: Vec<&Pat<'tcx>> = arms.iter().map(|&arm| &*thir[arm].pattern).collect(); // The last arm is the else, whose test never runs, unless it is guarded. let tested = match arms.last().is_some_and(|&arm| thir[arm].guard.is_none()) { @@ -991,6 +1105,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let arm = &self.thir[arm]; let test = self.pat_test(&arm.pattern, &scrut); let mut binds = Vec::new(); + self.open_scope(); self.pat_bind(&arm.pattern, &scrut, owned, &mut binds); let guard = arm.guard.map(|g| { let mut pre = Vec::new(); @@ -999,6 +1114,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { }); let mut body = Vec::new(); self.stmt(arm.body, dest.clone(), &mut body); + // What the arm binds that drops is dropped around its bindings and body. + if self.scope_owns() { + if guard.is_some() { + self.t.err(arm.span, "a guarded arm that binds a value that drops"); + } + binds.append(&mut body); + body = std::mem::take(&mut binds); + } + self.close_scope(&mut body, 0, arm.span); lowered.push(Lowered { test, binds, @@ -1267,6 +1391,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { is_loop: true, }); let mut stmts = Vec::new(); + if self.t.drops(self.subst(pat.ty)) { + self.t.err( + pat.span, + "a `for` loop over values that drop, which is not supported yet", + ); + } + self.open_scope(); let simple_name = match &pat.kind { PatKind::Binding { name, @@ -1275,7 +1406,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { subpattern: None, .. } if mode.1 == rustc_ast::Mutability::Not && !self.needs_copy(self.subst(pat.ty)) => { - Some(self.bind_var(*var, *name, false, pat.ty, pat.span)) + Some(self.bind_var(*var, *name, false, pat.ty, pat.span, mode.0 == rustc_hir::ByRef::No)) } PatKind::Wild => Some(self.fresh("_")), _ => None, @@ -1293,6 +1424,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } }; self.stmt(loop_body, Dest::Discard, &mut stmts); + self.close_scope(&mut stmts, 0, span); let breakable = self.breakables.pop().unwrap(); let label = breakable.used.then_some(breakable.label); let kind = match source { @@ -1428,6 +1560,21 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { value = self.spill(value, "value", out); } out.extend(pre); + // The old value drops once the new one is made. + let lty = self.ty_of(lhs); + if self.t.drops(lty) { + if !target.is_path() && !matches!(target, Expr::Index(..)) { + self.t + .err(span, "an assignment that drops the old value of a computed place"); + return; + } + if !value.is_path() && !value.is_constant() { + value = self.spill(value, "value", out); + } + if let Some(dropped) = self.t.drop_value(target.clone(), lty, span) { + self.push(out, StmtKind::Expr(dropped), span); + } + } // `*r = v` through a reference replaces what it points to. if let ExprKind::Deref { arg } = self.thir[self.strip(lhs)].kind && matches!(self.ty_of(arg).kind(), ty::Ref(..)) @@ -1528,6 +1675,30 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } + /// Whether lowering `id` for its value moves it out of a place that drops it. + pub fn moves(&mut self, id: ExprId) -> bool { + let ty = self.ty_of(id); + self.is_place(id) && !self.t.is_copy(ty) && self.t.drops(ty) + } + + /// Whether a block binds a variable that drops, so its value can't outlive it. + fn block_owns(&mut self, id: BlockId) -> bool { + let thir: &'a Thir<'tcx> = self.thir; + let mut owns = false; + for &stmt in &thir[id].stmts { + if let thir::StmtKind::Let { pattern, .. } = &thir[stmt].kind { + pattern.walk_always(|p| { + if let PatKind::Binding { mode, ty, .. } = p.kind + && mode.0 == rustc_hir::ByRef::No + { + owns |= self.t.drops(self.t.subst(self.args, ty)); + } + }); + } + } + owns + } + pub fn needs_copy(&self, ty: Ty<'tcx>) -> bool { if !self.t.is_copy(ty) { return false; @@ -1590,7 +1761,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.stmt(*source, Dest::Discard, out); Expr::undefined() } - ExprKind::Block { block } if !self.thir[*block].targeted_by_break => { + ExprKind::Block { block } if !self.thir[*block].targeted_by_break && !self.block_owns(*block) => { let block = &self.thir[*block]; for &stmt in &block.stmts { self.stmt_item(stmt, out); @@ -1660,10 +1831,17 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { }; return self.fn_value(def_id, args.skip_binder(), span); } + if self.moves(id) { + let place = self.place(id, out); + return self.move_out(place, span, out); + } let value = self.place(id, out); self.copied(value, ty) } ExprKind::Borrow { borrow_kind, arg } => { + if !self.is_place(*arg) && self.t.drops(self.ty_of(*arg)) { + return self.err(span, "a borrow of a temporary that drops: bind it to a variable first"); + } if let BorrowKind::Mut { .. } = borrow_kind { let pointee = self.ty_of(*arg); if self.t.object_kind(pointee).is_none() @@ -1797,7 +1975,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } ExprKind::Adt(adt) => self.adt_expr(adt, ty, span, out), - ExprKind::Closure(closure) => self.closure(closure, span), + ExprKind::Closure(closure) => self.closure(closure, span, out), ExprKind::Assign { .. } | ExprKind::AssignOp { .. } | ExprKind::Break { .. } @@ -1807,6 +1985,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { Expr::undefined() } ExprKind::Let { .. } => self.err(span, "a `let` outside an `if` condition"), + ExprKind::Yield { value } => { + self.stmt(*value, Dest::Discard, out); + Expr::Yield + } kind => self.err(span, format!("unsupported expression: {}", kind_name(kind))), } } @@ -1947,7 +2129,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { match ty.kind() { ty::Tuple(_) => base.index(Expr::lit(field.index().to_string())), ty::Adt(adt, _) => match library::Std::of(self.t.tcx, adt.did()) { - Some(library::Std::Option) => base, + Some(library::Std::Option | library::Std::Poll) => base, Some(library::Std::Result) => match variant.index() { 0 => base.member("value"), _ => base.member("error"), @@ -1977,8 +2159,11 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let mut values = self.operands(&ids, out); if let Some(std) = library::Std::of(tcx, def.did()) { return match (std, adt.variant_index.index()) { - (library::Std::Option, 0) => Expr::undefined(), - (library::Std::Option, _) => values.pop().unwrap(), + (library::Std::Option, 0) | (library::Std::Poll, 1) => match std { + library::Std::Poll => Expr::Rt("Pending"), + _ => Expr::undefined(), + }, + (library::Std::Option | library::Std::Poll, _) => values.pop().unwrap(), (library::Std::Result, 0) => Expr::rt("Ok", values), (library::Std::Result, _) => Expr::rt("Err", values), (library::Std::FmtError, _) => Expr::New(Box::new(Expr::Rt("FmtError")), Vec::new()), @@ -2085,39 +2270,76 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } - fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span) -> Expr { + /// A closure as an arrow function, or an `async` body as a future around a generator. + fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span, out: &mut Vec) -> Expr { let tcx = self.t.tcx; let local = closure.closure_id; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); }; - // A copy captured by `move` would be shared in JS: refuse one that can change. + let closure_ty = self.subst(tcx.type_of(local).instantiate_identity().skip_norm_wip()); + let (ret, coroutine) = match closure_ty.kind() { + ty::Closure(_, args) => ( + tcx.instantiate_bound_regions_with_erased(args.as_closure().sig()) + .output(), + false, + ), + ty::Coroutine(_, args) if tcx.coroutine_is_async(local.to_def_id()) => { + (args.as_coroutine().return_ty(), true) + } + _ => return self.err(span, format!("a closure of type `{closure_ty}`")), + }; + // What a future captures that drops, which it drops itself if never polled. + let mut captured = Vec::new(); + // A method's receiver, which a generator can't read as `this`. + let mut receiver = None; for capture in tcx.closure_captures(local) { - if let ty::UpvarCapture::ByValue = capture.info.capture_kind { - let var = capture.get_root_variable(); - let mutable = matches!(self.locals.get(&var), Some(Local::Name { mutable: true, .. })); - if mutable && self.t.is_copy(self.subst(capture.place.ty())) { - self.t - .err(capture.get_path_span(tcx), "a closure that copies a mutable variable"); + let var = capture.get_root_variable(); + let ty = self.subst(capture.place.ty()); + if coroutine && matches!(self.locals.get(&var), Some(Local::Name { name, .. }) if name == "this") { + let alias = self.fresh("self"); + out.push(StmtKind::decl(false, alias.clone(), None, Some(Expr::This)).at(None)); + let saved = self.locals.insert( + var, + Local::Name { + name: alias, + mutable: false, + }, + ); + receiver = Some((var, saved)); + } + let ty::UpvarCapture::ByValue = capture.info.capture_kind else { + continue; + }; + let mutable = matches!(self.locals.get(&var), Some(Local::Name { mutable: true, .. })); + // A copy captured by `move` would be shared in JS: refuse one that can change. + if !coroutine && mutable && self.t.is_copy(ty) { + self.t + .err(capture.get_path_span(tcx), "a closure that copies a mutable variable"); + } + if self.t.drops(ty) { + match (coroutine, &self.locals.get(&var)) { + (true, Some(Local::Name { name, .. })) if capture.place.projections.is_empty() => { + let name = name.clone(); + self.disown(&name); + captured.push((name, ty)); + } + _ => self.t.err( + capture.get_path_span(tcx), + "a closure that captures a value that drops, which is not supported yet", + ), } } } let saved_thir = std::mem::replace(&mut self.thir, thir); self.read.extend(reads(tcx, thir)); let saved_breakables = std::mem::take(&mut self.breakables); - let closure_ty = self.subst(tcx.type_of(local).instantiate_identity().skip_norm_wip()); - let sig = match closure_ty.kind() { - ty::Closure(_, args) => tcx.instantiate_bound_regions_with_erased(args.as_closure().sig()), - _ => { - self.thir = saved_thir; - self.breakables = saved_breakables; - return self.err(span, format!("a closure of type `{closure_ty}`")); - } - }; - let saved_ret = std::mem::replace(&mut self.ret, sig.output()); + let saved_ret = std::mem::replace(&mut self.ret, ret); let mut body_stmts = Vec::new(); let mut params = Vec::new(); - // The first parameter is the closure's environment. + self.open_scope(); + // The first parameter is the closure's environment; a coroutine's second is the + // context each poll resumes it with. for param in thir.params.iter().skip(1) { let name = match ¶m.pat { Some(pat) => self.param(pat, &mut body_stmts), @@ -2127,17 +2349,36 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let ty = self.t.ty(ty, span); params.push(Param { name, ty: Some(ty) }); } - let ret = self.ret; let dest = match ret.is_unit() || ret.is_never() { true => Dest::Discard, false => Dest::Return, }; self.stmt(body, dest, &mut body_stmts); + self.close_scope(&mut body_stmts, 0, span); let ret_ty = self.t.ret_ty(ret, span); self.thir = saved_thir; self.breakables = saved_breakables; self.ret = saved_ret; - Expr::Arrow(params, ret_ty, body_stmts) + if let Some((var, saved)) = receiver { + match saved { + Some(saved) => self.locals.insert(var, saved), + None => self.locals.remove(&var), + }; + } + if !coroutine { + return Expr::Arrow(params, ret_ty, body_stmts); + } + let mut drops = Vec::new(); + for (name, ty) in captured { + if let Some(dropped) = self.t.drop_value(Expr::ident(name), ty, span) { + drops.push(StmtKind::Expr(dropped).at(None)); + } + } + let generator = Expr::Generator(params, ret_ty, body_stmts); + Expr::rt( + "future", + vec![generator, Expr::Arrow(Vec::new(), Type::Builtin("void"), drops)], + ) } // Calls @@ -2210,6 +2451,14 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } _ => return self.err(span, format!("`{}` does not resolve", tcx.def_path_str(def_id))), }; + // An `async` body's `Future::poll`, which its future has itself. + if let ty::InstanceKind::Item(did) = instance.def + && tcx.is_coroutine(did) + { + let mut values = self.args(args, out); + let future = values.remove(0); + return future.member("poll").call(values); + } if let ty::InstanceKind::Item(did) = instance.def && did.is_local() { @@ -2278,7 +2527,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { if let Some(std) = library::Std::of(tcx, adt_id) { let mut values = values; return match (std, variant.index()) { - (library::Std::Option, 1) => values.pop().unwrap(), + (library::Std::Option, 1) | (library::Std::Poll, 0) => values.pop().unwrap(), (library::Std::Result, 0) => Expr::rt("Ok", values), (library::Std::Result, _) => Expr::rt("Err", values), _ => self.err(span, format!("constructing `{}`", tcx.def_path_str(adt_id))), @@ -2418,6 +2667,18 @@ fn needs_annotation(value: &Expr) -> bool { } } +/// Whether matching `pat` moves its whole value into a binding, or matches only a variant +/// with nothing in it: either way nothing is left to drop. +fn takes_all(pat: &Pat<'_>) -> bool { + match &pat.kind { + PatKind::Binding { + mode, subpattern: None, .. + } => mode.0 == rustc_hir::ByRef::No, + PatKind::Variant { subpatterns, .. } => subpatterns.iter().all(|f| takes_all(&f.pattern)), + _ => false, + } +} + pub fn has_bindings(pat: &Pat<'_>) -> bool { bindings(pat) > 0 } diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs new file mode 100644 index 000000000..aac5f7a2b --- /dev/null +++ b/ts/src/lower/drop.rs @@ -0,0 +1,296 @@ +//! Drops: which values JS can see drop, and where each one drops. +//! +//! A type drops if dropping it does something JS can see: runs a `Drop` impl, counts an +//! `Arc` down, or drops a waker. Such a value has `[Symbol.dispose]`, which a class gets +//! as drop glue: its `Drop` impl, then each field in order. A variable drops at the end +//! of its scope through a `finally`, so an early exit, a panic, or a cancelled future +//! drops it too. A move leaves `undefined` in the place it left, which drops as nothing, +//! so a variable moved on only some paths still drops on the others. + +use rustc_middle::ty::{self, AdtDef, Instance, Ty, TypeVisitableExt}; +use rustc_span::Span; + +use super::body::Body; +use super::library::Std; +use super::{Adt, AdtRepr, Translator}; +use crate::program::{SymKind, Symbol}; +use crate::ts::{self, Expr, Stmt, StmtKind, Target, Type}; + +/// A variable its scope drops when it ends. +pub struct Owned<'tcx> { + pub name: String, + pub ty: Ty<'tcx>, +} + +impl<'a, 'tcx> Translator<'a, 'tcx> { + /// Whether dropping a `ty` does something JS can see. + pub fn drops(&mut self, ty: Ty<'tcx>) -> bool { + if let Some(&drops) = self.drops.get(&ty) { + return drops; + } + // A type that holds itself drops through another field if at all. + self.drops.insert(ty, false); + let tcx = self.tcx; + let drops = match ty.kind() { + ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { + Some(Std::Arc | Std::Waker) => true, + Some(Std::Option | Std::Result | Std::Box | Std::Vec | Std::Mutex | Std::Poll) => { + args.types().any(|t| self.drops(t)) + } + Some(_) => false, + None if adt.did().is_local() => adt.has_dtor(tcx) || self.fields_drop(*adt, args, true), + None => false, + }, + ty::Tuple(tys) => tys.iter().any(|t| self.drops(t)), + 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, + _ => false, + }; + self.drops.insert(ty, drops); + drops + } + + /// Whether any field of `adt` with `args` drops, counting one of a type parameter only + /// if `params`. + fn fields_drop(&mut self, adt: AdtDef<'tcx>, args: ty::GenericArgsRef<'tcx>, params: bool) -> bool { + let tcx = self.tcx; + adt.all_fields().any(|field| { + let ty = self.subst(args, tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); + (params || !ty.has_param()) && self.drops(ty) + }) + } + + /// Whether a `ty` that drops does so through its own `[Symbol.dispose]`, so whatever + /// holds one can drop it without knowing its type. + fn disposable(&mut self, ty: Ty<'tcx>) -> bool { + if !self.drops(ty) { + return true; + } + match ty.kind() { + ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { + Some(Std::Arc | Std::Waker | Std::Mutex) => true, + Some(Std::Option | Std::Box) => self.disposable(args.type_at(0)), + Some(_) => false, + None => adt.is_struct(), + }, + ty::Coroutine(..) | ty::Param(_) => true, + _ => false, + } + } + + /// What drops the `ty` in `value`, or `None` if JS would see nothing drop. + pub fn drop_value(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Option { + if !self.drops(ty) { + return None; + } + let supported = match ty.kind() { + ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { + Some(Std::Vec) if self.disposable(args.type_at(0)) => { + return Some(Expr::rt("dropAll", vec![value])); + } + Some(Std::Arc | Std::Mutex | Std::Option | Std::Box) => self.disposable(args.type_at(0)), + Some(Std::Waker) => true, + Some(_) => false, + None if adt.is_struct() => { + let info = self.adt(*adt, span); + self.glue(*adt, &info, span); + args.types().all(|t| self.disposable(t)) + } + None => false, + }, + ty::Array(elem, _) if self.disposable(*elem) => return Some(Expr::rt("dropAll", vec![value])), + ty::Coroutine(..) | ty::Param(_) => true, + _ => false, + }; + if !supported { + self.err(span, format!("dropping `{ty}`, which is not supported yet")); + return None; + } + Some(Expr::rt("drop", vec![value])) + } + + /// Give a class whose own fields or `Drop` impl drop its drop glue up front, so JS + /// that holds one can drop it. One that drops only through a type parameter gets + /// it once an instance that drops does. + pub fn drop_glue(&mut self, adt: AdtDef<'tcx>, info: &Adt, span: Span) { + let identity = ty::GenericArgs::identity_for_item(self.tcx, adt.did()); + if adt.has_dtor(self.tcx) || self.fields_drop(adt, identity, false) { + self.glue(adt, info, span); + } + } + + /// The `[Symbol.dispose]` of a class: its `Drop` impl, then each field that drops. + fn glue(&mut self, adt: AdtDef<'tcx>, info: &Adt, span: Span) { + let tcx = self.tcx; + if !self.glued.insert(adt.did()) { + return; + } + let AdtRepr::Class { fields, .. } = &info.repr else { + self.err( + span, + format!( + "dropping the enum `{}`, which is not supported yet", + tcx.def_path_str(adt.did()) + ), + ); + return; + }; + let mut body: Vec = Vec::new(); + if let Some(dtor) = adt.destructor(tcx) { + match tcx.generics_of(adt.did()).requires_monomorphization(tcx) { + true => self.err( + span, + format!( + "`{}` is generic and implements `Drop`, which is not supported yet", + tcx.def_path_str(adt.did()) + ), + ), + false => { + let sym = self.instance(Instance::mono(tcx, dtor.did)); + body.push(StmtKind::Expr(Expr::Method(Box::new(Expr::This), sym, Vec::new())).at(None)); + } + } + } + for (field, &id) in adt.non_enum_variant().fields.iter().zip(fields) { + let ty = tcx.type_of(field.did).instantiate_identity().skip_norm_wip(); + if let Some(dropped) = self.drop_value(Expr::This.field(id), ty, span) { + body.push(StmtKind::Expr(dropped).at(None)); + } + } + let sym = self.program.sym(Symbol { + module: self.module_of(adt.did()), + base: "[Symbol.dispose]".into(), + suffix: String::new(), + owner: Some(info.sym), + kind: SymKind::Method { instance: true }, + order: (0, 0), + name: String::new(), + }); + self.program.methods.entry(info.sym).or_default().push(ts::Function { + sym, + method: true, + params: Vec::new(), + ret: Type::Builtin("void"), + body, + loc: None, + doc: None, + }); + } +} + +impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { + /// Start a scope: the variables bound until it closes drop when it does. + pub fn open_scope(&mut self) { + self.scopes.push(Vec::new()); + } + + /// Drop `name`, a `ty`, when the innermost scope closes, if JS would see it drop. + pub fn own(&mut self, name: &str, ty: Ty<'tcx>) { + if !self.t.drops(ty) { + return; + } + if let Some(scope) = self.scopes.last_mut() { + scope.push(Owned { + name: name.to_string(), + ty, + }); + } + } + + /// Stop dropping `name` here: it moved somewhere that drops it itself. + pub fn disown(&mut self, name: &str) { + for scope in &mut self.scopes { + scope.retain(|owned| owned.name != name); + } + } + + /// Whether the innermost scope drops anything yet. + pub fn scope_owns(&self) -> bool { + self.scopes.last().is_some_and(|scope| !scope.is_empty()) + } + + /// Close the innermost scope, whose statements are `out[start..]`: each variable it + /// drops is dropped in a `finally` around the statements after its declaration, the + /// last declared innermost, or around them all for a parameter. + pub fn close_scope(&mut self, out: &mut Vec, start: usize, span: Span) { + let owned = self.scopes.pop().unwrap_or_default(); + for owned in owned.into_iter().rev() { + let Some(dropped) = self.t.drop_value(Expr::ident(&owned.name), owned.ty, span) else { + continue; + }; + let moved = self.moved.contains(&owned.name); + let mut at = start; + for (i, stmt) in out.iter_mut().enumerate().skip(start) { + if let StmtKind::Decl { + mutable, target, init, .. + } = &mut stmt.kind + && declares(target, &owned.name) + { + *mutable |= moved; + // The `finally` may run before anything assigns it. + init.get_or_insert_with(|| Expr::lit("undefined!")); + at = i + 1; + break; + } + } + // What the declaration moved from is cleared before anything can throw. + while out.get(at).is_some_and(clears) { + at += 1; + } + let body = out.split_off(at); + let dropped = StmtKind::Expr(dropped).at(None); + match body.is_empty() { + true => out.push(dropped), + false => out.push( + StmtKind::Try { + body, + finally: vec![dropped], + } + .at(None), + ), + } + } + } + + /// The value of the place `place`, a `ty` that drops, moved out: the place is left + /// `undefined`, so whatever drops it later drops nothing. + pub fn move_out(&mut self, place: Expr, span: Span, out: &mut Vec) -> Expr { + let base = match &place { + Expr::Ident(name) => name.clone(), + _ => "moved".into(), + }; + match &place { + Expr::Ident(name) => { + self.moved.insert(name.clone()); + } + Expr::Member(..) if place.is_path() => {} + _ => return self.err(span, "a move out of a place that is no variable or field"), + } + let name = self.fresh(&base); + out.push(StmtKind::decl(false, name.clone(), None, Some(place.clone())).at(None)); + self.clear(place, out); + Expr::ident(name) + } + + /// Leave `undefined` in `place`, whose value moved. + pub fn clear(&mut self, place: Expr, out: &mut Vec) { + if let Expr::Ident(name) = &place { + self.moved.insert(name.clone()); + } + out.push(StmtKind::Expr(place.assign(Expr::lit("undefined!"))).at(None)); + } +} + +/// Whether `stmt` leaves a moved-out place `undefined`. +fn clears(stmt: &Stmt) -> bool { + matches!(&stmt.kind, StmtKind::Expr(Expr::Assign(_, value)) if matches!(&**value, Expr::Lit(text) if text == "undefined!")) +} + +/// Whether `target` declares `name`. +fn declares(target: &Target, name: &str) -> bool { + match target { + Target::Name(n) => n == name, + Target::Array(items) => items.iter().flatten().any(|t| declares(t, name)), + } +} diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 3ba20bbec..84b68d769 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -42,6 +42,23 @@ pub enum Std { DebugList, /// What `assert_eq!` and `assert_ne!` compare by: its operator, as a string. AssertKind, + /// `rt.Arc`, counted. + Arc, + /// `rt.Weak`. + Weak, + /// `rt.Mutex`, which is also its own guard. + Mutex, + MutexGuard, + /// What a `Mutex` can't be locked with on one thread: never. + PoisonError, + /// `rt.Waker`. + Waker, + /// `rt.Context`: its waker. + Context, + /// `rt.Poll`: `T` itself, or `rt.Pending`. + Poll, + /// Its pointer. + Pin, } impl Std { @@ -65,9 +82,31 @@ impl Std { if tcx.is_lang_item(did, rustc_attr_ir::LangItem::OwnedBox) { return Some(Self::Box); } + for (item, std) in [ + (sym::Arc, Self::Arc), + (sym::ArcWeak, Self::Weak), + (sym::Mutex, Self::Mutex), + (sym::MutexGuard, Self::MutexGuard), + (rustc_span::Symbol::intern("Waker"), Self::Waker), + ] { + if tcx.is_diagnostic_item(item, did) { + return Some(std); + } + } + for (item, std) in [ + (rustc_attr_ir::LangItem::Context, Self::Context), + (rustc_attr_ir::LangItem::ResumeTy, Self::Context), + (rustc_attr_ir::LangItem::Poll, Self::Poll), + (rustc_attr_ir::LangItem::Pin, Self::Pin), + ] { + if tcx.is_lang_item(did, item) { + return Some(std); + } + } match tcx.item_name(did).as_str() { "FromUtf8Error" => return Some(Self::FromUtf8Error), "TryFromIntError" => return Some(Self::TryFromIntError), + "PoisonError" => return Some(Self::PoisonError), _ => {} } match std_path(tcx, did) @@ -167,6 +206,10 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, let (owner, name) = key(tcx, call.def_id)?; let span = call.span; let gargs = call.args; + let args = match super::task::call(b, call, &owner, &name, args, out) { + Ok(e) => return e, + Err(args) => args, + }; // Methods on integers. if let Some(int) = int_named(&owner) { diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 7be26e2eb..85420e89c 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -6,10 +6,12 @@ mod body; mod consts; +mod drop; mod fmt; mod library; mod num; mod pat; +mod task; use std::collections::VecDeque; @@ -152,6 +154,10 @@ pub struct Translator<'a, 'tcx> { env: TypingEnv<'tcx>, /// Refusals collected for a census, rather than reported as errors. refusals: Option>, + /// Whether each type's drop does something JS can see, as [`Self::drops`] found. + drops: rustc_data_structures::fx::FxHashMap, bool>, + /// The classes given drop glue. + glued: rustc_data_structures::fx::FxHashSet, } /// A local struct or enum, and how it is represented. @@ -217,6 +223,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { failed: false, env: TypingEnv::fully_monomorphized(), refusals, + drops: Default::default(), + glued: Default::default(), }) } @@ -561,6 +569,14 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { .instantiate_and_normalize_erasing_regions(args, self.typing_env(), EarlyBinder::bind(self.tcx, value)) } + /// The standard library type `ty` is, if it is one with its own representation. + pub fn std_of(&self, ty: Ty<'tcx>) -> Option { + match ty.kind() { + ty::Adt(adt, _) => library::Std::of(self.tcx, adt.did()), + _ => None, + } + } + pub fn is_copy(&self, ty: Ty<'tcx>) -> bool { self.tcx.type_is_copy_modulo_regions(self.typing_env(), ty) } @@ -572,15 +588,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } let tcx = self.tcx; let did = adt.did(); - if adt.destructor(tcx).is_some() { - self.err( - span, - format!( - "`{}` implements `Drop`, which is not supported yet", - tcx.def_path_str(did) - ), - ); - } let repr = match () { _ if adt.is_struct() => { let variant = adt.non_enum_variant(); @@ -695,6 +702,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } }; self.program.items.push(item); + self.drop_glue(adt, &info, span); info } @@ -711,7 +719,14 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::Formatter | library::Std::DebugStruct | library::Std::DebugTuple - | library::Std::DebugList, + | library::Std::DebugList + | library::Std::Arc + | library::Std::Weak + | library::Std::Mutex + | library::Std::MutexGuard + | library::Std::Waker + | library::Std::Context + | library::Std::Pin, ) => Some(ObjectKind::Class), Some(_) => None, None if adt.is_struct() => Some(ObjectKind::Class), @@ -719,6 +734,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), _ if self.deferred(ty) => Some(ObjectKind::Class), _ => None, } @@ -763,6 +779,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { self.fn_ty(&inputs, sig.output(), span) } ty::Adt(adt, args) => self.adt_ty(*adt, args, span), + ty::Coroutine(_, args) => Type::Rt("Future", vec![self.ty(args.as_coroutine().return_ty(), span)]), // `&dyn Debug` and `&dyn Display` are values ready to write. ty::Dynamic(preds, ..) if preds @@ -813,6 +830,10 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { } Type::Union(vec![self.ty(inner, span), Type::Builtin("undefined")]) } + // A lock's result, which is never an error: its guard. + library::Std::Result if self.std_of(args.type_at(1)) == Some(library::Std::PoisonError) => { + self.ty(args.type_at(0), span) + } library::Std::Result => Type::Rt( "Result", vec![self.ty(args.type_at(0), span), self.ty(args.type_at(1), span)], @@ -832,6 +853,18 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::DebugTuple => Type::Rt("DebugTuple", vec![]), library::Std::DebugList => Type::Rt("DebugList", vec![]), library::Std::AssertKind => Type::Builtin("string"), + library::Std::Arc => Type::Rt("Arc", vec![self.ty(args.type_at(0), span)]), + library::Std::Weak => Type::Rt("Weak", vec![self.ty(args.type_at(0), span)]), + // A guard's first argument is its lifetime. + library::Std::Mutex | library::Std::MutexGuard => { + let inner = args.types().next().expect("a guarded type"); + Type::Rt("Mutex", vec![self.ty(inner, span)]) + } + library::Std::PoisonError => Type::Builtin("never"), + library::Std::Waker => Type::Rt("Waker", vec![]), + library::Std::Context => Type::Rt("Context", vec![]), + library::Std::Poll => Type::Rt("Poll", vec![self.ty(args.type_at(0), span)]), + library::Std::Pin => self.ty(args.type_at(0), span), }; } if !adt.did().is_local() { @@ -883,13 +916,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ); return; }; - if tcx.asyncness(def_id).is_async() { - self.err( - span, - format!("`{}` is async, which is not supported yet", tcx.def_path_str(def_id)), - ); - return; - } let owner = self.owner(instance); let method = matches!(owner, Owner::Class(_)) && self.has_self(def_id); let function = body::function(self, instance, thir, *expr, method); diff --git a/ts/src/lower/pat.rs b/ts/src/lower/pat.rs index fba5bb208..ef5a23891 100644 --- a/ts/src/lower/pat.rs +++ b/ts/src/lower/pat.rs @@ -41,6 +41,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { 0 => scrut.clone().binary("===", Expr::undefined()), _ => scrut.clone().binary("!==", Expr::undefined()), }), + Some(Std::Poll) => tests.push(match variant_index.index() { + 0 => scrut.clone().binary("!==", Expr::Rt("Pending")), + _ => scrut.clone().binary("===", Expr::Rt("Pending")), + }), Some(Std::Result) => tests.push(match variant_index.index() { 0 => scrut.clone().member("ok"), _ => scrut.clone().member("ok").not(), @@ -175,8 +179,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { if !by_value { self.ref_binding(mode.0, ty, pat.span); } + // A value that drops moves into its binding, read or not. + let moves = by_value && !self.t.is_copy(ty) && self.t.drops(ty); // Binding has no effect in JS, and TypeScript refuses an unread local. - if subpattern.is_none() && !self.is_read(*var) { + if subpattern.is_none() && !self.is_read(*var) && !moves { return; } let mutable = mode.1 == rustc_ast::Mutability::Mut; @@ -184,9 +190,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { true => self.copied(scrut.clone(), ty), false => scrut.clone(), }; - let name = self.bind_var(*var, *name, mutable, ty, pat.span); + let name = self.bind_var(*var, *name, mutable, ty, pat.span, by_value); let annotate = mutable.then(|| self.t.ty(ty, pat.span)); out.push(StmtKind::decl(mutable, name, annotate, Some(value)).at(None)); + // Out of a place, which is left `undefined`. + if moves && !owned { + self.clear(scrut.clone(), out); + } if let Some(sub) = subpattern { self.pat_bind(sub, scrut, owned, out); } diff --git a/ts/src/lower/task.rs b/ts/src/lower/task.rs new file mode 100644 index 000000000..d11d33a13 --- /dev/null +++ b/ts/src/lower/task.rs @@ -0,0 +1,89 @@ +//! The standard library's ownership and async types, as `rt/task.ts` gives them: `Arc`, +//! `Weak`, `Mutex`, `Waker`, `Context`, `Poll`, and `Pin`. + +use rustc_middle::ty::{self, Ty}; + +use super::body::Body; +use super::library::{Args, Call, Std}; +use crate::ts::{Expr, Stmt}; + +/// 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, 'x>( + b: &mut Body<'_, '_, 'tcx>, + call: &Call<'tcx>, + owner: &str, + name: &str, + args: Args<'x>, + out: &mut Vec, +) -> Result, Args<'x>> { + let tcx = b.t.tcx; + let std_of = |ty: Ty<'tcx>| match ty.peel_refs().kind() { + ty::Adt(adt, _) => Std::of(tcx, adt.did()), + _ => None, + }; + let self_ty = call.args.types().next(); + let self_std = self_ty.and_then(std_of); + let e = match (owner, name) { + ("Arc", "new") => Expr::New(Box::new(Expr::Rt("Arc")), b.args(args, out)), + ("Arc", "downgrade") => Expr::New(Box::new(Expr::Rt("Weak")), b.args(args, out)), + ("Arc", "strong_count") => first(b, args, out).member("strong"), + ("Arc", "ptr_eq") => { + let [l, r] = two(b, args, out); + l.binary("===", r) + } + ("Weak", "upgrade") => first(b, args, out).member("upgrade").call(vec![]), + ("Weak", "strong_count") => first(b, args, out).member("arc").member("strong"), + ("Weak", "ptr_eq") => { + let [l, r] = two(b, args, out); + l.member("arc").binary("===", r.member("arc")) + } + ("Clone", "clone") if matches!(self_std, Some(Std::Arc | Std::Weak | Std::Waker)) => { + first(b, args, out).member("clone").call(vec![]) + } + ("Deref", "deref") | ("DerefMut", "deref_mut") => match self_std { + Some(Std::Arc | Std::Mutex | Std::MutexGuard) => first(b, args, out).member("value"), + Some(Std::Pin) => first(b, args, out), + _ => return Err(args), + }, + ("Mutex", "new") => Expr::New(Box::new(Expr::Rt("Mutex")), b.args(args, out)), + // The mutex is its own guard, and a lock never fails on one thread. + ("Mutex", "lock") => first(b, args, out), + ("Result", "unwrap" | "expect") if call.args.types().nth(1).and_then(std_of) == Some(Std::PoisonError) => { + first(b, args, out) + } + ("Waker", "wake_by_ref") => first(b, args, out).member("wakeByRef").call(vec![]), + ("Waker", "wake") => first(b, args, out).member("wake").call(vec![]), + ("Waker", "will_wake") => { + let [l, r] = two(b, args, out); + l.member("willWake").call(vec![r]) + } + ("Context", "waker" | "from_waker") + | ("Pin", "new" | "new_unchecked" | "as_mut" | "get_mut" | "get_unchecked_mut") + | ("future", "get_context") + | ("IntoFuture", "into_future") => first(b, args, out), + ("mem", "drop") => { + let ty = call.args.type_at(0); + let value = first(b, args, out); + match b.t.drop_value(value.clone(), ty, call.span) { + Some(dropped) => dropped, + None if value.is_path() => Expr::undefined(), + None => value, + } + } + _ => return Err(args), + }; + Ok(Some(e)) +} + +fn first<'tcx>(b: &mut Body<'_, '_, 'tcx>, args: Args<'_>, out: &mut Vec) -> Expr { + b.args(args, out).into_iter().next().unwrap_or_else(Expr::undefined) +} + +fn two<'tcx>(b: &mut Body<'_, '_, 'tcx>, args: Args<'_>, out: &mut Vec) -> [Expr; 2] { + let mut values = b.args(args, out).into_iter(); + [ + values.next().unwrap_or_else(Expr::undefined), + values.next().unwrap_or_else(Expr::undefined), + ] +} diff --git a/ts/src/print.rs b/ts/src/print.rs index 6d1788f3d..2877ea17b 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -271,6 +271,10 @@ impl Refs { self.stmts(program, body); } StmtKind::Block { body, .. } => self.stmts(program, body), + StmtKind::Try { body, finally } => { + self.stmts(program, body); + self.stmts(program, finally); + } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } @@ -278,7 +282,7 @@ impl Refs { fn expr(&mut self, program: &Program, e: &Expr) { match e { - Expr::Ident(_) | Expr::This | Expr::Rt(_) | Expr::Lit(_) | Expr::Str(_) => {} + Expr::Ident(_) | Expr::This | Expr::Rt(_) | Expr::Lit(_) | Expr::Str(_) | Expr::Yield => {} Expr::Sym(id) => self.use_sym(program, *id, true), Expr::Array(es) => es.iter().for_each(|e| self.expr(program, e)), Expr::Object(props) => props.iter().for_each(|(_, e)| self.expr(program, e)), @@ -300,7 +304,7 @@ impl Refs { self.expr(program, b); self.expr(program, c); } - Expr::Arrow(params, ret, body) => { + Expr::Arrow(params, ret, body) | Expr::Generator(params, ret, body) => { self.params(program, params); self.ty(program, ret); self.stmts(program, body); @@ -733,6 +737,15 @@ impl Printer<'_> { self.start(); self.write("}\n"); } + StmtKind::Try { body, finally } => { + self.write("try {\n"); + self.block_body(body); + self.start(); + self.write("} finally {\n"); + self.block_body(finally); + self.start(); + self.write("}\n"); + } StmtKind::Break(label) => match label { Some(label) => self.write(&format!("break {label};\n")), None => self.write("break;\n"), @@ -874,6 +887,17 @@ impl Printer<'_> { self.write("}"); } } + Expr::Generator(params, ret, body) => { + self.write("function* ("); + self.params(params); + let ret = self.ty(ret); + self.uses_rt = true; + self.write(&format!("): Generator {{\n")); + self.block_body(body); + self.start(); + self.write("}"); + } + Expr::Yield => self.write("yield"), Expr::Lambda(params, body) => { self.write("("); self.params(params); @@ -1038,7 +1062,7 @@ fn binary_prec(op: &str) -> u8 { fn prec(e: &Expr) -> u8 { match e { - Expr::Assign(..) | Expr::Arrow(..) | Expr::Lambda(..) => 3, + Expr::Assign(..) | Expr::Arrow(..) | Expr::Lambda(..) | Expr::Generator(..) | Expr::Yield => 3, Expr::Cond(..) => 4, Expr::Binary(_, op, _) => binary_prec(op), Expr::As(..) => 12, @@ -1105,6 +1129,10 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_locals(body, out); } StmtKind::Block { body, .. } => collect_locals(body, out), + StmtKind::Try { body, finally } => { + collect_locals(body, out); + collect_locals(finally, out); + } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } @@ -1119,7 +1147,7 @@ fn collect_target(target: &Target, out: &mut Vec) { fn collect_expr_locals(e: &Expr, out: &mut Vec) { match e { - Expr::Arrow(params, _, body) => { + Expr::Arrow(params, _, body) | Expr::Generator(params, _, body) => { out.extend(params.iter().map(|p| p.name.clone())); collect_locals(body, out); } @@ -1143,6 +1171,6 @@ fn collect_expr_locals(e: &Expr, out: &mut Vec) { collect_expr_locals(b, out); collect_expr_locals(c, out); } - Expr::Ident(_) | Expr::This | Expr::Sym(_) | Expr::Rt(_) | Expr::Lit(_) | Expr::Str(_) => {} + Expr::Ident(_) | Expr::This | Expr::Sym(_) | Expr::Rt(_) | Expr::Lit(_) | Expr::Str(_) | Expr::Yield => {} } } diff --git a/ts/src/program.rs b/ts/src/program.rs index dd3799583..8b9b4e269 100644 --- a/ts/src/program.rs +++ b/ts/src/program.rs @@ -6,8 +6,12 @@ use std::path::{Path, PathBuf}; use crate::print; use crate::ts::{FieldId, Function, Item, SymId}; -/// The runtime every module imports helpers from, written beside the crate root. -pub const RUNTIME: &str = include_str!("../runtime/rt.ts"); +/// The runtime every module imports helpers from, written beside the crate root: each +/// file's path from there, and its text. +pub const RUNTIME: &[(&str, &str)] = &[ + ("rt.ts", include_str!("../runtime/rt.ts")), + ("rt/task.ts", include_str!("../runtime/rt/task.ts")), +]; /// The first line of every generated file, which also marks it as safe to replace. pub const HEADER: &str = "// Generated by rust2-ts. Do not edit."; @@ -166,7 +170,9 @@ impl Program { items.sort_by_key(|item| self.syms[item_sym(item)].order); } - write_file(&out.join("rt.ts"), &format!("{HEADER}\n{RUNTIME}"))?; + for (path, text) in RUNTIME { + write_file(&out.join(path), &format!("{HEADER}\n{text}"))?; + } for (module, items) in modules { let path = out.join(module_file(module)); let printed = print::module(self, module, &items, &path)?; diff --git a/ts/src/ts.rs b/ts/src/ts.rs index 4b3f27e26..cabcbe29f 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -49,6 +49,10 @@ pub enum Expr { Lambda(Vec, Box), /// `e as T`, for a literal whose type TypeScript would widen. As(Box, Type), + /// `function* (params): Generator { body }`, an async body. + Generator(Vec, Type, Vec), + /// `yield`, which a generator resumes from with the next `rt.Context`. + Yield, Located(Loc, Box), } @@ -205,6 +209,11 @@ pub enum StmtKind { }, Break(Option), Continue(Option), + /// `try { body } finally { finally }`: what `finally` drops is dropped on every exit. + Try { + body: Vec, + finally: Vec, + }, } impl StmtKind { @@ -241,7 +250,7 @@ impl Stmt { match &self.kind { StmtKind::Return(_) | StmtKind::Break(_) | StmtKind::Continue(_) => true, StmtKind::If { then, els, .. } => diverges(then) && diverges(els), - StmtKind::Block { label: None, body } => diverges(body), + StmtKind::Block { label: None, body } | StmtKind::Try { body, .. } => diverges(body), _ => false, } } diff --git a/ts/tests/differential.ts b/ts/tests/differential.ts index 6e70d8884..43c5d6931 100644 --- a/ts/tests/differential.ts +++ b/ts/tests/differential.ts @@ -80,6 +80,8 @@ for (let op = 0; op < 8; op++) { } } } +// A harness's own cases, which name what they cover. +if (Array.isArray(harness.cases)) cases.push(...harness.cases); for (let i = 0; i < count; i++) { const len = Number(next() % 48n); const input = new Uint8Array(len + 1); diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 024743dcf..b13285c88 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -62,7 +62,7 @@ fn sources(dir: &Path) -> Vec<(PathBuf, String)> { stack.push(path); } else if path.extension().is_some_and(|e| e == "ts") { let rel = path.strip_prefix(dir).unwrap().to_path_buf(); - if rel != Path::new("rt.ts") { + if rel != Path::new("rt.ts") && !rel.starts_with("rt") { files.push((rel, std::fs::read_to_string(&path).unwrap())); } } @@ -193,6 +193,31 @@ fn lang() { differential("lang-fixture", &out, 50_000); } +/// Futures and drops: the harness is hand-written TS around the translation, whose FIFO +/// executor logs every poll, wake, and drop as the fixture's native one does. +#[test] +fn task() { + let out = scratch().join("task").join("out"); + let glue = out.join("harness.ts"); + let _ = std::fs::remove_file(&glue); + let out = translated("task"); + snapshot("task", &out); + let harness = manifest_dir().join("tests").join("task.ts").display().to_string(); + let text = format!( + r#"import * as rt from "./rt.ts"; +import {{ Log }} from "./log.ts"; +import {{ Channel, Guard, drain, sum }} from "./model.ts"; +import {{ harness }} from {harness:?}; + +export {{ cases }} from {harness:?}; +export const run = harness({{ Pending: rt.Pending, Log, Channel, Guard, sum, drain }}); +"# + ); + std::fs::write(&glue, text).unwrap(); + typecheck(&out); + differential("task-fixture", &out, 20_000); +} + /// Each construct outside the subset fails with its span, and nothing is written. #[test] fn reject() { diff --git a/ts/tests/task.ts b/ts/tests/task.ts new file mode 100644 index 000000000..504d53c7c --- /dev/null +++ b/ts/tests/task.ts @@ -0,0 +1,238 @@ +// The task fixture's harness on the translation: a deterministic FIFO executor and the +// script runner of `fixtures/task/src/exec.rs` and `harness.rs`, step for step, logging +// the same events through the translated `Log`. `differential.ts` requires the two logs +// to match byte for byte, panics included. + +/** A waker, as the translation calls it. */ +interface Waker extends Disposable { + wake(): void; + wakeByRef(): void; + clone(): Waker; + willWake(other: Waker): boolean; +} + +interface Future extends Disposable { + poll(cx: Waker): T | symbol; +} + +interface Log { + note(event: string): void; + text(): { view(): Uint8Array }; + clone(): Log; +} + +type Consumer = Disposable; +type Guard = Disposable; + +interface Channel extends Disposable { + consumer(): Consumer; + send(value: bigint): boolean; + close(): boolean; + cloneProducer(): boolean; +} + +/** What the harness drives: the translation's roots, and the runtime's `Pending`. */ +export interface Fixture { + Pending: symbol; + Log: { "new"(): Log }; + Channel: { open(): Channel }; + Guard: { "new"(id: number, log: Log): Guard }; + sum(rx: Consumer, guard: Guard): Future; + drain(rx: Consumer, depth: number): Future; +} + +/** What every waker of one task points at. */ +class Wake { + readonly task: number; + readonly log: Log; + readonly queue: number[]; + queued = false; + + constructor(task: number, log: Log, queue: number[]) { + this.task = task; + this.log = log; + this.queue = queue; + } + + schedule(): void { + if (this.queued) return; + this.queued = true; + this.queue.push(this.task); + } +} + +class TaskWaker implements Waker { + readonly target: Wake; + + constructor(target: Wake) { + this.target = target; + } + + wake(): void { + this.target.log.note(`t${this.target.task} wake`); + this.target.schedule(); + } + + wakeByRef(): void { + this.wake(); + } + + clone(): Waker { + this.target.log.note(`t${this.target.task} waker clone`); + return new TaskWaker(this.target); + } + + willWake(other: Waker): boolean { + return other instanceof TaskWaker && other.target === this.target; + } + + [Symbol.dispose](): void { + this.target.log.note(`t${this.target.task} waker drop`); + } +} + +interface Task { + future: Future; + waker: Waker; + wake: Wake; + done: boolean; +} + +/** Runs tasks in the order they were woken. */ +class Executor { + readonly queue: number[] = []; + /** Every task spawned, by id; `undefined` once dropped. */ + readonly tasks: (Task | undefined)[] = []; + readonly log: Log; + readonly pending: symbol; + + constructor(log: Log, pending: symbol) { + this.log = log; + this.pending = pending; + } + + spawn(future: Future): void { + const task = this.tasks.length; + this.log.note(`t${task} spawn`); + const wake = new Wake(task, this.log, this.queue); + wake.schedule(); + this.tasks.push({ future, waker: new TaskWaker(wake), wake, done: false }); + } + + run(): void { + while (this.step()); + } + + step(): boolean { + const task = this.queue.shift(); + if (task === undefined) return false; + const t = this.tasks[task]; + if (t !== undefined && !t.done) this.poll(task); + return true; + } + + poll(task: number): void { + const t = this.tasks[task]; + if (t === undefined) return; + t.wake.queued = false; + this.log.note(`t${task} poll`); + const output = t.future.poll(t.waker); + if (output === this.pending) { + this.log.note(`t${task} pending`); + } else { + t.done = true; + this.log.note(`t${task} ready ${String(output)}`); + } + } + + drop(task: number): void { + const t = this.tasks[task]; + if (t === undefined) return; + this.tasks[task] = undefined; + this.log.note(`t${task} drop`); + t.future[Symbol.dispose](); + t.waker[Symbol.dispose](); + } +} + +/** The script runner, as `harness.rs` runs it natively. */ +export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array } { + return (input) => { + const log = f.Log.new(); + const exec = new Executor(log, f.Pending); + const channels: Channel[] = []; + for (let i = 0; i < input.length; i += 2) { + const op = input[i]; + const arg = input[i + 1] ?? 0; + const pick = (len: number) => (len > 0 ? arg % len : undefined); + const c = pick(channels.length); + switch (op % 10) { + case 0: + log.note(`c${channels.length} open`); + channels.push(f.Channel.open()); + break; + case 1: + if (c !== undefined) exec.spawn(f.sum(channels[c].consumer(), f.Guard.new(exec.tasks.length, log.clone()))); + break; + case 2: + if (c !== undefined) exec.spawn(f.drain(channels[c].consumer(), [1, 4, 16][(arg >> 4) % 3])); + break; + case 3: + if (c !== undefined) { + log.note(`c${c} send ${arg}`); + if (!channels[c].send(BigInt(arg))) log.note(`c${c} closed`); + } + break; + case 4: + if (c !== undefined) { + log.note(`c${c} close`); + channels[c].close(); + } + break; + case 5: + if (c !== undefined) { + log.note(`c${c} clone`); + channels[c].cloneProducer(); + } + break; + case 6: + exec.run(); + break; + case 7: + exec.step(); + break; + case 8: { + const t = pick(exec.tasks.length); + if (t !== undefined) exec.poll(t); + break; + } + default: { + const t = pick(exec.tasks.length); + if (t !== undefined) exec.drop(t); + } + } + } + for (let t = 0; t < exec.tasks.length; t++) exec.drop(t); + channels.forEach((channel, c) => { + log.note(`c${c} drop`); + channel[Symbol.dispose](); + }); + return log.text(); + }; +} + +/** Scripts for the cases async must get right, run before the random ones. */ +export const cases: Uint8Array[] = [ + // A future dropped before its first poll runs nothing, and drops its arguments. + [0, 0, 1, 0, 2, 0, 9, 0, 9, 1], + // One dropped mid-await drops its awaited future, then its locals, then its arguments. + [0, 0, 1, 0, 6, 0, 3, 5, 6, 0, 9, 0], + // Polling a future after it returned `Ready` panics. + [0, 0, 1, 0, 6, 0, 4, 0, 6, 0, 8, 0], + // Every await depth, woken by sends and the channel closing. + [0, 0, 2, 0, 2, 16, 2, 32, 6, 0, 3, 7, 6, 0, 3, 9, 7, 0, 4, 0, 6, 0], + // The channel stays open until its last producer drops. + [0, 0, 1, 0, 5, 0, 4, 0, 6, 0, 3, 2, 4, 0, 6, 0], + // A task woken twice before its poll is queued once. + [0, 0, 0, 1, 1, 0, 1, 1, 6, 0, 3, 1, 5, 0, 3, 2, 6, 0], +].map((script) => Uint8Array.from(script)); From e4c2dc2f574c613a7a398af0d34eb7a6b82953ad Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:43:56 -0700 Subject: [PATCH 03/30] wip(ts): async spike, MIR state machine prototype Both prototypes pass the task fixture's trace differential test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/rustc-ice-2026-10-24T06_41_29-465125.txt | 89 ++ ts/src/driver.rs | 6 + ts/src/lower/body.rs | 30 + ts/src/lower/fmt.rs | 8 +- ts/src/lower/mir.rs | 998 ++++++++++++++++++++ ts/src/lower/mod.rs | 5 + ts/src/print.rs | 40 + ts/src/ts.rs | 6 + ts/tests/fixtures.rs | 32 +- 9 files changed, 1208 insertions(+), 6 deletions(-) create mode 100644 ts/rustc-ice-2026-10-24T06_41_29-465125.txt create mode 100644 ts/src/lower/mir.rs diff --git a/ts/rustc-ice-2026-10-24T06_41_29-465125.txt b/ts/rustc-ice-2026-10-24T06_41_29-465125.txt new file mode 100644 index 000000000..04e70b9c9 --- /dev/null +++ b/ts/rustc-ice-2026-10-24T06_41_29-465125.txt @@ -0,0 +1,89 @@ +thread 'rustc' panicked at src/lower/mir.rs:512:28: +Box +stack backtrace: + 0: 0x73b3b7a28975 - ::create + 1: 0x73b3b7a288c5 - ::force_capture + 2: 0x73b3b67df9ea - std[76053f7ab5f7f410]::panicking::update_hook::>::{closure#0} + 3: 0x73b3b7a3ea82 - std[76053f7ab5f7f410]::panicking::panic_with_hook + 4: 0x73b3b75d71c0 - std[76053f7ab5f7f410]::panicking::begin_panic::::{closure#0} + 5: 0x73b3b75d522e - std[76053f7ab5f7f410]::sys::backtrace::__rust_end_short_backtrace::::{closure#0}, !> + 6: 0x73b3b75d5202 - std[76053f7ab5f7f410]::panicking::begin_panic:: + 7: 0x73b3b3a226c1 - rustc_span[84be90fd7ae9529b]::macros::bug_impl + 8: 0x582d28d52a8b - >::type_at::{closure#0} + at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/rustc-src/rust/compiler/rustc_middle/src/ty/generic_args.rs:542:16 + 9: 0x582d28d54f88 - >::unwrap_or_else::<>::type_at::{closure#0}> + at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/src/rust/library/core/src/option.rs:1067:21 + 10: 0x582d28d54f88 - >::type_at + at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/rustc-src/rust/compiler/rustc_middle/src/ty/generic_args.rs:540:27 + 11: 0x582d28e843ca - ::call + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:512:19 + 12: 0x582d28e8084d - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:430:22 + 13: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 14: 0x582d28e85500 - ::jump + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 + 15: 0x582d28e80fb4 - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:398:11 + 16: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 17: 0x582d28e85500 - ::jump + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 + 18: 0x582d28e817be - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:421:10 + 19: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 20: 0x582d28e85500 - ::jump + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 + 21: 0x582d28e80fb4 - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:398:11 + 22: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 23: 0x582d28e85500 - ::jump + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 + 24: 0x582d28e81c4b - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:447:11 + 25: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 26: 0x582d28e85500 - ::jump + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 + 27: 0x582d28e81c4b - ::terminator + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:447:11 + 28: 0x582d28e857a9 - ::block + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 + 29: 0x582d28e86bc0 - ::lower + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:270:9 + 30: 0x582d28e955cd - rust2_ts[d61b199175b2cdd0]::lower::mir::coroutine + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:102:66 + 31: 0x582d28cf0f70 - ::closure + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:2287:11 + 32: 0x582d28ce3b54 - ::expr + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:1978:39 + 33: 0x582d28ce7147 - ::stmt + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:414:22 + 34: 0x582d28ce769c - ::stmt + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:374:15 + 35: 0x582d28d0a211 - rust2_ts[d61b199175b2cdd0]::lower::body::function + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:122:4 + 36: 0x582d28e2259d - ::function + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:926:18 + 37: 0x582d28e1e2c8 - ::drain + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:243:10 + 38: 0x582d28e26e6d - rust2_ts[d61b199175b2cdd0]::lower::translate + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:63:4 + 39: 0x582d28e981ee - ::after_expansion + at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/driver.rs:99:30 + 40: 0x73b3b93067e6 - rustc_interface[428b96e9abb7cc47]::interface::run_compiler::<(), rustc_driver_impl[ab3368f39572c260]::compiler_entrypoint::{closure#0}>::{closure#2} + 41: 0x73b3b9330764 - std[76053f7ab5f7f410]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> + 42: 0x73b3b93304ff - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[68f4be281c81bf45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} + 43: 0x73b3b932d81b - ::new::thread_start + 44: 0x73b3b229f751 - start_thread + 45: 0x73b3b232ba4c - __clone3 + 46: 0x0 - + + +rustc version: 1.101.0-nightly (7df81381d 2026-10-14) +platform: x86_64-unknown-linux-gnu + +query stack during panic: +end of query stack diff --git a/ts/src/driver.rs b/ts/src/driver.rs index 6694e2406..56db71966 100644 --- a/ts/src/driver.rs +++ b/ts/src/driver.rs @@ -81,6 +81,12 @@ impl Translate { } impl Callbacks for Translate { + fn config(&mut self, config: &mut rustc_interface::interface::Config) { + // The async spike's state machines read MIR as the coroutine transform leaves it, + // before any optimization inlines std into it. + config.opts.unstable_opts.mir_opt_level = Some(0); + } + fn after_expansion<'tcx>(&mut self, _compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation { // Copy each body's THIR before borrow checking steals it. let bodies = lower::Bodies::collect(tcx); diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 35b981ec2..747b7a910 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -2274,6 +2274,36 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span, out: &mut Vec) -> Expr { let tcx = self.t.tcx; let local = closure.closure_id; + // The async spike's state machine prototype: the body from MIR. + if self.t.async_mir && tcx.coroutine_is_async(local.to_def_id()) { + let ty = self.subst(tcx.type_of(local).instantiate_identity().skip_norm_wip()); + for capture in tcx.closure_captures(local) { + if let Some(Local::Name { name, .. }) = self.locals.get(&capture.get_root_variable()) { + let name = name.clone(); + self.disown(&name); + } + } + let upvars = self.operands(&closure.upvars, out); + return super::mir::coroutine(self, local, ty, upvars, span); + } + self.lower_closure(local, span, out) + } + + /// Bind the variable `var`, which a closure body reads as an upvar, to `name`. + pub(super) fn bind_upvar(&mut self, var: HirId, name: String) { + self.names.insert(name.clone()); + self.locals.insert(var, Local::Name { name, mutable: false }); + } + + /// A closure as an arrow function, or an `async` body as a future around a generator, + /// reading its upvars as the variables they were bound to. + pub(super) fn lower_closure( + &mut self, + local: rustc_hir::def_id::LocalDefId, + span: Span, + out: &mut Vec, + ) -> Expr { + let tcx = self.t.tcx; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); }; diff --git a/ts/src/lower/fmt.rs b/ts/src/lower/fmt.rs index 9226e6883..9edb55d72 100644 --- a/ts/src/lower/fmt.rs +++ b/ts/src/lower/fmt.rs @@ -421,7 +421,7 @@ pub fn std_impl<'tcx>( } /// One part of a `format_args!` template. -enum Piece { +pub(super) enum Piece { Lit(String), /// A placeholder writing the `index`th argument. Arg { @@ -431,7 +431,7 @@ enum Piece { } /// A placeholder's options, from `FormattingOptions`' flags. -struct Spec { +pub(super) struct Spec { fill: char, align: Option, alternate: bool, @@ -441,7 +441,7 @@ struct Spec { impl Spec { /// The runtime's `Spec` object, or `None` for the defaults. - fn object(&self) -> Option { + pub(super) fn object(&self) -> Option { let mut props = Vec::new(); if self.fill != ' ' { props.push(("fill", Expr::Str(self.fill.to_string()))); @@ -476,7 +476,7 @@ const DEFAULT_FLAGS: u32 = ' ' as u32 | 3 << 29; /// Decode a template as `core::fmt::write` reads it: literal pieces, and placeholders /// with their argument and options. An option outside the subset is an error naming it. -fn decode(template: &[u8]) -> Result, &'static str> { +pub(super) fn decode(template: &[u8]) -> Result, &'static str> { const TRUNCATED: &str = "a truncated template"; let byte = |i: usize| template.get(i).copied().ok_or(TRUNCATED); let u16_at = |i: usize| Ok::<_, &str>(u16::from_le_bytes([byte(i)?, byte(i + 1)?])); diff --git a/ts/src/lower/mir.rs b/ts/src/lower/mir.rs new file mode 100644 index 000000000..28ac234a0 --- /dev/null +++ b/ts/src/lower/mir.rs @@ -0,0 +1,998 @@ +//! The async spike's state machine prototype: an `async` body lowered from MIR after +//! rustc's coroutine transform. Its future is a class whose fields are its state, its +//! upvars, and its saved locals; `poll` is the transform's resume function and the +//! dispose its drop shim, each a loop over a `switch` on the basic block. Types, calls, +//! drops, formatting, and closures go through the THIR lowering's own. + +use rustc_abi::{FieldIdx, VariantIdx}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_hir::def_id::LocalDefId; +use rustc_index::IndexVec; +use rustc_middle::mir::interpret::Scalar; +use rustc_middle::mir::visit::{PlaceContext, Visitor}; +use rustc_middle::mir::{ + self, AggregateKind, AssertKind, BasicBlock, BinOp, CastKind, ConstValue, CoroutineSavedLocal, Local, Operand, + Place, ProjectionElem, Rvalue, StatementKind, TerminatorKind, UnOp, +}; +use rustc_middle::ty::{self, Ty}; +use rustc_span::Span; + +use super::body::Body; +use super::fmt::{self, Piece, Trait}; +use super::library::{Args, Std}; +use super::num::{self, Int}; +use super::{AdtRepr, camel}; +use crate::program::{SymKind, Symbol}; +use crate::ts::{self, Ctor, Expr, FieldId, Key, Param, Stmt, StmtKind, SymId, Type}; + +/// The class of one `async` body's future, by the role of each field. +struct Class<'tcx> { + sym: SymId, + def_id: LocalDefId, + state: FieldId, + upvars: Vec, + saved: IndexVec, + layout: &'tcx mir::CoroutineLayout<'tcx>, +} + +/// The future of the `async` body `def_id`, a `ty`, capturing `upvars`: its class is +/// translated here, and this is a new instance of it. +pub fn coroutine<'tcx>( + b: &mut Body<'_, '_, 'tcx>, + def_id: LocalDefId, + ty: Ty<'tcx>, + upvars: Vec, + span: Span, +) -> Expr { + let tcx = b.t.tcx; + let ty::Coroutine(_, args) = *ty.kind() else { + return b.err(span, format!("an async body of type `{ty}`")); + }; + let Ok(layout) = tcx.coroutine_layout(def_id.to_def_id(), args) else { + return b.err(span, "an async body without a layout"); + }; + let parent = tcx.typeck_root_def_id(def_id.to_def_id()); + let name = pascal(&camel(tcx.item_name(parent).as_str())); + let order = b.t.order(tcx.def_span(def_id)); + let class = b.t.program.sym(Symbol { + module: b.t.module_of(parent), + base: format!("{name}Future"), + suffix: String::new(), + owner: None, + kind: SymKind::Class, + order, + name: String::new(), + }); + let mut fields = Vec::new(); + let state = b.t.program.field(class, "state".into()); + fields.push(ts::Field { + id: state, + ty: Type::Builtin("number"), + doc: Some("Which await it is suspended at, as the coroutine transform numbers them.".into()), + }); + let mut upvar_fields = Vec::new(); + let captures = tcx.closure_captures(def_id); + for (i, upvar) in args.as_coroutine().upvar_tys().iter().enumerate() { + let base = captures + .get(i) + .map_or(format!("upvar{i}"), |c| camel(c.to_symbol().as_str())); + let id = b.t.program.field(class, base); + let ty = local_type(b, upvar, span); + fields.push(ts::Field { id, ty, doc: None }); + upvar_fields.push(id); + } + let mut saved = IndexVec::new(); + for (local, field) in layout.field_tys.iter_enumerated() { + let id = b.t.program.field(class, format!("s{}", local.as_usize())); + let ty = local_type(b, b.subst(field.ty), span); + fields.push(ts::Field { id, ty, doc: None }); + saved.push(id); + } + let info = Class { + sym: class, + def_id, + state, + upvars: upvar_fields, + saved, + layout, + }; + b.t.program.items.push(ts::Item::Class { + sym: class, + params: Vec::new(), + fields, + ctor: Ctor::Named, + doc: Some(format!( + "The future of `{}`, as a state machine.", + tcx.def_path_str(parent) + )), + }); + + let body = tcx.optimized_mir(def_id); + let ret = b.subst(args.as_coroutine().return_ty()); + let poll_ret = Type::Rt("Poll", vec![local_type(b, ret, span)]); + let cx = "cx".to_string(); + let poll_body = Lowering::new(b, body, &info, Some(cx.clone())).lower(); + let mut methods = vec![( + "poll", + vec![Param { + name: cx, + ty: Some(Type::Rt("Context", vec![])), + }], + poll_ret, + poll_body, + )]; + match body.coroutine_drop() { + Some(drop) => { + let dispose = Lowering::new(b, drop, &info, None).lower(); + methods.push(("[Symbol.dispose]", Vec::new(), Type::Builtin("void"), dispose)); + } + None => b.t.err(span, "an async body without a drop shim"), + } + for (name, params, ret, body) in methods { + let sym = b.t.program.sym(Symbol { + module: b.t.module_of(parent), + base: name.into(), + suffix: String::new(), + owner: Some(class), + kind: SymKind::Method { instance: true }, + order, + name: String::new(), + }); + b.t.program.methods.entry(class).or_default().push(ts::Function { + sym, + method: true, + params, + ret, + body, + loc: None, + doc: None, + }); + } + + let mut props = vec![(Key::Field(state), Expr::lit("0"))]; + for (&id, value) in info.upvars.iter().zip(upvars) { + props.push((Key::Field(id), value)); + } + for &id in &info.saved { + props.push((Key::Field(id), Expr::lit("undefined!"))); + } + Expr::New(Box::new(Expr::Sym(class)), vec![Expr::Object(props)]) +} + +/// The TypeScript type of a local, for the types only MIR has. +fn local_type<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Type { + match ty.kind() { + ty::Adt(adt, args) => match super::library::std_path(b.t.tcx, adt.did()).last().map(String::as_str) { + Some("NonNull") => local_type(b, args.type_at(0), span), + Some("Argument") => Type::Rt("Fmt", vec![]), + _ => b.t.ty(ty, span), + }, + ty::Array(elem, _) | ty::Slice(elem) if is_argument(b, *elem) => Type::Array(Box::new(Type::Rt("Fmt", vec![]))), + ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => match inner.kind() { + ty::Array(elem, _) | ty::Slice(elem) if is_argument(b, *elem) => { + Type::Array(Box::new(Type::Rt("Fmt", vec![]))) + } + ty::Coroutine(..) => local_type(b, *inner, span), + _ => b.t.ty(ty, span), + }, + _ => b.t.ty(ty, span), + } +} + +/// Whether `ty` is `core::fmt::rt::Argument`. +fn is_argument<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { + match ty.kind() { + ty::Adt(adt, _) => super::library::std_path(b.t.tcx, adt.did()) == ["fmt", "rt", "Argument"], + _ => false, + } +} + +fn pascal(name: &str) -> String { + let mut chars = name.chars(); + chars + .next() + .map_or_else(String::new, |c| c.to_uppercase().chain(chars).collect()) +} + +/// One MIR body of a coroutine's class, lowered to a method's statements. +struct Lowering<'m, 'b, 'a, 'tcx> { + b: &'m mut Body<'b, 'a, 'tcx>, + mir: &'tcx mir::Body<'tcx>, + class: &'m Class<'tcx>, + /// The method's parameter for `_2`, the context a resume is given. + cx: Option, + /// Locals some statement reads, which are the only ones declared. + read: FxHashSet, + /// Locals holding a byte string, a `format_args!` template. + bytes: FxHashMap>, + /// How many edges reach each block. + preds: IndexVec, + span: Span, +} + +impl<'m, 'b, 'a, 'tcx> Lowering<'m, 'b, 'a, 'tcx> { + fn new( + b: &'m mut Body<'b, 'a, 'tcx>, + mir: &'tcx mir::Body<'tcx>, + class: &'m Class<'tcx>, + cx: Option, + ) -> Self { + // Cleanup blocks run only as a panic unwinds, which a JS exception never stops + // for: the target panics by aborting. + let mut preds = IndexVec::from_elem_n(0, mir.basic_blocks.len()); + for data in mir.basic_blocks.iter().filter(|data| !data.is_cleanup) { + for target in data.terminator().successors() { + preds[target] += 1; + } + } + let mut bytes = FxHashMap::default(); + for data in mir.basic_blocks.iter() { + for stmt in &data.statements { + let StatementKind::Assign(assign) = &stmt.kind else { + continue; + }; + let (place, rvalue) = &**assign; + let Some(local) = place.as_local() else { + continue; + }; + match rvalue { + Rvalue::Use(Operand::Constant(c), _) => { + if let Some(found) = const_bytes(b.t.tcx, c) { + bytes.insert(local, found); + } + } + Rvalue::Ref(_, _, from) if from.projection.as_slice() == [ProjectionElem::Deref] => { + if let Some(found) = bytes.get(&from.local).cloned() { + bytes.insert(local, found); + } + } + _ => {} + } + } + } + let mut reads = Reads(FxHashSet::default()); + reads.visit_body(mir); + let read = reads.0.into_iter().filter(|local| !bytes.contains_key(local)).collect(); + Self { + b, + mir, + class, + cx, + read, + bytes, + preds, + span: mir.span, + } + } + + fn tcx(&self) -> ty::TyCtxt<'tcx> { + self.b.t.tcx + } + + fn err(&mut self, msg: impl Into) -> Expr { + let span = self.span; + self.b.err(span, msg) + } + + fn local_ty(&self, local: Local) -> Ty<'tcx> { + self.b.subst(self.mir.local_decls[local].ty) + } + + /// The method's statements: each local declared, then the dispatch loop. + fn lower(mut self) -> Vec { + let mut cases = Vec::new(); + for (block, data) in self.mir.basic_blocks.iter_enumerated() { + if data.is_cleanup || self.inlined(block) { + continue; + } + let mut body = Vec::new(); + self.block(block, &mut body); + cases.push((Expr::lit(block.as_usize().to_string()), body)); + } + let mut out = Vec::new(); + for (local, decl) in self.mir.local_decls.iter_enumerated() { + let arg = (1..=self.mir.arg_count).contains(&local.as_usize()); + if arg || !self.read.contains(&local) { + continue; + } + let ty = self.b.subst(decl.ty); + if ty.is_unit() { + continue; + } + let span = self.span; + // The coroutine itself, which only its own class has fields for. + let ts = match ty.builtin_deref(true).unwrap_or(ty).kind() { + ty::Coroutine(def_id, _) if *def_id == self.class.def_id.to_def_id() => { + Type::Sym(self.class.sym, Vec::new()) + } + _ => local_type(self.b, ty, span), + }; + out.push(StmtKind::decl(true, name(local), Some(ts), Some(Expr::lit("undefined!"))).at(None)); + } + out.push(StmtKind::decl(true, "bb", Some(Type::Builtin("number")), Some(Expr::lit("0"))).at(None)); + out.push( + StmtKind::While { + label: None, + cond: Expr::lit("true"), + body: vec![ + StmtKind::Switch { + value: Expr::ident("bb"), + cases, + default: Vec::new(), + } + .at(None), + ], + } + .at(None), + ); + out + } + + /// Whether `block` is lowered where its one predecessor jumps to it, not as a case. + fn inlined(&self, block: BasicBlock) -> bool { + block != mir::START_BLOCK && self.preds[block] == 1 + } + + /// Control to `target`: inline if only this edge reaches it. + fn jump(&mut self, target: BasicBlock, out: &mut Vec) { + if self.inlined(target) { + self.block(target, out); + return; + } + out.push(StmtKind::Expr(Expr::ident("bb").assign(Expr::lit(target.as_usize().to_string()))).at(None)); + out.push(StmtKind::Continue(None).at(None)); + } + + fn block(&mut self, block: BasicBlock, out: &mut Vec) { + let data = &self.mir.basic_blocks[block]; + for stmt in &data.statements { + self.span = stmt.source_info.span; + self.statement(&stmt.kind, out); + } + let terminator = data.terminator(); + self.span = terminator.source_info.span; + self.terminator(&terminator.kind, out); + } + + fn statement(&mut self, kind: &StatementKind<'tcx>, out: &mut Vec) { + match kind { + StatementKind::Assign(assign) => { + let (place, rvalue) = &**assign; + if place + .as_local() + .is_some_and(|local| !self.read.contains(&local) || self.bytes.contains_key(&local)) + { + return; + } + if self.b.subst(place.ty(self.mir, self.tcx()).ty).is_unit() { + return; + } + let value = self.rvalue(rvalue, out); + let target = self.place(place, out); + out.push(StmtKind::Expr(target.assign(value)).at(None)); + } + StatementKind::SetDiscriminant { place, variant_index } => { + let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); + match ty.kind() { + ty::Coroutine(..) => { + let target = self.place(place, out).field(self.class.state); + out.push( + StmtKind::Expr(target.assign(Expr::lit(variant_index.as_usize().to_string()))).at(None), + ); + } + _ => { + self.err(format!("setting the discriminant of `{ty}`")); + } + } + } + StatementKind::StorageLive(_) + | StatementKind::StorageDead(_) + | StatementKind::Nop + | StatementKind::FakeRead(_) + | StatementKind::PlaceMention(_) + | StatementKind::AscribeUserType(..) + | StatementKind::Coverage(_) + | StatementKind::ConstEvalCounter + | StatementKind::BackwardIncompatibleDropHint { .. } => {} + StatementKind::Intrinsic(_) => { + self.err("an intrinsic"); + } + } + } + + fn terminator(&mut self, kind: &TerminatorKind<'tcx>, out: &mut Vec) { + match kind { + TerminatorKind::Goto { target, .. } => self.jump(*target, out), + TerminatorKind::FalseEdge { real_target, .. } | TerminatorKind::FalseUnwind { real_target, .. } => { + self.jump(*real_target, out) + } + TerminatorKind::SwitchInt { discr, targets } => { + let ty = self.b.subst(discr.ty(self.mir, self.tcx())); + let value = self.operand(discr, out); + let value = match value.is_path() { + true => value, + false => self.b.spill(value, "value", out), + }; + let mut els = Vec::new(); + self.jump(targets.otherwise(), &mut els); + let arms: Vec<(u128, BasicBlock)> = targets.iter().collect(); + for (bits, target) in arms.into_iter().rev() { + let test = match ty.kind() { + ty::Bool if bits == 0 => value.clone().not(), + ty::Bool => value.clone(), + _ => match Int::of(ty) { + Some(int) => value.clone().binary("===", int.lit(bits as i128)), + None => self.err(format!("a switch on `{ty}`")), + }, + }; + let mut then = Vec::new(); + self.jump(target, &mut then); + els = vec![StmtKind::If { cond: test, then, els }.at(None)]; + } + out.extend(els); + } + TerminatorKind::Return => { + let ret = self.local_ty(mir::RETURN_PLACE); + match ret.is_unit() { + true => out.push(StmtKind::Return(None).at(None)), + false => out.push(StmtKind::Return(Some(Expr::ident(name(mir::RETURN_PLACE)))).at(None)), + } + } + TerminatorKind::Unreachable => { + let panic = Expr::rt( + "panic", + vec![Expr::Str("internal error: entered unreachable code".into())], + ); + out.push(StmtKind::Expr(panic).at(None)); + } + TerminatorKind::Drop { place, target, .. } => { + let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); + let value = self.place(place, out); + let span = self.span; + if let Some(dropped) = self.b.t.drop_value(value, ty, span) { + out.push(StmtKind::Expr(dropped).at(None)); + } + self.jump(*target, out); + } + TerminatorKind::Call { + func, + args, + destination, + target, + .. + } => { + let value = self.call(func, args, out); + let dest_ty = self.b.subst(destination.ty(self.mir, self.tcx()).ty); + let unread = destination + .as_local() + .is_some_and(|local| !self.read.contains(&local) || self.bytes.contains_key(&local)); + match unread || dest_ty.is_unit() || dest_ty.is_never() { + true => { + if !value.is_path() { + out.push(StmtKind::Expr(value).at(None)); + } + } + false => { + let target = self.place(destination, out); + out.push(StmtKind::Expr(target.assign(value)).at(None)); + } + } + if let Some(target) = target { + self.jump(*target, out); + } + } + TerminatorKind::Assert { + cond, + expected, + msg, + target, + .. + } => { + // A checked operation, an index, or a division panics on its own, with + // the message its assert has. + let message = match &**msg { + AssertKind::ResumedAfterReturn(_) => Some("`async fn` resumed after completion"), + AssertKind::ResumedAfterPanic(_) => Some("`async fn` resumed after panicking"), + AssertKind::ResumedAfterDrop(_) => Some("`async fn` resumed after async drop"), + _ => None, + }; + if let Some(message) = message { + let value = self.operand(cond, out); + let test = match expected { + true => value.not(), + false => value, + }; + out.push( + StmtKind::If { + cond: test, + then: vec![StmtKind::Expr(Expr::rt("panic", vec![Expr::Str(message.into())])).at(None)], + els: Vec::new(), + } + .at(None), + ); + } + self.jump(*target, out); + } + _ => { + self.err(format!("unsupported terminator {kind:?}")); + } + } + } + + fn call(&mut self, func: &Operand<'tcx>, args: &[rustc_span::Spanned>], out: &mut Vec) -> Expr { + let tcx = self.tcx(); + let fn_ty = self.b.subst(func.ty(self.mir, tcx)); + let ty::FnDef(def_id, gargs) = *fn_ty.kind() else { + return self.err(format!("a call through `{fn_ty}`")); + }; + let gargs = gargs.skip_binder(); + let key = super::library::key(tcx, def_id); + let key = key.as_ref().map(|(owner, name)| (owner.as_str(), name.as_str())); + let span = self.span; + // `format_args!`, as MIR has it: its arguments, then its template around them. + if let Some(("Argument", name)) = key { + let tr = match name { + "new_display" => Trait::Display, + "new_debug" => Trait::Debug, + "new_lower_hex" => Trait::LowerHex, + "new_upper_hex" => Trait::UpperHex, + _ => return self.err(format!("`Argument::{name}`")), + }; + let Some(ty) = gargs.types().next() else { + return self.err("an `Argument` without a type"); + }; + let value = self.operand(&args[0].node, out); + return self.b.fmt_value(tr, ty, value, span, out); + } + if let Some(("Arguments", "new")) = key { + let template = match &args[0].node { + Operand::Copy(place) | Operand::Move(place) => { + place.as_local().and_then(|l| self.bytes.get(&l).cloned()) + } + Operand::Constant(c) => const_bytes(tcx, c), + _ => None, + }; + let Some(template) = template else { + return self.err("a `format_args!` template that is not a constant"); + }; + let arguments = self.operand(&args[1].node, out); + let arguments = match arguments.is_path() { + true => arguments, + false => self.b.spill(arguments, "args", out), + }; + let pieces = match fmt::decode(&template) { + Ok(pieces) => pieces, + Err(msg) => return self.err(format!("{msg} is not supported")), + }; + let mut parts = Vec::new(); + for piece in pieces { + parts.push(match piece { + Piece::Lit(s) => Expr::Str(s), + Piece::Arg { index, spec } => { + let value = arguments.clone().index(Expr::lit(index.to_string())); + match spec.object() { + Some(spec) => Expr::Rt("fmt").member("spec").call(vec![spec, value]), + None => value, + } + } + }); + } + return Expr::Array(parts); + } + let mut values = Vec::new(); + for arg in args { + let value = self.operand(&arg.node, out); + values.push(value); + } + // Lowered left to right: an earlier value a later one's statements could change is saved. + self.b.call_def(def_id, gargs, Args::Values(values), span, out) + } + + fn rvalue(&mut self, rvalue: &Rvalue<'tcx>, out: &mut Vec) -> Expr { + let tcx = self.tcx(); + let span = self.span; + match rvalue { + Rvalue::Use(op, _) => self.operand(op, out), + Rvalue::Ref(..) | Rvalue::Reborrow(..) => { + let (mutability, place) = match rvalue { + Rvalue::Ref(_, kind, place) => (kind.mutability(), place), + Rvalue::Reborrow(_, mutability, place) => (*mutability, place), + _ => unreachable!(), + }; + let pointee = self.b.subst(place.ty(self.mir, tcx).ty); + if mutability.is_mut() && self.b.t.object_kind(pointee).is_none() { + return self.err(format!( + "a mutable reference to `{pointee}`, which is no object it can change in place" + )); + } + self.place(place, out) + } + Rvalue::CopyForDeref(place) => self.place(place, out), + Rvalue::Cast(kind, op, to) => { + let to = self.b.subst(*to); + let from = self.b.subst(op.ty(self.mir, tcx)); + let value = self.operand(op, out); + match kind { + CastKind::IntToInt => num::cast( + self.b, + num::Operand { + expr: value, + value: None, + }, + from, + to, + span, + ), + // A context's pointer, as `.await` passes it around. + CastKind::Transmute | CastKind::PtrToPtr if context_like(tcx, from) && context_like(tcx, to) => { + value + } + CastKind::PointerCoercion(..) | CastKind::Subtype => value, + _ => self.err(format!("a {kind:?} cast from `{from}` to `{to}`")), + } + } + Rvalue::BinaryOp(op, operands) => { + let (l, r) = &**operands; + let lty = self.b.subst(l.ty(self.mir, tcx)); + let rty = self.b.subst(r.ty(self.mir, tcx)); + let lv = self.operand(l, out); + let rv = self.operand(r, out); + // A checked operation panics itself, so its overflow flag is always false. + let (op, checked) = match op { + BinOp::AddWithOverflow => (BinOp::Add, true), + BinOp::SubWithOverflow => (BinOp::Sub, true), + BinOp::MulWithOverflow => (BinOp::Mul, true), + op => (*op, false), + }; + let value = match (lty.kind(), op) { + (ty::Int(_) | ty::Uint(_), _) | (ty::Bool, BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor) => { + num::binary( + self.b, + op, + num::Operand { expr: lv, value: None }, + num::Operand { expr: rv, value: None }, + lty, + rty, + span, + ) + } + (_, BinOp::Eq) => lv.binary("===", rv), + (_, BinOp::Ne) => lv.binary("!==", rv), + _ => self.err(format!("`{op:?}` on `{lty}`")), + }; + match checked { + true => Expr::Array(vec![value, Expr::lit("false")]), + false => value, + } + } + Rvalue::UnaryOp(op, operand) => { + let ty = self.b.subst(operand.ty(self.mir, tcx)); + let value = self.operand(operand, out); + match op { + UnOp::Not | UnOp::Neg => num::unary(self.b, *op, value, ty, span), + UnOp::PtrMetadata => self.err("pointer metadata"), + } + } + Rvalue::Discriminant(place) => { + let ty = self.b.subst(place.ty(self.mir, tcx).ty); + let value = self.place(place, out); + self.discriminant(value, ty) + } + Rvalue::Aggregate(kind, operands) => self.aggregate(kind, operands, out), + _ => self.err(format!("unsupported rvalue {rvalue:?}")), + } + } + + /// The variant index of `value`, a `ty`. + fn discriminant(&mut self, value: Expr, ty: Ty<'tcx>) -> Expr { + let tcx = self.tcx(); + match ty.kind() { + ty::Coroutine(..) => value.field(self.class.state), + ty::Adt(adt, _) => match Std::of(tcx, adt.did()) { + Some(Std::Option) => Expr::Cond( + Box::new(value.binary("===", Expr::undefined())), + Box::new(Expr::lit("0")), + Box::new(Expr::lit("1")), + ), + Some(Std::Poll) => Expr::Cond( + Box::new(value.binary("===", Expr::Rt("Pending"))), + Box::new(Expr::lit("1")), + Box::new(Expr::lit("0")), + ), + Some(Std::Result) => Expr::Cond( + Box::new(value.member("ok")), + Box::new(Expr::lit("0")), + Box::new(Expr::lit("1")), + ), + _ => self.err(format!("the discriminant of `{ty}`")), + }, + _ => self.err(format!("the discriminant of `{ty}`")), + } + } + + fn aggregate( + &mut self, + kind: &AggregateKind<'tcx>, + operands: &IndexVec>, + out: &mut Vec, + ) -> Expr { + let tcx = self.tcx(); + let span = self.span; + match kind { + AggregateKind::Tuple if operands.is_empty() => Expr::undefined(), + AggregateKind::Tuple | AggregateKind::Array(_) => { + let values = operands.iter().map(|op| self.operand(op, out)).collect(); + Expr::Array(values) + } + AggregateKind::Adt(did, variant, gargs, _, None) => { + let gargs = self.b.subst(*gargs); + let mut values: Vec = operands.iter().map(|op| self.operand(op, out)).collect(); + let adt = tcx.adt_def(*did); + if context_like(tcx, tcx.type_of(*did).instantiate(tcx, gargs).skip_norm_wip()) || is_resume(tcx, *did) + { + return values.pop().unwrap_or_else(Expr::undefined); + } + match (Std::of(tcx, *did), variant.as_usize()) { + (Some(Std::Option), 0) => return Expr::undefined(), + (Some(Std::Option), _) | (Some(Std::Poll), 0) => { + return values.pop().unwrap_or_else(Expr::undefined); + } + (Some(Std::Poll), _) => return Expr::Rt("Pending"), + (Some(Std::Result), 0) => return Expr::rt("Ok", values), + (Some(Std::Result), _) => return Expr::rt("Err", values), + (Some(_), _) => return self.err(format!("constructing `{}`", tcx.def_path_str(*did))), + (None, _) => {} + } + let info = self.b.t.adt(adt, span); + let ty = tcx.type_of(*did).instantiate(tcx, gargs).skip_norm_wip(); + let def = adt.variant(*variant); + match info.repr { + AdtRepr::Class { ctor, fields } => match ctor { + Ctor::Unit => Expr::New(Box::new(Expr::Sym(info.sym)), Vec::new()), + Ctor::Positional => Expr::New( + Box::new(Expr::Sym(info.sym)), + values.into_iter().map(Expr::typed).collect(), + ), + Ctor::Named => { + let props = fields + .iter() + .zip(values) + .map(|(&id, value)| (Key::Field(id), value.typed())) + .collect(); + Expr::New(Box::new(Expr::Sym(info.sym)), vec![Expr::Object(props)]) + } + }, + AdtRepr::Tags => { + let ts = self.b.t.ty(ty, span); + Expr::As(Box::new(Expr::Str(def.name.to_string())), ts) + } + AdtRepr::Union => { + let mut props = vec![(Key::Name("tag".into()), Expr::Str(def.name.to_string()))]; + for (i, value) in values.into_iter().enumerate() { + let field = &def.fields[FieldIdx::from_usize(i)]; + props.push((Key::Name(super::field_name(field.name.as_str(), i)), value)); + } + let ts = self.b.t.ty(ty, span); + Expr::As(Box::new(Expr::Object(props)), ts) + } + } + } + AggregateKind::Closure(def_id, _) => { + let Some(local) = def_id.as_local() else { + return self.err("a closure from another crate"); + }; + let captures = tcx.closure_captures(local); + for (capture, op) in captures.iter().zip(operands.iter()) { + // A reference captured through a deref is still the object it points to. + let whole = capture + .place + .projections + .iter() + .all(|p| matches!(p.kind, rustc_middle::hir::place::ProjectionKind::Deref)); + if !whole { + return self.err("a closure that captures part of a variable"); + } + let value = self.operand(op, out); + let name = self.b.fresh(&camel(capture.to_symbol().as_str())); + out.push(StmtKind::decl(false, name.clone(), None, Some(value)).at(None)); + self.b.bind_upvar(capture.get_root_variable(), name); + } + self.b.lower_closure(local, span, out) + } + _ => self.err(format!("unsupported aggregate {kind:?}")), + } + } + + fn operand(&mut self, op: &Operand<'tcx>, out: &mut Vec) -> Expr { + match op { + Operand::Copy(place) => { + let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); + let value = self.place(place, out); + match context_like(self.tcx(), ty) { + true => value, + false => self.b.copied(value, ty), + } + } + Operand::Move(place) => self.place(place, out), + Operand::Constant(c) => self.constant(c), + Operand::RuntimeChecks(_) => self.err("a runtime check"), + } + } + + fn constant(&mut self, c: &mir::ConstOperand<'tcx>) -> Expr { + let tcx = self.tcx(); + let ty = self.b.subst(c.const_.ty()); + if ty.is_unit() || matches!(ty.kind(), ty::FnDef(..)) { + return Expr::undefined(); + } + let env = self.b.t.typing_env_pub(); + match ty.kind() { + ty::Bool => match c.const_.try_eval_scalar_int(tcx, env) { + Some(int) => Expr::lit(if int.is_null() { "false" } else { "true" }), + None => self.err("a constant that does not evaluate"), + }, + ty::Int(_) | ty::Uint(_) => { + let int = Int::of(ty).expect("an integer"); + match c.const_.try_eval_bits(tcx, env) { + Some(bits) => { + let size = rustc_abi::Size::from_bits(int.bits); + let value = match int.signed { + true => size.sign_extend(bits), + false => bits as i128, + }; + int.lit(value) + } + None => self.err("a constant that does not evaluate"), + } + } + ty::Ref(_, inner, _) if inner.is_str() => match c.const_.eval(tcx, env, self.span) { + Ok(value) => match value.try_get_slice_bytes_for_diagnostics(tcx) { + Some(bytes) => Expr::Str(String::from_utf8_lossy(bytes).into_owned()), + None => self.err("a string constant"), + }, + Err(_) => self.err("a constant that does not evaluate"), + }, + _ => self.err(format!("a constant of type `{ty}`")), + } + } + + fn place(&mut self, place: &Place<'tcx>, out: &mut Vec) -> Expr { + let tcx = self.tcx(); + let mut value = self.local(place.local); + for (i, elem) in place.projection.iter().enumerate() { + let base = Place::ty_from(place.local, &place.projection[..i], self.mir, tcx); + let ty = self.b.subst(base.ty); + value = match elem { + ProjectionElem::Deref + | ProjectionElem::Downcast(..) + | ProjectionElem::OpaqueCast(_) + | ProjectionElem::UnwrapUnsafeBinder(_) => value, + ProjectionElem::Field(field, field_ty) => { + let value = self.field(value, ty, base.variant_index, field); + // TypeScript can't see which variant a switch on its discriminant took. + match ty.kind() { + ty::Adt(adt, _) if matches!(Std::of(tcx, adt.did()), Some(Std::Option | Std::Poll)) => { + let field_ty = self.b.subst(field_ty); + let span = self.span; + Expr::As(Box::new(value), local_type(self.b, field_ty, span)) + } + _ => value, + } + } + ProjectionElem::Index(index) => { + let base = match value.is_path() { + true => value, + false => self.b.spill(value, "slice", out), + }; + let i = self.local(index); + base.clone().index(Expr::rt("idx", vec![base, i])) + } + _ => self.err(format!("unsupported projection {elem:?}")), + }; + } + value + } + + fn field(&mut self, base: Expr, ty: Ty<'tcx>, variant: Option, field: FieldIdx) -> Expr { + let tcx = self.tcx(); + let span = self.span; + match ty.kind() { + ty::Coroutine(..) => match variant { + None => match self.class.upvars.get(field.as_usize()) { + Some(&id) => base.field(id), + None => self.err("an upvar out of range"), + }, + Some(variant) => { + let saved = self.class.layout.variant_fields[variant][field]; + base.field(self.class.saved[saved]) + } + }, + ty::Adt(adt, _) if context_like(tcx, ty) || Std::of(tcx, adt.did()) == Some(Std::Pin) => base, + _ => self + .b + .project(base, ty, variant.unwrap_or(rustc_abi::FIRST_VARIANT), field, span), + } + } + + fn local(&mut self, local: Local) -> Expr { + match local.as_usize() { + 1 => Expr::This, + 2 if let Some(cx) = &self.cx => Expr::ident(cx), + _ => Expr::ident(name(local)), + } + } +} + +/// A local's name: `_3`. +fn name(local: Local) -> String { + format!("_{}", local.as_usize()) +} + +/// Whether `ty` is how `.await` carries the context: the context, a pointer to it, or +/// `ResumeTy`. +fn context_like<'tcx>(tcx: ty::TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + match ty.kind() { + ty::Ref(_, inner, _) => context_like(tcx, *inner), + ty::Adt(adt, args) => { + Std::of(tcx, adt.did()) == Some(Std::Context) + || (super::library::std_path(tcx, adt.did()) + .last() + .is_some_and(|n| n == "NonNull") + && context_like(tcx, args.type_at(0))) + } + _ => false, + } +} + +/// Whether `did` is `ResumeTy`, the context an `async` body is resumed with. +fn is_resume(tcx: ty::TyCtxt<'_>, did: rustc_hir::def_id::DefId) -> bool { + tcx.is_lang_item(did, rustc_attr_ir::LangItem::ResumeTy) +} + +/// The bytes of a constant `&[u8; N]`. +fn const_bytes<'tcx>(tcx: ty::TyCtxt<'tcx>, c: &mir::ConstOperand<'tcx>) -> Option> { + let ty::Ref(_, inner, _) = c.const_.ty().kind() else { + return None; + }; + let ty::Array(elem, len) = inner.kind() else { + return None; + }; + if !matches!(elem.kind(), ty::Uint(ty::UintTy::U8)) { + return None; + } + let len = len.try_to_target_usize(tcx)? as usize; + let value = c + .const_ + .eval(tcx, ty::TypingEnv::fully_monomorphized(), rustc_span::DUMMY_SP) + .ok()?; + let ConstValue::Scalar(Scalar::Ptr(ptr, _)) = value else { + return None; + }; + let (prov, offset) = ptr.prov_and_relative_offset(); + let alloc = tcx.global_alloc(prov.alloc_id()).unwrap_memory(); + let start = offset.bytes_usize(); + Some( + alloc + .inner() + .inspect_with_uninit_and_ptr_outside_interpreter(start..start + len) + .to_vec(), + ) +} + +/// The locals a body reads. +struct Reads(FxHashSet); + +impl<'tcx> Visitor<'tcx> for Reads { + fn visit_local(&mut self, local: Local, context: PlaceContext, _: mir::Location) { + use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext}; + match context { + PlaceContext::NonUse( + NonUseContext::StorageLive | NonUseContext::StorageDead | NonUseContext::VarDebugInfo, + ) + | PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {} + _ => { + self.0.insert(local); + } + } + } +} diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 85420e89c..7ba07a094 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -9,6 +9,7 @@ mod consts; mod drop; mod fmt; mod library; +mod mir; mod num; mod pat; mod task; @@ -158,6 +159,9 @@ pub struct Translator<'a, 'tcx> { drops: rustc_data_structures::fx::FxHashMap, bool>, /// The classes given drop glue. glued: rustc_data_structures::fx::FxHashSet, + /// The async spike's prototype switch: lower `async` bodies from MIR as state + /// machines rather than from THIR as generators. + pub async_mir: bool, } /// A local struct or enum, and how it is represented. @@ -225,6 +229,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { refusals, drops: Default::default(), glued: Default::default(), + async_mir: std::env::var_os("RUST2_TS_ASYNC").is_some_and(|mode| mode == "mir"), }) } diff --git a/ts/src/print.rs b/ts/src/print.rs index 2877ea17b..f56749f95 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -275,6 +275,14 @@ impl Refs { self.stmts(program, body); self.stmts(program, finally); } + StmtKind::Switch { value, cases, default } => { + self.expr(program, value); + for (case, body) in cases { + self.expr(program, case); + self.stmts(program, body); + } + self.stmts(program, default); + } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } @@ -737,6 +745,31 @@ impl Printer<'_> { self.start(); self.write("}\n"); } + StmtKind::Switch { value, cases, default } => { + self.write("switch ("); + self.expr(value, 0); + self.write(") {\n"); + self.indent += 1; + for (case, body) in cases { + self.start(); + self.write("case "); + self.expr(case, 0); + self.write(": {\n"); + self.block_body(body); + self.start(); + self.write("}\n"); + } + if !default.is_empty() { + self.start(); + self.write("default: {\n"); + self.block_body(default); + self.start(); + self.write("}\n"); + } + self.indent -= 1; + self.start(); + self.write("}\n"); + } StmtKind::Try { body, finally } => { self.write("try {\n"); self.block_body(body); @@ -1133,6 +1166,13 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_locals(body, out); collect_locals(finally, out); } + StmtKind::Switch { value, cases, default } => { + collect_expr_locals(value, out); + for (_, body) in cases { + collect_locals(body, out); + } + collect_locals(default, out); + } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } diff --git a/ts/src/ts.rs b/ts/src/ts.rs index cabcbe29f..7ee4354c8 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -209,6 +209,12 @@ pub enum StmtKind { }, Break(Option), Continue(Option), + /// `switch (value) { case a: { .. } default: { .. } }`, whose cases never fall through. + Switch { + value: Expr, + cases: Vec<(Expr, Vec)>, + default: Vec, + }, /// `try { body } finally { finally }`: what `finally` drops is dropped on every exit. Try { body: Vec, diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index b13285c88..d8adeb37c 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -202,6 +202,34 @@ fn task() { let _ = std::fs::remove_file(&glue); let out = translated("task"); snapshot("task", &out); + task_harness(&out); +} + +/// The async spike's state machine prototype, on the same harness. +#[test] +fn task_mir() { + let out = scratch().join("task-mir").join("out"); + let _ = std::fs::remove_file(out.join("harness.ts")); + let output = Command::new(env!("CARGO_BIN_EXE_rust2-ts")) + .arg("--config") + .arg(manifest_dir().join("fixtures").join("task").join("ts.toml")) + .arg("--out") + .arg(&out) + .env("CARGO_TARGET_DIR", scratch().join("build-mir")) + .env("RUST2_TS_ASYNC", "mir") + .output() + .expect("running rust2-ts"); + assert!( + output.status.success(), + "translating task as state machines failed:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + task_harness(&out); +} + +/// Run the task harness on a translation of the task fixture. +fn task_harness(out: &Path) { + let glue = out.join("harness.ts"); let harness = manifest_dir().join("tests").join("task.ts").display().to_string(); let text = format!( r#"import * as rt from "./rt.ts"; @@ -214,8 +242,8 @@ export const run = harness({{ Pending: rt.Pending, Log, Channel, Guard, sum, dra "# ); std::fs::write(&glue, text).unwrap(); - typecheck(&out); - differential("task-fixture", &out, 20_000); + typecheck(out); + differential("task-fixture", out, 20_000); } /// Each construct outside the subset fails with its span, and nothing is written. From 32242a1026ff877ed5f732c597b1d8167e2d5016 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Fri, 23 Oct 2026 23:55:03 -0700 Subject: [PATCH 04/30] wip(ts): async spike, hoisted generators and the handoff bench's native side Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/bench/task.ts | 191 ++++++++ ts/fixtures/bench.rs | 73 +++ ts/fixtures/codec/examples/bench.rs | 74 +-- ts/fixtures/task/Cargo.toml | 4 + ts/fixtures/task/examples/handoff.rs | 8 + ts/fixtures/task/expected/kio.ts | 39 +- ts/fixtures/task/expected/model.ts | 656 ++++++++++++++------------- ts/fixtures/task/src/bench.rs | 71 +++ ts/fixtures/task/src/lib.rs | 9 +- ts/runtime/rt/task.ts | 44 +- ts/src/lower/body.rs | 173 +++++-- ts/src/lower/drop.rs | 1 + ts/src/lower/mir.rs | 3 +- ts/src/print.rs | 25 +- ts/src/ts.rs | 5 +- 15 files changed, 898 insertions(+), 478 deletions(-) create mode 100644 ts/bench/task.ts create mode 100644 ts/fixtures/bench.rs create mode 100644 ts/fixtures/task/examples/handoff.rs create mode 100644 ts/fixtures/task/src/bench.rs diff --git a/ts/bench/task.ts b/ts/bench/task.ts new file mode 100644 index 000000000..cc34df94b --- /dev/null +++ b/ts/bench/task.ts @@ -0,0 +1,191 @@ +// The async handoff, as the task fixture's `bench.rs` runs it natively: a value sent to a +// task parked on a channel wakes it, which reads the value through `depth` async +// functions and parks again. `main.ts` bundles three routes from here: moq's way, with +// promises and `async`/`await`; the translation on a one-task executor that polls it +// right away, as `bench.rs` does; and the translation on the runtime's `spawn`, which +// polls woken tasks from a microtask. +// +// Each run's input is the depth, then the count of values as a big-endian `u32`; its +// output is the task's sum, as a big-endian `u64`. + +/** The translation's waker, by shape. */ +interface Waker extends Disposable { + wake(): void; + wakeByRef(): void; + clone(): Waker; + willWake(other: Waker): boolean; +} + +interface Future extends Disposable { + poll(cx: Waker): T | symbol; +} + +/** What a route drives: the translation's channel and task, and its runtime. */ +export interface Fixture { + Pending: symbol; + spawn(future: Future): Promise; + Channel: { open(): Channel }; + drain(rx: Disposable, depth: number): Future; +} + +interface Channel extends Disposable { + consumer(): Disposable; + send(value: bigint): boolean; +} + +function parse(input: Uint8Array): [depth: number, count: number] { + return [input[0], new DataView(input.buffer, input.byteOffset + 1, 4).getUint32(0)]; +} + +function output(total: bigint): Uint8Array { + const out = new Uint8Array(8); + new DataView(out.buffer).setBigUint64(0, total); + return out; +} + +/** A waker that only records that it was woken: the executor of one task. */ +class Woken implements Waker { + woken = true; + + wake(): void { + this.woken = true; + } + + wakeByRef(): void { + this.woken = true; + } + + clone(): Waker { + return this; + } + + willWake(other: Waker): boolean { + return other === this; + } + + [Symbol.dispose](): void {} +} + +/** The translation, polled right away whenever it is woken, as `bench.rs` polls it. */ +export function polled(f: Fixture): (input: Uint8Array) => Uint8Array { + return (input) => { + const [depth, count] = parse(input); + const channel = f.Channel.open(); + const task = f.drain(channel.consumer(), depth); + const waker = new Woken(); + const run = (): bigint | undefined => { + while (waker.woken) { + waker.woken = false; + const out = task.poll(waker); + if (out !== f.Pending) return out as bigint; + } + return undefined; + }; + run(); + for (let value = 0; value < count; value++) { + channel.send(BigInt(value)); + run(); + } + channel[Symbol.dispose](); + const total = run(); + task[Symbol.dispose](); + if (total === undefined) throw new Error("the task did not finish once its channel closed"); + return output(total); + }; +} + +/** The translation on the runtime's executor, which polls woken tasks from a microtask. */ +export function spawned(f: Fixture): (input: Uint8Array) => Promise { + return async (input) => { + const [depth, count] = parse(input); + const channel = f.Channel.open(); + const done = f.spawn(f.drain(channel.consumer(), depth)); + for (let value = 0; value < count; value++) { + // The task's poll is queued first, so it parks before the next send. + await undefined; + channel.send(BigInt(value)); + } + await undefined; + channel[Symbol.dispose](); + return output(await done); + }; +} + +/** moq's way: a channel whose reader awaits a promise, under `async` functions. */ +class PromiseChannel { + #queue: bigint[] = []; + #next = 0; + #closed = false; + #wake: (() => void) | undefined; + #parked: (() => void) | undefined; + + send(value: bigint): void { + this.#queue.push(value); + this.#notify(); + } + + close(): void { + this.#closed = true; + this.#notify(); + } + + #notify(): void { + const wake = this.#wake; + this.#wake = undefined; + wake?.(); + } + + async recv(): Promise { + for (;;) { + if (this.#next < this.#queue.length) return this.#queue[this.#next++]; + if (this.#closed) return undefined; + await new Promise((resolve) => { + this.#wake = resolve; + const parked = this.#parked; + this.#parked = undefined; + parked?.(); + }); + } + } + + /** Resolves once the reader next waits. */ + parked(): Promise { + return new Promise((resolve) => { + this.#parked = resolve; + }); + } +} + +/** The next value, read through `depth` async functions. */ +function read(rx: PromiseChannel, depth: number): Promise { + return depth === 1 ? rx.recv() : level(rx, depth); +} + +async function level(rx: PromiseChannel, depth: number): Promise { + return await read(rx, depth - 1); +} + +async function drainPromises(rx: PromiseChannel, depth: number): Promise { + let total = 0n; + for (;;) { + const value = await read(rx, depth); + if (value === undefined) return total; + total += value; + } +} + +/** The handoff, written with promises. */ +export async function handWritten(input: Uint8Array): Promise { + const [depth, count] = parse(input); + const channel = new PromiseChannel(); + let parked = channel.parked(); + const done = drainPromises(channel, depth); + for (let value = 0; value < count; value++) { + await parked; + parked = channel.parked(); + channel.send(BigInt(value)); + } + await parked; + channel.close(); + return output(await done); +} diff --git a/ts/fixtures/bench.rs b/ts/fixtures/bench.rs new file mode 100644 index 000000000..a53075660 --- /dev/null +++ b/ts/fixtures/bench.rs @@ -0,0 +1,73 @@ +//! A fixture's native benchmark route: times its `bench::run` on the host, as +//! `ts/bench/time.ts` times the other routes. Each fixture's `examples/bench.rs` runs it. +//! +//! usage: bench < workloads +//! +//! Each input line is ` `. Each output line is ` `. + +use std::hint::black_box; +use std::io::{BufRead, Write}; +use std::time::{Duration, Instant}; + +/// Time `run` on the workloads read from stdin. +pub fn main(run: fn(&[u8]) -> Vec) { + let args: Vec = std::env::args().skip(1).collect(); + let [sample, rounds] = args.as_slice() else { + panic!("usage: bench < workloads"); + }; + let sample = Duration::from_millis(sample.parse().expect("sample ms")); + let rounds: usize = rounds.parse().expect("rounds"); + + let workloads: Vec<(String, Vec)> = std::io::stdin() + .lock() + .lines() + .map(|line| { + let line = line.expect("reading stdin"); + let (name, hex) = line.split_once(' ').expect("a line is ` `"); + (name.to_string(), unhex(hex)) + }) + .collect(); + + // Calibrate each workload to a sample of at least `sample`, which also warms it. + let calls: Vec = workloads + .iter() + .map(|(_, input)| { + let mut calls = 1; + while time(run, input, calls) < sample { + calls *= 2; + } + calls + }) + .collect(); + + // Interleave the workloads in each round, so drift spreads over all of them. + let mut ns = vec![Vec::with_capacity(rounds); workloads.len()]; + for _ in 0..rounds { + for (i, (_, input)) in workloads.iter().enumerate() { + ns[i].push(time(run, input, calls[i]).as_nanos() as f64 / calls[i] as f64); + } + } + + let mut stdout = std::io::stdout().lock(); + for (i, (name, input)) in workloads.iter().enumerate() { + let samples: Vec = ns[i].iter().map(|ns| format!("{ns:.3}")).collect(); + let output: String = run(input).iter().map(|b| format!("{b:02x}")).collect(); + writeln!(stdout, "{name} {} {} {output}", calls[i], samples.join(",")).unwrap(); + } +} + +fn time(run: fn(&[u8]) -> Vec, input: &[u8], calls: u64) -> Duration { + let start = Instant::now(); + for _ in 0..calls { + black_box(run(black_box(input))); + } + start.elapsed() +} + +fn unhex(hex: &str) -> Vec { + (0..hex.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("input hex")) + .collect() +} diff --git a/ts/fixtures/codec/examples/bench.rs b/ts/fixtures/codec/examples/bench.rs index 89a48bb2c..32f49469a 100644 --- a/ts/fixtures/codec/examples/bench.rs +++ b/ts/fixtures/codec/examples/bench.rs @@ -1,74 +1,8 @@ -//! The benchmark's native route: times `bench::run` on the host, as `ts/bench/time.ts` -//! times the other routes. -//! -//! usage: bench < workloads -//! -//! Each input line is ` `. Each output line is ` `. +//! The benchmark's native route for this fixture: see `fixtures/bench.rs`. -use std::hint::black_box; -use std::io::{BufRead, Write}; -use std::time::{Duration, Instant}; - -use codec_fixture::bench; +#[path = "../../bench.rs"] +mod native; fn main() { - let args: Vec = std::env::args().skip(1).collect(); - let [sample, rounds] = args.as_slice() else { - panic!("usage: bench < workloads"); - }; - let sample = Duration::from_millis(sample.parse().expect("sample ms")); - let rounds: usize = rounds.parse().expect("rounds"); - - let workloads: Vec<(String, Vec)> = std::io::stdin() - .lock() - .lines() - .map(|line| { - let line = line.expect("reading stdin"); - let (name, hex) = line.split_once(' ').expect("a line is ` `"); - (name.to_string(), unhex(hex)) - }) - .collect(); - - // Calibrate each workload to a sample of at least `sample`, which also warms it. - let calls: Vec = workloads - .iter() - .map(|(_, input)| { - let mut calls = 1; - while time(input, calls) < sample { - calls *= 2; - } - calls - }) - .collect(); - - // Interleave the workloads in each round, so drift spreads over all of them. - let mut ns = vec![Vec::with_capacity(rounds); workloads.len()]; - for _ in 0..rounds { - for (i, (_, input)) in workloads.iter().enumerate() { - ns[i].push(time(input, calls[i]).as_nanos() as f64 / calls[i] as f64); - } - } - - let mut stdout = std::io::stdout().lock(); - for (i, (name, input)) in workloads.iter().enumerate() { - let samples: Vec = ns[i].iter().map(|ns| format!("{ns:.3}")).collect(); - let output: String = bench::run(input).iter().map(|b| format!("{b:02x}")).collect(); - writeln!(stdout, "{name} {} {} {output}", calls[i], samples.join(",")).unwrap(); - } -} - -fn time(input: &[u8], calls: u64) -> Duration { - let start = Instant::now(); - for _ in 0..calls { - black_box(bench::run(black_box(input))); - } - start.elapsed() -} - -fn unhex(hex: &str) -> Vec { - (0..hex.len()) - .step_by(2) - .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("input hex")) - .collect() + native::main(codec_fixture::bench::run); } diff --git a/ts/fixtures/task/Cargo.toml b/ts/fixtures/task/Cargo.toml index f48ec80bc..b58b1039f 100644 --- a/ts/fixtures/task/Cargo.toml +++ b/ts/fixtures/task/Cargo.toml @@ -10,5 +10,9 @@ publish = false # The cdylib is the native side of the differential test, built for wasm32. crate-type = ["lib", "cdylib"] +[features] +# The wasm32 build exports the benchmark's handoff in place of the harness. +bench = [] + [lints] workspace = true diff --git a/ts/fixtures/task/examples/handoff.rs b/ts/fixtures/task/examples/handoff.rs new file mode 100644 index 000000000..2b3506c34 --- /dev/null +++ b/ts/fixtures/task/examples/handoff.rs @@ -0,0 +1,8 @@ +//! The benchmark's native route for this fixture: see `fixtures/bench.rs`. + +#[path = "../../bench.rs"] +mod native; + +fn main() { + native::main(task_fixture::bench::run); +} diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts index af08edeac..9733183ca 100644 --- a/ts/fixtures/task/expected/kio.ts +++ b/ts/fixtures/task/expected/kio.ts @@ -260,25 +260,7 @@ export class Consumer { /** kio's one-line wrapper over a `poll_*` method. */ recv(): rt.Future { - const self = this; - return rt.future(function* (_taskContext: rt.Context): Generator { - const self2 = self; - let __awaitee: Pending<(a0: Waiter) => rt.Poll> = wait((waiter: Waiter): rt.Poll => { - return self2.pollRecv(waiter); - }); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; - } - } finally { - rt.drop(__awaitee); - } - }, (): void => {}); + return rt.future(recvBody, undefined, this); } /** The next value, or `None` once the channel closed and every value was read. */ @@ -297,4 +279,23 @@ export class Consumer { } } +export function* recvBody(_taskContext: rt.Context, self: Consumer): Generator { + const self2 = self; + let __awaitee: Pending<(a0: Waiter) => rt.Poll> = wait((waiter: Waiter): rt.Poll => { + return self2.pollRecv(waiter); + }); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } +} + //# sourceMappingURL=kio.ts.map diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index d9f144c95..78f36f54e 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -140,54 +140,58 @@ export class Guard { * each await beside the one it was given. */ export function sum(rx: Consumer, guard: Guard): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - let rx2: Consumer = rx; - rx = undefined!; + return rt.future(sumBody, sumDrop, rx, guard); +} + +export function* sumBody(_taskContext: rt.Context, rx: Consumer, guard: Guard): Generator { + let rx2: Consumer = rx; + rx = undefined!; + try { + const guard2 = guard; + guard = undefined!; try { - const guard2 = guard; - guard = undefined!; + const inner = Guard.new(rt.u32.add(guard2.id, 100), guard2.log.clone()); try { - const inner = Guard.new(rt.u32.add(guard2.id, 100), guard2.log.clone()); - try { - let total: bigint = 0n; - while (true) { - let option: bigint | undefined; - let __awaitee: rt.Future = rx2.recv(); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - option = result; - break; - } - _taskContext = yield; + let total: bigint = 0n; + while (true) { + let option: bigint | undefined; + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + option = result; + break; } - } finally { - rt.drop(__awaitee); - } - if (option !== undefined) { - const value = option; - inner.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(guard2.id, f), " got ", (f: rt.Formatter) => rt.u64.display(value, f)])); - total = rt.u64.add(total, value); - } else { - break; + _taskContext = yield; } + } finally { + rt.drop(__awaitee); + } + if (option !== undefined) { + const value = option; + inner.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(guard2.id, f), " got ", (f: rt.Formatter) => rt.u64.display(value, f)])); + total = rt.u64.add(total, value); + } else { + break; } - return total; - } finally { - rt.drop(inner); } + return total; } finally { - rt.drop(guard2); + rt.drop(inner); } } finally { - rt.drop(rx2); + rt.drop(guard2); } - }, (): void => { - rt.drop(rx); - rt.drop(guard); - }); + } finally { + rt.drop(rx2); + } +} + +export function sumDrop(rx: Consumer, guard: Guard): void { + rt.drop(rx); + rt.drop(guard); } /** @@ -195,359 +199,393 @@ export function sum(rx: Consumer, guard: Guard): rt.Future { * deep: 1, 4, or 16. */ export function drain(rx: Consumer, depth: number): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - let rx2: Consumer = rx; - rx = undefined!; - try { - const depth2 = depth; - let total: bigint = 0n; - while (true) { - let next: bigint | undefined; - if (depth2 === 1) { - let __awaitee: rt.Future = rx2.recv(); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - next = result; - break; - } - _taskContext = yield; + return rt.future(drainBody, drainDrop, rx, depth); +} + +export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: number): Generator { + let rx2: Consumer = rx; + rx = undefined!; + try { + const depth2 = depth; + let total: bigint = 0n; + while (true) { + let next: bigint | undefined; + if (depth2 === 1) { + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + next = result; + break; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - } else if (depth2 === 4) { - let __awaitee2: rt.Future = level3(rx2); - try { - while (true) { - const poll2 = __awaitee2.poll(_taskContext); - if (poll2 !== rt.Pending) { - const result2 = poll2; - next = result2; - break; - } - _taskContext = yield; + } finally { + rt.drop(__awaitee); + } + } else if (depth2 === 4) { + let __awaitee2: rt.Future = level3(rx2); + try { + while (true) { + const poll2 = __awaitee2.poll(_taskContext); + if (poll2 !== rt.Pending) { + const result2 = poll2; + next = result2; + break; } - } finally { - rt.drop(__awaitee2); + _taskContext = yield; } - } else { - let __awaitee3: rt.Future = level15(rx2); - try { - while (true) { - const poll3 = __awaitee3.poll(_taskContext); - if (poll3 !== rt.Pending) { - const result3 = poll3; - next = result3; - break; - } - _taskContext = yield; + } finally { + rt.drop(__awaitee2); + } + } else { + let __awaitee3: rt.Future = level15(rx2); + try { + while (true) { + const poll3 = __awaitee3.poll(_taskContext); + if (poll3 !== rt.Pending) { + const result3 = poll3; + next = result3; + break; } - } finally { - rt.drop(__awaitee3); + _taskContext = yield; } - } - if (next !== undefined) { - const value = next; - total = rt.u64.add(total, value); - } else { - break; + } finally { + rt.drop(__awaitee3); } } - return total; - } finally { - rt.drop(rx2); + if (next !== undefined) { + const value = next; + total = rt.u64.add(total, value); + } else { + break; + } } - }, (): void => { - rt.drop(rx); - }); + return total; + } finally { + rt.drop(rx2); + } +} + +export function drainDrop(rx: Consumer, _depth: number): void { + rt.drop(rx); } export function level1(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = rx2.recv(); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level1Body, undefined, rx); +} + +export function* level1Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; + } + } finally { + rt.drop(__awaitee); + } +} + +export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level2(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; + } + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level3(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level2(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level3Body, undefined, rx); +} + +export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level14(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level15(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level14(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level15Body, undefined, rx); +} + +export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level1(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level2(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level1(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level2Body, undefined, rx); +} + +export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level13(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level14(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level13(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level14Body, undefined, rx); +} + +export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level12(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level13(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level12(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level13Body, undefined, rx); +} + +export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level11(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level12(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level11(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level12Body, undefined, rx); +} + +export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level10(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level11(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level10(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level11Body, undefined, rx); +} + +export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level9(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level10(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level9(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level10Body, undefined, rx); +} + +export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level8(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level9(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level8(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level9Body, undefined, rx); +} + +export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level7(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level8(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level7(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level8Body, undefined, rx); +} + +export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level6(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level7(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level6(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level7Body, undefined, rx); +} + +export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level5(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level6(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level5(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level6Body, undefined, rx); +} + +export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level4(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level5(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level4(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; + return rt.future(level5Body, undefined, rx); +} + +export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { + const rx2 = rx; + let __awaitee: rt.Future = level3(rx2); + try { + while (true) { + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + return result; } - } finally { - rt.drop(__awaitee); + _taskContext = yield; } - }, (): void => {}); + } finally { + rt.drop(__awaitee); + } } export function level4(rx: Consumer): rt.Future { - return rt.future(function* (_taskContext: rt.Context): Generator { - const rx2 = rx; - let __awaitee: rt.Future = level3(rx2); - try { - while (true) { - const poll = __awaitee.poll(_taskContext); - if (poll !== rt.Pending) { - const result = poll; - return result; - } - _taskContext = yield; - } - } finally { - rt.drop(__awaitee); - } - }, (): void => {}); + return rt.future(level4Body, undefined, rx); } //# sourceMappingURL=model.ts.map diff --git a/ts/fixtures/task/src/bench.rs b/ts/fixtures/task/src/bench.rs new file mode 100644 index 000000000..0c7e22e54 --- /dev/null +++ b/ts/fixtures/task/src/bench.rs @@ -0,0 +1,71 @@ +//! The handoff `just ts bench` times on every route: a value sent to a task parked on the +//! channel, which wakes it, polls it through `depth` async functions, and parks it again. +//! Not translated: `bench/task.ts` runs the same loop on the translation with its own +//! executor. +//! +//! The input is the depth, then the count of values as a big-endian `u32`; the output is +//! the task's sum, as a big-endian `u64`. + +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Wake, Waker}; + +use crate::model::{self, Channel}; + +/// Run one handoff workload. +pub fn run(input: &[u8]) -> Vec { + let depth = u32::from(input[0]); + let count = u32::from_be_bytes([input[1], input[2], input[3], input[4]]); + let channel = Channel::open(); + let mut task = Task::new(model::drain(channel.consumer(), depth)); + task.run(); + for value in 0..count { + channel.send(u64::from(value)); + task.run(); + } + drop(channel); + let total = task.run().expect("the task finishes once its channel closes"); + total.to_be_bytes().to_vec() +} + +/// One task, polled whenever its waker was woken: an executor that only ever runs one. +struct Task { + future: Pin>, + woken: Arc, + waker: Waker, +} + +struct Woken(Mutex); + +impl Wake for Woken { + fn wake(self: Arc) { + self.wake_by_ref(); + } + + fn wake_by_ref(self: &Arc) { + *self.0.lock().unwrap() = true; + } +} + +impl Task { + fn new(future: F) -> Self { + let woken = Arc::new(Woken(Mutex::new(true))); + Self { + future: Box::pin(future), + waker: Waker::from(woken.clone()), + woken, + } + } + + /// Poll while woken, returning the output once it is ready. + fn run(&mut self) -> Option { + while std::mem::take(&mut *self.woken.0.lock().unwrap()) { + let mut cx = Context::from_waker(&self.waker); + if let Poll::Ready(output) = self.future.as_mut().poll(&mut cx) { + return Some(output); + } + } + None + } +} diff --git a/ts/fixtures/task/src/lib.rs b/ts/fixtures/task/src/lib.rs index 1a478dad3..aca8645c2 100644 --- a/ts/fixtures/task/src/lib.rs +++ b/ts/fixtures/task/src/lib.rs @@ -6,8 +6,10 @@ //! 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. Neither is translated. +//! 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 exec; pub mod harness; pub mod kio; @@ -16,5 +18,8 @@ pub mod model; #[cfg(target_arch = "wasm32")] #[path = "../../wasm.rs"] mod wasm; -#[cfg(target_arch = "wasm32")] +/// What the wasm32 build exports: the benchmark's handoff with `bench`, else the harness. +#[cfg(all(target_arch = "wasm32", feature = "bench"))] +use bench::run as entry; +#[cfg(all(target_arch = "wasm32", not(feature = "bench")))] use harness::run as entry; diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index b8fd624e4..2f7c7dc5d 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -122,8 +122,11 @@ export interface Future extends Disposable { poll(cx: Context): Poll; } -/** The body of an `async fn` or block: it yields at each `.await` that is pending. */ -export type Body = (cx: Context) => Generator; +/** + * The body of an `async fn` or block, a generator of what it captured: it yields at + * each `.await` that is pending. + */ +export type Body = (cx: Context, ...upvars: A) => Generator; const Unresumed = 0; const Suspended = 1; @@ -135,32 +138,36 @@ const Panicked = 3; * poll. Dropping it unresumed drops what it captured, and suspended runs the `finally` * blocks that drop its live locals. */ -class Async implements Future { +class Async implements Future { #state = Unresumed; - #body: Body; + #body: Body; + #drop: ((...upvars: A) => void) | undefined; + #upvars: A | undefined; #gen: Generator | undefined; - #drop: () => void; - constructor(body: Body, drop: () => void) { + constructor(body: Body, drop: ((...upvars: A) => void) | undefined, upvars: A) { this.#body = body; this.#drop = drop; + this.#upvars = upvars; } poll(cx: Context): Poll { - if (this.#state === Returned) panic("`async fn` resumed after completion"); - if (this.#state === Panicked) panic("`async fn` resumed after panicking"); const state = this.#state; + if (state === Returned) panic("`async fn` resumed after completion"); + if (state === Panicked) panic("`async fn` resumed after panicking"); this.#state = Panicked; - let gen = this.#gen; let next: IteratorResult; if (state === Unresumed) { - gen = this.#gen = this.#body(cx); + const gen = this.#body(cx, ...this.#upvars!); + this.#upvars = undefined; + this.#gen = gen; next = gen.next(); } else { - next = gen!.next(cx); + next = this.#gen!.next(cx); } if (next.done) { this.#state = Returned; + this.#gen = undefined; return next.value; } this.#state = Suspended; @@ -170,14 +177,21 @@ class Async implements Future { [Symbol.dispose](): void { const state = this.#state; this.#state = Returned; - if (state === Unresumed) this.#drop(); + if (state === Unresumed) this.#drop?.(...this.#upvars!); else if (state === Suspended) this.#gen!.return(undefined as T); } } -/** An `async fn`'s future: `body` runs at the first poll, and `drop` drops what it captured if it never does. */ -export function future(body: Body, drop: () => void): Future { - return new Async(body, drop); +/** + * An `async fn`'s future: `body` runs on what it captured at the first poll, and `drop` + * drops that if it never does. + */ +export function future( + body: Body, + drop: ((...upvars: A) => void) | undefined, + ...upvars: A +): Future { + return new Async(body, drop, upvars); } // Executor diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 747b7a910..f9310de21 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -130,6 +130,7 @@ pub fn function<'a, 'tcx>( body, loc: None, doc: None, + generator: false, }) } @@ -2270,7 +2271,6 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } - /// A closure as an arrow function, or an `async` body as a future around a generator. fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span, out: &mut Vec) -> Expr { let tcx = self.t.tcx; let local = closure.closure_id; @@ -2286,7 +2286,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let upvars = self.operands(&closure.upvars, out); return super::mir::coroutine(self, local, ty, upvars, span); } - self.lower_closure(local, span, out) + self.lower_closure(local, span) } /// Bind the variable `var`, which a closure body reads as an upvar, to `name`. @@ -2297,12 +2297,11 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { /// A closure as an arrow function, or an `async` body as a future around a generator, /// reading its upvars as the variables they were bound to. - pub(super) fn lower_closure( - &mut self, - local: rustc_hir::def_id::LocalDefId, - span: Span, - out: &mut Vec, - ) -> Expr { + /// + /// The generator is a function of its own, taking its upvars as parameters: a + /// generator function made per call costs V8 a prototype object and a new shape for + /// each generator, about 25 times what one made once does. + pub(super) fn lower_closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { let tcx = self.t.tcx; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); @@ -2319,47 +2318,59 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } _ => return self.err(span, format!("a closure of type `{closure_ty}`")), }; - // What a future captures that drops, which it drops itself if never polled. - let mut captured = Vec::new(); - // A method's receiver, which a generator can't read as `this`. - let mut receiver = None; + // A generator's upvars, each a parameter: its name, its value here, and its type. + let mut upvars: Vec<(String, Expr, Ty<'tcx>)> = Vec::new(); + // What the generator renames, to put back once it is lowered. + let mut renamed = Vec::new(); for capture in tcx.closure_captures(local) { let var = capture.get_root_variable(); let ty = self.subst(capture.place.ty()); - if coroutine && matches!(self.locals.get(&var), Some(Local::Name { name, .. }) if name == "this") { - let alias = self.fresh("self"); - out.push(StmtKind::decl(false, alias.clone(), None, Some(Expr::This)).at(None)); - let saved = self.locals.insert( - var, - Local::Name { - name: alias, - mutable: false, - }, - ); - receiver = Some((var, saved)); - } - let ty::UpvarCapture::ByValue = capture.info.capture_kind else { - continue; - }; + let by_value = matches!(capture.info.capture_kind, ty::UpvarCapture::ByValue); let mutable = matches!(self.locals.get(&var), Some(Local::Name { mutable: true, .. })); // A copy captured by `move` would be shared in JS: refuse one that can change. - if !coroutine && mutable && self.t.is_copy(ty) { + if !coroutine && by_value && mutable && self.t.is_copy(ty) { self.t .err(capture.get_path_span(tcx), "a closure that copies a mutable variable"); } - if self.t.drops(ty) { - match (coroutine, &self.locals.get(&var)) { - (true, Some(Local::Name { name, .. })) if capture.place.projections.is_empty() => { - let name = name.clone(); - self.disown(&name); - captured.push((name, ty)); - } - _ => self.t.err( + if !coroutine { + if by_value && self.t.drops(ty) { + self.t.err( capture.get_path_span(tcx), "a closure that captures a value that drops, which is not supported yet", - ), + ); } + continue; } + if !capture.place.projections.is_empty() { + self.t.err( + capture.get_path_span(tcx), + "an async body that captures part of a variable", + ); + continue; + } + let Some(Local::Name { name, .. }) = self.locals.get(&var).cloned() else { + self.t + .err(capture.get_path_span(tcx), "an async body capturing a function item"); + continue; + }; + // The future owns what it captures, so here drops none of it. + self.disown(&name); + let (param, value) = match name == "this" { + true => { + let alias = self.fresh("self"); + let saved = self.locals.insert( + var, + Local::Name { + name: alias.clone(), + mutable: false, + }, + ); + renamed.push((var, saved)); + (alias, Expr::This) + } + false => (name.clone(), Expr::ident(name)), + }; + upvars.push((param, value, ty)); } let saved_thir = std::mem::replace(&mut self.thir, thir); self.read.extend(reads(tcx, thir)); @@ -2389,7 +2400,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.thir = saved_thir; self.breakables = saved_breakables; self.ret = saved_ret; - if let Some((var, saved)) = receiver { + for (var, saved) in renamed { match saved { Some(saved) => self.locals.insert(var, saved), None => self.locals.remove(&var), @@ -2398,17 +2409,89 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { if !coroutine { return Expr::Arrow(params, ret_ty, body_stmts); } + + // `rt.future(body, drop, ...upvars)`: the body and what drops the upvars if it + // never runs, each a function of the upvars. + let parent = tcx.typeck_root_def_id(local.to_def_id()); + let base = camel(tcx.item_name(parent).as_str()); let mut drops = Vec::new(); - for (name, ty) in captured { - if let Some(dropped) = self.t.drop_value(Expr::ident(name), ty, span) { + for (name, _, ty) in &upvars { + if let Some(dropped) = self.t.drop_value(Expr::ident(name), *ty, span) { drops.push(StmtKind::Expr(dropped).at(None)); } } - let generator = Expr::Generator(params, ret_ty, body_stmts); - Expr::rt( - "future", - vec![generator, Expr::Arrow(Vec::new(), Type::Builtin("void"), drops)], - ) + let upvar_params: Vec = upvars + .iter() + .map(|(name, _, ty)| Param { + name: name.clone(), + ty: Some(self.t.ty(*ty, span)), + }) + .collect(); + params.extend(upvar_params.iter().cloned()); + let body_fn = self.hoist(parent, format!("{base}Body"), params, ret_ty, body_stmts, true, span); + // The drop reads only the upvars that drop: TypeScript lets the rest go unread as `_`s. + let drop_params = upvars + .iter() + .zip(upvar_params) + .map(|((_, _, ty), param)| match self.t.drops(*ty) { + true => param, + false => Param { + name: format!("_{}", param.name), + ..param + }, + }) + .collect(); + let drop_fn = match drops.is_empty() { + true => Expr::undefined(), + false => self.hoist( + parent, + format!("{base}Drop"), + drop_params, + Type::Builtin("void"), + drops, + false, + span, + ), + }; + let mut args = vec![body_fn, drop_fn]; + args.extend(upvars.into_iter().map(|(_, value, _)| value)); + Expr::rt("future", args) + } + + /// A module-level function in `parent`'s module, by the name `base`. + #[expect(clippy::too_many_arguments, reason = "a function's parts")] + fn hoist( + &mut self, + parent: rustc_hir::def_id::DefId, + base: String, + params: Vec, + ret: Type, + body: Vec, + generator: bool, + span: Span, + ) -> Expr { + let order = self.t.order(span); + let sym = self.t.program.sym(crate::program::Symbol { + module: self.t.module_of(parent), + base, + suffix: String::new(), + owner: None, + kind: SymKind::Function, + order, + name: String::new(), + }); + let loc = self.t.loc(span); + self.t.program.items.push(ts::Item::Function(ts::Function { + sym, + method: false, + params, + ret, + body, + loc, + doc: None, + generator, + })); + Expr::Sym(sym) } // Calls diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index aac5f7a2b..5a5560f9d 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -175,6 +175,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { body, loc: None, doc: None, + generator: false, }); } } diff --git a/ts/src/lower/mir.rs b/ts/src/lower/mir.rs index 28ac234a0..55f30ffe6 100644 --- a/ts/src/lower/mir.rs +++ b/ts/src/lower/mir.rs @@ -146,6 +146,7 @@ pub fn coroutine<'tcx>( body, loc: None, doc: None, + generator: false, }); } @@ -797,7 +798,7 @@ impl<'m, 'b, 'a, 'tcx> Lowering<'m, 'b, 'a, 'tcx> { out.push(StmtKind::decl(false, name.clone(), None, Some(value)).at(None)); self.b.bind_upvar(capture.get_root_variable(), name); } - self.b.lower_closure(local, span, out) + self.b.lower_closure(local, span) } _ => self.err(format!("unsupported aggregate {kind:?}")), } diff --git a/ts/src/print.rs b/ts/src/print.rs index f56749f95..ad87c34d9 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -312,7 +312,7 @@ impl Refs { self.expr(program, b); self.expr(program, c); } - Expr::Arrow(params, ret, body) | Expr::Generator(params, ret, body) => { + Expr::Arrow(params, ret, body) => { self.params(program, params); self.ty(program, ret); self.stmts(program, body); @@ -525,14 +525,19 @@ impl Printer<'_> { self.start(); self.mark(f.loc); let name = self.program.syms[f.sym].name.clone(); + let star = if f.generator { "*" } else { "" }; match cx { - Context::Module => self.write(&format!("export function {name}(")), + Context::Module => self.write(&format!("export function{star} {name}(")), Context::Class if f.method => self.write(&format!("{name}(")), Context::Class => self.write(&format!("static {name}(")), Context::Companion => self.write(&format!("{name}(")), } self.params(&f.params); - let ret = self.ty(&f.ret); + let mut ret = self.ty(&f.ret); + if f.generator { + self.uses_rt = true; + ret = format!("Generator"); + } self.write(&format!("): {ret} {{\n")); self.block_body(&f.body); self.start(); @@ -920,16 +925,6 @@ impl Printer<'_> { self.write("}"); } } - Expr::Generator(params, ret, body) => { - self.write("function* ("); - self.params(params); - let ret = self.ty(ret); - self.uses_rt = true; - self.write(&format!("): Generator {{\n")); - self.block_body(body); - self.start(); - self.write("}"); - } Expr::Yield => self.write("yield"), Expr::Lambda(params, body) => { self.write("("); @@ -1095,7 +1090,7 @@ fn binary_prec(op: &str) -> u8 { fn prec(e: &Expr) -> u8 { match e { - Expr::Assign(..) | Expr::Arrow(..) | Expr::Lambda(..) | Expr::Generator(..) | Expr::Yield => 3, + Expr::Assign(..) | Expr::Arrow(..) | Expr::Lambda(..) | Expr::Yield => 3, Expr::Cond(..) => 4, Expr::Binary(_, op, _) => binary_prec(op), Expr::As(..) => 12, @@ -1187,7 +1182,7 @@ fn collect_target(target: &Target, out: &mut Vec) { fn collect_expr_locals(e: &Expr, out: &mut Vec) { match e { - Expr::Arrow(params, _, body) | Expr::Generator(params, _, body) => { + Expr::Arrow(params, _, body) => { out.extend(params.iter().map(|p| p.name.clone())); collect_locals(body, out); } diff --git a/ts/src/ts.rs b/ts/src/ts.rs index 7ee4354c8..369672b5f 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -49,8 +49,6 @@ pub enum Expr { Lambda(Vec, Box), /// `e as T`, for a literal whose type TypeScript would widen. As(Box, Type), - /// `function* (params): Generator { body }`, an async body. - Generator(Vec, Type, Vec), /// `yield`, which a generator resumes from with the next `rt.Context`. Yield, Located(Loc, Box), @@ -296,6 +294,9 @@ pub struct Function { pub body: Vec, pub loc: Option, pub doc: Option, + /// An async body, run as a generator: `function*`, returning `Generator`. + pub generator: bool, } #[derive(Clone, Debug)] From a578abbc7821a7d40fada8ddd5070b7f8946c856 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:07:03 -0700 Subject: [PATCH 05/30] wip(ts): async spike, generators win; delete the MIR state machines Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 5 +- quest/m2/ts-async-spike.md | 58 -- quest/m2/ts-async.md | 39 +- quest/m2/ts-drop.md | 47 +- quest/m2/ts-shared.md | 6 + ts/README.md | 41 +- ts/bench/entry.ts | 30 +- ts/bench/main.ts | 120 +++- ts/bench/workloads.ts | 23 +- ts/fixtures/reject/census.md | 183 ++++-- ts/fixtures/reject/expected.txt | 50 +- ts/fixtures/reject/src/lib.rs | 76 ++- ts/fixtures/reject/ts.toml | 10 +- ts/justfile | 7 +- ts/src/driver.rs | 6 - ts/src/lower/body.rs | 61 +- ts/src/lower/drop.rs | 17 +- ts/src/lower/fmt.rs | 8 +- ts/src/lower/mir.rs | 999 -------------------------------- ts/src/lower/mod.rs | 16 +- ts/src/print.rs | 40 -- ts/src/ts.rs | 6 - ts/tests/differential.ts | 3 +- ts/tests/fixtures.rs | 22 - 24 files changed, 555 insertions(+), 1318 deletions(-) delete mode 100644 quest/m2/ts-async-spike.md delete mode 100644 ts/src/lower/mir.rs diff --git a/quest/m2/README.md b/quest/m2/README.md index 3cbd6d7f5..00b881193 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -14,11 +14,10 @@ deletes the quests that follow it. ## Required -- [Async and drop spike](/quest/m2/ts-async-spike.md) - generators from THIR against MIR state machines, deciding async, drop points, and the lowering - [Faster translator runtime](/quest/m2/ts-runtime-perf.md) - fewer allocations (`Result` included), direct byte reads, and number-only checked ops, kept where measured - [Wide integer spike](/quest/m2/ts-wide-ints.md) - `bigint` against boxed and unboxed hi/lo picks the 64- and 128-bit representation -- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - a `Drop` type's `drop()` runs where Rust drops it -- [Async in the TypeScript translator](/quest/m2/ts-async.md) - async code translates with Rust's lazy futures +- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it +- [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values - [Iterators](/quest/m2/ts-iter.md) - lazy `rt.ts` adaptors with a `DONE` protocol - [Collections](/quest/m2/ts-collections.md) - maps, sets, and queues keep Rust's key semantics diff --git a/quest/m2/ts-async-spike.md b/quest/m2/ts-async-spike.md deleted file mode 100644 index 2f9af8444..000000000 --- a/quest/m2/ts-async-spike.md +++ /dev/null @@ -1,58 +0,0 @@ -# [L] Async and drop lowering spike - -## Goal - -A report picks how [rust2-ts](/ts/README.md) translates async code and where it -reads drop points, from two prototypes run on the same kio-shaped channel: -JS generators lowered from THIR, and state machines lowered from MIR after the -coroutine transform. The report also decides whether the whole lowering moves -from THIR to MIR, and rewrites [Drop](/quest/m2/ts-drop.md) and -[Async](/quest/m2/ts-async.md) to the winner. - -## Plan - -Decided with the maintainer on 2026-10-23: prototype both, and measure one -spike for async and drop together, since both hinge on THIR versus MIR. - -Research (2026-10-23): - -- Nearly all of moq's async is `poll_*` functions behind one-line - `kio::wait(|w| self.poll_x(w)).await` wrappers. The hard parts are kio's - internals: `Waiter` holds `Arc`, `WaiterList` holds `Weak` and - frees slots when `Weak::upgrade` fails, plus `Mutex`, atomics, and a - thread-local coop budget. No `select!`, `join!`, or tokio in kio or the model. -- Generators: rustc desugars `.await` before THIR into a poll loop around - `yield`, which maps to `cx = yield` and `gen.next(cx)`. Laziness is free, JS - objects do not move so `Pin` is moot, and `gen.return()` runs `finally` and - `using` disposals. Gaps: the first `next()` drops its argument, an unstarted - generator's `return()` runs no `finally` (its captured arguments must still - drop), and polling after completion must panic. Output stays readable. -- MIR state machines: rustc's own transform, with its drop shim giving exact - drops on cancel, and the fastest shape. The output needs a structurizer and - reads poorly, and lowering MIR means mapping `Pin::new_unchecked` and raw - pointers. -- Eager `async`/`await` (rust-js's approach) is out: it breaks laziness, poll - order, and cancel-by-drop. -- A microbenchmark of a two-level await handoff measured a hand-written state - machine at 75 ns, generators at about 180 ns, and `async`/`await` at about - 95 ns in Node 24. Generators still sustain millions of wakeups per second. - -Prototype shape: - -- Translate a small kio-like `Producer`/`Consumer`, `Waiter`/`WaiterList`, - `kio::wait`, and one `async fn` consumer loop. Each prototype gets only the - `Arc`/`Weak` counting, `Drop`, and `Mutex` it needs. -- A deterministic FIFO executor in both Rust and TS logs every poll, wake, and - drop; the differential test requires identical traces. Cases: a never-polled - future has no effects, a future dropped mid-await drops in Rust's order, - dropping an unstarted future drops its arguments, and polling after `Ready` - panics. -- Executor integration: woken tasks run in a batch from one `queueMicrotask`; - the coop budget yields to a macrotask; promises appear only at the edge. -- Measure on the [TS benchmark](/ts/README.md#bench) against hand-written TS - and moq's WASM: handoff cost at await depths 1, 4, and 16, plus output size. - -Land the harness and the winning prototype's tests; record the loser's numbers -in the report and delete its code. - -Public API: none until Drop and Async land. diff --git a/quest/m2/ts-async.md b/quest/m2/ts-async.md index 4ede3b7f2..4ec568178 100644 --- a/quest/m2/ts-async.md +++ b/quest/m2/ts-async.md @@ -1,23 +1,38 @@ -# [L] Async in the TypeScript translator +# [M] Async in the TypeScript translator ## Goal -[rust2-ts](/ts/README.md) translates `async fn`, `.await`, and the `Future` and `Waker` -machinery kio is built on, keeping Rust's lazy futures: nothing runs until polled. -Differential tests against native Rust prove the same poll order and results. +[rust2-ts](/ts/README.md) translates the async code in moq-net's model and kio, keeping +Rust's lazy futures: nothing runs until polled, and dropping a future cancels it. +Differential tests against native Rust prove the same polls, wakes, drops, and results. ## Plan -Decided with the maintainer on 2026-10-23: async must keep Rust's lazy futures, so -an eager `async`/`await` mapping, as rust-js makes, is out. A future is a state -machine its executor polls; JS promises can sit at the edge, for callers. - -The [spike](/quest/m2/ts-async-spike.md) picks between generators and MIR state -machines; rewrite this plan to its report before starting. +Decided by the async spike ([#16](https://github.com/kixelated/rust2/pull/16)) on +2026-10-24: an async body is a generator lowered from THIR, not a state machine lowered +from MIR. MIR's were about twice as fast per await level, but would need a second +lowering of everything an async body can hold, and read as basic blocks. What landed +there: an `async fn` returns `rt.future(body, drop, ...upvars)`, whose body is a +module-level `function*` of what it captured (a generator function made per call costs +V8 about 25 times as much), `.await` is a poll loop around `yield`, and `rt.spawn` runs +a future from a microtask as a promise. The task fixture's trace test covers a +kio-shaped channel at await depths 1, 4, and 16. + +What moq-net and kio still need, by the census: + +- Async blocks and closures. An async closure fails translation; an async block that + captures a number by `&mut` must too, since its generator would change a copy. +- The rest of kio's machinery: atomics, `OnceLock`, the coop budget's thread-local, + `Tasks`, and `poll_fn`, `ready`, and `pending`. +- Boxed futures, which bind to hand-written TS at the boundary + ([model](/quest/m2/ts-model.md)). +- The edge: `rt.spawn`'s shape for callers, and cancelling a spawned task. + +If a profile of moq's client finds await overhead, `yield*` between translated futures +would skip each level's `poll`; measure it on the [TS benchmark](/ts/README.md#bench). Public API: the translator's output for async code. ## Required -- [Async and drop spike](/quest/m2/ts-async-spike.md) - the lowering this builds on -- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - a dropped future drops its state +- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - kio's waiters and wakers drop on paths the spike refused diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 2736f136a..300c827c3 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -2,23 +2,36 @@ ## Goal -[rust2-ts](/ts/README.md) translates types that implement `Drop`, which it refuses -today: each value's `drop()` runs where Rust drops it, in Rust's drop order, including -on early return, `?`, and panic, proven by differential tests against native Rust. +[rust2-ts](/ts/README.md) translates every value that drops in moq-net's model and kio: +each `drop()` runs where Rust drops it, in Rust's drop order, including on early +return, `?`, panic, and a cancelled future, proven by differential tests against +native Rust. ## Plan -Decided with the maintainer on 2026-10-23: `Drop` becomes an explicit `drop()`, -exposed as `[Symbol.dispose]` for JS callers. kio's producers close their channel -when the last one drops, so moq-net's model needs this first. - -THIR does not say where drops happen; MIR does, after drop elaboration. The -[spike](/quest/m2/ts-async-spike.md) decides whether to read drop points from MIR -beside the THIR lowering or move the lowering itself; rewrite this plan to its -report before starting. - -Public API: the translator's output for `Drop` types. - -## Required - -- [Async and drop spike](/quest/m2/ts-async-spike.md) - where drop points come from +Decided by the async spike ([#16](https://github.com/kixelated/rust2/pull/16)) on +2026-10-24: drop points come from the THIR lowering's own scopes, not MIR. What landed +there: a class that drops gets `[Symbol.dispose]` as drop glue (its `Drop` impl, then +each field); a variable drops in a `finally` at the end of its scope; a move leaves +`undefined` behind, so a variable moved on some paths drops on the others. The task +fixture's trace test proves it on kio's waiters, wakers, and channels. + +Each of these still fails translation with its span (the reject fixture has one of +each), and the census of moq-net and kio says which to lift first: + +- A temporary that drops, unless a call or binding takes it whole: borrowed, a field + or index of one, or a `match` or `if let` that moves only part of it. Rust drops it + at the end of its statement, or of the `match`. +- A closure that captures a value that drops, which dropping the closure would drop. +- A `for` loop over values that drop: each drops at the end of its iteration, and the + rest on a `break`. +- An enum whose variants hold values that drop, a tuple or array of them, a generic + type that implements `Drop`, a method taking such a `self` by value, and struct + update syntax from one. + +Watch the cost: each move of a value that drops writes `undefined` to where it was, and +each scope holding one becomes a `try`/`finally`. A pass that proves a variable moved on +every path, or on none, would drop most of both; measure it on the +[TS benchmark](/ts/README.md#bench) before adding it. + +Public API: the translator's output for values that drop. diff --git a/quest/m2/ts-shared.md b/quest/m2/ts-shared.md index 3e98205a1..4045e3622 100644 --- a/quest/m2/ts-shared.md +++ b/quest/m2/ts-shared.md @@ -14,6 +14,12 @@ Decided with the maintainer on 2026-10-23: deterministic reference counts in `rt.ts`, not GC-backed `WeakRef`. kio's `WaiterList` frees slots when `Weak::upgrade` fails and reads `weak_count`, so drop timing is observable. +The async spike ([#16](https://github.com/kixelated/rust2/pull/16)) landed what its +kio-shaped fixture needs, in `rt/task.ts`: `rt.Arc` counts strong references and +drops its value with the last, `rt.Weak` upgrades while one is left, and `rt.Mutex` +is its own guard. Left: `Rc`, `weak_count` (a dropped `Weak` counts nothing yet), +`RwLock`, atomics, `OnceLock`, `Cell`, and `RefCell`. + - `Send` and `Sync` bounds have no meaning in JS; accept them. - Keep Rust's failure modes where they are defined: a `RefCell` double borrow panics. A re-entrant `Mutex` lock on one thread is unspecified in Rust; pick diff --git a/ts/README.md b/ts/README.md index 1d64e5e21..e3e1889a1 100644 --- a/ts/README.md +++ b/ts/README.md @@ -43,7 +43,7 @@ it finds; translation still fails on any refusal. Each Rust module with translated items becomes a file (`lib.ts`, `coding/varint.ts`), with a `.ts.map` source map into the Rust it came from. `rt.ts` beside them is the -runtime: what std does that JS does not. +runtime: what std does that JS does not, with ownership and async in `rt/task.ts`. | Rust | TypeScript | | --- | --- | @@ -59,6 +59,10 @@ runtime: what std does that JS does not. | `&T`, `&mut T`, `Box` | the value: a `&mut` must point at an object JS can change in place | | closure | an arrow function | | constant | its value, inlined as Rust inlines it | +| a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | +| `Arc`, `Weak`, `Mutex` | `rt.Arc`, counted; `rt.Weak`; `rt.Mutex`, its own guard | +| `async fn` | a function returning `rt.Future`, around a generator | +| `Poll`, `Waker`, `Context` | `T \| typeof rt.Pending`; `rt.Waker`, which is also the context | `usize` is 32 bits, as on wasm32, so it is exact in a `number`. Arithmetic is checked as a debug build checks it, so translated code panics where native code would: it never @@ -80,6 +84,19 @@ own function, and instances that share a name are suffixed by type, as in array, or an `Option` or `Result` holding one, is copied where Rust copies it, since JS would share the object. +A value drops where Rust drops it, if dropping it does something JS can see: a `Drop` +impl, an `Arc`'s count, or a waker. A variable drops at the end of its scope through a +`finally`, so an early return, `?`, a panic, or a cancelled future drops it too, and a +move leaves `undefined` where it was, which drops as nothing. + +An `async fn` returns a future without running anything: `rt.future(body, drop, +...upvars)`, whose body is a module-level generator of what the function captured. Each +`.await` polls in a loop around `yield`. A poll after the future returned panics, and +dropping it cancels it: unpolled, it drops what it captured; suspended, its generator +returns through the `finally` blocks that drop its locals. `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. + Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` build sets `rewriteRelativeImportExtensions`, or `allowImportingTsExtensions` with `noEmit`. @@ -89,9 +106,10 @@ Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` bu faster but waits until `just ts bench` measures `bigint` as the cost. - `Result` is a plain `{ ok, value } | { ok, error }` object rather than an exception, so `?` and `match` keep Rust's control flow exactly. -- Bodies lower from THIR, which keeps loops, `match`, and `?` shaped as written. It does - not say where values drop; [Drop](/quest/m2/ts-drop.md) decides how to get that from - MIR. +- Bodies lower from THIR, which keeps loops, `match`, and `?` shaped as written. Drops + come from its scopes, and async bodies are generators: MIR state machines were about + twice as fast per await level, but read as basic blocks and would need a second + lowering ([#16](https://github.com/kixelated/rust2/pull/16) measured both). ## Never @@ -101,8 +119,10 @@ bind to hand-written TS through config ([model](/quest/m2/ts-model.md)). ## Not yet -These fail translation: floats, `char`, statics, `async`, -types that implement `Drop`, iterator adaptors (`for` over ranges, slices, arrays, and +These fail translation: floats, `char`, statics, async blocks that borrow a number +mutably and async closures, values that drop as temporaries not moved whole, in a +closure's captures, in a `for` loop, or in an enum, tuple, or generic `Drop` type +([Drop](/quest/m2/ts-drop.md)), iterator adaptors (`for` over ranges, slices, arrays, and `Vec` works), or-patterns that bind, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a `String` with `write!`, a `move` closure copying a mutable variable, `mem::swap`, `replace`, or `take` of a reference's whole @@ -126,6 +146,10 @@ built natively for wasm32 and run beside its translation on the same inputs by and writes its errors' `Display` and `Debug`. - `lang` covers every integer width's arithmetic and casts, control flow, patterns, `Copy` aggregates, and formatting. +- `task` trims moq's kio to a channel of `Arc`ed state, waiters, and wakers, under async + functions. Its harness 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. - `reject` holds constructs outside the subset; its expected errors are `expected.txt`, and its expected census is `census.md`. @@ -145,4 +169,9 @@ translation to show the noise. The report records the host and engine versions, each route's bundle size raw and gzipped. It sets no threshold; the nightly workflow runs it and posts the report to its summary. +The task fixture's `bench::run` times an async handoff: a value sent to a task parked on +its channel, read through 1, 4, or 16 async functions. Its translation runs polled at +once, as natively, and on `rt.spawn`; its hand-written route is the same handoff with +promises, as moq's TypeScript writes it. + The bench shell adds Bun, Chromium, and the wasm-bindgen that builds moq-wasm's package. diff --git a/ts/bench/entry.ts b/ts/bench/entry.ts index 31d23af54..ed2fcada1 100644 --- a/ts/bench/entry.ts +++ b/ts/bench/entry.ts @@ -5,10 +5,14 @@ import { Wasm } from "../tests/wasm.ts"; import { measure, type Route } from "./time.ts"; import type { Workload } from "./workloads.ts"; +type Workloads = { name: string; op: Workload["op"]; items: number; input: string }[]; + export interface Config { sampleMs: number; rounds: number; - workloads: { name: string; op: Workload["op"]; items: number; input: string }[]; + workloads: Workloads; + /** The async handoff's, on the task fixture. */ + handoffs: Workloads; } const browser = typeof window !== "undefined"; @@ -22,9 +26,9 @@ async function load(name: string): Promise { return new Uint8Array(await (await fetch(url)).arrayBuffer()); } -/** A bundled route, whose `run` returns its output as `view` reads it. */ -async function route(name: string, file: string, view: (out: T) => Uint8Array): Promise { - const { run } = await import(new URL(file, import.meta.url).href); +/** A bundled route, whose `run` (or `exported`) returns its output as `view` reads it. */ +async function route(name: string, file: string, view: (out: T) => Uint8Array, exported = "run"): Promise { + const run = (await import(new URL(file, import.meta.url).href))[exported]; return { name, run, output: async (input) => view(await run(input)) }; } @@ -35,9 +39,13 @@ function engine(): string { return `Node ${process.version} (V8 ${process.versions.v8})`; } +function parse(workloads: Workloads): Workload[] { + return workloads.map((w) => ({ ...w, input: Uint8Array.from(w.input.match(/../g) ?? [], (b) => parseInt(b, 16)) })); +} + async function main() { const config: Config = JSON.parse(new TextDecoder().decode(await load("workloads.json"))); - const workloads = config.workloads.map((w) => ({ ...w, input: Uint8Array.from(w.input.match(/../g) ?? [], (b) => parseInt(b, 16)) })); + const workloads = parse(config.workloads); const wasm = new Wasm(await WebAssembly.compile(await load("bench.wasm"))); // The A/A route is the translation again, loaded as its own module: its spread from the // first is the measurement's noise. @@ -48,6 +56,18 @@ async function main() { await route("A/A", "translated-aa.js", translated), ]; const timings = await measure(wasm, routes, workloads, config); + + // The async handoff: the translation polled at once by a one-task executor, as the + // native and WASM routes are, and on the runtime's microtask executor. + const bytes = (out: Uint8Array) => out; + const handoffRoutes = [ + await route("hand-written", "task-hand.js", bytes, "handWritten"), + await route("translated", "task-translated.js", bytes), + await route("spawned", "task-translated.js", bytes, "spawn"), + await route("A/A", "task-translated-aa.js", bytes), + ]; + const taskWasm = new Wasm(await WebAssembly.compile(await load("task.wasm"))); + timings.push(...(await measure(taskWasm, handoffRoutes, parse(config.handoffs), config))); return { engine: engine(), timings }; } diff --git a/ts/bench/main.ts b/ts/bench/main.ts index 3d3d7ac00..03d5e0a52 100644 --- a/ts/bench/main.ts +++ b/ts/bench/main.ts @@ -2,7 +2,10 @@ // and Chrome, and reports the numbers with each route's bundle size. // // usage: bun main.ts --translated --wasm --native --moq -// --moq-wasm --out [--sample-ms 10] [--rounds 15] +// --moq-wasm --task --task-wasm --task-native +// --out [--sample-ms 10] [--rounds 15] +// +// The task fixture's async handoff runs beside the codec, against moq's way with promises. import { cpus, release, totalmem } from "node:os"; import { join, resolve } from "node:path"; @@ -12,7 +15,7 @@ import type { BunPlugin } from "bun"; import { Wasm } from "../tests/wasm.ts"; import type { Config } from "./entry.ts"; import { hex, type Timing } from "./time.ts"; -import { type Workload, workloads } from "./workloads.ts"; +import { handoffs, type Workload, workloads } from "./workloads.ts"; interface Engine { engine: string; @@ -26,6 +29,9 @@ const { values: args } = parseArgs({ native: { type: "string" }, moq: { type: "string" }, "moq-wasm": { type: "string" }, + task: { type: "string" }, + "task-wasm": { type: "string" }, + "task-native": { type: "string" }, out: { type: "string" }, "sample-ms": { type: "string", default: "10" }, rounds: { type: "string", default: "15" }, @@ -72,12 +78,37 @@ const handWritten = join(import.meta.dir, "moq.ts"); const translated = join(arg("translated"), "bench.ts"); const wasmBytes = await read(arg("wasm")); const translation = await bundle(translated); + +// The task fixture's translation, as `bench/task.ts` drives it. +async function taskEntry(dir: string): Promise { + const entry = join(dir, "bench-entry.ts"); + await Bun.write( + entry, + `import * as rt from "./rt.ts"; +import { Channel, drain } from "./model.ts"; +import { polled, spawned } from ${JSON.stringify(join(import.meta.dir, "task.ts"))}; + +const fixture = { Pending: rt.Pending, spawn: rt.spawn, Channel, drain }; +export const run = polled(fixture); +export const spawn = spawned(fixture); +`, + ); + return entry; +} +const taskHand = join(import.meta.dir, "task.ts"); +const taskTranslated = await taskEntry(arg("task")); +const taskWasmBytes = await read(arg("task-wasm")); +const taskTranslation = await bundle(taskTranslated); await Promise.all([ Bun.write(join(out, "entry.js"), await bundle(join(import.meta.dir, "entry.ts"))), Bun.write(join(out, "moq.js"), await bundle(handWritten, { plugins: [moq] })), Bun.write(join(out, "translated.js"), translation), Bun.write(join(out, "translated-aa.js"), translation), Bun.write(join(out, "bench.wasm"), wasmBytes), + Bun.write(join(out, "task-hand.js"), await bundle(taskHand)), + Bun.write(join(out, "task-translated.js"), taskTranslation), + Bun.write(join(out, "task-translated-aa.js"), taskTranslation), + Bun.write(join(out, "task.wasm"), taskWasmBytes), Bun.write(join(out, "package.json"), '{ "type": "module" }\n'), Bun.write(join(out, "index.html"), page), ]); @@ -88,10 +119,19 @@ const sizes = [ { route: "hand-written", files: [await bundle(handWritten, { minify: true, plugins: [moq] })] }, { route: "translated", files: [await bundle(translated, { minify: true })] }, { route: "moq-wasm package", files: [await read(join(moqWasm, "moq_bg.wasm")), await read(join(moqWasm, "moq.js"))] }, -].map(({ route, files }) => { +].map(measureSize); + +// The task fixture: its channel, its async functions, and their runtime, as each route ships them. +const taskSizes = [ + { route: "wasm", files: [taskWasmBytes] }, + { route: "hand-written", files: [await bundle(taskHand, { minify: true })] }, + { route: "translated", files: [await bundle(taskTranslated, { minify: true })] }, +].map(measureSize); + +function measureSize({ route, files }: { route: string; files: Uint8Array[] }) { const sum = (f: (b: Uint8Array) => number) => files.reduce((n, b) => n + f(b), 0); return { route, raw: sum((b) => b.byteLength), gzip: sum((b) => Bun.gzipSync(b, { level: 9 }).byteLength) }; -}); +} // The workloads, made by the wasm32 build, which also gives each its expected output. const wasm = new Wasm(await WebAssembly.compile(wasmBytes)); @@ -101,25 +141,43 @@ function expected(input: Uint8Array): Uint8Array { return output; } const list = workloads(expected); +const handoffList = handoffs(); const config: Config = { sampleMs, rounds, workloads: list.map((w) => ({ name: w.name, op: w.op, items: w.items, input: hex(w.input) })), + handoffs: handoffList.map((w) => ({ name: w.name, op: w.op, items: w.items, input: hex(w.input) })), }; await Bun.write(join(out, "workloads.json"), JSON.stringify(config)); -async function native(): Promise { - const stdin = Buffer.from(list.map((w) => `${w.name}/${w.op} ${hex(w.input)}\n`).join("")); - const proc = Bun.spawn([arg("native"), String(sampleMs), String(rounds)], { stdin, stderr: "inherit" }); +/** The native route of `list`: `bin` times each on the host, which must match `expected`. */ +async function nativeRoute(bin: string, list: Workload[], expected: (input: Uint8Array) => Uint8Array): Promise { + // Names are one word on the binary's lines. + const key = (w: Workload) => `${w.name}/${w.op}`.replaceAll(" ", "-"); + const stdin = Buffer.from(list.map((w) => `${key(w)} ${hex(w.input)}\n`).join("")); + const proc = Bun.spawn([bin, String(sampleMs), String(rounds)], { stdin, stderr: "inherit" }); const lines = (await new Response(proc.stdout).text()).trim().split("\n"); - if ((await proc.exited) !== 0) throw new Error("the native benchmark failed"); - const timings = lines.map((line, i): Timing => { + if ((await proc.exited) !== 0) throw new Error(`the native benchmark ${bin} failed`); + return lines.map((line, i): Timing => { const [name, calls, ns, output] = line.split(" "); const w = list[i]; - if (name !== `${w.name}/${w.op}`) throw new Error(`the native benchmark printed ${name} for ${w.name}/${w.op}`); + if (name !== key(w)) throw new Error(`the native benchmark printed ${name} for ${key(w)}`); if (output !== hex(expected(w.input))) throw new Error(`native Rust on the host differs from wasm32 on ${name}`); return { workload: w.name, op: w.op, route: "native", calls: Number(calls), ns: ns.split(",").map((n) => Number(n) / w.items) }; }); +} + +async function native(): Promise { + const taskWasm = new Wasm(await WebAssembly.compile(taskWasmBytes)); + const handoff = (input: Uint8Array) => { + const output = taskWasm.call(input); + if (output === "panic") throw new Error(`native Rust panics on ${hex(input)}`); + return output; + }; + const timings = [ + ...(await nativeRoute(arg("native"), list, expected)), + ...(await nativeRoute(arg("task-native"), handoffList, handoff)), + ]; return { engine: "native", timings }; } @@ -177,7 +235,7 @@ for (const run of [() => script("node"), () => script(process.execPath), chrome] const report = render(); await Bun.write(join(out, "report.md"), report); -await Bun.write(join(out, "report.json"), JSON.stringify({ native: host, engines, sizes }, null, "\t")); +await Bun.write(join(out, "report.json"), JSON.stringify({ native: host, engines, sizes, taskSizes }, null, "\t")); console.log(report); function render(): string { @@ -231,9 +289,49 @@ function render(): string { }), ); } + lines.push(...renderHandoffs()); return `${lines.join("\n")}\n`; } +/** The async handoff on every route, and each route's size. */ +function renderHandoffs(): string[] { + const routes = ["native", "wasm", "hand-written", "translated", "spawned", "A/A"]; + const lines = [ + "", + "## Async handoff", + "", + "Nanoseconds per handoff: a value sent to a task parked on a kio-shaped channel, which", + "wakes it, polls it through `depth` async functions to the channel, and parks it again.", + "`native` and `wasm` run the task fixture's `bench.rs`, which polls the task at once on", + "each wake, and `translated` its translation polled the same way. `spawned` runs the", + "translation on the runtime's `spawn`, which polls woken tasks from a microtask.", + "`hand-written` is the handoff with promises and `async` functions, as moq's TypeScript", + "writes it, where each handoff waits for the reader to park again. Bundle sizes are of", + "the channel, the async functions, and their runtime.", + "", + "| route | raw | gzip |", + "| --- | ---: | ---: |", + ...taskSizes.map((s) => `| ${s.route} | ${s.raw} | ${s.gzip} |`), + ]; + for (const engine of engines) { + const all = [...host.timings, ...engine.timings]; + lines.push( + "", + `### ${engine.engine}`, + "", + `| depth | ${routes.join(" | ")} | translated ÷ hand-written |`, + `| --- |${" ---: |".repeat(routes.length + 1)}`, + ...handoffList.map((w) => { + const cells = routes.map((r) => cell(find(all, w, r).ns)); + const median = (route: string) => stats(find(all, w, route).ns).median; + const ratio = (median("translated") / median("hand-written")).toFixed(2); + return `| ${w.name.replace("depth ", "")} | ${cells.join(" | ")} | ${ratio} |`; + }), + ); + } + return lines; +} + function find(timings: Timing[], w: Workload, route: string): Timing { const timing = timings.find((t) => t.workload === w.name && t.op === w.op && t.route === route); if (!timing) throw new Error(`no ${route} timing for ${w.name} ${w.op}`); diff --git a/ts/bench/workloads.ts b/ts/bench/workloads.ts index ac434e1c3..7ac31273a 100644 --- a/ts/bench/workloads.ts +++ b/ts/bench/workloads.ts @@ -5,8 +5,9 @@ export interface Workload { /** What is coded, such as `varint/quic/2B` or `frames/video/lite-07`. */ name: string; - op: "encode" | "decode"; - /** Varints, frame headers, or messages per call, which each time is divided by. */ + /** `encode` or `decode`, or `handoff` for the async benchmark. */ + op: string; + /** Varints, frame headers, messages, or handoffs per call, which each time is divided by. */ items: number; input: Uint8Array; } @@ -47,6 +48,24 @@ export function workloads(encode: (input: Uint8Array) => Uint8Array): Workload[] return out; } +/** The async handoff at each await depth: `bench::run` of the task fixture. */ +export function handoffs(): Workload[] { + // One call hands this many values over. + const count = 1000; + return [1, 4, 16].map((depth) => ({ + name: `depth ${depth}`, + op: "handoff", + items: count, + input: Uint8Array.of(depth, ...u32(count)), + })); +} + +function u32(v: number): number[] { + const bytes = new Uint8Array(4); + new DataView(bytes.buffer).setUint32(0, v); + return [...bytes]; +} + function u64(v: bigint): number[] { const bytes = new Uint8Array(8); new DataView(bytes.buffer).setBigUint64(0, v); diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 5d1145ad3..e55c9df9f 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,35 +1,43 @@ # Census of `reject-fixture` -- Refusals: 36 -- Function instances: 19 -- Generic functions no instance reached, lowered over their type parameters: 1 +- Refusals: 46 +- Function instances: 27 +- Generic functions no instance reached, lowered over their type parameters: 2 ## By construct | Count | Construct | First | | ---: | --- | --- | +| 6 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | | 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | -| 5 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | -| 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:99:17 | +| 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:163:17 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | -| 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:63:3 | -| 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:65:3 | -| 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:64:3 | -| 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:68:3 | +| 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | +| 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:127:3 | +| 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:129:3 | +| 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:128:3 | +| 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:132:3 | +| 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:92:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | +| 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | -| 1 | a cast to `_` | fixtures/reject/src/lib.rs:110:2 | -| 1 | a closure that copies a mutable variable | fixtures/reject/src/lib.rs:80:18 | -| 1 | a mutable reference to `_`, which is no object it can change in place | fixtures/reject/src/lib.rs:75:17 | -| 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:60:3 | -| 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:67:3 | -| 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:87:3 | +| 1 | a cast to `_` | fixtures/reject/src/lib.rs:174:2 | +| 1 | a closure of type `_` | fixtures/reject/src/lib.rs:116:10 | +| 1 | a closure that captures a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:68:23 | +| 1 | a closure that copies a mutable variable | fixtures/reject/src/lib.rs:144:18 | +| 1 | a field of a temporary that drops: bind it to a variable first | fixtures/reject/src/lib.rs:62:2 | +| 1 | a method that takes `self` by value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:20 | +| 1 | a mutable reference to `_`, which is no object it can change in place | fixtures/reject/src/lib.rs:139:17 | +| 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:124:3 | +| 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:131:3 | +| 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:108:3 | +| 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:151:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | -| 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:66:3 | -| 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:61:3 | -| 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:62:3 | -| 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:94:2 | +| 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:130:3 | +| 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:125:3 | +| 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:126:3 | +| 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:158:2 | | 1 | unsupported literal of type `_` | fixtures/reject/src/lib.rs:7:6 | ## By API @@ -39,59 +47,71 @@ The type or module each refused type or path belongs to. | Count | API | First | | ---: | --- | --- | | 6 | `f64` | fixtures/reject/src/lib.rs:6:1 | -| 4 | `std::string::String` | fixtures/reject/src/lib.rs:73:16 | -| 3 | `Meters` | fixtures/reject/src/lib.rs:99:17 | +| 4 | `std::string::String` | fixtures/reject/src/lib.rs:137:16 | +| 3 | `Meters` | fixtures/reject/src/lib.rs:163:17 | | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | +| 2 | `{async closure}` | fixtures/reject/src/lib.rs:116:6 | +| 1 | `Boxed` | fixtures/reject/src/lib.rs:92:1 | | 1 | `Option` | fixtures/reject/src/lib.rs:31:15 | +| 1 | `Slot` | fixtures/reject/src/lib.rs:88:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | +| 1 | `u8` | fixtures/reject/src/lib.rs:108:3 | +| 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | ## By type or path | Count | Construct | Type or path | First | | ---: | --- | --- | --- | -| 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:99:17 | +| 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:163:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | +| 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:92:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | -| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:73:16 | +| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:137:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | -| 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:73:16 | +| 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:137:16 | | 1 | a cast from `_` | `char` | fixtures/reject/src/lib.rs:11:2 | -| 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:110:2 | -| 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:75:17 | +| 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:174:2 | +| 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:116:10 | +| 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:139:17 | +| 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:108:3 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | +| 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:88:1 | +| 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | | 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | | 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | -| 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:75:10 | +| 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:139:10 | | 1 | unsupported call to `_` | `std::slice::iter` | fixtures/reject/src/lib.rs:40:4 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:36:4 | | 1 | unsupported literal of type `_` | `f64` | fixtures/reject/src/lib.rs:7:6 | | 1 | unsupported type `_` | `char` | fixtures/reject/src/lib.rs:10:18 | | 1 | unsupported type `_` | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | +| 1 | unsupported type `_` | `{async closure}` | fixtures/reject/src/lib.rs:116:6 | ## Spans +
unsupported type `_` (6) + +- fixtures/reject/src/lib.rs:6:1: unsupported type `f64` +- fixtures/reject/src/lib.rs:6:14: unsupported type `f64` +- fixtures/reject/src/lib.rs:10:18: unsupported type `char` +- fixtures/reject/src/lib.rs:14:16: unsupported type `dyn std::ops::Fn(u8) -> u8` +- fixtures/reject/src/lib.rs:116:6: unsupported type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` +- fixtures/reject/src/lib.rs:172:1: unsupported type `f64` + +
+
unsupported call to `_` (5) - fixtures/reject/src/lib.rs:36:4: unsupported call to `std::slice::::sort` - fixtures/reject/src/lib.rs:40:4: unsupported call to `core::slice::::iter` - fixtures/reject/src/lib.rs:40:11: unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` - fixtures/reject/src/lib.rs:40:31: unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` -- fixtures/reject/src/lib.rs:75:10: unsupported call to `::write_fmt` - -
- -
unsupported type `_` (5) - -- fixtures/reject/src/lib.rs:6:1: unsupported type `f64` -- fixtures/reject/src/lib.rs:6:14: unsupported type `f64` -- fixtures/reject/src/lib.rs:10:18: unsupported type `char` -- fixtures/reject/src/lib.rs:14:16: unsupported type `dyn std::ops::Fn(u8) -> u8` -- fixtures/reject/src/lib.rs:108:1: unsupported type `f64` +- fixtures/reject/src/lib.rs:139:10: unsupported call to `::write_fmt`
@@ -99,46 +119,59 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:19:13: a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change - fixtures/reject/src/lib.rs:25:6: a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change -- fixtures/reject/src/lib.rs:73:16: a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change +- fixtures/reject/src/lib.rs:137:16: a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change
replacing the value behind a reference to `_` (3) -- fixtures/reject/src/lib.rs:99:17: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:99:20: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:103:25: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:163:17: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:163:20: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:167:25: replacing the value behind a reference to `Meters`
`_`: a JS value of `_` is a copy, so a reference can't change it (2) - fixtures/reject/src/lib.rs:19:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it -- fixtures/reject/src/lib.rs:73:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it +- fixtures/reject/src/lib.rs:137:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it + +
+ +
dropping `_`, which is not supported yet (2) + +- fixtures/reject/src/lib.rs:66:31: dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet +- fixtures/reject/src/lib.rs:88:1: dropping `Slot`, which is not supported yet
`Binary` formatting, as in `{:b}`, is not supported (1) -- fixtures/reject/src/lib.rs:63:3: `Binary` formatting, as in `{:b}`, is not supported +- fixtures/reject/src/lib.rs:127:3: `Binary` formatting, as in `{:b}`, is not supported
`LowerExp` formatting, as in `{:e}`, is not supported (1) -- fixtures/reject/src/lib.rs:65:3: `LowerExp` formatting, as in `{:e}`, is not supported +- fixtures/reject/src/lib.rs:129:3: `LowerExp` formatting, as in `{:e}`, is not supported
`Octal` formatting, as in `{:o}`, is not supported (1) -- fixtures/reject/src/lib.rs:64:3: `Octal` formatting, as in `{:o}`, is not supported +- fixtures/reject/src/lib.rs:128:3: `Octal` formatting, as in `{:o}`, is not supported
`Pointer` formatting, as in `{:p}`, is not supported (1) -- fixtures/reject/src/lib.rs:68:3: `Pointer` formatting, as in `{:p}`, is not supported +- fixtures/reject/src/lib.rs:132:3: `Pointer` formatting, as in `{:p}`, is not supported + +
+ +
`_` is generic and implements `Drop`, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:92:1: `Boxed` is generic and implements `Drop`, which is not supported yet
@@ -148,6 +181,12 @@ The type or module each refused type or path belongs to. +
a `for` loop over values that drop, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:76:6: a `for` loop over values that drop, which is not supported yet + +
+
a cast from `_` (1) - fixtures/reject/src/lib.rs:11:2: a cast from `char` @@ -156,37 +195,67 @@ The type or module each refused type or path belongs to.
a cast to `_` (1) -- fixtures/reject/src/lib.rs:110:2: a cast to `f64` +- fixtures/reject/src/lib.rs:174:2: a cast to `f64` + +
+ +
a closure of type `_` (1) + +- fixtures/reject/src/lib.rs:116:10: a closure of type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` + +
+ +
a closure that captures a value that drops, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:68:23: a closure that captures a value that drops, which is not supported yet
a closure that copies a mutable variable (1) -- fixtures/reject/src/lib.rs:80:18: a closure that copies a mutable variable +- fixtures/reject/src/lib.rs:144:18: a closure that copies a mutable variable + +
+ +
a field of a temporary that drops: bind it to a variable first (1) + +- fixtures/reject/src/lib.rs:62:2: a field of a temporary that drops: bind it to a variable first + +
+ +
a method that takes `self` by value that drops, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:51:20: a method that takes `self` by value that drops, which is not supported yet
a mutable reference to `_`, which is no object it can change in place (1) -- fixtures/reject/src/lib.rs:75:17: a mutable reference to `std::string::String`, which is no object it can change in place +- fixtures/reject/src/lib.rs:139:17: a mutable reference to `std::string::String`, which is no object it can change in place
a precision, as in `{:.2}`, is not supported (1) -- fixtures/reject/src/lib.rs:60:3: a precision, as in `{:.2}`, is not supported +- fixtures/reject/src/lib.rs:124:3: a precision, as in `{:.2}`, is not supported
a width or precision from an argument, as in `{:1$}`, is not supported (1) -- fixtures/reject/src/lib.rs:67:3: a width or precision from an argument, as in `{:1$}`, is not supported +- fixtures/reject/src/lib.rs:131:3: a width or precision from an argument, as in `{:1$}`, is not supported + +
+ +
an async body that borrows `_` mutably, which is no object it can change in place (1) + +- fixtures/reject/src/lib.rs:108:3: an async body that borrows `u8` mutably, which is no object it can change in place
an or-pattern with bindings (1) -- fixtures/reject/src/lib.rs:87:3: an or-pattern with bindings +- fixtures/reject/src/lib.rs:151:3: an or-pattern with bindings
@@ -198,25 +267,25 @@ The type or module each refused type or path belongs to.
hex `Debug`, as in `{:x?}`, is not supported (1) -- fixtures/reject/src/lib.rs:66:3: hex `Debug`, as in `{:x?}`, is not supported +- fixtures/reject/src/lib.rs:130:3: hex `Debug`, as in `{:x?}`, is not supported
the `+` flag of a format spec is not supported (1) -- fixtures/reject/src/lib.rs:61:3: the `+` flag of a format spec is not supported +- fixtures/reject/src/lib.rs:125:3: the `+` flag of a format spec is not supported
the `-` flag of a format spec is not supported (1) -- fixtures/reject/src/lib.rs:62:3: the `-` flag of a format spec is not supported +- fixtures/reject/src/lib.rs:126:3: the `-` flag of a format spec is not supported
unsupported expression: StaticRef (1) -- fixtures/reject/src/lib.rs:94:2: unsupported expression: StaticRef +- fixtures/reject/src/lib.rs:158:2: unsupported expression: StaticRef
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index d9c991bc5..cc2f4f518 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -1,4 +1,4 @@ -a root must not be generic at fixtures/reject/src/lib.rs:108:1 +a root must not be generic at fixtures/reject/src/lib.rs:172:1 no item `missing` in the crate unsupported type `f64` at fixtures/reject/src/lib.rs:6:14 unsupported literal of type `f64` at fixtures/reject/src/lib.rs:7:6 @@ -15,22 +15,32 @@ unsupported call to `std::slice::::sort` at fixtures/reject/src/lib.r unsupported call to `core::slice::::iter` at fixtures/reject/src/lib.rs:40:4 unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` at fixtures/reject/src/lib.rs:40:11 unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` at fixtures/reject/src/lib.rs:40:31 -a precision, as in `{:.2}`, is not supported at fixtures/reject/src/lib.rs:60:3 -the `+` flag of a format spec is not supported at fixtures/reject/src/lib.rs:61:3 -the `-` flag of a format spec is not supported at fixtures/reject/src/lib.rs:62:3 -`Binary` formatting, as in `{:b}`, is not supported at fixtures/reject/src/lib.rs:63:3 -`Octal` formatting, as in `{:o}`, is not supported at fixtures/reject/src/lib.rs:64:3 -`LowerExp` formatting, as in `{:e}`, is not supported at fixtures/reject/src/lib.rs:65:3 -hex `Debug`, as in `{:x?}`, is not supported at fixtures/reject/src/lib.rs:66:3 -a width or precision from an argument, as in `{:1$}`, is not supported at fixtures/reject/src/lib.rs:67:3 -`Pointer` formatting, as in `{:p}`, is not supported at fixtures/reject/src/lib.rs:68:3 -a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change at fixtures/reject/src/lib.rs:73:16 -`&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:73:16 -a mutable reference to `std::string::String`, which is no object it can change in place at fixtures/reject/src/lib.rs:75:17 -unsupported call to `::write_fmt` at fixtures/reject/src/lib.rs:75:10 -a closure that copies a mutable variable at fixtures/reject/src/lib.rs:80:18 -an or-pattern with bindings at fixtures/reject/src/lib.rs:87:3 -unsupported expression: StaticRef at fixtures/reject/src/lib.rs:94:2 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:99:17 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:99:20 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:103:25 +a method that takes `self` by value that drops, which is not supported yet at fixtures/reject/src/lib.rs:51:20 +a field of a temporary that drops: bind it to a variable first at fixtures/reject/src/lib.rs:62:2 +a closure that captures a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:68:23 +dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet at fixtures/reject/src/lib.rs:66:31 +a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:76:6 +dropping `Slot`, which is not supported yet at fixtures/reject/src/lib.rs:88:1 +`Boxed` is generic and implements `Drop`, which is not supported yet at fixtures/reject/src/lib.rs:100:6 +an async body that borrows `u8` mutably, which is no object it can change in place at fixtures/reject/src/lib.rs:108:3 +unsupported type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` at fixtures/reject/src/lib.rs:116:6 +a closure of type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` at fixtures/reject/src/lib.rs:116:10 +a precision, as in `{:.2}`, is not supported at fixtures/reject/src/lib.rs:124:3 +the `+` flag of a format spec is not supported at fixtures/reject/src/lib.rs:125:3 +the `-` flag of a format spec is not supported at fixtures/reject/src/lib.rs:126:3 +`Binary` formatting, as in `{:b}`, is not supported at fixtures/reject/src/lib.rs:127:3 +`Octal` formatting, as in `{:o}`, is not supported at fixtures/reject/src/lib.rs:128:3 +`LowerExp` formatting, as in `{:e}`, is not supported at fixtures/reject/src/lib.rs:129:3 +hex `Debug`, as in `{:x?}`, is not supported at fixtures/reject/src/lib.rs:130:3 +a width or precision from an argument, as in `{:1$}`, is not supported at fixtures/reject/src/lib.rs:131:3 +`Pointer` formatting, as in `{:p}`, is not supported at fixtures/reject/src/lib.rs:132:3 +a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change at fixtures/reject/src/lib.rs:137:16 +`&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:137:16 +a mutable reference to `std::string::String`, which is no object it can change in place at fixtures/reject/src/lib.rs:139:17 +unsupported call to `::write_fmt` at fixtures/reject/src/lib.rs:139:10 +a closure that copies a mutable variable at fixtures/reject/src/lib.rs:144:18 +an or-pattern with bindings at fixtures/reject/src/lib.rs:151:3 +unsupported expression: StaticRef at fixtures/reject/src/lib.rs:158:2 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:163:17 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:163:20 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:167:25 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index ea964364b..83c3c55d2 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -40,18 +40,82 @@ pub fn iterators(v: &[u8]) -> usize { v.iter().filter(|b| **b > 1).count() } -pub struct Guard; +pub struct Noisy(pub u8); -impl Drop for Guard { +impl Drop for Noisy { fn drop(&mut self) {} } -pub fn guard() -> Guard { - Guard +impl Noisy { + /// A move out of `self` would leave `this` undefined, which JS can't. + pub fn into_inner(self) -> u8 { + self.0 + } +} + +pub fn make() -> Noisy { + Noisy(1) +} + +/// The temporary drops at the end of the statement, which nothing in JS marks. +pub fn temporary() -> u8 { + make().0 +} + +/// Dropping the closure would drop what it captured. +pub fn owning_closure() -> u8 { + let n = make(); + let f = move || drop(n); + f(); + 0 +} + +/// Each element drops at the end of its iteration, and the rest on a `break`. +pub fn each(v: Vec) -> u8 { + let mut sum = 0; + for n in v { + sum += n.0; + } + sum +} + +pub enum Slot { + Empty, + Full(Noisy), +} + +/// An enum's drop glue would switch on its variant. +pub fn slot(s: Slot) -> bool { + matches!(s, Slot::Empty) +} + +pub struct Boxed(pub T); + +impl Drop for Boxed { + fn drop(&mut self) {} +} + +/// A generic `Drop` impl has an instance per type. +pub fn boxed() -> u8 { + let b = Boxed(1u8); + b.0 +} + +/// The async block's generator would change its own copy of `n`. +pub fn async_borrow() -> u8 { + let mut n = 1u8; + let f = async { + n += 1; + }; + drop(f); + n } -pub async fn later() -> u8 { - 1 +/// An async closure is a coroutine closure, not an async body. +pub fn async_closure() -> u8 { + let f = async || 1u8; + drop(f); + 0 } /// Format specs outside what moq uses. diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 377410e96..694d3550f 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -8,8 +8,14 @@ roots = [ "nested", "sorted", "iterators", - "guard", - "later", + "Noisy", + "temporary", + "owning_closure", + "each", + "slot", + "boxed", + "async_borrow", + "async_closure", "specs", "written", "captured", diff --git a/ts/justfile b/ts/justfile index 037a37bf9..580570991 100644 --- a/ts/justfile +++ b/ts/justfile @@ -84,13 +84,18 @@ bench checkout="": (moq checkout) cargo run --locked --quiet -- --config fixtures/codec/ts.toml --out "$out/translated" cargo build --locked --quiet --package codec-fixture --features bench --target wasm32-unknown-unknown --profile wasm-release cargo build --locked --quiet --package codec-fixture --example bench --release + cargo run --locked --quiet -- --config fixtures/task/ts.toml --out "$out/task" + cargo build --locked --quiet --package task-fixture --features bench --target wasm32-unknown-unknown --profile wasm-release + cargo build --locked --quiet --package task-fixture --example handoff --release # moq's hand-written TS imports its npm dependencies; its postinstall builds libav. (cd "$src" && bun install --frozen-lockfile --ignore-scripts --filter @moq/net) # moq-wasm's package, as moq's `just js wasm` builds it. (cd "$src" && cargo build --locked --quiet --package moq-wasm --target wasm32-unknown-unknown --profile wasm-release) wasm-bindgen --target web --out-name moq --out-dir "$out/moq-wasm" "$src/target/wasm32-unknown-unknown/wasm-release/moq_wasm.wasm" bun bench/main.ts --translated "$out/translated" --moq "$src" --moq-wasm "$out/moq-wasm" --out "$out" \ - --wasm target/wasm32-unknown-unknown/wasm-release/codec_fixture.wasm --native target/release/examples/bench + --wasm target/wasm32-unknown-unknown/wasm-release/codec_fixture.wasm --native target/release/examples/bench \ + --task "$out/task" \ + --task-wasm target/wasm32-unknown-unknown/wasm-release/task_fixture.wasm --task-native target/release/examples/handoff # Run cargo on the pinned nightly. cargo *args: diff --git a/ts/src/driver.rs b/ts/src/driver.rs index 56db71966..6694e2406 100644 --- a/ts/src/driver.rs +++ b/ts/src/driver.rs @@ -81,12 +81,6 @@ impl Translate { } impl Callbacks for Translate { - fn config(&mut self, config: &mut rustc_interface::interface::Config) { - // The async spike's state machines read MIR as the coroutine transform leaves it, - // before any optimization inlines std into it. - config.opts.unstable_opts.mir_opt_level = Some(0); - } - fn after_expansion<'tcx>(&mut self, _compiler: &Compiler, tcx: TyCtxt<'tcx>) -> Compilation { // Copy each body's THIR before borrow checking steals it. let bodies = lower::Bodies::collect(tcx); diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index f9310de21..3ba7edf98 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1676,6 +1676,11 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } + /// Whether `id` makes a temporary that drops, which only a statement could drop. + fn temporary_drops(&mut self, id: ExprId) -> bool { + !self.is_place(id) && self.t.drops(self.ty_of(id)) + } + /// Whether lowering `id` for its value moves it out of a place that drops it. pub fn moves(&mut self, id: ExprId) -> bool { let ty = self.ty_of(id); @@ -1840,7 +1845,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.copied(value, ty) } ExprKind::Borrow { borrow_kind, arg } => { - if !self.is_place(*arg) && self.t.drops(self.ty_of(*arg)) { + if self.temporary_drops(*arg) { return self.err(span, "a borrow of a temporary that drops: bind it to a variable first"); } if let BorrowKind::Mut { .. } = borrow_kind { @@ -1976,7 +1981,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } ExprKind::Adt(adt) => self.adt_expr(adt, ty, span, out), - ExprKind::Closure(closure) => self.closure(closure, span, out), + ExprKind::Closure(closure) => self.closure(closure, span), ExprKind::Assign { .. } | ExprKind::AssignOp { .. } | ExprKind::Break { .. } @@ -2076,6 +2081,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { variant_index, name, } => { + if self.temporary_drops(*lhs) { + return self.err(span, "a field of a temporary that drops: bind it to a variable first"); + } // A field of a tuple made in place, `(a, b).0`: its other fields still run. if let ExprKind::Tuple { fields } = &self.thir[self.strip(*lhs)].kind { let fields = fields.clone(); @@ -2098,6 +2106,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.project(base, lty, *variant_index, *name, span) } ExprKind::Index { lhs, index } => { + if self.temporary_drops(*lhs) { + return self.err( + span, + "an index into a temporary that drops: bind it to a variable first", + ); + } let base = self.place(*lhs, out); let base = self.path(base, *lhs, out); let lty = self.ty_of(*lhs); @@ -2182,6 +2196,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let info = self.t.adt(def, span); let base = match &adt.base { thir::AdtExprBase::None => None, + thir::AdtExprBase::Base(fru) if self.t.drops(self.ty_of(fru.base)) => { + return self.err(span, "struct update syntax from a value that drops"); + } thir::AdtExprBase::Base(fru) => { // The base is read after the fields, so earlier fields are saved first. let mut pre = Vec::new(); @@ -2271,37 +2288,16 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } - fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span, out: &mut Vec) -> Expr { - let tcx = self.t.tcx; - let local = closure.closure_id; - // The async spike's state machine prototype: the body from MIR. - if self.t.async_mir && tcx.coroutine_is_async(local.to_def_id()) { - let ty = self.subst(tcx.type_of(local).instantiate_identity().skip_norm_wip()); - for capture in tcx.closure_captures(local) { - if let Some(Local::Name { name, .. }) = self.locals.get(&capture.get_root_variable()) { - let name = name.clone(); - self.disown(&name); - } - } - let upvars = self.operands(&closure.upvars, out); - return super::mir::coroutine(self, local, ty, upvars, span); - } - self.lower_closure(local, span) - } - - /// Bind the variable `var`, which a closure body reads as an upvar, to `name`. - pub(super) fn bind_upvar(&mut self, var: HirId, name: String) { - self.names.insert(name.clone()); - self.locals.insert(var, Local::Name { name, mutable: false }); + fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span) -> Expr { + self.lower_closure(closure.closure_id, span) } - /// A closure as an arrow function, or an `async` body as a future around a generator, - /// reading its upvars as the variables they were bound to. + /// A closure as an arrow function, or an `async` body as a future around a generator. /// /// The generator is a function of its own, taking its upvars as parameters: a /// generator function made per call costs V8 a prototype object and a new shape for /// each generator, about 25 times what one made once does. - pub(super) fn lower_closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { + fn lower_closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { let tcx = self.t.tcx; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); @@ -2348,6 +2344,17 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ); continue; } + // Its generator takes the value: a change through the borrow would change a copy. + if let ty::UpvarCapture::ByRef(kind) = capture.info.capture_kind + && kind != ty::BorrowKind::Immutable + && self.t.object_kind(ty).is_none() + { + self.t.err( + capture.get_path_span(tcx), + format!("an async body that borrows `{ty}` mutably, which is no object it can change in place"), + ); + continue; + } let Some(Local::Name { name, .. }) = self.locals.get(&var).cloned() else { self.t .err(capture.get_path_span(tcx), "an async body capturing a function item"); diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 5a5560f9d..b6ebc05e1 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -126,14 +126,17 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { if !self.glued.insert(adt.did()) { return; } + // An enum that drops is refused where it drops: its glue would switch on its variant. let AdtRepr::Class { fields, .. } = &info.repr else { - self.err( - span, - format!( - "dropping the enum `{}`, which is not supported yet", - tcx.def_path_str(adt.did()) - ), - ); + if adt.has_dtor(tcx) { + self.err( + span, + format!( + "`{}` is an enum that implements `Drop`, which is not supported yet", + tcx.def_path_str(adt.did()) + ), + ); + } return; }; let mut body: Vec = Vec::new(); diff --git a/ts/src/lower/fmt.rs b/ts/src/lower/fmt.rs index 9edb55d72..9226e6883 100644 --- a/ts/src/lower/fmt.rs +++ b/ts/src/lower/fmt.rs @@ -421,7 +421,7 @@ pub fn std_impl<'tcx>( } /// One part of a `format_args!` template. -pub(super) enum Piece { +enum Piece { Lit(String), /// A placeholder writing the `index`th argument. Arg { @@ -431,7 +431,7 @@ pub(super) enum Piece { } /// A placeholder's options, from `FormattingOptions`' flags. -pub(super) struct Spec { +struct Spec { fill: char, align: Option, alternate: bool, @@ -441,7 +441,7 @@ pub(super) struct Spec { impl Spec { /// The runtime's `Spec` object, or `None` for the defaults. - pub(super) fn object(&self) -> Option { + fn object(&self) -> Option { let mut props = Vec::new(); if self.fill != ' ' { props.push(("fill", Expr::Str(self.fill.to_string()))); @@ -476,7 +476,7 @@ const DEFAULT_FLAGS: u32 = ' ' as u32 | 3 << 29; /// Decode a template as `core::fmt::write` reads it: literal pieces, and placeholders /// with their argument and options. An option outside the subset is an error naming it. -pub(super) fn decode(template: &[u8]) -> Result, &'static str> { +fn decode(template: &[u8]) -> Result, &'static str> { const TRUNCATED: &str = "a truncated template"; let byte = |i: usize| template.get(i).copied().ok_or(TRUNCATED); let u16_at = |i: usize| Ok::<_, &str>(u16::from_le_bytes([byte(i)?, byte(i + 1)?])); diff --git a/ts/src/lower/mir.rs b/ts/src/lower/mir.rs deleted file mode 100644 index 55f30ffe6..000000000 --- a/ts/src/lower/mir.rs +++ /dev/null @@ -1,999 +0,0 @@ -//! The async spike's state machine prototype: an `async` body lowered from MIR after -//! rustc's coroutine transform. Its future is a class whose fields are its state, its -//! upvars, and its saved locals; `poll` is the transform's resume function and the -//! dispose its drop shim, each a loop over a `switch` on the basic block. Types, calls, -//! drops, formatting, and closures go through the THIR lowering's own. - -use rustc_abi::{FieldIdx, VariantIdx}; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_hir::def_id::LocalDefId; -use rustc_index::IndexVec; -use rustc_middle::mir::interpret::Scalar; -use rustc_middle::mir::visit::{PlaceContext, Visitor}; -use rustc_middle::mir::{ - self, AggregateKind, AssertKind, BasicBlock, BinOp, CastKind, ConstValue, CoroutineSavedLocal, Local, Operand, - Place, ProjectionElem, Rvalue, StatementKind, TerminatorKind, UnOp, -}; -use rustc_middle::ty::{self, Ty}; -use rustc_span::Span; - -use super::body::Body; -use super::fmt::{self, Piece, Trait}; -use super::library::{Args, Std}; -use super::num::{self, Int}; -use super::{AdtRepr, camel}; -use crate::program::{SymKind, Symbol}; -use crate::ts::{self, Ctor, Expr, FieldId, Key, Param, Stmt, StmtKind, SymId, Type}; - -/// The class of one `async` body's future, by the role of each field. -struct Class<'tcx> { - sym: SymId, - def_id: LocalDefId, - state: FieldId, - upvars: Vec, - saved: IndexVec, - layout: &'tcx mir::CoroutineLayout<'tcx>, -} - -/// The future of the `async` body `def_id`, a `ty`, capturing `upvars`: its class is -/// translated here, and this is a new instance of it. -pub fn coroutine<'tcx>( - b: &mut Body<'_, '_, 'tcx>, - def_id: LocalDefId, - ty: Ty<'tcx>, - upvars: Vec, - span: Span, -) -> Expr { - let tcx = b.t.tcx; - let ty::Coroutine(_, args) = *ty.kind() else { - return b.err(span, format!("an async body of type `{ty}`")); - }; - let Ok(layout) = tcx.coroutine_layout(def_id.to_def_id(), args) else { - return b.err(span, "an async body without a layout"); - }; - let parent = tcx.typeck_root_def_id(def_id.to_def_id()); - let name = pascal(&camel(tcx.item_name(parent).as_str())); - let order = b.t.order(tcx.def_span(def_id)); - let class = b.t.program.sym(Symbol { - module: b.t.module_of(parent), - base: format!("{name}Future"), - suffix: String::new(), - owner: None, - kind: SymKind::Class, - order, - name: String::new(), - }); - let mut fields = Vec::new(); - let state = b.t.program.field(class, "state".into()); - fields.push(ts::Field { - id: state, - ty: Type::Builtin("number"), - doc: Some("Which await it is suspended at, as the coroutine transform numbers them.".into()), - }); - let mut upvar_fields = Vec::new(); - let captures = tcx.closure_captures(def_id); - for (i, upvar) in args.as_coroutine().upvar_tys().iter().enumerate() { - let base = captures - .get(i) - .map_or(format!("upvar{i}"), |c| camel(c.to_symbol().as_str())); - let id = b.t.program.field(class, base); - let ty = local_type(b, upvar, span); - fields.push(ts::Field { id, ty, doc: None }); - upvar_fields.push(id); - } - let mut saved = IndexVec::new(); - for (local, field) in layout.field_tys.iter_enumerated() { - let id = b.t.program.field(class, format!("s{}", local.as_usize())); - let ty = local_type(b, b.subst(field.ty), span); - fields.push(ts::Field { id, ty, doc: None }); - saved.push(id); - } - let info = Class { - sym: class, - def_id, - state, - upvars: upvar_fields, - saved, - layout, - }; - b.t.program.items.push(ts::Item::Class { - sym: class, - params: Vec::new(), - fields, - ctor: Ctor::Named, - doc: Some(format!( - "The future of `{}`, as a state machine.", - tcx.def_path_str(parent) - )), - }); - - let body = tcx.optimized_mir(def_id); - let ret = b.subst(args.as_coroutine().return_ty()); - let poll_ret = Type::Rt("Poll", vec![local_type(b, ret, span)]); - let cx = "cx".to_string(); - let poll_body = Lowering::new(b, body, &info, Some(cx.clone())).lower(); - let mut methods = vec![( - "poll", - vec![Param { - name: cx, - ty: Some(Type::Rt("Context", vec![])), - }], - poll_ret, - poll_body, - )]; - match body.coroutine_drop() { - Some(drop) => { - let dispose = Lowering::new(b, drop, &info, None).lower(); - methods.push(("[Symbol.dispose]", Vec::new(), Type::Builtin("void"), dispose)); - } - None => b.t.err(span, "an async body without a drop shim"), - } - for (name, params, ret, body) in methods { - let sym = b.t.program.sym(Symbol { - module: b.t.module_of(parent), - base: name.into(), - suffix: String::new(), - owner: Some(class), - kind: SymKind::Method { instance: true }, - order, - name: String::new(), - }); - b.t.program.methods.entry(class).or_default().push(ts::Function { - sym, - method: true, - params, - ret, - body, - loc: None, - doc: None, - generator: false, - }); - } - - let mut props = vec![(Key::Field(state), Expr::lit("0"))]; - for (&id, value) in info.upvars.iter().zip(upvars) { - props.push((Key::Field(id), value)); - } - for &id in &info.saved { - props.push((Key::Field(id), Expr::lit("undefined!"))); - } - Expr::New(Box::new(Expr::Sym(class)), vec![Expr::Object(props)]) -} - -/// The TypeScript type of a local, for the types only MIR has. -fn local_type<'tcx>(b: &mut Body<'_, '_, 'tcx>, ty: Ty<'tcx>, span: Span) -> Type { - match ty.kind() { - ty::Adt(adt, args) => match super::library::std_path(b.t.tcx, adt.did()).last().map(String::as_str) { - Some("NonNull") => local_type(b, args.type_at(0), span), - Some("Argument") => Type::Rt("Fmt", vec![]), - _ => b.t.ty(ty, span), - }, - ty::Array(elem, _) | ty::Slice(elem) if is_argument(b, *elem) => Type::Array(Box::new(Type::Rt("Fmt", vec![]))), - ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => match inner.kind() { - ty::Array(elem, _) | ty::Slice(elem) if is_argument(b, *elem) => { - Type::Array(Box::new(Type::Rt("Fmt", vec![]))) - } - ty::Coroutine(..) => local_type(b, *inner, span), - _ => b.t.ty(ty, span), - }, - _ => b.t.ty(ty, span), - } -} - -/// Whether `ty` is `core::fmt::rt::Argument`. -fn is_argument<'tcx>(b: &Body<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Adt(adt, _) => super::library::std_path(b.t.tcx, adt.did()) == ["fmt", "rt", "Argument"], - _ => false, - } -} - -fn pascal(name: &str) -> String { - let mut chars = name.chars(); - chars - .next() - .map_or_else(String::new, |c| c.to_uppercase().chain(chars).collect()) -} - -/// One MIR body of a coroutine's class, lowered to a method's statements. -struct Lowering<'m, 'b, 'a, 'tcx> { - b: &'m mut Body<'b, 'a, 'tcx>, - mir: &'tcx mir::Body<'tcx>, - class: &'m Class<'tcx>, - /// The method's parameter for `_2`, the context a resume is given. - cx: Option, - /// Locals some statement reads, which are the only ones declared. - read: FxHashSet, - /// Locals holding a byte string, a `format_args!` template. - bytes: FxHashMap>, - /// How many edges reach each block. - preds: IndexVec, - span: Span, -} - -impl<'m, 'b, 'a, 'tcx> Lowering<'m, 'b, 'a, 'tcx> { - fn new( - b: &'m mut Body<'b, 'a, 'tcx>, - mir: &'tcx mir::Body<'tcx>, - class: &'m Class<'tcx>, - cx: Option, - ) -> Self { - // Cleanup blocks run only as a panic unwinds, which a JS exception never stops - // for: the target panics by aborting. - let mut preds = IndexVec::from_elem_n(0, mir.basic_blocks.len()); - for data in mir.basic_blocks.iter().filter(|data| !data.is_cleanup) { - for target in data.terminator().successors() { - preds[target] += 1; - } - } - let mut bytes = FxHashMap::default(); - for data in mir.basic_blocks.iter() { - for stmt in &data.statements { - let StatementKind::Assign(assign) = &stmt.kind else { - continue; - }; - let (place, rvalue) = &**assign; - let Some(local) = place.as_local() else { - continue; - }; - match rvalue { - Rvalue::Use(Operand::Constant(c), _) => { - if let Some(found) = const_bytes(b.t.tcx, c) { - bytes.insert(local, found); - } - } - Rvalue::Ref(_, _, from) if from.projection.as_slice() == [ProjectionElem::Deref] => { - if let Some(found) = bytes.get(&from.local).cloned() { - bytes.insert(local, found); - } - } - _ => {} - } - } - } - let mut reads = Reads(FxHashSet::default()); - reads.visit_body(mir); - let read = reads.0.into_iter().filter(|local| !bytes.contains_key(local)).collect(); - Self { - b, - mir, - class, - cx, - read, - bytes, - preds, - span: mir.span, - } - } - - fn tcx(&self) -> ty::TyCtxt<'tcx> { - self.b.t.tcx - } - - fn err(&mut self, msg: impl Into) -> Expr { - let span = self.span; - self.b.err(span, msg) - } - - fn local_ty(&self, local: Local) -> Ty<'tcx> { - self.b.subst(self.mir.local_decls[local].ty) - } - - /// The method's statements: each local declared, then the dispatch loop. - fn lower(mut self) -> Vec { - let mut cases = Vec::new(); - for (block, data) in self.mir.basic_blocks.iter_enumerated() { - if data.is_cleanup || self.inlined(block) { - continue; - } - let mut body = Vec::new(); - self.block(block, &mut body); - cases.push((Expr::lit(block.as_usize().to_string()), body)); - } - let mut out = Vec::new(); - for (local, decl) in self.mir.local_decls.iter_enumerated() { - let arg = (1..=self.mir.arg_count).contains(&local.as_usize()); - if arg || !self.read.contains(&local) { - continue; - } - let ty = self.b.subst(decl.ty); - if ty.is_unit() { - continue; - } - let span = self.span; - // The coroutine itself, which only its own class has fields for. - let ts = match ty.builtin_deref(true).unwrap_or(ty).kind() { - ty::Coroutine(def_id, _) if *def_id == self.class.def_id.to_def_id() => { - Type::Sym(self.class.sym, Vec::new()) - } - _ => local_type(self.b, ty, span), - }; - out.push(StmtKind::decl(true, name(local), Some(ts), Some(Expr::lit("undefined!"))).at(None)); - } - out.push(StmtKind::decl(true, "bb", Some(Type::Builtin("number")), Some(Expr::lit("0"))).at(None)); - out.push( - StmtKind::While { - label: None, - cond: Expr::lit("true"), - body: vec![ - StmtKind::Switch { - value: Expr::ident("bb"), - cases, - default: Vec::new(), - } - .at(None), - ], - } - .at(None), - ); - out - } - - /// Whether `block` is lowered where its one predecessor jumps to it, not as a case. - fn inlined(&self, block: BasicBlock) -> bool { - block != mir::START_BLOCK && self.preds[block] == 1 - } - - /// Control to `target`: inline if only this edge reaches it. - fn jump(&mut self, target: BasicBlock, out: &mut Vec) { - if self.inlined(target) { - self.block(target, out); - return; - } - out.push(StmtKind::Expr(Expr::ident("bb").assign(Expr::lit(target.as_usize().to_string()))).at(None)); - out.push(StmtKind::Continue(None).at(None)); - } - - fn block(&mut self, block: BasicBlock, out: &mut Vec) { - let data = &self.mir.basic_blocks[block]; - for stmt in &data.statements { - self.span = stmt.source_info.span; - self.statement(&stmt.kind, out); - } - let terminator = data.terminator(); - self.span = terminator.source_info.span; - self.terminator(&terminator.kind, out); - } - - fn statement(&mut self, kind: &StatementKind<'tcx>, out: &mut Vec) { - match kind { - StatementKind::Assign(assign) => { - let (place, rvalue) = &**assign; - if place - .as_local() - .is_some_and(|local| !self.read.contains(&local) || self.bytes.contains_key(&local)) - { - return; - } - if self.b.subst(place.ty(self.mir, self.tcx()).ty).is_unit() { - return; - } - let value = self.rvalue(rvalue, out); - let target = self.place(place, out); - out.push(StmtKind::Expr(target.assign(value)).at(None)); - } - StatementKind::SetDiscriminant { place, variant_index } => { - let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); - match ty.kind() { - ty::Coroutine(..) => { - let target = self.place(place, out).field(self.class.state); - out.push( - StmtKind::Expr(target.assign(Expr::lit(variant_index.as_usize().to_string()))).at(None), - ); - } - _ => { - self.err(format!("setting the discriminant of `{ty}`")); - } - } - } - StatementKind::StorageLive(_) - | StatementKind::StorageDead(_) - | StatementKind::Nop - | StatementKind::FakeRead(_) - | StatementKind::PlaceMention(_) - | StatementKind::AscribeUserType(..) - | StatementKind::Coverage(_) - | StatementKind::ConstEvalCounter - | StatementKind::BackwardIncompatibleDropHint { .. } => {} - StatementKind::Intrinsic(_) => { - self.err("an intrinsic"); - } - } - } - - fn terminator(&mut self, kind: &TerminatorKind<'tcx>, out: &mut Vec) { - match kind { - TerminatorKind::Goto { target, .. } => self.jump(*target, out), - TerminatorKind::FalseEdge { real_target, .. } | TerminatorKind::FalseUnwind { real_target, .. } => { - self.jump(*real_target, out) - } - TerminatorKind::SwitchInt { discr, targets } => { - let ty = self.b.subst(discr.ty(self.mir, self.tcx())); - let value = self.operand(discr, out); - let value = match value.is_path() { - true => value, - false => self.b.spill(value, "value", out), - }; - let mut els = Vec::new(); - self.jump(targets.otherwise(), &mut els); - let arms: Vec<(u128, BasicBlock)> = targets.iter().collect(); - for (bits, target) in arms.into_iter().rev() { - let test = match ty.kind() { - ty::Bool if bits == 0 => value.clone().not(), - ty::Bool => value.clone(), - _ => match Int::of(ty) { - Some(int) => value.clone().binary("===", int.lit(bits as i128)), - None => self.err(format!("a switch on `{ty}`")), - }, - }; - let mut then = Vec::new(); - self.jump(target, &mut then); - els = vec![StmtKind::If { cond: test, then, els }.at(None)]; - } - out.extend(els); - } - TerminatorKind::Return => { - let ret = self.local_ty(mir::RETURN_PLACE); - match ret.is_unit() { - true => out.push(StmtKind::Return(None).at(None)), - false => out.push(StmtKind::Return(Some(Expr::ident(name(mir::RETURN_PLACE)))).at(None)), - } - } - TerminatorKind::Unreachable => { - let panic = Expr::rt( - "panic", - vec![Expr::Str("internal error: entered unreachable code".into())], - ); - out.push(StmtKind::Expr(panic).at(None)); - } - TerminatorKind::Drop { place, target, .. } => { - let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); - let value = self.place(place, out); - let span = self.span; - if let Some(dropped) = self.b.t.drop_value(value, ty, span) { - out.push(StmtKind::Expr(dropped).at(None)); - } - self.jump(*target, out); - } - TerminatorKind::Call { - func, - args, - destination, - target, - .. - } => { - let value = self.call(func, args, out); - let dest_ty = self.b.subst(destination.ty(self.mir, self.tcx()).ty); - let unread = destination - .as_local() - .is_some_and(|local| !self.read.contains(&local) || self.bytes.contains_key(&local)); - match unread || dest_ty.is_unit() || dest_ty.is_never() { - true => { - if !value.is_path() { - out.push(StmtKind::Expr(value).at(None)); - } - } - false => { - let target = self.place(destination, out); - out.push(StmtKind::Expr(target.assign(value)).at(None)); - } - } - if let Some(target) = target { - self.jump(*target, out); - } - } - TerminatorKind::Assert { - cond, - expected, - msg, - target, - .. - } => { - // A checked operation, an index, or a division panics on its own, with - // the message its assert has. - let message = match &**msg { - AssertKind::ResumedAfterReturn(_) => Some("`async fn` resumed after completion"), - AssertKind::ResumedAfterPanic(_) => Some("`async fn` resumed after panicking"), - AssertKind::ResumedAfterDrop(_) => Some("`async fn` resumed after async drop"), - _ => None, - }; - if let Some(message) = message { - let value = self.operand(cond, out); - let test = match expected { - true => value.not(), - false => value, - }; - out.push( - StmtKind::If { - cond: test, - then: vec![StmtKind::Expr(Expr::rt("panic", vec![Expr::Str(message.into())])).at(None)], - els: Vec::new(), - } - .at(None), - ); - } - self.jump(*target, out); - } - _ => { - self.err(format!("unsupported terminator {kind:?}")); - } - } - } - - fn call(&mut self, func: &Operand<'tcx>, args: &[rustc_span::Spanned>], out: &mut Vec) -> Expr { - let tcx = self.tcx(); - let fn_ty = self.b.subst(func.ty(self.mir, tcx)); - let ty::FnDef(def_id, gargs) = *fn_ty.kind() else { - return self.err(format!("a call through `{fn_ty}`")); - }; - let gargs = gargs.skip_binder(); - let key = super::library::key(tcx, def_id); - let key = key.as_ref().map(|(owner, name)| (owner.as_str(), name.as_str())); - let span = self.span; - // `format_args!`, as MIR has it: its arguments, then its template around them. - if let Some(("Argument", name)) = key { - let tr = match name { - "new_display" => Trait::Display, - "new_debug" => Trait::Debug, - "new_lower_hex" => Trait::LowerHex, - "new_upper_hex" => Trait::UpperHex, - _ => return self.err(format!("`Argument::{name}`")), - }; - let Some(ty) = gargs.types().next() else { - return self.err("an `Argument` without a type"); - }; - let value = self.operand(&args[0].node, out); - return self.b.fmt_value(tr, ty, value, span, out); - } - if let Some(("Arguments", "new")) = key { - let template = match &args[0].node { - Operand::Copy(place) | Operand::Move(place) => { - place.as_local().and_then(|l| self.bytes.get(&l).cloned()) - } - Operand::Constant(c) => const_bytes(tcx, c), - _ => None, - }; - let Some(template) = template else { - return self.err("a `format_args!` template that is not a constant"); - }; - let arguments = self.operand(&args[1].node, out); - let arguments = match arguments.is_path() { - true => arguments, - false => self.b.spill(arguments, "args", out), - }; - let pieces = match fmt::decode(&template) { - Ok(pieces) => pieces, - Err(msg) => return self.err(format!("{msg} is not supported")), - }; - let mut parts = Vec::new(); - for piece in pieces { - parts.push(match piece { - Piece::Lit(s) => Expr::Str(s), - Piece::Arg { index, spec } => { - let value = arguments.clone().index(Expr::lit(index.to_string())); - match spec.object() { - Some(spec) => Expr::Rt("fmt").member("spec").call(vec![spec, value]), - None => value, - } - } - }); - } - return Expr::Array(parts); - } - let mut values = Vec::new(); - for arg in args { - let value = self.operand(&arg.node, out); - values.push(value); - } - // Lowered left to right: an earlier value a later one's statements could change is saved. - self.b.call_def(def_id, gargs, Args::Values(values), span, out) - } - - fn rvalue(&mut self, rvalue: &Rvalue<'tcx>, out: &mut Vec) -> Expr { - let tcx = self.tcx(); - let span = self.span; - match rvalue { - Rvalue::Use(op, _) => self.operand(op, out), - Rvalue::Ref(..) | Rvalue::Reborrow(..) => { - let (mutability, place) = match rvalue { - Rvalue::Ref(_, kind, place) => (kind.mutability(), place), - Rvalue::Reborrow(_, mutability, place) => (*mutability, place), - _ => unreachable!(), - }; - let pointee = self.b.subst(place.ty(self.mir, tcx).ty); - if mutability.is_mut() && self.b.t.object_kind(pointee).is_none() { - return self.err(format!( - "a mutable reference to `{pointee}`, which is no object it can change in place" - )); - } - self.place(place, out) - } - Rvalue::CopyForDeref(place) => self.place(place, out), - Rvalue::Cast(kind, op, to) => { - let to = self.b.subst(*to); - let from = self.b.subst(op.ty(self.mir, tcx)); - let value = self.operand(op, out); - match kind { - CastKind::IntToInt => num::cast( - self.b, - num::Operand { - expr: value, - value: None, - }, - from, - to, - span, - ), - // A context's pointer, as `.await` passes it around. - CastKind::Transmute | CastKind::PtrToPtr if context_like(tcx, from) && context_like(tcx, to) => { - value - } - CastKind::PointerCoercion(..) | CastKind::Subtype => value, - _ => self.err(format!("a {kind:?} cast from `{from}` to `{to}`")), - } - } - Rvalue::BinaryOp(op, operands) => { - let (l, r) = &**operands; - let lty = self.b.subst(l.ty(self.mir, tcx)); - let rty = self.b.subst(r.ty(self.mir, tcx)); - let lv = self.operand(l, out); - let rv = self.operand(r, out); - // A checked operation panics itself, so its overflow flag is always false. - let (op, checked) = match op { - BinOp::AddWithOverflow => (BinOp::Add, true), - BinOp::SubWithOverflow => (BinOp::Sub, true), - BinOp::MulWithOverflow => (BinOp::Mul, true), - op => (*op, false), - }; - let value = match (lty.kind(), op) { - (ty::Int(_) | ty::Uint(_), _) | (ty::Bool, BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor) => { - num::binary( - self.b, - op, - num::Operand { expr: lv, value: None }, - num::Operand { expr: rv, value: None }, - lty, - rty, - span, - ) - } - (_, BinOp::Eq) => lv.binary("===", rv), - (_, BinOp::Ne) => lv.binary("!==", rv), - _ => self.err(format!("`{op:?}` on `{lty}`")), - }; - match checked { - true => Expr::Array(vec![value, Expr::lit("false")]), - false => value, - } - } - Rvalue::UnaryOp(op, operand) => { - let ty = self.b.subst(operand.ty(self.mir, tcx)); - let value = self.operand(operand, out); - match op { - UnOp::Not | UnOp::Neg => num::unary(self.b, *op, value, ty, span), - UnOp::PtrMetadata => self.err("pointer metadata"), - } - } - Rvalue::Discriminant(place) => { - let ty = self.b.subst(place.ty(self.mir, tcx).ty); - let value = self.place(place, out); - self.discriminant(value, ty) - } - Rvalue::Aggregate(kind, operands) => self.aggregate(kind, operands, out), - _ => self.err(format!("unsupported rvalue {rvalue:?}")), - } - } - - /// The variant index of `value`, a `ty`. - fn discriminant(&mut self, value: Expr, ty: Ty<'tcx>) -> Expr { - let tcx = self.tcx(); - match ty.kind() { - ty::Coroutine(..) => value.field(self.class.state), - ty::Adt(adt, _) => match Std::of(tcx, adt.did()) { - Some(Std::Option) => Expr::Cond( - Box::new(value.binary("===", Expr::undefined())), - Box::new(Expr::lit("0")), - Box::new(Expr::lit("1")), - ), - Some(Std::Poll) => Expr::Cond( - Box::new(value.binary("===", Expr::Rt("Pending"))), - Box::new(Expr::lit("1")), - Box::new(Expr::lit("0")), - ), - Some(Std::Result) => Expr::Cond( - Box::new(value.member("ok")), - Box::new(Expr::lit("0")), - Box::new(Expr::lit("1")), - ), - _ => self.err(format!("the discriminant of `{ty}`")), - }, - _ => self.err(format!("the discriminant of `{ty}`")), - } - } - - fn aggregate( - &mut self, - kind: &AggregateKind<'tcx>, - operands: &IndexVec>, - out: &mut Vec, - ) -> Expr { - let tcx = self.tcx(); - let span = self.span; - match kind { - AggregateKind::Tuple if operands.is_empty() => Expr::undefined(), - AggregateKind::Tuple | AggregateKind::Array(_) => { - let values = operands.iter().map(|op| self.operand(op, out)).collect(); - Expr::Array(values) - } - AggregateKind::Adt(did, variant, gargs, _, None) => { - let gargs = self.b.subst(*gargs); - let mut values: Vec = operands.iter().map(|op| self.operand(op, out)).collect(); - let adt = tcx.adt_def(*did); - if context_like(tcx, tcx.type_of(*did).instantiate(tcx, gargs).skip_norm_wip()) || is_resume(tcx, *did) - { - return values.pop().unwrap_or_else(Expr::undefined); - } - match (Std::of(tcx, *did), variant.as_usize()) { - (Some(Std::Option), 0) => return Expr::undefined(), - (Some(Std::Option), _) | (Some(Std::Poll), 0) => { - return values.pop().unwrap_or_else(Expr::undefined); - } - (Some(Std::Poll), _) => return Expr::Rt("Pending"), - (Some(Std::Result), 0) => return Expr::rt("Ok", values), - (Some(Std::Result), _) => return Expr::rt("Err", values), - (Some(_), _) => return self.err(format!("constructing `{}`", tcx.def_path_str(*did))), - (None, _) => {} - } - let info = self.b.t.adt(adt, span); - let ty = tcx.type_of(*did).instantiate(tcx, gargs).skip_norm_wip(); - let def = adt.variant(*variant); - match info.repr { - AdtRepr::Class { ctor, fields } => match ctor { - Ctor::Unit => Expr::New(Box::new(Expr::Sym(info.sym)), Vec::new()), - Ctor::Positional => Expr::New( - Box::new(Expr::Sym(info.sym)), - values.into_iter().map(Expr::typed).collect(), - ), - Ctor::Named => { - let props = fields - .iter() - .zip(values) - .map(|(&id, value)| (Key::Field(id), value.typed())) - .collect(); - Expr::New(Box::new(Expr::Sym(info.sym)), vec![Expr::Object(props)]) - } - }, - AdtRepr::Tags => { - let ts = self.b.t.ty(ty, span); - Expr::As(Box::new(Expr::Str(def.name.to_string())), ts) - } - AdtRepr::Union => { - let mut props = vec![(Key::Name("tag".into()), Expr::Str(def.name.to_string()))]; - for (i, value) in values.into_iter().enumerate() { - let field = &def.fields[FieldIdx::from_usize(i)]; - props.push((Key::Name(super::field_name(field.name.as_str(), i)), value)); - } - let ts = self.b.t.ty(ty, span); - Expr::As(Box::new(Expr::Object(props)), ts) - } - } - } - AggregateKind::Closure(def_id, _) => { - let Some(local) = def_id.as_local() else { - return self.err("a closure from another crate"); - }; - let captures = tcx.closure_captures(local); - for (capture, op) in captures.iter().zip(operands.iter()) { - // A reference captured through a deref is still the object it points to. - let whole = capture - .place - .projections - .iter() - .all(|p| matches!(p.kind, rustc_middle::hir::place::ProjectionKind::Deref)); - if !whole { - return self.err("a closure that captures part of a variable"); - } - let value = self.operand(op, out); - let name = self.b.fresh(&camel(capture.to_symbol().as_str())); - out.push(StmtKind::decl(false, name.clone(), None, Some(value)).at(None)); - self.b.bind_upvar(capture.get_root_variable(), name); - } - self.b.lower_closure(local, span) - } - _ => self.err(format!("unsupported aggregate {kind:?}")), - } - } - - fn operand(&mut self, op: &Operand<'tcx>, out: &mut Vec) -> Expr { - match op { - Operand::Copy(place) => { - let ty = self.b.subst(place.ty(self.mir, self.tcx()).ty); - let value = self.place(place, out); - match context_like(self.tcx(), ty) { - true => value, - false => self.b.copied(value, ty), - } - } - Operand::Move(place) => self.place(place, out), - Operand::Constant(c) => self.constant(c), - Operand::RuntimeChecks(_) => self.err("a runtime check"), - } - } - - fn constant(&mut self, c: &mir::ConstOperand<'tcx>) -> Expr { - let tcx = self.tcx(); - let ty = self.b.subst(c.const_.ty()); - if ty.is_unit() || matches!(ty.kind(), ty::FnDef(..)) { - return Expr::undefined(); - } - let env = self.b.t.typing_env_pub(); - match ty.kind() { - ty::Bool => match c.const_.try_eval_scalar_int(tcx, env) { - Some(int) => Expr::lit(if int.is_null() { "false" } else { "true" }), - None => self.err("a constant that does not evaluate"), - }, - ty::Int(_) | ty::Uint(_) => { - let int = Int::of(ty).expect("an integer"); - match c.const_.try_eval_bits(tcx, env) { - Some(bits) => { - let size = rustc_abi::Size::from_bits(int.bits); - let value = match int.signed { - true => size.sign_extend(bits), - false => bits as i128, - }; - int.lit(value) - } - None => self.err("a constant that does not evaluate"), - } - } - ty::Ref(_, inner, _) if inner.is_str() => match c.const_.eval(tcx, env, self.span) { - Ok(value) => match value.try_get_slice_bytes_for_diagnostics(tcx) { - Some(bytes) => Expr::Str(String::from_utf8_lossy(bytes).into_owned()), - None => self.err("a string constant"), - }, - Err(_) => self.err("a constant that does not evaluate"), - }, - _ => self.err(format!("a constant of type `{ty}`")), - } - } - - fn place(&mut self, place: &Place<'tcx>, out: &mut Vec) -> Expr { - let tcx = self.tcx(); - let mut value = self.local(place.local); - for (i, elem) in place.projection.iter().enumerate() { - let base = Place::ty_from(place.local, &place.projection[..i], self.mir, tcx); - let ty = self.b.subst(base.ty); - value = match elem { - ProjectionElem::Deref - | ProjectionElem::Downcast(..) - | ProjectionElem::OpaqueCast(_) - | ProjectionElem::UnwrapUnsafeBinder(_) => value, - ProjectionElem::Field(field, field_ty) => { - let value = self.field(value, ty, base.variant_index, field); - // TypeScript can't see which variant a switch on its discriminant took. - match ty.kind() { - ty::Adt(adt, _) if matches!(Std::of(tcx, adt.did()), Some(Std::Option | Std::Poll)) => { - let field_ty = self.b.subst(field_ty); - let span = self.span; - Expr::As(Box::new(value), local_type(self.b, field_ty, span)) - } - _ => value, - } - } - ProjectionElem::Index(index) => { - let base = match value.is_path() { - true => value, - false => self.b.spill(value, "slice", out), - }; - let i = self.local(index); - base.clone().index(Expr::rt("idx", vec![base, i])) - } - _ => self.err(format!("unsupported projection {elem:?}")), - }; - } - value - } - - fn field(&mut self, base: Expr, ty: Ty<'tcx>, variant: Option, field: FieldIdx) -> Expr { - let tcx = self.tcx(); - let span = self.span; - match ty.kind() { - ty::Coroutine(..) => match variant { - None => match self.class.upvars.get(field.as_usize()) { - Some(&id) => base.field(id), - None => self.err("an upvar out of range"), - }, - Some(variant) => { - let saved = self.class.layout.variant_fields[variant][field]; - base.field(self.class.saved[saved]) - } - }, - ty::Adt(adt, _) if context_like(tcx, ty) || Std::of(tcx, adt.did()) == Some(Std::Pin) => base, - _ => self - .b - .project(base, ty, variant.unwrap_or(rustc_abi::FIRST_VARIANT), field, span), - } - } - - fn local(&mut self, local: Local) -> Expr { - match local.as_usize() { - 1 => Expr::This, - 2 if let Some(cx) = &self.cx => Expr::ident(cx), - _ => Expr::ident(name(local)), - } - } -} - -/// A local's name: `_3`. -fn name(local: Local) -> String { - format!("_{}", local.as_usize()) -} - -/// Whether `ty` is how `.await` carries the context: the context, a pointer to it, or -/// `ResumeTy`. -fn context_like<'tcx>(tcx: ty::TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { - match ty.kind() { - ty::Ref(_, inner, _) => context_like(tcx, *inner), - ty::Adt(adt, args) => { - Std::of(tcx, adt.did()) == Some(Std::Context) - || (super::library::std_path(tcx, adt.did()) - .last() - .is_some_and(|n| n == "NonNull") - && context_like(tcx, args.type_at(0))) - } - _ => false, - } -} - -/// Whether `did` is `ResumeTy`, the context an `async` body is resumed with. -fn is_resume(tcx: ty::TyCtxt<'_>, did: rustc_hir::def_id::DefId) -> bool { - tcx.is_lang_item(did, rustc_attr_ir::LangItem::ResumeTy) -} - -/// The bytes of a constant `&[u8; N]`. -fn const_bytes<'tcx>(tcx: ty::TyCtxt<'tcx>, c: &mir::ConstOperand<'tcx>) -> Option> { - let ty::Ref(_, inner, _) = c.const_.ty().kind() else { - return None; - }; - let ty::Array(elem, len) = inner.kind() else { - return None; - }; - if !matches!(elem.kind(), ty::Uint(ty::UintTy::U8)) { - return None; - } - let len = len.try_to_target_usize(tcx)? as usize; - let value = c - .const_ - .eval(tcx, ty::TypingEnv::fully_monomorphized(), rustc_span::DUMMY_SP) - .ok()?; - let ConstValue::Scalar(Scalar::Ptr(ptr, _)) = value else { - return None; - }; - let (prov, offset) = ptr.prov_and_relative_offset(); - let alloc = tcx.global_alloc(prov.alloc_id()).unwrap_memory(); - let start = offset.bytes_usize(); - Some( - alloc - .inner() - .inspect_with_uninit_and_ptr_outside_interpreter(start..start + len) - .to_vec(), - ) -} - -/// The locals a body reads. -struct Reads(FxHashSet); - -impl<'tcx> Visitor<'tcx> for Reads { - fn visit_local(&mut self, local: Local, context: PlaceContext, _: mir::Location) { - use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext}; - match context { - PlaceContext::NonUse( - NonUseContext::StorageLive | NonUseContext::StorageDead | NonUseContext::VarDebugInfo, - ) - | PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {} - _ => { - self.0.insert(local); - } - } - } -} diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index 7ba07a094..5e813e580 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -9,7 +9,6 @@ mod consts; mod drop; mod fmt; mod library; -mod mir; mod num; mod pat; mod task; @@ -159,9 +158,6 @@ pub struct Translator<'a, 'tcx> { drops: rustc_data_structures::fx::FxHashMap, bool>, /// The classes given drop glue. glued: rustc_data_structures::fx::FxHashSet, - /// The async spike's prototype switch: lower `async` bodies from MIR as state - /// machines rather than from THIR as generators. - pub async_mir: bool, } /// A local struct or enum, and how it is represented. @@ -229,7 +225,6 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { refusals, drops: Default::default(), glued: Default::default(), - async_mir: std::env::var_os("RUST2_TS_ASYNC").is_some_and(|mode| mode == "mir"), }) } @@ -868,7 +863,16 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::PoisonError => Type::Builtin("never"), library::Std::Waker => Type::Rt("Waker", vec![]), library::Std::Context => Type::Rt("Context", vec![]), - library::Std::Poll => Type::Rt("Poll", vec![self.ty(args.type_at(0), span)]), + library::Std::Poll => { + let inner = args.type_at(0); + if self.std_of(inner) == Some(library::Std::Poll) { + self.err( + span, + format!("`Poll<{inner}>` is not supported: it would be pending two ways with one value"), + ); + } + Type::Rt("Poll", vec![self.ty(inner, span)]) + } library::Std::Pin => self.ty(args.type_at(0), span), }; } diff --git a/ts/src/print.rs b/ts/src/print.rs index ad87c34d9..bc666bdd1 100644 --- a/ts/src/print.rs +++ b/ts/src/print.rs @@ -275,14 +275,6 @@ impl Refs { self.stmts(program, body); self.stmts(program, finally); } - StmtKind::Switch { value, cases, default } => { - self.expr(program, value); - for (case, body) in cases { - self.expr(program, case); - self.stmts(program, body); - } - self.stmts(program, default); - } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } @@ -750,31 +742,6 @@ impl Printer<'_> { self.start(); self.write("}\n"); } - StmtKind::Switch { value, cases, default } => { - self.write("switch ("); - self.expr(value, 0); - self.write(") {\n"); - self.indent += 1; - for (case, body) in cases { - self.start(); - self.write("case "); - self.expr(case, 0); - self.write(": {\n"); - self.block_body(body); - self.start(); - self.write("}\n"); - } - if !default.is_empty() { - self.start(); - self.write("default: {\n"); - self.block_body(default); - self.start(); - self.write("}\n"); - } - self.indent -= 1; - self.start(); - self.write("}\n"); - } StmtKind::Try { body, finally } => { self.write("try {\n"); self.block_body(body); @@ -1161,13 +1128,6 @@ fn collect_locals(stmts: &[Stmt], out: &mut Vec) { collect_locals(body, out); collect_locals(finally, out); } - StmtKind::Switch { value, cases, default } => { - collect_expr_locals(value, out); - for (_, body) in cases { - collect_locals(body, out); - } - collect_locals(default, out); - } StmtKind::Return(None) | StmtKind::Break(_) | StmtKind::Continue(_) => {} } } diff --git a/ts/src/ts.rs b/ts/src/ts.rs index 369672b5f..34cc71b97 100644 --- a/ts/src/ts.rs +++ b/ts/src/ts.rs @@ -207,12 +207,6 @@ pub enum StmtKind { }, Break(Option), Continue(Option), - /// `switch (value) { case a: { .. } default: { .. } }`, whose cases never fall through. - Switch { - value: Expr, - cases: Vec<(Expr, Vec)>, - default: Vec, - }, /// `try { body } finally { finally }`: what `finally` drops is dropped on every exit. Try { body: Vec, diff --git a/ts/tests/differential.ts b/ts/tests/differential.ts index 43c5d6931..67cccc153 100644 --- a/ts/tests/differential.ts +++ b/ts/tests/differential.ts @@ -3,7 +3,8 @@ // // usage: node differential.ts // -// A harness exports `run(input: Uint8Array): Vec`; the wasm build exports `input`, +// A harness exports `run(input: Uint8Array): Vec`, and may export `cases`, inputs +// it names, which run with the generated ones. The wasm build exports `input`, // `run`, and `output` around it, which `wasm.ts` calls. A panic traps natively and // throws `Panic` in TypeScript, and the two agree only if their messages do. diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index d8adeb37c..6688328f6 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -205,28 +205,6 @@ fn task() { task_harness(&out); } -/// The async spike's state machine prototype, on the same harness. -#[test] -fn task_mir() { - let out = scratch().join("task-mir").join("out"); - let _ = std::fs::remove_file(out.join("harness.ts")); - let output = Command::new(env!("CARGO_BIN_EXE_rust2-ts")) - .arg("--config") - .arg(manifest_dir().join("fixtures").join("task").join("ts.toml")) - .arg("--out") - .arg(&out) - .env("CARGO_TARGET_DIR", scratch().join("build-mir")) - .env("RUST2_TS_ASYNC", "mir") - .output() - .expect("running rust2-ts"); - assert!( - output.status.success(), - "translating task as state machines failed:\n{}", - String::from_utf8_lossy(&output.stderr) - ); - task_harness(&out); -} - /// Run the task harness on a translation of the task fixture. fn task_harness(out: &Path) { let glue = out.join("harness.ts"); From 255148dff3c9b35e4baae0d32cfab6e73cee6ded Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:10:25 -0700 Subject: [PATCH 06/30] wip(ts): async spike cleanup: one closure path, trimmed runtime, text diffs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-generic-methods.md | 5 ++ ts/runtime/rt/task.ts | 30 +------ ts/rustc-ice-2026-10-24T06_41_29-465125.txt | 89 --------------------- ts/src/lower/body.rs | 8 +- ts/tests/differential.ts | 10 ++- 5 files changed, 19 insertions(+), 123 deletions(-) delete mode 100644 ts/rustc-ice-2026-10-24T06_41_29-465125.txt diff --git a/quest/m2/ts-generic-methods.md b/quest/m2/ts-generic-methods.md index 1b716e3b8..af4318a21 100644 --- a/quest/m2/ts-generic-methods.md +++ b/quest/m2/ts-generic-methods.md @@ -13,4 +13,9 @@ monomorphized method lands on the one generic class, so a body calls an instance's method on a field typed `T` (such as `this.value.fmt$Pair(f)`), which `tsc` rejects. moq-net's model has generic types, so the model quest needs this. +The async spike ([#16](https://github.com/kixelated/rust2/pull/16)) typed `this` as +the instance for an instance method of a generic class (`poll(this: Pending<..>, cx)`), +which kio's `Pending` needed: build on it, or replace it if a companion function, an +enum's methods, or derived `Debug` needs something else. + Public API: the translator's output for generic types. diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 2f7c7dc5d..691a46899 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -4,7 +4,7 @@ // A value whose drop JS can observe has `[Symbol.dispose]`, which runs its `Drop` impl // and drops its fields. A moved-out place holds `undefined`, which drops as nothing. -import { Ok, Panic, panic, type Result } from "../rt.ts"; +import { Panic, panic } from "../rt.ts"; // Drops @@ -20,24 +20,6 @@ export function dropAll(values: readonly unknown[] | undefined): void { for (const value of values) drop(value); } -/** `Vec::into_iter` of elements that drop: dropping it drops those not yet reached. */ -export class IntoIter implements Iterable, Disposable { - #items: T[]; - #next = 0; - - constructor(items: T[]) { - this.#items = items; - } - - *[Symbol.iterator](): Iterator { - while (this.#next < this.#items.length) yield this.#items[this.#next++]; - } - - [Symbol.dispose](): void { - while (this.#next < this.#items.length) drop(this.#items[this.#next++]); - } -} - // Shared ownership /** `Arc`: every clone is this one object, counted. */ @@ -77,20 +59,14 @@ export class Weak { } /** - * `Mutex`, which a single thread never contends, and its guard: locking hands out - * the mutex itself, and unlocking is nothing. + * `Mutex`, which a single thread never contends, and its guard: a lock is the mutex + * itself, and an unlock is nothing. */ export class Mutex implements Disposable { value: T; - readonly #locked: Result, never>; constructor(value: T) { this.value = value; - this.#locked = Ok(this); - } - - lock(): Result, never> { - return this.#locked; } [Symbol.dispose](): void { diff --git a/ts/rustc-ice-2026-10-24T06_41_29-465125.txt b/ts/rustc-ice-2026-10-24T06_41_29-465125.txt deleted file mode 100644 index 04e70b9c9..000000000 --- a/ts/rustc-ice-2026-10-24T06_41_29-465125.txt +++ /dev/null @@ -1,89 +0,0 @@ -thread 'rustc' panicked at src/lower/mir.rs:512:28: -Box -stack backtrace: - 0: 0x73b3b7a28975 - ::create - 1: 0x73b3b7a288c5 - ::force_capture - 2: 0x73b3b67df9ea - std[76053f7ab5f7f410]::panicking::update_hook::>::{closure#0} - 3: 0x73b3b7a3ea82 - std[76053f7ab5f7f410]::panicking::panic_with_hook - 4: 0x73b3b75d71c0 - std[76053f7ab5f7f410]::panicking::begin_panic::::{closure#0} - 5: 0x73b3b75d522e - std[76053f7ab5f7f410]::sys::backtrace::__rust_end_short_backtrace::::{closure#0}, !> - 6: 0x73b3b75d5202 - std[76053f7ab5f7f410]::panicking::begin_panic:: - 7: 0x73b3b3a226c1 - rustc_span[84be90fd7ae9529b]::macros::bug_impl - 8: 0x582d28d52a8b - >::type_at::{closure#0} - at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/rustc-src/rust/compiler/rustc_middle/src/ty/generic_args.rs:542:16 - 9: 0x582d28d54f88 - >::unwrap_or_else::<>::type_at::{closure#0}> - at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/src/rust/library/core/src/option.rs:1067:21 - 10: 0x582d28d54f88 - >::type_at - at /nix/store/i222nr66l2r3xfahzfpp1m6mawvhxyl2-rust-default-1.101.0-nightly-2026-10-15/lib/rustlib/rustc-src/rust/compiler/rustc_middle/src/ty/generic_args.rs:540:27 - 11: 0x582d28e843ca - ::call - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:512:19 - 12: 0x582d28e8084d - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:430:22 - 13: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 14: 0x582d28e85500 - ::jump - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 - 15: 0x582d28e80fb4 - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:398:11 - 16: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 17: 0x582d28e85500 - ::jump - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 - 18: 0x582d28e817be - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:421:10 - 19: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 20: 0x582d28e85500 - ::jump - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 - 21: 0x582d28e80fb4 - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:398:11 - 22: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 23: 0x582d28e85500 - ::jump - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 - 24: 0x582d28e81c4b - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:447:11 - 25: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 26: 0x582d28e85500 - ::jump - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:313:9 - 27: 0x582d28e81c4b - ::terminator - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:447:11 - 28: 0x582d28e857a9 - ::block - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:328:8 - 29: 0x582d28e86bc0 - ::lower - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:270:9 - 30: 0x582d28e955cd - rust2_ts[d61b199175b2cdd0]::lower::mir::coroutine - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mir.rs:102:66 - 31: 0x582d28cf0f70 - ::closure - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:2287:11 - 32: 0x582d28ce3b54 - ::expr - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:1978:39 - 33: 0x582d28ce7147 - ::stmt - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:414:22 - 34: 0x582d28ce769c - ::stmt - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:374:15 - 35: 0x582d28d0a211 - rust2_ts[d61b199175b2cdd0]::lower::body::function - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/body.rs:122:4 - 36: 0x582d28e2259d - ::function - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:926:18 - 37: 0x582d28e1e2c8 - ::drain - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:243:10 - 38: 0x582d28e26e6d - rust2_ts[d61b199175b2cdd0]::lower::translate - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/lower/mod.rs:63:4 - 39: 0x582d28e981ee - ::after_expansion - at /home/kixelated/work/rust2/.claude/worktrees/agent-ac2443627dd80745d/ts/src/driver.rs:99:30 - 40: 0x73b3b93067e6 - rustc_interface[428b96e9abb7cc47]::interface::run_compiler::<(), rustc_driver_impl[ab3368f39572c260]::compiler_entrypoint::{closure#0}>::{closure#2} - 41: 0x73b3b9330764 - std[76053f7ab5f7f410]::sys::backtrace::__rust_begin_short_backtrace::::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()> - 42: 0x73b3b93304ff - ::{closure#2}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[68f4be281c81bf45]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0} - 43: 0x73b3b932d81b - ::new::thread_start - 44: 0x73b3b229f751 - start_thread - 45: 0x73b3b232ba4c - __clone3 - 46: 0x0 - - - -rustc version: 1.101.0-nightly (7df81381d 2026-10-14) -platform: x86_64-unknown-linux-gnu - -query stack during panic: -end of query stack diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 3ba7edf98..9d9947d67 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1981,7 +1981,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } ExprKind::Adt(adt) => self.adt_expr(adt, ty, span, out), - ExprKind::Closure(closure) => self.closure(closure, span), + ExprKind::Closure(closure) => self.closure(closure.closure_id, span), ExprKind::Assign { .. } | ExprKind::AssignOp { .. } | ExprKind::Break { .. } @@ -2288,16 +2288,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } - fn closure(&mut self, closure: &thir::ClosureExpr<'tcx>, span: Span) -> Expr { - self.lower_closure(closure.closure_id, span) - } - /// A closure as an arrow function, or an `async` body as a future around a generator. /// /// The generator is a function of its own, taking its upvars as parameters: a /// generator function made per call costs V8 a prototype object and a new shape for /// each generator, about 25 times what one made once does. - fn lower_closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { + fn closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { let tcx = self.t.tcx; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); diff --git a/ts/tests/differential.ts b/ts/tests/differential.ts index 67cccc153..c0933153a 100644 --- a/ts/tests/differential.ts +++ b/ts/tests/differential.ts @@ -62,6 +62,14 @@ function show(outcome: Outcome): string { return outcome instanceof Uint8Array ? Buffer.from(outcome).toString("hex") : `panic ${JSON.stringify(outcome.panic)}`; } +/** An outcome to read: as text if it is lines of printable ASCII, as a log is. */ +function display(outcome: Outcome): string { + if (outcome instanceof Uint8Array && outcome.every((b) => b === 0x0a || (b >= 0x20 && b < 0x7f))) { + return `\n${Buffer.from(outcome).toString()}`; + } + return show(outcome); +} + const cases: Uint8Array[] = [new Uint8Array(0)]; // Every op with every short tail, so each path's edges are covered exhaustively. for (let op = 0; op < 256; op++) { @@ -108,7 +116,7 @@ for (const input of cases) { if (show(want) !== show(got)) { failures++; if (failures <= 20) { - console.error(`input ${show(input)}\nnative ${show(want)}\nts ${show(got)}\n`); + console.error(`input ${show(input)}\nnative ${display(want)}\nts ${display(got)}\n`); } } } From 2b98b68c83c58ba93f93bfe248a85e2f4668a7ea Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:28:49 -0700 Subject: [PATCH 07/30] fix(ts): census-safe drop analysis, and refuse a pattern-bound parameter that drops Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-async.md | 21 +++-- quest/m2/ts-drop.md | 26 +++--- ts/fixtures/reject/census.md | 140 ++++++++++++++++++-------------- ts/fixtures/reject/expected.txt | 52 ++++++------ ts/fixtures/reject/src/lib.rs | 5 ++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/body.rs | 7 ++ ts/src/lower/drop.rs | 7 +- 8 files changed, 150 insertions(+), 109 deletions(-) diff --git a/quest/m2/ts-async.md b/quest/m2/ts-async.md index 4ec568178..c69f9ac0b 100644 --- a/quest/m2/ts-async.md +++ b/quest/m2/ts-async.md @@ -18,14 +18,17 @@ V8 about 25 times as much), `.await` is a poll loop around `yield`, and `rt.spaw a future from a microtask as a promise. The task fixture's trace test covers a kio-shaped channel at await depths 1, 4, and 16. -What moq-net and kio still need, by the census: - -- Async blocks and closures. An async closure fails translation; an async block that - captures a number by `&mut` must too, since its generator would change a copy. -- The rest of kio's machinery: atomics, `OnceLock`, the coop budget's thread-local, - `Tasks`, and `poll_fn`, `ready`, and `pending`. -- Boxed futures, which bind to hand-written TS at the boundary - ([model](/quest/m2/ts-model.md)). +What moq-net still needs, by its census at the pinned revision: + +- `Poll`'s helpers (about 270 calls: `is_ready`, `is_pending`, `map`, `map_ok`, + `map_err`), `pin!` (47), `poll_fn` (51 with its `poll`), and `Box::pin` (17, a boxed + future that binds to hand-written TS at the boundary, per the + [model](/quest/m2/ts-model.md)). +- An async block that captures part of a variable (47), or borrows a number mutably + (4); async closures. +- kio's own API, reached across crates (`Pending`, `Consumer::poll`, + `Waiter::poll_future`, `Tasks`), with the atomics, `OnceLock`, and coop budget behind + it, which the model quest brings along. - The edge: `rt.spawn`'s shape for callers, and cancelling a spawned task. If a profile of moq's client finds await overhead, `yield*` between translated futures @@ -35,4 +38,4 @@ Public API: the translator's output for async code. ## Required -- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - kio's waiters and wakers drop on paths the spike refused +- [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - async bodies hold the values that drop it still refuses diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 300c827c3..01c559d19 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -16,18 +16,22 @@ each field); a variable drops in a `finally` at the end of its scope; a move lea `undefined` behind, so a variable moved on some paths drops on the others. The task fixture's trace test proves it on kio's waiters, wakers, and channels. -Each of these still fails translation with its span (the reject fixture has one of -each), and the census of moq-net and kio says which to lift first: - -- A temporary that drops, unless a call or binding takes it whole: borrowed, a field - or index of one, or a `match` or `if let` that moves only part of it. Rust drops it - at the end of its statement, or of the `match`. -- A closure that captures a value that drops, which dropping the closure would drop. -- A `for` loop over values that drop: each drops at the end of its iteration, and the +What still fails translation, each with its span (the reject fixture has one of each), +ranked by the census of moq-net at the pinned revision (kio's has 26 in all): + +- Dropping a value whose drop no `[Symbol.dispose]` carries (480): a `Result`, an + `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs + glue of its own, switching on the variant. +- A method taking `self` by value that drops (155), which can't leave `this` undefined. +- A temporary that drops, unless a call or binding takes it whole (247): borrowed, a + field or index of one, a `match`, `if let`, or let chain that moves only part of it, + and a guarded arm that binds one. Rust drops it at the end of its statement, or of + the `match`. +- A `for` loop over values that drop (53): each at the end of its iteration, and the rest on a `break`. -- An enum whose variants hold values that drop, a tuple or array of them, a generic - type that implements `Drop`, a method taking such a `self` by value, and struct - update syntax from one. +- Struct update syntax from a value that drops (15), a closure capturing one (13), a + generic type that implements `Drop` (11), and a parameter that drops bound by a + pattern. Watch the cost: each move of a value that drops writes `undefined` to where it was, and each scope holding one becomes a `try`/`finally`. A pass that proves a variable moved on diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index e55c9df9f..3920b4b14 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 46 -- Function instances: 27 +- Refusals: 48 +- Function instances: 28 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -11,33 +11,35 @@ | 6 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | | 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | -| 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:163:17 | +| 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | | 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | -| 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:127:3 | -| 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:129:3 | -| 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:128:3 | -| 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:132:3 | -| 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:92:1 | +| 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | +| 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | +| 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:133:3 | +| 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:137:3 | +| 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | -| 1 | a cast to `_` | fixtures/reject/src/lib.rs:174:2 | -| 1 | a closure of type `_` | fixtures/reject/src/lib.rs:116:10 | +| 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | +| 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | | 1 | a closure that captures a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:68:23 | -| 1 | a closure that copies a mutable variable | fixtures/reject/src/lib.rs:144:18 | +| 1 | a closure that copies a mutable variable | fixtures/reject/src/lib.rs:149:18 | | 1 | a field of a temporary that drops: bind it to a variable first | fixtures/reject/src/lib.rs:62:2 | | 1 | a method that takes `self` by value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:20 | -| 1 | a mutable reference to `_`, which is no object it can change in place | fixtures/reject/src/lib.rs:139:17 | -| 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:124:3 | -| 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:131:3 | -| 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:108:3 | -| 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:151:3 | +| 1 | a mutable reference to `_`, which is no object it can change in place | fixtures/reject/src/lib.rs:144:17 | +| 1 | a parameter that drops bound by a pattern, which is not supported yet | fixtures/reject/src/lib.rs:83:21 | +| 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:129:3 | +| 1 | a variable from outside the function | fixtures/reject/src/lib.rs:84:2 | +| 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:136:3 | +| 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:113:3 | +| 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | -| 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:130:3 | -| 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:125:3 | -| 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:126:3 | -| 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:158:2 | +| 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:135:3 | +| 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:130:3 | +| 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:131:3 | +| 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:163:2 | | 1 | unsupported literal of type `_` | fixtures/reject/src/lib.rs:7:6 | ## By API @@ -47,50 +49,50 @@ The type or module each refused type or path belongs to. | Count | API | First | | ---: | --- | --- | | 6 | `f64` | fixtures/reject/src/lib.rs:6:1 | -| 4 | `std::string::String` | fixtures/reject/src/lib.rs:137:16 | -| 3 | `Meters` | fixtures/reject/src/lib.rs:163:17 | +| 4 | `std::string::String` | fixtures/reject/src/lib.rs:142:16 | +| 3 | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | -| 2 | `{async closure}` | fixtures/reject/src/lib.rs:116:6 | -| 1 | `Boxed` | fixtures/reject/src/lib.rs:92:1 | +| 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | +| 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `Option` | fixtures/reject/src/lib.rs:31:15 | -| 1 | `Slot` | fixtures/reject/src/lib.rs:88:1 | +| 1 | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | -| 1 | `u8` | fixtures/reject/src/lib.rs:108:3 | +| 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | ## By type or path | Count | Construct | Type or path | First | | ---: | --- | --- | --- | -| 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:163:17 | +| 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | -| 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:92:1 | +| 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | -| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:137:16 | +| 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | -| 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:137:16 | +| 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 1 | a cast from `_` | `char` | fixtures/reject/src/lib.rs:11:2 | -| 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:174:2 | -| 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:116:10 | -| 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:139:17 | -| 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:108:3 | +| 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:179:2 | +| 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:121:10 | +| 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:144:17 | +| 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | -| 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:88:1 | +| 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | | 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | | 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | -| 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:139:10 | +| 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:144:10 | | 1 | unsupported call to `_` | `std::slice::iter` | fixtures/reject/src/lib.rs:40:4 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:36:4 | | 1 | unsupported literal of type `_` | `f64` | fixtures/reject/src/lib.rs:7:6 | | 1 | unsupported type `_` | `char` | fixtures/reject/src/lib.rs:10:18 | | 1 | unsupported type `_` | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | -| 1 | unsupported type `_` | `{async closure}` | fixtures/reject/src/lib.rs:116:6 | +| 1 | unsupported type `_` | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | ## Spans @@ -100,8 +102,8 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:6:14: unsupported type `f64` - fixtures/reject/src/lib.rs:10:18: unsupported type `char` - fixtures/reject/src/lib.rs:14:16: unsupported type `dyn std::ops::Fn(u8) -> u8` -- fixtures/reject/src/lib.rs:116:6: unsupported type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` -- fixtures/reject/src/lib.rs:172:1: unsupported type `f64` +- fixtures/reject/src/lib.rs:121:6: unsupported type `{async closure@fixtures/reject/src/lib.rs:121:10: 121:18}` +- fixtures/reject/src/lib.rs:177:1: unsupported type `f64`
@@ -111,7 +113,7 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:40:4: unsupported call to `core::slice::::iter` - fixtures/reject/src/lib.rs:40:11: unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` - fixtures/reject/src/lib.rs:40:31: unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` -- fixtures/reject/src/lib.rs:139:10: unsupported call to `::write_fmt` +- fixtures/reject/src/lib.rs:144:10: unsupported call to `::write_fmt` @@ -119,59 +121,59 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:19:13: a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change - fixtures/reject/src/lib.rs:25:6: a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change -- fixtures/reject/src/lib.rs:137:16: a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change +- fixtures/reject/src/lib.rs:142:16: a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change
replacing the value behind a reference to `_` (3) -- fixtures/reject/src/lib.rs:163:17: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:163:20: replacing the value behind a reference to `Meters` -- fixtures/reject/src/lib.rs:167:25: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:168:17: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:168:20: replacing the value behind a reference to `Meters` +- fixtures/reject/src/lib.rs:172:25: replacing the value behind a reference to `Meters`
`_`: a JS value of `_` is a copy, so a reference can't change it (2) - fixtures/reject/src/lib.rs:19:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it -- fixtures/reject/src/lib.rs:137:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it +- fixtures/reject/src/lib.rs:142:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it
dropping `_`, which is not supported yet (2) - fixtures/reject/src/lib.rs:66:31: dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet -- fixtures/reject/src/lib.rs:88:1: dropping `Slot`, which is not supported yet +- fixtures/reject/src/lib.rs:93:1: dropping `Slot`, which is not supported yet
`Binary` formatting, as in `{:b}`, is not supported (1) -- fixtures/reject/src/lib.rs:127:3: `Binary` formatting, as in `{:b}`, is not supported +- fixtures/reject/src/lib.rs:132:3: `Binary` formatting, as in `{:b}`, is not supported
`LowerExp` formatting, as in `{:e}`, is not supported (1) -- fixtures/reject/src/lib.rs:129:3: `LowerExp` formatting, as in `{:e}`, is not supported +- fixtures/reject/src/lib.rs:134:3: `LowerExp` formatting, as in `{:e}`, is not supported
`Octal` formatting, as in `{:o}`, is not supported (1) -- fixtures/reject/src/lib.rs:128:3: `Octal` formatting, as in `{:o}`, is not supported +- fixtures/reject/src/lib.rs:133:3: `Octal` formatting, as in `{:o}`, is not supported
`Pointer` formatting, as in `{:p}`, is not supported (1) -- fixtures/reject/src/lib.rs:132:3: `Pointer` formatting, as in `{:p}`, is not supported +- fixtures/reject/src/lib.rs:137:3: `Pointer` formatting, as in `{:p}`, is not supported
`_` is generic and implements `Drop`, which is not supported yet (1) -- fixtures/reject/src/lib.rs:92:1: `Boxed` is generic and implements `Drop`, which is not supported yet +- fixtures/reject/src/lib.rs:97:1: `Boxed` is generic and implements `Drop`, which is not supported yet
@@ -195,13 +197,13 @@ The type or module each refused type or path belongs to.
a cast to `_` (1) -- fixtures/reject/src/lib.rs:174:2: a cast to `f64` +- fixtures/reject/src/lib.rs:179:2: a cast to `f64`
a closure of type `_` (1) -- fixtures/reject/src/lib.rs:116:10: a closure of type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` +- fixtures/reject/src/lib.rs:121:10: a closure of type `{async closure@fixtures/reject/src/lib.rs:121:10: 121:18}`
@@ -213,7 +215,7 @@ The type or module each refused type or path belongs to.
a closure that copies a mutable variable (1) -- fixtures/reject/src/lib.rs:144:18: a closure that copies a mutable variable +- fixtures/reject/src/lib.rs:149:18: a closure that copies a mutable variable
@@ -231,31 +233,43 @@ The type or module each refused type or path belongs to.
a mutable reference to `_`, which is no object it can change in place (1) -- fixtures/reject/src/lib.rs:139:17: a mutable reference to `std::string::String`, which is no object it can change in place +- fixtures/reject/src/lib.rs:144:17: a mutable reference to `std::string::String`, which is no object it can change in place + +
+ +
a parameter that drops bound by a pattern, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:83:21: a parameter that drops bound by a pattern, which is not supported yet
a precision, as in `{:.2}`, is not supported (1) -- fixtures/reject/src/lib.rs:124:3: a precision, as in `{:.2}`, is not supported +- fixtures/reject/src/lib.rs:129:3: a precision, as in `{:.2}`, is not supported + +
+ +
a variable from outside the function (1) + +- fixtures/reject/src/lib.rs:84:2: a variable from outside the function
a width or precision from an argument, as in `{:1$}`, is not supported (1) -- fixtures/reject/src/lib.rs:131:3: a width or precision from an argument, as in `{:1$}`, is not supported +- fixtures/reject/src/lib.rs:136:3: a width or precision from an argument, as in `{:1$}`, is not supported
an async body that borrows `_` mutably, which is no object it can change in place (1) -- fixtures/reject/src/lib.rs:108:3: an async body that borrows `u8` mutably, which is no object it can change in place +- fixtures/reject/src/lib.rs:113:3: an async body that borrows `u8` mutably, which is no object it can change in place
an or-pattern with bindings (1) -- fixtures/reject/src/lib.rs:151:3: an or-pattern with bindings +- fixtures/reject/src/lib.rs:156:3: an or-pattern with bindings
@@ -267,25 +281,25 @@ The type or module each refused type or path belongs to.
hex `Debug`, as in `{:x?}`, is not supported (1) -- fixtures/reject/src/lib.rs:130:3: hex `Debug`, as in `{:x?}`, is not supported +- fixtures/reject/src/lib.rs:135:3: hex `Debug`, as in `{:x?}`, is not supported
the `+` flag of a format spec is not supported (1) -- fixtures/reject/src/lib.rs:125:3: the `+` flag of a format spec is not supported +- fixtures/reject/src/lib.rs:130:3: the `+` flag of a format spec is not supported
the `-` flag of a format spec is not supported (1) -- fixtures/reject/src/lib.rs:126:3: the `-` flag of a format spec is not supported +- fixtures/reject/src/lib.rs:131:3: the `-` flag of a format spec is not supported
unsupported expression: StaticRef (1) -- fixtures/reject/src/lib.rs:158:2: unsupported expression: StaticRef +- fixtures/reject/src/lib.rs:163:2: unsupported expression: StaticRef
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index cc2f4f518..54feaf106 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -1,4 +1,4 @@ -a root must not be generic at fixtures/reject/src/lib.rs:172:1 +a root must not be generic at fixtures/reject/src/lib.rs:177:1 no item `missing` in the crate unsupported type `f64` at fixtures/reject/src/lib.rs:6:14 unsupported literal of type `f64` at fixtures/reject/src/lib.rs:7:6 @@ -20,27 +20,29 @@ a field of a temporary that drops: bind it to a variable first at fixtures/rejec a closure that captures a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:68:23 dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet at fixtures/reject/src/lib.rs:66:31 a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:76:6 -dropping `Slot`, which is not supported yet at fixtures/reject/src/lib.rs:88:1 -`Boxed` is generic and implements `Drop`, which is not supported yet at fixtures/reject/src/lib.rs:100:6 -an async body that borrows `u8` mutably, which is no object it can change in place at fixtures/reject/src/lib.rs:108:3 -unsupported type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` at fixtures/reject/src/lib.rs:116:6 -a closure of type `{async closure@fixtures/reject/src/lib.rs:116:10: 116:18}` at fixtures/reject/src/lib.rs:116:10 -a precision, as in `{:.2}`, is not supported at fixtures/reject/src/lib.rs:124:3 -the `+` flag of a format spec is not supported at fixtures/reject/src/lib.rs:125:3 -the `-` flag of a format spec is not supported at fixtures/reject/src/lib.rs:126:3 -`Binary` formatting, as in `{:b}`, is not supported at fixtures/reject/src/lib.rs:127:3 -`Octal` formatting, as in `{:o}`, is not supported at fixtures/reject/src/lib.rs:128:3 -`LowerExp` formatting, as in `{:e}`, is not supported at fixtures/reject/src/lib.rs:129:3 -hex `Debug`, as in `{:x?}`, is not supported at fixtures/reject/src/lib.rs:130:3 -a width or precision from an argument, as in `{:1$}`, is not supported at fixtures/reject/src/lib.rs:131:3 -`Pointer` formatting, as in `{:p}`, is not supported at fixtures/reject/src/lib.rs:132:3 -a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change at fixtures/reject/src/lib.rs:137:16 -`&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:137:16 -a mutable reference to `std::string::String`, which is no object it can change in place at fixtures/reject/src/lib.rs:139:17 -unsupported call to `::write_fmt` at fixtures/reject/src/lib.rs:139:10 -a closure that copies a mutable variable at fixtures/reject/src/lib.rs:144:18 -an or-pattern with bindings at fixtures/reject/src/lib.rs:151:3 -unsupported expression: StaticRef at fixtures/reject/src/lib.rs:158:2 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:163:17 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:163:20 -replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:167:25 +a parameter that drops bound by a pattern, which is not supported yet at fixtures/reject/src/lib.rs:83:21 +a variable from outside the function at fixtures/reject/src/lib.rs:84:2 +dropping `Slot`, which is not supported yet at fixtures/reject/src/lib.rs:93:1 +`Boxed` is generic and implements `Drop`, which is not supported yet at fixtures/reject/src/lib.rs:105:6 +an async body that borrows `u8` mutably, which is no object it can change in place at fixtures/reject/src/lib.rs:113:3 +unsupported type `{async closure@fixtures/reject/src/lib.rs:121:10: 121:18}` at fixtures/reject/src/lib.rs:121:6 +a closure of type `{async closure@fixtures/reject/src/lib.rs:121:10: 121:18}` at fixtures/reject/src/lib.rs:121:10 +a precision, as in `{:.2}`, is not supported at fixtures/reject/src/lib.rs:129:3 +the `+` flag of a format spec is not supported at fixtures/reject/src/lib.rs:130:3 +the `-` flag of a format spec is not supported at fixtures/reject/src/lib.rs:131:3 +`Binary` formatting, as in `{:b}`, is not supported at fixtures/reject/src/lib.rs:132:3 +`Octal` formatting, as in `{:o}`, is not supported at fixtures/reject/src/lib.rs:133:3 +`LowerExp` formatting, as in `{:e}`, is not supported at fixtures/reject/src/lib.rs:134:3 +hex `Debug`, as in `{:x?}`, is not supported at fixtures/reject/src/lib.rs:135:3 +a width or precision from an argument, as in `{:1$}`, is not supported at fixtures/reject/src/lib.rs:136:3 +`Pointer` formatting, as in `{:p}`, is not supported at fixtures/reject/src/lib.rs:137:3 +a `&mut std::string::String` binding: a JS value of `std::string::String` is a copy, so it can't change at fixtures/reject/src/lib.rs:142:16 +`&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it at fixtures/reject/src/lib.rs:142:16 +a mutable reference to `std::string::String`, which is no object it can change in place at fixtures/reject/src/lib.rs:144:17 +unsupported call to `::write_fmt` at fixtures/reject/src/lib.rs:144:10 +a closure that copies a mutable variable at fixtures/reject/src/lib.rs:149:18 +an or-pattern with bindings at fixtures/reject/src/lib.rs:156:3 +unsupported expression: StaticRef at fixtures/reject/src/lib.rs:163:2 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:168:17 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:168:20 +replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:172:25 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 83c3c55d2..39419b6c0 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -79,6 +79,11 @@ pub fn each(v: Vec) -> u8 { sum } +/// The part the pattern skips drops at the end of the function, which nothing marks. +pub fn destructured((a, _): (Noisy, Noisy)) -> u8 { + a.0 +} + pub enum Slot { Empty, Full(Noisy), diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 694d3550f..9ae7c4636 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -12,6 +12,7 @@ roots = [ "temporary", "owning_closure", "each", + "destructured", "slot", "boxed", "async_borrow", diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 9d9947d67..36d2cef78 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -309,6 +309,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let mutable = mode.1 == rustc_ast::Mutability::Mut; self.bind_var(*var, *name, mutable, pat.ty, pat.span, true) } + _ if self.t.drops(self.subst(pat.ty)) => { + self.t.err( + pat.span, + "a parameter that drops bound by a pattern, which is not supported yet", + ); + self.fresh("arg") + } PatKind::Wild => self.fresh("_"), _ => { let name = self.fresh("arg"); diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index b6ebc05e1..8bce2c5b9 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -55,8 +55,13 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { /// if `params`. fn fields_drop(&mut self, adt: AdtDef<'tcx>, args: ty::GenericArgsRef<'tcx>, params: bool) -> bool { let tcx = self.tcx; + let env = self.typing_env_pub(); adt.all_fields().any(|field| { - let ty = self.subst(args, tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); + // A projection from a type parameter normalizes only where its bounds are known. + let field = ty::EarlyBinder::bind(tcx, tcx.type_of(field.did).instantiate_identity().skip_norm_wip()); + let ty = tcx + .try_instantiate_and_normalize_erasing_regions(args, env, field) + .unwrap_or_else(|_| field.instantiate(tcx, args).skip_norm_wip()); (params || !ty.has_param()) && self.drops(ty) }) } From abc7c4c452cd819a14b557af796e1be142b0c0c7 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:49:34 -0700 Subject: [PATCH 08/30] fix(ts): an async block drops only what it owns, on the path that moves it A block borrowing a value that drops no longer drops it when cancelled, a block created on one branch moves its captures out on that branch only, and a block drops the captures it owns when it returns or is cancelled mid-await, in capture order after its locals. The task fixture's `blocks` covers each against native Rust. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 8 +- ts/fixtures/task/expected/model.ts | 142 +++++++++++++++++++++++++++++ ts/fixtures/task/src/harness.rs | 10 +- ts/fixtures/task/src/model.rs | 27 ++++++ ts/fixtures/task/ts.toml | 2 +- ts/src/lower/body.rs | 57 ++++++++---- ts/tests/fixtures.rs | 4 +- ts/tests/task.ts | 13 ++- 8 files changed, 236 insertions(+), 27 deletions(-) diff --git a/ts/README.md b/ts/README.md index 6538a4a45..7ea3636d4 100644 --- a/ts/README.md +++ b/ts/README.md @@ -97,10 +97,10 @@ move leaves `undefined` where it was, which drops as nothing. An `async fn` returns a future without running anything: `rt.future(body, drop, ...upvars)`, whose body is a module-level generator of what the function captured. Each `.await` polls in a loop around `yield`. A poll after the future returned panics, and -dropping it cancels it: unpolled, it drops what it captured; suspended, its generator -returns through the `finally` blocks that drop its locals. `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. +dropping it cancels it: unpolled, it drops what it captured by value; suspended, its +generator returns through the `finally` blocks that drop its locals and captures. +`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. Imports name the `.ts` file, which Node, Bun, and bundlers run as is. A `tsc` build sets `rewriteRelativeImportExtensions`, or `allowImportingTsExtensions` with `noEmit`. diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 78f36f54e..b320b8ae9 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -133,6 +133,11 @@ export class Guard { rt.drop(log); } } + + /** Log `event` as this guard's. */ + note(event: string): void { + this.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(this.id, f), " ", (f: rt.Formatter) => f.pad(event)])); + } } /** @@ -194,6 +199,143 @@ export function sumDrop(rx: Consumer, guard: Guard): void { rt.drop(guard); } +/** + * One value read through the captures only an async block makes: a borrow, which + * dropping the block must not drop; a move on one path only; and a move the block only + * borrows, which drops when the block returns or is cancelled. + */ +export function blocks(rx: Consumer, guard: Guard, moves: boolean): rt.Future { + return rt.future(blocksBody, blocksDrop, rx, guard, moves); +} + +export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard, moves: boolean): Generator { + let rx2: Consumer = rx; + rx = undefined!; + try { + let guard2 = guard; + guard = undefined!; + try { + const moves2 = moves; + let first = Guard.new(rt.u32.add(guard2.id, 200), guard2.log.clone()); + try { + let second = Guard.new(rt.u32.add(guard2.id, 300), guard2.log.clone()); + try { + rt.drop(rt.future(blocksBody$2, undefined, first)); + if (moves2) { + const guard22 = guard2; + guard2 = undefined!; + rt.drop(rt.future(blocksBody$3, blocksDrop$2, guard22)); + } + const first2 = first; + first = undefined!; + const second2 = second; + second = undefined!; + const rx22 = rx2; + rx2 = undefined!; + let read = rt.future(blocksBody$4, blocksDrop$3, first2, second2, rx22); + try { + const read2 = read; + read = undefined!; + let __awaitee2: rt.Future = read2; + try { + while (true) { + const poll2 = __awaitee2.poll(_taskContext); + if (poll2 !== rt.Pending) { + const result2 = poll2; + return result2; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee2); + } + } finally { + rt.drop(read); + } + } finally { + rt.drop(second); + } + } finally { + rt.drop(first); + } + } finally { + rt.drop(guard2); + } + } finally { + rt.drop(rx2); + } +} + +export function blocksDrop(rx: Consumer, guard: Guard, _moves: boolean): void { + rt.drop(rx); + rt.drop(guard); +} + +export function* blocksBody$2(_taskContext2: rt.Context, first: Guard): Generator { + first.note("borrowed"); +} + +export function* blocksBody$3(_taskContext3: rt.Context, guard2: Guard): Generator { + try { + guard2.note("moved"); + } finally { + rt.drop(guard2); + } +} + +export function blocksDrop$2(guard2: Guard): void { + rt.drop(guard2); +} + +export function* blocksBody$4(_taskContext4: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { + try { + try { + try { + first.note("reads"); + second.note("reads"); + const _held = Guard.new(rt.u32.add(second.id, 100), second.log.clone()); + try { + let option: bigint | undefined; + let __awaitee: rt.Future = rx2.recv(); + try { + while (true) { + const poll = __awaitee.poll(_taskContext4); + if (poll !== rt.Pending) { + const result = poll; + option = result; + break; + } + _taskContext4 = yield; + } + } finally { + rt.drop(__awaitee); + } + if (option !== undefined) { + const value = option; + return value; + } else { + return 0n; + } + } finally { + rt.drop(_held); + } + } finally { + rt.drop(first); + } + } finally { + rt.drop(second); + } + } finally { + rt.drop(rx2); + } +} + +export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { + rt.drop(first); + rt.drop(second); + rt.drop(rx2); +} + /** * Every value until the channel closes, summed, each read `depth` async functions * deep: 1, 4, or 16. diff --git a/ts/fixtures/task/src/harness.rs b/ts/fixtures/task/src/harness.rs index 11e9accb5..ca40a6255 100644 --- a/ts/fixtures/task/src/harness.rs +++ b/ts/fixtures/task/src/harness.rs @@ -17,7 +17,7 @@ pub fn run(input: &[u8]) -> Vec { for step in input.chunks(2) { let (op, arg) = (step[0], step.get(1).copied().unwrap_or(0)); let pick = |len: usize| (len > 0).then(|| usize::from(arg) % len); - match op % 10 { + match op % 11 { 0 => { log.note(format!("c{} open", channels.len())); channels.push(Channel::open()); @@ -61,11 +61,17 @@ pub fn run(input: &[u8]) -> Vec { exec.poll(t); } } - _ => { + 9 => { if let Some(t) = pick(exec.len()) { exec.drop(t); } } + _ => { + if let Some(c) = pick(channels.len()) { + let guard = Guard::new(exec.len() as u32, log.clone()); + exec.spawn(model::blocks(channels[c].consumer(), guard, arg >= 128)); + } + } } } for t in 0..exec.len() { diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 721dac846..83a3f3596 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -67,6 +67,11 @@ impl Guard { pub fn new(id: u32, log: Log) -> Self { Self { id, log } } + + /// Log `event` as this guard's. + fn note(&self, event: &str) { + self.log.note(format!("g{} {event}", self.id)); + } } impl Drop for Guard { @@ -87,6 +92,28 @@ pub async fn sum(mut rx: Consumer, guard: Guard) -> u64 { total } +/// One value read through the captures only an async block makes: a borrow, which +/// dropping the block must not drop; a move on one path only; and a move the block only +/// borrows, which drops when the block returns or is cancelled. +pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { + let first = Guard::new(guard.id + 200, guard.log.clone()); + let second = Guard::new(guard.id + 300, guard.log.clone()); + drop(async { first.note("borrowed") }); + if moves { + drop(async move { guard.note("moved") }); + } + let read = async move { + first.note("reads"); + second.note("reads"); + let _held = Guard::new(second.id + 100, second.log.clone()); + match rx.recv().await { + Some(value) => value, + None => 0, + } + }; + read.await +} + /// Every value until the channel closes, summed, each read `depth` async functions /// deep: 1, 4, or 16. pub async fn drain(mut rx: Consumer, depth: u32) -> u64 { diff --git a/ts/fixtures/task/ts.toml b/ts/fixtures/task/ts.toml index 71edb61d5..21343ef6d 100644 --- a/ts/fixtures/task/ts.toml +++ b/ts/fixtures/task/ts.toml @@ -1,4 +1,4 @@ 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"] +roots = ["log::Log", "model::Channel", "model::Guard", "model::sum", "model::drain", "model::blocks"] diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 36d2cef78..56e44a708 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1988,7 +1988,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } } ExprKind::Adt(adt) => self.adt_expr(adt, ty, span, out), - ExprKind::Closure(closure) => self.closure(closure.closure_id, span), + ExprKind::Closure(closure) => self.closure(closure.closure_id, span, out), ExprKind::Assign { .. } | ExprKind::AssignOp { .. } | ExprKind::Break { .. } @@ -2300,7 +2300,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { /// The generator is a function of its own, taking its upvars as parameters: a /// generator function made per call costs V8 a prototype object and a new shape for /// each generator, about 25 times what one made once does. - fn closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span) -> Expr { + fn closure(&mut self, local: rustc_hir::def_id::LocalDefId, span: Span, out: &mut Vec) -> Expr { let tcx = self.t.tcx; let Some((thir, body)) = self.t.body(local) else { return self.err(span, "no body for a closure"); @@ -2317,8 +2317,16 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } _ => return self.err(span, format!("a closure of type `{closure_ty}`")), }; - // A generator's upvars, each a parameter: its name, its value here, and its type. - let mut upvars: Vec<(String, Expr, Ty<'tcx>)> = Vec::new(); + // An async fn's body is this block alone, which rustc starts by moving each argument + // into a local: the function gives its arguments up whole, and those locals drop + // them. A block moves what it owns out of its place, as any move does, and drops it. + let fn_body = matches!( + tcx.coroutine_kind(local), + Some(rustc_hir::CoroutineKind::Desugared(_, rustc_hir::CoroutineSource::Fn)) + ); + // A generator's upvars, each a parameter: its name, its value here, its type, and + // whether the future owns it and so drops it. + let mut upvars: Vec<(String, Expr, Ty<'tcx>, bool)> = Vec::new(); // What the generator renames, to put back once it is lowered. let mut renamed = Vec::new(); for capture in tcx.closure_captures(local) { @@ -2363,9 +2371,20 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { .err(capture.get_path_span(tcx), "an async body capturing a function item"); continue; }; - // The future owns what it captures, so here drops none of it. - self.disown(&name); - let (param, value) = match name == "this" { + let owns = by_value && self.t.drops(ty); + let place = match name == "this" { + true => Expr::This, + false => Expr::ident(&name), + }; + let value = match (owns, fn_body) { + (true, true) => { + self.disown(&name); + place + } + (true, false) => self.move_out(place, capture.get_path_span(tcx), out), + (false, _) => place, + }; + let param = match name == "this" { true => { let alias = self.fresh("self"); let saved = self.locals.insert( @@ -2376,11 +2395,11 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { }, ); renamed.push((var, saved)); - (alias, Expr::This) + alias } - false => (name.clone(), Expr::ident(name)), + false => name, }; - upvars.push((param, value, ty)); + upvars.push((param, value, ty, owns)); } let saved_thir = std::mem::replace(&mut self.thir, thir); self.read.extend(reads(tcx, thir)); @@ -2389,6 +2408,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let mut body_stmts = Vec::new(); let mut params = Vec::new(); self.open_scope(); + // Upvars drop in capture order, after the locals: the first is the innermost. + for (name, _, ty, owns) in upvars.iter().rev() { + if *owns && !fn_body { + self.own(name, *ty); + } + } // The first parameter is the closure's environment; a coroutine's second is the // context each poll resumes it with. for param in thir.params.iter().skip(1) { @@ -2425,25 +2450,25 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let parent = tcx.typeck_root_def_id(local.to_def_id()); let base = camel(tcx.item_name(parent).as_str()); let mut drops = Vec::new(); - for (name, _, ty) in &upvars { - if let Some(dropped) = self.t.drop_value(Expr::ident(name), *ty, span) { + for (name, _, ty, owns) in &upvars { + if *owns && let Some(dropped) = self.t.drop_value(Expr::ident(name), *ty, span) { drops.push(StmtKind::Expr(dropped).at(None)); } } let upvar_params: Vec = upvars .iter() - .map(|(name, _, ty)| Param { + .map(|(name, _, ty, _)| Param { name: name.clone(), ty: Some(self.t.ty(*ty, span)), }) .collect(); params.extend(upvar_params.iter().cloned()); let body_fn = self.hoist(parent, format!("{base}Body"), params, ret_ty, body_stmts, true, span); - // The drop reads only the upvars that drop: TypeScript lets the rest go unread as `_`s. + // The drop reads only the upvars it drops: TypeScript lets the rest go unread as `_`s. let drop_params = upvars .iter() .zip(upvar_params) - .map(|((_, _, ty), param)| match self.t.drops(*ty) { + .map(|((_, _, _, owns), param)| match owns { true => param, false => Param { name: format!("_{}", param.name), @@ -2464,7 +2489,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ), }; let mut args = vec![body_fn, drop_fn]; - args.extend(upvars.into_iter().map(|(_, value, _)| value)); + args.extend(upvars.into_iter().map(|(_, value, _, _)| value)); Expr::rt("future", args) } diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 8a4996ac3..5145cabc6 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -209,11 +209,11 @@ fn task() { let text = format!( r#"import * as rt from "./rt.ts"; import {{ Log }} from "./log.ts"; -import {{ Channel, Guard, drain, sum }} from "./model.ts"; +import {{ Channel, Guard, blocks, drain, sum }} from "./model.ts"; import {{ harness }} from {harness:?}; export {{ cases }} from {harness:?}; -export const run = harness({{ Pending: rt.Pending, Log, Channel, Guard, sum, drain }}); +export const run = harness({{ Pending: rt.Pending, Log, Channel, Guard, sum, drain, blocks }}); "# ); std::fs::write(out.join("caller.ts"), text).unwrap(); diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 504d53c7c..017bda089 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -39,6 +39,7 @@ export interface Fixture { Guard: { "new"(id: number, log: Log): Guard }; sum(rx: Consumer, guard: Guard): Future; drain(rx: Consumer, depth: number): Future; + blocks(rx: Consumer, guard: Guard, moves: boolean): Future; } /** What every waker of one task points at. */ @@ -166,7 +167,7 @@ export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array const arg = input[i + 1] ?? 0; const pick = (len: number) => (len > 0 ? arg % len : undefined); const c = pick(channels.length); - switch (op % 10) { + switch (op % 11) { case 0: log.note(`c${channels.length} open`); channels.push(f.Channel.open()); @@ -206,10 +207,15 @@ export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array if (t !== undefined) exec.poll(t); break; } - default: { + case 9: { const t = pick(exec.tasks.length); if (t !== undefined) exec.drop(t); + break; } + default: + if (c !== undefined) { + exec.spawn(f.blocks(channels[c].consumer(), f.Guard.new(exec.tasks.length, log.clone()), arg >= 128)); + } } } for (let t = 0; t < exec.tasks.length; t++) exec.drop(t); @@ -235,4 +241,7 @@ export const cases: Uint8Array[] = [ [0, 0, 1, 0, 5, 0, 4, 0, 6, 0, 3, 2, 4, 0, 6, 0], // A task woken twice before its poll is queued once. [0, 0, 0, 1, 1, 0, 1, 1, 6, 0, 3, 1, 5, 0, 3, 2, 6, 0], + // An async block's captures: one borrowed, one moved on one path only, and one moved + // but only borrowed, dropped when its block returns or is cancelled mid-await. + [0, 0, 10, 0, 10, 128, 10, 0, 6, 0, 3, 5, 7, 0, 7, 0, 9, 2, 6, 0], ].map((script) => Uint8Array.from(script)); From 89191313af274b9806c01e3ba6bccf771d87322c Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:02:23 -0700 Subject: [PATCH 09/30] test(ts): a loop broken inside a drop scope still ends its match arm Merging main's tail loops taught `breaks_out` about `try` blocks, which wrap a loop body that holds a value that drops. Without that, the task fixture's `turns` falls through to the next arm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 32 ++++++++++++++++++++++++++++++ ts/fixtures/task/src/model.rs | 21 ++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index b320b8ae9..3879db83a 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -221,6 +221,7 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard let second = Guard.new(rt.u32.add(guard2.id, 300), guard2.log.clone()); try { rt.drop(rt.future(blocksBody$2, undefined, first)); + turns(guard2.log, rt.u32.rem(guard2.id, 5)); if (moves2) { const guard22 = guard2; guard2 = undefined!; @@ -336,6 +337,37 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { rt.drop(rx2); } +/** + * A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from + * inside a turn's scope must still skip the arms after it. + */ +export function turns(log: Log, count: number): void { + arms: { + if (count === 0) { + log.note("no turns"); + break arms; + } + const n = count; + if (n < 4) { + let left: number = n; + while (true) { + const turn = Guard.new(left, log.clone()); + try { + if (left === 1) { + break; + } + turn.note("turn"); + left = rt.u32.sub(left, 1); + } finally { + rt.drop(turn); + } + } + break arms; + } + log.note("many turns"); + } +} + /** * Every value until the channel closes, summed, each read `depth` async functions * deep: 1, 4, or 16. diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 83a3f3596..336068b43 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -99,6 +99,7 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { let first = Guard::new(guard.id + 200, guard.log.clone()); let second = Guard::new(guard.id + 300, guard.log.clone()); drop(async { first.note("borrowed") }); + turns(&guard.log, guard.id % 5); if moves { drop(async move { guard.note("moved") }); } @@ -114,6 +115,26 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { read.await } +/// A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from +/// inside a turn's scope must still skip the arms after it. +fn turns(log: &Log, count: u32) { + match count { + 0 => log.note(format!("no turns")), + n if n < 4 => { + let mut left = n; + loop { + let turn = Guard::new(left, log.clone()); + if left == 1 { + break; + } + turn.note("turn"); + left -= 1; + } + } + _ => log.note(format!("many turns")), + } +} + /// Every value until the channel closes, summed, each read `depth` async functions /// deep: 1, 4, or 16. pub async fn drain(mut rx: Consumer, depth: u32) -> u64 { From 776680cdb2cd8bb819a07b87b85b2e8988a7af33 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:03:36 -0700 Subject: [PATCH 10/30] fix(ts): rt.spawn yields after its poll budget even when a task wakes itself `run` cleared `scheduled` before its batch, so a task waking itself queued another microtask, which ran ahead of the `setTimeout` continuation and starved timers. `scheduled` now stays set until the queue drains. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 2 ++ ts/runtime/rt/task.ts | 16 +++++++--------- ts/tests/runtime.rs | 15 +++++++++++++++ ts/tests/spawn.ts | 22 ++++++++++++++++++++++ 4 files changed, 46 insertions(+), 9 deletions(-) create mode 100644 ts/tests/runtime.rs create mode 100644 ts/tests/spawn.ts diff --git a/ts/README.md b/ts/README.md index aa8191d8e..976a23b0e 100644 --- a/ts/README.md +++ b/ts/README.md @@ -159,6 +159,8 @@ built natively for wasm32 and run beside its translation on the same inputs by - `reject` holds constructs outside the subset; its expected errors are `expected.txt`, and its expected census is `census.md`. +`tests/spawn.ts` checks that `rt.spawn` yields to a timer after its 128-poll budget. + ## Bench ```bash diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index 691a46899..a92e81cf6 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -187,16 +187,14 @@ const BUDGET = 128; const queue: { run(): void }[] = []; let scheduled = false; +// `scheduled` stays set while a batch runs, so a task it wakes joins the batch rather +// than queueing a microtask that would run ahead of the macrotask. function run(): void { - scheduled = false; - for (let polls = 0; polls < BUDGET; polls++) { - const task = queue.shift(); - if (task === undefined) return; - task.run(); - } - if (queue.length > 0) { - scheduled = true; - setTimeout(run, 0); + try { + for (let polls = 0; polls < BUDGET && queue.length > 0; polls++) queue.shift()!.run(); + } finally { + if (queue.length > 0) setTimeout(run, 0); + else scheduled = false; } } diff --git a/ts/tests/runtime.rs b/ts/tests/runtime.rs new file mode 100644 index 000000000..f9d024358 --- /dev/null +++ b/ts/tests/runtime.rs @@ -0,0 +1,15 @@ +//! The runtime's own behavior, beyond what translated fixtures exercise. + +use std::path::PathBuf; +use std::process::Command; + +/// `rt.spawn` yields to a macrotask once a batch spends its poll budget. +#[test] +fn spawn_budget() { + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("spawn.ts"); + let output = Command::new("node") + .arg(script) + .output() + .expect("running node, which the dev shell provides"); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); +} diff --git a/ts/tests/spawn.ts b/ts/tests/spawn.ts new file mode 100644 index 000000000..9226bf57a --- /dev/null +++ b/ts/tests/spawn.ts @@ -0,0 +1,22 @@ +// `rt.spawn` on a task that keeps waking itself: it yields to a timer queued before it +// once a batch spends its budget of 128 polls, so it cannot starve timers and I/O. +// +// usage: node spawn.ts + +import * as rt from "../runtime/rt.ts"; + +let polls = 0; +let beforeTimer: number | undefined; +const selfWaking: rt.Future = { + poll(cx: rt.Context): rt.Poll { + if (++polls === 1000) return polls; + cx.wakeByRef(); + return rt.Pending; + }, + [Symbol.dispose](): void {}, +}; +setTimeout(() => { + beforeTimer = polls; +}, 0); +await rt.spawn(selfWaking); +if (beforeTimer !== 128) throw new Error(`${beforeTimer} polls ran before the timer, not 128`); From cd567b58094bfa1e8e13ae6ec828d50e3da5e981 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:05:12 -0700 Subject: [PATCH 11/30] fix(ts): refuse dropping a borrow of a value that drops through an untyped holder An `Arc`, a `Mutex`, and a generic class's glue drop their contents through `[Symbol.dispose]`, but a reference is its referent in JS: `Arc<&Noisy>` dropping its last count would drop the `Noisy` it borrows. Such a holder now fails with its span, as the reject fixture's `shared_borrow` shows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/reject/census.md | 23 +++++++++++--------- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 6 ++++++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/drop.rs | 37 +++++++++++++++++++++++++++------ 5 files changed, 52 insertions(+), 16 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 4eed16538..2161b9750 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 49 -- Function instances: 28 +- Refusals: 50 +- Function instances: 29 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -11,9 +11,9 @@ | 6 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | | 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | +| 3 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | -| 2 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:133:3 | @@ -62,6 +62,7 @@ The type or module each refused type or path belongs to. | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | +| 1 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | @@ -84,6 +85,7 @@ The type or module each refused type or path belongs to. | 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | +| 1 | dropping `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | | 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | | 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | @@ -126,6 +128,14 @@ The type or module each refused type or path belongs to. +
dropping `_`, which is not supported yet (3) + +- fixtures/reject/src/lib.rs:66:31: dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet +- fixtures/reject/src/lib.rs:93:1: dropping `Slot`, which is not supported yet +- fixtures/reject/src/lib.rs:183:42: dropping `std::sync::Arc<&Noisy>`, which is not supported yet + +
+
replacing the value behind a reference to `_` (3) - fixtures/reject/src/lib.rs:168:17: replacing the value behind a reference to `Meters` @@ -141,13 +151,6 @@ The type or module each refused type or path belongs to.
-
dropping `_`, which is not supported yet (2) - -- fixtures/reject/src/lib.rs:66:31: dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet -- fixtures/reject/src/lib.rs:93:1: dropping `Slot`, which is not supported yet - -
-
`Binary` formatting, as in `{:b}`, is not supported (1) - fixtures/reject/src/lib.rs:132:3: `Binary` formatting, as in `{:b}`, is not supported diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index fd3a46661..f8958b601 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -47,3 +47,4 @@ unsupported expression: StaticRef at fixtures/reject/src/lib.rs:163:2 replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:168:17 replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:168:20 replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:172:25 +dropping `std::sync::Arc<&Noisy>`, which is not supported yet at fixtures/reject/src/lib.rs:183:42 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 39419b6c0..6e21e5c64 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -178,3 +178,9 @@ pub fn generic>(t: &mut T) -> f64 { // A census lowers this over `T`: what hinges on `T` waits for an instance, the float does not. (*t).into() as f64 } + +/// An `Arc` of a borrow is the borrowed value in JS: dropping the last one would drop it. +pub fn shared_borrow(n: &Noisy) -> usize { + let a = std::sync::Arc::new(n); + std::sync::Arc::strong_count(&a) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 35c475987..d5698b9c1 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -25,6 +25,7 @@ roots = [ "swapped", "replaced", "generic", + "shared_borrow", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index 8bce2c5b9..c0e1665fc 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -66,24 +66,49 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { }) } - /// Whether a `ty` that drops does so through its own `[Symbol.dispose]`, so whatever - /// holds one can drop it without knowing its type. + /// Whether whatever holds a `ty` can drop it without knowing its type, through the + /// `[Symbol.dispose]` its JS value has, as an `Arc` and a generic class's glue do. fn disposable(&mut self, ty: Ty<'tcx>) -> bool { if !self.drops(ty) { - return true; + return self.inert(ty); } match ty.kind() { ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { - Some(Std::Arc | Std::Waker | Std::Mutex) => true, - Some(Std::Option | Std::Box) => self.disposable(args.type_at(0)), + Some(Std::Waker) => true, + Some(Std::Arc | Std::Mutex | Std::Option | Std::Box) => self.disposable(args.type_at(0)), Some(_) => false, - None => adt.is_struct(), + None => adt.is_struct() && args.types().all(|t| self.disposable(t)), }, ty::Coroutine(..) | ty::Param(_) => true, _ => false, } } + /// Whether dropping a `ty` through its JS value's `[Symbol.dispose]` does nothing. A + /// reference is its referent in JS, so dropping a borrow of a value that drops would + /// drop the value. + fn inert(&mut self, ty: Ty<'tcx>) -> bool { + if self.drops(ty) { + return false; + } + match ty.kind() { + ty::Ref(_, inner, _) => self.inert(*inner), + ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { + // Each is its contents in JS. + Some(Std::Option | Std::Box | Std::Mutex | Std::MutexGuard | Std::Poll | Std::Pin) => { + args.types().all(|t| self.inert(t)) + } + // Its waker. + Some(Std::Context) => false, + Some(_) => true, + // Its glue, if an instance that drops gave it one, drops its type parameters' fields. + None if adt.is_struct() => args.types().all(|t| self.inert(t)), + None => true, + }, + _ => true, + } + } + /// What drops the `ty` in `value`, or `None` if JS would see nothing drop. pub fn drop_value(&mut self, value: Expr, ty: Ty<'tcx>, span: Span) -> Option { if !self.drops(ty) { From 90da98705673c9c6dd79d3c5b47212684b9facac Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:11:01 -0700 Subject: [PATCH 12/30] fix(ts): refuse an operand that drops ahead of an .await in the same call `consume(guard, fut.await)` moved `guard` into a temporary before the `yield`, where no scope dropped it if the future was cancelled. It now fails with its span (3 in moq-net, none in kio). The README and the Drop quest list it with the `Arc` of a borrow, and the quest's counts follow the census after main's merges. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 11 +++++++---- ts/README.md | 3 ++- ts/fixtures/reject/census.md | 11 +++++++++-- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 10 ++++++++++ ts/fixtures/reject/ts.toml | 1 + ts/src/census.rs | 1 + ts/src/lower/body.rs | 15 +++++++++++++++ 8 files changed, 46 insertions(+), 7 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 01c559d19..aef7a1d41 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -19,19 +19,22 @@ fixture's trace test proves it on kio's waiters, wakers, and channels. What still fails translation, each with its span (the reject fixture has one of each), ranked by the census of moq-net at the pinned revision (kio's has 26 in all): -- Dropping a value whose drop no `[Symbol.dispose]` carries (480): a `Result`, an +- Dropping a value whose drop no `[Symbol.dispose]` carries (657): a `Result`, an `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs glue of its own, switching on the variant. - A method taking `self` by value that drops (155), which can't leave `this` undefined. -- A temporary that drops, unless a call or binding takes it whole (247): borrowed, a +- A temporary that drops, unless a call or binding takes it whole (256): borrowed, a field or index of one, a `match`, `if let`, or let chain that moves only part of it, and a guarded arm that binds one. Rust drops it at the end of its statement, or of the `match`. -- A `for` loop over values that drop (53): each at the end of its iteration, and the +- A `for` loop over values that drop (60): each at the end of its iteration, and the rest on a `break`. -- Struct update syntax from a value that drops (15), a closure capturing one (13), a +- Struct update syntax from a value that drops (16), a closure capturing one (13), a generic type that implements `Drop` (11), and a parameter that drops bound by a pattern. +- An operand that drops ahead of an `.await` in the same call (3), which a cancel + would leave in a temporary no scope drops, and an `Arc` or `Mutex` holding a borrow + of a value that drops, which JS would drop as the value itself. Watch the cost: each move of a value that drops writes `undefined` to where it was, and each scope holding one becomes a `try`/`finally`. A pass that proves a variable moved on diff --git a/ts/README.md b/ts/README.md index 976a23b0e..4c878074a 100644 --- a/ts/README.md +++ b/ts/README.md @@ -126,7 +126,8 @@ bind to hand-written TS through config ([model](/quest/m2/ts-model.md)). These fail translation: floats, `char`, statics, async blocks that borrow a number mutably and async closures, values that drop as temporaries not moved whole, in a -closure's captures, in a `for` loop, or in an enum, tuple, or generic `Drop` type +closure's captures, in a `for` loop, in an enum, tuple, or generic `Drop` type, borrowed +in an `Arc` or `Mutex`, or passed ahead of an `.await` in the same call ([Drop](/quest/m2/ts-drop.md)), iterator adaptors (`for` over ranges, slices, arrays, and `Vec` works), or-patterns that bind, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a `String` with `write!`, a `move` closure diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 2161b9750..889a1ac13 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 50 -- Function instances: 29 +- Refusals: 51 +- Function instances: 31 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -34,6 +34,7 @@ | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:175:1 | | 1 | a variable from outside the function | fixtures/reject/src/lib.rs:84:2 | | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:136:3 | +| 1 | an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:190:13 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:113:3 | | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | @@ -271,6 +272,12 @@ The type or module each refused type or path belongs to.
+
an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first (1) + +- fixtures/reject/src/lib.rs:190:13: an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first + +
+
an async body that borrows `_` mutably, which is no object it can change in place (1) - fixtures/reject/src/lib.rs:113:3: an async body that borrows `u8` mutably, which is no object it can change in place diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index f8958b601..5d5904208 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -48,3 +48,4 @@ replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:168:20 replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:172:25 dropping `std::sync::Arc<&Noisy>`, which is not supported yet at fixtures/reject/src/lib.rs:183:42 +an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:190:13 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 6e21e5c64..6b19e931d 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -184,3 +184,13 @@ pub fn shared_borrow(n: &Noisy) -> usize { let a = std::sync::Arc::new(n); std::sync::Arc::strong_count(&a) } + +/// `n` would wait out the `.await` where no scope drops it if the future is cancelled. +pub async fn held_across(n: Noisy) -> u8 { + consume(n, async { 1u8 }.await) +} + +fn consume(n: Noisy, v: u8) -> u8 { + drop(n); + v +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index d5698b9c1..6d2113d41 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -26,6 +26,7 @@ roots = [ "replaced", "generic", "shared_borrow", + "held_across", "missing", ] printable = ["Meters"] diff --git a/ts/src/census.rs b/ts/src/census.rs index 20d06dd2a..1755d9997 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -134,6 +134,7 @@ const VERBATIM: &[&str] = &[ "()", "+", "-", + ".await", "?", "Binary", "Copy", diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 06c50d406..7dbaaefae 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -45,6 +45,7 @@ pub fn function<'a, 'tcx>( visited: FxHashSet::default(), scopes: Vec::new(), moved: FxHashSet::default(), + yields: 0, }; let span = tcx.def_span(def_id); let mut body = Vec::new(); @@ -183,6 +184,8 @@ pub struct Body<'b, 'a, 'tcx> { pub(super) scopes: Vec>>, /// The variables a move left `undefined`, which are declared `let` for it. pub(super) moved: FxHashSet, + /// How many `yield`s are lowered so far, so an operand can tell whether it awaits. + yields: usize, } /// One `&&`-joined part of an `if` condition. @@ -1671,9 +1674,20 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { /// could change. pub fn operands(&mut self, ids: &[ExprId], out: &mut Vec) -> Vec { let mut values: Vec = Vec::with_capacity(ids.len()); + // Whether an earlier operand is a value that drops, which a later `.await` would + // hold where no scope drops it if the future is cancelled. + let mut holds = false; for &id in ids { let mut pre = Vec::new(); + let yields = self.yields; let value = self.operand(id, &mut pre); + if holds && self.yields != yields { + self.t.err( + self.span(id), + "an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first", + ); + } + holds |= self.t.drops(self.ty_of(id)); if !pre.is_empty() { for earlier in values.iter_mut() { if !earlier.is_constant() { @@ -2029,6 +2043,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ExprKind::Let { .. } => self.err(span, "a `let` outside an `if` condition"), ExprKind::Yield { value } => { self.stmt(*value, Dest::Discard, out); + self.yields += 1; Expr::Yield } kind => self.err(span, format!("unsupported expression: {}", kind_name(kind))), From ac957b71dabe2619201c3f8a5f577c4a6409bdca Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:37 -0700 Subject: [PATCH 13/30] fix(ts): rt.spawn rejects when a finished future panics as it drops The completed future's disposal ran outside the `try` that settles the promise, so a panic there left it pending and escaped the scheduler. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 3 ++- ts/runtime/rt/task.ts | 6 +++--- ts/tests/spawn.ts | 15 +++++++++++++-- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/ts/README.md b/ts/README.md index 4c878074a..f8da82cc2 100644 --- a/ts/README.md +++ b/ts/README.md @@ -160,7 +160,8 @@ built natively for wasm32 and run beside its translation on the same inputs by - `reject` holds constructs outside the subset; its expected errors are `expected.txt`, and its expected census is `census.md`. -`tests/spawn.ts` checks that `rt.spawn` yields to a timer after its 128-poll budget. +`tests/spawn.ts` checks that `rt.spawn` yields to a timer after its 128-poll budget, and +rejects when a future panics as it drops. ## Bench diff --git a/ts/runtime/rt/task.ts b/ts/runtime/rt/task.ts index a92e81cf6..0309952fb 100644 --- a/ts/runtime/rt/task.ts +++ b/ts/runtime/rt/task.ts @@ -228,15 +228,15 @@ class Task implements Waker { let output: Poll; try { output = future.poll(this); + if (output === Pending) return; + this.#future = undefined; + future[Symbol.dispose](); } catch (err) { this.#future = undefined; this.#reject(err); if (!(err instanceof Panic)) throw err; return; } - if (output === Pending) return; - this.#future = undefined; - future[Symbol.dispose](); this.#resolve(output); } diff --git a/ts/tests/spawn.ts b/ts/tests/spawn.ts index 9226bf57a..8a8cdaeef 100644 --- a/ts/tests/spawn.ts +++ b/ts/tests/spawn.ts @@ -1,5 +1,6 @@ -// `rt.spawn` on a task that keeps waking itself: it yields to a timer queued before it -// once a batch spends its budget of 128 polls, so it cannot starve timers and I/O. +// `rt.spawn` on futures that misbehave: one that keeps waking itself yields to a timer +// queued before it once a batch spends its budget of 128 polls, so it cannot starve +// timers and I/O, and one that panics as it drops rejects its promise. // // usage: node spawn.ts @@ -20,3 +21,13 @@ setTimeout(() => { }, 0); await rt.spawn(selfWaking); if (beforeTimer !== 128) throw new Error(`${beforeTimer} polls ran before the timer, not 128`); + +const panicsOnDrop: rt.Future = { + poll: () => 1, + [Symbol.dispose]: () => rt.panic("drop failed"), +}; +const settled = await rt.spawn(panicsOnDrop).then( + () => "resolved", + (err: unknown) => (err instanceof rt.Panic ? err.message : `threw ${err}`), +); +if (settled !== "drop failed") throw new Error(`a panic in drop settled the promise as ${settled}`); From 9cc359ae68132104910ae829551be6d72204eac9 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:23:37 -0700 Subject: [PATCH 14/30] fix(ts): a let that binds part of a value that drops leaves the rest to drop `let [kept, _] = pair` moved `pair` out whole through the destructuring shortcut, so the skipped guard never dropped. A place now binds part by part and keeps the rest for its scope to drop, and a temporary bound only in part fails with its span, as a `match` or `if let` on one does (27 in moq-net). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 8 ++-- ts/fixtures/reject/census.md | 11 ++++- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 6 +++ ts/fixtures/reject/ts.toml | 1 + ts/fixtures/task/expected/model.ts | 53 ++++++++++++++--------- ts/fixtures/task/src/model.rs | 6 ++- ts/src/lower/body.rs | 67 +++++++++++++++++++++++++++++- 8 files changed, 125 insertions(+), 28 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index aef7a1d41..7a2a5a216 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -23,10 +23,10 @@ ranked by the census of moq-net at the pinned revision (kio's has 26 in all): `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs glue of its own, switching on the variant. - A method taking `self` by value that drops (155), which can't leave `this` undefined. -- A temporary that drops, unless a call or binding takes it whole (256): borrowed, a - field or index of one, a `match`, `if let`, or let chain that moves only part of it, - and a guarded arm that binds one. Rust drops it at the end of its statement, or of - the `match`. +- A temporary that drops, unless a call or binding takes it whole (283): borrowed, a + field or index of one, a `match`, `if let`, `let`, or let chain that moves only part + of it, and a guarded arm that binds one. Rust drops it at the end of its statement, or + of the `match`. - A `for` loop over values that drop (60): each at the end of its iteration, and the rest on a `break`. - Struct update syntax from a value that drops (16), a closure capturing one (13), a diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 889a1ac13..7b238264d 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 51 -- Function instances: 31 +- Refusals: 52 +- Function instances: 32 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -21,6 +21,7 @@ | 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | +| 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | @@ -194,6 +195,12 @@ The type or module each refused type or path belongs to.
+
a `let` on a temporary that drops, which it doesn't move out of whole (1) + +- fixtures/reject/src/lib.rs:200:2: a `let` on a temporary that drops, which it doesn't move out of whole + +
+
a cast from `_` (1) - fixtures/reject/src/lib.rs:11:2: a cast from `char` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 5d5904208..705d0e509 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -49,3 +49,4 @@ replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs:172:25 dropping `std::sync::Arc<&Noisy>`, which is not supported yet at fixtures/reject/src/lib.rs:183:42 an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:190:13 +a `let` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:200:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 6b19e931d..4e520af00 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -194,3 +194,9 @@ fn consume(n: Noisy, v: u8) -> u8 { drop(n); v } + +/// The skipped element drops at the end of the statement, which nothing marks. +pub fn skipped() -> u8 { + let [kept, _] = [make(), make()]; + kept.0 +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 6d2113d41..9bb9bf68f 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -27,6 +27,7 @@ roots = [ "generic", "shared_borrow", "held_across", + "skipped", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 3879db83a..6f608962e 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -339,32 +339,45 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { /** * A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from - * inside a turn's scope must still skip the arms after it. + * inside a turn's scope must still skip the arms after it. Before them, a pair of + * guards destructured in part: the one left in the array drops with it, after the other. */ export function turns(log: Log, count: number): void { - arms: { - if (count === 0) { - log.note("no turns"); - break arms; - } - const n = count; - if (n < 4) { - let left: number = n; - while (true) { - const turn = Guard.new(left, log.clone()); - try { - if (left === 1) { - break; + const pair = [Guard.new(rt.u32.add(count, 10), log.clone()), Guard.new(rt.u32.add(count, 20), log.clone())]; + try { + const kept = pair[0]; + pair[0] = undefined!; + try { + kept.note("kept"); + arms: { + if (count === 0) { + log.note("no turns"); + break arms; + } + const n = count; + if (n < 4) { + let left: number = n; + while (true) { + const turn = Guard.new(left, log.clone()); + try { + if (left === 1) { + break; + } + turn.note("turn"); + left = rt.u32.sub(left, 1); + } finally { + rt.drop(turn); + } } - turn.note("turn"); - left = rt.u32.sub(left, 1); - } finally { - rt.drop(turn); + break arms; } + log.note("many turns"); } - break arms; + } finally { + rt.drop(kept); } - log.note("many turns"); + } finally { + rt.dropAll(pair); } } diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 336068b43..f8157763b 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -116,8 +116,12 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { } /// A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from -/// inside a turn's scope must still skip the arms after it. +/// inside a turn's scope must still skip the arms after it. Before them, a pair of +/// guards destructured in part: the one left in the array drops with it, after the other. fn turns(log: &Log, count: u32) { + let pair = [Guard::new(count + 10, log.clone()), Guard::new(count + 20, log.clone())]; + let [kept, _] = pair; + kept.note("kept"); match count { 0 => log.note(format!("no turns")), n if n < 4 => { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 7dbaaefae..2b902813a 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -580,8 +580,18 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } return; } + // What the pattern leaves unbound drops with its place, or at the end of the + // statement from a temporary, which nothing marks. The shortcut below would move a + // place out whole, so a place binds part by part instead. + let leaves = self.leaves_drop(pat); + if leaves && !self.is_place(init) { + self.t.err( + span, + "a `let` on a temporary that drops, which it doesn't move out of whole", + ); + } // `const [a, b] = ...` for a tuple or array of plain bindings. - if els.is_none() && self.destructurable(pat, true) { + if els.is_none() && !leaves && self.destructurable(pat, true) { let value = self.operand(init, out); let mut mutable = false; let target = self.destructure(pat, &mut mutable); @@ -627,6 +637,61 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.pat_bind(pat, &scrut, owned, out); } + /// Whether binding `pat` by value leaves part of a value that drops unbound: under a + /// `_` or a `..`, in a field it doesn't name, or in another variant than the one it + /// matches. + fn leaves_drop(&mut self, pat: &Pat<'tcx>) -> bool { + let ty = self.subst(pat.ty); + if !self.t.drops(ty) { + return false; + } + let tcx = self.t.tcx; + match &pat.kind { + PatKind::Binding { + mode, subpattern: None, .. + } => mode.0 != rustc_hir::ByRef::No, + PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => { + let (variant, others) = match (ty.kind(), &pat.kind) { + (ty::Tuple(tys), _) => (tys.to_vec(), Vec::new()), + (ty::Adt(adt, args), PatKind::Variant { variant_index, .. }) => { + let fields = |v: &ty::VariantDef| -> Vec> { + v.fields.iter().map(|f| f.ty(tcx, args).skip_norm_wip()).collect() + }; + let others = adt + .variants() + .iter_enumerated() + .filter(|(i, _)| i != variant_index) + .flat_map(|(_, v)| fields(v)) + .collect(); + (fields(adt.variant(*variant_index)), others) + } + (ty::Adt(adt, args), _) => ( + adt.non_enum_variant() + .fields + .iter() + .map(|f| f.ty(tcx, args).skip_norm_wip()) + .collect(), + Vec::new(), + ), + _ => return true, + }; + others.into_iter().any(|t| self.t.drops(t)) + || variant.into_iter().enumerate().any(|(i, field)| { + match subpatterns.iter().find(|f| f.field.index() == i) { + Some(f) => self.leaves_drop(&f.pattern), + None => self.t.drops(field), + } + }) + } + PatKind::Array { + prefix, + slice: None, + suffix, + } => prefix.iter().chain(suffix.iter()).any(|p| self.leaves_drop(p)), + _ => true, + } + } + /// Whether `pat` is a tuple or array of plain bindings, which JS destructures. fn destructurable(&self, pat: &Pat<'tcx>, top: bool) -> bool { let ty = self.subst(pat.ty); From 32a286419285c55b3b1c30a2546b9625c7b8726b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 01:41:00 -0700 Subject: [PATCH 15/30] fix(ts): drop a pinned box, and refuse two more drops a cancel or pattern skips - `Pin

` drops as its pointer does, so `Pin::new(Box::new(guard))` drops the guard. - `Some(..)` names no field, so a `match` or `if let` on a temporary that drops no longer counts it as moving the payload out (3 in moq-net). - A value that drops, assigned to a place whose index awaits, would wait out the `.await` in a temporary no scope drops: it now fails with its span. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 9 +++--- ts/README.md | 2 +- ts/fixtures/reject/census.md | 18 ++++++++++-- ts/fixtures/reject/expected.txt | 2 ++ ts/fixtures/reject/src/lib.rs | 19 ++++++++++++ ts/fixtures/reject/ts.toml | 2 ++ ts/fixtures/task/expected/model.ts | 47 +++++++++++++++++------------- ts/fixtures/task/src/model.rs | 5 +++- ts/src/lower/body.rs | 19 +++++++++++- ts/src/lower/drop.rs | 6 ++-- 10 files changed, 97 insertions(+), 32 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 7a2a5a216..e95439ff9 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -23,7 +23,7 @@ ranked by the census of moq-net at the pinned revision (kio's has 26 in all): `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs glue of its own, switching on the variant. - A method taking `self` by value that drops (155), which can't leave `this` undefined. -- A temporary that drops, unless a call or binding takes it whole (283): borrowed, a +- A temporary that drops, unless a call or binding takes it whole (286): borrowed, a field or index of one, a `match`, `if let`, `let`, or let chain that moves only part of it, and a guarded arm that binds one. Rust drops it at the end of its statement, or of the `match`. @@ -32,9 +32,10 @@ ranked by the census of moq-net at the pinned revision (kio's has 26 in all): - Struct update syntax from a value that drops (16), a closure capturing one (13), a generic type that implements `Drop` (11), and a parameter that drops bound by a pattern. -- An operand that drops ahead of an `.await` in the same call (3), which a cancel - would leave in a temporary no scope drops, and an `Arc` or `Mutex` holding a borrow - of a value that drops, which JS would drop as the value itself. +- A value that drops, moved ahead of an `.await` in the same call (3) or in the place + an assignment writes it to, which a cancel would leave in a temporary no scope drops, + and an `Arc` or `Mutex` holding a borrow of a value that drops, which JS would drop + as the value itself. Watch the cost: each move of a value that drops writes `undefined` to where it was, and each scope holding one becomes a `try`/`finally`. A pass that proves a variable moved on diff --git a/ts/README.md b/ts/README.md index f8da82cc2..b69ac5ea4 100644 --- a/ts/README.md +++ b/ts/README.md @@ -127,7 +127,7 @@ bind to hand-written TS through config ([model](/quest/m2/ts-model.md)). These fail translation: floats, `char`, statics, async blocks that borrow a number mutably and async closures, values that drop as temporaries not moved whole, in a closure's captures, in a `for` loop, in an enum, tuple, or generic `Drop` type, borrowed -in an `Arc` or `Mutex`, or passed ahead of an `.await` in the same call +in an `Arc` or `Mutex`, or moved ahead of an `.await` in the same call or assignment ([Drop](/quest/m2/ts-drop.md)), iterator adaptors (`for` over ranges, slices, arrays, and `Vec` works), or-patterns that bind, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a `String` with `write!`, a `move` closure diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 7b238264d..0a07ccd67 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 52 -- Function instances: 32 +- Refusals: 54 +- Function instances: 35 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -22,6 +22,7 @@ | 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | +| 1 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | @@ -36,6 +37,7 @@ | 1 | a variable from outside the function | fixtures/reject/src/lib.rs:84:2 | | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:136:3 | | 1 | an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:190:13 | +| 1 | an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:207:2 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:113:3 | | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | @@ -201,6 +203,12 @@ The type or module each refused type or path belongs to.

+
a `match` on a temporary that drops, which it doesn't move out of whole (1) + +- fixtures/reject/src/lib.rs:217:2: a `match` on a temporary that drops, which it doesn't move out of whole + +
+
a cast from `_` (1) - fixtures/reject/src/lib.rs:11:2: a cast from `char` @@ -285,6 +293,12 @@ The type or module each refused type or path belongs to.
+
an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first (1) + +- fixtures/reject/src/lib.rs:207:2: an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first + +
+
an async body that borrows `_` mutably, which is no object it can change in place (1) - fixtures/reject/src/lib.rs:113:3: an async body that borrows `u8` mutably, which is no object it can change in place diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 705d0e509..55dee9acb 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -50,3 +50,5 @@ replacing the value behind a reference to `Meters` at fixtures/reject/src/lib.rs dropping `std::sync::Arc<&Noisy>`, which is not supported yet at fixtures/reject/src/lib.rs:183:42 an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:190:13 a `let` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:200:2 +an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:207:2 +a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:217:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 4e520af00..7e01e6bb6 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -200,3 +200,22 @@ pub fn skipped() -> u8 { let [kept, _] = [make(), make()]; kept.0 } + +/// `n` would wait out the `.await` in the index where no scope drops it on a cancel. +pub async fn assigned(n: Noisy) -> u8 { + let mut slots = [make(), make()]; + slots[index().await] = n; + slots[0].0 +} + +async fn index() -> usize { + 1 +} + +/// `Some(..)` leaves the payload in the temporary, which drops after the `match`. +pub fn unnamed() -> u8 { + match Some(make()) { + Some(..) => 1, + None => 0, + } +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 9bb9bf68f..8b03060f3 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -28,6 +28,8 @@ roots = [ "shared_borrow", "held_across", "skipped", + "assigned", + "unnamed", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 6f608962e..19581e363 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -340,7 +340,8 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { /** * A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from * inside a turn's scope must still skip the arms after it. Before them, a pair of - * guards destructured in part: the one left in the array drops with it, after the other. + * guards destructured in part: the one left in the array drops with it, after the other; + * and a pinned box of one, which drops it. */ export function turns(log: Log, count: number): void { const pair = [Guard.new(rt.u32.add(count, 10), log.clone()), Guard.new(rt.u32.add(count, 20), log.clone())]; @@ -349,29 +350,35 @@ export function turns(log: Log, count: number): void { pair[0] = undefined!; try { kept.note("kept"); - arms: { - if (count === 0) { - log.note("no turns"); - break arms; - } - const n = count; - if (n < 4) { - let left: number = n; - while (true) { - const turn = Guard.new(left, log.clone()); - try { - if (left === 1) { - break; + const pinned = Guard.new(rt.u32.add(count, 40), log.clone()); + try { + pinned.note("pinned"); + arms: { + if (count === 0) { + log.note("no turns"); + break arms; + } + const n = count; + if (n < 4) { + let left: number = n; + while (true) { + const turn = Guard.new(left, log.clone()); + try { + if (left === 1) { + break; + } + turn.note("turn"); + left = rt.u32.sub(left, 1); + } finally { + rt.drop(turn); } - turn.note("turn"); - left = rt.u32.sub(left, 1); - } finally { - rt.drop(turn); } + break arms; } - break arms; + log.note("many turns"); } - log.note("many turns"); + } finally { + rt.drop(pinned); } } finally { rt.drop(kept); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index f8157763b..baeabff30 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -117,11 +117,14 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { /// A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from /// inside a turn's scope must still skip the arms after it. Before them, a pair of -/// guards destructured in part: the one left in the array drops with it, after the other. +/// guards destructured in part: the one left in the array drops with it, after the other; +/// and a pinned box of one, which drops it. fn turns(log: &Log, count: u32) { let pair = [Guard::new(count + 10, log.clone()), Guard::new(count + 20, log.clone())]; let [kept, _] = pair; kept.note("kept"); + let pinned = std::pin::Pin::new(Box::new(Guard::new(count + 40, log.clone()))); + pinned.note("pinned"); match count { 0 => log.note(format!("no turns")), n if n < 4 => { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 2b902813a..55d8c9d31 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1650,7 +1650,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { fn assign(&mut self, lhs: ExprId, rhs: ExprId, span: Span, out: &mut Vec) { let mut value = self.operand(rhs, out); let mut pre = Vec::new(); + let yields = self.yields; let target = self.place(lhs, &mut pre); + // The value waits out the `.await` where no scope drops it if the future is cancelled. + if self.yields != yields && self.t.drops(self.ty_of(rhs)) { + self.t.err( + self.span(lhs), + "an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first", + ); + } if (!pre.is_empty() || !target.is_path()) && !value.is_constant() { value = self.spill(value, "value", out); } @@ -2931,7 +2939,16 @@ fn takes_all(pat: &Pat<'_>) -> bool { PatKind::Binding { mode, subpattern: None, .. } => mode.0 == rustc_hir::ByRef::No, - PatKind::Variant { subpatterns, .. } => subpatterns.iter().all(|f| takes_all(&f.pattern)), + // `Some(..)` names no field, which then stays in the temporary. + PatKind::Variant { + adt_def, + variant_index, + subpatterns, + .. + } => { + subpatterns.len() == adt_def.variant(*variant_index).fields.len() + && subpatterns.iter().all(|f| takes_all(&f.pattern)) + } _ => false, } } diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index c0e1665fc..b599f8716 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -34,7 +34,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { let drops = match ty.kind() { ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { Some(Std::Arc | Std::Waker) => true, - Some(Std::Option | Std::Result | Std::Box | Std::Vec | Std::Mutex | Std::Poll) => { + Some(Std::Option | Std::Result | Std::Box | Std::Vec | Std::Mutex | Std::Poll | Std::Pin) => { args.types().any(|t| self.drops(t)) } Some(_) => false, @@ -75,7 +75,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { match ty.kind() { ty::Adt(adt, args) => match Std::of(self.tcx, adt.did()) { Some(Std::Waker) => true, - Some(Std::Arc | Std::Mutex | Std::Option | Std::Box) => self.disposable(args.type_at(0)), + Some(Std::Arc | Std::Mutex | Std::Option | Std::Box | Std::Pin) => self.disposable(args.type_at(0)), Some(_) => false, None => adt.is_struct() && args.types().all(|t| self.disposable(t)), }, @@ -119,7 +119,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { Some(Std::Vec) if self.disposable(args.type_at(0)) => { return Some(Expr::rt("dropAll", vec![value])); } - Some(Std::Arc | Std::Mutex | Std::Option | Std::Box) => self.disposable(args.type_at(0)), + Some(Std::Arc | Std::Mutex | Std::Option | Std::Box | Std::Pin) => self.disposable(args.type_at(0)), Some(Std::Waker) => true, Some(_) => false, None if adt.is_struct() => { From 724435b4000091ee14f21d2c3ffb54fc61991713 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:05:34 -0700 Subject: [PATCH 16/30] fix(ts): a ref binding borrows its place, and `let _` still evaluates one `let ref r = g` moved and cleared `g`, so nothing dropped it; it now borrows `g` where it is, and `let ref r = make()` owns the temporary it keeps alive to the end of the block. `let _ = guards[i]` skipped the place entirely; it now evaluates the index and its bounds check, moving nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 68 +++++++++++++++++++++--------- ts/fixtures/task/src/model.rs | 18 +++++++- ts/src/lower/body.rs | 34 +++++++++++---- 3 files changed, 90 insertions(+), 30 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 19581e363..433ce0497 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -337,11 +337,19 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { rt.drop(rx2); } +/** `i`, noted as picked. */ +export function pick(log: Log, i: number): number { + log.note(rt.fmt.format(["pick ", (f: rt.Formatter) => rt.usize.display(i, f)])); + return i; +} + /** * A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from * inside a turn's scope must still skip the arms after it. Before them, a pair of * guards destructured in part: the one left in the array drops with it, after the other; - * and a pinned box of one, which drops it. + * a pinned box of one, which drops it; `ref` bindings, which borrow a variable and keep a + * temporary to the end of the block; and a `_` binding of an element, which evaluates its + * index and moves nothing. */ export function turns(log: Log, count: number): void { const pair = [Guard.new(rt.u32.add(count, 10), log.clone()), Guard.new(rt.u32.add(count, 20), log.clone())]; @@ -353,29 +361,49 @@ export function turns(log: Log, count: number): void { const pinned = Guard.new(rt.u32.add(count, 40), log.clone()); try { pinned.note("pinned"); - arms: { - if (count === 0) { - log.note("no turns"); - break arms; - } - const n = count; - if (n < 4) { - let left: number = n; - while (true) { - const turn = Guard.new(left, log.clone()); - try { - if (left === 1) { - break; + const held = Guard.new(rt.u32.add(count, 50), log.clone()); + try { + const borrowed = held; + borrowed.note("borrowed"); + const extended = Guard.new(rt.u32.add(count, 60), log.clone()); + try { + extended.note("extended"); + const spares = [Guard.new(rt.u32.add(count, 70), log.clone()), Guard.new(rt.u32.add(count, 80), log.clone())]; + try { + const index = pick(log, rt.usize.rem(count, 2)); + spares[rt.idx(spares, index)]; + arms: { + if (count === 0) { + log.note("no turns"); + break arms; + } + const n = count; + if (n < 4) { + let left: number = n; + while (true) { + const turn = Guard.new(left, log.clone()); + try { + if (left === 1) { + break; + } + turn.note("turn"); + left = rt.u32.sub(left, 1); + } finally { + rt.drop(turn); + } + } + break arms; } - turn.note("turn"); - left = rt.u32.sub(left, 1); - } finally { - rt.drop(turn); + log.note("many turns"); } + } finally { + rt.dropAll(spares); } - break arms; + } finally { + rt.drop(extended); } - log.note("many turns"); + } finally { + rt.drop(held); } } finally { rt.drop(pinned); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index baeabff30..9efc28e76 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -115,16 +115,32 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { read.await } +/// `i`, noted as picked. +fn pick(log: &Log, i: usize) -> usize { + log.note(format!("pick {i}")); + i +} + /// A guard per turn of a loop that ends a guarded `match` arm, so leaving the loop from /// inside a turn's scope must still skip the arms after it. Before them, a pair of /// guards destructured in part: the one left in the array drops with it, after the other; -/// and a pinned box of one, which drops it. +/// a pinned box of one, which drops it; `ref` bindings, which borrow a variable and keep a +/// temporary to the end of the block; and a `_` binding of an element, which evaluates its +/// index and moves nothing. +#[expect(clippy::toplevel_ref_arg, reason = "the `ref` bindings are under test")] fn turns(log: &Log, count: u32) { let pair = [Guard::new(count + 10, log.clone()), Guard::new(count + 20, log.clone())]; let [kept, _] = pair; kept.note("kept"); let pinned = std::pin::Pin::new(Box::new(Guard::new(count + 40, log.clone()))); pinned.note("pinned"); + let held = Guard::new(count + 50, log.clone()); + let ref borrowed = held; + borrowed.note("borrowed"); + let ref extended = Guard::new(count + 60, log.clone()); + extended.note("extended"); + let spares = [Guard::new(count + 70, log.clone()), Guard::new(count + 80, log.clone())]; + let _ = spares[pick(log, count as usize % 2)]; match count { 0 => log.note(format!("no turns")), n if n < 4 => { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 55d8c9d31..31b076546 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -527,13 +527,17 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.ref_binding(mode.0, pat_ty, pat.span); } let mutable = mode.1 == rustc_ast::Mutability::Mut; - let owns = mode.0 == rustc_hir::ByRef::No; + let by_value = mode.0 == rustc_hir::ByRef::No; let ty = self.t.ty(pat_ty, pat.span); let Some(init) = init else { - let name = self.bind_var(*var, *name, true, pat_ty, pat.span, owns); + let name = self.bind_var(*var, *name, true, pat_ty, pat.span, by_value); self.push(out, StmtKind::decl(true, name, Some(ty), None), span); return; }; + // A `ref` binding borrows a place where it is, and keeps a temporary alive to the + // end of the block, which then drops it as it would a variable. + let borrows = !by_value && self.is_place(init); + let owns = !borrows; if self.needs_dest(init) { let name = self.bind_var(*var, *name, true, pat_ty, pat.span, owns); self.push(out, StmtKind::decl(true, name.clone(), Some(ty), None), span); @@ -541,7 +545,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { return; } // A move from another variable or field: it is left `undefined`. - if self.moves(init) { + if by_value && self.moves(init) { let place = self.place(init, out); let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); let annotate = mutable.then_some(ty); @@ -549,7 +553,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.clear(place, out); return; } - let value = self.operand(init, out); + let value = match borrows { + true => self.place(init, out), + false => self.operand(init, out), + }; let name = self.bind_var(*var, *name, mutable, pat_ty, pat.span, owns); let annotate = mutable || needs_annotation(&value); self.push( @@ -567,15 +574,24 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } return; }; - // `let _ = value;` drops a value at once, and leaves a place alone. + // `let _ = value;` drops a value at once, and evaluates a place without moving it: + // an index still runs, and checks its bounds. if let PatKind::Wild = pat.kind && els.is_none() && self.t.drops(pat_ty) { - if !self.is_place(init) { - let value = self.operand(init, out); - if let Some(dropped) = self.t.drop_value(value, pat_ty, span) { - self.push(out, StmtKind::Expr(dropped), span); + match self.is_place(init) { + true => { + let place = self.place(init, out); + if !place.is_path() { + self.push(out, StmtKind::Expr(place), span); + } + } + false => { + let value = self.operand(init, out); + if let Some(dropped) = self.t.drop_value(value, pat_ty, span) { + self.push(out, StmtKind::Expr(dropped), span); + } } } return; From a9f34f91e0f1aac9da9e26106bd88d5895e18357 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:22:30 -0700 Subject: [PATCH 17/30] fix(ts): copy an async block's Copy captures, and refuse replacing an Arc in place `async move { read(tally) }` shared the caller's `Tally` object, so a later change reached the future; a by-value capture is now copied as any `Copy` aggregate is. `*dst = src` through a `&mut Arc` copied fields into the one JS object every clone shares; it now fails with its span, as does the same through a waker, context, or future. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 3 +- ts/fixtures/reject/census.md | 14 +++- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 5 ++ ts/fixtures/reject/ts.toml | 1 + ts/fixtures/task/expected/model.ts | 113 ++++++++++++++++++++--------- ts/fixtures/task/src/model.rs | 19 ++++- ts/src/lower/body.rs | 18 +++++ 8 files changed, 134 insertions(+), 40 deletions(-) diff --git a/ts/README.md b/ts/README.md index 457754453..b7eb827ed 100644 --- a/ts/README.md +++ b/ts/README.md @@ -133,7 +133,8 @@ in an `Arc` or `Mutex`, or moved ahead of an `.await` in the same call or assign `Vec` works), or-patterns that bind, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a `String` with `write!`, a `move` closure copying a mutable variable, `mem::swap`, `replace`, or `take` of a reference's whole -pointee, and std functions without a mapping in `src/lower/library.rs`. +pointee, assigning an `Arc`, a waker, or a future through a reference, and std functions +without a mapping in `src/lower/library.rs`. ## Tests diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 0a07ccd67..b15877af6 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 54 -- Function instances: 35 +- Refusals: 55 +- Function instances: 36 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -42,6 +42,7 @@ | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:135:3 | +| 1 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:130:3 | | 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:131:3 | | 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:163:2 | @@ -59,6 +60,7 @@ The type or module each refused type or path belongs to. | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | +| 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | | 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `Option` | fixtures/reject/src/lib.rs:31:15 | @@ -66,7 +68,6 @@ The type or module each refused type or path belongs to. | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | -| 1 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | @@ -91,6 +92,7 @@ The type or module each refused type or path belongs to. | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | dropping `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | +| 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::Arc` | fixtures/reject/src/lib.rs:225:2 | | 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | | 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:144:10 | @@ -323,6 +325,12 @@ The type or module each refused type or path belongs to.
+
replacing the `_` behind a reference, whose JS object is shared or private (1) + +- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private + +
+
the `+` flag of a format spec is not supported (1) - fixtures/reject/src/lib.rs:130:3: the `+` flag of a format spec is not supported diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 55dee9acb..06705e9d9 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -52,3 +52,4 @@ an `.await` in an operand after one that drops, which is not supported yet: bind a `let` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:200:2 an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:207:2 a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:217:2 +replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:225:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 7e01e6bb6..a6864ca8d 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -219,3 +219,8 @@ pub fn unnamed() -> u8 { None => 0, } } + +/// Every clone of an `Arc` is one JS object: replacing the payload would reach them all. +pub fn replace_shared(dst: &mut std::sync::Arc, src: std::sync::Arc) { + *dst = src; +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 8b03060f3..8ddcae726 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -30,6 +30,7 @@ roots = [ "skipped", "assigned", "unnamed", + "replace_shared", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 433ce0497..239c4d6c0 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -201,8 +201,9 @@ export function sumDrop(rx: Consumer, guard: Guard): void { /** * One value read through the captures only an async block makes: a borrow, which - * dropping the block must not drop; a move on one path only; and a move the block only - * borrows, which drops when the block returns or is cancelled. + * dropping the block must not drop; a copy, which a later change to the original must + * not reach; a move on one path only; and a move the block only borrows, which drops + * when the block returns or is cancelled. */ export function blocks(rx: Consumer, guard: Guard, moves: boolean): rt.Future { return rt.future(blocksBody, blocksDrop, rx, guard, moves); @@ -222,36 +223,63 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard try { rt.drop(rt.future(blocksBody$2, undefined, first)); turns(guard2.log, rt.u32.rem(guard2.id, 5)); - if (moves2) { - const guard22 = guard2; - guard2 = undefined!; - rt.drop(rt.future(blocksBody$3, blocksDrop$2, guard22)); - } - const first2 = first; - first = undefined!; - const second2 = second; - second = undefined!; - const rx22 = rx2; - rx2 = undefined!; - let read = rt.future(blocksBody$4, blocksDrop$3, first2, second2, rx22); + let tally: Tally = new Tally({ n: guard2.id }); + let seen = rt.future(blocksBody$3, undefined, rt.copy(tally)); try { - const read2 = read; - read = undefined!; - let __awaitee2: rt.Future = read2; + tally.n = rt.u32.add(tally.n, 1000); + const arg2 = guard2; + const arg = tally.n; + let value: number; + const seen2 = seen; + seen = undefined!; + let __awaitee: rt.Future = seen2; try { while (true) { - const poll2 = __awaitee2.poll(_taskContext); - if (poll2 !== rt.Pending) { - const result2 = poll2; - return result2; + const poll = __awaitee.poll(_taskContext); + if (poll !== rt.Pending) { + const result = poll; + value = result; + break; } _taskContext = yield; } } finally { - rt.drop(__awaitee2); + rt.drop(__awaitee); + } + arg2.note(rt.fmt.format(["tally ", (f: rt.Formatter) => rt.u32.display(arg, f), " then ", (f: rt.Formatter) => rt.u32.display(value, f)])); + if (moves2) { + const guard22 = guard2; + guard2 = undefined!; + rt.drop(rt.future(blocksBody$4, blocksDrop$2, guard22)); + } + const first2 = first; + first = undefined!; + const second2 = second; + second = undefined!; + const rx22 = rx2; + rx2 = undefined!; + let read_ = rt.future(blocksBody$5, blocksDrop$3, first2, second2, rx22); + try { + const read2 = read_; + read_ = undefined!; + let __awaitee3: rt.Future = read2; + try { + while (true) { + const poll3 = __awaitee3.poll(_taskContext); + if (poll3 !== rt.Pending) { + const result3 = poll3; + return result3; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee3); + } + } finally { + rt.drop(read_); } } finally { - rt.drop(read); + rt.drop(seen); } } finally { rt.drop(second); @@ -276,7 +304,11 @@ export function* blocksBody$2(_taskContext2: rt.Context, first: Guard): Generato first.note("borrowed"); } -export function* blocksBody$3(_taskContext3: rt.Context, guard2: Guard): Generator { +export function* blocksBody$3(_taskContext3: rt.Context, tally: Tally): Generator { + return read(rt.copy(tally)); +} + +export function* blocksBody$4(_taskContext4: rt.Context, guard2: Guard): Generator { try { guard2.note("moved"); } finally { @@ -288,7 +320,7 @@ export function blocksDrop$2(guard2: Guard): void { rt.drop(guard2); } -export function* blocksBody$4(_taskContext4: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { +export function* blocksBody$5(_taskContext5: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { try { try { try { @@ -297,23 +329,23 @@ export function* blocksBody$4(_taskContext4: rt.Context, first: Guard, second: G const _held = Guard.new(rt.u32.add(second.id, 100), second.log.clone()); try { let option: bigint | undefined; - let __awaitee: rt.Future = rx2.recv(); + let __awaitee2: rt.Future = rx2.recv(); try { while (true) { - const poll = __awaitee.poll(_taskContext4); - if (poll !== rt.Pending) { - const result = poll; - option = result; + const poll2 = __awaitee2.poll(_taskContext5); + if (poll2 !== rt.Pending) { + const result2 = poll2; + option = result2; break; } - _taskContext4 = yield; + _taskContext5 = yield; } } finally { - rt.drop(__awaitee); + rt.drop(__awaitee2); } if (option !== undefined) { - const value = option; - return value; + const value2 = option; + return value2; } else { return 0n; } @@ -337,6 +369,19 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { rt.drop(rx2); } +/** A `Copy` value an `async move` block takes its own copy of. */ +export class Tally { + n: number; + + constructor(fields: { n: number }) { + this.n = fields.n; + } +} + +export function read(t: Tally): number { + return t.n; +} + /** `i`, noted as picked. */ export function pick(log: Log, i: number): number { log.note(rt.fmt.format(["pick ", (f: rt.Formatter) => rt.usize.display(i, f)])); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 9efc28e76..bb1817efd 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -93,13 +93,18 @@ pub async fn sum(mut rx: Consumer, guard: Guard) -> u64 { } /// One value read through the captures only an async block makes: a borrow, which -/// dropping the block must not drop; a move on one path only; and a move the block only -/// borrows, which drops when the block returns or is cancelled. +/// dropping the block must not drop; a copy, which a later change to the original must +/// not reach; a move on one path only; and a move the block only borrows, which drops +/// when the block returns or is cancelled. pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { let first = Guard::new(guard.id + 200, guard.log.clone()); let second = Guard::new(guard.id + 300, guard.log.clone()); drop(async { first.note("borrowed") }); turns(&guard.log, guard.id % 5); + let mut tally = Tally { n: guard.id }; + let seen = async move { read(tally) }; + tally.n += 1000; + guard.note(&format!("tally {} then {}", tally.n, seen.await)); if moves { drop(async move { guard.note("moved") }); } @@ -115,6 +120,16 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { read.await } +/// A `Copy` value an `async move` block takes its own copy of. +#[derive(Clone, Copy)] +struct Tally { + n: u32, +} + +fn read(t: Tally) -> u32 { + t.n +} + /// `i`, noted as picked. fn pick(log: &Log, i: usize) -> usize { log.note(format!("pick {i}")); diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 766b3d455..a2d8b156b 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1706,7 +1706,23 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { && self.is_place(arg) { let pointee = self.ty_of(lhs); + // Every clone of an `Arc` or waker is one JS object, and a future keeps its state + // private: copying fields in would change the other handles, or nothing. + let shared = match pointee.kind() { + ty::Adt(adt, _) => matches!( + library::Std::of(self.t.tcx, adt.did()), + Some(library::Std::Arc | library::Std::Waker | library::Std::Context) + ), + ty::Coroutine(..) => true, + _ => false, + }; match self.t.object_kind(pointee) { + Some(ObjectKind::Class) if shared => { + self.t.err( + span, + format!("replacing the `{pointee}` behind a reference, whose JS object is shared or private"), + ); + } Some(ObjectKind::Class) => { let e = Expr::ident("Object").member("assign").call(vec![target, value]); self.push(out, StmtKind::Expr(e), span); @@ -2521,6 +2537,8 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { place } (true, false) => self.move_out(place, capture.get_path_span(tcx), out), + // A `Copy` aggregate taken by value is the future's own, as JS would share it. + (false, _) if by_value => self.copied(place, ty), (false, _) => place, }; let param = match name == "this" { From 71ba587e1a4e2a356e3900aa671925ffe5ea2c97 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:34:33 -0700 Subject: [PATCH 18/30] fix(ts): a ref temporary keeps its block scoped, and see Option and Poll through wrappers A block whose `let ref` keeps a temporary that drops was flattened into the enclosing scope, delaying the drop past the block's value; it now keeps a scope of its own. `Option` and `Poll` now check what their payload can already erase to through `Option`, `Poll`, `Box`, `Pin`, and references: `Poll>>` and `Option>` collided and are refused. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 4 +-- ts/fixtures/reject/census.md | 24 ++++++++++++------ ts/fixtures/reject/expected.txt | 2 ++ ts/fixtures/reject/src/lib.rs | 10 ++++++++ ts/fixtures/reject/ts.toml | 2 ++ ts/fixtures/task/expected/model.ts | 9 +++++++ ts/fixtures/task/src/model.rs | 5 ++++ ts/src/lower/body.rs | 15 +++++++++++- ts/src/lower/mod.rs | 39 ++++++++++++++++++++++-------- 9 files changed, 90 insertions(+), 20 deletions(-) diff --git a/ts/README.md b/ts/README.md index b7eb827ed..bc93cf952 100644 --- a/ts/README.md +++ b/ts/README.md @@ -56,7 +56,7 @@ runtime: what std does that JS does not, with ownership and async in `rt/task.ts | `struct` | a class; methods take `this`, trait methods included | | `enum` without data | a union of strings: `"Lite01" \| "Lite02"`, or `never` without variants | | `enum` | a union of objects tagged by variant, with a companion object of functions | -| `Option` | `T \| undefined`; an `Option` of `()` or an `Option` is refused | +| `Option` | `T \| undefined`; refused if `T` can already be `undefined`, as `()` and `Option` can | | `Result` | `rt.Result`: `{ ok: true, value }` or `{ ok: false, error }` | | tuple, `[T; N]`, `&[T]`, `Vec` | an array, `Uint8Array` for bytes, `rt.ByteVec` for `Vec` | | `&T`, `&mut T`, `Box` | the value: a `&mut` must point at an object JS can change in place | @@ -65,7 +65,7 @@ runtime: what std does that JS does not, with ownership and async in `rt/task.ts | a type that drops | a class with `[Symbol.dispose]`: its `Drop` impl, then its fields | | `Arc`, `Weak`, `Mutex` | `rt.Arc`, counted; `rt.Weak`; `rt.Mutex`, its own guard | | `async fn` | a function returning `rt.Future`, around a generator | -| `Poll`, `Waker`, `Context` | `T \| typeof rt.Pending`; `rt.Waker`, which is also the context | +| `Poll`, `Waker`, `Context` | `T \| typeof rt.Pending`, refused if `T` can already be pending; `rt.Waker`, which is also the context | `usize` is 32 bits, as on wasm32, so it is exact in a `number`. Arithmetic is checked as a debug build checks it, so translated code panics where native code would: it never diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index b15877af6..5b8e83e9e 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 55 -- Function instances: 36 +- Refusals: 57 +- Function instances: 38 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -13,13 +13,14 @@ | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | | 3 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | +| 2 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:133:3 | | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:137:3 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:97:1 | -| 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | +| 1 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:229:20 | | 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | | 1 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | @@ -58,12 +59,13 @@ The type or module each refused type or path belongs to. | 4 | `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 3 | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | +| 2 | `Option` | fixtures/reject/src/lib.rs:31:15 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | | 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | -| 1 | `Option` | fixtures/reject/src/lib.rs:31:15 | +| 1 | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | @@ -77,9 +79,10 @@ The type or module each refused type or path belongs to. | ---: | --- | --- | --- | | 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | +| 2 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:97:1 | -| 1 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | +| 1 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | | 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | @@ -150,6 +153,13 @@ The type or module each refused type or path belongs to.
+
`_` is not supported: its `None` and `Some` would both be `undefined` (2) + +- fixtures/reject/src/lib.rs:31:15: `Option>` is not supported: its `None` and `Some` would both be `undefined` +- fixtures/reject/src/lib.rs:234:19: `Option>` is not supported: its `None` and `Some` would both be `undefined` + +
+
`_`: a JS value of `_` is a copy, so a reference can't change it (2) - fixtures/reject/src/lib.rs:19:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it @@ -187,9 +197,9 @@ The type or module each refused type or path belongs to.
-
`_` is not supported: its `None` and `Some` would both be `undefined` (1) +
`_` is not supported: it would be pending two ways with one value (1) -- fixtures/reject/src/lib.rs:31:15: `Option>` is not supported: its `None` and `Some` would both be `undefined` +- fixtures/reject/src/lib.rs:229:20: `Poll>>` is not supported: it would be pending two ways with one value
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 06705e9d9..4b6d78f60 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -53,3 +53,5 @@ a `let` on a temporary that drops, which it doesn't move out of whole at fixture an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first at fixtures/reject/src/lib.rs:207:2 a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:217:2 replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:225:2 +`Poll>>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:229:20 +`Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:234:19 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index a6864ca8d..90dbabf28 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -224,3 +224,13 @@ pub fn unnamed() -> u8 { pub fn replace_shared(dst: &mut std::sync::Arc, src: std::sync::Arc) { *dst = src; } + +/// `Ready(Some(Pending))` would be `rt.Pending`, as the outer `Pending` is. +pub fn nested_poll(p: std::task::Poll>>) -> bool { + matches!(p, std::task::Poll::Pending) +} + +/// `None` and `Some(Ready(()))` would both be `undefined`. +pub fn ready_unit(p: Option>) -> bool { + matches!(p, None) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 8ddcae726..0c9d87b41 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -31,6 +31,8 @@ roots = [ "assigned", "unnamed", "replace_shared", + "nested_poll", + "ready_unit", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 239c4d6c0..820bc7a2f 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -413,6 +413,15 @@ export function turns(log: Log, count: number): void { const extended = Guard.new(rt.u32.add(count, 60), log.clone()); try { extended.note("extended"); + let value: number; + const inner = Guard.new(rt.u32.add(count, 90), log.clone()); + try { + value = inner.id; + } finally { + rt.drop(inner); + } + const scoped = value; + log.note(rt.fmt.format(["after ", (f: rt.Formatter) => rt.u32.display(scoped, f)])); const spares = [Guard.new(rt.u32.add(count, 70), log.clone()), Guard.new(rt.u32.add(count, 80), log.clone())]; try { const index = pick(log, rt.usize.rem(count, 2)); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index bb1817efd..ac0c66fe9 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -154,6 +154,11 @@ fn turns(log: &Log, count: u32) { borrowed.note("borrowed"); let ref extended = Guard::new(count + 60, log.clone()); extended.note("extended"); + let scoped = { + let ref inner = Guard::new(count + 90, log.clone()); + inner.id + }; + log.note(format!("after {scoped}")); let spares = [Guard::new(count + 70, log.clone()), Guard::new(count + 80, log.clone())]; let _ = spares[pick(log, count as usize % 2)]; match count { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index a2d8b156b..8c1e1a965 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1843,7 +1843,20 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let thir: &'a Thir<'tcx> = self.thir; let mut owns = false; for &stmt in &thir[id].stmts { - if let thir::StmtKind::Let { pattern, .. } = &thir[stmt].kind { + if let thir::StmtKind::Let { + pattern, initializer, .. + } = &thir[stmt].kind + { + // A `ref` binding keeps a temporary alive to the end of the block. + if let PatKind::Binding { + mode, subpattern: None, .. + } = pattern.kind + && mode.0 != rustc_hir::ByRef::No + && let Some(init) = *initializer + && !self.is_place(init) + { + owns |= self.t.drops(self.ty_of(init)); + } pattern.walk_always(|p| { if let PatKind::Binding { mode, ty, .. } = p.kind && mode.0 == rustc_hir::ByRef::No diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index c443e271d..049252352 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -193,6 +193,14 @@ pub enum ObjectKind { Closure, } +/// The JS values a type's own can be that `Option` and `Poll` erase to: `None` is +/// `undefined`, and `Pending` is `rt.Pending`. +#[derive(Clone, Copy, Default)] +pub struct Erased { + pub undefined: bool, + pub pending: bool, +} + /// Where a translated function lives. #[derive(Clone, Copy)] pub enum Owner { @@ -895,7 +903,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { return match std { library::Std::Option => { let inner = args.type_at(0); - if !self.option_payload_ok(inner) { + if self.erases_to(inner).undefined { self.err( span, format!( @@ -940,7 +948,7 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { library::Std::Context => Type::Rt("Context", vec![]), library::Std::Poll => { let inner = args.type_at(0); - if self.std_of(inner) == Some(library::Std::Poll) { + if self.erases_to(inner).pending { self.err( span, format!("`Poll<{inner}>` is not supported: it would be pending two ways with one value"), @@ -963,17 +971,28 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { Type::Sym(info.sym, args) } - /// Whether `undefined` is free to mean `None` around a `ty`. - pub fn option_payload_ok(&self, ty: Ty<'tcx>) -> bool { + /// Which of the values `Option` and `Poll` erase to a `ty`'s JS value can already be, + /// seen through the wrappers that erase to their contents. + pub fn erases_to(&self, ty: Ty<'tcx>) -> Erased { match ty.kind() { - ty::Tuple(tys) => !tys.is_empty(), - ty::Ref(_, inner, _) => self.option_payload_ok(*inner), + ty::Tuple(tys) if tys.is_empty() => Erased { + undefined: true, + pending: false, + }, + ty::Ref(_, inner, _) => self.erases_to(*inner), ty::Adt(adt, args) => match library::Std::of(self.tcx, adt.did()) { - Some(library::Std::Option) => false, - Some(library::Std::Box) => self.option_payload_ok(args.type_at(0)), - _ => true, + Some(library::Std::Box | library::Std::Pin) => self.erases_to(args.type_at(0)), + Some(library::Std::Option) => Erased { + undefined: true, + ..self.erases_to(args.type_at(0)) + }, + Some(library::Std::Poll) => Erased { + pending: true, + ..self.erases_to(args.type_at(0)) + }, + _ => Erased::default(), }, - _ => true, + _ => Erased::default(), } } From afed30f16f25644e33d0c300884f135da3ea3fe7 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:53:04 -0700 Subject: [PATCH 19/30] fix(ts): replace a generator's mutable borrow in place, and decide recursive drops whole An async block that replaced a variable it borrows mutably rebound its own parameter, so the caller never saw the write; it now writes into the caller's object, as `*r = v` does. `drops` cached a provisional `false` for a type that reached one still being decided, so `Inner` in a cycle with a dropping `Outer` never dropped; a `false` is now cached only once the cycle's first type is decided. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 140 ++++++++++++++++++++++------- ts/fixtures/task/src/model.rs | 34 ++++++- ts/src/lower/body.rs | 31 ++++--- ts/src/lower/drop.rs | 16 +++- ts/src/lower/mod.rs | 5 ++ 5 files changed, 178 insertions(+), 48 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 820bc7a2f..c3f722ba2 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -202,8 +202,9 @@ export function sumDrop(rx: Consumer, guard: Guard): void { /** * One value read through the captures only an async block makes: a borrow, which * dropping the block must not drop; a copy, which a later change to the original must - * not reach; a move on one path only; and a move the block only borrows, which drops - * when the block returns or is cancelled. + * not reach; a mutable borrow the block replaces whole, which the caller must see; a + * move on one path only; and a move the block only borrows, which drops when the block + * returns or is cancelled. Between them, a value of two types that hold each other. */ export function blocks(rx: Consumer, guard: Guard, moves: boolean): rt.Future { return rt.future(blocksBody, blocksDrop, rx, guard, moves); @@ -247,36 +248,65 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard rt.drop(__awaitee); } arg2.note(rt.fmt.format(["tally ", (f: rt.Formatter) => rt.u32.display(arg, f), " then ", (f: rt.Formatter) => rt.u32.display(value, f)])); - if (moves2) { - const guard22 = guard2; - guard2 = undefined!; - rt.drop(rt.future(blocksBody$4, blocksDrop$2, guard22)); + let mark: Mark = new Mark({ n: 1 }); + let replaced: number; + let __awaitee2: rt.Future = rt.future(blocksBody$4, undefined, mark); + try { + while (true) { + const poll2 = __awaitee2.poll(_taskContext); + if (poll2 !== rt.Pending) { + const result2 = poll2; + replaced = result2; + break; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee2); } - const first2 = first; - first = undefined!; - const second2 = second; - second = undefined!; - const rx22 = rx2; - rx2 = undefined!; - let read_ = rt.future(blocksBody$5, blocksDrop$3, first2, second2, rx22); + guard2.note(rt.fmt.format(["mark ", (f: rt.Formatter) => rt.u32.display(replaced, f), " ", (f: rt.Formatter) => rt.u32.display(mark.n, f)])); + let cycle = new Outer({ inner: undefined, guard: Guard.new(rt.u32.add(guard2.id, 800), guard2.log.clone()) }); try { - const read2 = read_; - read_ = undefined!; - let __awaitee3: rt.Future = read2; + const cycle2 = cycle; + cycle = undefined!; + const _nested = new Inner({ outer: cycle2 }); try { - while (true) { - const poll3 = __awaitee3.poll(_taskContext); - if (poll3 !== rt.Pending) { - const result3 = poll3; - return result3; + if (moves2) { + const guard22 = guard2; + guard2 = undefined!; + rt.drop(rt.future(blocksBody$5, blocksDrop$2, guard22)); + } + const first2 = first; + first = undefined!; + const second2 = second; + second = undefined!; + const rx22 = rx2; + rx2 = undefined!; + let read_ = rt.future(blocksBody$6, blocksDrop$3, first2, second2, rx22); + try { + const read2 = read_; + read_ = undefined!; + let __awaitee4: rt.Future = read2; + try { + while (true) { + const poll4 = __awaitee4.poll(_taskContext); + if (poll4 !== rt.Pending) { + const result4 = poll4; + return result4; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee4); } - _taskContext = yield; + } finally { + rt.drop(read_); } } finally { - rt.drop(__awaitee3); + rt.drop(_nested); } } finally { - rt.drop(read_); + rt.drop(cycle); } } finally { rt.drop(seen); @@ -308,7 +338,12 @@ export function* blocksBody$3(_taskContext3: rt.Context, tally: Tally): Generato return read(rt.copy(tally)); } -export function* blocksBody$4(_taskContext4: rt.Context, guard2: Guard): Generator { +export function* blocksBody$4(_taskContext4: rt.Context, mark: Mark): Generator { + Object.assign(mark, new Mark({ n: 2 })); + return mark.n; +} + +export function* blocksBody$5(_taskContext5: rt.Context, guard2: Guard): Generator { try { guard2.note("moved"); } finally { @@ -320,7 +355,7 @@ export function blocksDrop$2(guard2: Guard): void { rt.drop(guard2); } -export function* blocksBody$5(_taskContext5: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { +export function* blocksBody$6(_taskContext6: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { try { try { try { @@ -329,19 +364,19 @@ export function* blocksBody$5(_taskContext5: rt.Context, first: Guard, second: G const _held = Guard.new(rt.u32.add(second.id, 100), second.log.clone()); try { let option: bigint | undefined; - let __awaitee2: rt.Future = rx2.recv(); + let __awaitee3: rt.Future = rx2.recv(); try { while (true) { - const poll2 = __awaitee2.poll(_taskContext5); - if (poll2 !== rt.Pending) { - const result2 = poll2; - option = result2; + const poll3 = __awaitee3.poll(_taskContext6); + if (poll3 !== rt.Pending) { + const result3 = poll3; + option = result3; break; } - _taskContext5 = yield; + _taskContext6 = yield; } } finally { - rt.drop(__awaitee2); + rt.drop(__awaitee3); } if (option !== undefined) { const value2 = option; @@ -369,6 +404,45 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { rt.drop(rx2); } +export class Mark { + n: number; + + constructor(fields: { n: number }) { + this.n = fields.n; + } +} + +/** + * Drops through `guard`, and `Inner` through it: deciding `Outer` first must not leave + * `Inner` decided as dropping nothing. + */ +export class Outer { + inner: Inner | undefined; + guard: Guard; + + constructor(fields: { inner: Inner | undefined; guard: Guard }) { + this.inner = fields.inner; + this.guard = fields.guard; + } + + [Symbol.dispose](): void { + rt.drop(this.inner); + rt.drop(this.guard); + } +} + +export class Inner { + outer: Outer | undefined; + + constructor(fields: { outer: Outer | undefined }) { + this.outer = fields.outer; + } + + [Symbol.dispose](): void { + rt.drop(this.outer); + } +} + /** A `Copy` value an `async move` block takes its own copy of. */ export class Tally { n: number; diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index ac0c66fe9..5150fd21d 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -94,8 +94,9 @@ pub async fn sum(mut rx: Consumer, guard: Guard) -> u64 { /// One value read through the captures only an async block makes: a borrow, which /// dropping the block must not drop; a copy, which a later change to the original must -/// not reach; a move on one path only; and a move the block only borrows, which drops -/// when the block returns or is cancelled. +/// not reach; a mutable borrow the block replaces whole, which the caller must see; a +/// move on one path only; and a move the block only borrows, which drops when the block +/// returns or is cancelled. Between them, a value of two types that hold each other. pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { let first = Guard::new(guard.id + 200, guard.log.clone()); let second = Guard::new(guard.id + 300, guard.log.clone()); @@ -105,6 +106,20 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { let seen = async move { read(tally) }; tally.n += 1000; guard.note(&format!("tally {} then {}", tally.n, seen.await)); + let mut mark = Mark { n: 1 }; + let replaced = async { + mark = Mark { n: 2 }; + mark.n + } + .await; + guard.note(&format!("mark {replaced} {}", mark.n)); + let cycle = Outer { + inner: None, + guard: Guard::new(guard.id + 800, guard.log.clone()), + }; + let _nested = Inner { + outer: Some(Box::new(cycle)), + }; if moves { drop(async move { guard.note("moved") }); } @@ -120,6 +135,21 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { read.await } +struct Mark { + n: u32, +} + +/// Drops through `guard`, and `Inner` through it: deciding `Outer` first must not leave +/// `Inner` decided as dropping nothing. +struct Outer { + inner: Option>, + guard: Guard, +} + +struct Inner { + outer: Option>, +} + /// A `Copy` value an `async move` block takes its own copy of. #[derive(Clone, Copy)] struct Tally { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 366fc2515..ce4f44d9d 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -45,6 +45,7 @@ pub fn function<'a, 'tcx>( visited: FxHashSet::default(), scopes: Vec::new(), moved: FxHashSet::default(), + borrowed: FxHashSet::default(), yields: 0, }; let span = tcx.def_span(def_id); @@ -180,6 +181,9 @@ pub struct Body<'b, 'a, 'tcx> { pub(super) scopes: Vec>>, /// The variables a move left `undefined`, which are declared `let` for it. pub(super) moved: FxHashSet, + /// The variables a generator lowered so far borrows mutably: each is a parameter + /// holding the caller's object, so replacing it whole must change that object. + borrowed: FxHashSet, /// How many `yield`s are lowered so far, so an operand can tell whether it awaits. yields: usize, } @@ -1696,11 +1700,14 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.push(out, StmtKind::Expr(dropped), span); } } - // `*r = v` through a reference replaces what it points to. - if let ExprKind::Deref { arg } = self.thir[self.strip(lhs)].kind - && matches!(self.ty_of(arg).kind(), ty::Ref(..)) - && self.is_place(arg) - { + // `*r = v` through a reference replaces what it points to, as does replacing a + // variable a generator borrows mutably. + let through_ref = match self.thir[self.strip(lhs)].kind { + ExprKind::Deref { arg } => matches!(self.ty_of(arg).kind(), ty::Ref(..)) && self.is_place(arg), + ExprKind::UpvarRef { var_hir_id, .. } => self.borrowed.contains(&var_hir_id.0), + _ => false, + }; + if through_ref { let pointee = self.ty_of(lhs); // Every clone of an `Arc` or waker is one JS object, and a future keeps its state // private: copying fields in would change the other handles, or nothing. @@ -2525,13 +2532,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { // Its generator takes the value: a change through the borrow would change a copy. if let ty::UpvarCapture::ByRef(kind) = capture.info.capture_kind && kind != ty::BorrowKind::Immutable - && self.t.object_kind(ty).is_none() { - self.t.err( - capture.get_path_span(tcx), - format!("an async body that borrows `{ty}` mutably, which is no object it can change in place"), - ); - continue; + if self.t.object_kind(ty).is_none() { + self.t.err( + capture.get_path_span(tcx), + format!("an async body that borrows `{ty}` mutably, which is no object it can change in place"), + ); + continue; + } + self.borrowed.insert(var); } let Some(Local::Name { name, .. }) = self.locals.get(&var).cloned() else { self.t diff --git a/ts/src/lower/drop.rs b/ts/src/lower/drop.rs index b599f8716..d7050dd8a 100644 --- a/ts/src/lower/drop.rs +++ b/ts/src/lower/drop.rs @@ -29,7 +29,11 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { return drops; } // A type that holds itself drops through another field if at all. - self.drops.insert(ty, false); + if !self.drops_open.insert(ty) { + self.drops_cycle = true; + return false; + } + let outer_cycle = std::mem::replace(&mut self.drops_cycle, false); let tcx = self.tcx; let drops = match ty.kind() { ty::Adt(adt, args) => match Std::of(tcx, adt.did()) { @@ -47,7 +51,15 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { ty::Coroutine(..) | ty::Param(_) => true, _ => false, }; - self.drops.insert(ty, drops); + self.drops_open.remove(&ty); + // A `false` that read a type still being decided holds only once the first of + // them is decided: if it drops, so does every type it reached that reaches it. + let cycle = std::mem::replace(&mut self.drops_cycle, outer_cycle); + if drops || !cycle || self.drops_open.is_empty() { + self.drops.insert(ty, drops); + } else { + self.drops_cycle = true; + } drops } diff --git a/ts/src/lower/mod.rs b/ts/src/lower/mod.rs index adba09391..13fef294c 100644 --- a/ts/src/lower/mod.rs +++ b/ts/src/lower/mod.rs @@ -163,6 +163,9 @@ pub struct Translator<'a, 'tcx> { refusals: Option>, /// Whether each type's drop does something JS can see, as [`Self::drops`] found. drops: rustc_data_structures::fx::FxHashMap, bool>, + /// The types [`Self::drops`] is still deciding, and whether the query open now read one. + drops_open: rustc_data_structures::fx::FxHashSet>, + drops_cycle: bool, /// The classes given drop glue. glued: rustc_data_structures::fx::FxHashSet, } @@ -239,6 +242,8 @@ impl<'a, 'tcx> Translator<'a, 'tcx> { env: TypingEnv::fully_monomorphized(), refusals, drops: Default::default(), + drops_open: Default::default(), + drops_cycle: false, glued: Default::default(), }) } From a013edf4d339087230a8b1ca132835465714c201 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 06:01:31 -0700 Subject: [PATCH 20/30] fix(ts): an if let takes a temporary whole from every variant, and refuse Poll outputs `if let None = Some(guard)` passed the whole-move check, since `None` has no fields, and the failed test leaked the guard. An `if let` or let chain now asks `leaves_drop`, which also counts the other variants and is exact where `takes_all` was conservative (moq-net: 6 fewer refusals). An async body whose output can already be `rt.Pending` is refused, as `Poll>` is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 2 +- ts/fixtures/reject/census.md | 20 ++++++++++++++++++-- ts/fixtures/reject/expected.txt | 2 ++ ts/fixtures/reject/src/lib.rs | 11 +++++++++++ ts/fixtures/reject/ts.toml | 2 ++ ts/src/census.rs | 1 + ts/src/lower/body.rs | 10 +++++++++- 7 files changed, 44 insertions(+), 4 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index e95439ff9..054b775c0 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -23,7 +23,7 @@ ranked by the census of moq-net at the pinned revision (kio's has 26 in all): `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs glue of its own, switching on the variant. - A method taking `self` by value that drops (155), which can't leave `this` undefined. -- A temporary that drops, unless a call or binding takes it whole (286): borrowed, a +- A temporary that drops, unless a call or binding takes it whole (280): borrowed, a field or index of one, a `match`, `if let`, `let`, or let chain that moves only part of it, and a guarded arm that binds one. Rust drops it at the end of its statement, or of the `match`. diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 5b8e83e9e..07a99daee 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 57 -- Function instances: 38 +- Refusals: 59 +- Function instances: 40 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -39,6 +39,8 @@ | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:136:3 | | 1 | an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:190:13 | | 1 | an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:207:2 | +| 1 | an `if let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:241:9 | +| 1 | an async body returning `_` is not supported: its `Ready` could be pending | fixtures/reject/src/lib.rs:245:54 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:113:3 | | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | @@ -70,6 +72,7 @@ The type or module each refused type or path belongs to. | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | +| 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | @@ -90,6 +93,7 @@ The type or module each refused type or path belongs to. | 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:121:10 | | 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:144:17 | +| 1 | an async body returning `_` is not supported: its `Ready` could be pending | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | @@ -311,6 +315,18 @@ The type or module each refused type or path belongs to.
+
an `if let` on a temporary that drops, which it doesn't move out of whole (1) + +- fixtures/reject/src/lib.rs:241:9: an `if let` on a temporary that drops, which it doesn't move out of whole + +
+ +
an async body returning `_` is not supported: its `Ready` could be pending (1) + +- fixtures/reject/src/lib.rs:245:54: an async body returning `std::task::Poll` is not supported: its `Ready` could be pending + +
+
an async body that borrows `_` mutably, which is no object it can change in place (1) - fixtures/reject/src/lib.rs:113:3: an async body that borrows `u8` mutably, which is no object it can change in place diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 4b6d78f60..453fb5b33 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -55,3 +55,5 @@ a `match` on a temporary that drops, which it doesn't move out of whole at fixtu replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:225:2 `Poll>>` is not supported: it would be pending two ways with one value at fixtures/reject/src/lib.rs:229:20 `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:234:19 +an `if let` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:241:9 +an async body returning `std::task::Poll` is not supported: its `Ready` could be pending at fixtures/reject/src/lib.rs:245:54 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 90dbabf28..5ce9045bc 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -234,3 +234,14 @@ pub fn nested_poll(p: std::task::Poll>>) -> bool { pub fn ready_unit(p: Option>) -> bool { matches!(p, None) } + +/// The payload of the `Some` that fails the test drops after the `if let`. +#[allow(clippy::redundant_pattern_matching, reason = "the `if let` is under test")] +pub fn unmatched() -> u8 { + if let None = Some(make()) { 1 } else { 0 } +} + +/// A future's `Ready(Pending)` would be `rt.Pending`, as its own pending is. +pub async fn pending_output() -> std::task::Poll { + std::task::Poll::Pending +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 0c9d87b41..98bdc4945 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -33,6 +33,8 @@ roots = [ "replace_shared", "nested_poll", "ready_unit", + "unmatched", + "pending_output", "missing", ] printable = ["Meters"] diff --git a/ts/src/census.rs b/ts/src/census.rs index 1755d9997..2f71f5412 100644 --- a/ts/src/census.rs +++ b/ts/src/census.rs @@ -148,6 +148,7 @@ const VERBATIM: &[&str] = &[ "Octal", "Option", "Pointer", + "Ready", "Result", "Some", "UpperExp", diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index ce4f44d9d..8a07323b9 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1001,7 +1001,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { match part { CondPart::Bool(id) => Some(self.expr(*id, pre)), CondPart::Let(expr, pat) => { - if !self.is_place(*expr) && self.t.drops(self.ty_of(*expr)) && !takes_all(pat) { + // A failed test leaves the value whole, so the pattern must take all of it + // from every variant: a `let` with no other arm to take the rest. + if !self.is_place(*expr) && self.leaves_drop(pat) { self.t.err( pat.span, "an `if let` on a temporary that drops, which it doesn't move out of whole", @@ -2491,6 +2493,12 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } _ => return self.err(span, format!("a closure of type `{closure_ty}`")), }; + if coroutine && self.t.erases_to(ret).pending { + self.t.err( + span, + format!("an async body returning `{ret}` is not supported: its `Ready` could be pending"), + ); + } // An async fn's body is this block alone, which rustc starts by moving each argument // into a local: the function gives its arguments up whole, and those locals drop // them. A block moves what it owns out of its place, as any move does, and drops it. From c4e01e7e6fcdfcc67c0c98419a3236cc7adc7fce Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 06:11:15 -0700 Subject: [PATCH 21/30] fix(ts): read through a Box without moving it, and close two more refusal gaps `boxed.id` on a `Box` that drops lowered the deref as a move, clearing the box so a second read threw and nothing dropped it; reading through an owning pointer now reads it in place (moq-net: 2 fewer refusals). A ternary `match` on a temporary that drops skipped the check a `match` makes, and replacing a `Pin>` through a reference reached every clone; both now fail with their span. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/reject/census.md | 36 ++++++++++--------- ts/fixtures/reject/expected.txt | 2 ++ ts/fixtures/reject/src/lib.rs | 15 ++++++++ ts/fixtures/reject/ts.toml | 2 ++ ts/fixtures/task/expected/model.ts | 57 +++++++++++++++++------------- ts/fixtures/task/src/model.rs | 7 ++-- ts/src/lower/body.rs | 22 ++++++++++-- 7 files changed, 96 insertions(+), 45 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 07a99daee..ffe0dd571 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 59 -- Function instances: 40 +- Refusals: 61 +- Function instances: 42 - Generic functions no instance reached, lowered over their type parameters: 2 ## By construct @@ -15,6 +15,8 @@ | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | | 2 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | +| 2 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | +| 2 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:133:3 | @@ -23,7 +25,6 @@ | 1 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:229:20 | | 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | -| 1 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | @@ -45,7 +46,6 @@ | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:135:3 | -| 1 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:130:3 | | 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:131:3 | | 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:163:2 | @@ -71,6 +71,7 @@ The type or module each refused type or path belongs to. | 1 | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | | 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | +| 1 | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | @@ -99,6 +100,7 @@ The type or module each refused type or path belongs to. | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | dropping `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | +| 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::Arc` | fixtures/reject/src/lib.rs:225:2 | | 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | | 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | @@ -171,6 +173,20 @@ The type or module each refused type or path belongs to.
+
a `match` on a temporary that drops, which it doesn't move out of whole (2) + +- fixtures/reject/src/lib.rs:217:2: a `match` on a temporary that drops, which it doesn't move out of whole +- fixtures/reject/src/lib.rs:252:16: a `match` on a temporary that drops, which it doesn't move out of whole + +
+ +
replacing the `_` behind a reference, whose JS object is shared or private (2) + +- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:261:2: replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private + +
+
`Binary` formatting, as in `{:b}`, is not supported (1) - fixtures/reject/src/lib.rs:132:3: `Binary` formatting, as in `{:b}`, is not supported @@ -219,12 +235,6 @@ The type or module each refused type or path belongs to.
-
a `match` on a temporary that drops, which it doesn't move out of whole (1) - -- fixtures/reject/src/lib.rs:217:2: a `match` on a temporary that drops, which it doesn't move out of whole - -
-
a cast from `_` (1) - fixtures/reject/src/lib.rs:11:2: a cast from `char` @@ -351,12 +361,6 @@ The type or module each refused type or path belongs to.
-
replacing the `_` behind a reference, whose JS object is shared or private (1) - -- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private - -
-
the `+` flag of a format spec is not supported (1) - fixtures/reject/src/lib.rs:130:3: the `+` flag of a format spec is not supported diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 453fb5b33..065b36a17 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -57,3 +57,5 @@ replacing the `std::sync::Arc` behind a reference, whose JS object is shared `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:234:19 an `if let` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:241:9 an async body returning `std::task::Poll` is not supported: its `Ready` could be pending at fixtures/reject/src/lib.rs:245:54 +a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:252:16 +replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:261:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 5ce9045bc..98a719851 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -245,3 +245,18 @@ pub fn unmatched() -> u8 { pub async fn pending_output() -> std::task::Poll { std::task::Poll::Pending } + +/// The temporary drops after the `match`, which nothing marks. +#[allow(clippy::match_like_matches_macro, reason = "the `match` is under test")] +pub fn tested() -> u8 { + let matched = match Some(make()) { + Some(_) => 1, + None => 0, + }; + matched + 1 +} + +/// A `Pin` is its pointer in JS: replacing the `Arc` would reach every clone. +pub fn replace_pinned(dst: &mut std::pin::Pin>, src: std::pin::Pin>) { + *dst = src; +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 98bdc4945..5ff2a6905 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -35,6 +35,8 @@ roots = [ "ready_unit", "unmatched", "pending_output", + "tested", + "replace_pinned", "missing", ] printable = ["Meters"] diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index c3f722ba2..93e549901 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -467,8 +467,8 @@ export function pick(log: Log, i: number): number { * inside a turn's scope must still skip the arms after it. Before them, a pair of * guards destructured in part: the one left in the array drops with it, after the other; * a pinned box of one, which drops it; `ref` bindings, which borrow a variable and keep a - * temporary to the end of the block; and a `_` binding of an element, which evaluates its - * index and moves nothing. + * temporary to the end of the block; a `_` binding of an element, which evaluates its + * index and moves nothing; and a boxed guard read twice, which a read leaves boxed. */ export function turns(log: Log, count: number): void { const pair = [Guard.new(rt.u32.add(count, 10), log.clone()), Guard.new(rt.u32.add(count, 20), log.clone())]; @@ -496,36 +496,43 @@ export function turns(log: Log, count: number): void { } const scoped = value; log.note(rt.fmt.format(["after ", (f: rt.Formatter) => rt.u32.display(scoped, f)])); - const spares = [Guard.new(rt.u32.add(count, 70), log.clone()), Guard.new(rt.u32.add(count, 80), log.clone())]; + const boxed = Guard.new(rt.u32.add(count, 100), log.clone()); try { - const index = pick(log, rt.usize.rem(count, 2)); - spares[rt.idx(spares, index)]; - arms: { - if (count === 0) { - log.note("no turns"); - break arms; - } - const n = count; - if (n < 4) { - let left: number = n; - while (true) { - const turn = Guard.new(left, log.clone()); - try { - if (left === 1) { - break; + const once = boxed.id; + log.note(rt.fmt.format(["boxed ", (f: rt.Formatter) => rt.u32.display(once, f), " ", (f: rt.Formatter) => rt.u32.display(boxed.id, f)])); + const spares = [Guard.new(rt.u32.add(count, 70), log.clone()), Guard.new(rt.u32.add(count, 80), log.clone())]; + try { + const index = pick(log, rt.usize.rem(count, 2)); + spares[rt.idx(spares, index)]; + arms: { + if (count === 0) { + log.note("no turns"); + break arms; + } + const n = count; + if (n < 4) { + let left: number = n; + while (true) { + const turn = Guard.new(left, log.clone()); + try { + if (left === 1) { + break; + } + turn.note("turn"); + left = rt.u32.sub(left, 1); + } finally { + rt.drop(turn); } - turn.note("turn"); - left = rt.u32.sub(left, 1); - } finally { - rt.drop(turn); } + break arms; } - break arms; + log.note("many turns"); } - log.note("many turns"); + } finally { + rt.dropAll(spares); } } finally { - rt.dropAll(spares); + rt.drop(boxed); } } finally { rt.drop(extended); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 5150fd21d..82eaae1e9 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -170,8 +170,8 @@ fn pick(log: &Log, i: usize) -> usize { /// inside a turn's scope must still skip the arms after it. Before them, a pair of /// guards destructured in part: the one left in the array drops with it, after the other; /// a pinned box of one, which drops it; `ref` bindings, which borrow a variable and keep a -/// temporary to the end of the block; and a `_` binding of an element, which evaluates its -/// index and moves nothing. +/// temporary to the end of the block; a `_` binding of an element, which evaluates its +/// index and moves nothing; and a boxed guard read twice, which a read leaves boxed. #[expect(clippy::toplevel_ref_arg, reason = "the `ref` bindings are under test")] fn turns(log: &Log, count: u32) { let pair = [Guard::new(count + 10, log.clone()), Guard::new(count + 20, log.clone())]; @@ -189,6 +189,9 @@ fn turns(log: &Log, count: u32) { inner.id }; log.note(format!("after {scoped}")); + let boxed = Box::new(Guard::new(count + 100, log.clone())); + let once = boxed.id; + log.note(format!("boxed {once} {}", boxed.id)); let spares = [Guard::new(count + 70, log.clone()), Guard::new(count + 80, log.clone())]; let _ = spares[pick(log, count as usize % 2)]; match count { diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 8a07323b9..0121d1317 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1712,8 +1712,17 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { if through_ref { let pointee = self.ty_of(lhs); // Every clone of an `Arc` or waker is one JS object, and a future keeps its state - // private: copying fields in would change the other handles, or nothing. - let shared = match pointee.kind() { + // private: copying fields in would change the other handles, or nothing. A `Pin` + // or `Box` is its pointee in JS. + let mut erased = pointee; + while let ty::Adt(adt, args) = erased.kind() + && matches!( + library::Std::of(self.t.tcx, adt.did()), + Some(library::Std::Pin | library::Std::Box) + ) { + erased = args.type_at(0); + } + let shared = match erased.kind() { ty::Adt(adt, _) => matches!( library::Std::of(self.t.tcx, adt.did()), Some(library::Std::Arc | library::Std::Waker | library::Std::Context) @@ -2217,6 +2226,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { unreachable!() }; let thir: &'a Thir<'tcx> = self.thir; + // Its arms bind nothing, so a temporary that drops is left for nothing to drop. + if self.temporary_drops(*scrutinee) { + return self.err( + self.span(id), + "a `match` on a temporary that drops, which it doesn't move out of whole", + ); + } let reads: usize = arms .iter() .take(arms.len().saturating_sub(1)) @@ -2255,6 +2271,8 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } ExprKind::VarRef { id: var } => self.local(var.0, span), ExprKind::UpvarRef { var_hir_id, .. } => self.local(var_hir_id.0, span), + // Reading through a `Box` that drops reads its pointee: the box stays where it is. + ExprKind::Deref { arg } if self.is_place(*arg) && self.t.drops(self.ty_of(*arg)) => self.place(*arg, out), ExprKind::Deref { arg } => self.expr(*arg, out), ExprKind::Field { lhs, From b6fe796c45b3e3ccd8dffe2f404f7cb8c02f37d7 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:02:17 -0700 Subject: [PATCH 22/30] test(ts): regenerate snapshots after merging main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/reject/census.md | 101 ++++++++++++++++++------- ts/fixtures/reject/expected.txt | 15 +++- ts/fixtures/task/expected/kio.ts | 102 ++++++++++++------------- ts/fixtures/task/expected/log.ts | 8 +- ts/fixtures/task/expected/model.ts | 116 ++++++++++++++--------------- 5 files changed, 198 insertions(+), 144 deletions(-) diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index ffe0dd571..fd8dd387a 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,21 +1,25 @@ # Census of `reject-fixture` -- Refusals: 61 -- Function instances: 42 -- Generic functions no instance reached, lowered over their type parameters: 2 +- Refusals: 70 +- Function instances: 60 +- Generic functions no instance reached, lowered over their type parameters: 3 ## By construct | Count | Construct | First | | ---: | --- | --- | | 6 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | -| 5 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | +| 4 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | +| 3 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | +| 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:361:4 | | 3 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | -| 2 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | +| 2 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 2 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | +| 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:299:1 | +| 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:279:2 | | 2 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | @@ -23,8 +27,8 @@ | 1 | `Pointer` formatting, as in `{:p}`, is not supported | fixtures/reject/src/lib.rs:137:3 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:229:20 | -| 1 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | +| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:312:51 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | @@ -60,20 +64,26 @@ The type or module each refused type or path belongs to. | 6 | `f64` | fixtures/reject/src/lib.rs:6:1 | | 4 | `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 3 | `Meters` | fixtures/reject/src/lib.rs:168:17 | +| 3 | `Option` | fixtures/reject/src/lib.rs:31:15 | | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | -| 2 | `Option` | fixtures/reject/src/lib.rs:31:15 | +| 2 | `Iterator` | fixtures/reject/src/lib.rs:279:2 | +| 2 | `Noisy` | fixtures/reject/src/lib.rs:361:16 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | -| 2 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | | 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | +| 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:299:1 | +| 1 | `FusedIterator` | fixtures/reject/src/lib.rs:353:1 | | 1 | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | -| 1 | `std::iter::Filter` | fixtures/reject/src/lib.rs:40:31 | +| 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:312:51 | +| 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:320:8 | | 1 | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | -| 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:40:11 | +| 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:266:11 | +| 1 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | +| 1 | `std::vec::Vec` | fixtures/reject/src/lib.rs:361:4 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | @@ -81,31 +91,37 @@ The type or module each refused type or path belongs to. | Count | Construct | Type or path | First | | ---: | --- | --- | --- | +| 3 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | | 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | -| 2 | `_` is not supported: its `None` and `Some` would both be `undefined` | `Option` | fixtures/reject/src/lib.rs:31:15 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | +| 2 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:361:16 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | | 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | +| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:312:51 | | 1 | a cast from `_` | `char` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:121:10 | | 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:144:17 | | 1 | an async body returning `_` is not supported: its `Ready` could be pending | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:113:3 | +| 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:299:1 | +| 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:353:1 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:361:4 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | dropping `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | +| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:279:2 | +| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:333:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::Arc` | fixtures/reject/src/lib.rs:225:2 | -| 1 | unsupported call to `_` | `::count` | fixtures/reject/src/lib.rs:40:31 | -| 1 | unsupported call to `_` | `::filter` | fixtures/reject/src/lib.rs:40:11 | +| 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:266:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:144:10 | -| 1 | unsupported call to `_` | `std::slice::iter` | fixtures/reject/src/lib.rs:40:4 | +| 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:320:8 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:36:4 | | 1 | unsupported literal of type `_` | `f64` | fixtures/reject/src/lib.rs:7:6 | | 1 | unsupported type `_` | `char` | fixtures/reject/src/lib.rs:10:18 | @@ -125,13 +141,20 @@ The type or module each refused type or path belongs to.
-
unsupported call to `_` (5) +
unsupported call to `_` (4) - fixtures/reject/src/lib.rs:36:4: unsupported call to `std::slice::::sort` -- fixtures/reject/src/lib.rs:40:4: unsupported call to `core::slice::::iter` -- fixtures/reject/src/lib.rs:40:11: unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` -- fixtures/reject/src/lib.rs:40:31: unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` - fixtures/reject/src/lib.rs:144:10: unsupported call to `::write_fmt` +- fixtures/reject/src/lib.rs:266:11: unsupported call to ` as std::iter::Iterator>::cycle` +- fixtures/reject/src/lib.rs:320:8: unsupported call to `std::ops::Range::::contains::` + +
+ +
`_` is not supported: its `None` and `Some` would both be `undefined` (3) + +- fixtures/reject/src/lib.rs:31:15: `Option>` is not supported: its `None` and `Some` would both be `undefined` +- fixtures/reject/src/lib.rs:40:42: `Option>` is not supported: its `None` and `Some` would both be `undefined` +- fixtures/reject/src/lib.rs:234:19: `Option>` is not supported: its `None` and `Some` would both be `undefined`
@@ -143,6 +166,14 @@ The type or module each refused type or path belongs to.
+
an iterator that owns `_`, which drops, which is not supported yet (3) + +- fixtures/reject/src/lib.rs:361:4: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:361:16: an iterator that owns `Noisy`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:366:20: an iterator that owns `Noisy`, which drops, which is not supported yet + +
+
dropping `_`, which is not supported yet (3) - fixtures/reject/src/lib.rs:66:31: dropping `{closure@fixtures/reject/src/lib.rs:68:10: 68:17}`, which is not supported yet @@ -159,17 +190,17 @@ The type or module each refused type or path belongs to.
-
`_` is not supported: its `None` and `Some` would both be `undefined` (2) +
`_`: a JS value of `_` is a copy, so a reference can't change it (2) -- fixtures/reject/src/lib.rs:31:15: `Option>` is not supported: its `None` and `Some` would both be `undefined` -- fixtures/reject/src/lib.rs:234:19: `Option>` is not supported: its `None` and `Some` would both be `undefined` +- fixtures/reject/src/lib.rs:19:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it +- fixtures/reject/src/lib.rs:142:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it
-
`_`: a JS value of `_` is a copy, so a reference can't change it (2) +
a `for` loop over values that drop, which is not supported yet (2) -- fixtures/reject/src/lib.rs:19:13: `&mut u32`: a JS value of `u32` is a copy, so a reference can't change it -- fixtures/reject/src/lib.rs:142:16: `&mut std::string::String`: a JS value of `std::string::String` is a copy, so a reference can't change it +- fixtures/reject/src/lib.rs:76:6: a `for` loop over values that drop, which is not supported yet +- fixtures/reject/src/lib.rs:382:6: a `for` loop over values that drop, which is not supported yet
@@ -180,6 +211,20 @@ The type or module each refused type or path belongs to.
+
an iterator of the crate implementing `_`, which is not supported yet (2) + +- fixtures/reject/src/lib.rs:299:1: an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet +- fixtures/reject/src/lib.rs:353:1: an iterator of the crate implementing `FusedIterator`, which is not supported yet + +
+ +
overriding `_`, which std's adaptors call in place of `next` or beside it (2) + +- fixtures/reject/src/lib.rs:279:2: overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it +- fixtures/reject/src/lib.rs:333:2: overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it + +
+
replacing the `_` behind a reference, whose JS object is shared or private (2) - fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private @@ -223,15 +268,15 @@ The type or module each refused type or path belongs to.
-
a `for` loop over values that drop, which is not supported yet (1) +
a `let` on a temporary that drops, which it doesn't move out of whole (1) -- fixtures/reject/src/lib.rs:76:6: a `for` loop over values that drop, which is not supported yet +- fixtures/reject/src/lib.rs:200:2: a `let` on a temporary that drops, which it doesn't move out of whole
-
a `let` on a temporary that drops, which it doesn't move out of whole (1) +
a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` (1) -- fixtures/reject/src/lib.rs:200:2: a `let` on a temporary that drops, which it doesn't move out of whole +- fixtures/reject/src/lib.rs:312:51: a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:312:15: 312:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold`
diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 065b36a17..6230b0b2c 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -13,9 +13,7 @@ a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change at fixtu a `&mut u32` binding: a JS value of `u32` is a copy, so it can't change at fixtures/reject/src/lib.rs:25:6 `Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:31:15 unsupported call to `std::slice::::sort` at fixtures/reject/src/lib.rs:36:4 -unsupported call to `core::slice::::iter` at fixtures/reject/src/lib.rs:40:4 -unsupported call to ` as std::iter::Iterator>::filter::<{closure@fixtures/reject/src/lib.rs:40:18: 40:21}>` at fixtures/reject/src/lib.rs:40:11 -unsupported call to `, {closure@fixtures/reject/src/lib.rs:40:18: 40:21}> as std::iter::Iterator>::count` at fixtures/reject/src/lib.rs:40:31 +`Option>` is not supported: its `None` and `Some` would both be `undefined` at fixtures/reject/src/lib.rs:40:42 a method that takes `self` by value that drops, which is not supported yet at fixtures/reject/src/lib.rs:51:20 a field of a temporary that drops: bind it to a variable first at fixtures/reject/src/lib.rs:62:2 a closure that captures a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:68:23 @@ -59,3 +57,14 @@ an `if let` on a temporary that drops, which it doesn't move out of whole at fix an async body returning `std::task::Poll` is not supported: its `Ready` could be pending at fixtures/reject/src/lib.rs:245:54 a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:252:16 replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:261:2 +unsupported call to ` as std::iter::Iterator>::cycle` at fixtures/reject/src/lib.rs:266:11 +a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:312:15: 312:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` at fixtures/reject/src/lib.rs:312:51 +unsupported call to `std::ops::Range::::contains::` at fixtures/reject/src/lib.rs:320:8 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:361:16 +an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:361:4 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:366:20 +a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:382:6 +overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:279:2 +an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:299:1 +overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:333:2 +an iterator of the crate implementing `FusedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:353:1 diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts index 9733183ca..783e96b68 100644 --- a/ts/fixtures/task/expected/kio.ts +++ b/ts/fixtures/task/expected/kio.ts @@ -17,11 +17,6 @@ export class Waiter { rt.drop(this.shared); } - /** Register with `list`, a no-op while the list still holds this waiter. */ - register(list: WaiterList): void { - list.register(this); - } - static new(waker: rt.Waker): Waiter { try { let shared = new rt.Arc(waker.clone()); @@ -39,6 +34,11 @@ export class Waiter { rt.drop(waker); } } + + /** Register with `list`, a no-op while the list still holds this waiter. */ + register(list: WaiterList): void { + list.register(this); + } } /** Wakers waiting for one event, held weakly. */ @@ -52,32 +52,6 @@ export class WaiterList { this.cursor = fields.cursor; } - /** Drain every entry into a new list, leaving this one empty. */ - take(): WaiterList { - this.cursor = 0; - const taken = this.entries; - this.entries = []; - return new WaiterList({ entries: taken, cursor: 0 }); - } - - /** Wake every live waiter, draining the list. */ - wake(): void { - this.cursor = 0; - const taken = this.entries; - this.entries = []; - for (const entry of taken) { - const upgrade = entry.upgrade(); - if (upgrade !== undefined) { - const waker = upgrade; - try { - waker.value.wakeByRef(); - } finally { - rt.drop(waker); - } - } - } - } - static new(): WaiterList { return new WaiterList({ entries: [], cursor: 0 }); } @@ -113,6 +87,32 @@ export class WaiterList { } this.entries.push(weak); } + + /** Drain every entry into a new list, leaving this one empty. */ + take(): WaiterList { + this.cursor = 0; + const taken = this.entries; + this.entries = []; + return new WaiterList({ entries: taken, cursor: 0 }); + } + + /** Wake every live waiter, draining the list. */ + wake(): void { + this.cursor = 0; + const taken = this.entries; + this.entries = []; + for (const entry of taken) { + const upgrade = entry.upgrade(); + if (upgrade !== undefined) { + const waker = upgrade; + try { + waker.value.wakeByRef(); + } finally { + rt.drop(waker); + } + } + } + } } /** Holds a parked waiter between polls, so its registrations outlive the poll. */ @@ -206,26 +206,11 @@ export class Producer { rt.drop(this.state); } - drop(): void { - let state: rt.Mutex = this.state.value; - state.value.producers = rt.usize.sub(state.value.producers, 1); - if (state.value.producers > 0) { - return; - } - state.value.closed = true; - let waiters: WaiterList = state.value.waiters.take(); - waiters.wake(); - } - static new(): Producer { const state = new State({ queue: [], closed: false, producers: 1, waiters: WaiterList.new() }); return new Producer({ state: new rt.Arc(new rt.Mutex(state)) }); } - consume(): Consumer { - return new Consumer({ state: this.state.clone(), next: 0 }); - } - /** Queue `value` and wake every consumer, after releasing the lock. */ send(value: bigint): void { let state: rt.Mutex = this.state.value; @@ -234,10 +219,25 @@ export class Producer { waiters.wake(); } + consume(): Consumer { + return new Consumer({ state: this.state.clone(), next: 0 }); + } + clone(): Producer { this.state.value.value.producers = rt.usize.add(this.state.value.value.producers, 1); return new Producer({ state: this.state.clone() }); } + + drop(): void { + let state: rt.Mutex = this.state.value; + state.value.producers = rt.usize.sub(state.value.producers, 1); + if (state.value.producers > 0) { + return; + } + state.value.closed = true; + let waiters: WaiterList = state.value.waiters.take(); + waiters.wake(); + } } /** The receiving side of a channel: every value sent, in order. */ @@ -258,11 +258,6 @@ export class Consumer { return new Consumer({ state: this.state.clone(), next: this.next }); } - /** kio's one-line wrapper over a `poll_*` method. */ - recv(): rt.Future { - return rt.future(recvBody, undefined, this); - } - /** The next value, or `None` once the channel closed and every value was read. */ pollRecv(waiter: Waiter): rt.Poll { let state: rt.Mutex = this.state.value; @@ -277,6 +272,11 @@ export class Consumer { waiter.register(state.value.waiters); return rt.Pending; } + + /** kio's one-line wrapper over a `poll_*` method. */ + recv(): rt.Future { + return rt.future(recvBody, undefined, this); + } } export function* recvBody(_taskContext: rt.Context, self: Consumer): Generator { diff --git a/ts/fixtures/task/expected/log.ts b/ts/fixtures/task/expected/log.ts index 526cf98b5..2bd381560 100644 --- a/ts/fixtures/task/expected/log.ts +++ b/ts/fixtures/task/expected/log.ts @@ -14,6 +14,10 @@ export class Log { rt.drop(this._0); } + clone(): Log { + return new Log(this._0.clone()); + } + static new(): Log { return new Log(new rt.Arc(new rt.Mutex([]))); } @@ -33,10 +37,6 @@ export class Log { } return out; } - - clone(): Log { - return new Log(this._0.clone()); - } } //# sourceMappingURL=log.ts.map diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 93e549901..444ff8dae 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -119,10 +119,6 @@ export class Guard { rt.drop(this.log); } - drop(): void { - this.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(this.id, f), " drop"])); - } - static new(id: number, log: Log): Guard { try { const arg = id; @@ -138,6 +134,10 @@ export class Guard { note(event: string): void { this.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(this.id, f), " ", (f: rt.Formatter) => f.pad(event)])); } + + drop(): void { + this.log.note(rt.fmt.format(["g", (f: rt.Formatter) => rt.u32.display(this.id, f), " drop"])); + } } /** @@ -651,9 +651,13 @@ export function* level1Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level10(rx: Consumer): rt.Future { + return rt.future(level10Body, undefined, rx); +} + +export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level2(rx2); + let __awaitee: rt.Future = level9(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -668,13 +672,13 @@ export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level3Body, undefined, rx); +export function level11(rx: Consumer): rt.Future { + return rt.future(level11Body, undefined, rx); } -export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level14(rx2); + let __awaitee: rt.Future = level10(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -689,13 +693,13 @@ export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level15(rx: Consumer): rt.Future { - return rt.future(level15Body, undefined, rx); +export function level12(rx: Consumer): rt.Future { + return rt.future(level12Body, undefined, rx); } -export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level1(rx2); + let __awaitee: rt.Future = level11(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -710,13 +714,13 @@ export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level2Body, undefined, rx); +export function level13(rx: Consumer): rt.Future { + return rt.future(level13Body, undefined, rx); } -export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level13(rx2); + let __awaitee: rt.Future = level12(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -735,9 +739,9 @@ export function level14(rx: Consumer): rt.Future { return rt.future(level14Body, undefined, rx); } -export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level12(rx2); + let __awaitee: rt.Future = level13(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -752,13 +756,13 @@ export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level13(rx: Consumer): rt.Future { - return rt.future(level13Body, undefined, rx); +export function level15(rx: Consumer): rt.Future { + return rt.future(level15Body, undefined, rx); } -export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level11(rx2); + let __awaitee: rt.Future = level14(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -773,13 +777,13 @@ export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level12(rx: Consumer): rt.Future { - return rt.future(level12Body, undefined, rx); +export function level2(rx: Consumer): rt.Future { + return rt.future(level2Body, undefined, rx); } -export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level10(rx2); + let __awaitee: rt.Future = level1(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -794,13 +798,13 @@ export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level11(rx: Consumer): rt.Future { - return rt.future(level11Body, undefined, rx); +export function level3(rx: Consumer): rt.Future { + return rt.future(level3Body, undefined, rx); } -export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level9(rx2); + let __awaitee: rt.Future = level2(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -815,13 +819,13 @@ export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level10(rx: Consumer): rt.Future { - return rt.future(level10Body, undefined, rx); +export function level4(rx: Consumer): rt.Future { + return rt.future(level4Body, undefined, rx); } -export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level8(rx2); + let __awaitee: rt.Future = level3(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -836,13 +840,13 @@ export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level9Body, undefined, rx); +export function level5(rx: Consumer): rt.Future { + return rt.future(level5Body, undefined, rx); } -export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level7(rx2); + let __awaitee: rt.Future = level4(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -857,13 +861,13 @@ export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level8Body, undefined, rx); +export function level6(rx: Consumer): rt.Future { + return rt.future(level6Body, undefined, rx); } -export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level6(rx2); + let __awaitee: rt.Future = level5(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -882,9 +886,9 @@ export function level7(rx: Consumer): rt.Future { return rt.future(level7Body, undefined, rx); } -export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level5(rx2); + let __awaitee: rt.Future = level6(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -899,13 +903,13 @@ export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level6Body, undefined, rx); +export function level8(rx: Consumer): rt.Future { + return rt.future(level8Body, undefined, rx); } -export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level4(rx2); + let __awaitee: rt.Future = level7(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -920,13 +924,13 @@ export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level5Body, undefined, rx); +export function level9(rx: Consumer): rt.Future { + return rt.future(level9Body, undefined, rx); } -export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level3(rx2); + let __awaitee: rt.Future = level8(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -941,8 +945,4 @@ export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { - return rt.future(level4Body, undefined, rx); -} - //# sourceMappingURL=model.ts.map From d02598cd94e90e4611d25b0fa7ee72448a986c55 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:19:42 -0700 Subject: [PATCH 23/30] chore(quest): count iterators that own a value that drops in the Drop quest Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 054b775c0..1f064542c 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -17,7 +17,7 @@ each field); a variable drops in a `finally` at the end of its scope; a move lea fixture's trace test proves it on kio's waiters, wakers, and channels. What still fails translation, each with its span (the reject fixture has one of each), -ranked by the census of moq-net at the pinned revision (kio's has 26 in all): +ranked by the census of moq-net at the pinned revision (kio's has 27 in all): - Dropping a value whose drop no `[Symbol.dispose]` carries (657): a `Result`, an `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs @@ -29,6 +29,9 @@ ranked by the census of moq-net at the pinned revision (kio's has 26 in all): of the `match`. - A `for` loop over values that drop (60): each at the end of its iteration, and the rest on a `break`. +- An iterator that owns a value that drops (55): a `Vec` of one moved into it, or an + adaptor over items that drop. An `rt.Iter` drops nothing it skips, consumes, or still + holds when it is dropped. - Struct update syntax from a value that drops (16), a closure capturing one (13), a generic type that implements `Drop` (11), and a parameter that drops bound by a pattern. From 56d31c91080b9dbe1a996dc0762cd8964f31dfdd Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:24:55 -0700 Subject: [PATCH 24/30] fix(ts): drive the task fixture's u64s through rt.u64, after #26 A u64 is now a number while safe, or limbs, so the hand-written executor and the bench's translated routes make each value with `rt.u64.of` and read the sum with `rt.u64.toBeBytes`, rather than as a bigint. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/bench/main.ts | 2 +- ts/bench/task.ts | 29 +++++++++++++++-------------- ts/tests/fixtures.rs | 2 +- ts/tests/task.ts | 30 +++++++++++++++++------------- 4 files changed, 34 insertions(+), 29 deletions(-) diff --git a/ts/bench/main.ts b/ts/bench/main.ts index 1f290c43a..0a5aca525 100644 --- a/ts/bench/main.ts +++ b/ts/bench/main.ts @@ -88,7 +88,7 @@ async function taskEntry(dir: string): Promise { import { Channel, drain } from "./model.ts"; import { polled, spawned } from ${JSON.stringify(join(import.meta.dir, "task.ts"))}; -const fixture = { Pending: rt.Pending, spawn: rt.spawn, Channel, drain }; +const fixture = { Pending: rt.Pending, spawn: rt.spawn, u64: rt.u64, Channel, drain }; export const run = polled(fixture); export const spawn = spawned(fixture); `, diff --git a/ts/bench/task.ts b/ts/bench/task.ts index cc34df94b..62b3bd8a5 100644 --- a/ts/bench/task.ts +++ b/ts/bench/task.ts @@ -20,17 +20,18 @@ interface Future extends Disposable { poll(cx: Waker): T | symbol; } -/** What a route drives: the translation's channel and task, and its runtime. */ -export interface Fixture { +/** What a route drives: the translation's channel and task, and its runtime, whose `u64` values are `V`. */ +export interface Fixture { Pending: symbol; spawn(future: Future): Promise; - Channel: { open(): Channel }; - drain(rx: Disposable, depth: number): Future; + u64: { of(value: number): V; toBeBytes(a: V): Uint8Array }; + Channel: { open(): Channel }; + drain(rx: Disposable, depth: number): Future; } -interface Channel extends Disposable { +interface Channel extends Disposable { consumer(): Disposable; - send(value: bigint): boolean; + send(value: V): boolean; } function parse(input: Uint8Array): [depth: number, count: number] { @@ -67,35 +68,35 @@ class Woken implements Waker { } /** The translation, polled right away whenever it is woken, as `bench.rs` polls it. */ -export function polled(f: Fixture): (input: Uint8Array) => Uint8Array { +export function polled(f: Fixture): (input: Uint8Array) => Uint8Array { return (input) => { const [depth, count] = parse(input); const channel = f.Channel.open(); const task = f.drain(channel.consumer(), depth); const waker = new Woken(); - const run = (): bigint | undefined => { + const run = (): V | undefined => { while (waker.woken) { waker.woken = false; const out = task.poll(waker); - if (out !== f.Pending) return out as bigint; + if (out !== f.Pending) return out as V; } return undefined; }; run(); for (let value = 0; value < count; value++) { - channel.send(BigInt(value)); + channel.send(f.u64.of(value)); run(); } channel[Symbol.dispose](); const total = run(); task[Symbol.dispose](); if (total === undefined) throw new Error("the task did not finish once its channel closed"); - return output(total); + return f.u64.toBeBytes(total); }; } /** The translation on the runtime's executor, which polls woken tasks from a microtask. */ -export function spawned(f: Fixture): (input: Uint8Array) => Promise { +export function spawned(f: Fixture): (input: Uint8Array) => Promise { return async (input) => { const [depth, count] = parse(input); const channel = f.Channel.open(); @@ -103,11 +104,11 @@ export function spawned(f: Fixture): (input: Uint8Array) => Promise for (let value = 0; value < count; value++) { // The task's poll is queued first, so it parks before the next send. await undefined; - channel.send(BigInt(value)); + channel.send(f.u64.of(value)); } await undefined; channel[Symbol.dispose](); - return output(await done); + return f.u64.toBeBytes(await done); }; } diff --git a/ts/tests/fixtures.rs b/ts/tests/fixtures.rs index 0a27deb72..b70252986 100644 --- a/ts/tests/fixtures.rs +++ b/ts/tests/fixtures.rs @@ -279,7 +279,7 @@ import {{ Channel, Guard, blocks, drain, sum }} from "./model.ts"; import {{ harness }} from {harness:?}; export {{ cases }} from {harness:?}; -export const run = harness({{ Pending: rt.Pending, Log, Channel, Guard, sum, drain, blocks }}); +export const run = harness({{ Pending: rt.Pending, u64: rt.u64, Log, Channel, Guard, sum, drain, blocks }}); "# ); std::fs::write(out.join("caller.ts"), text).unwrap(); diff --git a/ts/tests/task.ts b/ts/tests/task.ts index 017bda089..e335cfe57 100644 --- a/ts/tests/task.ts +++ b/ts/tests/task.ts @@ -24,22 +24,26 @@ interface Log { type Consumer = Disposable; type Guard = Disposable; -interface Channel extends Disposable { +interface Channel extends Disposable { consumer(): Consumer; - send(value: bigint): boolean; + send(value: V): boolean; close(): boolean; cloneProducer(): boolean; } -/** What the harness drives: the translation's roots, and the runtime's `Pending`. */ -export interface Fixture { +/** + * What the harness drives: the translation's roots, and the runtime's `Pending` and + * `u64`, whose values are `V`. + */ +export interface Fixture { Pending: symbol; + u64: { of(value: number): V }; Log: { "new"(): Log }; - Channel: { open(): Channel }; + Channel: { open(): Channel }; Guard: { "new"(id: number, log: Log): Guard }; - sum(rx: Consumer, guard: Guard): Future; - drain(rx: Consumer, depth: number): Future; - blocks(rx: Consumer, guard: Guard, moves: boolean): Future; + sum(rx: Consumer, guard: Guard): Future; + drain(rx: Consumer, depth: number): Future; + blocks(rx: Consumer, guard: Guard, moves: boolean): Future; } /** What every waker of one task points at. */ @@ -93,7 +97,7 @@ class TaskWaker implements Waker { } interface Task { - future: Future; + future: Future; waker: Waker; wake: Wake; done: boolean; @@ -112,7 +116,7 @@ class Executor { this.pending = pending; } - spawn(future: Future): void { + spawn(future: Future): void { const task = this.tasks.length; this.log.note(`t${task} spawn`); const wake = new Wake(task, this.log, this.queue); @@ -157,11 +161,11 @@ class Executor { } /** The script runner, as `harness.rs` runs it natively. */ -export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array } { +export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array } { return (input) => { const log = f.Log.new(); const exec = new Executor(log, f.Pending); - const channels: Channel[] = []; + const channels: Channel[] = []; for (let i = 0; i < input.length; i += 2) { const op = input[i]; const arg = input[i + 1] ?? 0; @@ -181,7 +185,7 @@ export function harness(f: Fixture): (input: Uint8Array) => { view(): Uint8Array case 3: if (c !== undefined) { log.note(`c${c} send ${arg}`); - if (!channels[c].send(BigInt(arg))) log.note(`c${c} closed`); + if (!channels[c].send(f.u64.of(arg))) log.note(`c${c} closed`); } break; case 4: From daab443cf2637d3a1654c058d86bcfdc7f6dfca3 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:24:55 -0700 Subject: [PATCH 25/30] test(ts): regenerate snapshots after merging main Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/kio.ts | 30 ++--- ts/fixtures/task/expected/model.ts | 170 ++++++++++++++--------------- 2 files changed, 100 insertions(+), 100 deletions(-) diff --git a/ts/fixtures/task/expected/kio.ts b/ts/fixtures/task/expected/kio.ts index 783e96b68..30cdb7cdc 100644 --- a/ts/fixtures/task/expected/kio.ts +++ b/ts/fixtures/task/expected/kio.ts @@ -45,9 +45,9 @@ export class Waiter { export class WaiterList { entries: rt.Weak[]; /** Where the next registration looks for a dead slot to reuse. */ - cursor: number; + cursor: rt.usize; - constructor(fields: { entries: rt.Weak[]; cursor: number }) { + constructor(fields: { entries: rt.Weak[]; cursor: rt.usize }) { this.entries = fields.entries; this.cursor = fields.cursor; } @@ -63,7 +63,7 @@ export class WaiterList { return; } } - let probes: number = rt.min(this.entries.length, 2); + let probes: rt.usize = rt.min(this.entries.length, 2); while (probes > 0) { if (rt.at(this.entries, this.cursor).arc.strong === 0) { const value = weak; @@ -153,7 +153,7 @@ export class Park { } /** A future from a poll function that receives a [`Waiter`]. */ -export function wait(poll: (a0: Waiter) => rt.Poll): Pending<(a0: Waiter) => rt.Poll> { +export function wait(poll: (a0: Waiter) => rt.Poll): Pending<(a0: Waiter) => rt.Poll> { return new Pending({ _poll: poll, park: Park.default() }); } @@ -172,7 +172,7 @@ export class Pending { rt.drop(this.park); } - poll(this: Pending<(a0: Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { + poll(this: Pending<(a0: Waiter) => rt.Poll>, cx: rt.Context): rt.Poll { const this_ = this; const waiter = this_.park.hold(cx); return this_._poll(waiter); @@ -180,12 +180,12 @@ export class Pending { } export class State { - queue: bigint[]; + queue: rt.u64[]; closed: boolean; - producers: number; + producers: rt.usize; waiters: WaiterList; - constructor(fields: { queue: bigint[]; closed: boolean; producers: number; waiters: WaiterList }) { + constructor(fields: { queue: rt.u64[]; closed: boolean; producers: rt.usize; waiters: WaiterList }) { this.queue = fields.queue; this.closed = fields.closed; this.producers = fields.producers; @@ -212,7 +212,7 @@ export class Producer { } /** Queue `value` and wake every consumer, after releasing the lock. */ - send(value: bigint): void { + send(value: rt.u64): void { let state: rt.Mutex = this.state.value; state.value.queue.push(value); let waiters: WaiterList = state.value.waiters.take(); @@ -243,9 +243,9 @@ export class Producer { /** The receiving side of a channel: every value sent, in order. */ export class Consumer { state: rt.Arc>; - next: number; + next: rt.usize; - constructor(fields: { state: rt.Arc>; next: number }) { + constructor(fields: { state: rt.Arc>; next: rt.usize }) { this.state = fields.state; this.next = fields.next; } @@ -259,7 +259,7 @@ export class Consumer { } /** The next value, or `None` once the channel closed and every value was read. */ - pollRecv(waiter: Waiter): rt.Poll { + pollRecv(waiter: Waiter): rt.Poll { let state: rt.Mutex = this.state.value; if (this.next < state.value.queue.length) { const value = rt.at(state.value.queue, this.next); @@ -274,14 +274,14 @@ export class Consumer { } /** kio's one-line wrapper over a `poll_*` method. */ - recv(): rt.Future { + recv(): rt.Future { return rt.future(recvBody, undefined, this); } } -export function* recvBody(_taskContext: rt.Context, self: Consumer): Generator { +export function* recvBody(_taskContext: rt.Context, self: Consumer): Generator { const self2 = self; - let __awaitee: Pending<(a0: Waiter) => rt.Poll> = wait((waiter: Waiter): rt.Poll => { + let __awaitee: Pending<(a0: Waiter) => rt.Poll> = wait((waiter: Waiter): rt.Poll => { return self2.pollRecv(waiter); }); try { diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 444ff8dae..663210be8 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -53,7 +53,7 @@ export class Channel { } /** Send `value` through the first producer, if one is open. */ - send(value: bigint): boolean { + send(value: rt.u64): boolean { const first = rt.slice.first(this.producers); if (first !== undefined) { const producer = first; @@ -106,10 +106,10 @@ export class Channel { /** Logs its own drop. */ export class Guard { - id: number; + id: rt.u32; log: Log; - constructor(fields: { id: number; log: Log }) { + constructor(fields: { id: rt.u32; log: Log }) { this.id = fields.id; this.log = fields.log; } @@ -119,7 +119,7 @@ export class Guard { rt.drop(this.log); } - static new(id: number, log: Log): Guard { + static new(id: rt.u32, log: Log): Guard { try { const arg = id; const log2 = log; @@ -144,11 +144,11 @@ export class Guard { * Every value until the channel closes, summed, holding a guard of its own across * each await beside the one it was given. */ -export function sum(rx: Consumer, guard: Guard): rt.Future { +export function sum(rx: Consumer, guard: Guard): rt.Future { return rt.future(sumBody, sumDrop, rx, guard); } -export function* sumBody(_taskContext: rt.Context, rx: Consumer, guard: Guard): Generator { +export function* sumBody(_taskContext: rt.Context, rx: Consumer, guard: Guard): Generator { let rx2: Consumer = rx; rx = undefined!; try { @@ -157,10 +157,10 @@ export function* sumBody(_taskContext: rt.Context, rx: Consumer, guard: Guard): try { const inner = Guard.new(rt.u32.add(guard2.id, 100), guard2.log.clone()); try { - let total: bigint = 0n; + let total: rt.u64 = 0; while (true) { - let option: bigint | undefined; - let __awaitee: rt.Future = rx2.recv(); + let option: rt.u64 | undefined; + let __awaitee: rt.Future = rx2.recv(); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -206,11 +206,11 @@ export function sumDrop(rx: Consumer, guard: Guard): void { * move on one path only; and a move the block only borrows, which drops when the block * returns or is cancelled. Between them, a value of two types that hold each other. */ -export function blocks(rx: Consumer, guard: Guard, moves: boolean): rt.Future { +export function blocks(rx: Consumer, guard: Guard, moves: boolean): rt.Future { return rt.future(blocksBody, blocksDrop, rx, guard, moves); } -export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard, moves: boolean): Generator { +export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard, moves: boolean): Generator { let rx2: Consumer = rx; rx = undefined!; try { @@ -230,10 +230,10 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard tally.n = rt.u32.add(tally.n, 1000); const arg2 = guard2; const arg = tally.n; - let value: number; + let value: rt.u32; const seen2 = seen; seen = undefined!; - let __awaitee: rt.Future = seen2; + let __awaitee: rt.Future = seen2; try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -249,8 +249,8 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard } arg2.note(rt.fmt.format(["tally ", (f: rt.Formatter) => rt.u32.display(arg, f), " then ", (f: rt.Formatter) => rt.u32.display(value, f)])); let mark: Mark = new Mark({ n: 1 }); - let replaced: number; - let __awaitee2: rt.Future = rt.future(blocksBody$4, undefined, mark); + let replaced: rt.u32; + let __awaitee2: rt.Future = rt.future(blocksBody$4, undefined, mark); try { while (true) { const poll2 = __awaitee2.poll(_taskContext); @@ -286,7 +286,7 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard try { const read2 = read_; read_ = undefined!; - let __awaitee4: rt.Future = read2; + let __awaitee4: rt.Future = read2; try { while (true) { const poll4 = __awaitee4.poll(_taskContext); @@ -334,11 +334,11 @@ export function* blocksBody$2(_taskContext2: rt.Context, first: Guard): Generato first.note("borrowed"); } -export function* blocksBody$3(_taskContext3: rt.Context, tally: Tally): Generator { +export function* blocksBody$3(_taskContext3: rt.Context, tally: Tally): Generator { return read(rt.copy(tally)); } -export function* blocksBody$4(_taskContext4: rt.Context, mark: Mark): Generator { +export function* blocksBody$4(_taskContext4: rt.Context, mark: Mark): Generator { Object.assign(mark, new Mark({ n: 2 })); return mark.n; } @@ -355,7 +355,7 @@ export function blocksDrop$2(guard2: Guard): void { rt.drop(guard2); } -export function* blocksBody$6(_taskContext6: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { +export function* blocksBody$6(_taskContext6: rt.Context, first: Guard, second: Guard, rx2: Consumer): Generator { try { try { try { @@ -363,8 +363,8 @@ export function* blocksBody$6(_taskContext6: rt.Context, first: Guard, second: G second.note("reads"); const _held = Guard.new(rt.u32.add(second.id, 100), second.log.clone()); try { - let option: bigint | undefined; - let __awaitee3: rt.Future = rx2.recv(); + let option: rt.u64 | undefined; + let __awaitee3: rt.Future = rx2.recv(); try { while (true) { const poll3 = __awaitee3.poll(_taskContext6); @@ -382,7 +382,7 @@ export function* blocksBody$6(_taskContext6: rt.Context, first: Guard, second: G const value2 = option; return value2; } else { - return 0n; + return 0; } } finally { rt.drop(_held); @@ -405,9 +405,9 @@ export function blocksDrop$3(first: Guard, second: Guard, rx2: Consumer): void { } export class Mark { - n: number; + n: rt.u32; - constructor(fields: { n: number }) { + constructor(fields: { n: rt.u32 }) { this.n = fields.n; } } @@ -445,19 +445,19 @@ export class Inner { /** A `Copy` value an `async move` block takes its own copy of. */ export class Tally { - n: number; + n: rt.u32; - constructor(fields: { n: number }) { + constructor(fields: { n: rt.u32 }) { this.n = fields.n; } } -export function read(t: Tally): number { +export function read(t: Tally): rt.u32 { return t.n; } /** `i`, noted as picked. */ -export function pick(log: Log, i: number): number { +export function pick(log: Log, i: rt.usize): rt.usize { log.note(rt.fmt.format(["pick ", (f: rt.Formatter) => rt.usize.display(i, f)])); return i; } @@ -470,7 +470,7 @@ export function pick(log: Log, i: number): number { * temporary to the end of the block; a `_` binding of an element, which evaluates its * index and moves nothing; and a boxed guard read twice, which a read leaves boxed. */ -export function turns(log: Log, count: number): void { +export function turns(log: Log, count: rt.u32): void { const pair = [Guard.new(rt.u32.add(count, 10), log.clone()), Guard.new(rt.u32.add(count, 20), log.clone())]; try { const kept = pair[0]; @@ -487,7 +487,7 @@ export function turns(log: Log, count: number): void { const extended = Guard.new(rt.u32.add(count, 60), log.clone()); try { extended.note("extended"); - let value: number; + let value: rt.u32; const inner = Guard.new(rt.u32.add(count, 90), log.clone()); try { value = inner.id; @@ -502,7 +502,7 @@ export function turns(log: Log, count: number): void { log.note(rt.fmt.format(["boxed ", (f: rt.Formatter) => rt.u32.display(once, f), " ", (f: rt.Formatter) => rt.u32.display(boxed.id, f)])); const spares = [Guard.new(rt.u32.add(count, 70), log.clone()), Guard.new(rt.u32.add(count, 80), log.clone())]; try { - const index = pick(log, rt.usize.rem(count, 2)); + const index = pick(log, rt.usize.rem(count as rt.usize, 2)); spares[rt.idx(spares, index)]; arms: { if (count === 0) { @@ -511,7 +511,7 @@ export function turns(log: Log, count: number): void { } const n = count; if (n < 4) { - let left: number = n; + let left: rt.u32 = n; while (true) { const turn = Guard.new(left, log.clone()); try { @@ -555,20 +555,20 @@ export function turns(log: Log, count: number): void { * Every value until the channel closes, summed, each read `depth` async functions * deep: 1, 4, or 16. */ -export function drain(rx: Consumer, depth: number): rt.Future { +export function drain(rx: Consumer, depth: rt.u32): rt.Future { return rt.future(drainBody, drainDrop, rx, depth); } -export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: number): Generator { +export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: rt.u32): Generator { let rx2: Consumer = rx; rx = undefined!; try { const depth2 = depth; - let total: bigint = 0n; + let total: rt.u64 = 0; while (true) { - let next: bigint | undefined; + let next: rt.u64 | undefined; if (depth2 === 1) { - let __awaitee: rt.Future = rx2.recv(); + let __awaitee: rt.Future = rx2.recv(); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -583,7 +583,7 @@ export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: number rt.drop(__awaitee); } } else if (depth2 === 4) { - let __awaitee2: rt.Future = level3(rx2); + let __awaitee2: rt.Future = level3(rx2); try { while (true) { const poll2 = __awaitee2.poll(_taskContext); @@ -598,7 +598,7 @@ export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: number rt.drop(__awaitee2); } } else { - let __awaitee3: rt.Future = level15(rx2); + let __awaitee3: rt.Future = level15(rx2); try { while (true) { const poll3 = __awaitee3.poll(_taskContext); @@ -626,17 +626,17 @@ export function* drainBody(_taskContext: rt.Context, rx: Consumer, depth: number } } -export function drainDrop(rx: Consumer, _depth: number): void { +export function drainDrop(rx: Consumer, _depth: rt.u32): void { rt.drop(rx); } -export function level1(rx: Consumer): rt.Future { +export function level1(rx: Consumer): rt.Future { return rt.future(level1Body, undefined, rx); } -export function* level1Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level1Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = rx2.recv(); + let __awaitee: rt.Future = rx2.recv(); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -651,13 +651,13 @@ export function* level1Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level10(rx: Consumer): rt.Future { return rt.future(level10Body, undefined, rx); } -export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level9(rx2); + let __awaitee: rt.Future = level9(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -672,13 +672,13 @@ export function* level10Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level11(rx: Consumer): rt.Future { +export function level11(rx: Consumer): rt.Future { return rt.future(level11Body, undefined, rx); } -export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level10(rx2); + let __awaitee: rt.Future = level10(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -693,13 +693,13 @@ export function* level11Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level12(rx: Consumer): rt.Future { +export function level12(rx: Consumer): rt.Future { return rt.future(level12Body, undefined, rx); } -export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level11(rx2); + let __awaitee: rt.Future = level11(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -714,13 +714,13 @@ export function* level12Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level13(rx: Consumer): rt.Future { +export function level13(rx: Consumer): rt.Future { return rt.future(level13Body, undefined, rx); } -export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level12(rx2); + let __awaitee: rt.Future = level12(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -735,13 +735,13 @@ export function* level13Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level14(rx: Consumer): rt.Future { +export function level14(rx: Consumer): rt.Future { return rt.future(level14Body, undefined, rx); } -export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level13(rx2); + let __awaitee: rt.Future = level13(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -756,13 +756,13 @@ export function* level14Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level15(rx: Consumer): rt.Future { +export function level15(rx: Consumer): rt.Future { return rt.future(level15Body, undefined, rx); } -export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level14(rx2); + let __awaitee: rt.Future = level14(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -777,13 +777,13 @@ export function* level15Body(_taskContext: rt.Context, rx: Consumer): Generator< } } -export function level2(rx: Consumer): rt.Future { +export function level2(rx: Consumer): rt.Future { return rt.future(level2Body, undefined, rx); } -export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level1(rx2); + let __awaitee: rt.Future = level1(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -798,13 +798,13 @@ export function* level2Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level3(rx: Consumer): rt.Future { return rt.future(level3Body, undefined, rx); } -export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level2(rx2); + let __awaitee: rt.Future = level2(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -819,13 +819,13 @@ export function* level3Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level4(rx: Consumer): rt.Future { return rt.future(level4Body, undefined, rx); } -export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level3(rx2); + let __awaitee: rt.Future = level3(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -840,13 +840,13 @@ export function* level4Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level5(rx: Consumer): rt.Future { return rt.future(level5Body, undefined, rx); } -export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level4(rx2); + let __awaitee: rt.Future = level4(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -861,13 +861,13 @@ export function* level5Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level6(rx: Consumer): rt.Future { return rt.future(level6Body, undefined, rx); } -export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level5(rx2); + let __awaitee: rt.Future = level5(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -882,13 +882,13 @@ export function* level6Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level7(rx: Consumer): rt.Future { return rt.future(level7Body, undefined, rx); } -export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level6(rx2); + let __awaitee: rt.Future = level6(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -903,13 +903,13 @@ export function* level7Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level8(rx: Consumer): rt.Future { return rt.future(level8Body, undefined, rx); } -export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level7(rx2); + let __awaitee: rt.Future = level7(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); @@ -924,13 +924,13 @@ export function* level8Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function level9(rx: Consumer): rt.Future { return rt.future(level9Body, undefined, rx); } -export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { +export function* level9Body(_taskContext: rt.Context, rx: Consumer): Generator { const rx2 = rx; - let __awaitee: rt.Future = level8(rx2); + let __awaitee: rt.Future = level8(rx2); try { while (true) { const poll = __awaitee.poll(_taskContext); From 32784093c325095d876cdfe917ae9fea52b1db6e Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:32:48 -0700 Subject: [PATCH 26/30] fix(ts): refuse three more drops JS would skip, from Codex's review - Replacing a `MutexGuard` through a reference: the guard is its mutex in JS, so the copy would change the other mutex. - A std mapping taking a value that drops by value, unless it moves every such operand into its result or a closure: `unwrap_or`, `ok_or`, `map_or`, `then_some`, and `Result::ok` discard one. - A field read through a `Box` made in place: the deref of a temporary box is part of the temporary, which drops at the end of the statement. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 5 +- ts/README.md | 6 +- ts/fixtures/reject/census.md | 109 ++++++++++++++++++-------------- ts/fixtures/reject/expected.txt | 25 ++++---- ts/fixtures/reject/src/lib.rs | 15 +++++ ts/fixtures/reject/ts.toml | 3 + ts/src/lower/body.rs | 11 ++-- ts/src/lower/library.rs | 49 ++++++++++++++ 8 files changed, 155 insertions(+), 68 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 1f064542c..4786205f7 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -17,7 +17,7 @@ each field); a variable drops in a `finally` at the end of its scope; a move lea fixture's trace test proves it on kio's waiters, wakers, and channels. What still fails translation, each with its span (the reject fixture has one of each), -ranked by the census of moq-net at the pinned revision (kio's has 27 in all): +ranked by the census of moq-net at the pinned revision (kio's has 28 in all): - Dropping a value whose drop no `[Symbol.dispose]` carries (657): a `Result`, an `Option` or `Poll` of one, an enum or tuple holding one, a `Vec` of one. Each needs @@ -32,6 +32,9 @@ ranked by the census of moq-net at the pinned revision (kio's has 27 in all): - An iterator that owns a value that drops (55): a `Vec` of one moved into it, or an adaptor over items that drop. An `rt.Iter` drops nothing it skips, consumes, or still holds when it is dropped. +- A std mapping that may discard an operand that drops (19): `bool::then_some`, + `Option::ok_or`, `map_or`, and `unwrap_or`, and `Result::ok`. Each refuses any operand + that drops today, even one it always keeps, such as `ok_or`'s option. - Struct update syntax from a value that drops (16), a closure capturing one (13), a generic type that implements `Drop` (11), and a parameter that drops bound by a pattern. diff --git a/ts/README.md b/ts/README.md index 756274148..de7936166 100644 --- a/ts/README.md +++ b/ts/README.md @@ -180,9 +180,9 @@ bind to hand-written TS through config ([model](/quest/m2/ts-model.md)). These fail translation: floats, `char`, statics, async blocks that borrow a number mutably and async closures, values that drop as temporaries not moved whole, in a -closure's captures, in an iterator, in an enum, tuple, or generic `Drop` type, borrowed -in an `Arc` or `Mutex`, or moved ahead of an `.await` in the same call or assignment -([Drop](/quest/m2/ts-drop.md)), iterators of std's collections and the adaptors without +closure's captures, in an iterator, in an enum, tuple, or generic `Drop` type, passed to +a std function that may discard them (`unwrap_or`), borrowed in an `Arc` or `Mutex`, or +moved ahead of an `.await` in the same call or assignment ([Drop](/quest/m2/ts-drop.md)), iterators of std's collections and the adaptors without a mapping in `src/lower/iter.rs` (such as `cycle`, `unzip`, and `partition`), an own `impl Iterator` with `next_back`, `len`, or another provided method of its own, `while let` or `match` on the `next` of an iterator of `Option`, or-patterns that bind, other diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index fd8dd387a..84c5a2c62 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 70 -- Function instances: 60 +- Refusals: 73 +- Function instances: 63 - Generic functions no instance reached, lowered over their type parameters: 3 ## By construct @@ -12,15 +12,16 @@ | 4 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | | 3 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | -| 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:361:4 | +| 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:371:4 | | 3 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | +| 3 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | | 2 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | | 2 | a `match` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:217:2 | -| 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:299:1 | -| 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:279:2 | -| 2 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | +| 2 | a field of a temporary that drops: bind it to a variable first | fixtures/reject/src/lib.rs:62:2 | +| 2 | an iterator of the crate implementing `_`, which is not supported yet | fixtures/reject/src/lib.rs:309:1 | +| 2 | overriding `_`, which std's adaptors call in place of `next` or beside it | fixtures/reject/src/lib.rs:289:2 | | 1 | `Binary` formatting, as in `{:b}`, is not supported | fixtures/reject/src/lib.rs:132:3 | | 1 | `LowerExp` formatting, as in `{:e}`, is not supported | fixtures/reject/src/lib.rs:134:3 | | 1 | `Octal` formatting, as in `{:o}`, is not supported | fixtures/reject/src/lib.rs:133:3 | @@ -28,13 +29,12 @@ | 1 | `_` is generic and implements `Drop`, which is not supported yet | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: it would be pending two ways with one value | fixtures/reject/src/lib.rs:229:20 | | 1 | a `let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:200:2 | -| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:312:51 | +| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | fixtures/reject/src/lib.rs:322:51 | | 1 | a cast from `_` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | fixtures/reject/src/lib.rs:121:10 | | 1 | a closure that captures a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:68:23 | | 1 | a closure that copies a mutable variable | fixtures/reject/src/lib.rs:149:18 | -| 1 | a field of a temporary that drops: bind it to a variable first | fixtures/reject/src/lib.rs:62:2 | | 1 | a method that takes `self` by value that drops, which is not supported yet | fixtures/reject/src/lib.rs:51:20 | | 1 | a mutable reference to `_`, which is no object it can change in place | fixtures/reject/src/lib.rs:144:17 | | 1 | a parameter that drops bound by a pattern, which is not supported yet | fixtures/reject/src/lib.rs:83:21 | @@ -50,6 +50,7 @@ | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | | 1 | arithmetic on `_` | fixtures/reject/src/lib.rs:7:2 | | 1 | hex `Debug`, as in `{:x?}`, is not supported | fixtures/reject/src/lib.rs:135:3 | +| 1 | passing `_`, which drops, to `_`, which is not supported yet | fixtures/reject/src/lib.rs:400:4 | | 1 | the `+` flag of a format spec is not supported | fixtures/reject/src/lib.rs:130:3 | | 1 | the `-` flag of a format spec is not supported | fixtures/reject/src/lib.rs:131:3 | | 1 | unsupported expression: StaticRef | fixtures/reject/src/lib.rs:163:2 | @@ -62,28 +63,30 @@ The type or module each refused type or path belongs to. | Count | API | First | | ---: | --- | --- | | 6 | `f64` | fixtures/reject/src/lib.rs:6:1 | +| 4 | `Option` | fixtures/reject/src/lib.rs:31:15 | | 4 | `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 3 | `Meters` | fixtures/reject/src/lib.rs:168:17 | -| 3 | `Option` | fixtures/reject/src/lib.rs:31:15 | | 3 | `u32` | fixtures/reject/src/lib.rs:19:13 | -| 2 | `Iterator` | fixtures/reject/src/lib.rs:279:2 | -| 2 | `Noisy` | fixtures/reject/src/lib.rs:361:16 | +| 2 | `Iterator` | fixtures/reject/src/lib.rs:289:2 | +| 2 | `Noisy` | fixtures/reject/src/lib.rs:371:16 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | | 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | -| 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:299:1 | -| 1 | `FusedIterator` | fixtures/reject/src/lib.rs:353:1 | +| 1 | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:309:1 | +| 1 | `FusedIterator` | fixtures/reject/src/lib.rs:363:1 | | 1 | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | `dyn std::ops::Fn(u8) -> u8` | fixtures/reject/src/lib.rs:14:16 | -| 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:312:51 | -| 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:320:8 | +| 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:322:51 | +| 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:330:8 | +| 1 | `std::option::Option` | fixtures/reject/src/lib.rs:400:4 | | 1 | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | -| 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:266:11 | +| 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:276:11 | | 1 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | +| 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:271:2 | | 1 | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | -| 1 | `std::vec::Vec` | fixtures/reject/src/lib.rs:361:4 | +| 1 | `std::vec::Vec` | fixtures/reject/src/lib.rs:371:4 | | 1 | `u8` | fixtures/reject/src/lib.rs:113:3 | | 1 | `{closure}` | fixtures/reject/src/lib.rs:66:31 | @@ -95,33 +98,35 @@ The type or module each refused type or path belongs to. | 3 | replacing the value behind a reference to `_` | `Meters` | fixtures/reject/src/lib.rs:168:17 | | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | -| 2 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:361:16 | +| 2 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:371:16 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | | 1 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | -| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:312:51 | +| 1 | a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` | `std::iter::Chain` | fixtures/reject/src/lib.rs:322:51 | | 1 | a cast from `_` | `char` | fixtures/reject/src/lib.rs:11:2 | | 1 | a cast to `_` | `f64` | fixtures/reject/src/lib.rs:179:2 | | 1 | a closure of type `_` | `{async closure}` | fixtures/reject/src/lib.rs:121:10 | | 1 | a mutable reference to `_`, which is no object it can change in place | `std::string::String` | fixtures/reject/src/lib.rs:144:17 | | 1 | an async body returning `_` is not supported: its `Ready` could be pending | `std::task::Poll` | fixtures/reject/src/lib.rs:245:54 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | `u8` | fixtures/reject/src/lib.rs:113:3 | -| 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:299:1 | -| 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:353:1 | -| 1 | an iterator that owns `_`, which drops, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:361:4 | +| 1 | an iterator of the crate implementing `_`, which is not supported yet | `DoubleEndedIterator` | fixtures/reject/src/lib.rs:309:1 | +| 1 | an iterator of the crate implementing `_`, which is not supported yet | `FusedIterator` | fixtures/reject/src/lib.rs:363:1 | +| 1 | an iterator that owns `_`, which drops, which is not supported yet | `std::vec::Vec` | fixtures/reject/src/lib.rs:371:4 | | 1 | arithmetic on `_` | `f64` | fixtures/reject/src/lib.rs:7:2 | | 1 | dropping `_`, which is not supported yet | `Slot` | fixtures/reject/src/lib.rs:93:1 | | 1 | dropping `_`, which is not supported yet | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 1 | dropping `_`, which is not supported yet | `{closure}` | fixtures/reject/src/lib.rs:66:31 | -| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:279:2 | -| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:333:2 | +| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:289:2 | +| 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:343:2 | +| 1 | passing `_`, which drops, to `_`, which is not supported yet | `std::option::Option`, `Option::unwrap_or` | fixtures/reject/src/lib.rs:400:4 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::Arc` | fixtures/reject/src/lib.rs:225:2 | -| 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:266:11 | +| 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:271:2 | +| 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:276:11 | | 1 | unsupported call to `_` | `::write_fmt` | fixtures/reject/src/lib.rs:144:10 | -| 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:320:8 | +| 1 | unsupported call to `_` | `std::ops::Range::contains` | fixtures/reject/src/lib.rs:330:8 | | 1 | unsupported call to `_` | `std::slice::sort` | fixtures/reject/src/lib.rs:36:4 | | 1 | unsupported literal of type `_` | `f64` | fixtures/reject/src/lib.rs:7:6 | | 1 | unsupported type `_` | `char` | fixtures/reject/src/lib.rs:10:18 | @@ -145,8 +150,8 @@ The type or module each refused type or path belongs to. - fixtures/reject/src/lib.rs:36:4: unsupported call to `std::slice::::sort` - fixtures/reject/src/lib.rs:144:10: unsupported call to `::write_fmt` -- fixtures/reject/src/lib.rs:266:11: unsupported call to ` as std::iter::Iterator>::cycle` -- fixtures/reject/src/lib.rs:320:8: unsupported call to `std::ops::Range::::contains::` +- fixtures/reject/src/lib.rs:276:11: unsupported call to ` as std::iter::Iterator>::cycle` +- fixtures/reject/src/lib.rs:330:8: unsupported call to `std::ops::Range::::contains::`
@@ -168,9 +173,9 @@ The type or module each refused type or path belongs to.
an iterator that owns `_`, which drops, which is not supported yet (3) -- fixtures/reject/src/lib.rs:361:4: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:361:16: an iterator that owns `Noisy`, which drops, which is not supported yet -- fixtures/reject/src/lib.rs:366:20: an iterator that owns `Noisy`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:371:4: an iterator that owns `std::vec::Vec`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:371:16: an iterator that owns `Noisy`, which drops, which is not supported yet +- fixtures/reject/src/lib.rs:376:20: an iterator that owns `Noisy`, which drops, which is not supported yet
@@ -182,6 +187,14 @@ The type or module each refused type or path belongs to.
+
replacing the `_` behind a reference, whose JS object is shared or private (3) + +- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:261:2: replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:271:2: replacing the `std::sync::MutexGuard<'_, u8>` behind a reference, whose JS object is shared or private + +
+
replacing the value behind a reference to `_` (3) - fixtures/reject/src/lib.rs:168:17: replacing the value behind a reference to `Meters` @@ -200,7 +213,7 @@ The type or module each refused type or path belongs to.
a `for` loop over values that drop, which is not supported yet (2) - fixtures/reject/src/lib.rs:76:6: a `for` loop over values that drop, which is not supported yet -- fixtures/reject/src/lib.rs:382:6: a `for` loop over values that drop, which is not supported yet +- fixtures/reject/src/lib.rs:392:6: a `for` loop over values that drop, which is not supported yet
@@ -211,24 +224,24 @@ The type or module each refused type or path belongs to.
-
an iterator of the crate implementing `_`, which is not supported yet (2) +
a field of a temporary that drops: bind it to a variable first (2) -- fixtures/reject/src/lib.rs:299:1: an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet -- fixtures/reject/src/lib.rs:353:1: an iterator of the crate implementing `FusedIterator`, which is not supported yet +- fixtures/reject/src/lib.rs:62:2: a field of a temporary that drops: bind it to a variable first +- fixtures/reject/src/lib.rs:266:2: a field of a temporary that drops: bind it to a variable first
-
overriding `_`, which std's adaptors call in place of `next` or beside it (2) +
an iterator of the crate implementing `_`, which is not supported yet (2) -- fixtures/reject/src/lib.rs:279:2: overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it -- fixtures/reject/src/lib.rs:333:2: overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it +- fixtures/reject/src/lib.rs:309:1: an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet +- fixtures/reject/src/lib.rs:363:1: an iterator of the crate implementing `FusedIterator`, which is not supported yet
-
replacing the `_` behind a reference, whose JS object is shared or private (2) +
overriding `_`, which std's adaptors call in place of `next` or beside it (2) -- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private -- fixtures/reject/src/lib.rs:261:2: replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:289:2: overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it +- fixtures/reject/src/lib.rs:343:2: overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it
@@ -276,7 +289,7 @@ The type or module each refused type or path belongs to.
a `zip` of `_`, whose closures std calls one item further through `next` than through `fold` (1) -- fixtures/reject/src/lib.rs:312:51: a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:312:15: 312:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` +- fixtures/reject/src/lib.rs:322:51: a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:322:15: 322:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold`
@@ -310,12 +323,6 @@ The type or module each refused type or path belongs to.
-
a field of a temporary that drops: bind it to a variable first (1) - -- fixtures/reject/src/lib.rs:62:2: a field of a temporary that drops: bind it to a variable first - -
-
a method that takes `self` by value that drops, which is not supported yet (1) - fixtures/reject/src/lib.rs:51:20: a method that takes `self` by value that drops, which is not supported yet @@ -406,6 +413,12 @@ The type or module each refused type or path belongs to.
+
passing `_`, which drops, to `_`, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:400:4: passing `std::option::Option`, which drops, to `Option::unwrap_or`, which is not supported yet + +
+
the `+` flag of a format spec is not supported (1) - fixtures/reject/src/lib.rs:130:3: the `+` flag of a format spec is not supported diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 6230b0b2c..03a45d8b0 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -57,14 +57,17 @@ an `if let` on a temporary that drops, which it doesn't move out of whole at fix an async body returning `std::task::Poll` is not supported: its `Ready` could be pending at fixtures/reject/src/lib.rs:245:54 a `match` on a temporary that drops, which it doesn't move out of whole at fixtures/reject/src/lib.rs:252:16 replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:261:2 -unsupported call to ` as std::iter::Iterator>::cycle` at fixtures/reject/src/lib.rs:266:11 -a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:312:15: 312:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` at fixtures/reject/src/lib.rs:312:51 -unsupported call to `std::ops::Range::::contains::` at fixtures/reject/src/lib.rs:320:8 -an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:361:16 -an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:361:4 -an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:366:20 -a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:382:6 -overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:279:2 -an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:299:1 -overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:333:2 -an iterator of the crate implementing `FusedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:353:1 +a field of a temporary that drops: bind it to a variable first at fixtures/reject/src/lib.rs:266:2 +replacing the `std::sync::MutexGuard<'_, u8>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:271:2 +unsupported call to ` as std::iter::Iterator>::cycle` at fixtures/reject/src/lib.rs:276:11 +a `zip` of `std::iter::Chain, {closure@fixtures/reject/src/lib.rs:322:15: 322:18}>, std::iter::Copied>>`, whose closures std calls one item further through `next` than through `fold` at fixtures/reject/src/lib.rs:322:51 +unsupported call to `std::ops::Range::::contains::` at fixtures/reject/src/lib.rs:330:8 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:371:16 +an iterator that owns `std::vec::Vec`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:371:4 +an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:376:20 +a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:392:6 +passing `std::option::Option`, which drops, to `Option::unwrap_or`, which is not supported yet at fixtures/reject/src/lib.rs:400:4 +overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:289:2 +an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:309:1 +overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:343:2 +an iterator of the crate implementing `FusedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:363:1 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 4ba3bef97..af961da3f 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -261,6 +261,16 @@ pub fn replace_pinned(dst: &mut std::pin::Pin>, src: std::pin *dst = src; } +/// The box drops its `Noisy` at the end of the statement, which nothing marks. +pub fn boxed_field() -> u8 { + Box::new(make()).0 +} + +/// A guard is its mutex in JS: replacing it would copy the other mutex's value in. +pub fn replace_guard<'a>(dst: &mut std::sync::MutexGuard<'a, u8>, src: std::sync::MutexGuard<'a, u8>) { + *dst = src; +} + /// An adaptor without a mapping. pub fn cycled(v: &[u8]) -> usize { v.iter().cycle().take(3).count() @@ -384,3 +394,8 @@ pub fn looped(c: Countdown) -> u8 { } n } + +/// `unwrap_or` drops its fallback when the option holds a value. +pub fn fallback(a: Option, b: Noisy) -> Noisy { + a.unwrap_or(b) +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 588def12c..53da6c33b 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -37,6 +37,8 @@ roots = [ "pending_output", "tested", "replace_pinned", + "boxed_field", + "replace_guard", "cycled", "folds", "backs", @@ -47,6 +49,7 @@ roots = [ "drained", "counted", "looped", + "fallback", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 6379ddb6c..8eeabcf92 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1803,9 +1803,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { }; if through_ref { let pointee = self.ty_of(lhs); - // Every clone of an `Arc` or waker is one JS object, and a future keeps its state - // private: copying fields in would change the other handles, or nothing. A `Pin` - // or `Box` is its pointee in JS. + // Every clone of an `Arc` or waker is one JS object, a guard is its mutex, and a + // future keeps its state private: copying fields in would change the other + // handles, or nothing. A `Pin` or `Box` is its pointee in JS. let mut erased = pointee; while let ty::Adt(adt, args) = erased.kind() && matches!( @@ -1817,7 +1817,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { let shared = match erased.kind() { ty::Adt(adt, _) => matches!( library::Std::of(self.t.tcx, adt.did()), - Some(library::Std::Arc | library::Std::Waker | library::Std::Context) + Some(library::Std::Arc | library::Std::Waker | library::Std::Context | library::Std::MutexGuard) ), ty::Coroutine(..) => true, _ => false, @@ -1928,7 +1928,8 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ExprKind::VarRef { .. } | ExprKind::UpvarRef { .. } | ExprKind::Field { .. } | ExprKind::Index { .. } => { true } - ExprKind::Deref { .. } => true, + // What a `Box` made in place points at is part of that temporary. + ExprKind::Deref { arg } => matches!(self.ty_of(*arg).kind(), ty::Ref(..)) || self.is_place(*arg), _ => false, } } diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 85fcc11f6..975d7511a 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -204,6 +204,45 @@ pub struct Call<'tcx> { pub span: Span, } +/// Whether the mapping of `owner::name` moves each operand it takes by value into its +/// result or a closure, and so drops nothing JS would leave undropped. Any other mapping +/// may discard one, as `unwrap_or` does its fallback. Iterators refuse their own. +fn keeps_operands(owner: &str, name: &str) -> bool { + matches!( + (owner, name), + ("Option", "map" | "unwrap" | "expect") + | ( + "Result", + "map" | "map_err" | "and_then" | "inspect_err" | "unwrap" | "expect" | "unwrap_err" + ) + | ("Vec", "push") + | ("Box", "new") + | ("boxed", "box_new") + | ("mem", "replace" | "take" | "swap") + | ("hint", "must_use") + | ("From", "from") + | ("Into", "into") + ) +} + +/// The first type `call` takes by value that drops. +fn dropping_operand<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>) -> Option> { + let tcx = b.t.tcx; + let sig = tcx.fn_sig(call.def_id).instantiate(tcx, call.args).skip_norm_wip(); + let env = b.t.typing_env_pub(); + // A census's call over type parameters may leave a projection unnormalized. + let inputs: Vec> = tcx + .instantiate_bound_regions_with_erased(sig) + .inputs() + .iter() + .map(|&ty| { + tcx.try_normalize_erasing_regions(env, ty::Unnormalized::new_wip(ty)) + .unwrap_or(ty) + }) + .collect(); + inputs.into_iter().find(|&ty| b.t.drops(ty)) +} + /// `owner::name` for a standard library function. pub fn key(tcx: TyCtxt<'_>, def_id: DefId) -> Option<(String, String)> { let name = tcx.item_name(def_id).to_string(); @@ -250,6 +289,10 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, Ok(e) => return e, Err(args) => args, }; + let dropping = match keeps_operands(&owner, &name) { + true => None, + false => dropping_operand(b, call), + }; // Methods on integers. if let Some(int) = int_named(&owner) { @@ -774,6 +817,12 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, } _ => return super::iter::call(b, call, &owner, &name, args, out), }; + if let Some(ty) = dropping { + return Some(b.err( + span, + format!("passing `{ty}`, which drops, to `{owner}::{name}`, which is not supported yet"), + )); + } Some(e) } From 2315345fbf6d19921953678f041a776e82c1e41b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:35:21 -0700 Subject: [PATCH 27/30] fix(ts): refuse a rest pattern that moves values that drop out of a place Its slice copy would drop the elements, and so would the array they stay in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 4 ++-- ts/fixtures/reject/census.md | 11 +++++++++-- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 6 ++++++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/pat.rs | 8 ++++++++ 6 files changed, 27 insertions(+), 4 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index 4786205f7..ccf2a024f 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -36,8 +36,8 @@ ranked by the census of moq-net at the pinned revision (kio's has 28 in all): `Option::ok_or`, `map_or`, and `unwrap_or`, and `Result::ok`. Each refuses any operand that drops today, even one it always keeps, such as `ok_or`'s option. - Struct update syntax from a value that drops (16), a closure capturing one (13), a - generic type that implements `Drop` (11), and a parameter that drops bound by a - pattern. + generic type that implements `Drop` (11), a parameter that drops bound by a pattern, + and a rest pattern that moves values that drop out of a place. - A value that drops, moved ahead of an `.await` in the same call (3) or in the place an assignment writes it to, which a cancel would leave in a temporary no scope drops, and an `Arc` or `Mutex` holding a borrow of a value that drops, which JS would drop diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 84c5a2c62..9f5ee7ab6 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 73 -- Function instances: 63 +- Refusals: 74 +- Function instances: 64 - Generic functions no instance reached, lowered over their type parameters: 3 ## By construct @@ -40,6 +40,7 @@ | 1 | a parameter that drops bound by a pattern, which is not supported yet | fixtures/reject/src/lib.rs:83:21 | | 1 | a precision, as in `{:.2}`, is not supported | fixtures/reject/src/lib.rs:129:3 | | 1 | a printable type must implement `Display` or `Debug` | fixtures/reject/src/lib.rs:175:1 | +| 1 | a rest pattern that moves values that drop out of a place, which is not supported yet | fixtures/reject/src/lib.rs:405:14 | | 1 | a variable from outside the function | fixtures/reject/src/lib.rs:84:2 | | 1 | a width or precision from an argument, as in `{:1$}`, is not supported | fixtures/reject/src/lib.rs:136:3 | | 1 | an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:190:13 | @@ -353,6 +354,12 @@ The type or module each refused type or path belongs to.
+
a rest pattern that moves values that drop out of a place, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:405:14: a rest pattern that moves values that drop out of a place, which is not supported yet + +
+
a variable from outside the function (1) - fixtures/reject/src/lib.rs:84:2: a variable from outside the function diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 03a45d8b0..d48f846f3 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -67,6 +67,7 @@ an iterator that owns `std::vec::Vec`, which drops, which is not supporte an iterator that owns `Noisy`, which drops, which is not supported yet at fixtures/reject/src/lib.rs:376:20 a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:392:6 passing `std::option::Option`, which drops, to `Option::unwrap_or`, which is not supported yet at fixtures/reject/src/lib.rs:400:4 +a rest pattern that moves values that drop out of a place, which is not supported yet at fixtures/reject/src/lib.rs:405:14 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:289:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:309:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:343:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index af961da3f..5c32d975e 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -399,3 +399,9 @@ pub fn looped(c: Countdown) -> u8 { pub fn fallback(a: Option, b: Noisy) -> Noisy { a.unwrap_or(b) } + +/// `rest` moves the tail out of `pair`, which would still drop it. +pub fn rest_moved(pair: [Noisy; 2]) -> u8 { + let [first, rest @ ..] = pair; + first.0 + rest[0].0 +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 53da6c33b..c76d4170d 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -50,6 +50,7 @@ roots = [ "counted", "looped", "fallback", + "rest_moved", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/pat.rs b/ts/src/lower/pat.rs index 5a48d9fb5..08321f80f 100644 --- a/ts/src/lower/pat.rs +++ b/ts/src/lower/pat.rs @@ -263,6 +263,14 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ty::Uint(ty::UintTy::U8) => "subarray", _ => "slice", }; + // Its copy of the elements would drop them, and so would the place they stay in. + let rest_ty = self.subst(p.ty); + if !owned && !matches!(rest_ty.kind(), ty::Ref(..)) && self.t.drops(rest_ty) { + self.t.err( + p.span, + "a rest pattern that moves values that drop out of a place, which is not supported yet", + ); + } let rest = scrut.clone().member(method).call(vec![start, end]); self.pat_bind(p, &rest, true, out); } From 4f6b19bc1a18467a0691edea00340d35700e7729 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:46:52 -0700 Subject: [PATCH 28/30] fix(ts): refuse replacing a pinned reference through a reference A reference is its referent in JS, so copying the new one's fields in would change what the old one pointed at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 6 +++--- ts/fixtures/reject/census.md | 27 ++++++++++++++------------- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 5 +++++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/body.rs | 9 +++++---- 6 files changed, 29 insertions(+), 20 deletions(-) diff --git a/ts/README.md b/ts/README.md index de7936166..dadc77977 100644 --- a/ts/README.md +++ b/ts/README.md @@ -188,9 +188,9 @@ a mapping in `src/lower/iter.rs` (such as `cycle`, `unzip`, and `partition`), an let` or `match` on the `next` of an iterator of `Option`, or-patterns that bind, other format specs (a precision, `+`, `{:b}`, `{:x?}`, and widths from arguments), writing to a `String` with `write!`, a `move` closure copying a mutable variable, `mem::swap`, -`replace`, or `take` of a reference's whole pointee, assigning an `Arc`, a waker, or a -future through a reference, and std functions without a mapping in -`src/lower/library.rs`. +`replace`, or `take` of a reference's whole pointee, assigning an `Arc`, a waker, a +`MutexGuard`, a pinned reference, or a future through a reference, and std functions +without a mapping in `src/lower/library.rs`. ## Tests diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index 9f5ee7ab6..e50a96b01 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 74 -- Function instances: 64 +- Refusals: 75 +- Function instances: 65 - Generic functions no instance reached, lowered over their type parameters: 3 ## By construct @@ -9,12 +9,12 @@ | Count | Construct | First | | ---: | --- | --- | | 6 | unsupported type `_` | fixtures/reject/src/lib.rs:6:1 | +| 4 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 4 | unsupported call to `_` | fixtures/reject/src/lib.rs:36:4 | | 3 | `_` is not supported: its `None` and `Some` would both be `undefined` | fixtures/reject/src/lib.rs:31:15 | | 3 | a `_` binding: a JS value of `_` is a copy, so it can't change | fixtures/reject/src/lib.rs:19:13 | | 3 | an iterator that owns `_`, which drops, which is not supported yet | fixtures/reject/src/lib.rs:371:4 | | 3 | dropping `_`, which is not supported yet | fixtures/reject/src/lib.rs:66:31 | -| 3 | replacing the `_` behind a reference, whose JS object is shared or private | fixtures/reject/src/lib.rs:225:2 | | 3 | replacing the value behind a reference to `_` | fixtures/reject/src/lib.rs:168:17 | | 2 | `_`: a JS value of `_` is a copy, so a reference can't change it | fixtures/reject/src/lib.rs:19:13 | | 2 | a `for` loop over values that drop, which is not supported yet | fixtures/reject/src/lib.rs:76:6 | @@ -71,6 +71,7 @@ The type or module each refused type or path belongs to. | 2 | `Iterator` | fixtures/reject/src/lib.rs:289:2 | | 2 | `Noisy` | fixtures/reject/src/lib.rs:371:16 | | 2 | `char` | fixtures/reject/src/lib.rs:10:18 | +| 2 | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 2 | `std::sync::Arc` | fixtures/reject/src/lib.rs:183:42 | | 2 | `{async closure}` | fixtures/reject/src/lib.rs:121:6 | | 1 | `Boxed` | fixtures/reject/src/lib.rs:97:1 | @@ -82,7 +83,6 @@ The type or module each refused type or path belongs to. | 1 | `std::iter::Chain` | fixtures/reject/src/lib.rs:322:51 | | 1 | `std::ops::Range` | fixtures/reject/src/lib.rs:330:8 | | 1 | `std::option::Option` | fixtures/reject/src/lib.rs:400:4 | -| 1 | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | `std::slice::Iter` | fixtures/reject/src/lib.rs:276:11 | | 1 | `std::slice` | fixtures/reject/src/lib.rs:36:4 | | 1 | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:271:2 | @@ -100,6 +100,7 @@ The type or module each refused type or path belongs to. | 3 | unsupported type `_` | `f64` | fixtures/reject/src/lib.rs:6:1 | | 2 | a `_` binding: a JS value of `_` is a copy, so it can't change | `&mut u32`, `u32` | fixtures/reject/src/lib.rs:19:13 | | 2 | an iterator that owns `_`, which drops, which is not supported yet | `Noisy` | fixtures/reject/src/lib.rs:371:16 | +| 2 | replacing the `_` behind a reference, whose JS object is shared or private | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | `_` is generic and implements `Drop`, which is not supported yet | `Boxed` | fixtures/reject/src/lib.rs:97:1 | | 1 | `_` is not supported: it would be pending two ways with one value | `Poll` | fixtures/reject/src/lib.rs:229:20 | | 1 | `_`: a JS value of `_` is a copy, so a reference can't change it | `&mut std::string::String`, `std::string::String` | fixtures/reject/src/lib.rs:142:16 | @@ -122,7 +123,6 @@ The type or module each refused type or path belongs to. | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::fold` | fixtures/reject/src/lib.rs:289:2 | | 1 | overriding `_`, which std's adaptors call in place of `next` or beside it | `Iterator::size_hint` | fixtures/reject/src/lib.rs:343:2 | | 1 | passing `_`, which drops, to `_`, which is not supported yet | `std::option::Option`, `Option::unwrap_or` | fixtures/reject/src/lib.rs:400:4 | -| 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::pin::Pin` | fixtures/reject/src/lib.rs:261:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::Arc` | fixtures/reject/src/lib.rs:225:2 | | 1 | replacing the `_` behind a reference, whose JS object is shared or private | `std::sync::MutexGuard` | fixtures/reject/src/lib.rs:271:2 | | 1 | unsupported call to `_` | `::cycle` | fixtures/reject/src/lib.rs:276:11 | @@ -147,6 +147,15 @@ The type or module each refused type or path belongs to.
+
replacing the `_` behind a reference, whose JS object is shared or private (4) + +- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:261:2: replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:271:2: replacing the `std::sync::MutexGuard<'_, u8>` behind a reference, whose JS object is shared or private +- fixtures/reject/src/lib.rs:411:2: replacing the `std::pin::Pin<&mut Noisy>` behind a reference, whose JS object is shared or private + +
+
unsupported call to `_` (4) - fixtures/reject/src/lib.rs:36:4: unsupported call to `std::slice::::sort` @@ -188,14 +197,6 @@ The type or module each refused type or path belongs to.
-
replacing the `_` behind a reference, whose JS object is shared or private (3) - -- fixtures/reject/src/lib.rs:225:2: replacing the `std::sync::Arc` behind a reference, whose JS object is shared or private -- fixtures/reject/src/lib.rs:261:2: replacing the `std::pin::Pin>` behind a reference, whose JS object is shared or private -- fixtures/reject/src/lib.rs:271:2: replacing the `std::sync::MutexGuard<'_, u8>` behind a reference, whose JS object is shared or private - -
-
replacing the value behind a reference to `_` (3) - fixtures/reject/src/lib.rs:168:17: replacing the value behind a reference to `Meters` diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index d48f846f3..9cacf4ee6 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -68,6 +68,7 @@ an iterator that owns `Noisy`, which drops, which is not supported yet at fixtur a `for` loop over values that drop, which is not supported yet at fixtures/reject/src/lib.rs:392:6 passing `std::option::Option`, which drops, to `Option::unwrap_or`, which is not supported yet at fixtures/reject/src/lib.rs:400:4 a rest pattern that moves values that drop out of a place, which is not supported yet at fixtures/reject/src/lib.rs:405:14 +replacing the `std::pin::Pin<&mut Noisy>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:411:2 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:289:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:309:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:343:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index 5c32d975e..e672ff31e 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -405,3 +405,8 @@ pub fn rest_moved(pair: [Noisy; 2]) -> u8 { let [first, rest @ ..] = pair; first.0 + rest[0].0 } + +/// A pinned reference is its referent in JS: replacing it would change what it points at. +pub fn replace_pinned_ref<'a>(dst: &mut std::pin::Pin<&'a mut Noisy>, src: std::pin::Pin<&'a mut Noisy>) { + *dst = src; +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index c76d4170d..288b6c4c4 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -51,6 +51,7 @@ roots = [ "looped", "fallback", "rest_moved", + "replace_pinned_ref", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 8eeabcf92..5845a9242 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1803,9 +1803,10 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { }; if through_ref { let pointee = self.ty_of(lhs); - // Every clone of an `Arc` or waker is one JS object, a guard is its mutex, and a - // future keeps its state private: copying fields in would change the other - // handles, or nothing. A `Pin` or `Box` is its pointee in JS. + // Every clone of an `Arc` or waker is one JS object, a guard is its mutex, a + // reference is its referent, and a future keeps its state private: copying fields + // in would change the other handles, or nothing. A `Pin` or `Box` is its pointee + // in JS. let mut erased = pointee; while let ty::Adt(adt, args) = erased.kind() && matches!( @@ -1819,7 +1820,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { library::Std::of(self.t.tcx, adt.did()), Some(library::Std::Arc | library::Std::Waker | library::Std::Context | library::Std::MutexGuard) ), - ty::Coroutine(..) => true, + ty::Ref(..) | ty::Coroutine(..) => true, _ => false, }; match self.t.object_kind(pointee) { From 781a919c8e184d96a92f6e0ed0850b5ef6991959 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:57:01 -0700 Subject: [PATCH 29/30] fix(ts): refuse an array repeat of a value that drops `[v; 0]` drops `v` at once, which no element of the array would. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-drop.md | 6 ++++-- ts/fixtures/reject/census.md | 11 +++++++++-- ts/fixtures/reject/expected.txt | 1 + ts/fixtures/reject/src/lib.rs | 6 ++++++ ts/fixtures/reject/ts.toml | 1 + ts/src/lower/body.rs | 7 +++++++ 6 files changed, 28 insertions(+), 4 deletions(-) diff --git a/quest/m2/ts-drop.md b/quest/m2/ts-drop.md index ccf2a024f..ded21f8bc 100644 --- a/quest/m2/ts-drop.md +++ b/quest/m2/ts-drop.md @@ -34,10 +34,12 @@ ranked by the census of moq-net at the pinned revision (kio's has 28 in all): holds when it is dropped. - A std mapping that may discard an operand that drops (19): `bool::then_some`, `Option::ok_or`, `map_or`, and `unwrap_or`, and `Result::ok`. Each refuses any operand - that drops today, even one it always keeps, such as `ok_or`'s option. + that drops today, even one it always keeps, such as `ok_or`'s option: `keeps_operands` + in `library.rs` should name the operands each mapping may discard instead. - Struct update syntax from a value that drops (16), a closure capturing one (13), a generic type that implements `Drop` (11), a parameter that drops bound by a pattern, - and a rest pattern that moves values that drop out of a place. + a rest pattern that moves values that drop out of a place, and an array repeat of a + value that drops. - A value that drops, moved ahead of an `.await` in the same call (3) or in the place an assignment writes it to, which a cancel would leave in a temporary no scope drops, and an `Arc` or `Mutex` holding a borrow of a value that drops, which JS would drop diff --git a/ts/fixtures/reject/census.md b/ts/fixtures/reject/census.md index e50a96b01..74333ff31 100644 --- a/ts/fixtures/reject/census.md +++ b/ts/fixtures/reject/census.md @@ -1,7 +1,7 @@ # Census of `reject-fixture` -- Refusals: 75 -- Function instances: 65 +- Refusals: 76 +- Function instances: 66 - Generic functions no instance reached, lowered over their type parameters: 3 ## By construct @@ -46,6 +46,7 @@ | 1 | an `.await` in an operand after one that drops, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:190:13 | | 1 | an `.await` in the place an assignment of a value that drops writes to, which is not supported yet: bind the awaited value first | fixtures/reject/src/lib.rs:207:2 | | 1 | an `if let` on a temporary that drops, which it doesn't move out of whole | fixtures/reject/src/lib.rs:241:9 | +| 1 | an array repeat of a value that drops, which is not supported yet | fixtures/reject/src/lib.rs:416:14 | | 1 | an async body returning `_` is not supported: its `Ready` could be pending | fixtures/reject/src/lib.rs:245:54 | | 1 | an async body that borrows `_` mutably, which is no object it can change in place | fixtures/reject/src/lib.rs:113:3 | | 1 | an or-pattern with bindings | fixtures/reject/src/lib.rs:156:3 | @@ -391,6 +392,12 @@ The type or module each refused type or path belongs to.
+
an array repeat of a value that drops, which is not supported yet (1) + +- fixtures/reject/src/lib.rs:416:14: an array repeat of a value that drops, which is not supported yet + +
+
an async body returning `_` is not supported: its `Ready` could be pending (1) - fixtures/reject/src/lib.rs:245:54: an async body returning `std::task::Poll` is not supported: its `Ready` could be pending diff --git a/ts/fixtures/reject/expected.txt b/ts/fixtures/reject/expected.txt index 9cacf4ee6..df3e8e335 100644 --- a/ts/fixtures/reject/expected.txt +++ b/ts/fixtures/reject/expected.txt @@ -69,6 +69,7 @@ a `for` loop over values that drop, which is not supported yet at fixtures/rejec passing `std::option::Option`, which drops, to `Option::unwrap_or`, which is not supported yet at fixtures/reject/src/lib.rs:400:4 a rest pattern that moves values that drop out of a place, which is not supported yet at fixtures/reject/src/lib.rs:405:14 replacing the `std::pin::Pin<&mut Noisy>` behind a reference, whose JS object is shared or private at fixtures/reject/src/lib.rs:411:2 +an array repeat of a value that drops, which is not supported yet at fixtures/reject/src/lib.rs:416:14 overriding `Iterator::fold`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:289:2 an iterator of the crate implementing `DoubleEndedIterator`, which is not supported yet at fixtures/reject/src/lib.rs:309:1 overriding `Iterator::size_hint`, which std's adaptors call in place of `next` or beside it at fixtures/reject/src/lib.rs:343:2 diff --git a/ts/fixtures/reject/src/lib.rs b/ts/fixtures/reject/src/lib.rs index e672ff31e..62ac830ca 100644 --- a/ts/fixtures/reject/src/lib.rs +++ b/ts/fixtures/reject/src/lib.rs @@ -410,3 +410,9 @@ pub fn rest_moved(pair: [Noisy; 2]) -> u8 { pub fn replace_pinned_ref<'a>(dst: &mut std::pin::Pin<&'a mut Noisy>, src: std::pin::Pin<&'a mut Noisy>) { *dst = src; } + +/// `[n; 0]` drops `n` at once, which no element of the array would. +pub fn repeated(n: Noisy) -> usize { + let empty = [n; 0]; + empty.len() +} diff --git a/ts/fixtures/reject/ts.toml b/ts/fixtures/reject/ts.toml index 288b6c4c4..21325e271 100644 --- a/ts/fixtures/reject/ts.toml +++ b/ts/fixtures/reject/ts.toml @@ -52,6 +52,7 @@ roots = [ "fallback", "rest_moved", "replace_pinned_ref", + "repeated", "missing", ] printable = ["Meters"] diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 5845a9242..f95274d41 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -2240,6 +2240,13 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { None => return self.err(span, "an array length that is not a constant"), }; let elem_ty = self.ty_of(*value); + // `[v; 0]` drops `v` at once, which no element of the array would. + if self.t.drops(elem_ty) { + return self.err( + span, + "an array repeat of a value that drops, which is not supported yet", + ); + } let v = self.operand(*value, out); match elem_ty.kind() { ty::Uint(ty::UintTy::U8) => { From b2965a4c969ec02121f708f6afb0aa8ebff61711 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sat, 24 Oct 2026 11:11:09 -0700 Subject: [PATCH 30/30] fix(ts): keep a move inside the arm of a `match` or `if` that takes it An expression that moves a value that drops clears its place with a statement of its own, so it is not simple enough for `?:`: both arms' statements would run, and the second would read the `undefined` the first left. The task fixture's `blocks` moves a guard on each arm of a `match`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/fixtures/task/expected/model.ts | 66 +++++++++++++++++++----------- ts/fixtures/task/src/model.rs | 7 ++++ ts/src/lower/body.rs | 28 ++++++++----- 3 files changed, 68 insertions(+), 33 deletions(-) diff --git a/ts/fixtures/task/expected/model.ts b/ts/fixtures/task/expected/model.ts index 663210be8..e027632a7 100644 --- a/ts/fixtures/task/expected/model.ts +++ b/ts/fixtures/task/expected/model.ts @@ -271,36 +271,56 @@ export function* blocksBody(_taskContext: rt.Context, rx: Consumer, guard: Guard cycle = undefined!; const _nested = new Inner({ outer: cycle2 }); try { - if (moves2) { - const guard22 = guard2; - guard2 = undefined!; - rt.drop(rt.future(blocksBody$5, blocksDrop$2, guard22)); - } - const first2 = first; - first = undefined!; - const second2 = second; - second = undefined!; - const rx22 = rx2; - rx2 = undefined!; - let read_ = rt.future(blocksBody$6, blocksDrop$3, first2, second2, rx22); + let third = Guard.new(rt.u32.add(guard2.id, 400), guard2.log.clone()); try { - const read2 = read_; - read_ = undefined!; - let __awaitee4: rt.Future = read2; + let chosen: Guard = undefined!; try { - while (true) { - const poll4 = __awaitee4.poll(_taskContext); - if (poll4 !== rt.Pending) { - const result4 = poll4; - return result4; + if (moves2) { + const third2 = third; + third = undefined!; + chosen = third2; + } else { + const third3 = third; + third = undefined!; + chosen = third3; + } + chosen.note("chosen"); + if (moves2) { + const guard22 = guard2; + guard2 = undefined!; + rt.drop(rt.future(blocksBody$5, blocksDrop$2, guard22)); + } + const first2 = first; + first = undefined!; + const second2 = second; + second = undefined!; + const rx22 = rx2; + rx2 = undefined!; + let read_ = rt.future(blocksBody$6, blocksDrop$3, first2, second2, rx22); + try { + const read2 = read_; + read_ = undefined!; + let __awaitee4: rt.Future = read2; + try { + while (true) { + const poll4 = __awaitee4.poll(_taskContext); + if (poll4 !== rt.Pending) { + const result4 = poll4; + return result4; + } + _taskContext = yield; + } + } finally { + rt.drop(__awaitee4); } - _taskContext = yield; + } finally { + rt.drop(read_); } } finally { - rt.drop(__awaitee4); + rt.drop(chosen); } } finally { - rt.drop(read_); + rt.drop(third); } } finally { rt.drop(_nested); diff --git a/ts/fixtures/task/src/model.rs b/ts/fixtures/task/src/model.rs index 82eaae1e9..8d54111dd 100644 --- a/ts/fixtures/task/src/model.rs +++ b/ts/fixtures/task/src/model.rs @@ -120,6 +120,13 @@ pub async fn blocks(mut rx: Consumer, guard: Guard, moves: bool) -> u64 { let _nested = Inner { outer: Some(Box::new(cycle)), }; + // A move on each arm of a `match` simple enough to be an expression. + let third = Guard::new(guard.id + 400, guard.log.clone()); + let chosen = match moves { + true => third, + false => third, + }; + chosen.note("chosen"); if moves { drop(async move { guard.note("moved") }); } diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index f95274d41..12afe0c62 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -834,7 +834,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { /// Whether `id` is control flow that reads best delivering into a variable. One that /// never makes a value leaves the variable unassigned. - fn needs_dest(&self, id: ExprId) -> bool { + fn needs_dest(&mut self, id: ExprId) -> bool { match &self.thir[id].kind { ExprKind::Scope { value, .. } => self.needs_dest(*value), ExprKind::If { @@ -849,24 +849,32 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { } /// Whether `id` lowers to an expression with no statements before it. - fn simple(&self, id: ExprId) -> bool { + fn simple(&mut self, id: ExprId) -> bool { + self.simple_at(id, false) + } + + /// [`Self::simple`], for `id` read as a place, which a move out of would clear. + fn simple_at(&mut self, id: ExprId, place: bool) -> bool { + // A move leaves `undefined` behind with a statement of its own. + if !place && self.moves(id) { + return false; + } match &self.thir[id].kind { ExprKind::Scope { value, .. } | ExprKind::ValueTypeAscription { source: value, .. } - | ExprKind::PlaceTypeAscription { source: value, .. } - | ExprKind::Borrow { arg: value, .. } + | ExprKind::PlaceTypeAscription { source: value, .. } => self.simple_at(*value, place), + ExprKind::Borrow { arg: value, .. } | ExprKind::Deref { arg: value } - | ExprKind::Cast { source: value } + | ExprKind::Field { lhs: value, .. } => self.simple_at(*value, true), + ExprKind::Cast { source: value } | ExprKind::PointerCoercion { source: value, .. } - | ExprKind::Field { lhs: value, .. } | ExprKind::Unary { arg: value, .. } => self.simple(*value), ExprKind::Block { block } => { let block = &self.thir[*block]; block.stmts.is_empty() && !block.targeted_by_break && block.expr.is_some_and(|e| self.simple(e)) } - ExprKind::Binary { lhs, rhs, .. } | ExprKind::Index { lhs, index: rhs } => { - self.simple(*lhs) && self.simple(*rhs) - } + ExprKind::Binary { lhs, rhs, .. } => self.simple(*lhs) && self.simple(*rhs), + ExprKind::Index { lhs, index } => self.simple_at(*lhs, true) && self.simple(*index), ExprKind::LogicalOp { lhs, rhs, .. } => self.simple(*lhs) && self.simple(*rhs), ExprKind::Call { args, fun, .. } => self.simple(*fun) && args.iter().all(|a| self.simple(*a)), ExprKind::Tuple { fields } | ExprKind::Array { fields } => fields.iter().all(|f| self.simple(*f)), @@ -1394,7 +1402,7 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { /// Whether a `match` reads as a ternary chain: no bindings or guards, and arms that /// are each a simple value. - fn ternary_match(&self, id: ExprId) -> bool { + fn ternary_match(&mut self, id: ExprId) -> bool { let ExprKind::Match { arms, .. } = &self.thir[self.strip(id)].kind else { return false; };