Skip to content

[rust-plugin] flow support and emitter fixes for the swc compiler - #2099

Closed
mellyeliu wants to merge 13 commits into
feat/stylex-rust-portfrom
stylex/rust-swc-flow
Closed

mellyeliu wants to merge 13 commits into
feat/stylex-rust-portfrom
stylex/rust-swc-flow

Conversation

@mellyeliu

Copy link
Copy Markdown
Member

Context

The native compiler has to handle Flow. Most StyleX files in our largest codebase are Flow, and many use component, hook, match or enum syntax. oxc can't parse Flow, and oj_stylex parses every file as TSX. The oxc prototype only gets Flow through an unpublished Flow parser and its own lowering. SWC's Flow parser is published and already reads components, hooks, enums and match, so this builds on #2008.

On a sample of 3,186 internal Flow files that the Babel plugin compiles, #2008 matched Babel on 1,670 (52%). Most of the rest were emitter refusals ("source edit produced invalid syntax", comment order). A few were Flow parse errors.

Let's fix those.

  • Apply the nine emitter and perf fixes from the earlier review of Add Rust compiler #2008.
  • Update SWC to swc_core 85 and swc_ecma_parser 48. It reads Flow function types with unnamed params and inline interface types.
  • Turn on Flow match. SWC lowers a match while parsing and names the subject after its byte offset, so the postflight reparse refused every file with a match. Those names are now compared by order.
  • Reparse code frames with the compiler's syntax instead of TypeScript, so dev line numbers work in Flow files.
  • Edit classes member by member. A change inside one method used to print the whole class again and move its comments.

SWC still can't parse renders*, typed for...of bindings, match object patterns with const bindings, and records. Those need SWC fixes.

Testing

  • Internal Flow sample: 3,164 of 3,186 files now match Babel (99.3%). 16 still refuse and 6 differ in code.
  • Against Babel with hermes-parser: StyleX's own Flow sources 258 of 259 and React's packages 1,414 of 1,414.
  • New tests/flow_syntax_current.cjs fails on Add Rust compiler #2008's head and passes here.
  • scripts/test.cjs passes apart from width_order_is_total_and_context_aware, which already fails on Add Rust compiler #2008. fmt and both clippy runs are clean.
  • Median time per file on 1,673 files both versions compile went from 990 µs to 855 µs.

Part of #2008

The source-preserving emitter re-emitted a whole region when a change sat
inside an `export default function`, a conditional or logical expression,
an assignment, an object method, or an `if`, `switch` or loop body. A
re-emitted region keeps the comments of the source it reuses and moves
every other comment in front of the region. When a reused comment came
before a moved one, the module was refused with "cannot preserve the
relative order of comments inside this AST replacement". Babel compiles
these modules.

The planner now descends into these shapes and edits only the changed
operands, bodies and statements, as it already does for function
declarations, calls, arrays and objects. The postflight check still
reparses the output and compares it with the transformed AST.

On the StyleX modules of a large app (agentcloud, 4,576 modules) this
removes all 59 comment-order refusals. It also removes the 11, 11 and 8
refusals on @astryxdesign/core 0.7.16, 0.7.15 and 0.7.1 sources.
A re-emitted region reuses unchanged source text and wraps it in
parentheses unless it fills a slot that takes any assignment expression.
As the callee or object of an optional chain link, that turned
`a?.b.map(f)` into `(a?.b.map)(f)`, which ends the chain early. The
postflight check caught the changed AST and refused the module with
"source edits do not reproduce the transformed AST; refusing a lossy or
ambiguous emission".

Reused chain text now goes in bare there, where it parses back as the
same chain. This removes the 3 lossy-emission refusals in the same app.
With a JavaScript host, the evaluator keeps objects and arrays as typed
heap values. A spread of a local constant inside a dynamic style, such as
`popup: (w) => ({...COMPACT_TYPE, width: w})`, then reached
`spread_own_properties` as a typed value it does not read. The transform
failed with "[UNIMPLEMENTED] The spread operator (...) is not supported
in this context". Without a host the constant is a plain object literal,
so only host embedders hit this.

The spread now materializes typed values first, as style values already
are, and then merges their own properties like Babel's `Object.assign`.
Every reference to an imported theme value asked for the import's path
again, with a fresh `package.json` cache each time. Under `commonJS` each
answer costs file-system probes and `package.json` reads, and with a host
resolver it costs a host call. The answer cannot change while one module
compiles, so the state manager now keeps it per importing file and
specifier.

Measured on 4,514 StyleX modules of a large app (agentcloud), on one
thread, with the median of 5 runs per module and a release build without
LTO, the total drops from 11.30 s to 9.81 s.
`apply_source_edits` always built a source map, writing a mapping segment
for every character of the module and copying the source into
`sourcesContent`. The transform drops that map unless `sourceMaps` is set
or an input map must be composed. The emitter now takes a `with_map` flag
and splices the edits directly when no map is wanted.

Measured the same way, the total drops from 9.81 s to 9.12 s.
The planner compared function headers by cloning both functions, bodies
included, at every nesting level. It compared each list item with its
original twice, once for provenance and once before editing it. And its
provenance check cloned every leaf of the modified item into a map.

