Skip to content

feat(ts): smaller MIR output - #79

Merged
kixelated merged 15 commits into
mainfrom
quest/m2/ts-mir-size
Oct 26, 2026
Merged

kixelated merged 15 commits into
mainfrom
quest/m2/ts-mir-size

Conversation

@kixelated

@kixelated kixelated commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

#67 made MIR the only lowering, and its bundles grew against THIR's: the async handoff's to 18281 bytes minified and 4005 gzipped, with each async fn a class of about 520 bytes minified, and the codec's to 30487 and 9835. A browser consumer ships these bytes.

Approach

Each change was measured on the bench's bundles (Bun, minified, gzip -9) and kept only if it shrank them:

  • Coroutine classes. The state, captures, and saved locals are private fields (#state, #rx, #awaitee), which a minifier renames. A poll after the future returned or panicked calls rt.asyncFnResumed() / rt.asyncFnResumedPanic() rather than inlining the message. A call to a crate async fn whose body only moves its arguments into its future constructs the future directly (new recvFuture(rx)), so the wrapper function shakes out when nothing else calls it.
  • No else after a branch that leaves. A final pass splices an if's else after it when its then returns, throws, breaks, or continues.
  • Locals declared where first assigned. A local whose other references all follow its first statement-level assignment in the same block is declared there, const if written once, rather than in the let list at the top.
  • Fewer temporaries. A drop JS can't see no longer counts as a read, so a local read once besides such a drop folds into its reader. The stepped-iterator analysis counts drops the same way.
  • Fewer unwind = writes. A block's cleanup is known on entry when every predecessor left it the same, not only a sole predecessor.

It also records the maintainer's decision that the translator targets browsers, in quest/m2/README.md and ts/README.md's design section.

Impact

Output shape only. Behavior is unchanged, and just ts test compares every fixture against native Rust.

  • A coroutine's fields are private (#name) and saved locals lose their _ affixes. Nothing outside the class read them. A field that would be #constructor, which JS forbids, is #_constructor.
  • A positional constructor's parameters are escaped where strict code reserves the name (eval_), which also fixes a capture named eval or arguments, a SyntaxError on main.
  • A call to an async fn that only makes its future is new xFuture(...); the exported function x stays.
  • New runtime exports: rt.asyncFnResumed and rt.asyncFnResumedPanic.

Size

bundle THIR main this PR vs main vs THIR
codec, minified 30629 30487 30000 -1.6% -2.1%
codec, gzip 9422 9835 9540 -3.0% +1.3%
handoff, minified 10949 18281 15119 -17.3% +38%
handoff, gzip 3458 4005 3757 -6.2% +8.6%

THIR is #67's parent and main is main before #78, both built from the same fixtures; merging #78 moved this PR's codec by 4 bytes. Each step as built, in order (minified/gzip):

step codec handoff
main 30487/9835 18281/4005
no else after a branch that leaves 30221/9804 18131/4002
rt.asyncFnResumed* 30221/9804 17022/3982
private fields 30221/9804 15597/3929
new xFuture at the call 30221/9804 15156/3824
declared where assigned, else hoisted as a final pass 30015/9562 15128/3757
cleanup known from every predecessor 30015/9562 15119/3757
invisible drops aren't reads 29996/9545 15119/3756

Private fields alone are worth 1078 bytes minified and 28 gzipped on the handoff.

Speed

just ts bench with main as an extra route, before #78 merged: the geometric mean of this PR ÷ main, and of the A/A route ÷ main for the noise. Below 1 is faster.

runtime codec, this PR codec, A/A handoff, this PR handoff, A/A
Chrome 155 1.001 0.996 0.943 1.000
Node 24 0.989 0.998 1.013 0.991
Bun 1.4 0.986 0.993 1.045 1.067

Private fields cost V8 bytecode: this.#x is two bytecodes to this.x's one, so each level's poll grows 19% (186 to 221 bytes), and V8 inlines fewer nested polls under its budget.

  • Node 24. Timed as 25 alternating processes per minified bundle at depths 1/4/16, against main: private 1.023/1.013/1.050, public 1.012/1.005/1.010, A/A 1.010/0.980/0.995. With V8's inlining budget raised, private ran 3.6% faster than main at depth 16.
  • Chrome 155. No loss. In just ts bench with a public-field build as the route, private ÷ public is 0.960/1.009/0.826 at depths 1/4/16 (0.928 geomean, A/A 0.980). Its codec is 0.997 (A/A 1.007). That run shared the machine with other builds, so Node's and Bun's handoff in it are noise (A/A off by 12-25%).

Alternatives

  • Public coroutine fields: level with main in Node at depth 16, but 1078 bytes minified larger. Dropped: browsers decide (see below).
  • Closures instead of classes (the state in captured lets): smaller, but 1.3-1.8x slower on the handoff in Node.
  • Destructuring tuple temporaries (const [a, b] = ..): array destructuring measured 10x slower than indexing in JSC on the codec's take chains.
  • Restructuring the resume dispatch (a dispatch at each loop header rather than a switch): size-neutral on both bundles.
  • Skipping unwind = before a call that only makes a future: the write then lands between the future's construction and its store, which stops the fold, and the handoff grew 159 bytes minified.
  • Generators, as THIR had: 1.4-5.5x slower on the handoff, per Lower bodies from MIR #67.

Decisions

  • ✅ The translator targets browsers. Node and Bun stand in for V8 and JavaScriptCore; a native runtime uses rust2-ffi. Recorded in quest/m2/README.md (2026-10-26) and ts/README.md's design section.
  • ✅ Private coroutine fields (#state), taken despite Node 24's 5% at depth 16, since Chrome shows no loss and the maintainer prefers private fields where possible.

Follow-ups

The quest stays, rewritten to what remains. It now uses THIR numbers built from today's fixtures; the old ones came from an earlier codec fixture. Left:

  • A coroutine class is still about 360 bytes minified against about 140 for a THIR generator. A runtime base class for the poison-and-drop scaffolding, or sharing fields between saved locals never live at once, is next, timed in Chrome on minified bundles.
  • The handoff's code outside the classes is about 140 bytes gzipped over THIR's.
  • The codec's gzip is 1.3% over THIR's.
  • Firefox (SpiderMonkey) isn't in just ts bench yet: ts-bench-firefox, from chore(quest): typed copies, char and vec!, Firefox bench, narrower bench reruns #80, covers it.

(written by Opus 5.5)

🤖 Generated with Claude Code

https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn

kixelated and others added 9 commits October 26, 2026 06:56
Quest-Claim: da18cb1fbc3274b7
…nch that leaves

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
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
…fast

A `this.#field` access is two bytecodes in V8 to a public field's one, so each level's
`poll` grew 19% and Node 24 inlined fewer of them, 5% slower at depth 16.

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 Smaller output from MIR feat(ts): smaller MIR output Oct 26, 2026
kixelated and others added 2 commits October 26, 2026 09:28
# Conflicts:
#	ts/fixtures/codec/expected/lite/message.ts
#	ts/fixtures/lang/expected/harness.ts
#	ts/fixtures/lang/expected/shapes.ts
#	ts/fixtures/task/expected/model.ts
The translator targets browsers, so a minifier renaming the fields wins over Node's
inlining budget at the deepest nesting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
@kixelated
kixelated marked this pull request as ready for review October 26, 2026 16:44
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T17:09:31.911907Z 0b66bee New commits
🔒 Security Review ✅ Completed 2026-10-26T17:11:19.855608Z 0b66bee 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.

@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 head 3356958ee05a000ca8847f22934aac2c67f46f6d against 1d710c4c74aa068b5386352082ef0c9baa462d6b.

Two actionable correctness findings below: reserved private-field naming and incomplete traversal of arrow-body expressions before narrowing local scopes. No prior findings to classify as fixed or still open.

Direction: the measured, browser-focused size reductions and guarded async-wrapper bypass are reasonable; these are local fixes, not reasons to introduce a larger lowering abstraction.

Verification: GitHub source/diff and surrounding lowering/printer code inspection only; I did not run the translator, fixtures, type checks, or benchmarks. The current-head Check workflow was still running when inspected.

let mut upvars = Vec::new();
for (i, ty) in coroutine.upvar_tys().iter().enumerate() {
let name = names.get(i).cloned().unwrap_or_else(|| format!("u{i}"));
let name = format!("#{}", names.get(i).cloned().unwrap_or_else(|| format!("u{i}")));

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.

[P2] Escape the forbidden private name #constructor

A valid input such as async fn f(constructor: u32) -> u32 { constructor } now names its capture #constructor. JavaScript forbids that private field name, so the generated class cannot parse. Previously Program::name saw public constructor in the class's taken names and renamed it; the new # prefix bypasses that protection. Saved locals named constructor have the same problem at lines 115–116. Reserve/rename #constructor before uniquifying private names, and add capture/saved-local fixtures for it.

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 1e1b578. Field naming in Program maps #constructor to #_constructor, so this covers both captures and saved locals. The same repro exposed a second problem: a class constructor is strict code, so a capture named eval or arguments can't be a parameter. This one predates the PR. Positional constructor parameters now go through escape and are numbered with unique. The task fixture's slot takes captures named constructor and eval, and tsc rejected both before the fix.

(written by Opus 5.5)

Comment thread ts/src/lower/mir/mod.rs Outdated
visit_expr(a, f);
visit_expr(b, f);
}
Expr::Arrow(_, _, body) => body.iter().for_each(|s| visit_stmt(s, f)),

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.

[P2] Recurse into expressions held by arrow-body statements

visit_stmt passes only each directly held expression to f; it does not call visit_expr on that expression. Consequently the expr_names callback sees the Call in () => { return f(x); }, but never its Ident(x), and counts zero reads. If a local is initialized inside a loop/block and referenced afterward only by such a closure, place_declaration can move its declaration into the initializer's inner scope and leave the closure referring to an out-of-scope name. Walk each arrow statement's expression with visit_expr (not just f) and add a regression where a loop-initialized local is captured in a compound return expression after the loop.

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 1e1b578. visit_expr's arrow arm now runs visit_expr on each expression an arrow statement holds. Both visitors take &mut dyn FnMut so the recursion monomorphizes once. I tried a fixture where a loop-initialized local is read after the loop only by a closure. The structurer nests post-loop code inside the loop's exit branch, so that case stayed in scope and couldn't hit the bug. The regression is therefore a unit test, lower::mir::tests::declare_counts_arrow_reads, which fails without the fix.

(written by Opus 5.5)

kixelated and others added 3 commits October 26, 2026 10:03
…rrow reads

`#constructor` is the one private name JS forbids, and a class's constructor is strict
code, where `eval` and `arguments` can't be parameters. A read inside an arrow's
statement, below its top expression, went uncounted, so a declaration could move into
a block the arrow is outside.

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 head 0b66bee6d61de78044580a6424d0bef791ccd8ae since my review of 3356958ee05a000ca8847f22934aac2c67f46f6d, excluding changes brought in from the updated base 20bcc26f9569a76d44c24deacb291bf847f9b131.

Both prior findings are addressed in the code:

  • Private-field naming: Program::name escapes #constructor for captures and saved locals; constructor parameters are now separately escaped and uniquified. The task fixture covers constructor and eval.
  • Arrow-body traversal: statement expressions are now recursively visited, with an AST-level regression test. As noted in the reply, the attempted Rust loop example did not reproduce the scope failure; the new test directly exercises the faulty pass.

No new actionable bugs found in this delta. The localized fixes and reuse of existing name escaping are appropriate; no larger abstraction is needed.

Verification: GitHub source/diff inspection only. I did not run tests, type checks, or benchmarks; the current-head Check workflow was still running when inspected.

@kixelated
kixelated merged commit 7d2bbe1 into main Oct 26, 2026
1 check passed
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