Unverified Commit edd910c0 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

[Turbopack] Read merged module groups from chunking contexts

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 013908ab
...@@ -81,6 +81,7 @@ use turbopack_core::{ ...@@ -81,6 +81,7 @@ use turbopack_core::{
BindingUsageInfo, OptionBindingUsageInfo, compute_binding_usage_info, BindingUsageInfo, OptionBindingUsageInfo, compute_binding_usage_info,
}, },
chunk_group_info::{ChunkGroupEntry, EntryHeuristics}, chunk_group_info::{ChunkGroupEntry, EntryHeuristics},
merged_modules::MergedModuleGroups,
}, },
output::{ output::{
ExpandOutputAssetsInput, ExpandedOutputAssets, OutputAsset, OutputAssets, ExpandOutputAssetsInput, ExpandedOutputAssets, OutputAsset, OutputAssets,
...@@ -1718,6 +1719,7 @@ impl Project { ...@@ -1718,6 +1719,7 @@ impl Project {
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(), unused_references: self.unused_references(),
merged_modules: self.merged_modules(),
minify: self.next_config().turbo_client_minify(self.next_mode()), minify: self.next_config().turbo_client_minify(self.next_mode()),
source_maps: self.next_config().client_source_maps(self.next_mode()), source_maps: self.next_config().client_source_maps(self.next_mode()),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -1813,6 +1815,7 @@ impl Project { ...@@ -1813,6 +1815,7 @@ impl Project {
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(), unused_references: self.unused_references(),
merged_modules: self.merged_modules(),
minify: self.next_config().turbo_server_minify(self.next_mode()), minify: self.next_config().turbo_server_minify(self.next_mode()),
source_maps: self.next_config().server_source_maps(), source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -1860,6 +1863,7 @@ impl Project { ...@@ -1860,6 +1863,7 @@ impl Project {
module_id_strategy: self.module_ids(), module_id_strategy: self.module_ids(),
export_usage: self.export_usage(), export_usage: self.export_usage(),
unused_references: self.unused_references(), unused_references: self.unused_references(),
merged_modules: self.merged_modules(),
turbo_minify: self.next_config().turbo_edge_minify(self.next_mode()), turbo_minify: self.next_config().turbo_edge_minify(self.next_mode()),
turbo_source_maps: self.next_config().server_source_maps(), turbo_source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
...@@ -2807,6 +2811,26 @@ impl Project { ...@@ -2807,6 +2811,26 @@ impl Project {
} }
} }
/// Compute scope-hoisting groups for the same full graph used for production chunking.
#[turbo_tasks::function]
pub async fn merged_modules(self: Vc<Self>) -> Result<Vc<MergedModuleGroups>> {
if *self
.next_config()
.turbo_scope_hoisting(self.next_mode())
.await?
{
Ok(*self
.whole_app_module_graphs()
.await?
.full
.merged_modules()
.await?
.groups)
} else {
Ok(Vc::cell(Default::default()))
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn with_next_config(&self, next_config: Vc<NextConfig>) -> Result<Vc<Self>> { pub async fn with_next_config(&self, next_config: Vc<NextConfig>) -> Result<Vc<Self>> {
Ok(Self { Ok(Self {
......
...@@ -50,6 +50,7 @@ use turbopack_core::{ ...@@ -50,6 +50,7 @@ use turbopack_core::{
module_graph::{ module_graph::{
GraphTraversalAction, ModuleGraph, ModuleGraphLayer, async_module_info::AsyncModulesInfo, GraphTraversalAction, ModuleGraph, ModuleGraphLayer, async_module_info::AsyncModulesInfo,
binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroupKey, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroupKey,
merged_modules::MergedModuleGroups,
}, },
output::{OutputAsset, OutputAssets, OutputAssetsReference}, output::{OutputAsset, OutputAssets, OutputAssetsReference},
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType}, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
...@@ -1332,6 +1333,12 @@ impl ChunkingContext for UseCacheContentHashChunkingContext { ...@@ -1332,6 +1333,12 @@ impl ChunkingContext for UseCacheContentHashChunkingContext {
Vc::cell(Default::default()) Vc::cell(Default::default())
} }
#[turbo_tasks::function]
fn merged_modules(self: Vc<Self>) -> Vc<MergedModuleGroups> {
// Hashes describe standalone module content, independent of scope-hoisting groups.
Vc::cell(Default::default())
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> { async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> {
bail!("debug_ids_enabled should not be called in UseCacheContentHashChunkingContext") bail!("debug_ids_enabled should not be called in UseCacheContentHashChunkingContext")
......
...@@ -23,7 +23,8 @@ use turbopack_core::{ ...@@ -23,7 +23,8 @@ use turbopack_core::{
free_var_references, free_var_references,
issue::IssueSeverity, issue::IssueSeverity,
module_graph::{ module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm, binding_usage_info::OptionBindingUsageInfo, merged_modules::MergedModuleGroups,
style_groups::StyleGroupsAlgorithm,
}, },
resolve::{parse::Request, pattern::Pattern}, resolve::{parse::Request, pattern::Pattern},
}; };
...@@ -490,6 +491,7 @@ pub struct ClientChunkingContextOptions { ...@@ -490,6 +491,7 @@ pub struct ClientChunkingContextOptions {
pub module_id_strategy: Vc<ModuleIdStrategy>, pub module_id_strategy: Vc<ModuleIdStrategy>,
pub export_usage: Vc<OptionBindingUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<UnusedReferences>, pub unused_references: Vc<UnusedReferences>,
pub merged_modules: Vc<MergedModuleGroups>,
pub minify: Vc<bool>, pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>, pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -540,6 +542,7 @@ pub async fn get_client_chunking_context( ...@@ -540,6 +542,7 @@ pub async fn get_client_chunking_context(
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references, unused_references,
merged_modules,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -601,6 +604,7 @@ pub async fn get_client_chunking_context( ...@@ -601,6 +604,7 @@ pub async fn get_client_chunking_context(
.chunk_load_retry(NEXT_CHUNK_LOAD_RETRY) .chunk_load_retry(NEXT_CHUNK_LOAD_RETRY)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.worker_asset_prefix(worker_asset_prefix.owned().await?) .worker_asset_prefix(worker_asset_prefix.owned().await?)
......
...@@ -286,7 +286,7 @@ impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule { ...@@ -286,7 +286,7 @@ impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule {
async fn chunk_item_content( async fn chunk_item_content(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
...@@ -294,7 +294,6 @@ impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule { ...@@ -294,7 +294,6 @@ impl EcmascriptChunkPlaceable for EcmascriptClientReferenceModule {
*ResolvedVc::upcast(self), *ResolvedVc::upcast(self),
self.proxy_module(), self.proxy_module(),
*chunking_context, *chunking_context,
module_graph,
async_module_info, async_module_info,
)) ))
} }
......
...@@ -15,7 +15,8 @@ use turbopack_core::{ ...@@ -15,7 +15,8 @@ use turbopack_core::{
free_var_references, free_var_references,
issue::IssueSeverity, issue::IssueSeverity,
module_graph::{ module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm, binding_usage_info::OptionBindingUsageInfo, merged_modules::MergedModuleGroups,
style_groups::StyleGroupsAlgorithm,
}, },
}; };
use turbopack_css::chunk::CssChunkType; use turbopack_css::chunk::CssChunkType;
...@@ -181,6 +182,7 @@ pub struct EdgeChunkingContextOptions { ...@@ -181,6 +182,7 @@ pub struct EdgeChunkingContextOptions {
pub module_id_strategy: Vc<ModuleIdStrategy>, pub module_id_strategy: Vc<ModuleIdStrategy>,
pub export_usage: Vc<OptionBindingUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<UnusedReferences>, pub unused_references: Vc<UnusedReferences>,
pub merged_modules: Vc<MergedModuleGroups>,
pub turbo_minify: Vc<bool>, pub turbo_minify: Vc<bool>,
pub turbo_source_maps: Vc<SourceMapsType>, pub turbo_source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -209,6 +211,7 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -209,6 +211,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references, unused_references,
merged_modules,
turbo_minify, turbo_minify,
turbo_source_maps, turbo_source_maps,
no_mangling, no_mangling,
...@@ -264,6 +267,7 @@ pub async fn get_edge_chunking_context_with_client_assets( ...@@ -264,6 +267,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals()); .worker_forwarded_globals(worker_forwarded_globals());
...@@ -305,6 +309,7 @@ pub async fn get_edge_chunking_context( ...@@ -305,6 +309,7 @@ pub async fn get_edge_chunking_context(
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references, unused_references,
merged_modules,
turbo_minify, turbo_minify,
turbo_source_maps, turbo_source_maps,
no_mangling, no_mangling,
...@@ -377,6 +382,7 @@ pub async fn get_edge_chunking_context( ...@@ -377,6 +382,7 @@ pub async fn get_edge_chunking_context(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals()); .worker_forwarded_globals(worker_forwarded_globals());
......
...@@ -23,7 +23,8 @@ use turbopack_core::{ ...@@ -23,7 +23,8 @@ use turbopack_core::{
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion}, environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion},
issue::IssueSeverity, issue::IssueSeverity,
module_graph::{ module_graph::{
binding_usage_info::OptionBindingUsageInfo, style_groups::StyleGroupsAlgorithm, binding_usage_info::OptionBindingUsageInfo, merged_modules::MergedModuleGroups,
style_groups::StyleGroupsAlgorithm,
}, },
target::CompileTarget, target::CompileTarget,
}; };
...@@ -1021,6 +1022,7 @@ pub struct ServerChunkingContextOptions { ...@@ -1021,6 +1022,7 @@ pub struct ServerChunkingContextOptions {
pub module_id_strategy: Vc<ModuleIdStrategy>, pub module_id_strategy: Vc<ModuleIdStrategy>,
pub export_usage: Vc<OptionBindingUsageInfo>, pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<UnusedReferences>, pub unused_references: Vc<UnusedReferences>,
pub merged_modules: Vc<MergedModuleGroups>,
pub minify: Vc<bool>, pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>, pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
...@@ -1051,6 +1053,7 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1051,6 +1053,7 @@ pub async fn get_server_chunking_context_with_client_assets(
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references, unused_references,
merged_modules,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -1108,6 +1111,7 @@ pub async fn get_server_chunking_context_with_client_assets( ...@@ -1108,6 +1111,7 @@ pub async fn get_server_chunking_context_with_client_assets(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
...@@ -1163,6 +1167,7 @@ pub async fn get_server_chunking_context( ...@@ -1163,6 +1167,7 @@ pub async fn get_server_chunking_context(
module_id_strategy, module_id_strategy,
export_usage, export_usage,
unused_references, unused_references,
merged_modules,
minify, minify,
source_maps, source_maps,
no_mangling, no_mangling,
...@@ -1223,6 +1228,7 @@ pub async fn get_server_chunking_context( ...@@ -1223,6 +1228,7 @@ pub async fn get_server_chunking_context(
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.merged_modules(merged_modules.to_resolved().await?)
.debug_ids(*debug_ids.await?) .debug_ids(*debug_ids.await?)
.hash_salt(hash_salt) .hash_salt(hash_salt)
.nested_async_availability(*nested_async_chunking.await?) .nested_async_availability(*nested_async_chunking.await?)
......
...@@ -28,6 +28,7 @@ use turbopack_core::{ ...@@ -28,6 +28,7 @@ use turbopack_core::{
ModuleGraph, ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage}, binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::{ChunkGroup, ChunkGroupKey}, chunk_group_info::{ChunkGroup, ChunkGroupKey},
merged_modules::MergedModuleGroups,
}, },
output::{ExpandOutputAssetsInput, OutputAsset, OutputAssets, expand_output_assets}, output::{ExpandOutputAssetsInput, OutputAsset, OutputAssets, expand_output_assets},
}; };
...@@ -167,6 +168,11 @@ impl BrowserChunkingContextBuilder { ...@@ -167,6 +168,11 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn merged_modules(mut self, merged_modules: ResolvedVc<MergedModuleGroups>) -> Self {
self.chunking_context.merged_modules = Some(merged_modules);
self
}
pub fn debug_ids(mut self, debug_ids: bool) -> Self { pub fn debug_ids(mut self, debug_ids: bool) -> Self {
self.chunking_context.debug_ids = debug_ids; self.chunking_context.debug_ids = debug_ids;
self self
...@@ -390,6 +396,7 @@ pub struct BrowserChunkingContext { ...@@ -390,6 +396,7 @@ pub struct BrowserChunkingContext {
export_usage: Option<ResolvedVc<BindingUsageInfo>>, export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen). /// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<UnusedReferences>>, unused_references: Option<ResolvedVc<UnusedReferences>>,
merged_modules: Option<ResolvedVc<MergedModuleGroups>>,
/// The chunking configs /// The chunking configs
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>, chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
/// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`) /// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`)
...@@ -459,6 +466,7 @@ impl BrowserChunkingContext { ...@@ -459,6 +466,7 @@ impl BrowserChunkingContext {
module_id_strategy: None, module_id_strategy: None,
export_usage: None, export_usage: None,
unused_references: None, unused_references: None,
merged_modules: None,
chunking_configs: Default::default(), chunking_configs: Default::default(),
should_use_absolute_url_references: false, should_use_absolute_url_references: false,
worker_forwarded_globals: vec![], worker_forwarded_globals: vec![],
...@@ -1333,6 +1341,17 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -1333,6 +1341,17 @@ impl ChunkingContext for BrowserChunkingContext {
} }
} }
#[turbo_tasks::function]
fn merged_modules(&self) -> Vc<MergedModuleGroups> {
if self.enable_module_merging
&& let Some(merged_modules) = self.merged_modules
{
*merged_modules
} else {
Vc::cell(Default::default())
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> { async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.debug_ids)) Ok(Vc::cell(self.await?.debug_ids))
......
...@@ -385,6 +385,10 @@ async fn build_internal( ...@@ -385,6 +385,10 @@ async fn build_internal(
.asset_content_hashing(ContentHashing::Direct { length: 13 }) .asset_content_hashing(ContentHashing::Direct { length: 13 })
.nested_async_availability(true) .nested_async_availability(true)
.module_merging(scope_hoist); .module_merging(scope_hoist);
if scope_hoist {
builder =
builder.merged_modules(module_graph.merged_modules().await?.groups);
}
} }
} }
...@@ -432,6 +436,10 @@ async fn build_internal( ...@@ -432,6 +436,10 @@ async fn build_internal(
}, },
) )
.module_merging(scope_hoist); .module_merging(scope_hoist);
if scope_hoist {
builder =
builder.merged_modules(module_graph.merged_modules().await?.groups);
}
} }
} }
......
...@@ -20,7 +20,8 @@ use crate::{ ...@@ -20,7 +20,8 @@ use crate::{
module::Module, module::Module,
module_graph::{ module_graph::{
ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroupKey, ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroupKey,
module_batches::BatchingConfig, style_groups::StyleGroupsAlgorithm, merged_modules::MergedModuleGroups, module_batches::BatchingConfig,
style_groups::StyleGroupsAlgorithm,
}, },
output::{ output::{
ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences, ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences,
...@@ -552,6 +553,10 @@ pub trait ChunkingContext { ...@@ -552,6 +553,10 @@ pub trait ChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn unused_references(self: Vc<Self>) -> Result<Vc<UnusedReferences>>; async fn unused_references(self: Vc<Self>) -> Result<Vc<UnusedReferences>>;
/// Scope-hoisting groups keyed by source module. Empty when module merging is disabled.
#[turbo_tasks::function]
async fn merged_modules(self: Vc<Self>) -> Result<Vc<MergedModuleGroups>>;
/// Returns whether debug IDs are enabled for this chunking context. /// Returns whether debug IDs are enabled for this chunking context.
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>; fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
......
...@@ -15,7 +15,7 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat}; ...@@ -15,7 +15,7 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat};
use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference}; use turbopack_core::{chunk::ChunkingContext, reference::ModuleReference};
use crate::{ use crate::{
ModuleMergingAnalysis, ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder}, ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
references::{ references::{
...@@ -215,7 +215,6 @@ impl CodeGen { ...@@ -215,7 +215,6 @@ impl CodeGen {
&self, &self,
trie: &AstPathTrie, trie: &AstPathTrie,
ctx: Vc<Box<dyn ChunkingContext>>, ctx: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>, exports: ResolvedVc<EcmascriptExports>,
...@@ -223,18 +222,12 @@ impl CodeGen { ...@@ -223,18 +222,12 @@ impl CodeGen {
match self { match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(trie, ctx).await, Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(trie, ctx).await, Self::ConstantConditionCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx, module_merging).await, Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await, Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await,
Self::DynamicExpression(v) => v.code_generation(trie, ctx).await, Self::DynamicExpression(v) => v.code_generation(trie, ctx).await,
Self::EsmBindings(v) => { Self::EsmBindings(v) => v.code_generation(trie, ctx, scope_hoisting_context).await,
v.code_generation(trie, ctx, module_merging, scope_hoisting_context)
.await
}
Self::EsmModuleItem(v) => v.code_generation(trie, ctx).await, Self::EsmModuleItem(v) => v.code_generation(trie, ctx).await,
Self::ExportsInfoBinding(v) => { Self::ExportsInfoBinding(v) => v.code_generation(trie, ctx, module, exports).await,
v.code_generation(trie, ctx, module_merging, module, exports)
.await
}
Self::ExportsInfoRef(v) => v.code_generation(trie, ctx).await, Self::ExportsInfoRef(v) => v.code_generation(trie, ctx).await,
Self::CjsExportsDropCodeGen(v) => v.code_generation(trie, ctx, module, exports).await, Self::CjsExportsDropCodeGen(v) => v.code_generation(trie, ctx, module, exports).await,
Self::IdentReplacement(v) => v.code_generation(trie, ctx).await, Self::IdentReplacement(v) => v.code_generation(trie, ctx).await,
...@@ -252,8 +245,7 @@ impl CodeGen { ...@@ -252,8 +245,7 @@ impl CodeGen {
Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await, Self::WorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ServiceWorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await, Self::ServiceWorkerAssetReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ModuleHotReferenceCodeGen(v) => { Self::ModuleHotReferenceCodeGen(v) => {
v.code_generation(trie, ctx, module_merging, scope_hoisting_context) v.code_generation(trie, ctx, scope_hoisting_context).await
.await
} }
Self::WorkerGlobalsReplacementCodeGen(v) => v.code_generation(trie, ctx).await, Self::WorkerGlobalsReplacementCodeGen(v) => v.code_generation(trie, ctx).await,
} }
......
...@@ -281,13 +281,9 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup { ...@@ -281,13 +281,9 @@ impl EcmascriptChunkPlaceable for EcmascriptCollectModuleWithChunkGroup {
// The *key* this is exposed under may be mangled; the local binding keeps its own name. // The *key* this is exposed under may be mangled; the local binding keeps its own name.
// `references::emit_collect` resolves the same key for the read side, so both agree. // `references::emit_collect` resolves the same key for the read side, so both agree.
let module_merging =
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let export = generated_export_key( let export = generated_export_key(
ResolvedVc::upcast(self.to_resolved().await?), ResolvedVc::upcast(self.to_resolved().await?),
chunking_context, chunking_context,
module_merging,
&COLLECT_LIST_EXPORT, &COLLECT_LIST_EXPORT,
) )
.await?; .await?;
......
...@@ -491,16 +491,10 @@ pub trait EcmascriptAnalyzable: Module { ...@@ -491,16 +491,10 @@ pub trait EcmascriptAnalyzable: Module {
) -> Result<Vc<EcmascriptModuleContentOptions>>; ) -> Result<Vc<EcmascriptModuleContentOptions>>;
} }
/// Existing scope-hoisting results, passed explicitly to code generation. Each consumer reads
/// only its target modules through the keyed map; `None` means module merging is disabled.
pub type ModuleMergingAnalysis =
Option<ResolvedVc<turbopack_core::module_graph::merged_modules::MergedModuleGroups>>;
pub trait EcmascriptAnalyzableExt { pub trait EcmascriptAnalyzableExt {
fn module_content( fn module_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Vc<EcmascriptModuleContent>; ) -> Vc<EcmascriptModuleContent>;
} }
...@@ -512,12 +506,11 @@ where ...@@ -512,12 +506,11 @@ where
fn module_content( fn module_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Vc<EcmascriptModuleContent> { ) -> Vc<EcmascriptModuleContent> {
let analyzable = Vc::upcast_non_strict::<Box<dyn EcmascriptAnalyzable>>(self); let analyzable = Vc::upcast_non_strict::<Box<dyn EcmascriptAnalyzable>>(self);
let own_options = analyzable.module_content_options(chunking_context, async_module_info); let own_options = analyzable.module_content_options(chunking_context, async_module_info);
EcmascriptModuleContent::new(own_options, module_merging) EcmascriptModuleContent::new(own_options)
} }
} }
...@@ -980,7 +973,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset { ...@@ -980,7 +973,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
...@@ -990,10 +983,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset { ...@@ -990,10 +983,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleAsset {
); );
async { async {
let async_module_options = self.get_async_module().module_options(async_module_info); let async_module_options = self.get_async_module().module_options(async_module_info);
let module_merging = let content = self.module_content(chunking_context, async_module_info);
references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = self.module_content(chunking_context, module_merging, async_module_info);
EcmascriptChunkItemContent::new(content, chunking_context, async_module_options) EcmascriptChunkItemContent::new(content, chunking_context, async_module_options)
.to_resolved() .to_resolved()
.await .await
...@@ -1090,7 +1080,6 @@ pub async fn chunk_item_content_with_code_from( ...@@ -1090,7 +1080,6 @@ pub async fn chunk_item_content_with_code_from(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
code_source: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, code_source: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let Some(analyzable) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptAnalyzable>>(code_source) let Some(analyzable) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptAnalyzable>>(code_source)
...@@ -1102,9 +1091,7 @@ pub async fn chunk_item_content_with_code_from( ...@@ -1102,9 +1091,7 @@ pub async fn chunk_item_content_with_code_from(
.await?; .await?;
let mut options = (*source_options).clone(); let mut options = (*source_options).clone();
options.module = module; options.module = module;
let module_merging = let content = EcmascriptModuleContent::new(options.cell());
references::esm::mangle::module_merging_analysis(module_graph, *chunking_context).await?;
let content = EcmascriptModuleContent::new(options.cell(), module_merging);
let async_module_options = code_source let async_module_options = code_source
.get_async_module() .get_async_module()
.module_options(async_module_info); .module_options(async_module_info);
...@@ -1119,7 +1106,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1119,7 +1106,6 @@ impl EcmascriptModuleContentOptions {
async fn merged_code_gens( async fn merged_code_gens(
&self, &self,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
module_merging: ModuleMergingAnalysis,
eval_context: &EvalContext, eval_context: &EvalContext,
) -> Result<(Vec<CodeGeneration>, ReadRef<CodeGens>)> { ) -> Result<(Vec<CodeGeneration>, ReadRef<CodeGens>)> {
// Don't read `parsed` here again, it will cause a recomputation as `process_parse_result` // Don't read `parsed` here again, it will cause a recomputation as `process_parse_result`
...@@ -1149,7 +1135,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1149,7 +1135,6 @@ impl EcmascriptModuleContentOptions {
let (code_gen, subsumed) = exports let (code_gen, subsumed) = exports
.code_generation( .code_generation(
**chunking_context, **chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
eval_context, eval_context,
*module, *module,
...@@ -1173,7 +1158,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1173,7 +1158,6 @@ impl EcmascriptModuleContentOptions {
async_module_info.map(|info| *info), async_module_info.map(|info| *info),
**references, **references,
**chunking_context, **chunking_context,
module_merging,
) )
.await?, .await?,
) )
...@@ -1188,7 +1172,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1188,7 +1172,6 @@ impl EcmascriptModuleContentOptions {
.map(|r| { .map(|r| {
r.code_generation( r.code_generation(
**chunking_context, **chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
&subsumed_imports.namespaces, &subsumed_imports.namespaces,
) )
...@@ -1201,7 +1184,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1201,7 +1184,6 @@ impl EcmascriptModuleContentOptions {
.map(|r| { .map(|r| {
r.code_generation( r.code_generation(
**chunking_context, **chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
&subsumed_imports, &subsumed_imports,
) )
...@@ -1217,7 +1199,6 @@ impl EcmascriptModuleContentOptions { ...@@ -1217,7 +1199,6 @@ impl EcmascriptModuleContentOptions {
c.code_generation( c.code_generation(
&code_generation.ast_paths, &code_generation.ast_paths,
**chunking_context, **chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
*module, *module,
*exports, *exports,
...@@ -1245,10 +1226,7 @@ impl EcmascriptModuleContentOptions { ...@@ -1245,10 +1226,7 @@ impl EcmascriptModuleContentOptions {
impl EcmascriptModuleContent { impl EcmascriptModuleContent {
/// Creates a new [`Vc<EcmascriptModuleContent>`]. /// Creates a new [`Vc<EcmascriptModuleContent>`].
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn new( pub async fn new(input: Vc<EcmascriptModuleContentOptions>) -> Result<Vc<Self>> {
input: Vc<EcmascriptModuleContentOptions>,
module_merging: ModuleMergingAnalysis,
) -> Result<Vc<Self>> {
let input = input.await?; let input = input.await?;
let EcmascriptModuleContentOptions { let EcmascriptModuleContentOptions {
parsed, parsed,
...@@ -1270,7 +1248,6 @@ impl EcmascriptModuleContent { ...@@ -1270,7 +1248,6 @@ impl EcmascriptModuleContent {
*original_source_map, *original_source_map,
*minify, *minify,
Some(&*input), Some(&*input),
module_merging,
None, None,
) )
.await?; .await?;
...@@ -1294,7 +1271,6 @@ impl EcmascriptModuleContent { ...@@ -1294,7 +1271,6 @@ impl EcmascriptModuleContent {
MinifyType::NoMinify, MinifyType::NoMinify,
None, None,
None, None,
None,
) )
.await?; .await?;
emit_content(content, Default::default()).await emit_content(content, Default::default()).await
...@@ -1314,7 +1290,6 @@ impl EcmascriptModuleContent { ...@@ -1314,7 +1290,6 @@ impl EcmascriptModuleContent {
)>, )>,
module_options: Vec<Vc<EcmascriptModuleContentOptions>>, module_options: Vec<Vc<EcmascriptModuleContentOptions>>,
entry_points: Vec<ResolvedVc<Box<dyn EcmascriptAnalyzable>>>, entry_points: Vec<ResolvedVc<Box<dyn EcmascriptAnalyzable>>>,
module_merging: ModuleMergingAnalysis,
) -> Result<Vc<Self>> { ) -> Result<Vc<Self>> {
async { async {
let modules = modules let modules = modules
...@@ -1359,7 +1334,6 @@ impl EcmascriptModuleContent { ...@@ -1359,7 +1334,6 @@ impl EcmascriptModuleContent {
*original_source_map, *original_source_map,
*chunking_context.minify_type().await?, *chunking_context.minify_type().await?,
Some(&*options), Some(&*options),
module_merging,
Some(ScopeHoistingOptions { Some(ScopeHoistingOptions {
module: *module, module: *module,
modules: &modules, modules: &modules,
...@@ -1378,7 +1352,6 @@ impl EcmascriptModuleContent { ...@@ -1378,7 +1352,6 @@ impl EcmascriptModuleContent {
let flat_group = *references::esm::mangle::flat_export_group( let flat_group = *references::esm::mangle::flat_export_group(
*entry_points[0].0, *entry_points[0].0,
*options.chunking_context, *options.chunking_context,
module_merging,
) )
.await?; .await?;
let flat_exports = flat_group.is_some(); let flat_exports = flat_group.is_some();
...@@ -2033,7 +2006,6 @@ async fn process_parse_result( ...@@ -2033,7 +2006,6 @@ async fn process_parse_result(
original_source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>, original_source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>,
minify: MinifyType, minify: MinifyType,
options: Option<&EcmascriptModuleContentOptions>, options: Option<&EcmascriptModuleContentOptions>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_options: Option<ScopeHoistingOptions<'_>>, scope_hoisting_options: Option<ScopeHoistingOptions<'_>>,
) -> Result<CodeGenResult> { ) -> Result<CodeGenResult> {
with_consumed_parse_result( with_consumed_parse_result(
...@@ -2075,7 +2047,6 @@ async fn process_parse_result( ...@@ -2075,7 +2047,6 @@ async fn process_parse_result(
.unwrap() .unwrap()
.merged_code_gens( .merged_code_gens(
ctx, ctx,
module_merging,
match &eval_context { match &eval_context {
Either::Left(e) => e, Either::Left(e) => e,
Either::Right(e) => e, Either::Right(e) => e,
...@@ -2132,7 +2103,6 @@ async fn process_parse_result( ...@@ -2132,7 +2103,6 @@ async fn process_parse_result(
let (code_gens, ast_paths) = options let (code_gens, ast_paths) = options
.merged_code_gens( .merged_code_gens(
ScopeHoistingContext::None, ScopeHoistingContext::None,
module_merging,
match &eval_context { match &eval_context {
Either::Left(e) => e, Either::Left(e) => e,
Either::Right(e) => e, Either::Right(e) => e,
......
...@@ -114,7 +114,7 @@ impl EcmascriptChunkPlaceable for MergedEcmascriptModule { ...@@ -114,7 +114,7 @@ impl EcmascriptChunkPlaceable for MergedEcmascriptModule {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
...@@ -126,14 +126,10 @@ impl EcmascriptChunkPlaceable for MergedEcmascriptModule { ...@@ -126,14 +126,10 @@ impl EcmascriptChunkPlaceable for MergedEcmascriptModule {
.map(|(m, _)| m.module_content_options(chunking_context, async_module_info)) .map(|(m, _)| m.module_content_options(chunking_context, async_module_info))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let module_merging =
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = EcmascriptModuleContent::new_merged( let content = EcmascriptModuleContent::new_merged(
modules.clone(), modules.clone(),
options, options,
ResolvedVc::deref_vec(entry_points.clone()), ResolvedVc::deref_vec(entry_points.clone()),
module_merging,
); );
// Currently, merged modules never include async modules. // Currently, merged modules never include async modules.
......
...@@ -378,17 +378,14 @@ impl EcmascriptChunkPlaceable for EcmascriptModulePartAsset { ...@@ -378,17 +378,14 @@ impl EcmascriptChunkPlaceable for EcmascriptModulePartAsset {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let analyze = self.analyze().await?; let analyze = self.analyze().await?;
let async_module_options = analyze.async_module.module_options(async_module_info); let async_module_options = analyze.async_module.module_options(async_module_info);
let module_merging = let content = self.module_content(chunking_context, async_module_info);
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = self.module_content(chunking_context, module_merging, async_module_info);
Ok(EcmascriptChunkItemContent::new( Ok(EcmascriptChunkItemContent::new(
content, content,
......
...@@ -14,7 +14,7 @@ use turbopack_core::{ ...@@ -14,7 +14,7 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ModuleMergingAnalysis, ScopeHoistingContext, ScopeHoistingContext,
code_gen::{CodeGeneration, CodeGenerationHoistedStmt}, code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
references::esm::base::ReferencedAsset, references::esm::base::ReferencedAsset,
utils::AstSyntaxContext, utils::AstSyntaxContext,
...@@ -111,7 +111,6 @@ impl AsyncModule { ...@@ -111,7 +111,6 @@ impl AsyncModule {
async_module_info: Vc<AsyncModuleInfo>, async_module_info: Vc<AsyncModuleInfo>,
references: Vc<ModuleReferences>, references: Vc<ModuleReferences>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
) -> Result<Vc<AsyncModuleIdents>> { ) -> Result<Vc<AsyncModuleIdents>> {
let async_module_info = async_module_info.await?; let async_module_info = async_module_info.await?;
...@@ -126,12 +125,7 @@ impl AsyncModule { ...@@ -126,12 +125,7 @@ impl AsyncModule {
ReferencedAsset::External(_, ExternalType::EcmaScriptModule) => { ReferencedAsset::External(_, ExternalType::EcmaScriptModule) => {
if self.import_externals { if self.import_externals {
referenced_asset referenced_asset
.prepare_binding( .prepare_binding(chunking_context, None, ScopeHoistingContext::None)
chunking_context,
module_merging,
None,
ScopeHoistingContext::None,
)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await? .await?
...@@ -147,12 +141,7 @@ impl AsyncModule { ...@@ -147,12 +141,7 @@ impl AsyncModule {
.contains(&ResolvedVc::upcast(*placeable)) .contains(&ResolvedVc::upcast(*placeable))
{ {
referenced_asset referenced_asset
.prepare_binding( .prepare_binding(chunking_context, None, ScopeHoistingContext::None)
chunking_context,
module_merging,
None,
ScopeHoistingContext::None,
)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await? .await?
...@@ -225,16 +214,10 @@ impl AsyncModule { ...@@ -225,16 +214,10 @@ impl AsyncModule {
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
references: Vc<ModuleReferences>, references: Vc<ModuleReferences>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
if let Some(async_module_info) = async_module_info { if let Some(async_module_info) = async_module_info {
let async_idents = self let async_idents = self
.get_async_idents( .get_async_idents(async_module_info, references, chunking_context)
async_module_info,
references,
chunking_context,
module_merging,
)
.await?; .await?;
if !async_idents.is_empty() { if !async_idents.is_empty() {
......
...@@ -24,7 +24,6 @@ use turbopack_core::{ ...@@ -24,7 +24,6 @@ use turbopack_core::{
use turbopack_resolve::ecmascript::esm_resolve; use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
ModuleMergingAnalysis,
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder}, ast_path_trie::{AstPathId, AstPathTrie, AstPathTrieBuilder},
code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference}, code_gen::{CodeGen, CodeGeneration, IntoCodeGenReference},
...@@ -249,7 +248,6 @@ impl CollectReferenceCodeGen { ...@@ -249,7 +248,6 @@ impl CollectReferenceCodeGen {
&self, &self,
trie: &AstPathTrie, trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let reference = self.reference.await?; let reference = self.reference.await?;
...@@ -271,13 +269,7 @@ impl CollectReferenceCodeGen { ...@@ -271,13 +269,7 @@ impl CollectReferenceCodeGen {
let export = let export =
match ReferencedAsset::from_resolve_result(self.reference.resolve_reference()).await? { match ReferencedAsset::from_resolve_result(self.reference.resolve_reference()).await? {
ReferencedAsset::Some(module) => { ReferencedAsset::Some(module) => {
generated_export_key( generated_export_key(module, chunking_context, &COLLECT_LIST_EXPORT).await?
module,
chunking_context,
module_merging,
&COLLECT_LIST_EXPORT,
)
.await?
} }
_ => COLLECT_LIST_EXPORT, _ => COLLECT_LIST_EXPORT,
}; };
......
...@@ -39,7 +39,7 @@ use turbopack_core::{ ...@@ -39,7 +39,7 @@ use turbopack_core::{
use turbopack_resolve::ecmascript::esm_resolve; use turbopack_resolve::ecmascript::esm_resolve;
use crate::{ use crate::{
EcmascriptModuleAsset, ModuleMergingAnalysis, ScopeHoistingContext, EcmascriptModuleAsset, ScopeHoistingContext,
analyzer::imports::ImportAnnotations, analyzer::imports::ImportAnnotations,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGeneration, CodeGenerationHoistedStmt}, code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
...@@ -256,24 +256,16 @@ impl ReferencedAsset { ...@@ -256,24 +256,16 @@ impl ReferencedAsset {
pub async fn prepare_binding( pub async fn prepare_binding(
&self, &self,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
export: Option<RcStr>, export: Option<RcStr>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<PreparedBinding> { ) -> Result<PreparedBinding> {
self.prepare_binding_inner( self.prepare_binding_inner(chunking_context, export, scope_hoisting_context, None)
chunking_context, .await
module_merging,
export,
scope_hoisting_context,
None,
)
.await
} }
async fn prepare_binding_inner( async fn prepare_binding_inner(
&self, &self,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
export: Option<RcStr>, export: Option<RcStr>,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>, initial: Option<&ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,
...@@ -330,7 +322,6 @@ impl ReferencedAsset { ...@@ -330,7 +322,6 @@ impl ReferencedAsset {
return Ok( return Ok(
match Box::pin(referenced_asset.prepare_binding_inner( match Box::pin(referenced_asset.prepare_binding_inner(
chunking_context, chunking_context,
module_merging,
imported, imported,
scope_hoisting_context, scope_hoisting_context,
Some(asset), Some(asset),
...@@ -359,23 +350,21 @@ impl ReferencedAsset { ...@@ -359,23 +350,21 @@ impl ReferencedAsset {
} }
} }
let target = if let Some(group) = let target =
*flat_export_group(**asset, chunking_context, module_merging).await? if let Some(group) = *flat_export_group(**asset, chunking_context).await? {
{ group.await?.entry
group.await?.entry } else {
} else { *asset
*asset };
};
let import_source = ImportSource::Module { asset: target }; let import_source = ImportSource::Module { asset: target };
PreparedBinding::Module { PreparedBinding::Module {
ctxt: None, ctxt: None,
// Allocate against the original module, not the shared factory target, // Allocate against the original module, not the shared factory target,
// using the same mapping as the producing module. // using the same mapping as the producing module.
export: match &export { export: match &export {
Some(export) => Some( Some(export) => {
generated_export_key(*asset, chunking_context, module_merging, export) Some(generated_export_key(*asset, chunking_context, export).await?)
.await?, }
),
None => None, None => None,
}, },
import_source, import_source,
...@@ -863,7 +852,6 @@ impl EsmAssetReference { ...@@ -863,7 +852,6 @@ impl EsmAssetReference {
pub(crate) async fn code_generation( pub(crate) async fn code_generation(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
// References a compact re-export registration (`TURBOPACK_ESM_REEXPORT`) already imports // References a compact re-export registration (`TURBOPACK_ESM_REEXPORT`) already imports
// for itself. Emitting them here too would instantiate the module twice. // for itself. Emitting them here too would instantiate the module twice.
...@@ -940,7 +928,6 @@ impl EsmAssetReference { ...@@ -940,7 +928,6 @@ impl EsmAssetReference {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding( .prepare_binding(
chunking_context, chunking_context,
module_merging,
this.export_name this.export_name
.as_ref() .as_ref()
.and_then(ModulePart::get_export) .and_then(ModulePart::get_export)
......
...@@ -10,7 +10,7 @@ use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, Vc}; ...@@ -10,7 +10,7 @@ use turbo_tasks::{FxIndexMap, NonLocalValue, ResolvedVc, Vc};
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ModuleMergingAnalysis, ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie}, ast_path_trie::{AstPathId, AstPathTrie},
code_gen::CodeGeneration, code_gen::CodeGeneration,
create_visitor, create_visitor,
...@@ -92,7 +92,6 @@ impl EsmBindings { ...@@ -92,7 +92,6 @@ impl EsmBindings {
&self, &self,
trie: &AstPathTrie, trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let mut visitors = vec![]; let mut visitors = vec![];
...@@ -139,7 +138,6 @@ impl EsmBindings { ...@@ -139,7 +138,6 @@ impl EsmBindings {
let ident: ImportedIdent = imported_module let ident: ImportedIdent = imported_module
.prepare_binding( .prepare_binding(
chunking_context, chunking_context,
module_merging,
export.clone(), export.clone(),
scope_hoisting_context, scope_hoisting_context,
) )
......
...@@ -26,7 +26,7 @@ use turbopack_core::{ ...@@ -26,7 +26,7 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
EcmascriptModuleAsset, ModuleMergingAnalysis, ScopeHoistingContext, EcmascriptModuleAsset, ScopeHoistingContext,
analyzer::{ analyzer::{
graph::EvalContext, graph::EvalContext,
imports::{Export, ExportRegistrationMode}, imports::{Export, ExportRegistrationMode},
...@@ -649,7 +649,6 @@ impl EsmExports { ...@@ -649,7 +649,6 @@ impl EsmExports {
async fn compact_reference_target( async fn compact_reference_target(
reference: ResolvedVc<Box<dyn ModuleReference>>, reference: ResolvedVc<Box<dyn ModuleReference>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<Option<(NamespaceKey, ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>)>> { ) -> Result<Option<(NamespaceKey, ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>)>> {
let referenced_asset = let referenced_asset =
...@@ -660,12 +659,7 @@ async fn compact_reference_target( ...@@ -660,12 +659,7 @@ async fn compact_reference_target(
import_source: ImportSource::Module { asset }, import_source: ImportSource::Module { asset },
.. ..
}) = referenced_asset }) = referenced_asset
.prepare_binding( .prepare_binding(chunking_context, None, scope_hoisting_context)
chunking_context,
module_merging,
None,
scope_hoisting_context,
)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await? .await?
...@@ -685,7 +679,6 @@ async fn build_compact_reexports( ...@@ -685,7 +679,6 @@ async fn build_compact_reexports(
mode: ExportRegistrationMode, mode: ExportRegistrationMode,
synthetic_references: Option<SyntheticReexportReferences<'_>>, synthetic_references: Option<SyntheticReexportReferences<'_>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<Option<CompactReexports>> { ) -> Result<Option<CompactReexports>> {
let unused_references = chunking_context.unused_references().await?; let unused_references = chunking_context.unused_references().await?;
...@@ -714,7 +707,6 @@ async fn build_compact_reexports( ...@@ -714,7 +707,6 @@ async fn build_compact_reexports(
if let Some((key, asset)) = compact_reference_target( if let Some((key, asset)) = compact_reference_target(
ResolvedVc::upcast(*reference), ResolvedVc::upcast(*reference),
chunking_context, chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
) )
.await? .await?
...@@ -749,7 +741,6 @@ async fn build_compact_reexports( ...@@ -749,7 +741,6 @@ async fn build_compact_reexports(
if let Some((key, _)) = compact_reference_target( if let Some((key, _)) = compact_reference_target(
ResolvedVc::upcast(*reference), ResolvedVc::upcast(*reference),
chunking_context, chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
) )
.await? .await?
...@@ -792,7 +783,6 @@ async fn build_compact_reexports( ...@@ -792,7 +783,6 @@ async fn build_compact_reexports(
}) = referenced_asset }) = referenced_asset
.prepare_binding( .prepare_binding(
chunking_context, chunking_context,
module_merging,
Some(imported_name.clone()), Some(imported_name.clone()),
scope_hoisting_context, scope_hoisting_context,
) )
...@@ -1015,7 +1005,6 @@ impl EsmExports { ...@@ -1015,7 +1005,6 @@ impl EsmExports {
pub(crate) async fn code_generation( pub(crate) async fn code_generation(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
eval_context: &EvalContext, eval_context: &EvalContext,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
...@@ -1082,10 +1071,10 @@ impl EsmExports { ...@@ -1082,10 +1071,10 @@ impl EsmExports {
let mut getters = Vec::new(); let mut getters = Vec::new();
// The keys this module's exports are emitted under. Consumers resolve the same map for this // The keys this module's exports are emitted under. Consumers resolve the same map for this
// module (see `ReferencedAsset::get_ident_inner`), so both sides always agree. // module (see `ReferencedAsset::prepare_binding`), so both sides always agree.
let mangled_names = mangled_export_names(*module, chunking_context, module_merging).await?; let mangled_names = mangled_export_names(*module, chunking_context).await?;
let flat_group = if scope_hoisting_context.module().is_some() { let flat_group = if scope_hoisting_context.module().is_some() {
*flat_export_group(*module, chunking_context, module_merging).await? *flat_export_group(*module, chunking_context).await?
} else { } else {
None None
}; };
...@@ -1114,7 +1103,6 @@ impl EsmExports { ...@@ -1114,7 +1103,6 @@ impl EsmExports {
export_registration_mode, export_registration_mode,
synthetic_references, synthetic_references,
chunking_context, chunking_context,
module_merging,
scope_hoisting_context, scope_hoisting_context,
) )
.await? .await?
...@@ -1189,7 +1177,7 @@ impl EsmExports { ...@@ -1189,7 +1177,7 @@ impl EsmExports {
let referenced_asset = let referenced_asset =
ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?; ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?;
referenced_asset referenced_asset
.prepare_binding(chunking_context, module_merging, Some(name.clone()), scope_hoisting_context) .prepare_binding(chunking_context, Some(name.clone()), scope_hoisting_context)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await? .await?
...@@ -1256,12 +1244,7 @@ impl EsmExports { ...@@ -1256,12 +1244,7 @@ impl EsmExports {
let referenced_asset = let referenced_asset =
ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?; ReferencedAsset::from_resolve_result(esm_ref.resolve_reference()).await?;
referenced_asset referenced_asset
.prepare_binding( .prepare_binding(chunking_context, None, scope_hoisting_context)
chunking_context,
module_merging,
None,
scope_hoisting_context,
)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await? .await?
......
...@@ -27,29 +27,11 @@ use turbo_rcstr::RcStr; ...@@ -27,29 +27,11 @@ use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkingContext, MergeableModuleExposure}, chunk::{ChunkingContext, MergeableModuleExposure},
module_graph::{ module_graph::{binding_usage_info::ModuleExportUsageInfo, merged_modules::MergedModuleGroup},
ModuleGraph, binding_usage_info::ModuleExportUsageInfo, merged_modules::MergedModuleGroup,
},
}; };
use self::table::shorten_to_unique_names; use self::table::shorten_to_unique_names;
use crate::{ use crate::chunk::{EcmascriptChunkPlaceable, EcmascriptExports};
ModuleMergingAnalysis,
chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
};
/// Obtain the existing scope-hoisting analysis at a graph-aware code-generation boundary.
/// Consumers below read only the keyed entries for their target modules.
pub(crate) async fn module_merging_analysis(
module_graph: Vc<ModuleGraph>,
chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<ModuleMergingAnalysis> {
if *chunking_context.is_module_merging_enabled().await? {
Ok(Some(module_graph.merged_modules().await?.groups))
} else {
Ok(None)
}
}
/// A module's export name mapping: original export name -> the key actually used in the output. /// A module's export name mapping: original export name -> the key actually used in the output.
/// ///
...@@ -82,10 +64,12 @@ pub struct OptionFlatExportGroup(pub Option<ResolvedVc<FlatExportGroup>>); ...@@ -82,10 +64,12 @@ pub struct OptionFlatExportGroup(pub Option<ResolvedVc<FlatExportGroup>>);
pub async fn flat_export_group( pub async fn flat_export_group(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
) -> Result<Vc<OptionFlatExportGroup>> { ) -> Result<Vc<OptionFlatExportGroup>> {
if let Some(groups) = module_merging if let Some(group) = chunking_context
&& let Some(group) = groups.get(&ResolvedVc::upcast(module)).await?.as_deref() .merged_modules()
.get(&ResolvedVc::upcast(module))
.await?
.as_deref()
{ {
return Ok(flat_group_exports(**group, chunking_context)); return Ok(flat_group_exports(**group, chunking_context));
} }
...@@ -100,6 +84,8 @@ async fn flat_group_exports( ...@@ -100,6 +84,8 @@ async fn flat_group_exports(
let group = group.await?; let group = group.await?;
let mut exports_to_name = Vec::new(); let mut exports_to_name = Vec::new();
for (index, (module, exposure)) in group.modules.await?.iter().enumerate() { for (index, (module, exposure)) in group.modules.await?.iter().enumerate() {
// A shared export table can only be emitted for ECMAScript modules with statically
// known ESM exports; other module types need their existing runtime representation.
let Some(module) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(*module) let Some(module) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(*module)
else { else {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
...@@ -107,21 +93,29 @@ async fn flat_group_exports( ...@@ -107,21 +93,29 @@ async fn flat_group_exports(
let EcmascriptExports::EsmExports(exports) = *module.get_exports().await? else { let EcmascriptExports::EsmExports(exports) = *module.get_exports().await? else {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
}; };
// Every member must allow renaming. An internal namespace use still needs a distinct
// source-module namespace, which the shared flat table cannot represent.
if !exports.await?.mangle_export_names || *exposure == MergeableModuleExposure::Internal { if !exports.await?.mangle_export_names || *exposure == MergeableModuleExposure::Internal {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
} }
let usage = chunking_context let usage = chunking_context
.module_export_usage(*ResolvedVc::upcast(module)) .module_export_usage(*ResolvedVc::upcast(module))
.await?; .await?;
// Flattening changes both names and namespace identity: it is only safe when all reads
// are known named accesses lowered by codegen, not user-observable namespace reads.
if usage.namespace_object_may_escape if usage.namespace_object_may_escape
|| matches!(*usage.export_usage.await?, ModuleExportUsageInfo::All) || matches!(*usage.export_usage.await?, ModuleExportUsageInfo::All)
{ {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
} }
let expanded = exports.expand_exports(*usage.export_usage).await?; let expanded = exports.expand_exports(*usage.export_usage).await?;
// Runtime re-exports discover their names dynamically, so we cannot allocate collision-free
// keys for them or rewrite every access to the shared table ahead of time.
if !expanded.dynamic_exports.is_empty() { if !expanded.dynamic_exports.is_empty() {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
} }
// Only bindings read from outside the group need table entries. Unexposed members use
// direct local bindings within the merged factory and require no runtime registration.
if *exposure == MergeableModuleExposure::External { if *exposure == MergeableModuleExposure::External {
for name in expanded.exports.keys() { for name in expanded.exports.keys() {
exports_to_name.push(( exports_to_name.push((
...@@ -182,9 +176,8 @@ async fn flat_group_exports( ...@@ -182,9 +176,8 @@ async fn flat_group_exports(
pub async fn mangled_export_names( pub async fn mangled_export_names(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
) -> Result<Vc<MangledExportNames>> { ) -> Result<Vc<MangledExportNames>> {
if let Some(group) = *flat_export_group(*module, chunking_context, module_merging).await? { if let Some(group) = *flat_export_group(*module, chunking_context).await? {
return Ok(Vc::cell(Some( return Ok(Vc::cell(Some(
group.await?.names.get(&module).cloned().unwrap_or_default(), group.await?.names.get(&module).cloned().unwrap_or_default(),
))); )));
...@@ -255,10 +248,9 @@ pub async fn mangled_export_names( ...@@ -255,10 +248,9 @@ pub async fn mangled_export_names(
pub async fn generated_export_key( pub async fn generated_export_key(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
export: &RcStr, export: &RcStr,
) -> Result<RcStr> { ) -> Result<RcStr> {
let names = mangled_export_names(*module, chunking_context, module_merging).await?; let names = mangled_export_names(*module, chunking_context).await?;
Ok(names Ok(names
.as_ref() .as_ref()
.and_then(|names| names.get(export)) .and_then(|names| names.get(export))
......
...@@ -10,7 +10,6 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat}; ...@@ -10,7 +10,6 @@ use turbo_tasks::{NonLocalValue, ResolvedVc, Vc, debug::ValueDebugFormat};
use turbopack_core::chunk::ChunkingContext; use turbopack_core::chunk::ChunkingContext;
use crate::{ use crate::{
ModuleMergingAnalysis,
ast_path_trie::{AstPathId, AstPathTrie}, ast_path_trie::{AstPathId, AstPathTrie},
chunk::{EcmascriptChunkPlaceable, EcmascriptExports}, chunk::{EcmascriptChunkPlaceable, EcmascriptExports},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
...@@ -38,7 +37,6 @@ impl ExportsInfoBinding { ...@@ -38,7 +37,6 @@ impl ExportsInfoBinding {
&self, &self,
_trie: &AstPathTrie, _trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
exports: ResolvedVc<EcmascriptExports>, exports: ResolvedVc<EcmascriptExports>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
...@@ -52,7 +50,7 @@ impl ExportsInfoBinding { ...@@ -52,7 +50,7 @@ impl ExportsInfoBinding {
// whether export mangling is enabled at all — see the `map` closure below for exactly // whether export mangling is enabled at all — see the `map` closure below for exactly
// what each of the three fields means. // what each of the three fields means.
let exports = exports.await?; let exports = exports.await?;
let mangled_names = mangled_export_names(*module, chunking_context, module_merging).await?; let mangled_names = mangled_export_names(*module, chunking_context).await?;
let props = if let EcmascriptExports::EsmExports(exports) = &*exports { let props = if let EcmascriptExports::EsmExports(exports) = &*exports {
exports exports
......
...@@ -23,7 +23,7 @@ use turbopack_core::{ ...@@ -23,7 +23,7 @@ use turbopack_core::{
use turbopack_resolve::ecmascript::{cjs_resolve, esm_resolve}; use turbopack_resolve::ecmascript::{cjs_resolve, esm_resolve};
use crate::{ use crate::{
ModuleMergingAnalysis, ScopeHoistingContext, ScopeHoistingContext,
ast_path_trie::{AstPathId, AstPathTrie}, ast_path_trie::{AstPathId, AstPathTrie},
code_gen::{CodeGen, CodeGeneration}, code_gen::{CodeGen, CodeGeneration},
create_visitor, create_visitor,
...@@ -128,7 +128,6 @@ impl ModuleHotReferenceCodeGen { ...@@ -128,7 +128,6 @@ impl ModuleHotReferenceCodeGen {
&self, &self,
trie: &AstPathTrie, trie: &AstPathTrie,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
let resolved_ids: Vec<ReadRef<PatternMapping>> = self let resolved_ids: Vec<ReadRef<PatternMapping>> = self
...@@ -163,12 +162,7 @@ impl ModuleHotReferenceCodeGen { ...@@ -163,12 +162,7 @@ impl ModuleHotReferenceCodeGen {
match &referenced_asset { match &referenced_asset {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding( .prepare_binding(chunking_context, None, scope_hoisting_context)
chunking_context,
module_merging,
None,
scope_hoisting_context,
)
.await? .await?
.get_ident(chunking_context) .get_ident(chunking_context)
.await?; .await?;
......
...@@ -274,15 +274,12 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleRenameModule { ...@@ -274,15 +274,12 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleRenameModule {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let async_module_options = self.get_async_module().module_options(async_module_info); let async_module_options = self.get_async_module().module_options(async_module_info);
let module_merging = let content = self.module_content(chunking_context, async_module_info);
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = self.module_content(chunking_context, module_merging, async_module_info);
Ok(EcmascriptChunkItemContent::new( Ok(EcmascriptChunkItemContent::new(
content, content,
chunking_context, chunking_context,
......
...@@ -283,14 +283,11 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule { ...@@ -283,14 +283,11 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let module_merging = let content = self.module_content(chunking_context, async_module_info);
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = self.module_content(chunking_context, module_merging, async_module_info);
let async_module_options = self.get_async_module().module_options(async_module_info); let async_module_options = self.get_async_module().module_options(async_module_info);
......
...@@ -200,17 +200,14 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleLocalsModule { ...@@ -200,17 +200,14 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleLocalsModule {
async fn chunk_item_content( async fn chunk_item_content(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let analyze = self.await?.module.analyze().await?; let analyze = self.await?.module.analyze().await?;
let async_module_options = analyze.async_module.module_options(async_module_info); let async_module_options = analyze.async_module.module_options(async_module_info);
let module_merging = let content = self.module_content(chunking_context, async_module_info);
crate::references::esm::mangle::module_merging_analysis(module_graph, chunking_context)
.await?;
let content = self.module_content(chunking_context, module_merging, async_module_info);
Ok(EcmascriptChunkItemContent::new( Ok(EcmascriptChunkItemContent::new(
content, content,
......
...@@ -15,7 +15,7 @@ use turbopack_core::{ ...@@ -15,7 +15,7 @@ use turbopack_core::{
}; };
use crate::{ use crate::{
ModuleMergingAnalysis, ScopeHoistingContext, ScopeHoistingContext,
chunk::EcmascriptChunkPlaceable, chunk::EcmascriptChunkPlaceable,
code_gen::{CodeGeneration, CodeGenerationHoistedStmt}, code_gen::{CodeGeneration, CodeGenerationHoistedStmt},
references::esm::base::{ReferencedAsset, ReferencedAssetIdent}, references::esm::base::{ReferencedAsset, ReferencedAssetIdent},
...@@ -161,7 +161,6 @@ impl EcmascriptModulePartReference { ...@@ -161,7 +161,6 @@ impl EcmascriptModulePartReference {
pub async fn code_generation( pub async fn code_generation(
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
module_merging: ModuleMergingAnalysis,
scope_hoisting_context: ScopeHoistingContext<'_>, scope_hoisting_context: ScopeHoistingContext<'_>,
// Namespace variables a compact re-export registration already imports for itself. // Namespace variables a compact re-export registration already imports for itself.
subsumed_namespaces: &FxHashSet<(String, Option<SyntaxContext>)>, subsumed_namespaces: &FxHashSet<(String, Option<SyntaxContext>)>,
...@@ -207,7 +206,6 @@ impl EcmascriptModulePartReference { ...@@ -207,7 +206,6 @@ impl EcmascriptModulePartReference {
let ident = referenced_asset let ident = referenced_asset
.prepare_binding( .prepare_binding(
chunking_context, chunking_context,
module_merging,
match export_usage { match export_usage {
ExportUsage::Named(export) => Some(export.clone()), ExportUsage::Named(export) => Some(export.clone()),
ExportUsage::PartialNamespaceObject(_) ExportUsage::PartialNamespaceObject(_)
......
...@@ -27,10 +27,7 @@ use crate::{ ...@@ -27,10 +27,7 @@ use crate::{
EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item, EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item,
}, },
embed_js::embed_fs, embed_js::embed_fs,
references::esm::{ references::esm::{generated_export_key, mangle::flat_export_group},
generated_export_key,
mangle::{flat_export_group, module_merging_analysis},
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
utils::{StringifyJs, StringifyModuleId}, utils::{StringifyJs, StringifyModuleId},
}; };
...@@ -295,7 +292,6 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -295,7 +292,6 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
.cell()); .cell());
} }
let module_merging = module_merging_analysis(module_graph, chunking_context).await?;
let create_worker_module = self.create_worker_module().to_resolved().await?; let create_worker_module = self.create_worker_module().to_resolved().await?;
let mut create_worker_target = create_worker_module; let mut create_worker_target = create_worker_module;
// The helper's `default` export is read here as a string, so it has to go through the same // The helper's `default` export is read here as a string, so it has to go through the same
...@@ -307,18 +303,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -307,18 +303,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
Some(placeable) => { Some(placeable) => {
// Resolve the factory identity as well as the key, just like a generated ESM // Resolve the factory identity as well as the key, just like a generated ESM
// import. // import.
if let Some(group) = if let Some(group) = *flat_export_group(*placeable, chunking_context).await? {
*flat_export_group(*placeable, chunking_context, module_merging).await?
{
create_worker_target = ResolvedVc::upcast(group.await?.entry); create_worker_target = ResolvedVc::upcast(group.await?.entry);
} }
generated_export_key( generated_export_key(placeable, chunking_context, &rcstr!("default")).await?
placeable,
chunking_context,
module_merging,
&rcstr!("default"),
)
.await?
} }
None => rcstr!("default"), None => rcstr!("default"),
}; };
......
...@@ -26,6 +26,7 @@ use turbopack_core::{ ...@@ -26,6 +26,7 @@ use turbopack_core::{
ModuleGraph, ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage}, binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::ChunkGroupKey, chunk_group_info::ChunkGroupKey,
merged_modules::MergedModuleGroups,
}, },
output::{OutputAsset, OutputAssets}, output::{OutputAsset, OutputAssets},
}; };
...@@ -136,6 +137,11 @@ impl NodeJsChunkingContextBuilder { ...@@ -136,6 +137,11 @@ impl NodeJsChunkingContextBuilder {
self self
} }
pub fn merged_modules(mut self, merged_modules: ResolvedVc<MergedModuleGroups>) -> Self {
self.chunking_context.merged_modules = Some(merged_modules);
self
}
pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self
where where
T: Upcast<Box<dyn ChunkType>>, T: Upcast<Box<dyn ChunkType>>,
...@@ -240,6 +246,7 @@ pub struct NodeJsChunkingContext { ...@@ -240,6 +246,7 @@ pub struct NodeJsChunkingContext {
export_usage: Option<ResolvedVc<BindingUsageInfo>>, export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen). /// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<UnusedReferences>>, unused_references: Option<ResolvedVc<UnusedReferences>>,
merged_modules: Option<ResolvedVc<MergedModuleGroups>>,
/// The strategy to use for generating source map source uris /// The strategy to use for generating source map source uris
source_map_source_type: SourceMapSourceType, source_map_source_type: SourceMapSourceType,
/// The chunking configs /// The chunking configs
...@@ -295,6 +302,7 @@ impl NodeJsChunkingContext { ...@@ -295,6 +302,7 @@ impl NodeJsChunkingContext {
module_id_strategy: None, module_id_strategy: None,
export_usage: None, export_usage: None,
unused_references: None, unused_references: None,
merged_modules: None,
chunking_configs: Default::default(), chunking_configs: Default::default(),
debug_ids: false, debug_ids: false,
worker_forwarded_globals: vec![], worker_forwarded_globals: vec![],
...@@ -822,6 +830,17 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -822,6 +830,17 @@ impl ChunkingContext for NodeJsChunkingContext {
} }
} }
#[turbo_tasks::function]
fn merged_modules(&self) -> Vc<MergedModuleGroups> {
if self.enable_module_merging
&& let Some(merged_modules) = self.merged_modules
{
*merged_modules
} else {
Vc::cell(Default::default())
}
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(&self) -> Vc<bool> { fn debug_ids_enabled(&self) -> Vc<bool> {
Vc::cell(self.debug_ids) Vc::cell(self.debug_ids)
......
...@@ -645,6 +645,10 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -645,6 +645,10 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
); );
} }
if options.scope_hoisting {
builder = builder.merged_modules(module_graph.merged_modules().await?.groups);
}
if options.remove_unused_imports { if options.remove_unused_imports {
builder = builder.unused_references( builder = builder.unused_references(
binding_usage binding_usage
......
...@@ -556,6 +556,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -556,6 +556,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
builder = builder.single_chunk().await?; builder = builder.single_chunk().await?;
} }
if options.scope_hoisting {
builder = builder.merged_modules(module_graph.merged_modules().await?.groups);
}
if options.remove_unused_imports { if options.remove_unused_imports {
builder = builder.unused_references( builder = builder.unused_references(
binding_usage binding_usage
...@@ -603,6 +607,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -603,6 +607,10 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
.debug_ids(options.enable_debug_ids) .debug_ids(options.enable_debug_ids)
.source_map_source_type(options.source_map_source_type); .source_map_source_type(options.source_map_source_type);
if options.scope_hoisting {
builder = builder.merged_modules(module_graph.merged_modules().await?.groups);
}
if options.remove_unused_imports { if options.remove_unused_imports {
builder = builder.unused_references( builder = builder.unused_references(
binding_usage binding_usage
......
...@@ -227,7 +227,7 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset { ...@@ -227,7 +227,7 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset {
async fn chunk_item_content( async fn chunk_item_content(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
module_graph: Vc<ModuleGraph>, _module_graph: Vc<ModuleGraph>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
_estimated: bool, _estimated: bool,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
...@@ -247,7 +247,6 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset { ...@@ -247,7 +247,6 @@ impl EcmascriptChunkPlaceable for WebAssemblyModuleAsset {
*ResolvedVc::upcast(self), *ResolvedVc::upcast(self),
self.loader(), self.loader(),
*chunking_context, *chunking_context,
module_graph,
async_module_info, async_module_info,
)) ))
} }
......
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