Headers are now compared field by field without the body, each item is
compared once, and the modified item's leaves are matched against the
original's map as they are visited. Output is unchanged.

Measured the same way, the total drops from 9.12 s to 8.74 s.
A changed expression the planner could not edit in place was re-emitted
in parentheses, whatever its slot. Most such expressions are arrow
functions in an initializer or argument, so the output had
`const A = (() => <div className="..." />)` where Babel writes no
parentheses. Minifiers keep parentheses around a function on purpose, as
a hint to compile it eagerly, so this changed what the browser does.

The planner now knows when an expression fills a slot that takes any
assignment expression (an initializer, argument, element, property value,
JSX container, conditional branch, assigned value, or a returned, tested
or parenthesized expression). There a replacement is grouped only if it
is a sequence. Appended arguments, reused class property values and
reused primary expressions follow the same rule.

On the app's 4,576 StyleX modules, 634 files had 852 parenthesized
functions that neither Babel's output nor the source has. Now none do.
Under `application-order`, a shorthand such as `inset: 0` compiles with
`null` resets for its longhands. For a runtime `stylex.props` call, a
namespace keeps those resets only where an earlier argument may set the
key, and an unknown member read makes every later reset count. Babel
finds those reads with a `MemberExpression` visitor, which does not match
optional members. The Rust walk counted `p?.view` in
`[s.host, p?.view == null ? s.fill : s.at(p.view)]` as an unknown style,
so `s.fill` kept 8 resets that Babel drops.

The walk now skips optional links and visits only their object, computed
key, callee and arguments, as Babel does.

This removes the extra resets in 4 of the app's modules, including
`features/deltas/video/video-pane.tsx` and @astryxdesign/core's
`CodeBlock.tsx`.
Discovery records each JSX spread so the consumer pass can replace a
static `stylex.props(...)` spread with plain attributes. The record is
matched by shape. With `stylex.defaultMarker()` among the styles, the
producer pass rewrites the marker call inside the spread first, so the
consumer pass no longer found the record. The output kept
`{...{className: "..."}}` where Babel writes `className="..."`.

The consumer pass now records the current shape of every JSX spread
before it runs.

In the app this turns 5 remaining static `{...{className}}` spreads into
attributes.
swc_ecma_parser 48 reads Flow function types with unnamed params followed by
named ones, and inline interface types, which 47 rejected. Turn on Flow pattern
matching too.

SWC lowers a match while parsing and names the subject after the byte offset of
the match, so the postflight reparse of unchanged source saw different names and
refused every file with a match. Compare those names by order instead.
Code frames and dev line numbers reparse the module, but always as TypeScript.
A Flow file with Flow-only syntax such as import typeof failed that reparse, so
$$css and data-style-src lost their line numbers and the parse error went to
stderr. Share one syntax function between the compiler and the code frame.
A change inside a class method printed the whole class again. Formatting was
lost, comments inside moved above the class, and a comment between two reused
members was refused. Edit changed methods, constructors and field initializers
in place, as functions already are.
@vercel

vercel Bot commented Dec 2, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated
stylex Ignored Ignored Dec 2, 2026 9:08am UTC

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

workflow: benchmarks/size

Comparison of minified (terser) and compressed (brotli) size results, measured in bytes. Smaller is better.
yarn workspace v1.22.22
yarn run v1.22.22
$ node ./compare.js /tmp/tmp.P4U2eUtgsr /tmp/tmp.KVE1HPpJ9a

Results Base Patch Ratio
@stylexjs/stylex/lib/cjs/stylex.js
· compressed 1,547 1,547 1.00
· minified 5,197 5,197 1.00
@stylexjs/stylex/lib/cjs/inject.js
· compressed 1,790 1,790 1.00
· minified 4,908 4,908 1.00
benchmarks/size/.build/bundle.js
· compressed 496,665 496,665 1.00
· minified 4,854,716 4,854,716 1.00
benchmarks/size/.build/stylex.css
· compressed 99,697 99,697 1.00
· minified 741,204 741,204 1.00
Done in 0.07s.
Done in 0.28s.

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown

workflow: benchmarks/perf

Comparison of performance test results, measured in operations per second. Larger is better.
yarn workspace v1.22.22
yarn run v1.22.22
$ node ./compare.js /tmp/tmp.ywdKAacnXa /tmp/tmp.OKa4AxgdHu

Results Base Patch Ratio
babel-plugin: stylex.create
· basic create 585 602 1.03 +
· complex create 66 66 1.00
babel-plugin: stylex.createTheme
· basic themes 470 464 0.99 -
· complex themes 32 32 1.00
Done in 0.08s.
Done in 0.36s.

@mellyeliu

Copy link
Copy Markdown
Member Author

moved into #2008 (3d47fd4..12e1ce5), rebased on its new head. the emitter fixes were already there, so only the swc 48 update, flow match, code frame syntax and tests went in.

@mellyeliu mellyeliu closed this Dec 2, 2026
@mellyeliu
mellyeliu deleted the stylex/rust-swc-flow branch December 2, 2026 20:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant