Unverified Commit 84e103b3 authored by Donny/강동윤's avatar Donny/강동윤 Committed by GitHub

chore: Backport SWC-based RC optimization (#78260)

### What?

Backport https://github.com/vercel/next.js/pull/75605

### Why?

x-ref: https://vercel.slack.com/archives/C06DGJ420TZ/p1744644426250019
parent a9e7a24d
...@@ -50,6 +50,7 @@ pub mod minify; ...@@ -50,6 +50,7 @@ pub mod minify;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub mod next_api; pub mod next_api;
pub mod parse; pub mod parse;
pub mod react_compiler;
pub mod transform; pub mod transform;
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
pub mod turbo_trace_server; pub mod turbo_trace_server;
......
use std::{path::PathBuf, sync::Arc};
use napi::bindgen_prelude::*;
use next_custom_transforms::react_compiler;
use swc_core::{
common::{SourceMap, GLOBALS},
ecma::{
ast::EsVersion,
parser::{parse_file_as_program, Syntax, TsSyntax},
},
};
pub struct CheckTask {
pub filename: PathBuf,
}
#[napi]
impl Task for CheckTask {
type Output = bool;
type JsValue = bool;
fn compute(&mut self) -> napi::Result<Self::Output> {
GLOBALS.set(&Default::default(), || {
//
let cm = Arc::new(SourceMap::default());
let Ok(fm) = cm.load_file(&self.filename.clone()) else {
return Ok(false);
};
let mut errors = vec![];
let Ok(program) = parse_file_as_program(
&fm,
Syntax::Typescript(TsSyntax {
tsx: true,
..Default::default()
}),
EsVersion::EsNext,
None,
&mut errors,
) else {
return Ok(false);
};
if !errors.is_empty() {
return Ok(false);
}
Ok(react_compiler::is_required(&program))
})
}
fn resolve(&mut self, _env: Env, result: Self::Output) -> napi::Result<Self::JsValue> {
Ok(result)
}
}
#[napi]
pub fn is_react_compiler_required(
filename: String,
signal: Option<AbortSignal>,
) -> AsyncTask<CheckTask> {
let filename = PathBuf::from(filename);
AsyncTask::with_optional_signal(CheckTask { filename }, signal)
}
...@@ -39,6 +39,7 @@ use rustc_hash::FxHasher; ...@@ -39,6 +39,7 @@ use rustc_hash::FxHasher;
pub mod chain_transforms; pub mod chain_transforms;
mod linter; mod linter;
pub mod react_compiler;
pub mod transforms; pub mod transforms;
type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>; type FxIndexMap<K, V> = IndexMap<K, V, BuildHasherDefault<FxHasher>>;
use swc_core::ecma::{
ast::{Callee, Expr, FnDecl, FnExpr, Program, ReturnStmt},
visit::{Visit, VisitWith},
};
pub fn is_required(program: &Program) -> bool {
let mut finder = Finder::default();
finder.visit_program(program);
finder.found
}
#[derive(Default)]
struct Finder {
found: bool,
/// We are in a function that starts with a capital letter or it's a function that starts with
/// `use`
is_interested: bool,
}
impl Visit for Finder {
fn visit_callee(&mut self, node: &Callee) {
if self.is_interested {
if let Callee::Expr(e) = node {
if let Expr::Ident(c) = &**e {
if c.sym.starts_with("use") {
self.found = true;
return;
}
}
}
}
node.visit_children_with(self);
}
fn visit_fn_decl(&mut self, node: &FnDecl) {
let old = self.is_interested;
self.is_interested = node.ident.sym.starts_with("use")
|| node.ident.sym.starts_with(|c: char| c.is_ascii_uppercase());
node.visit_children_with(self);
self.is_interested = old;
}
fn visit_fn_expr(&mut self, node: &FnExpr) {
let old = self.is_interested;
self.is_interested = node.ident.as_ref().is_some_and(|ident| {
ident.sym.starts_with("use") || ident.sym.starts_with(|c: char| c.is_ascii_uppercase())
});
node.visit_children_with(self);
self.is_interested = old;
}
fn visit_return_stmt(&mut self, node: &ReturnStmt) {
if self.is_interested {
if let Some(Expr::JSXElement(..) | Expr::JSXEmpty(..) | Expr::JSXFragment(..)) =
node.arg.as_deref()
{
self.found = true;
return;
}
}
node.visit_children_with(self);
}
}
...@@ -8,6 +8,7 @@ import type { NextBabelLoaderOptions, NextJsLoaderContext } from './types' ...@@ -8,6 +8,7 @@ import type { NextBabelLoaderOptions, NextJsLoaderContext } from './types'
import { consumeIterator } from './util' import { consumeIterator } from './util'
import * as Log from '../../output/log' import * as Log from '../../output/log'
import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx' import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx'
import { isReactCompilerRequired } from '../../swc'
const nextDistPath = const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/ /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
...@@ -257,7 +258,7 @@ function checkCustomBabelConfigDeprecation( ...@@ -257,7 +258,7 @@ function checkCustomBabelConfigDeprecation(
* Generate a new, flat Babel config, ready to be handed to Babel-traverse. * Generate a new, flat Babel config, ready to be handed to Babel-traverse.
* This config should have no unresolved overrides, presets, etc. * This config should have no unresolved overrides, presets, etc.
*/ */
function getFreshConfig( async function getFreshConfig(
this: NextJsLoaderContext, this: NextJsLoaderContext,
cacheCharacteristics: CharacteristicsGermaneToCaching, cacheCharacteristics: CharacteristicsGermaneToCaching,
loaderOptions: NextBabelLoaderOptions, loaderOptions: NextBabelLoaderOptions,
...@@ -265,7 +266,7 @@ function getFreshConfig( ...@@ -265,7 +266,7 @@ function getFreshConfig(
filename: string, filename: string,
inputSourceMap?: object | null inputSourceMap?: object | null
) { ) {
const hasReactCompiler = (() => { const hasReactCompiler = await (async () => {
if ( if (
loaderOptions.reactCompilerPlugins && loaderOptions.reactCompilerPlugins &&
loaderOptions.reactCompilerPlugins.length === 0 loaderOptions.reactCompilerPlugins.length === 0
...@@ -284,6 +285,10 @@ function getFreshConfig( ...@@ -284,6 +285,10 @@ function getFreshConfig(
return false return false
} }
if (!(await isReactCompilerRequired(filename))) {
return false
}
return true return true
})() })()
...@@ -436,7 +441,7 @@ type BabelConfig = any ...@@ -436,7 +441,7 @@ type BabelConfig = any
const configCache: Map<any, BabelConfig> = new Map() const configCache: Map<any, BabelConfig> = new Map()
const configFiles: Set<string> = new Set() const configFiles: Set<string> = new Set()
export default function getConfig( export default async function getConfig(
this: NextJsLoaderContext, this: NextJsLoaderContext,
{ {
source, source,
...@@ -451,7 +456,7 @@ export default function getConfig( ...@@ -451,7 +456,7 @@ export default function getConfig(
filename: string filename: string
inputSourceMap?: object | null inputSourceMap?: object | null
} }
): BabelConfig { ): Promise<BabelConfig> {
const cacheCharacteristics = getCacheCharacteristics( const cacheCharacteristics = getCacheCharacteristics(
loaderOptions, loaderOptions,
source, source,
...@@ -493,7 +498,7 @@ export default function getConfig( ...@@ -493,7 +498,7 @@ export default function getConfig(
) )
} }
const freshConfig = getFreshConfig.call( const freshConfig = await getFreshConfig.call(
this, this,
cacheCharacteristics, cacheCharacteristics,
loaderOptions, loaderOptions,
......
...@@ -27,16 +27,17 @@ async function nextBabelLoader( ...@@ -27,16 +27,17 @@ async function nextBabelLoader(
const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform') const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform')
const { code: transformedSource, map: outputSourceMap } = const { code: transformedSource, map: outputSourceMap } =
loaderSpanInner.traceFn(() => await loaderSpanInner.traceAsyncFn(
transform.call( async () =>
this, await transform.call(
inputSource, this,
inputSourceMap, inputSource,
loaderOptions, inputSourceMap,
filename, loaderOptions,
target, filename,
loaderSpanInner target,
) loaderSpanInner
)
) )
return [transformedSource, outputSourceMap] return [transformedSource, outputSourceMap]
......
...@@ -69,7 +69,7 @@ function transformAst(file: any, babelConfig: any, parentSpan: Span) { ...@@ -69,7 +69,7 @@ function transformAst(file: any, babelConfig: any, parentSpan: Span) {
} }
} }
export default function transform( export default async function transform(
this: NextJsLoaderContext, this: NextJsLoaderContext,
source: string, source: string,
inputSourceMap: object | null | undefined, inputSourceMap: object | null | undefined,
...@@ -79,7 +79,7 @@ export default function transform( ...@@ -79,7 +79,7 @@ export default function transform(
parentSpan: Span parentSpan: Span
) { ) {
const getConfigSpan = parentSpan.traceChild('babel-turbo-get-config') const getConfigSpan = parentSpan.traceChild('babel-turbo-get-config')
const babelConfig = getConfig.call(this, { const babelConfig = await getConfig.call(this, {
source, source,
loaderOptions, loaderOptions,
inputSourceMap, inputSourceMap,
......
...@@ -367,6 +367,10 @@ export declare function parse( ...@@ -367,6 +367,10 @@ export declare function parse(
filename?: string | undefined | null, filename?: string | undefined | null,
signal?: AbortSignal | undefined | null signal?: AbortSignal | undefined | null
): Promise<string> ): Promise<string>
export declare function isReactCompilerRequired(
filename: string,
signal?: AbortSignal | undefined | null
): Promise<boolean>
export declare function transform( export declare function transform(
src: string | Buffer | undefined, src: string | Buffer | undefined,
isModule: boolean, isModule: boolean,
......
...@@ -1104,6 +1104,11 @@ async function loadWasm(importPath = '') { ...@@ -1104,6 +1104,11 @@ async function loadWasm(importPath = '') {
return bindings.mdxCompileSync(src, getMdxOptions(options)) return bindings.mdxCompileSync(src, getMdxOptions(options))
}, },
}, },
reactCompiler: {
isReactCompilerRequired(_filename: string) {
return Promise.resolve(true)
},
},
} }
return wasmBindings return wasmBindings
} catch (e: any) { } catch (e: any) {
...@@ -1275,6 +1280,11 @@ function loadNative(importPath?: string) { ...@@ -1275,6 +1280,11 @@ function loadNative(importPath?: string) {
}, },
}, },
}, },
reactCompiler: {
isReactCompilerRequired: (filename: string) => {
return bindings.isReactCompilerRequired(filename)
},
},
} }
return nativeBindings return nativeBindings
} }
...@@ -1320,6 +1330,13 @@ export async function minify( ...@@ -1320,6 +1330,13 @@ export async function minify(
return bindings.minify(src, options) return bindings.minify(src, options)
} }
export async function isReactCompilerRequired(
filename: string
): Promise<boolean> {
let bindings = await loadBindings()
return bindings.reactCompiler.isReactCompilerRequired(filename)
}
export async function parse(src: string, options: any): Promise<any> { export async function parse(src: string, options: any): Promise<any> {
let bindings = await loadBindings() let bindings = await loadBindings()
let parserOptions = getParserOptions(options) let parserOptions = getParserOptions(options)
......
...@@ -39,6 +39,10 @@ export interface Binding { ...@@ -39,6 +39,10 @@ export interface Binding {
transformStyleAttr(transformAttrOptions: any): Promise<any> transformStyleAttr(transformAttrOptions: any): Promise<any>
} }
} }
reactCompiler: {
isReactCompilerRequired(filename: string): Promise<boolean>
}
} }
export type StyledString = export type StyledString =
......
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