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;
#[cfg(not(target_arch = "wasm32"))]
pub mod next_api;
pub mod parse;
pub mod react_compiler;
pub mod transform;
#[cfg(not(target_arch = "wasm32"))]
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;
pub mod chain_transforms;
mod linter;
pub mod react_compiler;
pub mod transforms;
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'
import { consumeIterator } from './util'
import * as Log from '../../output/log'
import jsx from 'next/dist/compiled/babel/plugin-syntax-jsx'
import { isReactCompilerRequired } from '../../swc'
const nextDistPath =
/(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/
......@@ -257,7 +258,7 @@ function checkCustomBabelConfigDeprecation(
* Generate a new, flat Babel config, ready to be handed to Babel-traverse.
* This config should have no unresolved overrides, presets, etc.
*/
function getFreshConfig(
async function getFreshConfig(
this: NextJsLoaderContext,
cacheCharacteristics: CharacteristicsGermaneToCaching,
loaderOptions: NextBabelLoaderOptions,
......@@ -265,7 +266,7 @@ function getFreshConfig(
filename: string,
inputSourceMap?: object | null
) {
const hasReactCompiler = (() => {
const hasReactCompiler = await (async () => {
if (
loaderOptions.reactCompilerPlugins &&
loaderOptions.reactCompilerPlugins.length === 0
......@@ -284,6 +285,10 @@ function getFreshConfig(
return false
}
if (!(await isReactCompilerRequired(filename))) {
return false
}
return true
})()
......@@ -436,7 +441,7 @@ type BabelConfig = any
const configCache: Map<any, BabelConfig> = new Map()
const configFiles: Set<string> = new Set()
export default function getConfig(
export default async function getConfig(
this: NextJsLoaderContext,
{
source,
......@@ -451,7 +456,7 @@ export default function getConfig(
filename: string
inputSourceMap?: object | null
}
): BabelConfig {
): Promise<BabelConfig> {
const cacheCharacteristics = getCacheCharacteristics(
loaderOptions,
source,
......@@ -493,7 +498,7 @@ export default function getConfig(
)
}
const freshConfig = getFreshConfig.call(
const freshConfig = await getFreshConfig.call(
this,
cacheCharacteristics,
loaderOptions,
......
......@@ -27,16 +27,17 @@ async function nextBabelLoader(
const loaderSpanInner = parentTrace.traceChild('next-babel-turbo-transform')
const { code: transformedSource, map: outputSourceMap } =
loaderSpanInner.traceFn(() =>
transform.call(
this,
inputSource,
inputSourceMap,
loaderOptions,
filename,
target,
loaderSpanInner
)
await loaderSpanInner.traceAsyncFn(
async () =>
await transform.call(
this,
inputSource,
inputSourceMap,
loaderOptions,
filename,
target,
loaderSpanInner
)
)
return [transformedSource, outputSourceMap]
......
......@@ -69,7 +69,7 @@ function transformAst(file: any, babelConfig: any, parentSpan: Span) {
}
}
export default function transform(
export default async function transform(
this: NextJsLoaderContext,
source: string,
inputSourceMap: object | null | undefined,
......@@ -79,7 +79,7 @@ export default function transform(
parentSpan: Span
) {
const getConfigSpan = parentSpan.traceChild('babel-turbo-get-config')
const babelConfig = getConfig.call(this, {
const babelConfig = await getConfig.call(this, {
source,
loaderOptions,
inputSourceMap,
......
......@@ -367,6 +367,10 @@ export declare function parse(
filename?: string | undefined | null,
signal?: AbortSignal | undefined | null
): Promise<string>
export declare function isReactCompilerRequired(
filename: string,
signal?: AbortSignal | undefined | null
): Promise<boolean>
export declare function transform(
src: string | Buffer | undefined,
isModule: boolean,
......
......@@ -1104,6 +1104,11 @@ async function loadWasm(importPath = '') {
return bindings.mdxCompileSync(src, getMdxOptions(options))
},
},
reactCompiler: {
isReactCompilerRequired(_filename: string) {
return Promise.resolve(true)
},
},
}
return wasmBindings
} catch (e: any) {
......@@ -1275,6 +1280,11 @@ function loadNative(importPath?: string) {
},
},
},
reactCompiler: {
isReactCompilerRequired: (filename: string) => {
return bindings.isReactCompilerRequired(filename)
},
},
}
return nativeBindings
}
......@@ -1320,6 +1330,13 @@ export async function minify(
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> {
let bindings = await loadBindings()
let parserOptions = getParserOptions(options)
......
......@@ -39,6 +39,10 @@ export interface Binding {
transformStyleAttr(transformAttrOptions: any): Promise<any>
}
}
reactCompiler: {
isReactCompilerRequired(filename: string): Promise<boolean>
}
}
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