Skip to content

Commit

Permalink
[compiler] Patch error reporting for blocklisted imports
Browse files Browse the repository at this point in the history
ghstack-source-id: 614c1e9c04828bfa2da13a6abaeff7ce3e67cb9b
Pull Request resolved: #30652
  • Loading branch information
mofeiZ committed Aug 9, 2024
1 parent 0e6d8c3 commit 5a6c20d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,39 @@

import {NodePath} from '@babel/core';
import * as t from '@babel/types';
import {CompilerError} from '../CompilerError';
import {CompilerError, ErrorSeverity} from '../CompilerError';
import {EnvironmentConfig, ExternalFunction, GeneratedSource} from '../HIR';
import {getOrInsertDefault} from '../Utils/utils';

export function validateRestrictedImports(
path: NodePath<t.Program>,
{validateBlocklistedImports}: EnvironmentConfig,
): void {
): CompilerError | null {
if (
validateBlocklistedImports == null ||
validateBlocklistedImports.length === 0
) {
return;
return null;
}
const error = new CompilerError();
const restrictedImports = new Set(validateBlocklistedImports);
path.traverse({
ImportDeclaration(importDeclPath) {
if (restrictedImports.has(importDeclPath.node.source.value)) {
CompilerError.throwTodo({
error.push({
severity: ErrorSeverity.Todo,
reason: 'Bailing out due to blocklisted import',
description: `Import from module ${importDeclPath.node.source.value}`,
loc: importDeclPath.node.loc ?? null,
});
}
},
});
if (error.hasErrors()) {
return error;
} else {
return null;
}
}

export function addImportsToProgram(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ function isFilePartOfSources(
return false;
}

/**
* `compileProgram` is directly invoked by the react-compiler babel plugin, so
* exceptions thrown by this function will fail the babel build.
* - call `handleError` if your error is recoverable.
* Unless the error is a warning / info diagnostic, compilation of a function
* / entire file should also be skipped.
* - throw an exception if the error is fatal / not recoverable.
* Examples of this are invalid compiler configs or failure to codegen outlined
* functions *after* already emitting optimized components / hooks that invoke
* the outlined functions.
*/
export function compileProgram(
program: NodePath<t.Program>,
pass: CompilerPass,
Expand All @@ -300,7 +311,11 @@ export function compileProgram(
});
}
const environment = environmentResult.unwrap();
validateRestrictedImports(program, environment);
const restrictedImportsErr = validateRestrictedImports(program, environment);
if (restrictedImportsErr) {
handleError(restrictedImportsErr, pass, null);
return;
}
const useMemoCacheIdentifier = program.scope.generateUidIdentifier('c');
const moduleName = pass.opts.runtimeModule ?? 'react/compiler-runtime';

Expand Down

0 comments on commit 5a6c20d

Please sign in to comment.