Skip to content

feat(ts): async fns as generators and drops from THIR scopes, from the async spike - #16

Merged
kixelated merged 39 commits into
mainfrom
quest/m2/ts-async-spike
Oct 24, 2026
Merged

kixelated merged 39 commits into
mainfrom
quest/m2/ts-async-spike

Conversation

@kixelated

@kixelated kixelated commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes the async and drop spike quest.

Problem

rust2-ts refused async and every type that implements Drop, and kio, which moq-net's model is built on, is all futures, wakers, and channels that close when their last producer drops. How to lower async (generators from THIR, or state machines from MIR after rustc's coroutine transform), where drop points come from, and whether the whole lowering should move to MIR all hinged on one THIR-versus-MIR question, so the spike built both on the same kio-shaped channel and measured them.

Approach

  • Harness: a new task fixture trims kio to what its futures hinge on: Waiter holding the task's waker in an Arc that WaiterLists hold weakly, Park, wait, and a channel that closes when its last producer drops, under async fns holding guards across awaits, at await depths 1, 4, and 16, and async blocks that borrow a guard, move one on one path only, or own one they only borrow. A deterministic FIFO executor in Rust (exec.rs, with a hand-made waker vtable) and in TS (tests/task.ts) each run a script of spawns, sends, closes, polls, and drops, and log every poll, wake, waker clone and drop, and guard drop. differential.ts requires the logs to match byte for byte: 35,280 scripts (535 panicking), seven of them named for the quest's cases (a never-polled future does nothing and drops its arguments, a future dropped mid-await drops in Rust's order, a poll after Ready panics, an async block drops only what it owns).
  • Prototype A, generators from THIR (landed): an async fn returns rt.future(body, drop, ...upvars). The body is a module-level function* taking the upvars as parameters; .await falls out of the existing match and loop lowering as a poll loop around yield. rt.future starts the generator at the first poll, drops the upvars if it never ran, returns the generator through its finally blocks if dropped while suspended, and panics on a poll after completion, as rustc's coroutines do.
  • Prototype B, MIR state machines (measured, then deleted): each async body's future was a class of its upvars and saved locals, its poll the transform's resume function and its dispose the drop shim, each a loop over a switch on the basic block, with calls, types, closures, and formatting through the THIR lowering's helpers.
  • Drops, shared by both: a class that drops gets [Symbol.dispose] (its Drop impl, then its fields); a variable drops in a finally at the end of its scope; a move leaves undefined behind. rt.Arc, rt.Weak, and rt.Mutex give kio's waiters exact strong counts. Whatever the spike did not cover fails with its span (the reject fixture has one of each).
  • Executor integration: rt.spawn(future) returns a promise, polls woken tasks in a batch from one queueMicrotask, and yields to a macrotask after 128 polls.
  • Bench: just ts bench gains an async handoff: a value sent to a task parked on the channel, which wakes it and reads it through 1, 4, or 16 async functions. It runs natively, as wasm32, translated (polled at once, and on rt.spawn), and hand-written with promises and async/await as moq's TS writes it.

Results

Local run with both prototypes, on a host shared with other builds (Ryzen 9 5900XT). Nanoseconds per handoff, medians of 15 samples; Chromium's spread was 1-10%, Node's and Bun's up to 50%.

engine depth native wasm hand-written generators state machines generators ÷ machines
Chromium 155 1 56 113 170 371 263 1.41
Chromium 155 4 61 146 313 643 336 1.91
Chromium 155 16 78 196 920 2290 879 2.61
Node 24.21 1 56 139 213 468 331 1.42
Node 24.21 4 61 147 467 824 436 1.89
Node 24.21 16 78 209 1270 2520 1130 2.23
Bun 1.4.2 1 56 114 370 844 402 2.10
Bun 1.4.2 4 61 118 471 1070 440 2.44
Bun 1.4.2 16 78 160 1260 4270 1140 3.75
  • Speed: state machines are 1.4-2.6x faster per handoff than generators in Chromium and Node, and on par with hand-written promises. Generators are about 2x hand-written promises. Both are far behind WASM (113-209 ns). On rt.spawn a handoff costs about 0.3-0.7 µs more in Node and 1.1-1.2 µs more in Chromium: the microtask hop.

  • A generator pitfall: a function* expression evaluated per call costs V8 a fresh prototype object and generator shape each time: about 800 ns per generator against 33 ns for one made once. Hoisting the body to a module-level function cut the generators' handoff from 2.0 to 0.5 µs at depth 1, and from 16.6 to 3.0 µs at depth 16 (Node, before the bench).

  • Size: minified, the fixture's translation is 18.3 KB (5.6 KB gzip) with generators and 32.4 KB (6.6 KB gzip) with state machines; the WASM is 29.8 KB (12.4 KB gzip). Unminified, the generators' TS is 934 lines against the state machines' 3,006.

  • Correctness: both prototypes passed every script with zero differences.

  • Cost to build: the generator lowering is about 150 lines on the THIR lowering, plus 80 in the runtime. The state machines took 999 lines for async bodies alone, re-implementing places, rvalues, constants, closures, and format_args!'s template decoding at the MIR level, and every construct an async body can hold would need it again.

  • Readability: generators keep the source's loops, matches, and names; each .await is a poll loop of about ten lines. The state machines read as basic blocks: 45 let _N declarations for sum's 10 lines, and a switch no structurizer can remove, since the transform's resume dispatch jumps into the middle of loops.

  • Census (just ts census at the pinned moq revision): kio and moq-net no longer refuse any async fn. kio has 28 refusals left about drops; moq-net's lead with dropping a Result, Option, Poll, enum, or tuple whose payload drops (657), methods taking a droppable self by value (155), and borrowed temporaries that drop (152), then for loops over values that drop (60), iterators that own one (55), and std mappings that may discard one (19), counted after merging main through feat(ts): wide integers are numbers while safe, and each integer type is branded #26. The rewritten quests rank the rest.

Decisions

  • Maintainer, on merging: merge the generators-from-THIR verdict now, and plan a follow-up spike that ports the lowering to MIR and measures bundle size and exact drops. The priorities are correctness first, speed second, bundle size third, and readability a non-goal. That ordering discounts the readability argument below and puts weight on the state machines' speed, and the MIR spike will revisit drop points from THIR scopes.
  • Async: generators from THIR. State machines are faster, but at moq's message rates (thousands per second) the 0.1-1.4 µs per handoff they save is noise, while generators reuse the whole THIR lowering inside async bodies, read like the source, and ship smaller.
  • Drop points: from THIR's scopes, as landed. MIR's drop elaboration is exact by construction, but only for a MIR lowering: nothing ties MIR's temporaries back to THIR's expressions, so reading its drops beside the THIR lowering would be fragile. Under wasm32's panic=abort, MIR also has no cleanup paths, so a JS exception would skip drops that THIR's finally blocks run.
  • The whole lowering stays on THIR. Moving it would trade readable output for exactness the differential tests already prove, at the cost of a structurizer, expression reconstruction, and naming before it read as well.

Drop and Async are rewritten to these, with what the spike left refused; Shared ownership to what remains after rt.Arc, rt.Weak, and rt.Mutex.

Impact

  • Translator output: types that drop get [Symbol.dispose] and drop where Rust drops them; async fns return rt.Future<T>; Poll<T> is T | typeof rt.Pending (refused, as an Option is, when its payload can already be pending, through Option, Box, Pin, or a reference); Arc, Weak, Mutex, MutexGuard, Waker, and Context map to rt/task.ts, and a Pin drops as its pointer does. The Drop and Async quests own this output until they finish.
  • Runtime: new rt/task.ts, re-exported from rt.ts and written beside it: drop, dropAll, Arc, Weak, Mutex, Pending, Poll, Waker, Context, Future, future, and spawn. runtime/tsconfig.json adds esnext.disposable for Symbol.dispose.
  • Tests: new task fixture and tests/task.ts; differential.ts runs a harness's own cases and prints a text output as text. tests/runtime.rs runs tests/spawn.ts, which checks rt.spawn's poll budget and its rejection on a panic in drop.
  • Bench: the handoff workload, and a --task, --task-wasm, and --task-native route for bench/main.ts. The fixtures share fixtures/bench.rs as their native route.
  • The reject fixture swaps Guard and later, which now translate, for each new refusal, including an Arc of a borrow of a value that drops, a value that drops moved ahead of an .await in the same call or assignment, and a let, match, or if let that binds only part of a temporary that drops (Some(..) included).
  • Iterators (from main's feat(ts): translate iterators through a DONE protocol #23) that own a value that drops are refused, since an rt.Iter drops nothing it skips, consumes, or holds: into_iter or once of one, any adaptor but the crate's own next over items that drop, and a for loop over an iterator that drops. The reject fixture has one of each.
  • A std mapping that takes a value that drops by value is refused unless it moves every such operand into its result or a closure (unwrap_or, ok_or, map_or, then_some, and Result::ok may discard one), as are replacing a MutexGuard or a pinned reference through a reference, a field read through a Box made in place, a rest pattern that moves values that drop out of a place, and an array repeat of a value that drops.
  • The task fixture's executor and the bench's translated routes make and read u64s through rt.u64, since main's feat(ts): wide integers are numbers while safe, and each integer type is branded #26 made them numbers while safe.
  • A match or if whose arm moves a value that drops lowers to statements rather than ?:, so the move happens only on the arm taken; the task fixture's blocks covers it.
  • Fixed in passing, since the fixture needed them: an explicit self: Pin<&mut Self> is the method's this, and a ValueExpr delivers to its destination. Merging main's tail loops (feat(ts): translate loops that only return leaves #14), breaks_out also looks inside the try blocks drops add, so a loop broken inside a drop scope still ends its match arm.

Alternatives

  • Eager async/await: out, decided with the maintainer, since it breaks laziness, poll order, and cancel-by-drop.
  • A generator closure per call: about 25x the cost of a hoisted one in V8, as measured above.
  • Drop points read from MIR beside the THIR lowering: rejected above.
  • Unwinding into MIR's cleanup blocks with try/catch: not tried, since the target's panic=abort builds none.

Follow-ups

  • A pass proving a variable moved on every path, or on none, would drop most undefined! writes and try/finally blocks; the Drop quest says to measure it first.
  • yield* between translated futures would skip each await level's poll; the Async quest names it if a profile finds await overhead.
  • ts-tail-loop will lift the tail loop the fixture's drain avoids.
  • keeps_operands refuses every operand that drops, even one a mapping always keeps (ok_or's option); the Drop quest says to name the discarded operands per mapping instead.
  • bench/task.ts's Fixture.spawn<T> does not type-check against rt.spawn (its poll result includes the pending symbol). Bun bundles the bench without tsc, so nothing fails; a typed harness should fix it when it next changes.

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

kixelated and others added 9 commits October 23, 2026 22:53
Quest-Claim: b76999a56b3a7148
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Both prototypes pass the task fixture's trace differential test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…ter that drops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
# Conflicts:
#	ts/README.md
#	ts/fixtures/reject/census.md
#	ts/tests/differential.ts
#	ts/tests/fixtures.rs
@kixelated kixelated changed the title Async and drop lowering spike feat(ts): async fns as generators and drops from THIR scopes, from the async spike Oct 24, 2026
@kixelated
kixelated marked this pull request as ready for review October 24, 2026 07:31
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T18:27:30.705666Z d51a5d7 New commits
🔒 Security Review ✅ Completed 2026-10-24T18:28:15.250459Z d51a5d7 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d64f666d96

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +2326 to +2327
let ty = self.subst(capture.place.ty());
let by_value = matches!(capture.info.capture_kind, ty::UpvarCapture::ByValue);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve borrowed ownership when capturing an async block

For a non-move async block borrowing a droppable local, capture.place.ty() is the local's value type, not the captured reference type. That type is subsequently used to generate the unresumed future's drop callback, so let a = Arc::new(1); let f = async { Arc::strong_count(&a) }; drop(f); decrements a's strong count even though Rust only drops a reference. The unconditional disown also removes the actual owner's cleanup. Preserve the capture mode when deciding whether to transfer ownership and generate capture drops; cancelling a borrowing future must not destroy the borrowed value.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: native Rust dropped g200 only when the block that owns it finished. The translation dropped it when the borrowing block was cancelled. Fixed in abc7c4c: the owner keeps a by-reference capture, and the future never drops it. model::blocks in the task fixture covers it, and the differential test runs it against native Rust.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs Outdated
Comment on lines +2366 to +2367
// The future owns what it captures, so here drops none of it.
self.disown(&name);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Transfer async captures on the executed path only

When an owning async block is created conditionally, disown removes its captured local from all enclosing drop scopes while translating the branch, regardless of whether that branch executes. For example, let a = Arc::new(1); if flag { drop(async move { Arc::strong_count(&a) }); } must still drop a at scope exit when flag is false, but the generated cleanup has already been removed, leaking the strong reference and suppressing its eventual destructor. Keep the enclosing cleanup and clear the captured place on the actual capture path, as ordinary moves already do.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Fixed in abc7c4c: an async block now moves each capture it owns out of its place, as any other move does. The owner keeps its cleanup, which drops undefined on the paths that moved it. model::blocks creates such a block only when moves is set, and both paths match native Rust. An async fn still hands its arguments over whole, since its block is the whole function body and always runs.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs
Comment on lines +2391 to 2394
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register owned async-block captures for generator cleanup

For an async move block that only borrows its owned capture inside the body, the capture is never registered with own in the generator's scope. For example, polling async move { Arc::strong_count(&a) } to completion must drop the captured Arc, but this lowering emits no cleanup for it: the capture-drop callback only runs before the first poll, and disposing a returned Async does nothing. The same omission affects cancellation while suspended when the capture has not moved into another owned binding. Register by-value captures for generator cleanup as well as unresumed cleanup, leaving moved-out captures empty to prevent double drops.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced. Fixed in abc7c4c: a block's generator now owns its by-value captures, so they drop when it returns or is cancelled while suspended. They drop in capture order, after its locals, as in native Rust. My first attempt reversed that order, and the differential test caught it. An async fn needs no change: rustc moves each argument into a local at the top of the body, and that local already drops it.

(written by Opus 5.5)

kixelated and others added 2 commits October 24, 2026 00:49
…es 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fdfa210f27

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/runtime/rt/task.ts
Comment on lines +39 to +40
[Symbol.dispose](): void {
if (--this.strong === 0) drop(this.value);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve borrowed ownership when dropping an Arc payload

When the payload is a reference to a disposable value, this drops the referent rather than the reference. For example, let a = Arc::new(1); let b = Arc::new(&a); drop(b); must leave Arc::strong_count(&a) at 1, but Arc::new lowers both owned and borrowed payloads to the same runtime representation, and this unconditional drop(this.value) reduces it to 0. This can prematurely run the referent's destructor and invalidate later weak upgrades. Carry payload-specific drop behavior into the runtime, or reject payload types whose ownership cannot be represented.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Before this fix, Arc::new(&n) with n: Noisy translated without any error, and dropping the last count would have dropped n. Fixed in cd567b5 by refusing it rather than carrying per-payload drops into the runtime. A holder that drops its contents through [Symbol.dispose] (an Arc, a Mutex, or a generic class's glue) now requires contents whose JS drop is exact. A borrow of a value that drops is its referent in JS, so it fails with its span. The same check catches a generic struct instantiated with such a borrow, such as Pair<Noisy, &Noisy>. The reject fixture's shared_borrow covers it. The census finds none in moq-net or kio.

(written by Opus 5.5)

Comment thread ts/runtime/rt/task.ts Outdated
Comment on lines +190 to +191
function run(): void {
scheduled = false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the scheduler marked active while draining its queue

For a future that wakes itself during poll, clearing scheduled here lets Task.schedule() enqueue another microtask while this batch is still running. After 128 polls, the queued microtask runs before the intended setTimeout continuation and repeats this indefinitely, starving timers and I/O despite the poll budget. A bounded reproduction with 1,000 self-waking polls completes all 1,000 before an already-scheduled timer runs. Keep the active batch marked scheduled and clear that state only when the queue has drained.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: a future that wakes itself ran all 1,000 polls before a timer queued ahead of it. Fixed in 776680c: scheduled stays set until the queue drains (in a finally, so a rethrown non-Panic error can't wedge it). Now the timer runs after 128 polls. tests/spawn.ts, run by tests/runtime.rs, fails on the old runtime and passes on the new one.

(written by Opus 5.5)

Comment thread ts/src/lower/drop.rs
Comment on lines +279 to +282
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Track cleanup for moved operands until ownership is transferred

When a later call argument panics, an earlier moved argument has already been cleared from its original place, but the temporary created here has no cleanup registration. For example, in consume(guard, fail()), where guard implements Drop and fail() panics, Rust drops the already-evaluated first argument during unwinding. The generated code instead leaves the enclosing finally dropping undefined, never enters consume, and leaks the guard. The same gap affects partially evaluated struct construction. Track ownership of these operand temporaries until the receiving call or aggregate takes ownership.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly agreed.

The panic path is not a divergence on this target. The translator builds for wasm32-unknown-unknown, which is panic=abort, so native Rust runs no drops at all after fail() panics. The differential test compares only the panic message.

A later operand that awaits is a real divergence, though: keep(held, rx.recv().await) moved held into a temporary before the yield, and cancelling the future then leaked it. I reproduced it in the task fixture (1,887 log differences). Owning that temporary until the call takes it would need a declaration at its scope's top level, which operands can't guarantee. So 90da987 refuses an operand that drops ahead of an .await in the same call, with its span (3 in moq-net, none in kio). The reject fixture's held_across covers it, and the Drop quest lists it for a real fix.

(written by Opus 5.5)

kixelated and others added 5 commits October 24, 2026 01:00
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
… 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…typed 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 90da987056

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Drop wildcard elements of destructured temporaries

For let [first, _] = [Guard::new(1), Guard::new(2)];, where Guard implements Drop, this path registers cleanup only for first; destructure_elem emits a hole for _, and nothing owns or drops the skipped temporary element. Native Rust drops the second guard at the end of the declaration, but the translation never runs its destructor. Preserve cleanup for unmatched elements of temporary aggregates, or reject these patterns until that cleanup is supported.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and it reached further than temporaries. let [kept, _] = pair on a place also moved pair out whole through the destructuring shortcut, so the skipped guard never dropped. I reproduced that in the task fixture (native drops g20, the translation never did).

Fixed in 9cc359a:

  • A place bound only in part now takes the field-by-field path. That path clears what it moves and leaves the rest for the place's scope to drop. turns in the task fixture covers it differentially.
  • A temporary bound only in part (under a _, a .., an unnamed field, or another variant of a let ... else) fails with its span, as a match or if let on one already does. The reject fixture's skipped covers it. The census finds 27 in moq-net and none in kio, and the Drop quest counts them.

(written by Opus 5.5)

Comment thread ts/src/lower/drop.rs
Comment on lines +188 to +191
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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Run field cleanup when a destructor panics

When a struct's Drop::drop panics, native Rust still drops its fields while unwinding. The generated disposal method instead emits the destructor call followed by ordinary field-drop statements, so the exception skips every field cleanup. The same problem skips later fields when an earlier field's destructor panics. Generate unwind-safe cleanup around these calls so owned resources are released in Rust's field order even on the error path.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this diverges from native Rust on this target. The translator builds for wasm32-unknown-unknown, which is panic=abort. A panicking Drop::drop aborts there, without unwinding, so native Rust drops none of the remaining fields either. The differential test compares only the panic message on that path, and it already matches. Running the remaining fields' drops after a panic would add behavior the native build doesn't have, and a try/finally per field in every class's glue. If the target ever unwinds, this belongs in the Drop quest with the rest of the unwind paths.

(written by Opus 5.5)

Comment thread ts/runtime/rt/task.ts Outdated
Comment on lines +239 to +240
future[Symbol.dispose]();
this.#resolve(output);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject the spawn promise when completed-future disposal panics

If a custom future returns Ready and its destructor panics, disposal runs outside the try that handles polling errors. Consequently, rt.spawn neither resolves nor rejects its promise and instead throws an uncaught exception from the scheduler. A runtime reproduction with poll() { return 1; } and a disposer calling rt.panic('drop failed') leaves the promise pending. Include disposal in task error handling so destructor panics reject the promise just like polling panics.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: the promise stayed pending. Fixed in ac957b7: disposing a finished future now runs inside the same try as its poll, so a panic there rejects the promise. tests/spawn.ts now checks this too. It fails on the old runtime and passes on the new one.

(written by Opus 5.5)

kixelated and others added 2 commits October 24, 2026 01:23
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9cc359ae68

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs Outdated
PatKind::Binding {
mode, subpattern: None, ..
} => mode.0 == rustc_hir::ByRef::No,
PatKind::Variant { subpatterns, .. } => subpatterns.iter().all(|f| takes_all(&f.pattern)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for omitted variant fields in temporary-drop checks

For if let Some(..) = Some(a.clone()) {}, with a: Arc<_>, THIR represents Some(..) with an empty subpatterns list, so this returns true even though the payload never moves into a binding. Both cond_part and match_ consequently accept the temporary, but neither registers cleanup for its unmatched payload. The cloned strong reference leaks after the conditional instead of dropping as in Rust. Check omitted fields as well as explicit subpatterns before declaring that a pattern consumes the whole temporary.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: in the task fixture, native Rust dropped the guard in Some(..) = Some(guard) and the translation never did. Fixed in 32a2864: takes_all now requires a variant pattern to name every field, so Some(..) on a temporary that drops fails with its span, like any other partial move. The reject fixture's unnamed covers it. The census finds 3 in moq-net and none in kio.

(written by Opus 5.5)

Comment thread ts/src/lower/drop.rs Outdated
Comment on lines +37 to +40
Some(Std::Option | Std::Result | Std::Box | Std::Vec | Std::Mutex | Std::Poll) => {
args.types().any(|t| self.drops(t))
}
Some(_) => false,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate ownership through owning Pin wrappers

For an owning wrapper such as Pin::new(Box::new(a.clone())), where a: Arc<_>, Std::Pin falls through to Some(_) => false. Although the new mappings accept this construction and erase both wrappers to their contents, scope cleanup and explicit drop consequently treat the pinned value as non-dropping, leaking the cloned strong reference. Determine whether a Pin<P> drops from its pointer type, while retaining non-owning behavior for Pin<&mut T>, and support or explicitly reject its drop operation.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: the guard in Pin::new(Box::new(guard)) never dropped. Fixed in 32a2864: Pin<P> now drops exactly when P does, and through the same [Symbol.dispose], since its JS value is the pointee. Pin<&mut T> still doesn't drop. turns in the task fixture now pins a boxed guard, and it drops where native Rust drops it across all 35,280 scripts.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs
Comment on lines +1658 to +1660
// The old value drops once the new one is made.
let lty = self.ty_of(lhs);
if self.t.drops(lty) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain assignment-value cleanup while its destination awaits

In an async function executing values[next_index().await] = guard, where guard implements Drop and the index future suspends, assign first moves guard into an unregistered temporary and clears its original binding. Cancelling during the left-hand-side await therefore drops neither that temporary nor the guard, unlike Rust. The new suspension check in operands only covers operand lists; assign independently lowers the destination through place, so that rejection does not protect this path. Keep the replacement value owned until assignment completes, or reject suspension while evaluating its destination.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: slots[slot(&mut rx).await] = spare translated, and cancelling during the index's .await leaked spare (1,890 differences in the task fixture). Fixed in 32a2864 by refusing it, as with an operand ahead of an .await. Owning the value until the write would need a declaration at its scope's top level. The reject fixture's assigned covers it, the Drop quest lists it, and the census finds none in moq-net or kio.

(written by Opus 5.5)

…tern skips

- `Pin<P>` 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs Outdated
Comment on lines +544 to +549
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve ownership when lowering simple ref bindings

For let ref r = g, where g is an Arc or another droppable value, self.moves(init) is true even though the binding borrows its initializer. This path therefore clears g, while r receives no cleanup because owns is false. At scope exit neither binding drops the value. For example, after { let g = a.clone(); let ref r = g; Arc::strong_count(r); }, the translated strong count of a remains 2 instead of returning to 1. Lower by-reference initializers as borrowed places without moving or clearing them.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced in the task fixture: after let ref borrowed = held, native Rust dropped held and the translation never did. A related case also leaked: let ref extended = Guard::new(..), whose temporary Rust keeps alive to the end of the block and then drops. Fixed in 724435b: a ref binding of a place now reads the place without moving or clearing it. A ref binding of a temporary owns that temporary, so it drops at the end of the block. turns covers both, and the 35,280 scripts match native Rust.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs Outdated
Comment on lines +575 to +579
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);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Evaluate wildcard initializers without moving their places

When a wildcard initializer is a droppable place, this branch returns without evaluating it at all. For let _ = guards[index()];, Rust executes index() and performs the bounds check without moving or dropping the selected guard, but the translation omits both operations. This can suppress observable side effects and out-of-bounds panics. Evaluate the place without transferring ownership rather than skipping its evaluation.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: let _ = spares[pick(log, i)] never ran pick in the translation. Fixed in 724435b: a place under let _ is now evaluated as an expression statement when it isn't a plain path, so its index runs and checks its bounds. Nothing moves or drops. turns covers it.

(written by Opus 5.5)

kixelated and others added 2 commits October 24, 2026 05:05
… 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
# Conflicts:
#	quest/m2/README.md
#	ts/README.md
…cursive 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: afed30f16f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs Outdated
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Account for unmatched variants in temporary if let scrutinees

For if let None = Some(a.clone()) {}, where a is an Arc, takes_all(None) returns true because None has no fields. This therefore accepts the temporary, but the failed pattern test neither transfers its payload into a binding nor registers cleanup for it. The cloned strong reference leaks, leaving the count at 2 instead of Rust's 1. Account for the failed-match path as well as the matched variant's fields, or reject this case until temporary cleanup is supported.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: if let None = Some(make()) translated without an error, and the failed test's payload never dropped. Fixed in a013edf: an if let or let chain on a temporary that drops now asks leaves_drop, the check let uses, instead of takes_all. leaves_drop also requires the variants the pattern doesn't match to hold nothing that drops. It is exact where takes_all was conservative, so moq-net has 6 fewer if let refusals (patterns that bind every part that drops, which now own those parts). The reject fixture's unmatched covers it.

(written by Opus 5.5)

Comment thread ts/src/lower/mod.rs
}
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject async outputs that collide with the pending sentinel

For async { Poll::<u32>::Pending }, the coroutine type becomes Future<Poll<u32>> without checking whether its output can erase to rt.Pending. The generator completes with that sentinel, so Async.poll reports pending instead of Ready(Pending): rt.spawn remains unresolved, and another poll panics because the future is already marked returned. The explicit nested-Poll check in adt_ty does not cover this implicit outer poll. Apply the same output-representation check to coroutine return types, including erased wrappers, or preserve a distinct ready representation.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: async fn pending_output() -> Poll<u8> { Poll::Pending } translated without an error. Fixed in a013edf: an async body whose output can already erase to rt.Pending now fails with its span. This uses the erases_to check that Poll and Option use, so it sees through Option, Box, Pin, and references. The reject fixture's pending_output covers it, and the census finds none in moq-net or kio.

(written by Opus 5.5)

…fuse 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<Poll<T>>` is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a013edf4d3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +2019 to +2021
if self.moves(id) {
let place = self.place(id, out);
return self.move_out(place, span, out);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve owning pointers when lowering dereference places

When reading through a Box<T> whose pointee drops, place lowers Deref { arg } by calling expr(arg), so this new move handling clears the box even though Rust is only accessing its pointee. For example, with a droppable Guard { n: u32 }, let b = Box::new(Guard { n: 7 }); let x = b.n; let y = b.n; clears b during the first field read, makes the second read throw, and leaves the enclosing cleanup dropping undefined instead of the guard. Lower the pointer as a borrowed place when accessing its pointee, reserving ownership transfer for an actual move.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: reading boxed.id twice threw TypeError: Cannot read properties of undefined in the translation, in 3,209 scripts. Fixed in c4e01e7: place now lowers a Deref of a place whose pointer drops (a Box) by reading the pointer in place instead of moving it. A real move out of *b still goes through move_out and consumes the box. turns in the task fixture covers it, and the 35,280 scripts match native Rust. The census has 2 fewer refusals in moq-net.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs
Comment on lines +1190 to +1194
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply temporary-drop checks to ternary matches

For a match used as an expression with simple, binding-free arms, expr calls ternary directly and bypasses this temporary-drop check. Consequently, let matched = match Some(a.clone()) { Some(_) => true, None => false };, with a: Arc<_>, evaluates the clone and tests it without registering or emitting its cleanup. The strong count remains 2 after the match instead of returning to Rust's 1. Apply the same rejection to the ternary path, or arrange cleanup of its temporary scrutinee.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: let matched = match Some(make()) { Some(_) => 1, None => 0 }; translated without an error. Fixed in c4e01e7: ternary now applies the check match makes, refusing a temporary that drops with its span, since its arms bind nothing. The reject fixture's tested covers it, and the census count is unchanged.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs Outdated
Comment on lines +1716 to +1720
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)
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Check erased Pin payloads before replacing borrowed handles

For fn replace(dst: &mut Pin<Arc<u32>>, src: Pin<Arc<u32>>) { *dst = src; }, the immediate pointee is Pin, so this check allows replacement through Object.assign. Both Pin values erase to their underlying runtime Arc objects, however, so replacing a pinned clone overwrites the allocation shared with the original owner. With let a = Arc::new(1); let mut b = Pin::new(a.clone()); replace(&mut b, Pin::new(Arc::new(2)));, the original a consequently reads 2 rather than 1. The fresh case is the supported, payload-erasing Pin wrapper bypassing the direct-Arc rejection; inspect that erased payload too, or reject this replacement.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and reproduced: *dst = src through &mut Pin<Arc<u8>> translated without an error. Fixed in c4e01e7: the shared-object check now looks through Pin and Box, which are their pointee in JS, before deciding. Replacing a pinned or boxed Arc, waker, context, or future through a reference fails with its span. The reject fixture's replace_pinned covers it.

(written by Opus 5.5)

kixelated and others added 3 commits October 24, 2026 06:11
…usal 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<Arc<_>>` through a reference reached every clone; both now fail with
their span.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Keeps both sides: iterators (#23) beside drops and async, `!` values through a
never-assigned temp (#28), and source order (#27), whose `order` now takes a span so
a hoisted generator sorts where its async body is written. An iterator that owns a
value that drops is refused, since an `rt.Iter` drops nothing it skips, consumes, or
holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b6fe796c45

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs Outdated
Comment on lines +1826 to +1828
ty::Adt(adt, _) => matches!(
library::Std::of(self.t.tcx, adt.did()),
Some(library::Std::Arc | library::Std::Waker | library::Std::Context)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject replacement of borrowed MutexGuard handles

For fn replace<'a>(dst: &mut MutexGuard<'a, u32>, src: MutexGuard<'a, u32>) { *dst = src; }, MutexGuard passes this shared-object check and reaches Object.assign. However, the new runtime represents a guard as the mutex itself, so replacing the guard copies the second mutex's value into the first mutex instead of replacing only the guard handle. After replacing a guard of Mutex::new(1) with a guard of Mutex::new(2) and dropping it, native Rust still reads 1 from the first mutex, while the runtime reads 2. Include MutexGuard in the rejection or represent its handle separately from the mutex.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3278409: a MutexGuard joins the handles whose replacement through a reference is refused, with replace_guard in the reject fixture.

(written by Opus 5.5)

Comment thread ts/src/lower/drop.rs
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 | Std::Pin) => self.disposable(args.type_at(0)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle discarded operands when accepting droppable Option payloads

Now that Option<Arc<_>> is accepted, consuming standard-library mappings also need ownership-aware cleanup. For example, let chosen = Some(a.clone()).unwrap_or(b.clone()); drop(chosen); translates through library.rs to rt.option.unwrapOr, which returns the first argument without dropping the eagerly evaluated fallback. Native Rust leaves both original strong counts at 1, but the runtime leaves b at 2, leaking its allocation and suppressing its eventual destructor. Add cleanup for discarded operands in these mappings, or reject their droppable instantiations until supported.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3278409, for every mapping rather than just unwrap_or: a std mapping that takes a value that drops by value is refused unless it moves every such operand into its result or a closure (keeps_operands in library.rs). It catches unwrap_or, ok_or, map_or, then_some, and Result::ok; fallback in the reject fixture covers it. moq-net gains 19 refusals, now in the Drop quest.

(written by Opus 5.5)

Comment thread ts/src/lower/body.rs
Comment on lines +2380 to +2382
if self.temporary_drops(*lhs) {
return self.err(span, "a field of a temporary that drops: bind it to a variable first");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect temporary owners behind dereference projections

For let id = Box::new(Guard { id: 7 }).id;, where Guard implements Drop, the field's THIR base is a Deref of the Box::new call. is_place classifies every dereference as a place, so this temporary-drop check accepts it; lowering then erases the box and reads the field without registering cleanup for the guard. Native Rust drops the guard at the end of the declaration, whereas the translation never drops it. Trace projections back to temporary owners and reject this case with its span, or retain the owner's statement-scoped cleanup.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3278409: a deref is a place only through a reference or of a place, so a field of *Box::new(..) is a field of a temporary that drops and is refused. boxed_field in the reject fixture covers it.

(written by Opus 5.5)

@kixelated

Copy link
Copy Markdown
Collaborator Author

Merged main (#15, #20, #22, #23, #25, #27, #28) in bb37176, snapshots regenerated in b6fe796. Logic changes beyond keeping both sides:

  • Iterators that own a value that drops are refused (ts/src/lower/iter.rs, body.rs's for). feat(ts): translate iterators through a DONE protocol #23's rt.Iter drops nothing it skips, consumes, or still holds, so v.into_iter() of a Vec<Noisy> would leak its drops, and (0..2).map(Noisy).count() would never drop the items count consumes. Refused: into_iter or iter::once of a type that drops, any iterator call over items that drop except the crate's own next and by_ref, and a for loop over an iterator that drops (Rust drops it after the loop). The reject fixture has drained, counted, and looped. moq-net's census gains 55 of these, kio 1; the Drop quest lists them.
  • ! values take fix(ts): type-check values of type ! where a value goes #28's never-assigned temp; Block keeps the spike's block_owns guard. In an Iterator::next, closures and async bodies reset done as feat(ts): translate iterators through a DONE protocol #23's closures do.
  • Source order: feat(ts): emit each module in Rust source order #27's order now takes a span, so the hoisted fooBody/fooDrop generators sort where their async body is written; [Symbol.dispose] sorts first among its class's methods, as before.
  • option_payload_ok became the spike's erases_to(ty).undefined in iter.rs.

just check, just test (task trace diff included), and just ts census pass.

(written by Opus 5.5)

kixelated and others added 3 commits October 24, 2026 10:22
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: daab443cf2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/pat.rs
Comment on lines +205 to +206
if moves && !owned {
self.clear(scrut.clone(), out);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clear moved array-rest elements in their original owner

For let pair = [a.clone(), a.clone()]; let [first, rest @ ..] = pair;, the array-rest path recursively calls pat_bind with pair.slice(...) and owned = true. This registers cleanup for rest but skips clearing its elements from pair, whose enclosing cleanup remains active. Dropping both bindings and leaving the scope therefore decrements the tail's reference count twice: the surviving original a has count 0 instead of native Rust's 1, potentially destroying a still-owned payload. Transfer the rest elements out of the original array, or reject owning rest patterns until that transfer is supported.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2315345 by refusing it: a rest pattern that moves values that drop out of a place fails with its span until the transfer is supported (rest_moved in the reject fixture, listed in the Drop quest). A rest of a temporary, or one bound by reference, still translates.

(written by Opus 5.5)

kixelated and others added 2 commits October 24, 2026 10:32
- 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…lace

Its slice copy would drop the elements, and so would the array they stay in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2315345fbf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +1810 to +1815
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject replacement of borrowed Pin pointers

For fn replace<'a>(dst: &mut Pin<&'a mut State>, src: Pin<&'a mut State>) { *dst = src; }, stripping Pin leaves a reference, which falls through the shared-object check and permits Object.assign(dst, src). Rust replaces the pointer without changing either referent, but the translation overwrites the original referent and leaves the caller's pointer targeting it. For example, rebinding from first { n: 1 } to second { n: 2 } and then writing p.n = 3 produces (3, 2) instead of (1, 3). Unlike the previously rejected owning Pin<Arc<_>> case, this non-owning Pin<&mut State> needs pointer replacement, not referent mutation. Reject this case until the borrowed pointer has a separate representation.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4f6b19b: a reference reached through Pin or Box counts as shared, so replacing a Pin<&mut T> through a reference is refused (replace_pinned_ref in the reject fixture).

(written by Opus 5.5)

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4f6b19bc1a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +2120 to +2122
if self.moves(id) {
let place = self.place(id, out);
return self.move_out(place, span, out);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Drop the initializer of a zero-length array repeat

For a zero-length repeat such as let g = a.clone(); let empty = [g; 0];, where a is an Arc, Rust evaluates and immediately drops g. The new move lowering clears g, but ExprKind::Repeat saves that operand in an unowned temporary and emits Array.from({ length: 0 }, ...). Its callback never executes, and dropping the empty array drops nothing, so the cloned strong reference leaks. The native example leaves a with count 1, whereas the emitted operations leave count 2. Handle the zero-length initializer's cleanup in the repeat lowering, or reject droppable repeat operands until supported.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 781a919: an array repeat of a value that drops is refused (repeated in the reject fixture, listed in the Drop quest).

(written by Opus 5.5)

`[v; 0]` drops `v` at once, which no element of the array would.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 781a919c8e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +2120 to +2122
if self.moves(id) {
let place = self.place(id, out);
return self.move_out(place, span, out);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep move-out statements inside the selected match arm

For let chosen = match flag { true => a, false => a }; with a: Arc<u32>, ternary_match still considers both arms simple, but the new move lowering emits statements that clear a. ternary unconditionally appends both arms' statements to its enclosing output before evaluating the conditional, so the first arm moves out a and the second reads undefined. When flag is false, chosen is consequently undefined instead of the original Arc, and dereferencing it throws. Use statement-based match lowering when an arm requires move-out statements, keeping those statements on the selected path.

AGENTS.md reference: AGENTS.md:L15-L15

Useful? React with 👍 / 👎.

@kixelated kixelated Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reproduced (the task fixture threw on chosen.note in 1,710 scripts) and fixed in b2965a4: an expression that moves a value that drops is no longer simple, so a match or if that moves one in an arm lowers to statements and the move stays on the arm taken. The task fixture's blocks now moves a guard on each arm of a match.

(written by Opus 5.5)

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
@kixelated

Copy link
Copy Markdown
Collaborator Author

Merging at b2965a4.

(written by Opus 5.5)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d51a5d741b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ts/src/lower/body.rs
Comment on lines +1807 to +1809
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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Apply borrowed-capture handling to mapped replacements

When a non-move async block replaces a captured variable through std::mem::replace, the replacement still changes only the generator parameter. For example, with mark = Mark { n: 1 }, executing async { std::mem::replace(&mut mark, Mark { n: 2 }).n }.await must leave the caller's mark.n at 2, but this lowering leaves it at 1. The fresh evidence beyond the previously fixed direct-assignment case is that library.rs::borrowed_place accepts the captured UpvarRef, and swap_out emits a parameter reassignment without consulting self.borrowed or going through assign. Apply the borrowed-capture handling to mapped replacement operations too, or reject them with a source span until supported.

AGENTS.md reference: AGENTS.md:L14-L15

Useful? React with 👍 / 👎.

@kixelated

Copy link
Copy Markdown
Collaborator Author

Merged main again at d51a5d7 for #29's quests. The spike quest is gone from the tree, so the MIR spike and the Drop and Async quests no longer require it. The README's THIR design note now points at the MIR spike rather than readability. CI is green, and quest check --base origin/main passes. Merging at d51a5d7.

(written by Opus 5.5)

@kixelated
kixelated merged commit 004519e into main Oct 24, 2026
1 check passed
@kixelated
kixelated deleted the quest/m2/ts-async-spike branch October 27, 2026 20:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant