From 505284b3f16ec0a5ab968219c1280c12d1eb5abb Mon Sep 17 00:00:00 2001 From: Joe Savona Date: Tue, 29 Apr 2025 18:03:20 +0900 Subject: [PATCH] [compiler] Null out source locations where not explicitly preserved Inspired by #32950. Specifically from https://github.com/facebook/react/issues/32950#issuecomment-2837887871, it sounds like Babel by default emits source map information for all nodes, even when they don't have a `loc` property set. Code coverage tools then pick up the synthesized source location information for this, leading to the issue described. A few google searches didn't turn up any documented way to opt-out of generating source span information, but AI tools answer that explicitly setting `node.loc = null` omits the node from source maps. This PR is a quick hack to confirm that. ghstack-source-id: 2ed630101ce25424cc0f364955167cc00ee6ac6e Pull Request resolved: https://github.com/facebook/react/pull/33051 --- .../ReactiveScopes/CodegenReactiveFunction.ts | 39 +++++++++++++- .../compiler/sourcemaps-simple.expect.md | 51 +++++++++++++++++++ .../fixtures/compiler/sourcemaps-simple.js | 4 ++ compiler/packages/snap/src/compiler.ts | 6 +++ compiler/packages/snap/src/reporter.ts | 10 ++++ compiler/packages/snap/src/runner-worker.ts | 1 + 6 files changed, 110 insertions(+), 1 deletion(-) create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.expect.md create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.js diff --git a/compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts b/compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts index 790a64b407..eb4d95333c 100644 --- a/compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts +++ b/compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts @@ -48,7 +48,7 @@ import {printIdentifier, printPlace} from '../HIR/PrintHIR'; import {eachPatternOperand} from '../HIR/visitors'; import {Err, Ok, Result} from '../Utils/Result'; import {GuardKind} from '../Utils/RuntimeDiagnosticConstants'; -import {assertExhaustive} from '../Utils/utils'; +import {assertExhaustive, hasOwnProperty} from '../Utils/utils'; import {buildReactiveFunction} from './BuildReactiveFunction'; import {SINGLE_CHILD_FBT_TAGS} from './MemoizeFbtAndMacroOperandsInSameScope'; import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors'; @@ -374,6 +374,8 @@ function codegenReactiveFunction( const countMemoBlockVisitor = new CountMemoBlockVisitor(fn.env); visitReactiveFunction(fn, countMemoBlockVisitor, undefined); + setMissingLocationsToNull(body); + return Ok({ type: 'CodegenFunction', loc: fn.loc, @@ -2681,3 +2683,38 @@ function compareScopeDeclaration( else if (aName > bName) return 1; else return 0; } + +function setMissingLocationsToNull(ast: any): void { + if (Array.isArray(ast)) { + ast.forEach(item => setMissingLocationsToNull(item)); + return; + } else if ( + ast == null || + typeof ast !== 'object' || + typeof ast['type'] !== 'string' + ) { + return; + } + if (ast['loc'] == null) { + ast['loc'] = { + start: {line: null, column: null, index: null}, + end: {line: null, column: null, index: null}, + filename: null, + identifierName: null, + }; + } + for (const key in ast) { + if (!hasOwnProperty(ast, key)) { + continue; + } + const value = ast[key]; + if (typeof value !== 'object') { + /* + * We handle this above too, but avoid extra function calls in the majority of + * cases where we're traversing an AST node's properties + */ + continue; + } + setMissingLocationsToNull(ast[key]); + } +} diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.expect.md new file mode 100644 index 0000000000..590b3d92f4 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.expect.md @@ -0,0 +1,51 @@ + +## Input + +```javascript +// @sourceMaps +export const Button = () => { + return ; +}; + +``` + +## Code + +```javascript +import { c as _c } from "react/compiler-runtime"; // @sourceMaps +export const Button = () => { + const $ = _c(1); + let t0; + if ($[0] === Symbol.for("react.memo_cache_sentinel")) { + t0 = ; + $[0] = t0; + } else { + t0 = $[0]; + } + return t0; +}; + +``` + +## Source Map + +``` +{ + "version": 3, + "names": [ + "Button", + "t0" + ], + "sources": [ + "sourcemaps-simple.ts" + ], + "sourcesContent": [ + "// @sourceMaps\nexport const Button = () => {\n return ;\n};\n" + ], + "mappings": "kDAAA;AACA,OAAO,MAAMA,MAAM,GAAGA,CAAA,K;SACb,OAAyB,CAAjB,QAAQ,EAAhB,MAAyB,C,qCAAzBC,EAAyB,C,CACjC", + "ignoreList": [] +} +``` + +### Eval output +(kind: exception) Fixture not implemented \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.js new file mode 100644 index 0000000000..dd68df6a86 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sourcemaps-simple.js @@ -0,0 +1,4 @@ +// @sourceMaps +export const Button = () => { + return ; +}; diff --git a/compiler/packages/snap/src/compiler.ts b/compiler/packages/snap/src/compiler.ts index 6fce644542..119364deb8 100644 --- a/compiler/packages/snap/src/compiler.ts +++ b/compiler/packages/snap/src/compiler.ts @@ -306,6 +306,7 @@ export type TransformResult = { original: string; forget: string; } | null; + sourceMap: BabelCore.BabelFileResult['map']; }; export async function transformFixtureInput( @@ -331,6 +332,9 @@ export async function transformFixtureInput( // with `cwd`, which is different across machines const virtualFilepath = '/' + filename; + // Check if we should emit source maps in the test fixture + const includeSourceMaps = firstLine.includes('@sourceMaps'); + const presets = language === 'typescript' ? TypescriptEvaluatorPresets @@ -357,6 +361,7 @@ export async function transformFixtureInput( 'babel-plugin-idx', ], sourceType: 'module', + sourceMaps: includeSourceMaps, ast: includeEvaluator, cloneInputAst: includeEvaluator, configFile: false, @@ -447,6 +452,7 @@ export async function transformFixtureInput( forgetOutput, logs: formattedLogs, evaluatorCode, + sourceMap: includeSourceMaps ? forgetResult.map : null, }, }; } diff --git a/compiler/packages/snap/src/reporter.ts b/compiler/packages/snap/src/reporter.ts index 9f7d1d9a50..5839f14650 100644 --- a/compiler/packages/snap/src/reporter.ts +++ b/compiler/packages/snap/src/reporter.ts @@ -5,6 +5,7 @@ * LICENSE file in the root directory of this source tree. */ +import {BabelFileResult} from '@babel/core'; import chalk from 'chalk'; import fs from 'fs'; import invariant from 'invariant'; @@ -24,6 +25,7 @@ export function writeOutputToString( evaluatorOutput: string | null, logs: string | null, errorMessage: string | null, + sourceMap: BabelFileResult['map'] | null, ) { // leading newline intentional let result = ` @@ -42,6 +44,14 @@ ${wrapWithTripleBackticks(compilerOutput, 'javascript')} result += '\n'; } + if (sourceMap != null) { + result += ` +## Source Map + +${wrapWithTripleBackticks(JSON.stringify(sourceMap, null, 2))} +`; + } + if (logs != null) { result += ` ## Logs diff --git a/compiler/packages/snap/src/runner-worker.ts b/compiler/packages/snap/src/runner-worker.ts index a72acf34db..305a0d54aa 100644 --- a/compiler/packages/snap/src/runner-worker.ts +++ b/compiler/packages/snap/src/runner-worker.ts @@ -245,6 +245,7 @@ export async function transformFixture( sproutOutput, compileResult?.logs ?? null, error, + compileResult?.sourceMap ?? null, ); return {