Turbopack: keep IIFEs with a PURE-annotated callee in production builds

Merged
SO
15d ago
+201-24

What?

In production builds, Turbopack removed side-effecting IIFEs whose callee is a PURE-annotated call, for example (/* @__PURE__ */ __name(function () { … }, "x"))(). esbuild emits this shape for keepNames output, so Radix UI dists are one affected example.

This PR fixes that, along with the member-expression form (/* @__PURE__ */ f()).g(), both with and without scope hoisting.

Why?

Turbopack runs SWC's fixer on every module after codegen, but it passed no comments. SWC's fixer intentionally keeps the parentheses around a PURE / NO_SIDE_EFFECTS-annotated callee or member object, but it can only do that when it can see the comments. Without them it drops the parens.

The printed code then reads /* @__PURE__ */ f()(). When the minifier re-parses it, the annotation applies to the outer call, and the whole call is removed as an unused pure expression. webpack is unaffected.

How?

  • ReadOnlyComments adapter in swc_comments.rs. It gives the fixer a read-only view over both the parsed module comments and the comments added by codegen.
    • has_* / get_* read every store.
    • has_flag is overridden to only read. It shares its matcher with ImmutableComments, because SWC's default implementation takes the comments and re-adds them.
    • add_*, take_* and add_pure_comment panic, so the adapter can't be used where comments really need to change.
    • move_* are deliberate no-ops: the fixer calls them for every pair of parentheses it removes. Ignoring them keeps the comments where they were, which is the same as before the fixer saw any comments.
  • process_parse_result now passes the adapter to the fixer. The only behavioural difference is that annotated callees and objects keep their parentheses.

Tests:

  • Execution tests minification/pure-annotated-callee and pure-annotated-callee-no-scope-hoisting. They run minified code and assert that both the IIFE and the .run() side effects happen. Without this fix, the scope-hoisted variant loses both, and the other variant loses the member call.
  • .prettierignore: the two test inputs are excluded, because Prettier rewrites ;(/* @__PURE__ */ f())() into /* @__PURE__ */ f()(), which is exactly the shape under test.

Verification:

  • cargo test -p turbopack-tests --test execution passes, with no ReadOnlyComments panic.
  • cargo test -p turbopack-tests --test snapshot passes, with no snapshot changes.
  • Not run: a Next.js e2e test against a rebuilt native binary.

Fixes #99897