Unverified Commit 8136e9ce authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Add React Compiler memoization preservation option (#98589)

parent 1bcedb48
...@@ -32,7 +32,8 @@ use turbopack_core::{ ...@@ -32,7 +32,8 @@ use turbopack_core::{
resolve::ResolveAliasMap, resolve::ResolveAliasMap,
}; };
use turbopack_ecmascript::transform::{ use turbopack_ecmascript::transform::{
OptionReactCompilerCompilationMode, ReactCompilerCompilationMode, ReactCompilerTarget, OptionReactCompilerTransformOptions, ReactCompilerCompilationMode, ReactCompilerTarget,
ReactCompilerTransformOptions,
}; };
use turbopack_ecmascript_plugins::transform::{ use turbopack_ecmascript_plugins::transform::{
emotion::EmotionTransformConfig, relay::RelayConfig, emotion::EmotionTransformConfig, relay::RelayConfig,
...@@ -766,12 +767,22 @@ pub enum ReactCompilerPanicThreshold { ...@@ -766,12 +767,22 @@ pub enum ReactCompilerPanicThreshold {
pub struct ReactCompilerOptions { pub struct ReactCompilerOptions {
#[serde(default)] #[serde(default)]
pub compilation_mode: ReactCompilerCompilationMode, pub compilation_mode: ReactCompilerCompilationMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub environment: Option<ReactCompilerEnvironmentOptions>,
#[serde(default)] #[serde(default)]
pub panic_threshold: ReactCompilerPanicThreshold, pub panic_threshold: ReactCompilerPanicThreshold,
#[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")] #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")]
pub target: Option<ReactCompilerTarget>, pub target: Option<ReactCompilerTarget>,
} }
#[turbo_tasks::value(shared, operation)]
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactCompilerEnvironmentOptions {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enable_preserve_existing_memoization_guarantees: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, NonLocalValue, OperationValue, Encode, Decode)] #[derive(Clone, Debug, PartialEq, Deserialize, NonLocalValue, OperationValue, Encode, Decode)]
#[serde(untagged)] #[serde(untagged)]
pub enum ReactCompilerOptionsOrBoolean { pub enum ReactCompilerOptionsOrBoolean {
...@@ -2082,17 +2093,25 @@ impl NextConfig { ...@@ -2082,17 +2093,25 @@ impl NextConfig {
/// Returns compilation mode when both `reactCompiler` and `turbopackRustReactCompiler` are set; /// Returns compilation mode when both `reactCompiler` and `turbopackRustReactCompiler` are set;
/// `None` otherwise. /// `None` otherwise.
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn rust_react_compiler(&self) -> Vc<OptionReactCompilerCompilationMode> { pub fn rust_react_compiler(&self) -> Vc<OptionReactCompilerTransformOptions> {
let use_rust = self let use_rust = self
.experimental .experimental
.turbopack_rust_react_compiler .turbopack_rust_react_compiler
.unwrap_or(false); .unwrap_or(false);
let mode = match (use_rust, &self.react_compiler) { let mode = match (use_rust, &self.react_compiler) {
(true, Some(ReactCompilerOptionsOrBoolean::Boolean(true))) => { (true, Some(ReactCompilerOptionsOrBoolean::Boolean(true))) => {
Some(ReactCompilerCompilationMode::Infer) Some(ReactCompilerTransformOptions::default())
} }
(true, Some(ReactCompilerOptionsOrBoolean::Option(opts))) => { (true, Some(ReactCompilerOptionsOrBoolean::Option(opts))) => {
Some(opts.compilation_mode) Some(ReactCompilerTransformOptions {
compilation_mode: opts.compilation_mode,
enable_preserve_existing_memoization_guarantees: opts
.environment
.as_ref()
.and_then(|environment| {
environment.enable_preserve_existing_memoization_guarantees
}),
})
} }
_ => None, _ => None,
}; };
......
...@@ -19,7 +19,7 @@ use turbopack_ecmascript::transform::{ReactCompilerCompilationMode, ReactCompile ...@@ -19,7 +19,7 @@ use turbopack_ecmascript::transform::{ReactCompilerCompilationMode, ReactCompile
use turbopack_node::transforms::webpack::WebpackLoaderItem; use turbopack_node::transforms::webpack::WebpackLoaderItem;
use crate::{ use crate::{
next_config::{NextConfig, ReactCompilerOptions}, next_config::{NextConfig, ReactCompilerOptions, ReactCompilerPanicThreshold},
next_import_map::try_get_next_package, next_import_map::try_get_next_package,
next_shared::webpack_rules::{ next_shared::webpack_rules::{
ManuallyConfiguredBuiltinLoaderIssue, WebpackLoaderBuiltinCondition, ManuallyConfiguredBuiltinLoaderIssue, WebpackLoaderBuiltinCondition,
...@@ -171,20 +171,47 @@ pub async fn get_babel_loader_rules( ...@@ -171,20 +171,47 @@ pub async fn get_babel_loader_rules(
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct EnvironmentOptions { struct EnvironmentOptions {
enable_name_anonymous_functions: bool, enable_name_anonymous_functions: bool,
#[serde(skip_serializing_if = "Option::is_none")]
enable_preserve_existing_memoization_guarantees: Option<bool>,
} }
#[derive(Serialize)] #[derive(Serialize)]
struct ResolvedOptions<'a> { struct ResolvedOptions<'a> {
#[serde(flatten)] #[serde(flatten)]
base: &'a ReactCompilerOptions, base: ReactCompilerOptionsWithoutEnvironment<'a>,
environment: EnvironmentOptions, environment: EnvironmentOptions,
} }
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ReactCompilerOptionsWithoutEnvironment<'a> {
compilation_mode: ReactCompilerCompilationMode,
panic_threshold: &'a ReactCompilerPanicThreshold,
#[serde(skip_serializing_if = "Option::is_none")]
target: Option<ReactCompilerTarget>,
}
impl<'a> From<&'a ReactCompilerOptions> for ReactCompilerOptionsWithoutEnvironment<'a> {
fn from(options: &'a ReactCompilerOptions) -> Self {
Self {
compilation_mode: options.compilation_mode,
panic_threshold: &options.panic_threshold,
target: options.target,
}
}
}
let resolved_options = ResolvedOptions { let resolved_options = ResolvedOptions {
base: &react_compiler_options_with_target, base: (&react_compiler_options_with_target).into(),
environment: EnvironmentOptions { environment: EnvironmentOptions {
enable_name_anonymous_functions: builtin_conditions enable_name_anonymous_functions: builtin_conditions
.contains(&WebpackLoaderBuiltinCondition::Development), .contains(&WebpackLoaderBuiltinCondition::Development),
enable_preserve_existing_memoization_guarantees: react_compiler_options_with_target
.environment
.as_ref()
.and_then(|environment| {
environment.enable_preserve_existing_memoization_guarantees
}),
}, },
}; };
let react_compiler_plugins = let react_compiler_plugins =
......
...@@ -97,6 +97,39 @@ export default function Page() { ...@@ -97,6 +97,39 @@ export default function Page() {
> **Note:** You can also use the `"use no memo"` directive from React for the opposite effect, to opt-out a component or hook. > **Note:** You can also use the `"use no memo"` directive from React for the opposite effect, to opt-out a component or hook.
## Existing memoization guarantees
You can configure whether the compiler preserves existing memoization guarantees from `useMemo`, `useCallback`, and `React.memo`:
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
reactCompiler: {
environment: {
enablePreserveExistingMemoizationGuarantees: false,
},
},
}
export default nextConfig
```
```js filename="next.config.js" switcher
/** @type {import('next').NextConfig} */
const nextConfig = {
reactCompiler: {
environment: {
enablePreserveExistingMemoizationGuarantees: false,
},
},
}
module.exports = nextConfig
```
When omitted, Next.js uses the default from the active React Compiler implementation. Because defaults may differ between compiler implementations and versions, set this option explicitly to ensure consistent behavior.
## Version History ## Version History
| Version | Changes | | Version | Changes |
......
...@@ -39,17 +39,25 @@ const getReactCompilerPlugins = ( ...@@ -39,17 +39,25 @@ const getReactCompilerPlugins = (
// react/package.json not resolvable — skip target detection // react/package.json not resolvable — skip target detection
} }
const environment: Pick<EnvironmentConfig, 'enableNameAnonymousFunctions'> = {
enableNameAnonymousFunctions: isDev,
}
const options: ReactCompilerOptions = const options: ReactCompilerOptions =
typeof maybeOptions === 'boolean' ? {} : maybeOptions typeof maybeOptions === 'boolean' ? {} : maybeOptions
const compilerOptions: JSONValue = { const { environment: userEnvironment, ...compilerOptions } = options
...options, const environment = {
enableNameAnonymousFunctions: isDev,
...(userEnvironment?.enablePreserveExistingMemoizationGuarantees !==
undefined
? {
enablePreserveExistingMemoizationGuarantees:
userEnvironment.enablePreserveExistingMemoizationGuarantees,
}
: {}),
} satisfies Partial<EnvironmentConfig>
const resolvedCompilerOptions: JSONValue = {
...compilerOptions,
...(target ? { target } : {}), ...(target ? { target } : {}),
environment, environment,
} }
return [[getReactCompiler(), compilerOptions]] return [[getReactCompiler(), resolvedCompilerOptions]]
} }
const getBabelLoader = ( const getBabelLoader = (
......
...@@ -859,6 +859,13 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -859,6 +859,13 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
z z
.object({ .object({
compilationMode: z.enum(['infer', 'annotation', 'all']).optional(), compilationMode: z.enum(['infer', 'annotation', 'all']).optional(),
environment: z
.object({
enablePreserveExistingMemoizationGuarantees: z
.boolean()
.optional(),
})
.optional(),
panicThreshold: z panicThreshold: z
.enum(['none', 'critical_errors', 'all_errors']) .enum(['none', 'critical_errors', 'all_errors'])
.optional(), .optional(),
......
...@@ -359,6 +359,15 @@ export interface ReactCompilerOptions { ...@@ -359,6 +359,15 @@ export interface ReactCompilerOptions {
* @see https://react.dev/reference/react-compiler/compilationMode * @see https://react.dev/reference/react-compiler/compilationMode
*/ */
compilationMode?: 'infer' | 'annotation' | 'all' compilationMode?: 'infer' | 'annotation' | 'all'
environment?: {
/**
* Controls whether the React Compiler preserves existing memoization
* guarantees from `useMemo`, `useCallback`, and `React.memo`.
*
* When omitted, the installed React Compiler's default is used.
*/
enablePreserveExistingMemoizationGuarantees?: boolean
}
/** /**
* Controls how the React Compiler handles errors during compilation. * Controls how the React Compiler handles errors during compilation.
* *
......
...@@ -92,11 +92,21 @@ pub enum EcmascriptInputTransform { ...@@ -92,11 +92,21 @@ pub enum EcmascriptInputTransform {
use_define_for_class_fields: bool, use_define_for_class_fields: bool,
}, },
ReactCompilerRust { ReactCompilerRust {
compilation_mode: ReactCompilerCompilationMode, options: ReactCompilerTransformOptions,
target: ReactCompilerTarget, target: ReactCompilerTarget,
}, },
} }
#[turbo_tasks::value(shared, operation)]
#[derive(Default, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReactCompilerTransformOptions {
#[serde(default)]
pub compilation_mode: ReactCompilerCompilationMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enable_preserve_existing_memoization_guarantees: Option<bool>,
}
#[turbo_tasks::value(shared, operation)] #[turbo_tasks::value(shared, operation)]
#[derive(Default, Debug, Clone, Copy, Hash, Serialize, Deserialize)] #[derive(Default, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
...@@ -118,7 +128,7 @@ impl ReactCompilerCompilationMode { ...@@ -118,7 +128,7 @@ impl ReactCompilerCompilationMode {
} }
#[turbo_tasks::value(transparent)] #[turbo_tasks::value(transparent)]
pub struct OptionReactCompilerCompilationMode(Option<ReactCompilerCompilationMode>); pub struct OptionReactCompilerTransformOptions(Option<ReactCompilerTransformOptions>);
#[turbo_tasks::value(shared, operation)] #[turbo_tasks::value(shared, operation)]
#[derive(Default, Debug, Clone, Copy, Hash, Serialize, Deserialize)] #[derive(Default, Debug, Clone, Copy, Hash, Serialize, Deserialize)]
...@@ -401,11 +411,8 @@ impl EcmascriptInputTransform { ...@@ -401,11 +411,8 @@ impl EcmascriptInputTransform {
apply_transform(program, helpers, decorators(config)) apply_transform(program, helpers, decorators(config))
} }
EcmascriptInputTransform::ReactCompilerRust { EcmascriptInputTransform::ReactCompilerRust { options, target } => {
compilation_mode, apply_rust_react_compiler(program, ctx, helpers, *options, *target).await?
target,
} => {
apply_rust_react_compiler(program, ctx, helpers, *compilation_mode, *target).await?
} }
EcmascriptInputTransform::Plugin(transform) => { EcmascriptInputTransform::Plugin(transform) => {
// We cannot pass helpers to plugins, so we return them as is // We cannot pass helpers to plugins, so we return them as is
...@@ -538,7 +545,7 @@ async fn apply_rust_react_compiler( ...@@ -538,7 +545,7 @@ async fn apply_rust_react_compiler(
program: &mut Program, program: &mut Program,
ctx: &TransformContext<'_>, ctx: &TransformContext<'_>,
helpers: HelperData, helpers: HelperData,
compilation_mode: ReactCompilerCompilationMode, options: ReactCompilerTransformOptions,
target: ReactCompilerTarget, target: ReactCompilerTarget,
) -> Result<HelperData> { ) -> Result<HelperData> {
let Program::Module(_) = program else { let Program::Module(_) = program else {
...@@ -548,7 +555,7 @@ async fn apply_rust_react_compiler( ...@@ -548,7 +555,7 @@ async fn apply_rust_react_compiler(
// Avoid invoking the compiler when the selected mode cannot change this module. These checks // Avoid invoking the compiler when the selected mode cannot change this module. These checks
// run on the SWC AST we already parsed, before converting it to the compiler AST. `All` mode // run on the SWC AST we already parsed, before converting it to the compiler AST. `All` mode
// remains unconditional because every function is eligible. // remains unconditional because every function is eligible.
if !should_run_rust_react_compiler(program, compilation_mode) { if !should_run_rust_react_compiler(program, options.compilation_mode) {
return Ok(helpers); return Ok(helpers);
} }
...@@ -559,7 +566,7 @@ async fn apply_rust_react_compiler( ...@@ -559,7 +566,7 @@ async fn apply_rust_react_compiler(
swc_ecma_react_compiler::SourceType::from_program(program), swc_ecma_react_compiler::SourceType::from_program(program),
ctx.source_text, ctx.source_text,
Some(&single_threaded_comments), Some(&single_threaded_comments),
react_compiler_options(ctx, compilation_mode, target), react_compiler_options(ctx.node_env.as_str(), ctx.file_name_str, options, target),
); );
// TODO: Emit these diagnostics with an Info level once there's a way of adjusting log levels in // TODO: Emit these diagnostics with an Info level once there's a way of adjusting log levels in
...@@ -585,18 +592,19 @@ async fn apply_rust_react_compiler( ...@@ -585,18 +592,19 @@ async fn apply_rust_react_compiler(
} }
fn react_compiler_options( fn react_compiler_options(
ctx: &TransformContext<'_>, node_env: &str,
compilation_mode: ReactCompilerCompilationMode, file_name: &str,
options: ReactCompilerTransformOptions,
target: ReactCompilerTarget, target: ReactCompilerTarget,
) -> react_compiler::entrypoint::plugin_options::PluginOptions { ) -> react_compiler::entrypoint::plugin_options::PluginOptions {
use react_compiler::entrypoint::plugin_options::{CompilerTarget, PluginOptions}; use react_compiler::entrypoint::plugin_options::{CompilerTarget, PluginOptions};
PluginOptions { let mut plugin_options = PluginOptions {
should_compile: true, should_compile: true,
enable_reanimated: false, enable_reanimated: false,
is_dev: ctx.node_env != "production", is_dev: node_env != "production",
filename: Some(ctx.file_name_str.to_string()), filename: Some(file_name.to_string()),
compilation_mode: compilation_mode.as_str().to_string(), compilation_mode: options.compilation_mode.as_str().to_string(),
panic_threshold: "none".to_string(), panic_threshold: "none".to_string(),
target: CompilerTarget::Version(target.as_str().to_string()), target: CompilerTarget::Version(target.as_str().to_string()),
gating: None, gating: None,
...@@ -611,7 +619,17 @@ fn react_compiler_options( ...@@ -611,7 +619,17 @@ fn react_compiler_options(
source_code: None, source_code: None,
profiling: false, profiling: false,
debug: false, debug: false,
};
if let Some(enable_preserve_existing_memoization_guarantees) =
options.enable_preserve_existing_memoization_guarantees
{
plugin_options
.environment
.enable_preserve_existing_memoization_guarantees =
enable_preserve_existing_memoization_guarantees;
} }
plugin_options
} }
fn apply_transform(program: &mut Program, helpers: HelperData, op: impl Pass) -> HelperData { fn apply_transform(program: &mut Program, helpers: HelperData, op: impl Pass) -> HelperData {
...@@ -690,6 +708,41 @@ mod react_compiler_tests { ...@@ -690,6 +708,41 @@ mod react_compiler_tests {
use super::*; use super::*;
#[test]
fn preserves_default_environment_without_explicit_option() {
let options = react_compiler_options(
"production",
"input.js",
ReactCompilerTransformOptions::default(),
ReactCompilerTarget::React19,
);
assert!(
options
.environment
.enable_preserve_existing_memoization_guarantees
);
}
#[test]
fn forwards_explicit_memoization_preservation_option() {
let options = react_compiler_options(
"production",
"input.js",
ReactCompilerTransformOptions {
compilation_mode: ReactCompilerCompilationMode::Infer,
enable_preserve_existing_memoization_guarantees: Some(false),
},
ReactCompilerTarget::React19,
);
assert!(
!options
.environment
.enable_preserve_existing_memoization_guarantees
);
}
fn parse_program(source: &str) -> Program { fn parse_program(source: &str) -> Program {
GLOBALS.set(&Default::default(), || { GLOBALS.set(&Default::default(), || {
let cm = SourceMap::default(); let cm = SourceMap::default();
......
...@@ -56,7 +56,8 @@ use turbopack_core::{ ...@@ -56,7 +56,8 @@ use turbopack_core::{
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
AnalyzeMode, CustomTransformer, EcmascriptInputTransform, TransformPlugin, AnalyzeMode, CustomTransformer, EcmascriptInputTransform, TransformPlugin,
chunk::EcmascriptChunkType, transform::ReactCompilerCompilationMode, chunk::EcmascriptChunkType,
transform::{ReactCompilerCompilationMode, ReactCompilerTransformOptions},
}; };
use turbopack_ecmascript_plugins::transform::{ use turbopack_ecmascript_plugins::transform::{
emotion::{EmotionTransformConfig, EmotionTransformer}, emotion::{EmotionTransformConfig, EmotionTransformer},
...@@ -429,9 +430,12 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -429,9 +430,12 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
cjs_scope_hoisting: options.cjs_scope_hoisting, cjs_scope_hoisting: options.cjs_scope_hoisting,
cross_module_constants: options.cross_module_constants, cross_module_constants: options.cross_module_constants,
enable_exports_info_inlining: true, enable_exports_info_inlining: true,
enable_rust_react_compiler: options enable_rust_react_compiler: options.enable_rust_react_compiler.then_some(
.enable_rust_react_compiler ReactCompilerTransformOptions {
.then_some(ReactCompilerCompilationMode::Infer), compilation_mode: ReactCompilerCompilationMode::Infer,
..Default::default()
},
),
..Default::default() ..Default::default()
}, },
environment: Some(env), environment: Some(env),
......
...@@ -309,9 +309,9 @@ impl ModuleOptions { ...@@ -309,9 +309,9 @@ impl ModuleOptions {
let mut ecma_preprocess = vec![]; let mut ecma_preprocess = vec![];
let mut postprocess = vec![]; let mut postprocess = vec![];
if let Some(compilation_mode) = enable_rust_react_compiler { if let Some(options) = enable_rust_react_compiler {
ecma_preprocess.push(EcmascriptInputTransform::ReactCompilerRust { ecma_preprocess.push(EcmascriptInputTransform::ReactCompilerRust {
compilation_mode, options,
target: rust_react_compiler_target, target: rust_react_compiler_target,
}); });
} }
......
...@@ -16,7 +16,7 @@ use turbopack_core::{ ...@@ -16,7 +16,7 @@ use turbopack_core::{
use turbopack_ecmascript::{ use turbopack_ecmascript::{
AnalyzeMode, TypeofWindow, AnalyzeMode, TypeofWindow,
references::esm::UrlRewriteBehavior, references::esm::UrlRewriteBehavior,
transform::{PresetEnvConfig, ReactCompilerCompilationMode, ReactCompilerTarget}, transform::{PresetEnvConfig, ReactCompilerTarget, ReactCompilerTransformOptions},
}; };
pub use turbopack_mdx::MdxTransformOptions; pub use turbopack_mdx::MdxTransformOptions;
use turbopack_node::{ use turbopack_node::{
...@@ -254,7 +254,7 @@ pub struct EcmascriptOptionsContext { ...@@ -254,7 +254,7 @@ pub struct EcmascriptOptionsContext {
// node_modules. // node_modules.
pub enable_typeof_window_inlining: Option<TypeofWindow>, pub enable_typeof_window_inlining: Option<TypeofWindow>,
pub enable_jsx: Option<ResolvedVc<JsxTransformOptions>>, pub enable_jsx: Option<ResolvedVc<JsxTransformOptions>>,
pub enable_rust_react_compiler: Option<ReactCompilerCompilationMode>, pub enable_rust_react_compiler: Option<ReactCompilerTransformOptions>,
pub rust_react_compiler_target: ReactCompilerTarget, pub rust_react_compiler_target: ReactCompilerTarget,
/// Follow type references and resolve declaration files in additional to /// Follow type references and resolve declaration files in additional to
/// normal resolution. /// normal resolution.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment