Repository navigation
feat(ts): MIR lowering spike, which moves the translator to MIR - #36
Conversation
Quest-Claim: e106caa154d47fdb
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…machines Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…s temporaries across calls Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…lace Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…all site, format arguments in place Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…uncopied 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
…tors, receivers that change Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…o the MIR spike 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
# Conflicts: # quest/m2/README.md
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: 6a6d78dc49
ℹ️ 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".
| && (matches!(field_ty.kind(), ty::Ref(..)) | ||
| || part.is_constant() | ||
| || matches!(part, Expr::Ident(_))) => |
There was a problem hiding this comment.
Require stable operands before substituting aggregate fields
With --lower mir, an identifier used to construct an immutable aggregate can still be reassigned afterward. For example, fn f(mut x: u32) -> u32 { let t = (x, x); x = 9; t.0 + t.1 + x } records [x, x] in var_parts, then this substitution replaces both tuple-field reads with the current x: f(2) produces 27 instead of Rust's 13. Checking that the aggregate itself is never mutated does not establish that its operands stay unchanged. Only substitute identifiers proven stable across the aggregate's lifetime; otherwise retain the stored field read, and cover this with a native differential test as required by AGENTS.md.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture now builds (n, n), changes n, and reads the tuple, which made 1,737 of 240,671 differential cases differ from native. Fixed in f6678bb: a field reads its operand in place only through a name assigned at most once and never changed in place (a reference field stays exempt, since borrow checking keeps its referent). lang_mir passes again.
(written by Opus 5.5)
…g changes Found by review: a tuple of a variable read its operand after the variable changed. 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: f6678bbed9
ℹ️ 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 mut folded = self.fold_exprs(Vec::new(), vec![value], true, out); | ||
| let value = folded.pop().unwrap(); | ||
| let parts = parts.and_then(|_| parts_of(&value)); | ||
| self.hold(local, value, effect, memory, parts); |
There was a problem hiding this comment.
Preserve effect metadata when folding pending expressions
With --lower mir, folding an effectful temporary into a pure rvalue loses its effect and memory flags: self.hold receives the outer rvalue's original flags rather than those of the folded expression. For example, let b = first(v) == 0; second(v); b, where both functions append to v, emits the equivalent of second(v); return first(v) === 0, reversing the observable calls. I reproduced this ordering with the extracted emitter methods and checked the source's native MIR. Propagate the folded temporaries' metadata, or recompute it before holding the result, and cover the ordering with a native differential test.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture now computes mark(out, 1) == 0, calls mark(out, 2), then reads the first; MIR emitted the calls swapped. Fixed in 4766695: a value held back carries the effects and reads of what folds into it. Taking an effectful aggregate apart now holds each part back in its place instead, so the ordering checks see them, and a variable assigned no longer counts as a read. lang_mir passes, and the codec and task bundles stay the same size.
(written by Opus 5.5)
| let method = match elem_ty.kind() { | ||
| ty::Uint(ty::UintTy::U8) => "subarray", | ||
| _ => "slice", | ||
| }; |
There was a problem hiding this comment.
Reject mutable non-byte subslice projections instead of copying
With --lower mir, a rest-pattern borrow such as let [_, ref mut tail @ ..] = a reaches this projection through the alias-assignment path, bypassing the rejection in the indexing-call handler. For non-byte arrays, slice creates a separate array, so writes through tail no longer update a. For example, fn f(mut a: [u32; 3]) -> u32 { let [_, ref mut tail @ ..] = a; tail[0] = 9; a[1] } returns 9 natively but this representation returns the original second element. Reject these mutable projections with a source-span error until a shared-view representation is available, and add differential coverage for rest-pattern mutation.
AGENTS.md reference: AGENTS.md:L14-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and THIR had it too. Fixed in 4766695: both lowerings refuse a mutable borrow of a subslice of other than bytes (rest_mut in the reject fixture), and the lang fixture now changes bytes through a rest pattern, which reads the array in place.
(written by Opus 5.5)
…fuse mutable subslices JS would copy A value held back with a call folded into it kept only its own effects, so a later call ran first. It now carries what it folds in, an aggregate's parts taken apart stay held back one by one, and a variable assigned is no read. A mutable borrow of a subslice of other than bytes wrote to a copy, in both lowerings: it is refused. 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: d0001f5339
ℹ️ 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 value = match (ty.kind(), value.is_constant()) { | ||
| (ty::Ref(..), _) | (_, true) => value, |
There was a problem hiding this comment.
Snapshot references captured by value in move closures
With --lower mir, a reference-typed capture is always reused as an expression, but a move closure copies the reference itself rather than borrowing the variable holding it. For example, fn f(a: &[u8], b: &[u8]) -> u8 { let mut r = a; let g = move || r[0]; r = b; g() + r[0] } captures the mutable JS variable r, so inputs [2] and [9] produce 18 instead of native Rust's 11. Borrow checking permits this reassignment because the closure owns a separate reference. Distinguish by-value reference captures from actual by-reference captures, snapshot the former at construction, and add differential coverage against native Rust as required by AGENTS.md.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: a move closure over a slice reference, with the variable assigned after, made 1,439 of 240,671 lang cases differ from native under MIR. Fixed in 7a59f1c: a capture by value from a variable that is assigned again is copied into a constant when the closure is made; a borrow, or a variable assigned once, still reads in place. THIR refuses this construct (a closure that copies a mutable variable), so the shared lang fixture can't keep the case until THIR is deleted; ts-mir.md now says to move it in then.
(written by Opus 5.5)
…as made MIR lowered a reference captured by value as the variable holding it, so assigning the variable after changed what the closure read. A capture from a variable assigned again is now copied when the closure is made. THIR refuses the construct, so the lang fixture can't hold it until THIR goes: ts-mir notes the move. 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: 7a59f1cb16
ℹ️ 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 bytes = self.operand_frozen(&args[0].node, span, out); | ||
| int.method("fromBeBytes", vec![bytes]) | ||
| } | ||
| }; | ||
| done(value, false) |
There was a problem hiding this comment.
Preserve memory-read metadata for byte conversion calls
With --lower mir, marking from_be_bytes as effect-free also marks its result as memory-free, because call passes effect for both flags to set_local. Its uncopied array argument can consequently change before the conversion runs. For example, fn f(mut a: [u8; 4]) -> u32 { let x = u32::from_be_bytes(a); a[0] = 9; x + a[0] as u32 } should return 11 for [0, 0, 0, 2], but the pending conversion can fold past the write and produce 150994955. I verified the native MIR and reproduced the delayed read with the extracted emitter. Track memory reads independently of effects, and add native differential coverage for conversions followed by input mutation.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture now converts a byte array, changes it in place, and reads both, which made 1,771 of 240,671 cases differ under MIR. The array reached the call through a temporary that shared it until it folded in. Fixed in e2bfc4c: that shared copy counts as a memory read, and so does an uncopied argument to a call without effects, kept apart from the effect flag. lang_mir passes; the codec and task bundles are byte-identical in size.
(written by Opus 5.5)
…olds A copy shared until it folds into a call's argument, or an argument passed uncopied to a call without effects, read its source where it folded, after that source changed in place. Both now count as reading memory, so a change in place emits them first. 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: c4ad18ba89
ℹ️ 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 shares = place.as_local().is_some_and(|l| self.arg_use[l] && self.foldable(l)) | ||
| && matches!(rvalue, Rvalue::Use(Operand::Copy(p), _) if !self.frozen(*p) && self.b.needs_copy(p.ty(&self.mir.local_decls, self.tcx).ty)); | ||
| if shares { | ||
| self.into_frozen = true; | ||
| self.force_share = true; |
There was a problem hiding this comment.
Preserve copies when another argument can mutate their source
With --lower mir, a copied aggregate cannot safely share its source merely because it folds into a call: another argument can let the callee mutate that source. For example, fn g(a: [u8; 1], b: &mut [u8; 1]) -> u8 { b[0] = 9; a[0] } called by fn f(mut a: [u8; 1]) -> u8 { g(a, &mut a) } returns 2 natively for [2]. This optimization instead folds the argument copy into g(a, a); g does not copy its first parameter because that parameter is never directly mutated, so it reads 9. I verified the native MIR and reproduced the folding with the extracted emitter. Retain the copy unless aliasing during the call is ruled out, and cover this with a native differential test.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture now passes write_then_read(cell, &mut cell), which made 1,737 of 240,671 cases differ under MIR. Fixed in 62fa534: a copy shares its source with an argument only if the source is a local's own value nothing borrows, or if nothing the call is given can change memory (no mutable reference, raw pointer, or interior mutability in any operand's type). The codec and task translations are byte-identical to before, so the benchmark numbers in the description stand.
(written by Opus 5.5)
…its source A copy folded into a call's argument shared its source, which the callee could change through another argument, as in g(a, &mut a). It shares now only a local's own value nothing borrows, or when nothing the call is given can change memory: no mutable reference, raw pointer, or interior mutability. 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: 62fa5349b1
ℹ️ 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".
| ("Option", "insert") => { | ||
| let place = self.borrowed_place(&args[0].node, span)?; | ||
| let value = self.operand(&args[1].node, span, out); | ||
| out.push(StmtKind::Expr(place.clone().assign(value)).at(None)); |
There was a problem hiding this comment.
Drop the previous payload before inserting into Some
With --lower mir, calling Option::insert on an occupied option overwrites its payload without running its destructor. For example, let a = Arc::new(7u32); let mut slot = Some(a.clone()); slot.insert(a.clone()); Arc::strong_count(&a) returns 2 natively, but this lowering leaves the count at 3, and dropping both remaining owners still leaks one strong reference. The native MIR contains only the Option::insert call here, so no separate drop terminator repairs the omission. Drop the previous payload before replacing it, preserving panic behavior, and add native differential coverage for insertion into an occupied option whose payload drops.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right: insert overwrote a payload that drops. No fixture uses Option::insert or Option::replace, so neither had a differential test, and THIR refuses both. Fixed in 66b54ae by deleting both interceptions: MIR now refuses them as unsupported calls, as THIR does. Supporting them, with drop coverage, belongs to the move in ts-mir, once a fixture can hold constructs THIR refuses.
(written by Opus 5.5)
Their MIR lowering had no test against native Rust, and insert overwrote a payload that drops without dropping it. Like THIR, MIR now refuses both as unsupported calls; no fixture uses them. 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: 66b54ae1c7
ℹ️ 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".
| // A result into a local changed in place is its own copy: it may share the callee's. | ||
| let value = match dest.as_local() { | ||
| Some(local) if self.mutated[local] => { | ||
| let ty = self.mir.local_decls[local].ty; | ||
| self.b.copied(value, ty) |
There was a problem hiding this comment.
Preserve ownership when a callee returns a shared argument
With --lower mir, an unmodified result can still need a copy when the callee returns an argument shared with the caller. For example, fn id(a: [u8; 1]) -> [u8; 1] { a } and fn f(mut a: [u8; 1]) -> u8 { let b = id(a); a[0] = 9; b[0] + a[0] } should return 11 for [2]. The argument-copy optimization allows id(a) to share a, id returns it without copying, and this guard leaves b uncopied because only a is mutated. Consequently, both arrays observe the write and the result is 18. Preserve the value boundary when shared arguments escape through the return value, and add native differential coverage for returned aggregates followed by source mutation.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture now passes an array through a function that returns it, then changes the source, which made 1,737 of 240,671 cases differ under MIR. Fixed in c59c322: a copy shares its source with an argument only if the call's result type can't hold the argument's, meaning it doesn't contain that type and doesn't hide what it holds (dyn, opaque, generic, closure, or coroutine). The codec and task translations are unchanged.
(written by Opus 5.5)
…'t hold it A shared argument that the callee returned stayed shared with its source, which changed after. A copy now shares only into a call whose result type can't hold the argument's: neither contains it nor hides what it holds. 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: d00c7756ab
ℹ️ 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".
| && !matches!(self.slots[place.local], Slot::Alias(_)) | ||
| && !(place.local.as_u32() == 1 && matches!(self.env, Env::Closure(_))) |
There was a problem hiding this comment.
Preserve referent identity when writing through captured references
With --lower mir, fn replace(a: &mut [u8; 1]) { let mut g = || { *a = [9]; }; g(); } fails to update the caller's array. The closure's reference temporary becomes a Slot::Alias through env_field, so this guard skips the in-place byte-array assignment and the fallback emits the equivalent of a = Uint8Array.of(9). Calling replace on [2] therefore leaves the caller observing 2 instead of native Rust's 9. Distinguish aliases of assignable storage from aliases holding references, preserve the latter's referent identity on whole-value writes, and add native differential coverage for this closure case.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced: the lang fixture's overwrite writes a whole array through a reference its closure captured, and MIR emitted a = Uint8Array.of(9), reassigning the captured variable. Fixed in 7581fa3: a whole write through an alias made from a copied reference (or a reborrow of *r) changes the referent in place, with set or Object.assign as for any reference. An alias of a borrowed place (&mut x, &mut v[i]) still assigns that place. The codec and task translations are unchanged.
(written by Opus 5.5)
…it points at An alias made from a copy of a reference, such as a closure's capture, read as the variable holding the object, so writing through it whole replaced the variable instead of the object the caller shares. Such a write now changes the object in place; an alias of a borrowed place still assigns the place. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Indexing by a range read its slice into a constant first, which flushed the range held back behind it, so each size prefix the codec's encoders write built a Range object. The bounds are now taken apart first and held back as parts. A range type the call doesn't map is refused before anything is emitted. 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: 04e3c7121d
ℹ️ 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".
| return None; | ||
| } | ||
| match &self.slots[place.local] { | ||
| Slot::Alias(Some(target)) if target.is_path() || matches!(target, Expr::Index(..)) => Some(target.clone()), |
There was a problem hiding this comment.
Reject reference-value aliases in replacement intrinsics
With --lower mir, a reference copied from a move closure's environment becomes a Slot::Alias, but its target holds the reference's JS object rather than assignable Rust storage. For example, fn f(a: &mut [u8; 1]) { let mut g = move || std::mem::replace(&mut *a, [9]); g(); } reaches this arm and swap_out emits a = Uint8Array.of(9), leaving the caller's array unchanged. I checked the native MIR and reproduced the rebinding with the extracted emitter. Although whole-value assignments now distinguish these aliases using alias_of_place, this interception bypasses that distinction. Reject reference-value aliases here, as THIR does, until replacement can preserve both referent identity and the returned old value, and add native differential coverage. (Written by GPT-6.1 Sol)
AGENTS.md reference: AGENTS.md:L14-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 157bdca: borrowed_place now also requires alias_of_place, so mem::replace/swap through a copied reference is refused with its span, as THIR does. Reproduced your example with --lower mir (accepted before, refused after). There's no MIR reject harness yet, so no fixture: THIR refuses the same construct, so a differential test can't cover it.
(written by Opus 5.5)
…ied reference A reference copied into a move closure holds the object it points at, so `mem::replace` through it rebound the copy and left the caller's value unchanged. Refuse it, as THIR does. 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: 71b437d028
ℹ️ 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 mut inner = Fx::new(&mut *self.b, &mir, Env::Closure(captures), span); | ||
| let params = inner.params(); | ||
| let body = inner.lower(); | ||
| Expr::Arrow(params, ret, body) |
There was a problem hiding this comment.
Preserve independent environments when copying mutable closures
With --lower mir, copying a closure that owns mutable Copy captures shares its state instead of copying it. For example, let mut a = [0u8]; let mut g = move || { a[0] += 1; a[0] }; let mut h = g; g() + h() returns 2 natively, but this arrow representation makes both calls mutate the same captured array, producing 3. The closure copy passes through Body::copied, whose mutable_aggregate excludes closure types, so nothing creates an independent environment for h. Preserve the environment's value semantics or reject this case with a source-span error, and add native differential coverage. (Written by GPT-6.1 Sol)
AGENTS.md reference: AGENTS.md:L14-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced with the lang differential under --lower mir (native 02, translated 03). Fixed in a87d03b by refusing the copy with its span: an Operand::Copy of a type holding an FnMut closure by value is "a copy of a closure that changes what it captured". Giving each copy its own environment would need closures as objects rather than arrow functions, and nothing in moq-net or kio copies such a closure (their census from MIR has no hits), so a refusal is the right size. Only FnMut closures matter: an Fn closure can't change its captures, and a closure that moves a capture out isn't Copy. New reject_mir snapshots what MIR refuses in the reject fixture, covering this case and the replace-through-a-captured-reference one.
(written by Opus 5.5)
Copies of an arrow function share the variables it captured, where each copy of a Rust closure has its own, so a copied `FnMut` closure saw the other's changes. Refuse the copy with its span. `reject_mir` now checks what lowering from MIR refuses in the reject fixture, which covers this and replacing through a reference a closure captured. 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: fc4bf73d6e
ℹ️ 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".
| fn place_memory<'tcx>(p: &Place<'tcx>, fx: &Fx<'_, '_, '_, 'tcx>) -> bool { | ||
| !p.projection.is_empty() | ||
| || fx.borrowed[p.local] | ||
| || matches!(fx.slots[p.local], Slot::Alias(_)) | ||
| || p.local.as_u32() == 1 && !matches!(fx.env, Env::Plain | Env::Shim) |
There was a problem hiding this comment.
Treat aggregate copies as memory reads before deferring them
With --lower mir, copying an unborrowed local that is mutated through a field is classified as memory-free because this predicate ignores fx.mutated[p.local]. For example, fn f(mut a: (u32, u32)) -> u32 { let b = a; a.0 = 9; b.0 + a.0 } holds rt.copy(a) as a pure pending expression, allowing emit to move it past the field assignment. Consequently, f((2, 0)) reads the modified tuple and returns 18 instead of native Rust's 11. Unlike the existing call-argument issue, this requires no call: an ordinary aggregate copy is delayed across a direct write. Track the copy's memory read before holding it, and add native differential coverage for single-use copies followed by source mutation. (Written by GPT-6.1 Sol)
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Reproduced with a new lang case, copy_then_write (let b = a; a.0 = 9; b.0 + a.0): under --lower mir the translation gave 18 where native gives 9 + the input. Fixed in e77cea3. An operand now reads memory when its local is changed in place, so a held copy flushes before the field write. That rule is shared with call arguments as operand_memory, which replaces arg_memory. The case stays in the lang differential for both lowerings.
(written by Opus 5.5)
#32 made a type's functions free functions in a module per type. Lowering from MIR follows: a method's `self` is its first parameter, a struct is built through `construct` (a plain object unless it drops), and a coroutine stays a class whose `poll` and `[Symbol.dispose]` are its methods. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed commit: 86398a7
Reviewed the MIR adaptation to #32, excluding changes inherited unchanged from the new base. No new actionable bug found in this update. Explicit receiver parameters and shared struct construction are a coherent simplification; coroutine poll/dispose retain their class-method behavior.
Still open, not a new finding: the independently reported aggregate-copy deferral bug remains in ts/src/lower/mir/rvalue.rs:467–471, 483–490. Ordinary copies omit mutated-source memory tracking, allowing a copy to move past a field write. Please address the existing finding and add its native differential regression: #36 (comment)
Verification: static GitHub diff and surrounding-code inspection only; no tests run.
… passes it A copy of an aggregate local was held as a pure expression, so a later write to the local's field could run before it and the copy saw the write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed commit: e77cea3
The aggregate-copy deferral finding is addressed. Rvalue operands include mutated-source memory tracking through the same operand_memory helper used for call arguments. Pending copies flush before a field write instead of observing the modified source. The copy_then_write case adds differential coverage: #36 (comment)
No new actionable bugs found. Sharing the operand-memory rule is a simpler, consistent fix that preserves existing call-argument handling.
Verification: static diff and surrounding deferral/flush inspection only; tests were not run.
|
Ready to merge at e77cea3.
(written by Opus 5.5) |
Closes the MIR lowering spike quest.
Problem
rust2-ts lowers bodies from THIR. Its drops come from THIR's scopes, which drew about ten review rounds of small coverage misses, each closed by a narrow refusal, and its async bodies are generators, which #16 measured 1.4-2.6x slower than MIR state machines. MIR's drop elaboration is exact by construction, but #16 found a second lowering costly, and that wasm32's
panic=abortMIR has no cleanup paths, so a JS exception would skip drops THIR'sfinallyblocks run. The maintainer asked for the whole lowering ported to MIR on the codec and task fixtures and measured: correctness first, then speed, then the consumer's minified bundle size.Approach
--lower mir(RUST2_TS_LOWER) lowers every body fromoptimized_mirinstead, beside the THIR lowering, insrc/lower/mir/. It reuses the THIR lowering's types, library mappings, formatting, iterators, numbers, and constants through aBodywith no THIR of its own.cfg.rs): a reducible graph becomes nested blocks, loops, andifs left by labeledbreakandcontinue, by Ramsey's "Beyond Relooper" (ICFP 2022), which places each node under its immediate dominator. An irreducible one, a coroutine's resume function entering loops in the middle, becomes a loop over aswitchon the next block, with each chain of single-predecessor blocks in one case.mod.rs): every MIR local is a JS variable, except references assigned once from a place that stays put, which read as that place (so a&mutto a number changes the number), and discriminants only a switch reads. A temporary assigned once and read once is held back and folded into the expression that reads it, unless that would reorder an effect, a throw, or a read of memory something could change.Copyaggregates are copied only where a copy could change in place.Dropterminator drops where drop elaboration put it, through the existing[Symbol.dispose]glue; an enum, tuple, orResultthat drops gets glue lowered from rustc's owndrop_in_placeshim (glue.rs).unwind.rs): the driver adds-C panic=unwind(and-Z ub-checks=no) for the translated crate, so MIR keeps the cleanup blocks a panic unwinds through; wasm32 only strips them under abort. A function whose cleanup does something JS can see keeps the cleanup of the code running now in a variable, set before each call that can panic where it changes, and runs it from acatch, then throws on.coroutine.rs): each coroutine instance is a class of its state, its captures, and the locals it keeps across.await, with the state transform's resume function aspolland its drop as[Symbol.dispose].call.rs): MIR passes through temporaries what THIR wrote in place, so a few std calls lower here:mem::takeand its kin replace the place a&mutborrows, indexing and slicing read in place,from_be_bytesof bytes made in place shifts them,format_args!fromArguments::new's template,?fromTry::branch, ranges step in place, andIterator::nextkeeps the item-or-rt.DONEprotocol.A new test for drops on panic: the task fixture's
sumpanics on 99 with its guards live, andtests/unwind.tsruns 5,000 scripts natively on the host (examples/unwind.rs, where a panic unwinds) and translated, catching and logging each step's panic and going on. The logs must match byte for byte.Results
Correctness: every differential test passes from MIR, with no snapshot of MIR's output.
Aborting MIR skips the drops a panic should run and never marks the coroutine as panicked, so a later poll resumes it; with
-C panic=unwindMIR matches native unwinding exactly, as THIR'sfinallyblocks do.Speed,
just ts benchon 04e3c71 (after the review fixes), on a Ryzen 9 5900XT (32 threads) shared with CI runners and other agents' builds: 1-minute load 2.9 to 10 during this run. Each workload is the median of 15 samples, with the routes in a seeded random order each round (#39). The codec, geometric mean of MIR over THIR per engine:Group encode is 1.9-2.6x slower than THIR in every engine, frames encode 1.3-1.4x in Chromium, and small varint encodes up to 1.6x in Node but 0.7-0.9x in Bun; ts-mir records them. The run before the review fixes and #39 measured 1.03, 0.92, and 1.07; this run doesn't separate the two changes. The async handoff, nanoseconds per handoff:
Unwinding against aborting, both from MIR on 04e3c71: three runs with the aborting translation as a
--route, and two A/A controls with the unwinding translation itself as the--route, each over the bench's built-in A/A column. 1-minute load 1.6 to 19.8 (median 5.4) across the five runs. Geometric means, the--routeover A/A, where below 1 means the route is faster:The codec doesn't move. On the handoff, aborting is faster in V8 in every run: about 6% in Chromium, below every control, and about 4% in Node, at the controls' edge. In Bun it is about 5% slower. A run on the previous head agreed: abort over A/A of 0.90, 0.96, and 0.94 in Node and 0.99, 0.92, and 0.93 in Chromium, against controls of 0.97 to 1.02. So unwinding costs the V8 handoff about 4-6%, which is more than noise.
Bundle size, Bun-minified as the bench bundles each route:
Census of moq-net (and kio) at the pinned revision, by construct: drop refusals fall from 1,393 to 254 (kio: 28 to 9). Gone: dropping a value without glue (657 to 128),
selfby value that drops (155), temporaries that drop (280),forloops over values that drop (60), moves out of other places (112), and the rest in patterns, let chains, closures, struct updates, and guarded arms. Also gone: or-patterns with bindings (34), patterns on unmapped types (39), async blocks capturing part of a variable (47), andref mutbindings (117). Totals barely move (15,128 to 15,214; kio 227 to 253) because MIR types each intermediate it holds, so a library or model gap shows once more per temporary: unsupported calls and types from another crate go from 11,494 to 12,794, the same gaps. MIR-only:?onPoll<Result<..>>reads as 284 refusals of?from one type to another, where THIR refused 244 the same sites.Cost to build:
src/lower/mir/is 4,947 lines, against THIR'sbody.rs,pat.rs, and drop scopes (about 3,700) that a move deletes.Verdict
MIR wins. On correctness it drops exactly where Rust does by construction, including on panic, which the new unwinding test proves against native Rust, and it closes about 1,100 drop refusals THIR could only refuse. On speed async is 1.4-5.5x faster, faster than moq's hand-written promises past depth 1, and the codec is 2-12% slower than THIR, mostly in encode, which ts-mir-codec must close before MIR becomes the only lowering. It loses on size, third in the ranking: 9% more gzip on the codec, 35% on the async fixture. The translator moves: quest/m2/ts-mir.md makes MIR the only lowering and deletes THIR's, and Drop, Async, and the README's design note are rewritten to MIR.
Decisions
--lower mirwith its tests in CI, as the start of ts-mir.Impact
rust2-tsgains--lower thir|mir(RUST2_TS_LOWER); THIR stays the default. Undermirthe driver passes-C panic=unwind -Z ub-checks=noto the translated crate's rustc (RUST2_TS_ABORT=1drops the first, for measuring).sumpanics on a sent 99, with its guards live; its THIR snapshot changes by that assert. Its harness catches a step's panic where a panic unwinds (the host), which the wasm32 build, aborting, never does.tests/task.ts'sharnesstakesunwind; newtests/unwind.tsandfixtures/task/examples/unwind.rs; new testscodec_mir,lang_mir,task_mir, andreject_mir(againstfixtures/reject/expected-mir.txt), andtaskalso runs the unwinding test.switch,try/catch,throw,let x!: T, class fields with initializers, and postfix++; the THIR lowering emits none of them.library::StdnamesControlFlow,Infallible,RangeTo,RangeFrom,RangeFull,Argument, andNonNull, which only MIR reaches.Alternatives
switchfor every function: simpler, but the structurizer made the codec tie THIR's structured code.Follow-ups
--routefor identical code, which fix(ts): shuffle the bench's order each round so no route keeps a slot #39's random order fixed.rt.copycopies aCopyaggregate through its shared references, duplicating anArcor aCell(added to ts-shared). Fixed here in both: a mutable borrow of a non-byte subslice wrote to a copy, and is now refused.(written by Opus 5.5)
🤖 Generated with Claude Code
https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn