Skip to content

feat(ts): MIR lowering spike, which moves the translator to MIR - #36

Merged
kixelated merged 31 commits into
mainfrom
quest/m2/ts-mir-spike
Oct 25, 2026
Merged

kixelated merged 31 commits into
mainfrom
quest/m2/ts-mir-spike

Conversation

@kixelated

@kixelated kixelated commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

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=abort MIR has no cleanup paths, so a JS exception would skip drops THIR's finally blocks 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 from optimized_mir instead, beside the THIR lowering, in src/lower/mir/. It reuses the THIR lowering's types, library mappings, formatting, iterators, numbers, and constants through a Body with no THIR of its own.

  • Control flow (cfg.rs): a reducible graph becomes nested blocks, loops, and ifs left by labeled break and continue, 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 a switch on the next block, with each chain of single-predecessor blocks in one case.
  • Expressions (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 &mut to 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. Copy aggregates are copied only where a copy could change in place.
  • Drops: each Drop terminator drops where drop elaboration put it, through the existing [Symbol.dispose] glue; an enum, tuple, or Result that drops gets glue lowered from rustc's own drop_in_place shim (glue.rs).
  • Panics (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 a catch, then throws on.
  • Async (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 as poll and its drop as [Symbol.dispose].
  • Calls (call.rs): MIR passes through temporaries what THIR wrote in place, so a few std calls lower here: mem::take and its kin replace the place a &mut borrows, indexing and slicing read in place, from_be_bytes of bytes made in place shifts them, format_args! from Arguments::new's template, ? from Try::branch, ranges step in place, and Iterator::next keeps the item-or-rt.DONE protocol.

A new test for drops on panic: the task fixture's sum panics on 99 with its guards live, and tests/unwind.ts runs 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.

test cases THIR MIR (unwind) MIR (abort)
codec differential 35,273 0 differences 0 not run
lang differential (all widths, patterns, iterators, formatting) 240,671 0 0 not run
task trace (polls, wakes, waker clones and drops, guard drops) 35,281 0 0 0
task unwinding (host-native, panics caught per step) 5,008 (281 panic) 0 0 130

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=unwind MIR matches native unwinding exactly, as THIR's finally blocks do.

Speed, just ts bench on 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:

engine MIR ÷ THIR A/A ÷ THIR
Node 24.21 1.10 1.00
Bun 1.4.2 1.02 1.00
Chromium 155 1.12 1.01

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:

engine depth native wasm hand-written THIR generators MIR state machines THIR ÷ MIR
Node 1 53 156 303 374 241 1.55
Node 4 59 142 639 765 349 2.19
Node 16 74 225 1630 2580 956 2.70
Bun 1 53 115 261 418 237 1.76
Bun 4 59 132 450 1010 309 3.27
Bun 16 74 174 1360 3790 695 5.45
Chromium 1 53 108 153 241 169 1.43
Chromium 4 59 118 285 499 225 2.22
Chromium 16 74 174 783 1810 518 3.49

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 --route over A/A, where below 1 means the route is faster:

run codec Node codec Bun codec Chromium handoff Node handoff Bun handoff Chromium
abort 0.99 1.00 1.01 0.97 1.03 0.96
abort 1.00 0.99 1.00 0.94 1.00 0.90
abort 1.01 1.00 1.00 0.97 1.07 0.94
A/A control 0.97 1.00 1.00 0.94 0.95 0.98
A/A control 1.01 1.00 1.01 0.98 0.98 1.04

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:

bundle THIR MIR (unwind) MIR (abort)
codec, raw 48,525 50,222 (+3.5%) 50,192
codec, gzip 13,569 14,717 (+8.5%) 14,697
task, raw 25,762 45,034 (+75%) 41,607
task, gzip 8,153 11,038 (+35%) 10,649

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), self by value that drops (155), temporaries that drop (280), for loops 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), and ref mut bindings (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: ? on Poll<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's body.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

  1. ✅ Panics unwind, so drops run when a JS caller catches a panic, with no poison mechanism. It costs 3.7% gzip on the task fixture and, by the speed check above, 4-6% on the V8 async handoff (Node and Chromium), with Bun about 5% faster and the codec unchanged; the maintainer accepted that cost.
  2. ✅ Land the prototype behind --lower mir with its tests in CI, as the start of ts-mir.

Impact

  • rust2-ts gains --lower thir|mir (RUST2_TS_LOWER); THIR stays the default. Under mir the driver passes -C panic=unwind -Z ub-checks=no to the translated crate's rustc (RUST2_TS_ABORT=1 drops the first, for measuring).
  • The task fixture's sum panics 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's harness takes unwind; new tests/unwind.ts and fixtures/task/examples/unwind.rs; new tests codec_mir, lang_mir, task_mir, and reject_mir (against fixtures/reject/expected-mir.txt), and task also runs the unwinding test.
  • The TS AST gains switch, try/catch, throw, let x!: T, class fields with initializers, and postfix ++; the THIR lowering emits none of them.
  • library::Std names ControlFlow, Infallible, RangeTo, RangeFrom, RangeFull, Argument, and NonNull, which only MIR reaches.

Alternatives

Follow-ups

  • quest/m2/ts-mir.md: make MIR the only lowering, with the reject fixture, snapshots, census parity, and size work.
  • ts-mir-codec: the codec from MIR no slower than from THIR in any engine, which blocks ts-mir.
  • Found in passing: the bench's main slot ran 1-15% slower than --route for identical code, which fix(ts): shuffle the bench's order each round so no route keeps a slot #39's random order fixed.
  • Found in review, both lowerings: rt.copy copies a Copy aggregate through its shared references, duplicating an Arc or a Cell (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

kixelated and others added 13 commits October 24, 2026 11:34
Quest-Claim: e106caa154d47fdb
…s temporaries across calls

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
…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
@kixelated kixelated changed the title MIR lowering spike feat(ts): MIR lowering spike, which moves the translator to MIR Oct 24, 2026
@kixelated
kixelated marked this pull request as ready for review October 24, 2026 23:37
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T05:30:58.687929Z e77cea3 New commits
🔒 Security Review ✅ Completed 2026-10-25T05:30:45.221293Z e77cea3 New commits
ℹ️ About Codex in GitHub

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

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/place.rs Outdated
Comment on lines +70 to +72
&& (matches!(field_ty.kind(), ty::Ref(..))
|| part.is_constant()
|| matches!(part, Expr::Ident(_))) =>

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/mod.rs
Comment on lines +1151 to +1154
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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)

Comment thread ts/src/lower/mir/place.rs
Comment on lines +135 to +138
let method = match elem_ty.kind() {
ty::Uint(ty::UintTy::U8) => "subarray",
_ => "slice",
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Agreed, and 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)

kixelated and others added 2 commits October 24, 2026 17:21
…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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/rvalue.rs Outdated
Comment on lines +408 to +409
let value = match (ty.kind(), value.is_constant()) {
(ty::Ref(..), _) | (_, true) => value,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: 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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/call.rs
Comment on lines +272 to +276
let bytes = self.operand_frozen(&args[0].node, span, out);
int.method("fromBeBytes", vec![bytes])
}
};
done(value, false)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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)

kixelated and others added 2 commits October 24, 2026 18:02
…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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/mod.rs Outdated
Comment on lines +1324 to +1328
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/call.rs Outdated
Comment on lines +247 to +250
("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));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Drop 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/call.rs
Comment on lines +75 to +79
// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve ownership when 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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)

kixelated and others added 2 commits October 24, 2026 18:47
…'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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/place.rs Outdated
Comment on lines +292 to +293
&& !matches!(self.slots[place.local], Slot::Alias(_))
&& !(place.local.as_u32() == 1 && matches!(self.env, Env::Closure(_)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced: the 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)

kixelated and others added 2 commits October 24, 2026 20:32
…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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread ts/src/lower/mir/call.rs Outdated
return None;
}
match &self.slots[place.local] {
Slot::Alias(Some(target)) if target.is_path() || matches!(target, Expr::Index(..)) => Some(target.clone()),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 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)

kixelated and others added 2 commits October 24, 2026 21:01
…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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +433 to +436
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced 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)

kixelated and others added 2 commits October 24, 2026 21:21
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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment on lines +481 to +485
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reproduced 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 kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 kixelated left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@kixelated

Copy link
Copy Markdown
Collaborator Author

Ready to merge at e77cea3.

  • Decisions: panics unwind (✅, at a measured 4-6% on V8's async handoff, no difference on the codec). The prototype lands behind --lower mir with its tests in CI (✅). The codec's speed from MIR (10-12% behind THIR in V8, group encode 2-2.6x) is now ts-mir-codec, which blocks making MIR the only lowering.
  • Merged main with feat(ts): a type's functions are free functions in a module per type, from the tree-shaking spike #32: lowering from MIR now follows the module-per-type layout. A method's self is its first parameter, and a struct is built through construct. A coroutine stays a class whose methods are poll and [Symbol.dispose]. Snapshots were regenerated.
  • Review fixes since the last summary:
    • mem::replace through a captured reference is refused (157bdca).
    • Copying an FnMut closure is refused (a87d03b), with the new reject_mir test checking what MIR refuses.
    • A copy of a local changed in place no longer moves past a write to its field (e77cea3).
  • Checks: just check and just test pass locally in the current dev shell, CI passes on e77cea3, and quest check --base origin/main passes from outside the checkout.

(written by Opus 5.5)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant