Unverified Commit 797eb7fe authored by Matt Mastracci's avatar Matt Mastracci Committed by GitHub

Turbopack: refactoring to prepare for name mangling (#89406)

## What

Refactors module splitting and re-export handling to prepare for the name mangling PR.

### Changes

1. **`EsmExports::reexport_including_default` helper** — New helper that creates re-export facades (default + star export) from a module reference. Replaces duplicated boilerplate in `NextDynamicEntryModule`, `NextServerComponentModule`, and `NextServerUtilityModule`.

2. **`get_locals_if_split` / `get_facade_if_split` on `EcmascriptModuleAsset`** — Encapsulates the split-check-then-wrap logic that was previously inlined in `turbopack/src/lib.rs`. Returns the locals or facade module when the module has re-exports that should be separated, otherwise returns self.

3. **Simplified `apply_module_type` in `turbopack/src/lib.rs`** — The tree-shaking `ReexportsOnly` path now uses the new helpers instead of manually checking `split_locals_and_reexports` and constructing facade/locals modules inline.

4. **Documentation improvements** — Added doc comments to `EsmExport` variants, `EsmExports` fields, and `split_locals_and_reexports`.

## Why

Extracting these helpers simplifies the upstream code and reduces the diff for the name mangling PR. The `reexport_including_default` helper is needed because the next stage will require additional work for virtual facade modules to function with mangled names. The `get_locals_if_split` / `get_facade_if_split` methods centralize split logic so that next.js module wrappers (which need unmangled export names) can use them directly.
parent 4268acf1
use std::collections::BTreeMap;
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -9,7 +7,7 @@ use turbopack_core::{ ...@@ -9,7 +7,7 @@ use turbopack_core::{
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::ModuleGraph, module_graph::ModuleGraph,
reference::{ModuleReferences, SingleChunkableModuleReference}, reference::{ModuleReference, ModuleReferences, SingleChunkableModuleReference},
resolve::ExportUsage, resolve::ExportUsage,
source::OptionSource, source::OptionSource,
}; };
...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{ ...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
}, },
references::esm::{EsmExport, EsmExports}, references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT}, runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs, utils::StringifyJs,
}; };
...@@ -90,32 +88,14 @@ impl ChunkableModule for NextDynamicEntryModule { ...@@ -90,32 +88,14 @@ impl ChunkableModule for NextDynamicEntryModule {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextDynamicEntryModule { impl EcmascriptChunkPlaceable for NextDynamicEntryModule {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> { fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference = ResolvedVc::upcast( let module_reference: Vc<Box<dyn ModuleReference>> =
SingleChunkableModuleReference::new( Vc::upcast(SingleChunkableModuleReference::new(
Vc::upcast(*self.module), Vc::upcast(*self.module),
dynamic_ref_description(), dynamic_ref_description(),
ExportUsage::all(), ExportUsage::all(),
) ));
.to_resolved() EsmExports::reexport_including_default(module_reference)
.await?,
);
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
default.clone(),
EsmExport::ImportedBinding(module_reference, default, false),
);
Ok(EcmascriptExports::EsmExports(
EsmExports {
exports,
star_exports: vec![module_reference],
}
.resolved_cell(),
)
.cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use std::collections::BTreeMap;
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::rcstr; use turbo_rcstr::rcstr;
...@@ -10,7 +8,7 @@ use turbopack_core::{ ...@@ -10,7 +8,7 @@ use turbopack_core::{
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::ModuleGraph, module_graph::ModuleGraph,
reference::ModuleReferences, reference::{ModuleReference, ModuleReferences},
source::OptionSource, source::OptionSource,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{ ...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
}, },
references::esm::{EsmExport, EsmExports}, references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT}, runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs, utils::StringifyJs,
}; };
...@@ -107,28 +105,11 @@ impl ChunkableModule for NextServerComponentModule { ...@@ -107,28 +105,11 @@ impl ChunkableModule for NextServerComponentModule {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextServerComponentModule { impl EcmascriptChunkPlaceable for NextServerComponentModule {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> { fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference = ResolvedVc::upcast( let module_reference: Vc<Box<dyn ModuleReference>> = Vc::upcast(
NextServerComponentModuleReference::new(Vc::upcast(*self.module)) NextServerComponentModuleReference::new(Vc::upcast(*self.module)),
.to_resolved()
.await?,
); );
EsmExports::reexport_including_default(module_reference)
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
default.clone(),
EsmExport::ImportedBinding(module_reference, default, false),
);
Ok(EcmascriptExports::EsmExports(
EsmExports {
exports,
star_exports: vec![module_reference],
}
.resolved_cell(),
)
.cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
use std::collections::BTreeMap;
use anyhow::Result; use anyhow::Result;
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::rcstr; use turbo_rcstr::rcstr;
...@@ -10,7 +8,7 @@ use turbopack_core::{ ...@@ -10,7 +8,7 @@ use turbopack_core::{
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::ModuleGraph, module_graph::ModuleGraph,
reference::ModuleReferences, reference::{ModuleReference, ModuleReferences},
source::OptionSource, source::OptionSource,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{ ...@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports, EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item, ecmascript_chunk_item,
}, },
references::esm::{EsmExport, EsmExports}, references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT}, runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs, utils::StringifyJs,
}; };
...@@ -88,28 +86,11 @@ impl ChunkableModule for NextServerUtilityModule { ...@@ -88,28 +86,11 @@ impl ChunkableModule for NextServerUtilityModule {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextServerUtilityModule { impl EcmascriptChunkPlaceable for NextServerUtilityModule {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> { fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference = ResolvedVc::upcast( let module_reference: Vc<Box<dyn ModuleReference>> = Vc::upcast(
NextServerUtilityModuleReference::new(Vc::upcast(*self.module)) NextServerUtilityModuleReference::new(Vc::upcast(*self.module)),
.to_resolved()
.await?,
); );
EsmExports::reexport_including_default(module_reference)
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
default.clone(),
EsmExport::ImportedBinding(module_reference, default, false),
);
Ok(EcmascriptExports::EsmExports(
EsmExports {
exports,
star_exports: vec![module_reference],
}
.resolved_cell(),
)
.cell())
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -293,6 +293,10 @@ pub enum EcmascriptExports { ...@@ -293,6 +293,10 @@ pub enum EcmascriptExports {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptExports { impl EcmascriptExports {
/// Returns whether this module should be split into separate locals and facade modules.
///
/// Splitting is enabled when the module has re-exports (star exports or imported bindings),
/// which allows the tree-shaking optimization to separate local definitions from re-exports.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn split_locals_and_reexports(&self) -> Result<Vc<bool>> { pub async fn split_locals_and_reexports(&self) -> Result<Vc<bool>> {
Ok(match self { Ok(match self {
......
...@@ -95,7 +95,7 @@ use turbopack_core::{ ...@@ -95,7 +95,7 @@ use turbopack_core::{
reference::ModuleReferences, reference::ModuleReferences,
reference_type::InnerAssets, reference_type::InnerAssets,
resolve::{ resolve::{
FindContextFileResult, find_context_file, origin::ResolveOrigin, package_json, FindContextFileResult, ModulePart, find_context_file, origin::ResolveOrigin, package_json,
parse::Request, parse::Request,
}, },
source::Source, source::Source,
...@@ -118,7 +118,10 @@ use crate::{ ...@@ -118,7 +118,10 @@ use crate::{
async_module::OptionAsyncModule, async_module::OptionAsyncModule,
esm::{UrlRewriteBehavior, base::EsmAssetReferences, export}, esm::{UrlRewriteBehavior, base::EsmAssetReferences, export},
}, },
side_effect_optimization::reference::EcmascriptModulePartReference, side_effect_optimization::{
facade::module::EcmascriptModuleFacadeModule, locals::module::EcmascriptModuleLocalsModule,
reference::EcmascriptModulePartReference,
},
swc_comments::{CowComments, ImmutableComments}, swc_comments::{CowComments, ImmutableComments},
transform::{remove_directives, remove_shebang}, transform::{remove_directives, remove_shebang},
}; };
...@@ -829,6 +832,44 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset { ...@@ -829,6 +832,44 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset {
} }
} }
#[turbo_tasks::value_impl]
impl EcmascriptModuleAsset {
/// Returns the locals module if the module should be split (has re-exports), otherwise self.
///
/// The locals module contains only the local bindings and evaluation side effects,
/// while re-exports are handled separately by the facade module.
#[turbo_tasks::function]
pub async fn get_locals_if_split(
self: Vc<Self>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
let should_split = *self.get_exports().split_locals_and_reexports().await?;
Ok(if should_split {
Vc::upcast(EcmascriptModuleLocalsModule::new(self))
} else {
Vc::upcast(self)
})
}
/// Returns the facade module if the module should be split (has re-exports), otherwise self.
///
/// The facade module re-exports all exports from the original module, including
/// both local bindings (via the locals module) and re-exports from other modules.
#[turbo_tasks::function]
pub async fn get_facade_if_split(
self: Vc<Self>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
let should_split = *self.get_exports().split_locals_and_reexports().await?;
Ok(if should_split {
Vc::upcast(EcmascriptModuleFacadeModule::new(
Vc::upcast(self),
ModulePart::Facade,
))
} else {
Vc::upcast(self)
})
}
}
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl MergeableModule for EcmascriptModuleAsset { impl MergeableModule for EcmascriptModuleAsset {
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -56,11 +56,11 @@ pub enum Liveness { ...@@ -56,11 +56,11 @@ pub enum Liveness {
pub enum EsmExport { pub enum EsmExport {
/// A local binding that is exported (export { a } or export const a = 1) /// A local binding that is exported (export { a } or export const a = 1)
/// ///
/// The last bool is true if the binding is a mutable binding /// Fields: (local_name, liveness)
LocalBinding(RcStr, Liveness), LocalBinding(RcStr, Liveness),
/// An imported binding that is exported (export { a as b } from "...") /// An imported binding that is exported (export { a as b } from "...")
/// ///
/// The last bool is true if the binding is a mutable binding /// Fields: (module_reference, name, is_mutable)
ImportedBinding(ResolvedVc<Box<dyn ModuleReference>>, RcStr, bool), ImportedBinding(ResolvedVc<Box<dyn ModuleReference>>, RcStr, bool),
/// An imported namespace that is exported (export * from "...") /// An imported namespace that is exported (export * from "...")
ImportedNamespace(ResolvedVc<Box<dyn ModuleReference>>), ImportedNamespace(ResolvedVc<Box<dyn ModuleReference>>),
...@@ -490,7 +490,9 @@ async fn emit_star_exports_issue(source_ident: Vc<AssetIdent>, message: RcStr) - ...@@ -490,7 +490,9 @@ async fn emit_star_exports_issue(source_ident: Vc<AssetIdent>, message: RcStr) -
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[derive(Hash, Debug)] #[derive(Hash, Debug)]
pub struct EsmExports { pub struct EsmExports {
/// Explicit exports
pub exports: BTreeMap<RcStr, EsmExport>, pub exports: BTreeMap<RcStr, EsmExport>,
/// Unexpanded `export * from ...` statements (expanded in `expand_star_exports`)
pub star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>>, pub star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>>,
} }
...@@ -508,6 +510,34 @@ pub struct ExpandedExports { ...@@ -508,6 +510,34 @@ pub struct ExpandedExports {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EsmExports { impl EsmExports {
/// Creates an EsmExports that re-exports all exports from another module.
/// This is useful for wrapper modules that simply forward all exports.
///
/// The resulting exports will have:
/// - A default export binding to the module's default
/// - A star export that re-exports all named exports
#[turbo_tasks::function]
pub async fn reexport_including_default(
module_reference: Vc<Box<dyn ModuleReference>>,
) -> Result<Vc<EcmascriptExports>> {
let module_reference = module_reference.to_resolved().await?;
let mut exports = BTreeMap::new();
let default = rcstr!("default");
exports.insert(
default.clone(),
EsmExport::ImportedBinding(module_reference, default, false),
);
Ok(EcmascriptExports::EsmExports(
EsmExports {
exports,
star_exports: vec![module_reference],
}
.resolved_cell(),
)
.cell())
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn expand_exports( pub async fn expand_exports(
&self, &self,
......
...@@ -54,9 +54,7 @@ use turbopack_ecmascript::{ ...@@ -54,9 +54,7 @@ use turbopack_ecmascript::{
external_module::{CachedExternalModule, CachedExternalTracingMode, CachedExternalType}, external_module::{CachedExternalModule, CachedExternalTracingMode, CachedExternalType},
follow_reexports, follow_reexports,
}, },
side_effect_optimization::{ side_effect_optimization::facade::module::EcmascriptModuleFacadeModule,
facade::module::EcmascriptModuleFacadeModule, locals::module::EcmascriptModuleLocalsModule,
},
tree_shake::asset::EcmascriptModulePartAsset, tree_shake::asset::EcmascriptModulePartAsset,
}; };
use turbopack_node::transforms::webpack::{WebpackLoaderItem, WebpackLoaderItems, WebpackLoaders}; use turbopack_node::transforms::webpack::{WebpackLoaderItem, WebpackLoaderItems, WebpackLoaders};
...@@ -198,33 +196,13 @@ async fn apply_module_type( ...@@ -198,33 +196,13 @@ async fn apply_module_type(
)) ))
} }
Some(TreeShakingMode::ReexportsOnly) => { Some(TreeShakingMode::ReexportsOnly) => {
// Returns the split module if necessary due to re-exports
if let Some(part) = part { if let Some(part) = part {
match part { match part {
ModulePart::Evaluation => { ModulePart::Evaluation => Vc::upcast(module.get_locals_if_split()),
if *module.get_exports().split_locals_and_reexports().await? {
Vc::upcast(EcmascriptModuleLocalsModule::new(*module))
} else {
Vc::upcast(*module)
}
}
ModulePart::Export(_) => { ModulePart::Export(_) => {
if *module.get_exports().split_locals_and_reexports().await? { apply_reexport_tree_shaking(module.get_facade_if_split(), part)
apply_reexport_tree_shaking(
Vc::upcast(
EcmascriptModuleFacadeModule::new(
Vc::upcast(*module),
ModulePart::facade(),
)
.resolve()
.await?,
),
part,
)
.await? .await?
} else {
apply_reexport_tree_shaking(Vc::upcast(*module), part)
.await?
}
} }
_ => bail!( _ => bail!(
"Invalid module part \"{}\" for reexports only tree shaking \ "Invalid module part \"{}\" for reexports only tree shaking \
...@@ -232,13 +210,8 @@ async fn apply_module_type( ...@@ -232,13 +210,8 @@ async fn apply_module_type(
part part
), ),
} }
} else if *module.get_exports().split_locals_and_reexports().await? {
Vc::upcast(EcmascriptModuleFacadeModule::new(
Vc::upcast(*module),
ModulePart::facade(),
))
} else { } else {
Vc::upcast(*module) Vc::upcast(module.get_facade_if_split())
} }
} }
None => Vc::upcast(*module), None => Vc::upcast(*module),
......
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