Skip to content

feat(minifier): inline single use function declaration to assignment - #28121

Closed
armano2 wants to merge 11 commits into
oxc-project:mainfrom
armano2:feat/inline_single_use_function_declaration
Closed

armano2 wants to merge 11 commits into
oxc-project:mainfrom
armano2:feat/inline_single_use_function_declaration

Conversation

@armano2

@armano2 armano2 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Move an immediately preceding single-use function declaration into an assignment expression.

function a() {} b.a = a; -> b.a = function a() {};

@armano2
armano2 requested a review from Dunqing as a code owner October 23, 2026 02:03
@github-actions github-actions Bot added the A-minifier Area - Minification, compression and name mangling, oxc_minifier / oxc_mangler label Oct 23, 2026
@codspeed

codspeed Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 77 untouched benchmarks
⏩ 19 skipped benchmarks1


Comparing armano2:feat/inline_single_use_function_declaration (597df54) with main (8239dac)

Open in CodSpeed

Footnotes

  1. 19 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@Dunqing Dunqing left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good. It seems we can implement this in substitute_single_use_symbol_in_statement, which could reduce some repeated checks, but I haven't verified it yet.

@armano2

armano2 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Looks good. It seems we can implement this in substitute_single_use_symbol_in_statement, which could reduce some repeated checks, but I haven't verified it yet.

thats a good idea, i'm going to check it latter on

@oddharsh

Copy link
Copy Markdown
Contributor

Hey, I saw you're planning to look at moving this into substitute_single_use_symbol_in_statement, so I prototyped the general version on top of this branch (597df54) to see what it's worth before you spend time on it. On minsize it saves 65,354 B minified and 15,106 B gzip, idempotent on all 12 files. Below are the numbers and the traps I hit, which might save you all some of the same digging.

What it does: A function declaration with exactly one reference moves into that reference as a function expression. The reference could be an argument, a callee, a property value, or the right side of an assignment as in this PR:

function c() { function f() { g() } h('x', f) }
// => function c() { h('x', function() { g() }) }

function c() { function f() { g() } return function() { f() } }
// => function c() { return function() { g() } }

Inside a closure it'd move only as a callee, where the function object never escapes, so creating it once per call can't be observed. It'd never move into a loop.

A second, smaller change would turn a strict function IIFE into an arrow when its body uses no this, arguments, new.target, super, class or direct eval. The existing arrow-IIFE fold then applies, which is what turns the callee case above into g().

Size. minsize against this branch's head:

file minified gzip
react.development.js -256 -84 (-1.03%)
moment.js -997 -497 (-2.65%)
jquery.js -135 -9 (-0.03%)
vue.js -1,511 -445 (-1.04%)
lodash.js -1,247 -743 (-2.90%)
d3.js -2,755 -467 (-0.53%)
bundle.min.js -1,047 -55 (-0.05%)
three.js -1,803 -647 (-0.41%)
victory.js -4,779 -2,159 (-1.35%)
echarts.js -8,419 -2,042 (-0.64%)
antd.js -3,039 -804 (-0.18%)
typescript.js -39,366 -7,154 (-0.85%)
total -65,354 -15,106 (-0.67%)

Iterations would stay the same, save for three.js and echarts.js (2 to 3). On my personal site's 26 scripts, oxc trails SWC by 1,132 B brotli, and this closes the gap by 495 B. SWC makes the same move through reduce_vars.

Speed. Local only: minifySync through the napi build, median of 7 runs on an M3 Max. typescript.js +4%, lodash.js +8%, echarts.js +14%, three.js +16%. CodSpeed would be the real answer.

Traps I ran into, each caught by minsize's idempotency check or a test:

  1. Shadowing would need a rename. Moving f into a closure is wrong if a scope in between binds a name f reads, and a refusal there depends on source names that mangling then changes. In lodash, runInContext binds a local Array, so pass 1 refuses to move setToPairs. Mangling renames the local, and pass 2 moves it.

    Renaming the capturing binding to a fresh uid and then moving keeps both passes in agreement. The rename gives up on ({ x } = y) (the AST name is also the key), on arguments/eval, and on names keep_names protects.

  2. Chains cost a pass per link. If f is only referenced inside g, and g only inside h, deferring f until g settles took typescript.js from 4 to 11 iterations. Every check reads the live scope tree, so both can move in the same pass.

  3. It might make sense to move the name binding too. A declaration that becomes an expression should bind its name in its own scope (move_binding_by_symbol_id). Left in the outer scope, it looks like a shadow on the next check.

  4. Shorthand. { f } has to become { f: function() {} }. Skipping shorthand made React non-idempotent, because oxc folds f: f into shorthand and mangling expands it again.

  5. Strictness. Nothing ends up moving out of a sloppy-mode block (Annex B binds f in the function too), and no sloppy function moves into a class body, where it would turn strict.

