Repository navigation
feat(ts): async fns as generators and drops from THIR scopes, from the async spike - #16
Conversation
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
…ve side 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
… diffs 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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| let ty = self.subst(capture.place.ty()); | ||
| let by_value = matches!(capture.info.capture_kind, ty::UpvarCapture::ByValue); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| // The future owns what it captures, so here drops none of it. | ||
| self.disown(&name); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
…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
# Conflicts: # ts/src/lower/body.rs
There was a problem hiding this comment.
💡 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".
| [Symbol.dispose](): void { | ||
| if (--this.strong === 0) drop(this.value); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| function run(): void { | ||
| scheduled = false; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
# Conflicts: # ts/src/ts.rs
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
There was a problem hiding this comment.
💡 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".
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
turnsin the task fixture covers it differentially. - A temporary bound only in part (under a
_, a.., an unnamed field, or another variant of alet ... else) fails with its span, as amatchorif leton one already does. The reject fixture'sskippedcovers it. The census finds 27 in moq-net and none in kio, and the Drop quest counts them.
(written by Opus 5.5)
| 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)); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| future[Symbol.dispose](); | ||
| this.#resolve(output); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
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
There was a problem hiding this comment.
💡 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".
| PatKind::Binding { | ||
| mode, subpattern: None, .. | ||
| } => mode.0 == rustc_hir::ByRef::No, | ||
| PatKind::Variant { subpatterns, .. } => subpatterns.iter().all(|f| takes_all(&f.pattern)), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| Some(Std::Option | Std::Result | Std::Box | Std::Vec | Std::Mutex | Std::Poll) => { | ||
| args.types().any(|t| self.drops(t)) | ||
| } | ||
| Some(_) => false, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| // The old value drops once the new one is made. | ||
| let lty = self.ty_of(lhs); | ||
| if self.t.drops(lty) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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); | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
… 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
There was a problem hiding this comment.
💡 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".
| 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) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| } | ||
| 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. |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| if self.moves(id) { | ||
| let place = self.place(id, out); | ||
| return self.move_out(place, span, out); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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)) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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) | ||
| ), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
…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
There was a problem hiding this comment.
💡 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".
| ty::Adt(adt, _) => matches!( | ||
| library::Std::of(self.t.tcx, adt.did()), | ||
| Some(library::Std::Arc | library::Std::Waker | library::Std::Context) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| 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)), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
| if self.temporary_drops(*lhs) { | ||
| return self.err(span, "a field of a temporary that drops: bind it to a variable first"); | ||
| } |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
… quest Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
|
Merged main (#15, #20, #22, #23, #25, #27, #28) in bb37176, snapshots regenerated in b6fe796. Logic changes beyond keeping both sides:
(written by Opus 5.5) |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
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
There was a problem hiding this comment.
💡 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".
| if moves && !owned { | ||
| self.clear(scrut.clone(), out); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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)
- 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
There was a problem hiding this comment.
💡 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".
| 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); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| if self.moves(id) { | ||
| let place = self.place(id, out); | ||
| return self.move_out(place, span, out); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
💡 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".
| if self.moves(id) { | ||
| let place = self.place(id, out); | ||
| return self.move_out(place, span, out); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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
|
Merging at b2965a4.
(written by Opus 5.5) |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
There was a problem hiding this comment.
💡 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".
| 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), |
There was a problem hiding this comment.
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 👍 / 👎.
|
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 (written by Opus 5.5) |
Closes the async and drop spike quest.
Problem
rust2-ts refused
asyncand every type that implementsDrop, 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
taskfixture trims kio to what its futures hinge on:Waiterholding the task's waker in anArcthatWaiterLists hold weakly,Park,wait, and a channel that closes when its last producer drops, underasync 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.tsrequires 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 afterReadypanics, an async block drops only what it owns).async fnreturnsrt.future(body, drop, ...upvars). The body is a module-levelfunction*taking the upvars as parameters;.awaitfalls out of the existing match and loop lowering as a poll loop aroundyield.rt.futurestarts the generator at the first poll, drops the upvars if it never ran, returns the generator through itsfinallyblocks if dropped while suspended, and panics on a poll after completion, as rustc's coroutines do.pollthe transform's resume function and its dispose the drop shim, each a loop over aswitchon the basic block, with calls, types, closures, and formatting through the THIR lowering's helpers.[Symbol.dispose](itsDropimpl, then its fields); a variable drops in afinallyat the end of its scope; a move leavesundefinedbehind.rt.Arc,rt.Weak, andrt.Mutexgive kio's waiters exact strong counts. Whatever the spike did not cover fails with its span (the reject fixture has one of each).rt.spawn(future)returns a promise, polls woken tasks in a batch from onequeueMicrotask, and yields to a macrotask after 128 polls.just ts benchgains 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 onrt.spawn), and hand-written with promises andasync/awaitas 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%.
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.spawna 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
.awaitis a poll loop of about ten lines. The state machines read as basic blocks: 45let _Ndeclarations forsum's 10 lines, and aswitchno structurizer can remove, since the transform's resume dispatch jumps into the middle of loops.Census (
just ts censusat the pinned moq revision): kio and moq-net no longer refuse anyasync fn. kio has 28 refusals left about drops; moq-net's lead with dropping aResult,Option,Poll, enum, or tuple whose payload drops (657), methods taking a droppableselfby value (155), and borrowed temporaries that drop (152), thenforloops 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
panic=abort, MIR also has no cleanup paths, so a JS exception would skip drops that THIR'sfinallyblocks run.Drop and Async are rewritten to these, with what the spike left refused; Shared ownership to what remains after
rt.Arc,rt.Weak, andrt.Mutex.Impact
[Symbol.dispose]and drop where Rust drops them;async fns returnrt.Future<T>;Poll<T>isT | typeof rt.Pending(refused, as anOptionis, when its payload can already be pending, throughOption,Box,Pin, or a reference);Arc,Weak,Mutex,MutexGuard,Waker, andContextmap tort/task.ts, and aPindrops as its pointer does. The Drop and Async quests own this output until they finish.rt/task.ts, re-exported fromrt.tsand written beside it:drop,dropAll,Arc,Weak,Mutex,Pending,Poll,Waker,Context,Future,future, andspawn.runtime/tsconfig.jsonaddsesnext.disposableforSymbol.dispose.taskfixture andtests/task.ts;differential.tsruns a harness's owncasesand prints a text output as text.tests/runtime.rsrunstests/spawn.ts, which checksrt.spawn's poll budget and its rejection on a panic in drop.--task,--task-wasm, and--task-nativeroute forbench/main.ts. The fixtures sharefixtures/bench.rsas their native route.Guardandlater, which now translate, for each new refusal, including anArcof a borrow of a value that drops, a value that drops moved ahead of an.awaitin the same call or assignment, and alet,match, orif letthat binds only part of a temporary that drops (Some(..)included).rt.Iterdrops nothing it skips, consumes, or holds:into_iteroronceof one, any adaptor but the crate's ownnextover items that drop, and aforloop over an iterator that drops. The reject fixture has one of each.unwrap_or,ok_or,map_or,then_some, andResult::okmay discard one), as are replacing aMutexGuardor a pinned reference through a reference, a field read through aBoxmade in place, a rest pattern that moves values that drop out of a place, and an array repeat of a value that drops.u64s throughrt.u64, since main's feat(ts): wide integers are numbers while safe, and each integer type is branded #26 made them numbers while safe.matchorifwhose arm moves a value that drops lowers to statements rather than?:, so the move happens only on the arm taken; the task fixture'sblockscovers it.self: Pin<&mut Self>is the method'sthis, and aValueExprdelivers to its destination. Merging main's tail loops (feat(ts): translate loops that onlyreturnleaves #14),breaks_outalso looks inside thetryblocks drops add, so a loop broken inside a drop scope still ends itsmatcharm.Alternatives
async/await: out, decided with the maintainer, since it breaks laziness, poll order, and cancel-by-drop.try/catch: not tried, since the target'spanic=abortbuilds none.Follow-ups
undefined!writes andtry/finallyblocks; the Drop quest says to measure it first.yield*between translated futures would skip each await level'spoll; the Async quest names it if a profile finds await overhead.ts-tail-loopwill lift the tailloopthe fixture'sdrainavoids.keeps_operandsrefuses 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'sFixture.spawn<T>does not type-check againstrt.spawn(itspollresult includes the pending symbol). Bun bundles the bench withouttsc, 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