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 indoc::formatdoc;
use turbo_rcstr::{RcStr, rcstr};
......@@ -9,7 +7,7 @@ use turbopack_core::{
ident::AssetIdent,
module::{Module, ModuleSideEffects},
module_graph::ModuleGraph,
reference::{ModuleReferences, SingleChunkableModuleReference},
reference::{ModuleReference, ModuleReferences, SingleChunkableModuleReference},
resolve::ExportUsage,
source::OptionSource,
};
......@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item,
},
references::esm::{EsmExport, EsmExports},
references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs,
};
......@@ -90,32 +88,14 @@ impl ChunkableModule for NextDynamicEntryModule {
#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextDynamicEntryModule {
#[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> {
let module_reference = ResolvedVc::upcast(
SingleChunkableModuleReference::new(
fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference: Vc<Box<dyn ModuleReference>> =
Vc::upcast(SingleChunkableModuleReference::new(
Vc::upcast(*self.module),
dynamic_ref_description(),
ExportUsage::all(),
)
.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())
));
EsmExports::reexport_including_default(module_reference)
}
#[turbo_tasks::function]
......
use std::collections::BTreeMap;
use anyhow::Result;
use indoc::formatdoc;
use turbo_rcstr::rcstr;
......@@ -10,7 +8,7 @@ use turbopack_core::{
ident::AssetIdent,
module::{Module, ModuleSideEffects},
module_graph::ModuleGraph,
reference::ModuleReferences,
reference::{ModuleReference, ModuleReferences},
source::OptionSource,
};
use turbopack_ecmascript::{
......@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item,
},
references::esm::{EsmExport, EsmExports},
references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs,
};
......@@ -107,28 +105,11 @@ impl ChunkableModule for NextServerComponentModule {
#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextServerComponentModule {
#[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> {
let module_reference = ResolvedVc::upcast(
NextServerComponentModuleReference::new(Vc::upcast(*self.module))
.to_resolved()
.await?,
fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference: Vc<Box<dyn ModuleReference>> = Vc::upcast(
NextServerComponentModuleReference::new(Vc::upcast(*self.module)),
);
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())
EsmExports::reexport_including_default(module_reference)
}
#[turbo_tasks::function]
......
use std::collections::BTreeMap;
use anyhow::Result;
use indoc::formatdoc;
use turbo_rcstr::rcstr;
......@@ -10,7 +8,7 @@ use turbopack_core::{
ident::AssetIdent,
module::{Module, ModuleSideEffects},
module_graph::ModuleGraph,
reference::ModuleReferences,
reference::{ModuleReference, ModuleReferences},
source::OptionSource,
};
use turbopack_ecmascript::{
......@@ -18,7 +16,7 @@ use turbopack_ecmascript::{
EcmascriptChunkItemContent, EcmascriptChunkPlaceable, EcmascriptExports,
ecmascript_chunk_item,
},
references::esm::{EsmExport, EsmExports},
references::esm::EsmExports,
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_IMPORT},
utils::StringifyJs,
};
......@@ -88,28 +86,11 @@ impl ChunkableModule for NextServerUtilityModule {
#[turbo_tasks::value_impl]
impl EcmascriptChunkPlaceable for NextServerUtilityModule {
#[turbo_tasks::function]
async fn get_exports(&self) -> Result<Vc<EcmascriptExports>> {
let module_reference = ResolvedVc::upcast(
NextServerUtilityModuleReference::new(Vc::upcast(*self.module))
.to_resolved()
.await?,
fn get_exports(&self) -> Vc<EcmascriptExports> {
let module_reference: Vc<Box<dyn ModuleReference>> = Vc::upcast(
NextServerUtilityModuleReference::new(Vc::upcast(*self.module)),
);
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())
EsmExports::reexport_including_default(module_reference)
}
#[turbo_tasks::function]
......
......@@ -293,6 +293,10 @@ pub enum EcmascriptExports {
#[turbo_tasks::value_impl]
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]
pub async fn split_locals_and_reexports(&self) -> Result<Vc<bool>> {
Ok(match self {
......
......@@ -95,7 +95,7 @@ use turbopack_core::{
reference::ModuleReferences,
reference_type::InnerAssets,
resolve::{
FindContextFileResult, find_context_file, origin::ResolveOrigin, package_json,
FindContextFileResult, ModulePart, find_context_file, origin::ResolveOrigin, package_json,
parse::Request,
},
source::Source,
......@@ -118,7 +118,10 @@ use crate::{
async_module::OptionAsyncModule,
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},
transform::{remove_directives, remove_shebang},
};
......@@ -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]
impl MergeableModule for EcmascriptModuleAsset {
#[turbo_tasks::function]
......
......@@ -56,11 +56,11 @@ pub enum Liveness {
pub enum EsmExport {
/// 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),
/// 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),
/// An imported namespace that is exported (export * from "...")
ImportedNamespace(ResolvedVc<Box<dyn ModuleReference>>),
......@@ -490,7 +490,9 @@ async fn emit_star_exports_issue(source_ident: Vc<AssetIdent>, message: RcStr) -
#[turbo_tasks::value(shared)]
#[derive(Hash, Debug)]
pub struct EsmExports {
/// Explicit exports
pub exports: BTreeMap<RcStr, EsmExport>,
/// Unexpanded `export * from ...` statements (expanded in `expand_star_exports`)
pub star_exports: Vec<ResolvedVc<Box<dyn ModuleReference>>>,
}
......@@ -508,6 +510,34 @@ pub struct ExpandedExports {
#[turbo_tasks::value_impl]
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]
pub async fn expand_exports(
&self,
......
......@@ -54,9 +54,7 @@ use turbopack_ecmascript::{
external_module::{CachedExternalModule, CachedExternalTracingMode, CachedExternalType},
follow_reexports,
},
side_effect_optimization::{
facade::module::EcmascriptModuleFacadeModule, locals::module::EcmascriptModuleLocalsModule,
},
side_effect_optimization::facade::module::EcmascriptModuleFacadeModule,
tree_shake::asset::EcmascriptModulePartAsset,
};
use turbopack_node::transforms::webpack::{WebpackLoaderItem, WebpackLoaderItems, WebpackLoaders};
......@@ -198,33 +196,13 @@ async fn apply_module_type(
))
}
Some(TreeShakingMode::ReexportsOnly) => {
// Returns the split module if necessary due to re-exports
if let Some(part) = part {
match part {
ModulePart::Evaluation => {
if *module.get_exports().split_locals_and_reexports().await? {
Vc::upcast(EcmascriptModuleLocalsModule::new(*module))
} else {
Vc::upcast(*module)
}
}
ModulePart::Evaluation => Vc::upcast(module.get_locals_if_split()),
ModulePart::Export(_) => {
if *module.get_exports().split_locals_and_reexports().await? {
apply_reexport_tree_shaking(
Vc::upcast(
EcmascriptModuleFacadeModule::new(
Vc::upcast(*module),
ModulePart::facade(),
)
.resolve()
.await?,
),
part,
)
apply_reexport_tree_shaking(module.get_facade_if_split(), part)
.await?
} else {
apply_reexport_tree_shaking(Vc::upcast(*module), part)
.await?
}
}
_ => bail!(
"Invalid module part \"{}\" for reexports only tree shaking \
......@@ -232,13 +210,8 @@ async fn apply_module_type(
part
),
}
} else if *module.get_exports().split_locals_and_reexports().await? {
Vc::upcast(EcmascriptModuleFacadeModule::new(
Vc::upcast(*module),
ModulePart::facade(),
))
} else {
Vc::upcast(*module)
Vc::upcast(module.get_facade_if_split())
}
}
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