State. About 520 lines in two files, using unregister_function_declaration from this PR. 62 existing test expectations change (fixtures whose helpers now move or become arrows); I've read each diff but haven't rewritten them. The tiny-helper case SWC also handles, pasting the body and substituting arguments, is #27381 and isn't included.

How would you like me to go from here? I can definitely push the branch so you can read it, you can fold whatever's useful into this PR, or I can open it as a follow-up once this lands.

Disclosure: I built the prototype and ran these measurements with Claude Code, and I've reviewed the code and numbers before posting.

@Dunqing

Dunqing commented Oct 30, 2026

Copy link
Copy Markdown
Member

/monitor-oxc run

@oxc-guard

oxc-guard Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

@Dunqing

Dunqing commented Oct 30, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-11-02T07:46:19.403602Z 597df54 Manual request
ℹ️ About Codex in GitHub

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

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" 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

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@Dunqing

Dunqing commented Nov 2, 2026

Copy link
Copy Markdown
Member

@codex review

@Dunqing

Dunqing commented Nov 2, 2026

Copy link
Copy Markdown
Member

/monitor-oxc run

@oxc-guard

oxc-guard Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Minify Size

feat/inline_single_use_function_declaration vs main

965 of 109,516 files changed.

files changed raw gzip -9 brotli q5
normal 108,351 879
879 smaller, 0 larger
-17,249 B (-0.003%)
501.92 MB → 501.90 MB
-9,026 B (-0.006%)
148.11 MB → 148.10 MB
-9,815 B (-0.007%)
136.18 MB → 136.17 MB
already minified (*.min.js) 1,165 86
86 smaller, 0 larger
-960 B (-0.002%)
54.32 MB → 54.32 MB
-1,025 B (-0.007%)
14.16 MB → 14.16 MB
-1,235 B (-0.009%)
13.23 MB → 13.23 MB

Full report (Test Minify Size summary): top files and packages each way, and before/after diffs of the files that changed most.

Output bytes of oxc's full minify pipeline (compress + mangle + whitespace) over monitor-oxc's node_modules corpus; gzip and brotli compress each file on its own and are summed. Sizes only: correctness is in the Monitor Oxc comment. Identical pnpm peer-variant copies were counted once (384 collapsed).

@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: 597df54817

ℹ️ About Codex in GitHub

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

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

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

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

) {
if ctx.is_tree_shake_only()
|| Self::is_script_root_scope(ctx)
|| ctx.current_scope_flags().contains_direct_eval()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Check the declaration's binding scope for direct eval

In sloppy Script/CommonJS, an Annex B block function can be hoisted into the enclosing function scope, while DirectEval propagates upward rather than into child blocks. Consequently, function outer(){ { function f(){} globalThis.saved=f; } return eval('typeof f'); } passes this guard: the block has no direct eval, and the assignment is the only resolved reference to f. Inlining removes the implicit outer binding, changing outer() from returning "function" to "undefined". Check the declaration symbol's binding scope for direct eval as well before removing it.

Useful? React with 👍 / 👎.

let symbol_id = id.symbol_id();
// check if symbol: is referenced once, is implicitly observable, as function is dead, has redeclarations
if ctx.scoping().get_resolved_reference_ids(symbol_id) != [reference.reference_id()]
|| ctx.state.symbols.is_implicitly_observable(symbol_id)

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 Seed Annex B observability when unused removal is disabled

With unused: Keep, including CompressOptions::safest(), symbol_liveness::register_function skips the registration path that marks Annex B aliases implicitly observable. In sloppy Script/CommonJS, { function f(){return 1} } { function f(){return 2} globalThis.saved=f; } console.log(f()); therefore allows the second declaration through this check: its block-local symbol has one resolved reference and no redeclarations. Inlining removes its implicit assignment to the outer f, so the program prints 1 instead of 2. Record Annex B observability independently of recursive-function removal, or explicitly exclude these declarations here.

Useful? React with 👍 / 👎.

@armano2

armano2 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

@oddharsh i'm not going to have time for now to follow up on this, feel free to follow up on this change if you want

@oddharsh

oddharsh commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Thanks @armano2, happy to pick it up.

Here's the plan, so it stays reviewable:

  1. A new PR with your commits from this branch with your authorship kept, plus a merge of current main (the only conflict was the allocs snapshot, now regenerated). Same scope as this one (declaration into an assignment). If that lands, this PR can close in its favor.
  2. The general version from my earlier comment as a separate PR on top, with the 62 changed test expectations rewritten and Dunqing's suggestion to route it through substitute_single_use_symbol_in_statement.

On the monitor-oxc run from 2026-11-02: I went through the logs, and I don't think the red rows come from this change. The Test262 diff only removes 9 known failures and adds none, which looks like the branch's snapshot falling behind main. The codegen failure is a dropped /** @type {Range} */ comment in webpack's BasicEvaluatedExpression.js, and codegen doesn't run the compressor. I'll rerun it on the new PR to confirm.

Dunqing added a commit that referenced this pull request Nov 16, 2026
…28917)

