Skip to content

Commit d325f87

Browse files
authored
[compiler][be] Logger based debug printing in test runner (#31809)
Avoid mutable logging enabled state and writing to `process.stdout` within our babel transform.
1 parent ac17270 commit d325f87

File tree

8 files changed

+78
-173
lines changed

8 files changed

+78
-173
lines changed

compiler/packages/babel-plugin-react-compiler/package.json

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,7 @@
4242
"babel-jest": "^29.0.3",
4343
"babel-plugin-fbt": "^1.0.0",
4444
"babel-plugin-fbt-runtime": "^1.0.0",
45-
"chalk": "4",
4645
"eslint": "^8.57.1",
47-
"glob": "^7.1.6",
4846
"invariant": "^2.2.4",
4947
"jest": "^29.0.3",
5048
"jest-environment-jsdom": "^29.0.3",

compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts

Lines changed: 2 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,6 @@ import {
7979
rewriteInstructionKindsBasedOnReassignment,
8080
} from '../SSA';
8181
import {inferTypes} from '../TypeInference';
82-
import {
83-
logCodegenFunction,
84-
logDebug,
85-
logHIRFunction,
86-
logReactiveFunction,
87-
} from '../Utils/logger';
88-
import {assertExhaustive} from '../Utils/utils';
8982
import {
9083
validateContextVariableLValues,
9184
validateHooksUsage,
@@ -139,13 +132,7 @@ function run(
139132
name: 'EnvironmentConfig',
140133
value: prettyFormat(env.config),
141134
});
142-
printLog({
143-
kind: 'debug',
144-
name: 'EnvironmentConfig',
145-
value: prettyFormat(env.config),
146-
});
147-
const ast = runWithEnvironment(func, env);
148-
return ast;
135+
return runWithEnvironment(func, env);
149136
}
150137

151138
/*
@@ -158,10 +145,8 @@ function runWithEnvironment(
158145
>,
159146
env: Environment,
160147
): CodegenFunction {
161-
const log = (value: CompilerPipelineValue): CompilerPipelineValue => {
162-
printLog(value);
148+
const log = (value: CompilerPipelineValue): void => {
163149
env.logger?.debugLogIRs?.(value);
164-
return value;
165150
};
166151
const hir = lower(func, env).unwrap();
167152
log({kind: 'hir', name: 'HIR', value: hir});
@@ -545,28 +530,3 @@ export function compileFn(
545530
code,
546531
);
547532
}
548-
549-
function printLog(value: CompilerPipelineValue): CompilerPipelineValue {
550-
switch (value.kind) {
551-
case 'ast': {
552-
logCodegenFunction(value.name, value.value);
553-
break;
554-
}
555-
case 'hir': {
556-
logHIRFunction(value.name, value.value);
557-
break;
558-
}
559-
case 'reactive': {
560-
logReactiveFunction(value.name, value.value);
561-
break;
562-
}
563-
case 'debug': {
564-
logDebug(value.name, value.value);
565-
break;
566-
}
567-
default: {
568-
assertExhaustive(value, 'Unexpected compilation kind');
569-
}
570-
}
571-
return value;
572-
}

compiler/packages/babel-plugin-react-compiler/src/Inference/AnalyseFunctions.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import {
1919
import {deadCodeElimination} from '../Optimization';
2020
import {inferReactiveScopeVariables} from '../ReactiveScopes';
2121
import {rewriteInstructionKindsBasedOnReassignment} from '../SSA';
22-
import {logHIRFunction} from '../Utils/logger';
2322
import {inferMutableContextVariables} from './InferMutableContextVariables';
2423
import {inferMutableRanges} from './InferMutableRanges';
2524
import inferReferenceEffects from './InferReferenceEffects';
@@ -112,7 +111,11 @@ function lower(func: HIRFunction): void {
112111
rewriteInstructionKindsBasedOnReassignment(func);
113112
inferReactiveScopeVariables(func);
114113
inferMutableContextVariables(func);
115-
logHIRFunction('AnalyseFunction (inner)', func);
114+
func.env.logger?.debugLogIRs?.({
115+
kind: 'hir',
116+
name: 'AnalyseFunction (inner)',
117+
value: func,
118+
});
116119
}
117120

118121
function infer(

compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/InferReactiveScopeVariables.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import {
2525
eachPatternOperand,
2626
} from '../HIR/visitors';
2727
import DisjointSet from '../Utils/DisjointSet';
28-
import {logHIRFunction} from '../Utils/logger';
2928
import {assertExhaustive} from '../Utils/utils';
3029

3130
/*
@@ -156,7 +155,11 @@ export function inferReactiveScopeVariables(fn: HIRFunction): void {
156155
scope.range.end > maxInstruction + 1
157156
) {
158157
// Make it easier to debug why the error occurred
159-
logHIRFunction('InferReactiveScopeVariables (invalid scope)', fn);
158+
fn.env.logger?.debugLogIRs?.({
159+
kind: 'hir',
160+
name: 'InferReactiveScopeVariables (invalid scope)',
161+
value: fn,
162+
});
160163
CompilerError.invariant(false, {
161164
reason: `Invalid mutable range for scope`,
162165
loc: GeneratedSource,

compiler/packages/babel-plugin-react-compiler/src/Utils/logger.ts

Lines changed: 0 additions & 110 deletions
This file was deleted.

compiler/packages/snap/src/compiler.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type {
1919
PanicThresholdOptions,
2020
PluginOptions,
2121
CompilerReactTarget,
22+
CompilerPipelineValue,
2223
} from 'babel-plugin-react-compiler/src/Entrypoint';
2324
import type {Effect, ValueKind} from 'babel-plugin-react-compiler/src/HIR';
2425
import type {
@@ -45,6 +46,7 @@ export function parseLanguage(source: string): 'flow' | 'typescript' {
4546
function makePluginOptions(
4647
firstLine: string,
4748
parseConfigPragmaFn: typeof ParseConfigPragma,
49+
debugIRLogger: (value: CompilerPipelineValue) => void,
4850
EffectEnum: typeof Effect,
4951
ValueKindEnum: typeof ValueKind,
5052
): [PluginOptions, Array<{filename: string | null; event: LoggerEvent}>] {
@@ -182,15 +184,15 @@ function makePluginOptions(
182184
.filter(s => s.length > 0);
183185
}
184186

185-
let logs: Array<{filename: string | null; event: LoggerEvent}> = [];
186-
let logger: Logger | null = null;
187-
if (firstLine.includes('@logger')) {
188-
logger = {
189-
logEvent(filename: string | null, event: LoggerEvent): void {
190-
logs.push({filename, event});
191-
},
192-
};
193-
}
187+
const logs: Array<{filename: string | null; event: LoggerEvent}> = [];
188+
const logger: Logger = {
189+
logEvent: firstLine.includes('@logger')
190+
? (filename, event) => {
191+
logs.push({filename, event});
192+
}
193+
: () => {},
194+
debugLogIRs: debugIRLogger,
195+
};
194196

195197
const config = parseConfigPragmaFn(firstLine);
196198
const options = {
@@ -338,6 +340,7 @@ export async function transformFixtureInput(
338340
parseConfigPragmaFn: typeof ParseConfigPragma,
339341
plugin: BabelCore.PluginObj,
340342
includeEvaluator: boolean,
343+
debugIRLogger: (value: CompilerPipelineValue) => void,
341344
EffectEnum: typeof Effect,
342345
ValueKindEnum: typeof ValueKind,
343346
): Promise<{kind: 'ok'; value: TransformResult} | {kind: 'err'; msg: string}> {
@@ -365,6 +368,7 @@ export async function transformFixtureInput(
365368
const [options, logs] = makePluginOptions(
366369
firstLine,
367370
parseConfigPragmaFn,
371+
debugIRLogger,
368372
EffectEnum,
369373
ValueKindEnum,
370374
);

compiler/packages/snap/src/constants.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,17 @@ export const COMPILER_PATH = path.join(
1818
'BabelPlugin.js',
1919
);
2020
export const COMPILER_INDEX_PATH = path.join(process.cwd(), 'dist', 'index');
21-
export const LOGGER_PATH = path.join(
21+
export const PRINT_HIR_PATH = path.join(
2222
process.cwd(),
2323
'dist',
24-
'Utils',
25-
'logger.js',
24+
'HIR',
25+
'PrintHIR.js',
26+
);
27+
export const PRINT_REACTIVE_IR_PATH = path.join(
28+
process.cwd(),
29+
'dist',
30+
'ReactiveScopes',
31+
'PrintReactiveFunction.js',
2632
);
2733
export const PARSE_CONFIG_PRAGMA_PATH = path.join(
2834
process.cwd(),

compiler/packages/snap/src/runner-worker.ts

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,21 @@
88
import {codeFrameColumns} from '@babel/code-frame';
99
import type {PluginObj} from '@babel/core';
1010
import type {parseConfigPragmaForTests as ParseConfigPragma} from 'babel-plugin-react-compiler/src/HIR/Environment';
11+
import type {printFunctionWithOutlined as PrintFunctionWithOutlined} from 'babel-plugin-react-compiler/src/HIR/PrintHIR';
12+
import type {printReactiveFunctionWithOutlined as PrintReactiveFunctionWithOutlined} from 'babel-plugin-react-compiler/src/ReactiveScopes/PrintReactiveFunction';
1113
import {TransformResult, transformFixtureInput} from './compiler';
1214
import {
1315
COMPILER_PATH,
1416
COMPILER_INDEX_PATH,
15-
LOGGER_PATH,
1617
PARSE_CONFIG_PRAGMA_PATH,
18+
PRINT_HIR_PATH,
19+
PRINT_REACTIVE_IR_PATH,
1720
} from './constants';
1821
import {TestFixture, getBasename, isExpectError} from './fixture-utils';
1922
import {TestResult, writeOutputToString} from './reporter';
2023
import {runSprout} from './sprout';
24+
import {CompilerPipelineValue} from 'babel-plugin-react-compiler/src';
25+
import chalk from 'chalk';
2126

2227
const originalConsoleError = console.error;
2328

@@ -64,20 +69,56 @@ async function compile(
6469
const {Effect: EffectEnum, ValueKind: ValueKindEnum} = require(
6570
COMPILER_INDEX_PATH,
6671
);
67-
const {toggleLogging} = require(LOGGER_PATH);
72+
const {printFunctionWithOutlined} = require(PRINT_HIR_PATH) as {
73+
printFunctionWithOutlined: typeof PrintFunctionWithOutlined;
74+
};
75+
const {printReactiveFunctionWithOutlined} = require(
76+
PRINT_REACTIVE_IR_PATH,
77+
) as {
78+
printReactiveFunctionWithOutlined: typeof PrintReactiveFunctionWithOutlined;
79+
};
80+
81+
let lastLogged: string | null = null;
82+
const debugIRLogger = shouldLog
83+
? (value: CompilerPipelineValue) => {
84+
let printed: string;
85+
switch (value.kind) {
86+
case 'hir':
87+
printed = printFunctionWithOutlined(value.value);
88+
break;
89+
case 'reactive':
90+
printed = printReactiveFunctionWithOutlined(value.value);
91+
break;
92+
case 'debug':
93+
printed = value.value;
94+
break;
95+
case 'ast':
96+
// skip printing ast as we already write fixture output JS
97+
printed = '(ast)';
98+
break;
99+
}
100+
101+
if (printed !== lastLogged) {
102+
lastLogged = printed;
103+
console.log(`${chalk.green(value.name)}:\n ${printed}\n`);
104+
} else {
105+
console.log(`${chalk.blue(value.name)}: (no change)\n`);
106+
}
107+
}
108+
: () => {};
68109
const {parseConfigPragmaForTests} = require(PARSE_CONFIG_PRAGMA_PATH) as {
69110
parseConfigPragmaForTests: typeof ParseConfigPragma;
70111
};
71112

72113
// only try logging if we filtered out all but one fixture,
73114
// since console log order is non-deterministic
74-
toggleLogging(shouldLog);
75115
const result = await transformFixtureInput(
76116
input,
77117
fixturePath,
78118
parseConfigPragmaForTests,
79119
BabelPluginReactCompiler,
80120
includeEvaluator,
121+
debugIRLogger,
81122
EffectEnum,
82123
ValueKindEnum,
83124
);

0 commit comments

Comments
 (0)