mirror of
https://github.com/hanzoai/react.git
synced 2026-09-24 17:02:27 +00:00
This is an experimental, work-in-progress port of React Compiler to Rust. Key points: * Work-in-progress - we are sharing early, prior to testing internally at Meta, to get feedback from partners in parallel with continued development. * No builds available yet, you'll have to do some hacking if you want to try this. * All fixtures pass, no known gaps but there may be lurking bugs. * The architecture was heavily guided by humans (me, @josephsavona) but majority coded by AI. I was very hands-on in setting the architecture, the testing and verification strategy, incremental migration approach, etc. I also kept a close eye on the code and spent a decent amount of time going back and forth to get code quality to a decent level. * The public API is basically "Rust Babel AST" + Scope Info in, Rust Babel AST out. We use a Rust representation of the Babel AST as our "public API", as it were, and then each integration (Babel, OXC, SWC) converts to/from their native representation. For now integrations must also provide scope information - in the future React Compiler may compute bindings and references itself from the AST. * Internally, the Rust version uses the same architecture as the TypeScript version. The compiler converts from the AST into our own intermediate representation (HIR, short for High-level Intermediate Representation) which uses a control-flow graph (CFG) and single-static assignment (SSA). We go through the same series of passes, with the same overall algorithms. It's very much a pass-by-pass port. The main differences are in the data representation - using arena-like structures (and indices into these arenas) to work within Rust's borrowing system. * Early performance numbers are derived from AI and i haven't spent much time validating the benchmark setup, beyond the fact that the optimization opportunities it discovered made complete sense and the fixes were right. With that caveat, itt does appear that the Rust version is quite fast already: 3x faster when operating as a Babel plugin. The serialization cost is quite high, but the actual transformation logic is ~10x faster, so it's net faster. Native integrations (oxc, swc) should be even faster. * There are 3 integrations right now: an alternative Babel plugin (which will eventually get removed as we integrate into babel-plugin-react-compiler), and examples of what OXC and SWC integrations could look like (see react_compiler_oxc and react_compiler_swc crates). correctness: * all 1725 fixtures pass in snap when comparing the temporary rust version of the plugin with the main version. this compares generated code output as well as errors. * all fixtures also pass a full comparison of the per-pass compiler intermediate representation — the intermediate state (including log events and errors) are ~identical after every single pass (modulo some normalization of ids) * The OXC and SWC example integrations seem to be working well, though i haven't manually verified this to the same extent as i have the Babel integration. development: * `yarn snap --rust` is the primary test suite, testing that we error or compile as expected. It does not test the inner state of the compiler along the way, though, making it less suitable for finding subtle logic gaps btw the TS and Rust versions. It's also Babel based, making it less easy to test OXC and SWC integrations. * `compiler/scripts/test-e2e.sh` is an e2e test of all 3 variants (babel wrapper around Rust, OXC/SWC integrations) against the TS implementation. This does a partial comparison, focused on final output code only (doesn't test error details etc). Useful for getting the swc and oxc integrations closer to parity. * `compiler/script/test-rust-port.sh` does detailed testing of the internal compiler state after each pass, in addition to checking the final output code. This is the key script used to port the compiler, ensuring not just that the output was the same but that each pass was capturing all the same detail. This script can be pointed at *any* directory of JS files, which we expect to use for internal testing at Meta. ## For Partners We're excited to partner with teams to integrate the Rust version of React Compiler into other tools, like OXC and SWC. If you're interested in working with us on this, the best place to start is by taking a look at the react_compiler_swc and react_compiler_oxc crates. These give you an idea of the API shape that we're thinking of. Note that the conversion from any AST into our HIR is complex, and we can only maintain one version. Hence we've aligned on using a Babel-like AST as our public API. Another key point is that we don't yet implement our own scope analysis (since the TS version of the compiler relied on Babel's scope analysis), so for now we require that the scope data be serialized. It's a denormalized graph, and some metadata has to be stored to associate nodes with scopes. We're open to feedback about the AST and scope representation - we iterated a bit just to get things to work, but it can be more optimal. Key changes that we are considering: * Currently the compiler returns `Option<Program>`, which is `Some` if anything changed. This requires replacing the entire program. We plan to change this to return a series of patches to apply, in a form that is reasonably usable and efficient for all the integrations we care about (Babel, OXC, SWC, etc). * The Rust representation of the Babel AST is fine enough, but we could make it more optimal by doing arena allocation. We also plan to change the string representation to smol_str. * The scope representation, and association of data btw AST and scope, is very much a first pass approach that is good enough. We expect to implement our own scope resolution, though, so we hopefully won't need to iterate on the scope representation and can just throw it away. In terms of the shape of the integration, we anticipate that each integration would have the following: * Implementor repo (OXC, SWC, etc): lightweight code transform and lint pipeline integration that delegates to `crates/react_compiler_<name>` from our repo * Our repo: one crate per implementor, eg react_compiler_swc, react_compiler_oxc, where most of the logic lives. This setup lets us make changes to the integration layer easily within our repo. Feedback appreciated! --------- Co-authored-by: Joe Savona <[email protected]> Co-authored-by: Mike Vitousek <[email protected]> Co-authored-by: Mike Vitousek <[email protected]> Co-authored-by: lauren <[email protected]> Co-authored-by: lauren <[email protected]>
565 lines
15 KiB
TypeScript
565 lines
15 KiB
TypeScript
/**
|
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*/
|
|
|
|
/**
|
|
* Comparison test: runs every ESLint test case with both the TS and Rust
|
|
* backends and asserts the diagnostics (message + line) are identical.
|
|
*
|
|
* Uses ESLint's Linter API directly (not RuleTester) so we can capture
|
|
* the full list of diagnostics per backend without throwing on the first
|
|
* mismatch.
|
|
*/
|
|
|
|
import {Linter} from 'eslint';
|
|
import {configs} from '../src/index';
|
|
import {
|
|
allRules,
|
|
recommendedRules,
|
|
mapErrorSeverityToESlint,
|
|
} from '../src/rules/ReactCompilerRule';
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Check Rust availability
|
|
// --------------------------------------------------------------------------
|
|
let rustAvailable = false;
|
|
try {
|
|
require('babel-plugin-react-compiler-rust');
|
|
rustAvailable = true;
|
|
} catch {
|
|
// Rust native module not built — skip all comparison tests
|
|
}
|
|
|
|
const describeIfRust = rustAvailable ? describe : describe.skip;
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Helpers
|
|
// --------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Remove leading indentation (same as normalizeIndent in shared-utils).
|
|
*/
|
|
function normalizeIndent(strings: TemplateStringsArray): string {
|
|
const codeLines = strings[0].split('\n');
|
|
const leftPadding = codeLines[1]?.match(/\s+/)?.[0] ?? '';
|
|
return codeLines.map(line => line.slice(leftPadding.length)).join('\n');
|
|
}
|
|
|
|
interface DiagnosticSummary {
|
|
message: string;
|
|
line: number | null;
|
|
}
|
|
|
|
/**
|
|
* Lint `code` using all recommended rules and return sorted diagnostics.
|
|
*/
|
|
function lintWithBackend(
|
|
code: string,
|
|
filename: string,
|
|
useRust: boolean,
|
|
): DiagnosticSummary[] {
|
|
const linter = new Linter();
|
|
|
|
// Register all rules from the plugin
|
|
for (const [name, {rule}] of Object.entries(allRules)) {
|
|
linter.defineRule(`react-compiler/${name}`, rule);
|
|
}
|
|
|
|
// Build the rule config: enable all recommended rules at their default severity
|
|
const ruleConfig: Record<string, Linter.RuleEntry> = {};
|
|
for (const [name, ruleEntry] of Object.entries(recommendedRules)) {
|
|
const severity = mapErrorSeverityToESlint(ruleEntry.severity);
|
|
if (severity === 'off') continue;
|
|
const opts: Record<string, unknown> = {};
|
|
if (useRust) {
|
|
opts.__unstable_useRustCompiler = true;
|
|
}
|
|
ruleConfig[`react-compiler/${name}`] = [severity, opts];
|
|
}
|
|
|
|
const messages = linter.verify(
|
|
code,
|
|
{
|
|
parser: 'hermes-eslint',
|
|
parserOptions: {
|
|
ecmaVersion: 2015,
|
|
sourceType: 'module',
|
|
enableExperimentalComponentSyntax: true,
|
|
},
|
|
rules: ruleConfig,
|
|
},
|
|
{filename},
|
|
);
|
|
|
|
// Filter out parser errors — only keep rule diagnostics
|
|
const diagnostics: DiagnosticSummary[] = messages
|
|
.filter(m => m.ruleId != null)
|
|
.map(m => ({
|
|
message: m.message,
|
|
line: m.line ?? null,
|
|
}));
|
|
|
|
// Sort deterministically by line then message
|
|
diagnostics.sort((a, b) => {
|
|
const lineDiff = (a.line ?? 0) - (b.line ?? 0);
|
|
if (lineDiff !== 0) return lineDiff;
|
|
return a.message.localeCompare(b.message);
|
|
});
|
|
|
|
return diagnostics;
|
|
}
|
|
|
|
/**
|
|
* Lint with a specific single rule (not recommended set).
|
|
*/
|
|
function lintWithRule(
|
|
code: string,
|
|
filename: string,
|
|
ruleName: string,
|
|
useRust: boolean,
|
|
): DiagnosticSummary[] {
|
|
const linter = new Linter();
|
|
|
|
const ruleEntry = allRules[ruleName];
|
|
if (!ruleEntry) throw new Error(`Unknown rule: ${ruleName}`);
|
|
|
|
linter.defineRule(`react-compiler/${ruleName}`, ruleEntry.rule);
|
|
|
|
const opts: Record<string, unknown> = {};
|
|
if (useRust) {
|
|
opts.__unstable_useRustCompiler = true;
|
|
}
|
|
const severity = mapErrorSeverityToESlint(ruleEntry.severity);
|
|
if (severity === 'off') return [];
|
|
|
|
const messages = linter.verify(
|
|
code,
|
|
{
|
|
parser: 'hermes-eslint',
|
|
parserOptions: {
|
|
ecmaVersion: 2015,
|
|
sourceType: 'module',
|
|
enableExperimentalComponentSyntax: true,
|
|
},
|
|
rules: {
|
|
[`react-compiler/${ruleName}`]: [severity, opts],
|
|
},
|
|
},
|
|
{filename},
|
|
);
|
|
|
|
const diagnostics: DiagnosticSummary[] = messages
|
|
.filter(m => m.ruleId != null)
|
|
.map(m => ({
|
|
message: m.message,
|
|
line: m.line ?? null,
|
|
}));
|
|
|
|
diagnostics.sort((a, b) => {
|
|
const lineDiff = (a.line ?? 0) - (b.line ?? 0);
|
|
if (lineDiff !== 0) return lineDiff;
|
|
return a.message.localeCompare(b.message);
|
|
});
|
|
|
|
return diagnostics;
|
|
}
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Test case catalog — every test case from the existing test files
|
|
// --------------------------------------------------------------------------
|
|
|
|
interface ComparisonTestCase {
|
|
name: string;
|
|
code: string;
|
|
filename?: string;
|
|
/** Which rule to test in isolation, or 'recommended' for all */
|
|
rule: string;
|
|
expectedErrorCount: number;
|
|
}
|
|
|
|
// Gather all test cases from across the test suite. We replicate the test
|
|
// data here so the comparison is self-contained.
|
|
|
|
const testCases: ComparisonTestCase[] = [
|
|
// ---- PluginTest-test.ts (recommended rules) ----
|
|
{
|
|
name: '[PluginTest] Basic example with component syntax',
|
|
code: normalizeIndent`
|
|
export default component HelloWorld(
|
|
text: string = 'Hello!',
|
|
onClick: () => void,
|
|
) {
|
|
return <div onClick={onClick}>{text}</div>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[PluginTest] [Invariant] Defined after use',
|
|
code: normalizeIndent`
|
|
function Component(props) {
|
|
let y = function () {
|
|
m(x);
|
|
};
|
|
|
|
let x = { a };
|
|
m(x);
|
|
return y;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: "[PluginTest] Classes don't throw",
|
|
code: normalizeIndent`
|
|
class Foo {
|
|
#bar() {}
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[PluginTest] Multiple diagnostic kinds from the same function',
|
|
code: normalizeIndent`
|
|
import Child from './Child';
|
|
function Component() {
|
|
const result = cond ?? useConditionalHook();
|
|
return <>
|
|
{Child(result)}
|
|
</>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 2,
|
|
},
|
|
{
|
|
name: '[PluginTest] Multiple diagnostics within the same file',
|
|
code: normalizeIndent`
|
|
function useConditional1() {
|
|
'use memo';
|
|
return cond ?? useConditionalHook();
|
|
}
|
|
function useConditional2(props) {
|
|
'use memo';
|
|
return props.cond && useConditionalHook();
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 2,
|
|
},
|
|
{
|
|
name: "[PluginTest] 'use no forget' does not disable eslint rule",
|
|
code: normalizeIndent`
|
|
let count = 0;
|
|
function Component() {
|
|
'use no forget';
|
|
return cond ?? useConditionalHook();
|
|
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
{
|
|
name: '[PluginTest] Multiple non-fatal useMemo diagnostics',
|
|
code: normalizeIndent`
|
|
import {useMemo, useState} from 'react';
|
|
|
|
function Component({item, cond}) {
|
|
const [prevItem, setPrevItem] = useState(item);
|
|
const [state, setState] = useState(0);
|
|
|
|
useMemo(() => {
|
|
if (cond) {
|
|
setPrevItem(item);
|
|
setState(0);
|
|
}
|
|
}, [cond, item, init]);
|
|
|
|
return <Child x={state} />;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 4,
|
|
},
|
|
|
|
// ---- InvalidHooksRule-test.ts ----
|
|
{
|
|
name: '[InvalidHooks] Basic example (valid)',
|
|
code: normalizeIndent`
|
|
function Component() {
|
|
useHook();
|
|
return <div>Hello world</div>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[InvalidHooks] Violation with Flow suppression (valid)',
|
|
code: `
|
|
// Valid since error already suppressed with flow.
|
|
function useHook() {
|
|
if (cond) {
|
|
// $FlowFixMe[react-rule-hook]
|
|
useConditionalHook();
|
|
}
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[InvalidHooks] Simple violation',
|
|
code: normalizeIndent`
|
|
function useConditional() {
|
|
if (cond) {
|
|
useConditionalHook();
|
|
}
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
{
|
|
name: '[InvalidHooks] Multiple diagnostics within the same function',
|
|
code: normalizeIndent`
|
|
function useConditional() {
|
|
cond ?? useConditionalHook();
|
|
props.cond && useConditionalHook();
|
|
return <div>Hello world</div>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 2,
|
|
},
|
|
|
|
// ---- ImpureFunctionCallsRule-test.ts ----
|
|
{
|
|
name: '[ImpureFunctionCalls] Known impure function calls are caught',
|
|
code: normalizeIndent`
|
|
function Component() {
|
|
const date = Date.now();
|
|
const now = performance.now();
|
|
const rand = Math.random();
|
|
return <Foo date={date} now={now} rand={rand} />;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 3,
|
|
},
|
|
|
|
// ---- NoCapitalizedCallsRule-test.ts ----
|
|
{
|
|
name: '[NoCapitalizedCalls] Simple violation',
|
|
code: normalizeIndent`
|
|
import Child from './Child';
|
|
function Component() {
|
|
return <>
|
|
{Child()}
|
|
</>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
{
|
|
name: '[NoCapitalizedCalls] Method call violation',
|
|
code: normalizeIndent`
|
|
import myModule from './MyModule';
|
|
function Component() {
|
|
return <>
|
|
{myModule.Child()}
|
|
</>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
{
|
|
name: '[NoCapitalizedCalls] Multiple diagnostics',
|
|
code: normalizeIndent`
|
|
import Child1 from './Child1';
|
|
import MyModule from './MyModule';
|
|
function Component() {
|
|
return <>
|
|
{Child1()}
|
|
{MyModule.Child2()}
|
|
</>;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 2,
|
|
},
|
|
|
|
// ---- NoAmbiguousJsxRule-test.ts ----
|
|
{
|
|
name: '[NoAmbiguousJsx] JSX in try blocks',
|
|
code: normalizeIndent`
|
|
function Component(props) {
|
|
let el;
|
|
try {
|
|
el = <Child />;
|
|
} catch {
|
|
return null;
|
|
}
|
|
return el;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
|
|
// ---- NoRefAccessInRender-tests.ts ----
|
|
{
|
|
name: '[NoRefAccessInRender] Simple ref access in render',
|
|
code: normalizeIndent`
|
|
function Component(props) {
|
|
const ref = useRef(null);
|
|
const value = ref.current;
|
|
return value;
|
|
}
|
|
`,
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
|
|
// ---- ReactCompilerRuleTypescript-test.ts ----
|
|
{
|
|
name: '[TypeScript] Basic example (valid)',
|
|
code: normalizeIndent`
|
|
function Button(props) {
|
|
return null;
|
|
}
|
|
`,
|
|
filename: 'test.tsx',
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[TypeScript] Repro for hooks as normal values',
|
|
code: normalizeIndent`
|
|
function Button(props) {
|
|
const scrollview = React.useRef<ScrollView>(null);
|
|
return <Button thing={scrollview} />;
|
|
}
|
|
`,
|
|
filename: 'test.tsx',
|
|
rule: 'recommended',
|
|
expectedErrorCount: 0,
|
|
},
|
|
{
|
|
name: '[TypeScript] Mutating useState value',
|
|
code: `
|
|
import { useState } from 'react';
|
|
function Component(props) {
|
|
// typescript syntax that hermes-parser doesn't understand yet
|
|
const x: \`foo\${1}\` = 'foo1';
|
|
const [state, setState] = useState({a: 0});
|
|
state.a = 1;
|
|
return <div>{props.foo}</div>;
|
|
}
|
|
`,
|
|
filename: 'test.tsx',
|
|
rule: 'recommended',
|
|
expectedErrorCount: 1,
|
|
},
|
|
];
|
|
|
|
// --------------------------------------------------------------------------
|
|
// Tests
|
|
// --------------------------------------------------------------------------
|
|
|
|
describeIfRust('TS vs Rust backend comparison', () => {
|
|
const results: Array<{
|
|
name: string;
|
|
ts: DiagnosticSummary[];
|
|
rust: DiagnosticSummary[];
|
|
match: boolean;
|
|
}> = [];
|
|
|
|
for (const tc of testCases) {
|
|
test(tc.name, () => {
|
|
const filename = tc.filename ?? 'test.js';
|
|
const tsDiags = lintWithBackend(tc.code, filename, false);
|
|
const rustDiags = lintWithBackend(tc.code, filename, true);
|
|
|
|
results.push({
|
|
name: tc.name,
|
|
ts: tsDiags,
|
|
rust: rustDiags,
|
|
match: JSON.stringify(tsDiags) === JSON.stringify(rustDiags),
|
|
});
|
|
|
|
// First check: both backends agree on error count
|
|
if (tsDiags.length !== rustDiags.length) {
|
|
const tsMessages = tsDiags
|
|
.map(d => ` L${d.line}: ${d.message}`)
|
|
.join('\n');
|
|
const rustMessages = rustDiags
|
|
.map(d => ` L${d.line}: ${d.message}`)
|
|
.join('\n');
|
|
console.log(
|
|
`\n⚠️ DIAGNOSTIC COUNT MISMATCH: ${tc.name}\n` +
|
|
` TS (${tsDiags.length}):\n${tsMessages || ' (none)'}\n` +
|
|
` Rust (${rustDiags.length}):\n${rustMessages || ' (none)'}\n`,
|
|
);
|
|
}
|
|
|
|
// Second check: messages match in content
|
|
// We compare sorted diagnostics — message text should be identical
|
|
const tsMessages = tsDiags.map(d => d.message);
|
|
const rustMessages = rustDiags.map(d => d.message);
|
|
|
|
// Log detailed diff for any mismatch
|
|
if (JSON.stringify(tsDiags) !== JSON.stringify(rustDiags)) {
|
|
console.log(
|
|
`\n⚠️ DIAGNOSTIC MISMATCH: ${tc.name}\n` +
|
|
` TS diagnostics:\n${tsDiags.map(d => ` L${d.line}: ${d.message}`).join('\n') || ' (none)'}\n` +
|
|
` Rust diagnostics:\n${rustDiags.map(d => ` L${d.line}: ${d.message}`).join('\n') || ' (none)'}\n`,
|
|
);
|
|
}
|
|
|
|
// Assert equality — both count and messages should match
|
|
expect(rustDiags.length).toBe(tsDiags.length);
|
|
expect(rustMessages).toEqual(tsMessages);
|
|
});
|
|
}
|
|
|
|
// Summary — printed once after all tests
|
|
afterAll(() => {
|
|
const total = results.length;
|
|
const matches = results.filter(r => r.match).length;
|
|
const mismatches = results.filter(r => !r.match);
|
|
|
|
console.log('\n' + '='.repeat(70));
|
|
console.log(`TS vs Rust ESLint Backend Comparison`);
|
|
console.log('='.repeat(70));
|
|
console.log(`Total test cases: ${total}`);
|
|
console.log(`Matching: ${matches}`);
|
|
console.log(`Mismatches: ${mismatches.length}`);
|
|
|
|
if (mismatches.length > 0) {
|
|
console.log('\nMismatched cases:');
|
|
for (const m of mismatches) {
|
|
console.log(`\n ❌ ${m.name}`);
|
|
console.log(
|
|
` TS (${m.ts.length}): ${m.ts.map(d => `L${d.line}:${d.message.slice(0, 60)}`).join(' | ') || '(none)'}`,
|
|
);
|
|
console.log(
|
|
` Rust(${m.rust.length}): ${m.rust.map(d => `L${d.line}:${d.message.slice(0, 60)}`).join(' | ') || '(none)'}`,
|
|
);
|
|
}
|
|
} else {
|
|
console.log('\n✅ All diagnostics match between TS and Rust backends!');
|
|
}
|
|
console.log('='.repeat(70) + '\n');
|
|
});
|
|
});
|