Carries on #28121 by @armano2, who [handed it
off](#28121 (comment)).
Their 8 commits are unchanged and still theirs. On top: one commit that
widens where the declaration can come from, two Annex B fixes from
review, and a snapshot refresh. The branch is rebased onto current
`main`.

Moves a single-use function declaration into the assignment that uses
it:

```js
function a() {} b.a = a;
// => b.a = function a() {};

function a() { g() } function b() { h() } exports.a = a; exports.b = b;
// => exports.a = function() { g() }, exports.b = function() { h() };
```

**Where it applies.** The declaration can sit anywhere earlier in the
same statement list, and the target can be any assignment in a sequence
or a chain (`r.a = r.b = f`). The assignment holds the only reference,
so no statement in between can observe the move; creating a function has
no side effects, and a statement that exits early just means the
function is never created. It skips `with`, compound operators (`+=`),
declarations that come after the use, redeclared names, direct `eval` in
the binding's scope, the script root scope, and the sloppy-mode Annex B
cases below, each with a test.

**Why the whole list (94c6291).** I first tried looking back only
through the run of preceding declarations, which covers the common
CommonJS export block. minsize's idempotency check failed on three.js:
merging expression statements into a sequence and inlining a single-use
`var` don't request another pass, so the move landed on the second
minify instead of the first. Searching the whole list doesn't depend on
what an earlier pass left in between.

**Annex B (added in review).** In sloppy mode, evaluating a block-level
function declaration also writes the enclosing var binding (Annex
B.3.2.1), and semantic doesn't record that write as a reference. The
move is now skipped when:

- a sloppy block declaration would lose its write to an enclosing var
binding (75756ea);
- a same-named block function in an earlier statement overwrites the
outer function before the assignment reads it, e.g. `function f() {
return 1 } if (c) { function f() { return 2 } } exports.f = f`
(bd25837);
- a direct `eval` in the enclosing var scope can read a hoisted block
function. The eval check now uses the binding's scope, not only the
current block (bd25837).

Neither fix changes any minsize or allocation number.

**Size** (minsize, against `main` e4703b1):

| file | minified | gzip |
|---|--:|--:|
| typescript.js | -6,500 | -4,429 |
| lodash.js | -965 | -626 |
| d3.js | -916 | +342 |
| moment.js | -604 | -408 |
| antd.js | -489 | -424 |
| victory.js | -474 | -286 |
| three.js | -246 | -237 |
| react.development.js | -75 | -51 |
| echarts.js | -59 | +33 |
| bundle.min.js | -10 | +1 |
| vue.js | -9 | +4 |
| **total** | **-10,347** | **-6,081** |

d3 gets worse under gzip. I think moving helper bodies into the export
block at the end splits up code gzip was matching, but I haven't
confirmed it. three.js goes from 2 to 3 iterations; the rest are
unchanged.

**Rebase onto `main`.** The minsize and allocation snapshots were
regenerated after the rebase (6452484). One Annex B test input was
adjusted there so `main`'s new unused-label removal doesn't rewrite it.

**Tests.** `cargo test -p oxc_minifier` passes and clippy is clean. CI
is green at 6452484, including Conformance, Minification Size and
Allocations. Monitor Oxc last ran on an earlier head (45c8273; results
and analysis are in the comments) and still needs a rerun on this one.

The general version (any single reference, such as call arguments and
`return f`) follows as a separate PR once this one settles.

Disclosure: I wrote the extension, did the merge, and wrote this
description with Claude Code, and I've reviewed all three. The Annex B
fixes were written with AI assistance (Codex for 75756ea, Claude Code
for bd25837) and checked by running original and minified output side
by side.

---------

Co-authored-by: armano <armano2@users.noreply.github.com>
Co-authored-by: Aadharsh Pannirselvam <19518661+oddharsh@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: qing deng <dengqing0821@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
@armano2 armano2 closed this Nov 20, 2026
@armano2
armano2 deleted the feat/inline_single_use_function_declaration branch November 20, 2026 18:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-minifier Area - Minification, compression and name mangling, oxc_minifier / oxc_mangler

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants