react/compiler/packages/eslint-plugin-react-compiler/__tests__/shared-utils.ts
Joseph Savona 7d29ecbeb2
[compiler] Aggregate error reporting, separate eslint rules (#34176)
NOTE: this is a merged version of @mofeiZ's original PR along with my
edits per offline discussion. The description is updated to reflect the
latest approach.

The key problem we're trying to solve with this PR is to allow
developers more control over the compiler's various validations. The
idea is to have a number of rules targeting a specific category of
issues, such as enforcing immutability of props/state/etc or disallowing
access to refs during render. We don't want to have to run the compiler
again for every single rule, though, so @mofeiZ added an LRU cache that
caches the full compilation output of N most recent files. The first
rule to run on a given file will cause it to get cached, and then
subsequent rules can pull from the cache, with each rule filtering down
to its specific category of errors.

For the categories, I went through and assigned a category roughly 1:1
to existing validations, and then used my judgement on some places that
felt distinct enough to warrant a separate error. Every error in the
compiler now has to supply both a severity (for legacy reasons) and a
category (for ESLint). Each category corresponds 1:1 to a ESLint rule
definition, so that the set of rules is automatically populated based on
the defined categories.

Categories include a flag for whether they should be in the recommended
set or not.

Note that as with the original version of this PR, only
eslint-plugin-react-compiler is changed. We still have to update the
main lint rule.

## Test Plan

* Created a sample project using ESLint v9 and verified that the plugin
can be configured correctly and detects errors
* Edited `fixtures/eslint-v9` and introduced errors, verified that the w
latest config changes in that fixture it correctly detects the errors
* In the sample project, confirmed that the LRU caching is correctly
caching compiler output, ie compiling files just once.

Co-authored-by: Mofei Zhang <feifei0@meta.com>
2025-08-21 14:53:34 -07:00

77 lines
2.1 KiB
TypeScript

import {RuleTester as ESLintTester, Rule} from 'eslint';
import {type ErrorCategory} from 'babel-plugin-react-compiler/src/CompilerError';
import escape from 'regexp.escape';
import {configs} from '../src/index';
import {allRules} from '../src/rules/ReactCompilerRule';
/**
* A string template tag that removes padding from the left side of multi-line strings
* @param {Array} strings array of code strings (only one expected)
*/
export 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');
}
export type CompilerTestCases = {
valid: ESLintTester.ValidTestCase[];
invalid: ESLintTester.InvalidTestCase[];
};
export function makeTestCaseError(reason: string): ESLintTester.TestCaseError {
return {
message: new RegExp(escape(reason)),
};
}
export function testRule(
name: string,
rule: Rule.RuleModule,
tests: {
valid: ESLintTester.ValidTestCase[];
invalid: ESLintTester.InvalidTestCase[];
},
): void {
const eslintTester = new ESLintTester({
// @ts-ignore[2353] - outdated types
parser: require.resolve('hermes-eslint'),
parserOptions: {
ecmaVersion: 2015,
sourceType: 'module',
enableExperimentalComponentSyntax: true,
},
});
eslintTester.run(name, rule, tests);
}
/**
* Aggregates all recommended rules from the plugin.
*/
export const TestRecommendedRules: Rule.RuleModule = {
meta: {
type: 'problem',
docs: {
description: 'Disallow capitalized function calls',
category: 'Possible Errors',
recommended: true,
},
// validation is done at runtime with zod
schema: [{type: 'object', additionalProperties: true}],
},
create(context) {
for (const rule of Object.values(
configs.recommended.plugins['react-compiler'].rules,
)) {
const listener = rule.create(context);
if (Object.entries(listener).length !== 0) {
throw new Error('TODO: handle rules that return listeners to eslint');
}
}
return {};
},
};
test('no test', () => {});