Skip to content

Add Rust compiler - #2008

Draft
mellyeliu wants to merge 446 commits into
mainfrom
feat/stylex-rust-port
Draft

mellyeliu wants to merge 446 commits into
mainfrom
feat/stylex-rust-port

Conversation

@mellyeliu

@mellyeliu mellyeliu commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

No description provided.

@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 Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 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.YbeObiCVpf /tmp/tmp.xoGzrDwOWs

Results Base Patch Ratio
babel-plugin: stylex.create
· basic create 486 471 0.97 -
· complex create 54 52 0.96 -
babel-plugin: stylex.createTheme
· basic themes 433 438 1.01 +
· complex themes 30 31 1.03 +
stylex.props: application-order
· single style 34,062,331 33,574,662 0.99 -
· merge 3 styles 7,283,974 7,319,521 1.00 +
· merge 3 styles, first use 287,611 280,214 0.97 -
· conditional styles 3,699,380 3,991,619 1.08 !!
· many combinations 6,215,741 6,311,866 1.02 +
· dynamic styles 1,024,059 1,054,523 1.03 +
stylex.props: property-specificity
· single style 29,371,541 28,896,504 0.98 -
· merge 3 styles 6,756,947 7,415,517 1.10 !!
· merge 3 styles, first use 498,891 492,088 0.99 -
· conditional styles 3,640,901 3,793,909 1.04 +
· many combinations 6,315,148 5,980,185 0.95 !!
· dynamic styles 1,335,612 1,309,180 0.98 -
Done in 0.08s.
Done in 0.35s.

@github-actions

github-actions Bot commented Nov 5, 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.ZrhS5Dyrvi /tmp/tmp.yZC7ziEUXk

Results Base Patch Ratio
@stylexjs/stylex/lib/cjs/stylex.js
· compressed 1,862 1,862 1.00
· minified 6,141 6,141 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 538,354 538,354 1.00
· minified 7,447,226 7,447,226 1.00
benchmarks/size/.build/stylex.css
· compressed 99,748 99,748 1.00
· minified 741,101 741,101 1.00
Done in 0.07s.
Done in 0.27s.

@vercel

vercel Bot commented Nov 5, 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 3, 2026 5:12pm UTC

Request Review

@MarcelOlsen

MarcelOlsen commented Nov 24, 2026 •

Copy link
Copy Markdown

super glad to see an official rust compiler happening here, getting the full babel suite and host callbacks passing is huge.

know this is still a draft, so feel free to ignore for later, but we ran into a bunch of the same perf bottlenecks when building our own rust stylex compiler (oj_stylex) and i was curious where time goes on this branch. i ran a quick stage profile on 95538975 (opt-level = 3, lto = "thin", mimalloc, sourceMaps: false) against packages/benchmarks in case it's useful:

fixture total parse (NestingCheck) clone core emit (plan / apply+map / reparse / cmp)
create-complex.js 0.96 ms 0.06 ms (0.01) 0.01 ms 0.60 ms 0.24 ms (0.10 / 0.03 / 0.08 / 0.03)
createTheme-complex.js 7.67 ms 0.18 ms (0.02) 0.04 ms 6.77 ms 0.58 ms (0.05 / 0.27 / 0.20 / 0.07)
lotsOfStylesDynamic.js 6.10 ms 0.23 ms (0.09) 0.03 ms 2.56 ms 3.03 ms (1.28 / 0.25 / 0.99 / 0.51)
lotsOfStyles.js (7.3 MB, 163k rules) 1,202 ms 85.9 ms (15.4) 25.0 ms 725.9 ms 322.3 ms (96.1 / 39.1 / 109.1 / 78.0)
plain JS (32 KB, no stylex) 0.545 ms 0.439 ms (0.05) - - fast_path: 0.037 ms

and process_stylex_rules on the 163,593 rules from lotsOfStyles.js (352.9 ms total):

  • consts + clone: 17.6 ms
  • width_keys: 27.7 ms
  • sort (icu_collator): 282.9 ms (80%)
  • group + collect + regex: 21.9 ms

a few concrete things that jumped out:

  1. process_stylex_rules calling icu_collator inside sort_by (src/stylesheet/process.rs:57-91, 262-327)
    80% of stylesheet assembly is locale_compare running up to 3x per comparison. crates/stylex-css/src/utils/pre_rule.rs already has ASCII_PRIMARY_RANK for an ASCII fast path (or [babel-plugin] Sort compiler output by UTF-16 code units #2066's UTF-16 sort would make this plain slice comparison). in the same pass, skipping non-@ rules in width_keys, skipping rule cloning/regex when constants.is_empty(), and gating the THEMES regex on rule.contains(":root") should get assembly down to ~15–20 ms.

  2. double evaluation + ObjectLit deep-clones on member reads (crates/stylex-evaluator/src/evaluate/nodes/member_expression.rs:406-422, crates/stylex-evaluator/src/evaluate/binding.rs:194-212)
    this explains most of the 6.77 ms on createTheme-complex.js:

    • member_expression.rs:406-422 speculatively evaluates base_path to check for ThemeRef, and when it's not one, drops the result and calls evaluate_cached(&member.obj) again on line 421.
    • binding.rs:194-195 caches Rc<EvaluateResultValue> but returns (*value).clone(), which deep-clones the full SWC ObjectLit on every property read before linearly scanning Vec<PropOrSpread> (member_expression.rs:592). keeping immutable evaluated objects behind Rc with a key index made a massive difference for us on token/theme files.
  3. emitter work when sourceMaps: false + postflight re-parse (src/utils/source_edits.rs:480-490, 600-671, src/utils/transform/mod.rs:521-534)
    verify_output_typed makes total sense during bring-up, just worth noting it's ~25% of lotsOfStylesDynamic (1.50 ms) and ~187 ms on lotsOfStyles.js, so gating it behind debug_assertions or a CI flag later is a big free win. apply_source_edits also always builds the v3 source map even when sourceMaps: false drops it at transform/mod.rs:531.

  4. opt-in pre-parse byte gate for unplugin/bundler callers (src/utils/transform/mod.rs:445-465)
    always parsing makes sense for transformSync as a babel drop-in, but for the unplugin/vite path where most modules don't touch stylex and the bundler parses anyway, a memchr/memmem byte pre-gate before SWC parse drops plain files from ~0.5 ms to a couple microseconds.

  5. cross-call declaration memoization
    a bounded thread-local + sharded cross-thread cache keyed on (property, value, keyPath, options) around rule generation paid off a lot for us since atomic rules repeat heavily across files.

happy to help dig into any of these whenever this is ready for outside PRs!

`docs/values.md` covers the types, what each call's front end must produce, how the SWC front end answers for its nodes, and what still uses SWC in the core.
Values, refusal paths and memo witnesses hold arena clones (contexts kept).
EvaluationState carries the arena. Binary and logical expressions share a
view, and an optional link reads as SWC's OptChainExpr. The native engine's
'static stores hold tokens the evaluation heap resolves. A compiler callback
the JavaScript host holds refuses when called, since a 'static function
cannot reach the arena.
oxc walks some nodes as expressions that SWC did not, and the reverse.
The frame search now skips static keys and shorthand values, matches an
update's operand, matches optional chain links against whole chains,
and ignores a parameter's optional mark. Arrow parameters keep SWC's
span over their type annotation, through the strip as well.

Checked against the SWC implementation on 533 repository sources:
101914 expression lookups and 8654 declaration lookups agree.
A match becomes an array of its argument and one arrow per case. The
case's bindings are the arrow's parameters and a constant pattern is the
default of an empty object pattern, so every reference and binding keeps
its scope. A guard stays before the body, in the arrow's body. The text
grows, so offsets map back through the offset map. Neither the SWC Flow
parser nor Babel's flow plugin reads match, so this has no reference
output; bindings inside | alternatives and nested as or instance
patterns stay unsupported.
…ifferential

The root falls back to the SWC parser for Flow the oxc front end rejects,
as before, but counts a fallback only when SWC reads the file. Input both
parsers reject goes to SWC for its diagnostic. In an oxc-only build an
unsupported construct names the missing SWC Flow parser.

examples/flow_diff.rs parses each file with the SWC Flow parser and the
oxc front end and compares the IR with SWC's type syntax stripped, the
comment ranges, and optionally the binding partitions.
…sults

An object with a spread, shorthand or method passes the media-query transform unchanged, a rewritten one is marked compiler-made, and nested conditional values assert the strings they coerce to.
Each `AstHost` numbered its nodes from zero, so a node converted by one host and asked about through another was answered from an unrelated expression. Hosts now number from their own base and refuse a node outside the range they handed out. `createThemeNested` converts its variables again with the host that answers for its overrides instead of reusing nodes from the validation host.

Adds host tests for resolution from borrowed, listed and owned roots, an unbound identifier, a compiler-made node and a node from another host.
…interface

The transformers and the helpers below them read options, the export id and two caches through `StyleState` instead of `StateManager`, which also carries the evaluator's SWC declarations and bindings. `StateManager` implements it, so the AST layer passes its state unchanged.
A reprinted `a < b > (c)` read as a generic call in TypeScript. The
`<` comparison is now grouped when a `>` follows it. Regenerated Flow
classes copy back their blanked declared fields. The this-parameter facts
are sorted before lookup, as nested defaults record them inner first. The
output check reads `(f<T>)(x)` and `f<T>(x)` as the same call.
Own-property questions on an object with a known prototype chain read its
own entries, and string conversion reads each method along the chain as
OrdinaryToPrimitive does. Exponentiation follows Node's NaN rule on every
path and refuses a finite result Node may round differently. The final
review tests cover this and the previous fixes.
hasOwnProperty on an object whose known prototype holds the key answers
false, as Babel does; a prototype that redefines the method still refuses.
Node's `**` and `Math.pow` run fdlibm's pow as V8 adapted it, which
rounds differently from Rust's `powf`. The evaluator now ports that pow,
so folded powers match Node (3999 of 4000 random inputs on Node 22 here,
against 3817 before) and no longer refuse. The port keeps Sun's fdlibm
notice; NOTICE.md and the third-party notices name it, and NOTICE.md's
relative links now resolve.
…ypes

The own-property fast path now yields to an object's own method of that
name. Array and function prototypes, and custom prototypes whose own
chain is known, answer own-property questions; the setter follows a
nested chain that ends in null.
…tage

A rewrite that would print over a Flow match outside its case bodies now
refuses instead of writing the surrogate arrow. Class gaps mix blanked
members and authored semicolons. Superclass type arguments are restored.
A commented callback whose changed statement the body planner lacks is
reprinted whole. A TSX attribute sequence parses as Babel reads it, and
the import-kind check keys by decoded local names. The final review tests
cover this and the two previous fixes.
A changed Flow match is now planned through its surrogate call: the
matched argument and each case's guard and result, never a case arrow,
whose printed form would replace the authored pattern. The printed-match
check ignores white space at a printed part's edges. A superclass's type
arguments are now restorable, which the unit test expects.
`export default enum E {...}` became `export default let E=[...]`, which
does not parse, so such files refused where base compiled them. The
front end now blanks `export default` and inserts `;export default E;`
after the enum, which the offset map takes out again.
Node's pow differs between builds: V8's fdlibm compiled plainly, the same
code with fused multiply-adds (this host's Node 22), or a C library pow.
A single port answered 10 ** 13.375 as one build and so chose the wrong
branch under another. A power is now folded only when plain fdlibm, the
fused build (a port matched on 200,000 inputs) and the correctly rounded
power (256-bit, away from a rounding midpoint) agree, or when it is a
special, exact or out-of-range result. Other powers refuse. PROVENANCE.md
and NOTICE.md now name the ported source and its revision.
With mimalloc v3, a second Node worker crashed with SIGSEGV once the
worker that loaded the addon had exited: v3 frees its main thread data
with that thread, and the next thread's allocator setup reads it. The
addon now builds mimalloc's v2 sources on the targets where swc_malloc
uses mimalloc. Corpus timing is unchanged (www sample, 4000 files: 3.76 s
v2 vs 3.79 s v3 median). Base had the crash too.
Hermes and Babel read `component` before a line break as an identifier
(`component; C(s); {...}`), while Flow's parser read a component
declaration. The output then dropped a binding the authored code still
used. Such input now refuses. A `hook` before a line break already reads
as Hermes does. Base had the same wrong output.
fdlibm returns 1 / x for an exponent of -1, but the C library pow that
Node 24 runs rounds 0.9999999999999999 ** -1 to 1. The shortcut is gone;
-1 now goes through the engine-consensus check like other exponents.
A bodyless `component C(...)` was blanked as type-only, so the
line-break guard never ran and `component\nC(s);` dropped `s`, which
Hermes reads as runtime code. Hermes and Babel reject a bodyless
component (only `declare component` may omit the body), so it now
refuses.
…rated

A transform can copy one authored range more than once (dynamic styles
repeat their value). When one copy was copied from the source, the
other, printed from the AST, was not counted as regenerated, so the Flow
check missed what it dropped: a copied Flow component lost its props
object. Each printed authored subtree now counts its range less its own
copied descendants, in region prints and generated nodes alike. The
final review tests cover this and the two previous fixes.
The per-copy accounting counted the blanked Flow text the printer copies
back between statements and class members as regenerated, so changed
Flow callbacks with local declarations refused again. Copied gaps are now
recorded apart and taken out of every printed part.
The emitter's maps end a generated line at every JavaScript line
terminator, but composing through an inputSourceMap checked them against
LF-only lines and refused output with a lone CR, U+2028 or U+2029. The
direct map is now checked with the emitter's line counting.
The previous change checked every direct map with JavaScript line
counting, but maps from other producers count LF lines. The JavaScript
counting is now an option the emitter's composition sets.
Merges opt-f (c727293) on c2395ce. The only conflict was in
flow_ast::apply. It keeps the hook keywords c2395ce adds to the
restored ranges and uses the span table from opt-f.
A recorded source map in flow_swc_goldens.json reads as the typo AACK.
Port #2066. Rule ordering, pseudo keys, at-rule keys and createTheme at-rules now compare UTF-16 code units instead of ICU collation, so the icu_collator dependency is gone.
Their binder goldens are keyed by a hash of each file's bytes and list identifier byte offsets, and the inputs redeclare and leave names unused on purpose.
Two expected outputs now carry the longhand resets. The shorthand validation cases pin property-specificity, the only resolution that rejects or warns about those shorthands.
Upstream sorts the at-rule list with a bare sort(), which compares UTF-16 code units. The byte sort put U+E000..U+FFFF before supplementary characters, changing the nested rule text and its class hash. Inherited from before the merge.
…form

Flow's parser builds operator chains, qualified type names (a.b.c), JSX
member names (<a.b.c>) and match member patterns in loops, so the
parse's stack checks do not bound how deep the tree is, and dropping the
AST recursed once per level. to_javascript planned 128 bytes of stack
per byte of source for that drop. That fit Linux debug builds by less
than 2x and overflowed on macOS (arm64), where deep_input_is_too_deep
died with SIGBUS on the guard page of the stack stacker mapped.

The drop of Expression, Statement and Type, of both Qualified names, of
jsx::MemberExpression and of match_pattern::MemberPattern now moves to a
fresh stack when less than 256 KiB is left, so the plan can no longer
overflow.

The parser's stack check also missed recursion that does not pass
through with_loc. Member and call chains, parenthesized types, typeof
arguments and match patterns, blocks, a postfix ! chain, and helpers
that follow loop-built chains (JSX names, computed keys, typeof targets,
hook callees, trailing comment removal) now check the stack too, and so
do the walk that collects typeof names and the rewrite's walk over JSX
member names.
Main's #2078 bumped cross-spawn from 7.0.6 to 7.1.0, which quotes the bare command name when it runs a batch file through cmd.exe. A quoted batch file found on PATH reads %~dp0 as the working directory, so yarn's workspace-local rollup.cmd in packages/@stylexjs/stylex resolved its five '..' from the package directory and looked for D:\a\node_modules\rollup. The workflow now runs that package's prebuild and its two rollup builds through npm, which runs rollup unquoted, as it already does for babel-plugin.
… on Unix

The tests are copied from facebook/flow and assume Unix paths, so they fail on Windows. Parser behavior is unchanged.

This branch has not been deployed

No deployments
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.

3 participants