Unverified Commit bb1a5728 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: inner graph tree shaking (#85973)

Alias "unused import removal"

Closes PACK-5782

Performance:

```
* 58fe2e2e377d877f51f91f50770310d2bbf20987 - WIP: enable by default

pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  380.01s user 53.74s system 691% cpu 1:02.76 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  384.99s user 51.00s system 708% cpu 1:01.57 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  381.52s user 46.86s system 711% cpu 1:00.21 total

vs canary:
* f6c2d491 - Turbopack: add task_id_details feature (#84970)

pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  374.87s user 48.47s system 760% cpu 55.662 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  379.18s user 50.27s system 700% cpu 1:01.28 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  370.39s user 45.93s system 726% cpu 57.305 total
pnpm next build --experimental-build-mode=compile > ~/Downloads/log.txt 2>&1  372.70s user 46.24s system 717% cpu 58.364 total
```
parent 4deba0f6
......@@ -430,7 +430,8 @@ pub async fn analyze_module_graphs(module_graphs: Vc<ModuleGraphs>) -> Result<Vc
let mut all_async_edges = FxIndexSet::default();
for &module_graph in module_graphs.await? {
let module_graph = module_graph.read_graphs().await?;
module_graph.traverse_all_edges_unordered(|(parent_node, reference), node| {
module_graph.traverse_all_edges_unordered(|parent, node| {
if let Some((parent_node, reference)) = parent {
all_modules.insert(parent_node);
all_modules.insert(node);
match reference.chunking_type {
......@@ -441,6 +442,7 @@ pub async fn analyze_module_graphs(module_graphs: Vc<ModuleGraphs>) -> Result<Vc
all_edges.insert((parent_node, node));
}
}
}
Ok(())
})?;
}
......
......@@ -59,6 +59,7 @@ use turbopack_core::{
module::Module,
module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry},
},
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
......@@ -856,7 +857,8 @@ impl AppProject {
has_layout_segments: bool,
) -> Result<Vc<BaseAndFullModuleGraph>> {
if *self.project.per_page_module_graph().await? {
let should_trace = self.project.next_mode().await?.is_production();
let next_mode = self.project.next_mode();
let should_trace = next_mode.await?.is_production();
let client_shared_entries = client_shared_entries
.await?
.into_iter()
......@@ -949,10 +951,31 @@ impl AppProject {
);
graphs.push(additional_module_graph);
let full = ModuleGraph::from_graphs(graphs);
let full_with_unused_references =
ModuleGraph::from_graphs(graphs).to_resolved().await?;
let full = if *self
.project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?
{
full_with_unused_references
.without_unused_references(
*compute_binding_usage_info(full_with_unused_references, true)
.resolve_strongly_consistent()
.await?,
)
.to_resolved()
.await?
} else {
full_with_unused_references
};
Ok(BaseAndFullModuleGraph {
base: base.to_resolved().await?,
full: full.to_resolved().await?,
full_with_unused_references,
full,
}
.cell())
}
......
......@@ -24,7 +24,7 @@ use turbopack_core::{
context::AssetContext,
issue::{Issue, IssueExt, IssueSeverity, IssueStage, OptionStyledString, StyledString},
module::Module,
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraph},
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraphWithBindingUsage},
};
use crate::{
......@@ -35,8 +35,9 @@ use crate::{
#[turbo_tasks::value]
pub struct NextDynamicGraph {
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
/// list of NextDynamicEntryModules
data: ResolvedVc<DynamicImportEntries>,
}
......@@ -51,12 +52,12 @@ impl NextDynamicGraphs {
graphs: ResolvedVc<ModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
let graphs_ref = &graphs.await?.graphs;
let graphs_ref = &graphs.await?;
let next_dynamic = async {
graphs_ref
.iter()
.iter_graphs()
.map(|graph| {
NextDynamicGraph::new_with_entries(**graph, is_single_page).to_resolved()
NextDynamicGraph::new_with_entries(graph, is_single_page).to_resolved()
})
.try_join()
.await
......@@ -129,10 +130,10 @@ pub struct DynamicImportEntriesWithImporter(
impl NextDynamicGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
) -> Result<Vc<Self>> {
let mapped = map_next_dynamic(*graph);
let mapped = map_next_dynamic(*graph.graph);
Ok(NextDynamicGraph {
is_single_page,
......@@ -150,7 +151,7 @@ impl NextDynamicGraph {
let span = tracing::info_span!("collect next/dynamic imports for endpoint");
async move {
let data = &*self.data.await?;
let graph = self.graph.await?;
let graph = self.graph.read().await?;
#[derive(Clone, PartialEq, Eq)]
enum VisitState {
......@@ -159,20 +160,20 @@ impl NextDynamicGraph {
}
let entries = if !self.is_single_page {
if !graph.has_entry_module(entry) {
if !graph.graphs.first().unwrap().has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(Vc::cell(vec![]));
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
Either::Right(graph.graphs.first().unwrap().entry_modules())
};
let mut result = vec![];
// module -> the client reference entry (if any)
let mut state_map = FxHashMap::default();
graph.read().traverse_edges_from_entries_dfs(
graph.traverse_edges_from_entries_dfs(
entries,
&mut (),
|parent_info, node, _| {
......@@ -231,8 +232,9 @@ impl NextDynamicGraph {
#[turbo_tasks::value]
pub struct ServerActionsGraph {
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
/// (Layer, RSC or Browser module) -> list of actions
data: ResolvedVc<AllModuleActions>,
}
......@@ -247,12 +249,12 @@ impl ServerActionsGraphs {
graphs: ResolvedVc<ModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
let graphs_ref = &graphs.await?.graphs;
let graphs_ref = &graphs.await?;
let server_actions = async {
graphs_ref
.iter()
.iter_graphs()
.map(|graph| {
ServerActionsGraph::new_with_entries(**graph, is_single_page).to_resolved()
ServerActionsGraph::new_with_entries(graph, is_single_page).to_resolved()
})
.try_join()
.await
......@@ -314,10 +316,10 @@ impl ServerActionsGraphs {
impl ServerActionsGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
) -> Result<Vc<Self>> {
let mapped = map_server_actions(*graph);
let mapped = map_server_actions(*graph.graph);
Ok(ServerActionsGraph {
is_single_page,
......@@ -341,15 +343,15 @@ impl ServerActionsGraph {
Cow::Borrowed(data)
} else {
// The graph contains the whole app, traverse and collect all reachable imports.
let graph = self.graph.await?;
let graph = self.graph.read().await?;
if !graph.has_entry_module(entry) {
if !graph.graphs.first().unwrap().has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(Vc::cell(Default::default()));
}
let mut result = FxIndexMap::default();
graph.read().traverse_nodes_from_entries_dfs(
graph.traverse_nodes_from_entries_dfs(
vec![entry],
&mut result,
|node, result| {
......@@ -405,7 +407,8 @@ impl ServerActionsGraph {
#[turbo_tasks::value]
pub struct ClientReferencesGraph {
is_single_page: bool,
graph: ResolvedVc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
/// List of client references (modules that entries into the client graph)
data: ResolvedVc<ClientReferenceData>,
}
......@@ -420,12 +423,12 @@ impl ClientReferencesGraphs {
graphs: ResolvedVc<ModuleGraph>,
is_single_page: bool,
) -> Result<Vc<Self>> {
let graphs_ref = &graphs.await?.graphs;
let graphs_ref = &graphs.await?;
let client_references = async {
graphs_ref
.iter()
.iter_graphs()
.map(|graph| {
ClientReferencesGraph::new_with_entries(**graph, is_single_page).to_resolved()
ClientReferencesGraph::new_with_entries(graph, is_single_page).to_resolved()
})
.try_join()
.await
......@@ -512,10 +515,10 @@ impl ClientReferencesGraphs {
impl ClientReferencesGraph {
#[turbo_tasks::function]
pub async fn new_with_entries(
graph: ResolvedVc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
) -> Result<Vc<Self>> {
let mapped = map_client_references(*graph);
let mapped = map_client_references(*graph.graph);
Ok(Self {
is_single_page,
......@@ -533,16 +536,16 @@ impl ClientReferencesGraph {
let span = tracing::info_span!("collect client references for endpoint");
async move {
let data = &*self.data.await?;
let graph = self.graph.await?;
let graph = self.graph.read().await?;
let entries = if !self.is_single_page {
if !graph.has_entry_module(entry) {
if !graph.graphs.first().unwrap().has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(ClientReferenceGraphResult::default().cell());
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
Either::Right(graph.graphs.first().unwrap().entry_modules())
};
// Because we care about 'evaluation order' we need to collect client references in the
......@@ -552,7 +555,6 @@ impl ClientReferencesGraph {
let mut server_components = FxIndexSet::default();
let graph = graph.read();
// Perform a DFS traversal to find all server components included by this page.
graph.traverse_nodes_from_entries_dfs(
entries,
......@@ -761,27 +763,27 @@ struct ModuleNameMap(pub FxModuleNameMap);
#[tracing::instrument(level = "info", name = "validate pages css imports", skip_all)]
#[turbo_tasks::function]
async fn validate_pages_css_imports_individual(
graph: Vc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
is_single_page: bool,
entry: Vc<Box<dyn Module>>,
app_module: ResolvedVc<Box<dyn Module>>,
) -> Result<()> {
let graph = graph.await?;
let graph = graph.read().await?;
let entry = entry.to_resolved().await?;
let entries = if !is_single_page {
if !graph.has_entry_module(entry) {
if !graph.graphs.first().unwrap().has_entry_module(entry) {
// the graph doesn't contain the entry, e.g. for the additional module graph
return Ok(());
}
Either::Left(std::iter::once(entry))
} else {
Either::Right(graph.entry_modules())
Either::Right(graph.graphs.first().unwrap().entry_modules())
};
let mut candidates = vec![];
graph.read().traverse_edges_from_entries_dfs(
graph.traverse_edges_from_entries_dfs(
entries,
&mut (),
|parent_info, node, _| {
......@@ -799,7 +801,8 @@ async fn validate_pages_css_imports_individual(
return Ok(GraphTraversalAction::Continue);
}
// If the module being imported isn't a global css module, there is nothing to validate.
// If the module being imported isn't a global css module, there is nothing to
// validate.
let module_is_global_css =
ResolvedVc::try_downcast_type::<CssModuleAsset>(module).is_some();
......@@ -811,14 +814,15 @@ async fn validate_pages_css_imports_individual(
ResolvedVc::try_downcast_type::<ModuleCssAsset>(parent_module).is_some()
|| ResolvedVc::try_downcast_type::<CssModuleAsset>(parent_module).is_some();
// We also always allow .module css/scss/sass files to import global css files as well.
// We also always allow .module css/scss/sass files to import global css files as
// well.
if parent_is_css_module {
return Ok(GraphTraversalAction::Continue);
}
// If all of the above invariants have been checked, we look to see if the parent module
// is the same as the app module. If it isn't we know it isn't a valid place
// to import global css.
// If all of the above invariants have been checked, we look to see if the parent
// module is the same as the app module. If it isn't we know it
// isn't a valid place to import global css.
if parent_module != app_module {
candidates.push(CssGlobalImportIssue::new(parent_module, module))
}
......@@ -862,11 +866,11 @@ pub async fn validate_pages_css_imports(
entry: Vc<Box<dyn Module>>,
app_module: Vc<Box<dyn Module>>,
) -> Result<()> {
let graphs = &graph.await?.graphs;
let graphs = &graph.await?;
graphs
.iter()
.iter_graphs()
.map(|graph| {
validate_pages_css_imports_individual(**graph, is_single_page, entry, app_module)
validate_pages_css_imports_individual(graph, is_single_page, entry, app_module)
.as_side_effect()
})
.try_join()
......
......@@ -54,6 +54,7 @@ use turbopack_core::{
module::Module,
module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry},
},
output::{OptionOutputAsset, OutputAsset, OutputAssets},
......@@ -726,7 +727,8 @@ impl PageEndpoint {
let project = this.pages_project.project();
if *project.per_page_module_graph().await? {
let should_trace = project.next_mode().await?.is_production();
let next_mode = project.next_mode();
let should_trace = next_mode.await?.is_production();
let ssr_chunk_module = self.internal_ssr_chunk_module().await?;
// Implements layout segment optimization to compute a graph "chain" for document, app,
// page
......@@ -755,7 +757,21 @@ impl PageEndpoint {
);
graphs.push(graph);
Ok(ModuleGraph::from_graphs(graphs))
let mut graph = ModuleGraph::from_graphs(graphs);
if *project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?
{
graph = graph.without_unused_references(
*compute_binding_usage_info(graph.to_resolved().await?, true)
.resolve_strongly_consistent()
.await?,
);
}
Ok(graph)
} else {
Ok(*project.whole_app_module_graphs().await?.full)
}
......
......@@ -59,8 +59,10 @@ use turbopack_core::{
module::Module,
module_graph::{
GraphEntries, ModuleGraph, SingleModuleGraph, VisitedModules,
binding_usage_info::{
BindingUsageInfo, OptionBindingUsageInfo, compute_binding_usage_info,
},
chunk_group_info::ChunkGroupEntry,
export_usage::{OptionExportUsageInfo, compute_export_usage_info},
},
output::{
ExpandOutputAssetsInput, ExpandedOutputAssets, OutputAsset, OutputAssets,
......@@ -1165,6 +1167,7 @@ impl Project {
environment: self.client_compile_time_info().environment(),
module_id_strategy: self.module_ids(),
export_usage: self.export_usage(),
unused_references: self.unused_references(),
minify: self.next_config().turbo_minify(self.next_mode()),
source_maps: self.next_config().client_source_maps(self.next_mode()),
no_mangling: self.no_mangling(),
......@@ -1190,6 +1193,7 @@ impl Project {
environment: self.server_compile_time_info().environment(),
module_id_strategy: self.module_ids(),
export_usage: self.export_usage(),
unused_references: self.unused_references(),
minify: self.next_config().turbo_minify(self.next_mode()),
source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(),
......@@ -1221,6 +1225,7 @@ impl Project {
environment: self.edge_compile_time_info().environment(),
module_id_strategy: self.module_ids(),
export_usage: self.export_usage(),
unused_references: self.unused_references(),
turbo_minify: self.next_config().turbo_minify(self.next_mode()),
turbo_source_maps: self.next_config().server_source_maps(),
no_mangling: self.no_mangling(),
......@@ -1925,20 +1930,50 @@ impl Project {
}
}
/// Compute the used exports and unused imports for each module.
#[turbo_tasks::function]
async fn binding_usage_info(self: Vc<Self>) -> Result<Vc<BindingUsageInfo>> {
let remove_unused_imports = *self
.next_config()
.turbopack_remove_unused_imports(self.next_mode())
.await?;
let module_graphs = self.whole_app_module_graphs().await?;
Ok(*compute_binding_usage_info(
module_graphs.full_with_unused_references,
remove_unused_imports,
)
// As a performance optimization, we resolve strongly consistently
.resolve_strongly_consistent()
.await?)
}
/// Compute the used exports for each module.
#[turbo_tasks::function]
pub async fn export_usage(self: Vc<Self>) -> Result<Vc<OptionExportUsageInfo>> {
pub async fn export_usage(self: Vc<Self>) -> Result<Vc<OptionBindingUsageInfo>> {
if *self
.next_config()
.turbopack_remove_unused_exports(self.next_mode())
.await?
{
let module_graphs = self.whole_app_module_graphs().await?;
Ok(Vc::cell(Some(
compute_export_usage_info(module_graphs.full)
// As a performance optimization, we resolve strongly consistently
.resolve_strongly_consistent()
.await?,
self.binding_usage_info().to_resolved().await?,
)))
} else {
Ok(Vc::cell(None))
}
}
/// Compute the unused references that were removed (inner graph tree shaking).
#[turbo_tasks::function]
pub async fn unused_references(self: Vc<Self>) -> Result<Vc<OptionBindingUsageInfo>> {
if *self
.next_config()
.turbopack_remove_unused_imports(self.next_mode())
.await?
{
Ok(Vc::cell(Some(
self.binding_usage_info().to_resolved().await?,
)))
} else {
Ok(Vc::cell(None))
......@@ -1963,12 +1998,31 @@ async fn whole_app_module_graph_operation(
) -> Result<Vc<BaseAndFullModuleGraph>> {
mark_root();
let should_trace = project.next_mode().await?.is_production();
let next_mode = project.next_mode();
let should_trace = next_mode.await?.is_production();
let base_single_module_graph =
SingleModuleGraph::new_with_entries(project.get_all_entries(), should_trace);
let base_visited_modules = VisitedModules::from_graph(base_single_module_graph);
let base = ModuleGraph::from_single_graph(base_single_module_graph);
let turbopack_remove_unused_imports = *project
.next_config()
.turbopack_remove_unused_imports(next_mode)
.await?;
let base = if turbopack_remove_unused_imports {
// TODO suboptimal that we do compute_binding_usage_info twice (once for the base graph
// and later for the full graph)
base.without_unused_references(
*compute_binding_usage_info(base.to_resolved().await?, true)
.resolve_strongly_consistent()
.await?,
)
} else {
base
};
let additional_entries = project.get_all_additional_entries(base);
let additional_module_graph = SingleModuleGraph::new_with_entries_visited(
......@@ -1977,17 +2031,40 @@ async fn whole_app_module_graph_operation(
should_trace,
);
let full = ModuleGraph::from_graphs(vec![base_single_module_graph, additional_module_graph]);
let full_with_unused_references =
ModuleGraph::from_graphs(vec![base_single_module_graph, additional_module_graph])
.to_resolved()
.await?;
let full = if turbopack_remove_unused_imports {
full_with_unused_references
.without_unused_references(
*compute_binding_usage_info(full_with_unused_references, true)
.resolve_strongly_consistent()
.await?,
)
.to_resolved()
.await?
} else {
full_with_unused_references
};
Ok(BaseAndFullModuleGraph {
base: base.to_resolved().await?,
full: full.to_resolved().await?,
full_with_unused_references,
full,
}
.cell())
}
#[turbo_tasks::value(shared)]
pub struct BaseAndFullModuleGraph {
/// The base module graph generated from the entry points.
pub base: ResolvedVc<ModuleGraph>,
/// The base graph plus any modules that were generated from additional entries (for which the
/// base graph is needed).
pub full_with_unused_references: ResolvedVc<ModuleGraph>,
/// `full_with_unused_references` but with unused references removed.
pub full: ResolvedVc<ModuleGraph>,
}
......
......@@ -58,12 +58,14 @@ where
let asset_reasons = {
let module_graph = module_graph.read_graphs().await?;
let mut edges = vec![];
module_graph.traverse_all_edges_unordered(|(parent_node, r), current| {
module_graph.traverse_all_edges_unordered(|parent, current| {
if let Some((parent_node, r)) = parent {
edges.push((
parent_node,
RcStr::from(format!("{}: {}", r.chunking_type, r.export)),
RcStr::from(format!("{}: {}", r.chunking_type, r.binding_usage.export)),
current,
));
}
Ok(())
})?;
......
......@@ -25,7 +25,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{BrowserEnvironment, Environment, ExecutionEnvironment},
free_var_references,
module_graph::export_usage::OptionExportUsageInfo,
module_graph::binding_usage_info::OptionBindingUsageInfo,
resolve::{parse::Request, pattern::Pattern},
};
use turbopack_ecmascript::{AnalyzeMode, TypeofWindow, chunk::EcmascriptChunkType};
......@@ -416,7 +416,8 @@ pub struct ClientChunkingContextOptions {
pub asset_prefix: Vc<RcStr>,
pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>,
pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>,
......@@ -439,6 +440,7 @@ pub async fn get_client_chunking_context(
environment,
module_id_strategy,
export_usage,
unused_references,
minify,
source_maps,
no_mangling,
......@@ -473,6 +475,7 @@ pub async fn get_client_chunking_context(
.asset_base_path(Some(asset_prefix))
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?)
......
......@@ -15,7 +15,7 @@ use turbopack_core::{
context::AssetContext,
ident::AssetIdent,
module::Module,
module_graph::{ModuleGraph, export_usage::ModuleExportUsageInfo},
module_graph::{ModuleGraph, binding_usage_info::ModuleExportUsageInfo},
output::OutputAssetsReference,
reference::{ModuleReference, ModuleReferences},
reference_type::ReferenceType,
......
......@@ -192,9 +192,9 @@ impl Visit<FindServerEntriesNode> for FindServerEntries {
let referenced_modules = referenced_modules
.iter()
.flat_map(|(chunking_type, _, modules)| match chunking_type {
.flat_map(|(_, resolved)| match resolved.chunking_type {
ChunkingType::Traced => None,
_ => Some(modules.iter()),
_ => Some(resolved.modules.iter()),
})
.flatten()
.map(async |module| {
......
......@@ -901,6 +901,8 @@ pub struct ExperimentalConfig {
// Whether to enable the global-not-found convention
global_not_found: Option<bool>,
/// Defaults to false in development mode, true in production mode.
turbopack_remove_unused_imports: Option<bool>,
/// Defaults to false in development mode, true in production mode.
turbopack_remove_unused_exports: Option<bool>,
/// Devtool option for the segment explorer.
devtool_segment_explorer: Option<bool>,
......@@ -1754,6 +1756,27 @@ impl NextConfig {
.cell()
}
#[turbo_tasks::function]
pub async fn turbopack_remove_unused_imports(
self: Vc<Self>,
mode: Vc<NextMode>,
) -> Result<Vc<bool>> {
let remove_unused_imports = self
.await?
.experimental
.turbopack_remove_unused_imports
.unwrap_or(matches!(*mode.await?, NextMode::Build));
if remove_unused_imports && !*self.turbopack_remove_unused_exports(mode).await? {
bail!(
"`experimental.turbopackRemoveUnusedImports` cannot be enabled without also \
enabling `experimental.turbopackRemoveUnusedExports`"
);
}
Ok(Vc::cell(remove_unused_imports))
}
#[turbo_tasks::function]
pub async fn turbopack_remove_unused_exports(&self, mode: Vc<NextMode>) -> Result<Vc<bool>> {
Ok(Vc::cell(
......
......@@ -13,7 +13,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment, NodeJsVersion},
free_var_references,
module_graph::export_usage::OptionExportUsageInfo,
module_graph::binding_usage_info::OptionBindingUsageInfo,
};
use turbopack_ecmascript::chunk::EcmascriptChunkType;
use turbopack_node::execution_context::ExecutionContext;
......@@ -203,7 +203,8 @@ pub struct EdgeChunkingContextOptions {
pub output_root_to_root_path: Vc<RcStr>,
pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>,
pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub turbo_minify: Vc<bool>,
pub turbo_source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>,
......@@ -226,6 +227,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
environment,
module_id_strategy,
export_usage,
unused_references,
turbo_minify,
turbo_source_maps,
no_mangling,
......@@ -258,6 +260,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
.source_maps(*turbo_source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.nested_async_availability(*nested_async_chunking.await?);
if !next_mode.is_development() {
......@@ -295,6 +298,7 @@ pub async fn get_edge_chunking_context(
environment,
module_id_strategy,
export_usage,
unused_references,
turbo_minify,
turbo_source_maps,
no_mangling,
......@@ -333,6 +337,7 @@ pub async fn get_edge_chunking_context(
.source_maps(*turbo_source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.nested_async_availability(*nested_async_chunking.await?);
if !next_mode.is_development() {
......
......@@ -23,7 +23,7 @@ use turbopack_core::{
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReferences},
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, NodeJsVersion},
free_var_references,
module_graph::export_usage::OptionExportUsageInfo,
module_graph::binding_usage_info::OptionBindingUsageInfo,
target::CompileTarget,
};
use turbopack_ecmascript::{
......@@ -991,7 +991,8 @@ pub struct ServerChunkingContextOptions {
pub node_root_to_root_path: RcStr,
pub environment: Vc<Environment>,
pub module_id_strategy: Vc<Box<dyn ModuleIdStrategy>>,
pub export_usage: Vc<OptionExportUsageInfo>,
pub export_usage: Vc<OptionBindingUsageInfo>,
pub unused_references: Vc<OptionBindingUsageInfo>,
pub minify: Vc<bool>,
pub source_maps: Vc<SourceMapsType>,
pub no_mangling: Vc<bool>,
......@@ -1015,6 +1016,7 @@ pub async fn get_server_chunking_context_with_client_assets(
environment,
module_id_strategy,
export_usage,
unused_references,
minify,
source_maps,
no_mangling,
......@@ -1051,6 +1053,7 @@ pub async fn get_server_chunking_context_with_client_assets(
.source_maps(*source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?);
......@@ -1097,6 +1100,7 @@ pub async fn get_server_chunking_context(
environment,
module_id_strategy,
export_usage,
unused_references,
minify,
source_maps,
no_mangling,
......@@ -1133,6 +1137,7 @@ pub async fn get_server_chunking_context(
.source_maps(*source_maps.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?)
.export_usage(*export_usage.await?)
.unused_references(*unused_references.await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?);
......
......@@ -300,6 +300,7 @@ export const experimentalSchema = {
turbopackSourceMaps: z.boolean().optional(),
turbopackInputSourceMaps: z.boolean().optional(),
turbopackTreeShaking: z.boolean().optional(),
turbopackRemoveUnusedImports: z.boolean().optional(),
turbopackRemoveUnusedExports: z.boolean().optional(),
turbopackScopeHoisting: z.boolean().optional(),
turbopackClientSideNestedAsyncChunking: z.boolean().optional(),
......
......@@ -452,6 +452,11 @@ export interface ExperimentalConfig {
*/
turbopackTreeShaking?: boolean
/**
* Enable removing unused imports for turbopack dev server and build.
*/
turbopackRemoveUnusedImports?: boolean
/**
* Enable removing unused exports for turbopack dev server and build.
*/
......
export default function Root({ children }) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
import { Server } from '../library/index.js'
export default function page() {
return <Server />
}
export function Bar() {
async function create() {
'use server'
console.log('Action called')
}
return <button onClick={create}>Bar</button>
}
'use client'
export function Foo() {
return 'Client'
}
export function Server() {
return 'This is Server'
}
import { Foo } from './client.js'
// This is unused
export function Client() {
return <Foo />
}
import { Bar } from './action.js'
// This is unused
export function Action() {
return <Bar />
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('reference-tree-shaking', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('Should apply removeUnusedImports tree shaking to client and server references', async () => {
const res = await next.fetch('/')
expect(await res.text()).toContain('This is Server')
// Only Turbopack applies inner graph tree shaking here
if (process.env.IS_TURBOPACK_TEST) {
const serverReferences = await next.readFile(
'.next/server/server-reference-manifest.json'
)
expect(serverReferences).not.toContain('library/action.js')
const clientReferences = await next.readFile(
'.next/server/app/page_client-reference-manifest.js'
)
expect(clientReferences).not.toContain('library/client.js')
}
})
})
import React from 'react'
export default function Layout({ children }) {
return (
<html>
<head>
<title>My App</title>
</head>
<body>{children}</body>
</html>
)
}
'use client'
import { used } from '../library'
export default function Page() {
return <h1>My Page{used()}</h1>
}
export function a() {
return `This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
This is some big library. This is some big library. This is some big library. This is some big library. This is some big library. This is some big library.
`
}
module.exports.b = function b() {
return `This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library. This is a big library.
`
}
import { b } from './b'
export function unused() {
return b()
}
export function used() {
return 'used'
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
describe('remove-unused-imports', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (skipped) {
return
}
it('should remove unused imports', async () => {
const browser = await next.browser('/')
let scripts = await browser.elementsByCss('script[src]')
expect(
(
await Promise.all(
scripts.map(async (el) => {
const src = await el.getAttribute('src')
const res = await next.fetch(src)
const code = await res.text()
if (code.includes('This is a big library.')) {
return src
}
return false
})
)
).filter((item) => item)
).toBeEmpty()
})
})
......@@ -23,10 +23,11 @@ use turbopack_core::{
module::Module,
module_graph::{
ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsage},
},
output::{OutputAsset, OutputAssets},
reference::ModuleReference,
};
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
......@@ -168,11 +169,19 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<ExportUsageInfo>>) -> Self {
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<BindingUsageInfo>>) -> Self {
self.chunking_context.export_usage = export_usage;
self
}
pub fn unused_references(
mut self,
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
) -> Self {
self.chunking_context.unused_references = unused_references;
self
}
pub fn debug_ids(mut self, debug_ids: bool) -> Self {
self.chunking_context.debug_ids = debug_ids;
self
......@@ -291,7 +300,9 @@ pub struct BrowserChunkingContext {
/// The module id strategy to use
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
/// The module export usage info, if available.
export_usage: Option<ResolvedVc<ExportUsageInfo>>,
export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
/// The chunking configs
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
/// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`)
......@@ -340,6 +351,7 @@ impl BrowserChunkingContext {
manifest_chunks: false,
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None,
unused_references: None,
chunking_configs: Default::default(),
should_use_absolute_url_references: false,
},
......@@ -866,12 +878,24 @@ impl ChunkingContext for BrowserChunkingContext {
if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module).await?)
} else {
// In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all())
}
}
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: ResolvedVc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>> {
if let Some(unused_references) = self.await?.unused_references {
Ok(Vc::cell(
unused_references.await?.is_reference_unused(&reference),
))
} else {
Ok(Vc::cell(false))
}
}
#[turbo_tasks::function]
async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.debug_ids))
......
......@@ -33,8 +33,8 @@ use turbopack_core::{
module::Module,
module_graph::{
ModuleGraph,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry},
export_usage::compute_export_usage_info,
},
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType},
......@@ -305,7 +305,7 @@ async fn build_internal(
.instrument(tracing::info_span!("resolve entries"))
.await?;
let module_graph = ModuleGraph::from_modules(
let mut module_graph = ModuleGraph::from_modules(
Vc::cell(vec![ChunkGroupEntry::Entry(entries.clone())]),
false,
);
......@@ -314,9 +314,10 @@ async fn build_internal(
.to_resolved()
.await?,
);
let export_usage = compute_export_usage_info(module_graph.to_resolved().await?)
let binding_usage = compute_binding_usage_info(module_graph.to_resolved().await?, true)
.resolve_strongly_consistent()
.await?;
module_graph = module_graph.without_unused_references(*binding_usage);
let chunking_context: Vc<Box<dyn ChunkingContext>> = match target {
Target::Browser => {
......@@ -342,7 +343,8 @@ async fn build_internal(
)
.source_maps(source_maps_type)
.module_id_strategy(module_id_strategy)
.export_usage(Some(export_usage))
.export_usage(Some(binding_usage))
.unused_references(Some(binding_usage))
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.minify_type(minify_type);
......@@ -391,7 +393,8 @@ async fn build_internal(
)
.source_maps(source_maps_type)
.module_id_strategy(module_id_strategy)
.export_usage(Some(export_usage))
.export_usage(Some(binding_usage))
.unused_references(Some(binding_usage))
.minify_type(minify_type);
match *node_env.await? {
......
......@@ -14,13 +14,14 @@ use crate::{
ident::AssetIdent,
module::Module,
module_graph::{
ModuleGraph, chunk_group_info::ChunkGroup, export_usage::ModuleExportUsage,
ModuleGraph, binding_usage_info::ModuleExportUsage, chunk_group_info::ChunkGroup,
module_batches::BatchingConfig,
},
output::{
ExpandOutputAssetsInput, OutputAsset, OutputAssets, OutputAssetsReferences,
OutputAssetsWithReferenced, expand_output_assets,
},
reference::ModuleReference,
};
#[derive(
......@@ -439,6 +440,12 @@ pub trait ChunkingContext {
module: Vc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>>;
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: Vc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>>;
/// Returns whether debug IDs are enabled for this chunking context.
#[turbo_tasks::function]
fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
......
......@@ -46,7 +46,7 @@ use crate::{
},
output::{OutputAssets, OutputAssetsReference},
reference::ModuleReference,
resolve::ExportUsage,
resolve::BindingUsage,
};
/// A module id, which can be a number or string
......@@ -416,8 +416,8 @@ pub trait ChunkableModuleReference: ModuleReference + ValueToString {
}
#[turbo_tasks::function]
fn export_usage(self: Vc<Self>) -> Vc<ExportUsage> {
ExportUsage::all()
fn binding_usage(self: Vc<Self>) -> Vc<BindingUsage> {
BindingUsage::all()
}
}
......
......@@ -4,7 +4,7 @@ use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc};
use crate::{
module::{Module, Modules},
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraph},
module_graph::{GraphTraversalAction, ModuleGraph, SingleModuleGraphWithBindingUsage},
};
#[turbo_tasks::value(transparent)]
......@@ -37,25 +37,29 @@ impl AsyncModulesInfo {
#[turbo_tasks::function(operation)]
pub async fn compute_async_module_info(
graph: ResolvedVc<ModuleGraph>,
graphs: ResolvedVc<ModuleGraph>,
) -> Result<Vc<AsyncModulesInfo>> {
// Layout segment optimization, we can individually compute the async modules for each graph.
let mut result: Vc<AsyncModulesInfo> = Vc::cell(Default::default());
for g in &graph.await?.graphs {
result = compute_async_module_info_single(**g, result);
let graphs = graphs.await?;
for graph in graphs.iter_graphs() {
result = compute_async_module_info_single(graph, result);
}
Ok(result)
}
#[turbo_tasks::function]
async fn compute_async_module_info_single(
graph: Vc<SingleModuleGraph>,
graph: SingleModuleGraphWithBindingUsage,
parent_async_modules: Vc<AsyncModulesInfo>,
) -> Result<Vc<AsyncModulesInfo>> {
let parent_async_modules = parent_async_modules.await?;
let graph = graph.await?;
let graph = graph.read().await?;
let self_async_modules = graph
.graphs
.first()
.unwrap()
.iter_nodes()
.map(async |node| Ok((node, *node.is_self_async().await?)))
.try_join()
......@@ -73,9 +77,8 @@ async fn compute_async_module_info_single(
// modules in the SCC is async.
let mut async_modules = self_async_modules;
let graph_ref = graph.read();
graph_ref.traverse_edges_from_entries_dfs(
graph.entry_modules(),
graph.traverse_edges_from_entries_dfs(
graph.graphs.first().unwrap().entry_modules(),
&mut (),
|_, _, _| Ok(GraphTraversalAction::Continue),
|parent_info, module, _| {
......@@ -91,7 +94,7 @@ async fn compute_async_module_info_single(
},
)?;
graph_ref.traverse_cycles(
graph.traverse_cycles(
|ref_data| ref_data.chunking_type.is_inherit_async(),
|cycle| {
if cycle.iter().any(|node| async_modules.contains(node)) {
......
use std::collections::hash_map::Entry;
use anyhow::{Result, bail};
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{
module::Module,
module_graph::{GraphEdgeIndex, GraphTraversalAction, ModuleGraph},
reference::ModuleReference,
resolve::{ExportUsage, ImportUsage},
};
#[turbo_tasks::value]
#[derive(Clone, Default, Debug)]
pub struct BindingUsageInfo {
unused_references: FxHashSet<ResolvedVc<Box<dyn ModuleReference>>>,
#[turbo_tasks(trace_ignore)]
unused_references_edges: FxHashSet<GraphEdgeIndex>,
used_exports: FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsageInfo>,
export_circuit_breakers: FxHashSet<ResolvedVc<Box<dyn Module>>>,
}
#[turbo_tasks::value(transparent)]
pub struct OptionBindingUsageInfo(Option<ResolvedVc<BindingUsageInfo>>);
#[turbo_tasks::value]
pub struct ModuleExportUsage {
pub export_usage: ResolvedVc<ModuleExportUsageInfo>,
// Whether this module exists in an import cycle and has been selected to break the cycle.
pub is_circuit_breaker: bool,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsage {
#[turbo_tasks::function]
pub async fn all() -> Result<Vc<Self>> {
Ok(Self {
export_usage: ModuleExportUsageInfo::all().to_resolved().await?,
is_circuit_breaker: true,
}
.cell())
}
}
impl BindingUsageInfo {
pub fn is_reference_unused_edge(&self, edge: &GraphEdgeIndex) -> bool {
self.unused_references_edges.contains(edge)
}
pub fn is_reference_unused(&self, reference: &ResolvedVc<Box<dyn ModuleReference>>) -> bool {
self.unused_references.contains(reference)
}
pub async fn used_exports(
&self,
module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>> {
let is_circuit_breaker = self.export_circuit_breakers.contains(&module);
let Some(exports) = self.used_exports.get(&module) else {
// There are some module that are codegened, but not referenced in the module graph,
let ident = module.ident_string().await?;
if ident.contains(".wasm_.loader.mjs") || ident.contains("/__nextjs-internal-proxy.") {
// Both the turbopack-wasm `ModuleChunkItem` and `EcmascriptClientReferenceModule`
// do `self.slightly_different_module().as_chunk_item()`, so the
// module that codegen sees isn't actually in the module graph.
// TODO fix these cases
return Ok(ModuleExportUsage::all());
}
bail!("export usage not found for module: {ident:?}");
};
Ok(ModuleExportUsage {
export_usage: exports.clone().resolved_cell(),
is_circuit_breaker,
}
.cell())
}
}
#[turbo_tasks::function(operation)]
pub async fn compute_binding_usage_info(
graph: ResolvedVc<ModuleGraph>,
remove_unused_imports: bool,
) -> Result<Vc<BindingUsageInfo>> {
let span_outer = tracing::info_span!(
"compute bindung usage info",
visit_count = tracing::field::Empty,
unused_reference_count = tracing::field::Empty
);
let span = span_outer.clone();
async move {
let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default();
#[cfg(debug_assertions)]
let mut debug_unused_references_name = FxHashSet::<(
ResolvedVc<Box<dyn Module>>,
ExportUsage,
ResolvedVc<Box<dyn Module>>,
)>::default();
let mut unused_references_edges = FxHashSet::default();
let mut unused_references = FxHashSet::default();
if graph.await?.binding_usage.is_some() {
// If the graph already has binding usage info, return it directly. This is
// unfortunately easy to do with
// ```
// fn get_module_graph(){
// let graph = ....;
// let graph = graph.without_unused_references(compute_binding_usage_info(graph));
// return graph
// }
//
// compute_binding_usage_info(get_module_graph())
// ```
panic!(
"don't run compute_binding_usage_info on a graph after calling \
without_unused_references"
);
}
let graph = graph.read_graphs().await?;
let entries = graph.graphs.iter().flat_map(|g| g.entry_modules());
let visit_count = graph.traverse_edges_fixed_point_with_priority(
entries.map(|m| (m, 0)),
&mut (),
|parent, target, _| {
// Entries are always used
let Some((parent, ref_data, edge)) = parent else {
used_exports.insert(target, ModuleExportUsageInfo::All);
return Ok(GraphTraversalAction::Continue);
};
if remove_unused_imports {
// If the current edge is an unused import, skip it
match &ref_data.binding_usage.import {
ImportUsage::Exports(exports) => {
let source_used_exports = used_exports.get(&parent).unwrap();
if exports
.iter()
.all(|e| !source_used_exports.is_export_used(e))
{
#[cfg(debug_assertions)]
debug_unused_references_name.insert((
parent,
ref_data.binding_usage.export.clone(),
target,
));
unused_references_edges.insert(edge);
unused_references.insert(ref_data.reference);
return Ok(GraphTraversalAction::Skip);
} else {
#[cfg(debug_assertions)]
debug_unused_references_name.remove(&(
parent,
ref_data.binding_usage.export.clone(),
target,
));
unused_references_edges.remove(&edge);
unused_references.remove(&ref_data.reference);
// Continue, add export
}
}
ImportUsage::SideEffects => {
#[cfg(debug_assertions)]
debug_unused_references_name.remove(&(
parent,
ref_data.binding_usage.export.clone(),
target,
));
unused_references_edges.remove(&edge);
unused_references.remove(&ref_data.reference);
// Continue, has to always be included
}
}
}
let entry = used_exports.entry(target);
let is_first_visit = matches!(entry, Entry::Vacant(_));
if entry.or_default().add(&ref_data.binding_usage.export) || is_first_visit {
// First visit, or the used exports changed. This can cause more imports to get
// used downstream.
Ok(GraphTraversalAction::Continue)
} else {
Ok(GraphTraversalAction::Skip)
}
},
|_, _| Ok(0),
)?;
// Compute cycles and select modules to be 'circuit breakers'
// A circuit breaker module will need to eagerly export lazy getters for its exports to
// break an evaluation cycle all other modules can export values after defining them
let mut export_circuit_breakers = FxHashSet::default();
graph.traverse_cycles(
|e| e.chunking_type.is_parallel(),
|cycle| {
// To break cycles we need to ensure that no importing module can observe a
// partially populated exports object.
// We could compute this based on the module graph via a DFS from each entry point
// to the cycle. Whatever node is hit first is an entry point to the cycle.
// (scope hoisting does something similar) and then we would only need to
// mark 'entry' modules (basically the targets of back edges in the export graph) as
// circuit breakers. For now we just mark everything on the theory that cycles are
// rare. For vercel-site on 8/22/2025 there were 106 cycles covering 800 modules
// (or 1.2% of all modules). So with this analysis we could potentially drop 80% of
// the cycle breaker modules.
export_circuit_breakers.extend(cycle.iter().map(|n| **n));
Ok(())
},
)?;
span.record("visit_count", visit_count);
span.record("unused_reference_count", unused_references.len());
#[cfg(debug_assertions)]
{
use once_cell::sync::Lazy;
static PRINT_UNUSED_REFERENCES: Lazy<bool> = Lazy::new(|| {
std::env::var_os("TURBOPACK_PRINT_UNUSED_REFERENCES")
.is_some_and(|v| v == "1" || v == "true")
});
if *PRINT_UNUSED_REFERENCES {
use turbo_tasks::TryJoinIterExt;
println!(
"unused references: {:#?}",
debug_unused_references_name
.iter()
.map(async |(s, e, t)| Ok((
s.ident_string().await?,
e,
t.ident_string().await?,
)))
.try_join()
.await?
);
}
}
Ok(BindingUsageInfo {
unused_references,
unused_references_edges,
used_exports,
export_circuit_breakers,
}
.cell())
}
.instrument(span_outer)
.await
}
#[turbo_tasks::value]
#[derive(Default, Clone, Debug)]
pub enum ModuleExportUsageInfo {
/// Only the side effects are needed, no exports is used.
#[default]
Evaluation,
Exports(AutoSet<RcStr>),
All,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsageInfo {
#[turbo_tasks::function]
pub fn all() -> Vc<Self> {
ModuleExportUsageInfo::All.cell()
}
}
impl ModuleExportUsageInfo {
/// Merge the given usage into self. Returns true if Self changed.
pub fn add(&mut self, usage: &ExportUsage) -> bool {
match (&mut *self, usage) {
(Self::All, _) => false,
(_, ExportUsage::All) => {
*self = Self::All;
true
}
(Self::Evaluation, ExportUsage::Named(name)) => {
// Promote evaluation to something more specific
*self = Self::Exports(AutoSet::from_iter([name.clone()]));
true
}
(Self::Exports(l), ExportUsage::Named(r)) => {
// Merge exports
l.insert(r.clone())
}
(_, ExportUsage::Evaluation) => false,
}
}
pub fn is_export_used(&self, export: &RcStr) -> bool {
match self {
Self::All => true,
Self::Evaluation => false,
Self::Exports(exports) => exports.contains(export),
}
}
}
......@@ -507,7 +507,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk
})
.collect::<Result<Vec<_>>>()?,
&mut module_chunk_groups,
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>,
module_chunk_groups: &mut FxHashMap<
ResolvedVc<Box<dyn Module>>,
......@@ -518,7 +518,7 @@ pub async fn compute_chunk_group_info(graph: &ModuleGraphRef) -> Result<Vc<Chunk
Inherit(ResolvedVc<Box<dyn Module>>),
ChunkGroup(It),
}
let chunk_groups = if let Some((parent, ref_data)) = parent_info {
let chunk_groups = if let Some((parent, ref_data, _)) = parent_info {
match &ref_data.chunking_type {
ChunkingType::Parallel { .. } => ChunkGroupInheritance::Inherit(parent),
ChunkingType::Async => ChunkGroupInheritance::ChunkGroup(Either::Left(
......
//! Intermediate tree shaking that uses global information but not good as the full tree shaking.
use anyhow::Result;
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet};
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use crate::{module::Module, module_graph::ModuleGraph, resolve::ExportUsage};
#[turbo_tasks::function(operation)]
pub async fn compute_export_usage_info(
graph: ResolvedVc<ModuleGraph>,
) -> Result<Vc<ExportUsageInfo>> {
let mut used_exports = FxHashMap::<_, ModuleExportUsageInfo>::default();
let graph = graph.read_graphs().await?;
graph.traverse_all_edges_unordered(|(_, ref_data), target| {
let e = used_exports.entry(target).or_default();
e.add(&ref_data.export);
Ok(())
})?;
// Compute cycles and select modules to be 'circuit breakers'
// A circuit breaker module will need to eagerly export lazy getters for its exports to break an
// evaluation cycle all other modules can export values after defining them
let mut circuit_breakers = FxHashSet::default();
graph.traverse_cycles(
|e| e.chunking_type.is_parallel(),
|cycle| {
// To break cycles we need to ensure that no importing module can observe a
// partially populated exports object.
// We could compute this based on the module graph via a DFS from each entry point
// to the cycle. Whatever node is hit first is an entry point to the cycle.
// (scope hoisting does something similar) and then we would only need to
// mark 'entry' modules (basically the targets of back edges in the export graph) as
// circuit breakers. For now we just mark everything on the theory that cycles are
// rare. For vercel-site on 8/22/2025 there were 106 cycles covering 800 modules
// (or 1.2% of all modules). So with this analysis we could potentially drop 80% of
// the cycle breaker modules.
circuit_breakers.extend(cycle.iter().map(|n| **n));
Ok(())
},
)?;
Ok(ExportUsageInfo {
used_exports,
circuit_breakers,
}
.cell())
}
#[turbo_tasks::value(transparent)]
pub struct OptionExportUsageInfo(Option<ResolvedVc<ExportUsageInfo>>);
#[turbo_tasks::value]
pub struct ExportUsageInfo {
used_exports: FxHashMap<ResolvedVc<Box<dyn Module>>, ModuleExportUsageInfo>,
circuit_breakers: FxHashSet<ResolvedVc<Box<dyn Module>>>,
}
#[turbo_tasks::value(shared)]
pub struct ModuleExportUsage {
pub export_usage: ResolvedVc<ModuleExportUsageInfo>,
// Whether this module exists in an import cycle and has been selected to break the cycle.
pub is_circuit_breaker: bool,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsage {
#[turbo_tasks::function]
pub async fn all() -> Result<Vc<Self>> {
Ok(Self {
export_usage: ModuleExportUsageInfo::all().to_resolved().await?,
is_circuit_breaker: true,
}
.cell())
}
}
impl ExportUsageInfo {
pub async fn used_exports(
&self,
module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<ModuleExportUsage>> {
let is_circuit_breaker = self.circuit_breakers.contains(&module);
let export_usage = if let Some(exports) = self.used_exports.get(&module) {
exports.clone().resolved_cell()
} else {
// We exclude template files from tree shaking because they are entrypoints to the
// module graph.
ModuleExportUsageInfo::all().to_resolved().await?
};
Ok(ModuleExportUsage {
export_usage,
is_circuit_breaker,
}
.cell())
}
}
#[turbo_tasks::value]
#[derive(Default, Clone)]
pub enum ModuleExportUsageInfo {
/// Only the side effects are needed, no exports is used.
#[default]
Evaluation,
Exports(AutoSet<RcStr>),
All,
}
#[turbo_tasks::value_impl]
impl ModuleExportUsageInfo {
#[turbo_tasks::function]
pub fn all() -> Vc<Self> {
ModuleExportUsageInfo::All.cell()
}
}
impl ModuleExportUsageInfo {
fn add(&mut self, usage: &ExportUsage) {
match (&mut *self, usage) {
(Self::All, _) => {}
(_, ExportUsage::All) => {
*self = Self::All;
}
(Self::Evaluation, ExportUsage::Named(name)) => {
// Promote evaluation to something more specific
*self = Self::Exports(AutoSet::from_iter([name.clone()]));
}
(Self::Exports(l), ExportUsage::Named(r)) => {
// Merge exports
l.insert(r.clone());
}
(_, ExportUsage::Evaluation) => {
// Ignore evaluation
}
}
}
pub fn is_export_used(&self, export: &RcStr) -> bool {
match self {
Self::All => true,
Self::Evaluation => false,
Self::Exports(exports) => exports.contains(export),
}
}
}
......@@ -148,13 +148,14 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
.map(|e| Ok((*e, -*module_depth.get(e).context("Module depth not found")?)))
.collect::<Result<Vec<_>>>()?,
&mut (),
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
|parent_info: Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, _)>,
node: ResolvedVc<Box<dyn Module>>,
_|
-> Result<GraphTraversalAction> {
// On the down traversal, establish which edges are mergeable and set the list
// indices.
let (parent_module, hoisted) = parent_info.map_or((None, false), |(node, ty)| {
let (parent_module, hoisted) =
parent_info.map_or((None, false), |(node, ty, _)| {
(
Some(node),
match &ty.chunking_type {
......@@ -490,7 +491,9 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
// necessarily needed for browser),
exposed_modules_imported.insert(module);
}
if parent_info.is_some_and(|(_, r)| matches!(r.export, ExportUsage::All)) {
if parent_info
.is_some_and(|(_, r)| matches!(r.binding_usage.export, ExportUsage::All))
{
// This module needs to be exposed:
// - namespace import from another group
exposed_modules_namespace.insert(module);
......
......@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level, Span};
use turbo_rcstr::RcStr;
use turbo_tasks::{
CollectiblesSource, FxIndexMap, NonLocalValue, ReadRef, ResolvedVc, TryJoinIterExt,
CollectiblesSource, FxIndexMap, NonLocalValue, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt,
ValueToString, Vc,
debug::ValueDebugFormat,
graph::{AdjacencyMap, GraphTraversal, Visit, VisitControlFlow},
......@@ -29,19 +29,20 @@ use crate::{
module::Module,
module_graph::{
async_module_info::{AsyncModulesInfo, compute_async_module_info},
binding_usage_info::BindingUsageInfo,
chunk_group_info::{ChunkGroupEntry, ChunkGroupInfo, compute_chunk_group_info},
merged_modules::{MergedModuleInfo, compute_merged_modules},
module_batches::{ModuleBatchesGraph, compute_module_batches},
style_groups::{StyleGroups, StyleGroupsConfig, compute_style_groups},
traced_di_graph::TracedDiGraph,
},
reference::primary_chunkable_referenced_modules,
resolve::ExportUsage,
reference::{ModuleReference, primary_chunkable_referenced_modules},
resolve::BindingUsage,
};
pub mod async_module_info;
pub mod binding_usage_info;
pub mod chunk_group_info;
pub mod export_usage;
pub mod merged_modules;
pub mod module_batch;
pub(crate) mod module_batches;
......@@ -60,14 +61,36 @@ pub struct GraphNodeIndex {
node_idx: NodeIndex,
}
impl GraphNodeIndex {
#[inline(always)]
fn graph_idx(&self) -> usize {
self.graph_idx as usize
fn new(graph_idx: u32, node_idx: NodeIndex) -> Self {
Self {
graph_idx,
node_idx,
}
}
}
unsafe impl NonLocalValue for GraphNodeIndex {}
#[derive(
Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash, PartialEq, Serialize, Deserialize, TraceRawVcs,
)]
pub struct GraphEdgeIndex {
#[turbo_tasks(trace_ignore)]
graph_idx: u32,
#[turbo_tasks(trace_ignore)]
edge_idx: EdgeIndex,
}
impl GraphEdgeIndex {
fn new(graph_idx: u32, edge_idx: EdgeIndex) -> Self {
Self {
graph_idx,
edge_idx,
}
}
}
unsafe impl NonLocalValue for GraphEdgeIndex {}
#[turbo_tasks::value]
#[derive(Clone, Debug)]
pub struct VisitedModules {
......@@ -204,7 +227,8 @@ pub struct SingleModuleGraph {
)]
pub struct RefData {
pub chunking_type: ChunkingType,
pub export: ExportUsage,
pub binding_usage: BindingUsage,
pub reference: ResolvedVc<Box<dyn ModuleReference>>,
}
impl SingleModuleGraph {
......@@ -223,14 +247,15 @@ impl SingleModuleGraph {
.map(|e| async move {
Ok(SingleModuleGraphBuilderEdge {
to: SingleModuleGraphBuilderNode::new_module(emit_spans, e).await?,
export: ExportUsage::All,
binding_usage: BindingUsage::default(),
reference: None,
})
})
.try_join()
.await?;
let (children_nodes_iter, visited_nodes) = AdjacencyMap::new()
.skip_duplicates_with_key(|node: &(SingleModuleGraphBuilderNode, ExportUsage)| &node.0)
.skip_duplicates_with_key(|node: &(SingleModuleGraphBuilderNode, _, _)| &node.0)
.visit(
root_edges,
SingleModuleGraphBuilder {
......@@ -257,13 +282,16 @@ impl SingleModuleGraph {
FxHashMap::with_capacity_and_hasher(node_count, Default::default());
{
let _span = tracing::info_span!("build module graph").entered();
for (parent, (current, export)) in children_nodes_iter.into_breadth_first_edges() {
for (parent, (current, reference, binding_usage)) in
children_nodes_iter.into_breadth_first_edges()
{
let parent_edge = match parent.map(|v| v.0) {
Some(SingleModuleGraphBuilderNode::Module { module, .. }) => Some((
*modules.get(&module).unwrap(),
RefData {
chunking_type: COMMON_CHUNKING_TYPE,
export,
binding_usage,
reference: reference.unwrap(),
},
)),
Some(SingleModuleGraphBuilderNode::ChunkableReference { .. }) => {
......@@ -404,17 +432,12 @@ impl SingleModuleGraph {
self.graph.node_references()
}
pub fn read(self: &ReadRef<SingleModuleGraph>) -> ModuleGraphRef {
ModuleGraphRef {
graphs: vec![self.clone()],
skip_visited_module_children: true,
}
}
fn traverse_cycles<'l>(
&'l self,
edge_filter: impl Fn(&'l RefData) -> bool,
mut visit_cycle: impl FnMut(&[&'l ResolvedVc<Box<dyn Module>>]) -> Result<()>,
graph_idx: u32,
binding_usage: &'l Option<ReadRef<BindingUsageInfo>>,
) -> Result<()> {
// see https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
// but iteratively instead of recursively
......@@ -454,6 +477,13 @@ impl SingleModuleGraph {
visit_stack.push(VisitStep::AfterVisit(node));
let mut neighbors = self.graph.neighbors(node).detach();
while let Some((edge, succ)) = neighbors.next(&self.graph) {
if binding_usage.as_ref().is_some_and(|binding_usage| {
binding_usage
.is_reference_unused_edge(&GraphEdgeIndex::new(graph_idx, edge))
}) {
continue;
}
let edge_weight = self.graph.edge_weight(edge).unwrap();
if !edge_filter(edge_weight) {
continue;
......@@ -724,19 +754,26 @@ impl ImportTracer for ModuleGraphImportTracer {
#[derive(Clone, Default)]
pub struct ModuleGraph {
pub graphs: Vec<ResolvedVc<SingleModuleGraph>>,
pub binding_usage: Option<ResolvedVc<BindingUsageInfo>>,
}
#[turbo_tasks::value_impl]
impl ModuleGraph {
#[turbo_tasks::function]
pub fn from_graphs(graphs: Vec<ResolvedVc<SingleModuleGraph>>) -> Vc<Self> {
Self { graphs }.cell()
Self {
graphs,
binding_usage: None,
}
.cell()
}
#[turbo_tasks::function]
pub fn from_single_graph(graph: ResolvedVc<SingleModuleGraph>) -> Vc<Self> {
Self {
graphs: vec![graph],
binding_usage: None,
}
.cell()
}
......@@ -804,16 +841,13 @@ impl ModuleGraph {
module: ResolvedVc<Box<dyn Module>>,
) -> Result<Vc<AsyncModuleInfo>> {
let graph_ref = self.read_graphs().await?;
let graphs = &graph_ref.graphs;
let async_modules_info = self.async_module_info().await?;
let entry = graph_ref.get_entry(module)?;
let referenced_modules = iter_graphs_neighbors_rev(graphs, entry)
let referenced_modules = graph_ref
.iter_graphs_neighbors_rev(entry)
.filter(|(edge_idx, _)| {
let ty = graphs[entry.graph_idx()]
.graph
.edge_weight(*edge_idx)
.unwrap();
let ty = graph_ref.get_edge(*edge_idx).unwrap();
ty.chunking_type.is_inherit_async()
})
.map(|(_, child_idx)| anyhow::Ok(graph_ref.get_node(child_idx)?.module()))
......@@ -826,13 +860,76 @@ impl ModuleGraph {
Ok(AsyncModuleInfo::new(referenced_modules))
}
/// Analyze the module graph and remove unused references (by determining the used exports and
/// removing unused imports).
///
/// In particular, this removes ChunkableModuleReference-s that list only unused exports in the
/// `import_usage()`
#[turbo_tasks::function]
pub async fn without_unused_references(
self: ResolvedVc<Self>,
binding_usage: ResolvedVc<BindingUsageInfo>,
) -> Result<Vc<Self>> {
Ok(Self {
graphs: self.await?.graphs.clone(),
binding_usage: Some(binding_usage),
}
.cell())
}
}
impl ModuleGraph {
/// Reads the ModuleGraph into a ModuleGraphRef, awaiting all underlying graphs.
pub async fn read_graphs(self: Vc<ModuleGraph>) -> Result<ModuleGraphRef> {
let this = self.await?;
Ok(ModuleGraphRef {
graphs: self.await?.graphs.iter().try_join().await?,
graphs: this.graphs.iter().try_join().await?,
skip_visited_module_children: false,
graph_idx_override: None,
binding_usage: if let Some(binding_usage) = this.binding_usage {
Some(binding_usage.await?)
} else {
None
},
})
}
/// Returns the underlying graphs as a list, to be used for individual graph traversals.
pub fn iter_graphs(
self: &ModuleGraph,
) -> impl Iterator<Item = SingleModuleGraphWithBindingUsage> {
self.graphs
.iter()
.enumerate()
.map(|(graph_idx, graph)| SingleModuleGraphWithBindingUsage {
graph: *graph,
graph_idx: graph_idx as u32,
binding_usage: self.binding_usage,
})
}
}
#[derive(
Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, TaskInput, TraceRawVcs, NonLocalValue,
)]
pub struct SingleModuleGraphWithBindingUsage {
pub graph: ResolvedVc<SingleModuleGraph>,
pub graph_idx: u32,
pub binding_usage: Option<ResolvedVc<BindingUsageInfo>>,
}
impl SingleModuleGraphWithBindingUsage {
pub async fn read(self: &SingleModuleGraphWithBindingUsage) -> Result<ModuleGraphRef> {
Ok(ModuleGraphRef {
graphs: vec![self.graph.await?],
skip_visited_module_children: true,
graph_idx_override: Some(self.graph_idx),
binding_usage: if let Some(binding_usage) = &self.binding_usage {
Some(binding_usage.await?)
} else {
None
},
})
}
}
......@@ -844,17 +941,25 @@ pub struct ModuleGraphRef {
// Whether to simply ignore SingleModuleGraphNode::VisitedModule during traversals. For single
// module graph usecases, this is what you want. For the whole graph, there should be an error.
skip_visited_module_children: bool,
pub graph_idx_override: Option<u32>,
pub binding_usage: Option<ReadRef<BindingUsageInfo>>,
}
impl ModuleGraphRef {
fn get_entry(&self, entry: ResolvedVc<Box<dyn Module>>) -> Result<GraphNodeIndex> {
if self.graph_idx_override.is_some() {
debug_assert_eq!(self.graphs.len(), 1,);
}
let Some(idx) = self
.graphs
.iter()
.enumerate()
.find_map(|(graph_idx, graph)| {
graph.modules.get(&entry).map(|node_idx| GraphNodeIndex {
graph_idx: u32::try_from(graph_idx).unwrap(),
graph_idx: self.graph_idx_override.unwrap_or(graph_idx as u32),
node_idx: *node_idx,
})
})
......@@ -868,11 +973,27 @@ impl ModuleGraphRef {
self.graphs.iter().flat_map(|g| g.entries.iter().cloned())
}
fn get_node(&self, entry: GraphNodeIndex) -> Result<&SingleModuleGraphNode> {
let graph = &self.graphs[entry.graph_idx()];
fn get_graph(&self, graph_idx: u32) -> &ReadRef<SingleModuleGraph> {
if self.graph_idx_override.is_some() {
self.graphs.first().unwrap()
} else {
&self.graphs[graph_idx as usize]
}
}
fn get_node(&self, node: GraphNodeIndex) -> Result<&SingleModuleGraphNode> {
let graph = self.get_graph(node.graph_idx);
graph
.graph
.node_weight(entry.node_idx)
.node_weight(node.node_idx)
.context("Expected graph node")
}
fn get_edge(&self, edge: GraphEdgeIndex) -> Result<&RefData> {
let graph = self.get_graph(edge.graph_idx);
graph
.graph
.edge_weight(edge.edge_idx)
.context("Expected graph node")
}
......@@ -884,6 +1005,39 @@ impl ModuleGraphRef {
}
}
/// Iterate the edges of a node REVERSED!
fn iter_graphs_neighbors_rev<'a>(
&'a self,
node: GraphNodeIndex,
) -> impl Iterator<Item = (GraphEdgeIndex, GraphNodeIndex)> + 'a {
let graph = &*self.get_graph(node.graph_idx).graph;
if cfg!(debug_assertions) {
let node_weight = graph.node_weight(node.node_idx).unwrap();
if let SingleModuleGraphNode::VisitedModule { .. } = node_weight {
panic!("iter_graphs_neighbors_rev called on VisitedModule node");
}
}
let mut walker = graph.neighbors(node.node_idx).detach();
std::iter::from_fn(move || {
while let Some((edge_idx, succ_idx)) = walker.next(graph) {
let edge_idx = GraphEdgeIndex::new(node.graph_idx, edge_idx);
if self
.binding_usage
.as_ref()
.is_some_and(|binding_usage| binding_usage.is_reference_unused_edge(&edge_idx))
{
// Don't just return None here, that would end the iterator
continue;
}
return Some((edge_idx, GraphNodeIndex::new(node.graph_idx, succ_idx)));
}
None
})
}
/// Returns a map of all modules in the graphs to their identifiers.
/// This is primarily useful for debugging.
pub async fn get_ids(&self) -> Result<FxHashMap<ResolvedVc<Box<dyn Module>>, ReadRef<RcStr>>> {
......@@ -913,8 +1067,6 @@ impl ModuleGraphRef {
visit_preorder: impl Fn(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<GraphTraversalAction>,
mut visit_postorder: impl FnMut(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<()>,
) -> Result<()> {
let graphs = &self.graphs;
let entries = entries.into_iter().collect::<Vec<_>>();
enum Pass {
......@@ -946,7 +1098,7 @@ impl ModuleGraphRef {
{
let current = current_node.target_idx().unwrap_or(current);
stack.extend(
iter_graphs_neighbors_rev(graphs, current)
self.iter_graphs_neighbors_rev(current)
.map(|(_, child)| (Pass::ExpandAndVisit, child)),
);
}
......@@ -975,8 +1127,6 @@ impl ModuleGraphRef {
ResolvedVc<Box<dyn Module>>,
) -> Result<GraphTraversalAction>,
) -> Result<()> {
let graphs = &self.graphs;
let mut queue = VecDeque::from(
entries
.into_iter()
......@@ -990,12 +1140,10 @@ impl ModuleGraphRef {
while let Some(node) = queue.pop_front() {
if visited.insert(node) {
let node_weight = self.get_node(node)?;
let graph = &graphs[node.graph_idx()].graph;
for (edge, succ) in iter_graphs_neighbors_rev(graphs, node) {
for (edge, succ) in self.iter_graphs_neighbors_rev(node) {
let succ_weight = self.get_node(succ)?;
let edge_weight = graph.edge_weight(edge).unwrap();
let action = visitor(
Some((node_weight.module(), edge_weight)),
Some((node_weight.module(), self.get_edge(edge)?)),
succ_weight.module(),
)?;
if !self.should_visit_node(succ_weight) {
......@@ -1030,8 +1178,6 @@ impl ModuleGraphRef {
ResolvedVc<Box<dyn Module>>,
) -> GraphTraversalAction,
) -> Result<()> {
let graphs = &self.graphs;
let mut stack = entries
.into_iter()
.map(|e| self.get_entry(e))
......@@ -1043,12 +1189,10 @@ impl ModuleGraphRef {
while let Some(node) = stack.pop() {
if visited.insert(node) {
let node_weight = self.get_node(node)?;
let graph = &graphs[node.graph_idx()].graph;
for (edge, succ) in iter_graphs_neighbors_rev(graphs, node) {
for (edge, succ) in self.iter_graphs_neighbors_rev(node) {
let succ_weight = self.get_node(succ)?;
let edge_weight = graph.edge_weight(edge).unwrap();
let action = visitor(
Some((node_weight.module(), edge_weight)),
Some((node_weight.module(), self.get_edge(edge)?)),
succ_weight.module(),
);
if !self.should_visit_node(succ_weight) {
......@@ -1076,19 +1220,21 @@ impl ModuleGraphRef {
pub fn traverse_all_edges_unordered(
&self,
mut visitor: impl FnMut(
(ResolvedVc<Box<dyn Module>>, &'_ RefData),
Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
ResolvedVc<Box<dyn Module>>,
) -> Result<()>,
) -> Result<()> {
for graph in &self.graphs {
let graph = &graph.graph;
for edge in graph.edge_references() {
let source = graph.node_weight(edge.source()).unwrap().module();
let target = graph.node_weight(edge.target()).unwrap().module();
visitor((source, edge.weight()), target)?;
}
}
Ok(())
let entries = self.graphs.iter().flat_map(|g| g.entry_modules());
self.traverse_edges_from_entries_dfs(
entries,
&mut (),
|parent, target, _| {
visitor(parent, target)?;
Ok(GraphTraversalAction::Continue)
},
|_, _, _| Ok(()),
)
}
/// Traverses all reachable edges in dfs order. The preorder visitor can be used to
......@@ -1124,8 +1270,6 @@ impl ModuleGraphRef {
&mut S,
) -> Result<()>,
) -> Result<()> {
let graphs = &self.graphs;
let entries = entries.into_iter().collect::<Vec<_>>();
enum Pass {
......@@ -1133,8 +1277,11 @@ impl ModuleGraphRef {
ExpandAndVisit,
}
#[allow(clippy::type_complexity)] // This is a temporary internal structure
let mut stack: Vec<(Pass, Option<(GraphNodeIndex, EdgeIndex)>, GraphNodeIndex)> =
Vec::with_capacity(entries.len());
let mut stack: Vec<(
Pass,
Option<(GraphNodeIndex, GraphEdgeIndex)>,
GraphNodeIndex,
)> = Vec::with_capacity(entries.len());
for entry in entries.into_iter().rev() {
stack.push((Pass::ExpandAndVisit, None, self.get_entry(entry)?));
}
......@@ -1143,10 +1290,7 @@ impl ModuleGraphRef {
let parent_arg = match parent {
Some((parent_node, parent_edge)) => Some((
self.get_node(parent_node)?.module(),
graphs[parent_node.graph_idx()]
.graph
.edge_weight(parent_edge)
.unwrap(),
self.get_edge(parent_edge)?,
)),
None => None,
};
......@@ -1166,7 +1310,7 @@ impl ModuleGraphRef {
&& self.should_visit_node(current_node)
{
let current = current_node.target_idx().unwrap_or(current);
stack.extend(iter_graphs_neighbors_rev(graphs, current).map(
stack.extend(self.iter_graphs_neighbors_rev(current).map(
|(edge, child)| (Pass::ExpandAndVisit, Some((current, edge)), child),
));
}
......@@ -1184,8 +1328,13 @@ impl ModuleGraphRef {
edge_filter: impl Fn(&RefData) -> bool,
mut visit_cycle: impl FnMut(&[&ResolvedVc<Box<dyn Module>>]) -> Result<()>,
) -> Result<()> {
for graph in &self.graphs {
graph.traverse_cycles(&edge_filter, &mut visit_cycle)?;
for (graph_idx, graph) in self.graphs.iter().enumerate() {
graph.traverse_cycles(
&edge_filter,
&mut visit_cycle,
graph_idx as u32,
&self.binding_usage,
)?;
}
Ok(())
}
......@@ -1216,13 +1365,12 @@ impl ModuleGraphRef {
entries: impl IntoIterator<Item = (ResolvedVc<Box<dyn Module>>, P)>,
state: &mut S,
mut visit: impl FnMut(
Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData)>,
Option<(ResolvedVc<Box<dyn Module>>, &'_ RefData, GraphEdgeIndex)>,
ResolvedVc<Box<dyn Module>>,
&mut S,
) -> Result<GraphTraversalAction>,
priority: impl Fn(ResolvedVc<Box<dyn Module>>, &mut S) -> Result<P>,
) -> Result<usize> {
let graphs = &self.graphs;
if self.skip_visited_module_children {
panic!(
"traverse_edges_fixed_point_with_priority musn't be called on individual graphs"
......@@ -1275,13 +1423,11 @@ impl ModuleGraphRef {
visit_count += 1;
let graph = &graphs[node.graph_idx()].graph;
for (edge, succ) in iter_graphs_neighbors_rev(graphs, node) {
for (edge, succ) in self.iter_graphs_neighbors_rev(node) {
let succ_weight = self.get_node(succ)?;
let edge_weight = graph.edge_weight(edge).unwrap();
let action = visit(
Some((node_weight.module(), edge_weight)),
Some((node_weight.module(), self.get_edge(edge)?, edge)),
succ_weight.module(),
state,
)?;
......@@ -1300,34 +1446,6 @@ impl ModuleGraphRef {
}
}
/// Iterate the edges of a node REVERSED!
fn iter_graphs_neighbors_rev(
graphs: &[ReadRef<SingleModuleGraph>],
node: GraphNodeIndex,
) -> impl Iterator<Item = (EdgeIndex, GraphNodeIndex)> + '_ {
let graph = &*graphs[node.graph_idx()].graph;
if cfg!(debug_assertions) {
let node_weight = graph.node_weight(node.node_idx).unwrap();
if let SingleModuleGraphNode::VisitedModule { .. } = node_weight {
panic!("iter_graphs_neighbors_rev called on VisitedModule node");
}
}
let mut walker = graph.neighbors(node.node_idx).detach();
std::iter::from_fn(move || {
walker.next(graph).map(|(edge_idx, succ_idx)| {
(
edge_idx,
GraphNodeIndex {
graph_idx: node.graph_idx,
node_idx: succ_idx,
},
)
})
})
}
#[turbo_tasks::value_impl]
impl SingleModuleGraph {
#[turbo_tasks::function]
......@@ -1468,7 +1586,8 @@ impl SingleModuleGraphBuilderNode {
}
struct SingleModuleGraphBuilderEdge {
to: SingleModuleGraphBuilderNode,
export: ExportUsage,
binding_usage: BindingUsage,
reference: Option<ResolvedVc<Box<dyn ModuleReference>>>,
}
/// The chunking type that occurs most often, is handled more efficiently by not creating
......@@ -1486,7 +1605,13 @@ struct SingleModuleGraphBuilder<'a> {
/// Whether to walk ChunkingType::Traced references
include_traced: bool,
}
impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBuilder<'_> {
impl
Visit<(
SingleModuleGraphBuilderNode,
Option<ResolvedVc<Box<dyn ModuleReference>>>,
BindingUsage,
)> for SingleModuleGraphBuilder<'_>
{
type Edge = SingleModuleGraphBuilderEdge;
type EdgesIntoIter = Vec<Self::Edge>;
type EdgesFuture = impl Future<Output = Result<Self::EdgesIntoIter>>;
......@@ -1494,20 +1619,26 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
fn visit(
&mut self,
edge: Self::Edge,
) -> VisitControlFlow<(SingleModuleGraphBuilderNode, ExportUsage)> {
) -> VisitControlFlow<(
SingleModuleGraphBuilderNode,
Option<ResolvedVc<Box<dyn ModuleReference>>>,
BindingUsage,
)> {
match edge.to {
SingleModuleGraphBuilderNode::Module { .. } => {
VisitControlFlow::Continue((edge.to, edge.export))
VisitControlFlow::Continue((edge.to, edge.reference, edge.binding_usage))
}
SingleModuleGraphBuilderNode::ChunkableReference { ref ref_data, .. } => {
match &ref_data.chunking_type {
ChunkingType::Traced => VisitControlFlow::Skip((edge.to, edge.export)),
_ => VisitControlFlow::Continue((edge.to, edge.export)),
ChunkingType::Traced => {
VisitControlFlow::Skip((edge.to, edge.reference, edge.binding_usage))
}
_ => VisitControlFlow::Continue((edge.to, edge.reference, edge.binding_usage)),
}
}
// Module was already visited previously
SingleModuleGraphBuilderNode::VisitedModule { .. } => {
VisitControlFlow::Skip((edge.to, edge.export))
VisitControlFlow::Skip((edge.to, edge.reference, edge.binding_usage))
}
}
}
......@@ -1516,14 +1647,21 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
&mut self,
// The `skip_duplicates_with_key()` above ensures only a single `edges()` call per module
// (and not per `(module, export)` pair), so the export must not be read here!
(node, _): &(SingleModuleGraphBuilderNode, ExportUsage),
(node, ..): &(
SingleModuleGraphBuilderNode,
Option<ResolvedVc<Box<dyn ModuleReference>>>,
BindingUsage,
),
) -> Self::EdgesFuture {
// Destructure beforehand to not have to clone the whole node when entering the async block
let (module, chunkable_ref_target) = match node {
SingleModuleGraphBuilderNode::Module { module, .. } => (Some(*module), None),
SingleModuleGraphBuilderNode::ChunkableReference {
target, ref_data, ..
} => (None, Some((*target, ref_data.export.clone()))),
} => (
None,
Some((*target, ref_data.reference, ref_data.binding_usage.clone())),
),
// These are always skipped in `visit()`
SingleModuleGraphBuilderNode::VisitedModule { .. } => unreachable!(),
};
......@@ -1542,10 +1680,17 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
};
refs.iter()
.flat_map(|(ty, export, modules)| {
modules.iter().map(|m| (ty.clone(), export.clone(), *m))
.flat_map(|(reference, resolved)| {
resolved.modules.iter().map(|m| {
(
*reference,
resolved.chunking_type.clone(),
resolved.binding_usage.clone(),
*m,
)
})
.map(async |(ty, export, target)| {
})
.map(async |(reference, ty, binding_usage, target)| {
let to = if ty == COMMON_CHUNKING_TYPE {
if let Some(idx) = visited_modules.get(&target) {
SingleModuleGraphBuilderNode::new_visited_module(target, *idx)
......@@ -1560,17 +1705,22 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
target,
RefData {
chunking_type: ty,
export: export.clone(),
binding_usage: binding_usage.clone(),
reference,
},
)
.await?
};
Ok(SingleModuleGraphBuilderEdge { to, export })
Ok(SingleModuleGraphBuilderEdge {
to,
binding_usage,
reference: Some(reference),
})
})
.try_join()
.await?
}
(None, Some((chunkable_ref_target, export))) => {
(None, Some((chunkable_ref_target, reference, binding_usage))) => {
vec![SingleModuleGraphBuilderEdge {
to: if let Some(idx) = visited_modules.get(&chunkable_ref_target) {
SingleModuleGraphBuilderNode::new_visited_module(
......@@ -1584,7 +1734,8 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
)
.await?
},
export,
binding_usage,
reference: Some(reference),
}]
}
_ => unreachable!(),
......@@ -1592,7 +1743,14 @@ impl Visit<(SingleModuleGraphBuilderNode, ExportUsage)> for SingleModuleGraphBui
}
}
fn span(&mut self, (node, _): &(SingleModuleGraphBuilderNode, ExportUsage)) -> tracing::Span {
fn span(
&mut self,
(node, ..): &(
SingleModuleGraphBuilderNode,
Option<ResolvedVc<Box<dyn ModuleReference>>>,
BindingUsage,
),
) -> tracing::Span {
if !self.emit_spans {
return Span::current();
}
......@@ -1790,7 +1948,7 @@ pub mod tests {
&mut (),
|parent, target, _| {
visits.push((
parent.map(|(node, _)| module_to_name.get(&node).unwrap().clone()),
parent.map(|(node, _, _)| module_to_name.get(&node).unwrap().clone()),
module_to_name.get(&target).unwrap().clone(),
));
count += 1;
......
......@@ -350,7 +350,8 @@ pub async fn compute_module_batches(
// Walk the module graph and mark all modules that are boundary modules (referenced from a
// different chunk group bitmap)
module_graph.traverse_all_edges_unordered(|(parent, ty), node| {
module_graph.traverse_all_edges_unordered(|parent, node| {
if let Some((parent, ty)) = parent {
let std::collections::hash_set::Entry::Vacant(entry) =
pre_batches.boundary_modules.entry(node)
else {
......@@ -373,6 +374,7 @@ pub async fn compute_module_batches(
} else {
entry.insert();
}
}
Ok(())
})?;
......
use std::collections::HashSet;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_tasks::{
FxIndexSet, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, ValueToString, Vc,
FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt,
ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
};
use crate::{
......@@ -14,7 +16,7 @@ use crate::{
expand_output_assets,
},
raw_module::RawModule,
resolve::{ExportUsage, ModuleResolveResult, RequestKey},
resolve::{BindingUsage, ExportUsage, ImportUsage, ModuleResolveResult, RequestKey},
};
pub mod source_map;
......@@ -121,8 +123,12 @@ impl ChunkableModuleReference for SingleChunkableModuleReference {
}
#[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> {
*self.export
async fn binding_usage(&self) -> Result<Vc<BindingUsage>> {
Ok(BindingUsage {
import: ImportUsage::SideEffects,
export: self.export.owned().await?,
}
.cell())
}
}
......@@ -287,8 +293,17 @@ pub async fn primary_referenced_modules(module: Vc<Box<dyn Module>>) -> Result<V
Ok(Vc::cell(modules))
}
#[derive(
Clone, Serialize, Deserialize, Eq, PartialEq, ValueDebugFormat, TraceRawVcs, NonLocalValue,
)]
pub struct ResolvedReference {
pub chunking_type: ChunkingType,
pub binding_usage: BindingUsage,
pub modules: ReadRef<Modules>,
}
#[turbo_tasks::value(transparent)]
pub struct ModulesWithRefData(Vec<(ChunkingType, ExportUsage, ReadRef<Modules>)>);
pub struct ModulesWithRefData(Vec<(ResolvedVc<Box<dyn ModuleReference>>, ResolvedReference)>);
/// Aggregates all primary [Module]s referenced by an [Module] via [ChunkableModuleReference]s.
/// This does not include transitively referenced [Module]s, only includes
......@@ -319,9 +334,16 @@ pub async fn primary_chunkable_referenced_modules(
.await?
.primary_modules()
.await?;
let export = reference.export_usage().owned().await?;
return Ok(Some((chunking_type.clone(), export, resolved)));
let binding_usage = reference.binding_usage().owned().await?;
return Ok(Some((
ResolvedVc::upcast(reference),
ResolvedReference {
chunking_type: chunking_type.clone(),
binding_usage,
modules: resolved,
},
)));
}
Ok(None)
})
......
......@@ -7,6 +7,7 @@ use std::{
};
use anyhow::{Result, bail};
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::{Deserialize, Serialize};
use tracing::{Instrument, Level};
......@@ -103,6 +104,35 @@ impl ModuleResolveResultItem {
}
}
#[turbo_tasks::value(shared)]
#[derive(Clone, Debug, Hash, Default)]
pub struct BindingUsage {
pub import: ImportUsage,
pub export: ExportUsage,
}
#[turbo_tasks::value_impl]
impl BindingUsage {
#[turbo_tasks::function]
pub fn all() -> Vc<Self> {
Self::default().cell()
}
}
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Default, Hash)]
pub enum ImportUsage {
/// This import is used by some side effect in the module (and can't be tree shaken).
#[default]
SideEffects,
/// This import is used only by these specific exports, if all exports are unused, the import
/// can also be removed.
///
/// (This is only ever set on `ModulePart::Export` references. Side effects are handled via
/// `ModulePart::Evaluation` references, which always have `ImportUsage::SideEffects`.)
Exports(AutoSet<RcStr>),
}
#[turbo_tasks::value]
#[derive(Debug, Clone, Default, Hash)]
pub enum ExportUsage {
......
......@@ -31,7 +31,7 @@ use super::{
use crate::{
AnalyzeMode, SpecifiedModuleType,
analyzer::{WellKnownObjectKind, is_unresolved},
references::constant_value::parse_single_expr_lit,
references::{constant_value::parse_single_expr_lit, for_each_ident_in_pat},
utils::{AstPathRange, unparen},
};
......@@ -307,6 +307,30 @@ impl VarMeta {
}
}
#[derive(Clone, Debug)]
pub enum DeclUsage {
SideEffects,
Bindings(FxHashSet<Id>),
}
impl Default for DeclUsage {
fn default() -> Self {
DeclUsage::Bindings(Default::default())
}
}
impl DeclUsage {
fn add_usage(&mut self, user: &Id) {
match self {
Self::Bindings(set) => {
set.insert(user.clone());
}
Self::SideEffects => {}
}
}
fn make_side_effects(&mut self) {
*self = Self::SideEffects;
}
}
#[derive(Debug)]
pub struct VarGraph {
pub values: FxHashMap<Id, VarMeta>,
......@@ -315,6 +339,13 @@ pub struct VarGraph {
pub free_var_ids: FxHashMap<Atom, Id>,
pub effects: Vec<Effect>,
// ident -> immediate usage (top level decl)
pub decl_usages: FxHashMap<Id, DeclUsage>,
// import -> immediate usage (top level decl)
pub import_usages: FxHashMap<usize, DeclUsage>,
// export name -> top level decl
pub exports: FxHashMap<Atom, Id>,
}
impl VarGraph {
......@@ -339,14 +370,17 @@ pub fn create_graph(
values: Default::default(),
free_var_ids: Default::default(),
effects: Default::default(),
decl_usages: Default::default(),
import_usages: Default::default(),
exports: Default::default(),
};
m.visit_with_ast_path(
&mut Analyzer {
analyze_mode,
data: &mut graph,
state: analyzer_state::AnalyzerState::new(),
eval_context,
state: Default::default(),
effects: Default::default(),
hoisted_effects: Default::default(),
},
......@@ -873,9 +907,9 @@ struct Analyzer<'a> {
state: analyzer_state::AnalyzerState,
effects: Vec<Effect>,
// Effects collected from hoisted declarations. See https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
// Tracked separately so we can preserve effects from hoisted declarations even when we don't
// collect effects from the declaring context.
/// Effects collected from hoisted declarations. See https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
/// Tracked separately so we can preserve effects from hoisted declarations even when we don't
/// collect effects from the declaring context.
hoisted_effects: Vec<Effect>,
eval_context: &'a EvalContext,
......@@ -956,6 +990,7 @@ mod analyzer_state {
/// Contains fields of `Analyzer` that should only be modified using helper methods. These are
/// intentionally private to the rest of the `Analyzer` implementation.
#[derive(Default)]
pub struct AnalyzerState {
pat_value: Option<JsValue>,
/// Return values of the current function.
......@@ -967,17 +1002,14 @@ mod analyzer_state {
early_return_stack: Vec<EarlyReturn>,
lexical_stack: Vec<LexicalContext>,
var_decl_kind: Option<VarDeclKind>,
cur_top_level_decl_name: Option<Id>,
}
impl AnalyzerState {
pub fn new() -> AnalyzerState {
AnalyzerState {
pat_value: None,
cur_fn_return_values: None,
early_return_stack: Default::default(),
lexical_stack: Default::default(),
var_decl_kind: None,
}
/// Returns the identifier of the current top level declaration.
pub(super) fn cur_top_level_decl_name(&self) -> &Option<Id> {
&self.cur_top_level_decl_name
}
}
......@@ -1273,6 +1305,23 @@ mod analyzer_state {
}
always_returns
}
/// Runs `visitor` with the current top level declaration identifier
pub(super) fn enter_top_level_decl<T>(
&mut self,
name: &Ident,
visitor: impl FnOnce(&mut Self) -> T,
) -> T {
let is_top_level_fn = self.state.cur_top_level_decl_name.is_none();
if is_top_level_fn {
self.state.cur_top_level_decl_name = Some(name.to_id());
}
let result = visitor(self);
if is_top_level_fn {
self.state.cur_top_level_decl_name = None;
}
result
}
}
}
......@@ -1909,9 +1958,12 @@ impl VisitAstPath for Analyzer<'_> {
decl: &'ast FnDecl,
ast_path: &mut AstNodePath<AstParentNodeRef<'r>>,
) {
let fn_value = self.enter_fn(&*decl.function, |this| {
let fn_value = self.enter_top_level_decl(&decl.ident, |this| {
this.enter_fn(&*decl.function, |this| {
decl.visit_children_with_ast_path(this, ast_path);
})
});
// Take all effects produced by the function and move them to hoisted effects since
// function declarations are hoisted.
// This accounts for the fact that even with `if (true) { return f} function f() {} ` `f` is
......@@ -2386,6 +2438,17 @@ impl VisitAstPath for Analyzer<'_> {
if let Some((esm_reference_index, export)) =
self.eval_context.imports.get_binding(&ident.to_id())
{
let usage = self
.data
.import_usages
.entry(esm_reference_index)
.or_default();
if let Some(top_level) = self.state.cur_top_level_decl_name() {
usage.add_usage(top_level);
} else {
usage.make_side_effects();
}
// Optimization: Look for a MemberExpr to see if we only access a few members from the
// module, add those specific effects instead of depending on the entire module.
//
......@@ -2432,6 +2495,24 @@ impl VisitAstPath for Analyzer<'_> {
span: ident.span(),
})
}
if !is_unresolved(ident, self.eval_context.unresolved_mark) {
if let Some(top_level) = self.state.cur_top_level_decl_name() {
if !(ident.sym == top_level.0 && ident.ctxt == top_level.1) {
self.data
.decl_usages
.entry(ident.to_id())
.or_default()
.add_usage(top_level);
}
} else {
self.data
.decl_usages
.entry(ident.to_id())
.or_default()
.make_side_effects();
}
}
}
fn visit_this_expr<'ast: 'r, 'r>(
......@@ -2728,6 +2809,55 @@ impl VisitAstPath for Analyzer<'_> {
self.effects = prev_effects;
}
fn visit_export_decl<'ast: 'r, 'r>(
&mut self,
node: &'ast ExportDecl,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
match &node.decl {
Decl::Class(node) => {
self.data
.exports
.insert(node.ident.sym.clone(), node.ident.to_id());
}
Decl::Fn(node) => {
self.data
.exports
.insert(node.ident.sym.clone(), node.ident.to_id());
}
Decl::Var(node) => {
for VarDeclarator { name, .. } in &node.decls {
for_each_ident_in_pat(name, &mut |name, ctxt| {
self.data.exports.insert(name.clone(), (name.clone(), ctxt));
});
}
}
_ => {}
};
node.visit_children_with_ast_path(self, ast_path);
}
fn visit_export_named_specifier<'ast: 'r, 'r>(
&mut self,
node: &'ast ExportNamedSpecifier,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
let export_name = node
.exported
.as_ref()
.unwrap_or(&node.orig)
.atom()
.into_owned();
self.data.exports.insert(
export_name,
match &node.orig {
ModuleExportName::Ident(ident) => ident.to_id(),
ModuleExportName::Str(_) => unreachable!("exporting a string should be impossible"),
},
);
node.visit_children_with_ast_path(self, ast_path);
}
}
impl Analyzer<'_> {
......
......@@ -23,12 +23,12 @@ use turbopack_core::{
OptionStyledString, StyledString,
},
module::Module,
module_graph::export_usage::ModuleExportUsageInfo,
module_graph::binding_usage_info::ModuleExportUsageInfo,
reference::ModuleReference,
reference_type::{EcmaScriptModulesReferenceSubType, ImportWithType},
resolve::{
ExportUsage, ExternalType, ModulePart, ModuleResolveResult, ModuleResolveResultItem,
RequestKey,
BindingUsage, ExportUsage, ExternalType, ImportUsage, ModulePart, ModuleResolveResult,
ModuleResolveResultItem, RequestKey,
origin::{ResolveOrigin, ResolveOriginExt},
parse::Request,
},
......@@ -325,6 +325,7 @@ pub struct EsmAssetReference {
pub annotations: ImportAnnotations,
pub issue_source: IssueSource,
pub export_name: Option<ModulePart>,
pub import_usage: ImportUsage,
pub import_externals: bool,
pub is_pure_import: bool,
}
......@@ -346,6 +347,7 @@ impl EsmAssetReference {
issue_source: IssueSource,
annotations: ImportAnnotations,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
) -> Self {
EsmAssetReference {
......@@ -354,6 +356,7 @@ impl EsmAssetReference {
issue_source,
annotations,
export_name,
import_usage,
import_externals,
is_pure_import: false,
}
......@@ -365,6 +368,7 @@ impl EsmAssetReference {
issue_source: IssueSource,
annotations: ImportAnnotations,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
) -> Self {
EsmAssetReference {
......@@ -373,6 +377,7 @@ impl EsmAssetReference {
issue_source,
annotations,
export_name,
import_usage,
import_externals,
is_pure_import: true,
}
......@@ -512,12 +517,16 @@ impl ChunkableModuleReference for EsmAssetReference {
}
#[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> {
match &self.export_name {
Some(ModulePart::Export(export_name)) => ExportUsage::named(export_name.clone()),
Some(ModulePart::Evaluation) => ExportUsage::evaluation(),
_ => ExportUsage::all(),
fn binding_usage(&self) -> Vc<BindingUsage> {
BindingUsage {
import: self.import_usage.clone(),
export: match &self.export_name {
Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
Some(ModulePart::Evaluation) => ExportUsage::Evaluation,
_ => ExportUsage::All,
},
}
.cell()
}
}
......@@ -529,6 +538,13 @@ impl EsmAssetReference {
) -> Result<CodeGeneration> {
let this = &*self.await?;
if *chunking_context
.is_reference_unused(Vc::upcast(self))
.await?
{
return Ok(CodeGeneration::empty());
}
// only chunked references can be imported
if this.annotations.chunking_type().is_none_or(|v| v != "none") {
let import_externals = this.import_externals;
......@@ -571,7 +587,7 @@ impl EsmAssetReference {
}
if merged_index.is_some()
&& matches!(*self.export_usage().await?, ExportUsage::Evaluation)
&& matches!(this.export_name, Some(ModulePart::Evaluation))
{
// No need to import, the module was already executed and is available in
// the same scope hoisting group (unless it's a
......
......@@ -21,7 +21,7 @@ use turbopack_core::{
ident::AssetIdent,
issue::{IssueExt, IssueSeverity, StyledString, analyze::AnalyzeIssue},
module::Module,
module_graph::export_usage::ModuleExportUsageInfo,
module_graph::binding_usage_info::ModuleExportUsageInfo,
reference::ModuleReference,
resolve::ModulePart,
};
......
......@@ -42,7 +42,7 @@ use serde::{Deserialize, Serialize};
use swc_core::{
atoms::{Atom, Wtf8Atom, atom},
common::{
GLOBALS, Globals, Span, Spanned,
GLOBALS, Globals, Span, Spanned, SyntaxContext,
comments::{CommentKind, Comments},
errors::{DiagnosticId, HANDLER, Handler},
pass::AstNodePath,
......@@ -79,7 +79,7 @@ use turbopack_core::{
reference::{ModuleReference, ModuleReferences},
reference_type::{CommonJsReferenceSubType, ReferenceType},
resolve::{
FindContextFileResult, ModulePart, find_context_file,
FindContextFileResult, ImportUsage, ModulePart, find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin, ResolveOriginExt},
parse::Request,
pattern::Pattern,
......@@ -134,7 +134,7 @@ use crate::{
analyzer::{
ConstantNumber, ConstantString, JsValueUrlKind, RequireContextValue,
builtin::early_replace_builtin,
graph::{ConditionalKind, EffectArg, EvalContext, VarGraph},
graph::{ConditionalKind, DeclUsage, EffectArg, EvalContext, VarGraph},
imports::{ImportAnnotations, ImportAttributes, ImportedSymbol, Reexport},
parse_require_context,
top_level_await::has_top_level_await,
......@@ -745,6 +745,51 @@ async fn analyze_ecmascript_module_internal(
})
};
let mut import_usage =
FxHashMap::with_capacity_and_hasher(var_graph.import_usages.len(), Default::default());
for (reference, usage) in &var_graph.import_usages {
// TODO make this more efficient, i.e. cache the result?
if let DeclUsage::Bindings(ids) = usage {
// compute transitive closure of `ids` over `top_level_mappings`
let mut visited = ids.clone();
let mut stack = ids.iter().collect::<Vec<_>>();
let mut has_global_usage = false;
while let Some(id) = stack.pop() {
match var_graph.decl_usages.get(id) {
Some(DeclUsage::SideEffects) => {
has_global_usage = true;
break;
}
Some(DeclUsage::Bindings(callers)) => {
for caller in callers {
if visited.insert(caller.clone()) {
stack.push(caller);
}
}
}
_ => {}
}
}
// Collect all `visited` declarations which are exported
import_usage.insert(
*reference,
if has_global_usage {
ImportUsage::SideEffects
} else {
ImportUsage::Exports(
var_graph
.exports
.iter()
.filter(|(_, id)| visited.contains(*id))
.map(|(exported, _)| exported.as_str().into())
.collect(),
)
},
);
}
}
let span = tracing::trace_span!("esm import references");
let import_references = async {
let mut import_references = Vec::with_capacity(eval_context.imports.references().len());
......@@ -785,6 +830,7 @@ async fn analyze_ecmascript_module_internal(
)
.then(ModulePart::exports),
},
import_usage.get(&i).cloned().unwrap_or_default(),
import_externals,
)
.resolved_cell();
......@@ -1416,6 +1462,8 @@ async fn analyze_ecmascript_module_internal(
options.tree_shaking_mode,
Some(TreeShakingMode::ReexportsOnly)
) {
// TODO move this logic into Effect creation itself and don't create new
// references after the fact here.
let original_reference = r.await?;
if original_reference.export_name.is_none()
&& export.is_some()
......@@ -1434,6 +1482,11 @@ async fn analyze_ecmascript_module_internal(
original_reference.issue_source,
original_reference.annotations.clone(),
Some(ModulePart::export(export.clone())),
// TODO this is correct, but an overapproximation.
// We should have individual import_usage data for
// each export. This would be fixed by moving this
// logic earlier (see TODO above)
original_reference.import_usage.clone(),
original_reference.import_externals,
)
.resolved_cell()
......@@ -2874,6 +2927,7 @@ async fn handle_free_var_reference(
) => export.clone().map(ModulePart::export),
None => None,
},
ImportUsage::SideEffects,
state.import_externals,
)
.resolved_cell())
......@@ -3502,10 +3556,10 @@ fn as_parent_path(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> Vec<AstParent
ast_path.iter().map(|n| n.kind()).collect()
}
fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) {
pub(crate) fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(&Atom, SyntaxContext)) {
match pat {
Pat::Ident(BindingIdent { id, .. }) => {
f(id.sym.as_str().into());
f(&id.sym, id.ctxt);
}
Pat::Array(ArrayPat { elems, .. }) => elems.iter().for_each(|e| {
if let Some(e) = e {
......@@ -3521,7 +3575,7 @@ fn for_each_ident_in_pat(pat: &Pat, f: &mut impl FnMut(RcStr)) {
for_each_ident_in_pat(value, f);
}
ObjectPatProp::Assign(AssignPatProp { key, .. }) => {
f(key.sym.as_str().into());
f(&key.sym, key.ctxt);
}
ObjectPatProp::Rest(RestPat { arg, .. }) => {
for_each_ident_in_pat(arg, f);
......@@ -3654,8 +3708,8 @@ impl VisitAstPath for ModuleReferencesVisitor<'_> {
};
let decls = &*var_decl.decls;
decls.iter().for_each(|VarDeclarator { name, .. }| {
for_each_ident_in_pat(name, &mut |name| {
insert_export_binding(name, liveness)
for_each_ident_in_pat(name, &mut |name, _| {
insert_export_binding(name.as_str().into(), liveness)
})
});
}
......
......@@ -14,7 +14,7 @@ use turbopack_core::{
},
module::Module,
reference::ModuleReference,
resolve::{ExportUsage, ModulePart, ModuleResolveResult},
resolve::{BindingUsage, ExportUsage, ImportUsage, ModulePart, ModuleResolveResult},
};
use super::{
......@@ -144,8 +144,12 @@ impl ChunkableModuleReference for EcmascriptModulePartReference {
}
#[turbo_tasks::function]
fn export_usage(&self) -> Vc<ExportUsage> {
*self.export_usage
async fn binding_usage(&self) -> Result<Vc<BindingUsage>> {
Ok(BindingUsage {
import: ImportUsage::SideEffects,
export: self.export_usage.owned().await?,
}
.cell())
}
}
......
......@@ -18,10 +18,11 @@ use turbopack_core::{
module::Module,
module_graph::{
ModuleGraph,
binding_usage_info::{BindingUsageInfo, ModuleExportUsage},
chunk_group_info::ChunkGroup,
export_usage::{ExportUsageInfo, ModuleExportUsage},
},
output::{OutputAsset, OutputAssets},
reference::ModuleReference,
};
use turbopack_ecmascript::{
async_chunk::module::AsyncLoaderModule,
......@@ -117,11 +118,19 @@ impl NodeJsChunkingContextBuilder {
self
}
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<ExportUsageInfo>>) -> Self {
pub fn export_usage(mut self, export_usage: Option<ResolvedVc<BindingUsageInfo>>) -> Self {
self.chunking_context.export_usage = export_usage;
self
}
pub fn unused_references(
mut self,
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
) -> Self {
self.chunking_context.unused_references = unused_references;
self
}
pub fn chunking_config<T>(mut self, ty: ResolvedVc<T>, chunking_config: ChunkingConfig) -> Self
where
T: Upcast<Box<dyn ChunkType>>,
......@@ -188,7 +197,9 @@ pub struct NodeJsChunkingContext {
/// The strategy to use for generating module ids
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
/// The module export usage info, if available.
export_usage: Option<ResolvedVc<ExportUsageInfo>>,
export_usage: Option<ResolvedVc<BindingUsageInfo>>,
/// Which references are unused and should be skipped (e.g. during codegen).
unused_references: Option<ResolvedVc<BindingUsageInfo>>,
/// The strategy to use for generating source map source uris
source_map_source_type: SourceMapSourceType,
/// The chunking configs
......@@ -233,6 +244,7 @@ impl NodeJsChunkingContext {
source_map_source_type: SourceMapSourceType::TurbopackUri,
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None,
unused_references: None,
chunking_configs: Default::default(),
debug_ids: false,
},
......@@ -613,12 +625,24 @@ impl ChunkingContext for NodeJsChunkingContext {
if let Some(export_usage) = self.await?.export_usage {
Ok(export_usage.await?.used_exports(module).await?)
} else {
// In development mode, we don't have export usage info, so we assume all exports are
// used.
Ok(ModuleExportUsage::all())
}
}
#[turbo_tasks::function]
async fn is_reference_unused(
self: Vc<Self>,
reference: ResolvedVc<Box<dyn ModuleReference>>,
) -> Result<Vc<bool>> {
if let Some(unused_references) = self.await?.unused_references {
Ok(Vc::cell(
unused_references.await?.is_reference_unused(&reference),
))
} else {
Ok(Vc::cell(false))
}
}
#[turbo_tasks::function]
fn debug_ids_enabled(&self) -> Vc<bool> {
Vc::cell(self.debug_ids)
......
......@@ -39,7 +39,7 @@ use turbopack_core::{
file_source::FileSource,
ident::Layer,
issue::CollectibleIssuesExt,
module_graph::{ModuleGraph, export_usage::compute_export_usage_info},
module_graph::{ModuleGraph, binding_usage_info::compute_binding_usage_info},
reference_type::{InnerAssets, ReferenceType},
resolve::{
ExternalTraced, ExternalType,
......@@ -239,8 +239,12 @@ async fn run_inner_operation(
struct TestOptions {
#[serde(default = "default_tree_shaking_mode")]
tree_shaking_mode: Option<TreeShakingMode>,
remove_unused_exports: Option<bool>,
scope_hoisting: Option<bool>,
#[serde(default = "default_true")]
remove_unused_imports: bool,
#[serde(default = "default_true")]
remove_unused_exports: bool,
#[serde(default = "default_true")]
scope_hoisting: bool,
#[serde(default)]
minify: bool,
#[serde(default)]
......@@ -251,12 +255,17 @@ fn default_tree_shaking_mode() -> Option<TreeShakingMode> {
Some(TreeShakingMode::ReexportsOnly)
}
fn default_true() -> bool {
true
}
impl Default for TestOptions {
fn default() -> Self {
Self {
tree_shaking_mode: default_tree_shaking_mode(),
remove_unused_exports: None,
scope_hoisting: None,
remove_unused_exports: default_true(),
remove_unused_imports: default_true(),
scope_hoisting: default_true(),
minify: false,
production_chunking: false,
}
......@@ -351,7 +360,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
compile_time_defines!(
process.turbopack = true,
process.env.TURBOPACK = true,
process.env.NODE_ENV = "development",
process.env.NODE_ENV = "production",
)
.resolved_cell(),
)
......@@ -395,8 +404,6 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
.resolved_cell(),
);
let remove_unused_exports = options.remove_unused_exports.unwrap_or(true);
let asset_context: Vc<Box<dyn AssetContext>> = Vc::upcast(ModuleAssetContext::new(
Default::default(),
compile_time_info,
......@@ -469,7 +476,23 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
let entries = get_evaluate_entries(jest_entry_asset, asset_context, None);
let module_graph = ModuleGraph::from_modules(entries.graph_entries(), false);
let mut module_graph = ModuleGraph::from_modules(entries.graph_entries(), false);
let binding_usage = if options.remove_unused_imports || options.remove_unused_exports {
Some(
compute_binding_usage_info(
module_graph.to_resolved().await?,
options.remove_unused_imports,
)
.resolve_strongly_consistent()
.await?,
)
} else {
None
};
if options.remove_unused_imports {
module_graph = module_graph.without_unused_references(*binding_usage.unwrap());
}
let mut builder = NodeJsChunkingContext::builder(
project_root.clone(),
......@@ -481,7 +504,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
env,
RuntimeType::Development,
)
.module_merging(options.scope_hoisting.unwrap_or(true))
.module_merging(options.scope_hoisting)
.minify_type(if options.minify {
MinifyType::Minify {
mangle: Some(MangleType::OptimalSize),
......@@ -489,15 +512,16 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
} else {
MinifyType::NoMinify
})
.export_usage(if remove_unused_exports {
Some(
compute_export_usage_info(module_graph.to_resolved().await?)
.resolve_strongly_consistent()
.await?,
.export_usage(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
)
} else {
None
});
.unused_references(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
);
if options.production_chunking {
builder = builder
.chunking_config(
......
......@@ -122,7 +122,7 @@ it('should evaluate !process.turbopack', () => {
})
it('should evaluate NODE_ENV', () => {
if (process.env.NODE_ENV !== 'development') {
if (process.env.NODE_ENV !== 'production') {
require('fail')
import('fail')
}
......
module.exports = {}
function f() {
if (!process.turbopack) {
throw new Error('Turbopack is not enabled')
}
if (process.env.NODE_ENV !== 'development') {
throw new Error('NODE_ENV is not development')
}
}
f()
// if (f.toString().includes("process.turbopack")) {
// throw new Error("process.turbopack is not replaced");
// }
import { x } from './library/x.js'
import { y } from './library/y.js'
y()
function helper() {
return x()
}
export function unused() {
return helper()
}
export function used() {
return 1234
}
import { used } from './a.js'
it('should error when importing an invalid export', () => {
expect(used()).toBe(1234)
expect(globalThis.xBundled).toBeUndefined()
expect(globalThis.yBundled).toBeTruthy()
})
import * as lib from './library/index.js'
lib.y()
function helper() {
return lib.x()
}
export function unused() {
return helper()
}
export function used() {
return 1234
}
import { used } from './a.js'
it('should error when importing an invalid export', () => {
expect(used()).toBe(1234)
// TODO we don't actually want x to be bundled, but currently we can't track this easily.
// See the TODOs in turbopack/crates/turbopack-ecmascript/src/references/mod.rs
expect(globalThis.xBundled).toBeTruthy()
expect(globalThis.yBundled).toBeTruthy()
})
import { x } from './library/x.js'
function bar() {
return x()
}
export { bar as used }
import { used } from './a.js'
it('should error when importing an invalid export', () => {
used()
expect(globalThis.xBundled).toBeTruthy()
})
import { x } from './dep?c'
export default function abc() {
return x
}
abc()
import { x } from './dep?d'
export default class def {
method() {
return x
}
}
import { x } from './dep?e'
export default class def {
method() {
return x
}
}
import { x } from './dep?f'
export default class def {
method() {
return x
}
}
new def().method()
import A from './a'
import './b'
import './c'
import D from './d'
import './e'
import './f'
import a from './dep?a'
import b from './dep?b'
import c from './dep?c'
import d from './dep?d'
import e from './dep?e'
import f from './dep?f'
it('should generate valid code', () => {
expect(A()).toBe('x')
expect(new D().method()).toBe('x')
})
it('a should be used', () => {
expect(a).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('b should be unused', () => {
expect(b).toBe(false)
})
}
it('c should be used', () => {
expect(c).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('d should be used', () => {
expect(d).toBe(true)
})
it('e should be unused', () => {
expect(e).toBe(false)
})
}
it('f should be used', () => {
expect(f).toBe(true)
})
import B from './b.js'
import { A1 } from './dep1'
export default class A extends B {
constructor() {
super()
}
test() {
super.test()
this.b = new B()
this.a1 = new A1()
}
}
import A from './a.js'
import { A1 } from './dep1'
export default class B {
constructor() {}
test() {
this.a = new A()
this.a2 = new A1()
}
}
import { BaseError, BaseError1, BaseError2, BaseError3 } from './dep2'
export class ExtendedError extends BaseError {
constructor(message) {
super(message)
}
}
export class ExtendedError1 extends BaseError1 {
constructor(message) {
super(message)
}
}
export class ExtendedError2 extends BaseError2 {
myMethod() {}
}
export class ExtendedError3 extends BaseError3 {}
export class ExtendedError4 extends Error {
constructor(message = 'ExtendedError') {
super(message)
}
}
import { A, B, Z, W } from './dep2'
export const A1 = class A1 extends A {
render() {
return new E()
}
}
class B1 extends B {
render() {
return new D()
}
}
export class Z1 extends Z {}
export class E {}
class D {
foo() {
class B2 extends B {}
return B2
}
}
export const isZ = new Z1() instanceof Z
export { W }
export const A = class A {}
export class B {}
export class C {}
export class Y {}
export class Z {}
export function mixin1(_class) {
return _class
}
export function mixin2(_class) {
return _class
}
export function mixin3(_class) {
return _class
}
export function mixin4(_class) {
return _class
}
export function mixin5(_class) {
return _class
}
export function getField() {
return 'test'
}
export class BaseError extends Error {}
export class BaseError1 extends Error {}
export class BaseError2 extends Error {}
export class BaseError3 extends Error {}
export class W {}
export class J {}
export class K {}
var SuperClass = class {}
export { SuperClass }
export const exportsInfoForA = __webpack_exports_info__.A.used
export const exportsInfoForB = __webpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.C.used
export const exportsInfoForY = __webpack_exports_info__.Y.used
export const exportsInfoForZ = __webpack_exports_info__.Z.used
export const exportsInfoForW = __webpack_exports_info__.W.used
export const exportsInfoForJ = __webpack_exports_info__.J.used
export const exportsInfoForK = __webpack_exports_info__.K.used
export const exportsInfoForMixin1 = __webpack_exports_info__.mixin1.used
export const exportsInfoForMixin2 = __webpack_exports_info__.mixin2.used
export const exportsInfoForMixin3 = __webpack_exports_info__.mixin3.used
export const exportsInfoForMixin4 = __webpack_exports_info__.mixin4.used
export const exportsInfoForMixin5 = __webpack_exports_info__.mixin5.used
export const exportsInfoForgetField = __webpack_exports_info__.getField.used
export const exportsInfoForBaseError = __webpack_exports_info__.BaseError.used
export const exportsInfoForBaseError1 = __webpack_exports_info__.BaseError1.used
export const exportsInfoForBaseError2 = __webpack_exports_info__.BaseError2.used
export const exportsInfoForBaseError3 = __webpack_exports_info__.BaseError3.used
export const exportsInfoForSuperClass = __webpack_exports_info__.SuperClass.used
import { mixin1, mixin2, mixin3, getField, A, B, C, Y, mixin4 } from './dep2'
export const A1 = class A1 extends A {
render() {
return new E()
}
}
export const B1 = class B1 extends /*#__PURE__*/ mixin1(B) {
render() {
return new E()
}
}
export const C1 = class C1 extends mixin2(Y, /*#__PURE__*/ mixin3(C)) {
render() {
return new D()
}
}
export class Y1 extends /*#__PURE__*/ mixin2(Y) {
constructor() {
super()
this.innerClass = class B2 extends mixin1(B) {}
}
render() {
return new D()
}
}
export class Bar extends /*#__PURE__*/ mixin4(A) {
[/*#__PURE__*/ getField()] = 12
}
export class E {}
const D = class D {}
import {
exportsInfoForA,
exportsInfoForB,
exportsInfoForC,
exportsInfoForY,
exportsInfoForZ,
exportsInfoForW,
exportsInfoForJ,
exportsInfoForK,
exportsInfoForMixin1,
exportsInfoForMixin2,
exportsInfoForMixin3,
exportsInfoForMixin4,
exportsInfoForMixin5,
exportsInfoForBaseError,
exportsInfoForBaseError1,
exportsInfoForBaseError2,
exportsInfoForBaseError3,
exportsInfoForSuperClass,
} from './dep2'
it('should load modules correctly', () => {
require('./module1')
require('./module2')
require('./module3')
require('./module4')
require('./module5')
require('./module6')
require('./module7')
require('./module8')
require('./module9')
})
if (process.env.NODE_ENV === 'production') {
it('W and J should not be used', () => {
expect(exportsInfoForJ).toBe(false)
expect(exportsInfoForW).toBe(false)
})
it('Keep extends with constructor', () => {
expect(exportsInfoForBaseError).toBe(true)
expect(exportsInfoForBaseError1).toBe(true)
expect(exportsInfoForBaseError2).toBe(false)
expect(exportsInfoForBaseError3).toBe(false)
})
}
it('A should be used', () => {
expect(exportsInfoForA).toBe(true)
})
it('B should be used', () => {
expect(exportsInfoForB).toBe(true)
})
it('K should be used', () => {
expect(exportsInfoForK).toBe(true)
})
it('Z used, inner graph can not determine const usage', () => {
expect(exportsInfoForZ).toBe(true)
})
it('SuperClass should be used', () => {
expect(exportsInfoForSuperClass).toBe(true)
})
it('Pure super expression should be unused, another used', () => {
if (process.env.NODE_ENV === 'production') {
expect(exportsInfoForMixin4).toBe(false)
expect(exportsInfoForMixin5).toBe(false)
}
expect(exportsInfoForMixin1).toBe(true)
expect(exportsInfoForMixin2).toBe(true)
expect(exportsInfoForMixin3).toBe(true)
expect(exportsInfoForC).toBe(true)
expect(exportsInfoForY).toBe(true)
})
import { ExtendedError4 } from './c.js'
export default new ExtendedError4()
import { J } from './dep2'
class BaseJ extends J {}
class BaseBaseJ extends BaseJ {}
import { K } from './dep2'
class BaseK extends K {}
class BaseBaseK extends BaseK {}
export default new BaseBaseK()
import { mixin5 } from './dep2'
class Bar extends /*#__PURE__*/ mixin5(null) {
static displayName = 'Point'
}
function test() {
return Bar.displayName
}
import { SuperClass } from './dep2'
var UnusedClass = class extends SuperClass {
constructor() {
super()
}
},
unusedVariable = new UnusedClass()
'use strict'
const supportsClassStaticBlock = require('../../../helpers/supportsClassStaticBlock')
module.exports = () => supportsClassStaticBlock()
import {
A,
B,
getC,
getD,
getE,
getF,
Foo,
Pure,
DateFormatter,
ConditionalExpression,
LogicalExpression,
} from './dep2?decl'
import {
A3,
B3,
C3,
D3,
E3,
F3,
Pure3,
ConditionalExpression3,
LogicalExpression3,
} from './dep3?decl'
export class A1 extends A {
render() {
return new A2()
}
}
export class B1 extends B {
render() {
return new B2()
}
}
// prettier-ignore
export class C1 extends /*#__PURE__*/ getC() {
render() {
return new C2();
}
}
// prettier-ignore
export class D1 extends /*@__PURE__*/ getD() {
render() {
return new D2();
}
}
export class E1 extends getE() {
render() {
return new E2()
}
}
export class F1 extends getF() {
render() {
return new F2()
}
}
function foo(instance) {
return new instance()
}
class Bar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
class BarA extends Foo {
static prop = 42
static a = foo(this).prop
}
class BarB extends Foo {
static prop = 42
static b = foo(Bar).prop
}
class BarC extends Foo {
static prop = 42
static c = foo(super.Bar).prop
}
class BarPA extends Foo {
static prop = 42
static #a = foo(this).prop
}
class BarPB extends Foo {
static prop = 42
static #b = foo(Bar).prop
}
class BarPC extends Foo {
static prop = 42
static #c = foo(super.Bar).prop
}
const ExpressionFoo = class Bar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export class Baz extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export default class DefaultBar extends Foo {
static prop = 42
static a = foo(this).prop
static b = foo(Bar).prop
static c = foo(super.Bar).prop
static inStatic1
static inStatic2
static inStatic3
static {
this.inStatic1 = new Bar().prop
this.inStatic2 = new super.Bar().prop
this.inStatic3 = new this().prop
}
}
export class ExtendsPure extends Pure {
render() {
return new Pure3()
}
}
export class DateBar extends DateFormatter {
constructor() {
super()
}
render() {}
}
export class ConditionalExpression1 extends ConditionalExpression {
render() {
return new ConditionalExpression3()
}
}
export class LogicalExpression1 extends LogicalExpression {
render() {
return new LogicalExpression3()
}
}
export class A2 extends A3 {}
export class B2 extends B3 {}
export class C2 extends C3 {}
export class D2 extends D3 {}
export class E2 extends E3 {}
export class F2 extends F3 {}
import {
A,
B,
DateFormatter,
getC,
getD,
getE,
getF,
Pure,
ConditionalExpression,
LogicalExpression,
} from './dep2?expr'
import { A3, B3, C3, D3, E3, F3, Pure3 } from './dep3?expr'
export const A1 = class extends A {
render() {
return new A2()
}
}
export const B1 = class extends B {
render() {
return new B2()
}
}
// prettier-ignore
export const C1 = class extends /*#__PURE__*/ getC() {
render() {
return new C2();
}
}
// prettier-ignore
export const D1 = class extends /*@__PURE__*/ getD() {
render() {
return new D2();
}
}
export const E1 = class extends getE() {
render() {
return new E2()
}
}
export const F1 = class extends getF() {
render() {
return new F2()
}
}
export const ExtendsPure = class extends Pure {
render() {
return new Pure3()
}
}
export class DateBar extends DateFormatter {
constructor() {
super()
}
render() {}
}
export class ConditionalExpression1 extends ConditionalExpression {
render() {
return new ConditionalExpression3()
}
}
export class LogicalExpression1 extends LogicalExpression {
render() {
return new LogicalExpression3()
}
}
export const A2 = class extends A3 {}
export const B2 = class extends B3 {}
export const C2 = class extends C3 {}
export const D2 = class extends D3 {}
export const E2 = class extends E3 {}
export const F2 = class extends F3 {}
export class A {}
export class B {}
export const getC = () => class C {}
export const getD = () => class D {}
export const getE = () => class E {}
export const getF = () => class F {}
export class Foo {
static Bar = Foo
}
export class Pure {}
export class DateFormatter extends Date {
constructor() {
super()
this.date = this.getDate()
}
}
export class ConditionalExpression extends (true ? A : B) {}
export class LogicalExpression extends (A || B) {}
export const exportsInfoForA = __webpack_exports_info__.A.used
export const exportsInfoForB = __webpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.getC.used
export const exportsInfoForD = __webpack_exports_info__.getD.used
export const exportsInfoForE = __webpack_exports_info__.getE.used
export const exportsInfoForF = __webpack_exports_info__.getF.used
export const exportsInfoForFoo = __webpack_exports_info__.Foo.used
export const exportsInfoForPure = __webpack_exports_info__.Pure.used
export const exportsInfoForDateFormatter =
__webpack_exports_info__.DateFormatter.used
export const exportsInfoForConditionalExpression =
__webpack_exports_info__.ConditionalExpression.used
export const exportsInfoForLogicalExpression =
__webpack_exports_info__.LogicalExpression.used
export class A3 {}
export class B3 {}
export class C3 {}
export class D3 {}
export class E3 {}
export class F3 {}
export class Pure3 {}
export class ConditionalExpression3 extends (true ? A3 : B3) {}
export class LogicalExpression3 extends (A3 || B3) {}
import {
exportsInfoForA as declA,
exportsInfoForB as declB,
exportsInfoForC as declC,
exportsInfoForD as declD,
exportsInfoForE as declE,
exportsInfoForF as declF,
exportsInfoForFoo as declFoo,
exportsInfoForPure as declPure,
exportsInfoForDateFormatter as declDateFormatter,
exportsInfoForConditionalExpression as declConditionalExpression,
exportsInfoForLogicalExpression as declLogicalExpression,
} from './dep2?decl'
import {
exportsInfoForA as exprA,
exportsInfoForB as exprB,
exportsInfoForC as exprC,
exportsInfoForD as exprD,
exportsInfoForE as exprE,
exportsInfoForF as exprF,
exportsInfoForPure as exprPure,
exportsInfoForDateFormatter as exprDateFormatter,
exportsInfoForConditionalExpression as exprConditionalExpression,
exportsInfoForLogicalExpression as exprLogicalExpression,
} from './dep2?expr'
it('should load module correctly', () => {
require('./module-decl')
require('./module-expr')
})
it('A should be used', () => {
expect(declA).toBe(true)
expect(exprA).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('B should not be used', () => {
expect(declB).toBe(false)
expect(exprB).toBe(false)
})
}
it('C should be used', () => {
expect(declC).toBe(true)
expect(exprC).toBe(true)
})
if (process.env.NODE_ENV === 'production') {
it('D should not be used', () => {
expect(declD).toBe(false)
expect(exprD).toBe(false)
})
}
it('E should be used', () => {
expect(declE).toBe(true)
expect(exprE).toBe(true)
})
it('F should be used', () => {
if (process.env.NODE_ENV === 'production') {
expect(declPure).toBe(false)
expect(exprPure).toBe(false)
expect(declConditionalExpression).toBe(false)
expect(exprConditionalExpression).toBe(false)
expect(declLogicalExpression).toBe(false)
expect(exprLogicalExpression).toBe(false)
}
// Note: it has side-effects and is not affected by usage of the class
expect(declF).toBe(true)
expect(declFoo).toBe(true)
expect(exprF).toBe(true)
expect(declDateFormatter).toBe(true)
expect(exprDateFormatter).toBe(true)
})
import { A1, C1, E1, DateBar } from './dep-decl'
export default [
new A1().render(),
new C1().render(),
new E1().render(),
new DateBar(),
]
import { A1, C1, E1, DateBar } from './dep-expr'
export default [
new A1().render(),
new C1().render(),
new E1().render(),
new DateBar(),
]
'use strict'
const supportsClassStaticBlock = require('../../../helpers/supportsClassStaticBlock')
module.exports = () => supportsClassStaticBlock()
import {
exportUsed,
export2Used,
export3Used,
export4Used,
export5Used,
export6Used,
} from './inner'
import { f1, pureUsed, fWithDefault } from './module'
it('export should be unused when only unused functions use it', () => {
f1()
expect(pureUsed).toBe(42)
expect(fWithDefault()).toBe(42)
if (process.env.NODE_ENV === 'production') {
expect(exportUsed).toBe(false)
expect(export2Used).toBe(true)
expect(export3Used).toBe(true)
expect(export4Used).toBe(true)
expect(export5Used).toBe(true)
expect(export6Used).toBe(true)
}
return import('./chunk')
})
export const EXPORT = 42
export const EXPORT2 = 42
export const EXPORT3 = 42
export const EXPORT4 = 42
export const EXPORT5 = () => 42
export const EXPORT6 = () => 42
export const exportUsed = __webpack_exports_info__.EXPORT.used
export const export2Used = __webpack_exports_info__.EXPORT2.used
export const export3Used = __webpack_exports_info__.EXPORT3.used
export const export4Used = __webpack_exports_info__.EXPORT4.used
export const export5Used = __webpack_exports_info__.EXPORT5.used
export const export6Used = __webpack_exports_info__.EXPORT6.used
import { EXPORT, EXPORT2, EXPORT3, EXPORT4, EXPORT5, EXPORT6 } from './inner'
export function f1() {
// no using EXPORT
}
export function f2() {
return EXPORT
}
function f3() {
return EXPORT
}
const f4 = function () {
return EXPORT
}
const f5 = () => {
return EXPORT
}
let f6 = () => {
return EXPORT
}
const f7 = () => {
return EXPORT5()
}
const f8 = () => {
return EXPORT6()
}
export function g2() {
return f2()
}
export function g3() {
return f3()
}
export var g4 = () => f4()
export let g5 = () => {
return f5()
}
function ga6() {
return f6() || gb6()
}
function gb6() {
return ga6()
}
export class g7 {
static f() {
return EXPORT
}
}
export const pure1 = EXPORT
export const pure2 = /*#__PURE__*/ f6()
const pure3 = /*#__PURE__*/ g5()
const pure4 = /*#__PURE__*/ f7(f8())
const pure5 =
('fefef', 1123, /*#__PURE__*/ f2('fwefe'), /*#__PURE__*/ f2('efwefa'))
const pure6 = /*#__PURE__*/ f2(/*#__PURE__*/ f2(), /*#__PURE__*/ f2())
const pure7 = /*#__PURE__*/ f2(
class {
f() {
return EXPORT
}
}
)
const pure8 = /*#__PURE__*/ f2(() => EXPORT)
export const pureUsed = EXPORT3
function x1() {
return EXPORT2
}
const x2 = function x2() {
return x1()
}
const x3 = () => {
return x2()
}
const x4 = x3()
export function fWithDefault(r = EXPORT4) {
return r
}
export default (function () {
return EXPORT
})
import { exportAUsed, exportBUsed, exportCUsed } from './inner'
import { y } from './module'
it('export should be unused when only unused functions use it', () => {
expect(y('a')).toBe('okBAA')
expect(exportAUsed).toBe(true)
expect(exportBUsed).toBe(true)
if (process.env.NODE_ENV === 'production') {
expect(exportCUsed).toBe(false)
}
return import('./chunk')
})
export function A(s) {
return s + 'A'
}
export function B(s) {
return s + 'B'
}
export function C(s) {
return s + 'C'
}
export const exportAUsed = __webpack_exports_info__.A.used
export const exportBUsed = __webpack_exports_info__.B.used
export const exportCUsed = __webpack_exports_info__.C.used
import { A, B, C } from './inner'
function x(type) {
switch (type) {
case 'a':
return withA('b')
case 'b':
return withB('c')
case 'c':
return 'ok'
}
}
function y(v) {
return withA(v)
}
function withA(v) {
const value = x(v)
return A(value)
}
function withB(v) {
const value = x(v)
return B(value)
}
function withC(v) {
const value = x(v)
return C(value)
}
export { x, y }
import { x, y, z, a, f3 } from './module'
it('should be able to handle circular referenced', () => {
expect(x()).toEqual([y, z])
const [_a, b, c, d] = a()
expect(b()).toEqual([a, b, c, d])
expect(c()).toEqual([a, b, c, d])
expect(d()).toEqual([a, b, c, d])
const [f2, f4] = f3()
const [f1, _f3] = f2()
expect(_f3).toBe(f3)
expect(f3()).toEqual(f1())
expect(f2()).toEqual(f4())
})
function x() {
return [y, z]
}
function y() {
return [x, z]
}
function z() {
return [x, y]
}
export { x, y, z }
function a() {
return [a, b, c, d]
}
function b() {
return [a, b, c, d]
}
function c() {
return [a, b, c, d]
}
function d() {
return [a, b, c, d]
}
export { a }
function f1() {
return [f2, f4]
}
function f2() {
return [f1, f3]
}
function f3() {
return [f2, f4]
}
function f4() {
return [f1, f3]
}
export { f3 }
it('should not throw when using dynamic properties in unused classes', () => {
require('./unused1')
})
it('should not throw when using dynamic properties in used classes', () => {
const exports = require('./used1')
const x = new exports.Used()
expect(x.a()).toBe('A')
expect(x.b).toBe('B')
expect(x.c).toBe('C')
expect(exports.Used.d()).toBe('D')
expect(exports.Used.e).toBe('E')
expect(exports.Used.f).toBe('F')
const x2 = new exports.Used2()
expect(x2.a()).toBe('A')
expect(x2.b).toBe('B')
expect(x2.c).toBe('C')
expect(exports.Used2.d()).toBe('D')
expect(exports.Used2.e).toBe('E')
expect(exports.Used2.f).toBe('F')
expect(x2.x).toBe('X')
})
export const a = () => 'a'
export const A = 'A'
export const b = 'b'
export const B = 'B'
export const c = 'c'
export const C = 'C'
export const d = () => 'd'
export const D = 'D'
export const e = 'e'
export const E = 'E'
export const f = 'f'
export const F = 'F'
export class X {
x = 'X'
}
export const y = 'y'
'use strict'
const supportsClassFields = require('../../../helpers/supportsClassFields')
module.exports = () => supportsClassFields()
import { a, b, c, d, e, f, A, B, C, D, E, F, X } from './module'
class Unused {
[a()]() {
return A
}
[b] = B
get [c]() {
return C
}
static [d()]() {
return D
}
static [e] = E
static get [f]() {
return F
}
}
class Unused2 extends X {
[a()]() {
return A
}
[b] = B
get [c]() {
return C
}
static [d()]() {
return D
}
static [e] = E
static get [f]() {
return F
}
}
export {}
import { a, b, c, d, e, f, A, B, C, D, E, F, X } from './module?1'
class Used {
[a()]() {
return A
}
[b] = B
get [c]() {
return C
}
static [d()]() {
return D
}
static [e] = E
static get [f]() {
return F
}
}
class Used2 extends X {
[a()]() {
return A
}
[b] = B
get [c]() {
return C
}
static [d()]() {
return D
}
static [e] = E
static get [f]() {
return F
}
}
export { Used, Used2 }
it('should be able to load package without side effects where modules are unused', () => {
require('./module')
})
import value from './unusedModule'
export function a() {
return 42
}
export function b() {
return value
}
import './module?1'
import { getX, getY } from './module?2'
import { getX as getX2 } from './module?3'
import { getY as getY2 } from './module?4'
export function test() {
expect(getX()).toBe(42)
expect(getY()).toBe(42)
expect(getX2()).toBe(42)
expect(getY2()).toBe(42)
}
it('should generate correct code when pure expressions are in dead branches', () => {
require('./import-module').test()
})
function f() {
return 43
}
if (true) {
var x = /*#__PURE__*/ f() - 1
var y = 42
} else {
var x = /*#__PURE__*/ f()
var y = 43
}
export const getX = () => x,
getY = () => y
import { exportDefaultUsed as export1 } from './package1/script'
import { exportDefaultUsed as export2 } from './package1/script2'
import { exportDefaultUsed as export3 } from './package2/script'
it('should load module correctly', () => {
require('./module')
})
if (process.env.NODE_ENV === 'production') {
it('default export should be unused', () => {
expect(export1).toBe(false)
expect(export2).toBe(false)
})
}
it('default export should be used', () => {
expect(export3).toBe(true)
})
import * as script from './package1/script'
import script1 from './package2/script'
export const mod = script1
import mod from './script1'
export default mod
export * from './script1'
export const exportDefaultUsed = __webpack_exports_info__.default.used
import mod from './script3'
export default function () {
return mod
}
export * from './script3'
export const exportDefaultUsed = __webpack_exports_info__.default.used
import mod from './script1'
export default mod
export * from './script1'
export const exportDefaultUsed = __webpack_exports_info__.default.used
import './module-unused'
import { NativeClass, TranspiledClass } from './module-used'
export function test() {
expect(NativeClass.f()).toBe(42)
expect(TranspiledClass.f()).toBe(42)
}
it('should generate correct code when pure expressions are in dead branches', () => {
require('./import-module').test()
return import('./chunk')
})
import { x } from './other/module-unused'
class NativeClass {
static f() {
return 42
}
}
var TranspiledClass = /*#__PURE__*/ (function () {
x()
function C() {}
C.f = function () {
return 42
}
return C
})()
export { NativeClass, TranspiledClass }
import { x } from './other/module-used'
class NativeClass {
static f() {
return 42
}
}
var TranspiledClass = /*#__PURE__*/ (function () {
x()
function C() {}
C.f = function () {
return 42
}
return C
})()
export { NativeClass, TranspiledClass }
import doSomething from './module'
export function test() {
doSomething({
type: 'inline',
})
}
it('should generate correct code when pure expressions are in dead branches', () => {
require('./import-module').test()
return Promise.all([import('./some-module'), import('./chunk')])
})
import { Block, Inline, Document } from './some-module'
function getType(obj) {
return obj.type
}
// Local functions
function doSomethingWithBlock(obj) {
return Block.doSomething(obj)
}
function doSomethingWithInline(obj) {
return Inline.doSomething(obj)
}
function doSomethingWithDocument(obj) {
return Document.doSomething(obj)
}
// Exported functions
function doSomething(obj) {
const type = getType(obj)
switch (type) {
case 'document':
return doSomethingWithDocument(obj)
case 'block':
return doSomethingWithBlock(obj)
case 'inline':
return doSomethingWithInline(obj)
default:
throw new Error()
}
}
function useDocument(obj) {
return doSomethingWithDocument(obj)
}
export { useDocument }
export default doSomething
class Block {
static doSomething() {}
}
class Inline {
static doSomething() {}
}
class Document {
static doSomething() {}
}
export { Block, Inline, Document }
import { ok, ok2 } from './module'
expect(ok).toBe(true)
expect(ok2).toBe(true)
it('should not threat globals as pure', () => {
require('./import-module')
})
try {
var x = NOT_DEFINED
var y = x
var ok = false
} catch (e) {
var yep = true
var ok = yep
}
try {
const b = a
var c = b
const a = 42
var ok2 = false
eval('') // TODO terser has a bug and incorrectly remove this code, eval opts out
} catch (e) {
var ok2 = true
}
export { x, y, c, ok, ok2 }
......@@ -47,8 +47,8 @@ use turbopack_core::{
module::Module,
module_graph::{
ModuleGraph,
binding_usage_info::compute_binding_usage_info,
chunk_group_info::{ChunkGroup, ChunkGroupEntry},
export_usage::compute_export_usage_info,
},
output::{OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType},
......@@ -84,6 +84,8 @@ struct SnapshotOptions {
#[serde(default)]
tree_shaking_mode: Option<TreeShakingMode>,
#[serde(default)]
remove_unused_imports: bool,
#[serde(default)]
remove_unused_exports: bool,
#[serde(default)]
scope_hoisting: bool,
......@@ -119,6 +121,7 @@ impl Default for SnapshotOptions {
runtime_type: default_runtime_type(),
environment: Default::default(),
tree_shaking_mode: None,
remove_unused_imports: false,
remove_unused_exports: false,
scope_hoisting: false,
production_chunking: false,
......@@ -426,20 +429,26 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
bail!("Entry module is not chunkable, so it can't be used to bootstrap the application")
};
let module_graph = ModuleGraph::from_modules(
let mut module_graph = ModuleGraph::from_modules(
Vc::cell(vec![ChunkGroupEntry::Entry(entry_modules.clone())]),
false,
);
let export_usage = if options.remove_unused_exports {
let binding_usage = if options.remove_unused_imports || options.remove_unused_exports {
Some(
compute_export_usage_info(module_graph.to_resolved().await?)
compute_binding_usage_info(
module_graph.to_resolved().await?,
options.remove_unused_imports,
)
.resolve_strongly_consistent()
.await?,
)
} else {
None
};
if options.remove_unused_imports {
module_graph = module_graph.without_unused_references(*binding_usage.unwrap());
}
let chunk_root_path = project_path.join("output")?;
let static_root_path = project_path.join("static")?;
......@@ -463,7 +472,16 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
)
.minify_type(options.minify_type)
.module_merging(options.scope_hoisting)
.export_usage(export_usage)
.export_usage(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
)
.unused_references(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
)
.debug_ids(options.enable_debug_ids)
.source_map_source_type(options.source_map_source_type);
......@@ -495,7 +513,16 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
)
.minify_type(options.minify_type)
.module_merging(options.scope_hoisting)
.export_usage(export_usage)
.export_usage(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
)
.unused_references(
options
.remove_unused_exports
.then(|| binding_usage.unwrap()),
)
.debug_ids(options.enable_debug_ids)
.source_map_source_type(options.source_map_source_type);
......
import { x } from './library/x.js'
import { y } from './library/y.js'
y()
function helper() {
return x()
}
export function unused() {
return helper()
}
export function used() {
return 1234
}
import { leafX, leafY } from './leaf'
export function sharedX() {
leafX()
}
export function sharedY() {
leafY()
}
import { sharedX } from './shared'
globalThis.xBundled = true
export function x() {
sharedX()
}
import { sharedY } from './shared'
globalThis.yBundled = true
export function y() {
sharedY()
}
{
"scopeHoisting": false,
"removeUnusedImports": true,
"removeUnusedExports": true,
"treeShakingMode": "reexports-only"
}
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/780ce_turbopack-tests_tests_snapshot_remove-unused-imports_exports_input_19985db1._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/leaf.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
function leafX() {}
function leafY() {}
__turbopack_context__.s([
"leafY",
()=>leafY
]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/shared.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$leaf$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/leaf.js [test] (ecmascript)");
;
function sharedX() {
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$leaf$2e$js__$5b$test$5d$__$28$ecmascript$29$__["leafX"])();
}
function sharedY() {
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$leaf$2e$js__$5b$test$5d$__$28$ecmascript$29$__["leafY"])();
}
__turbopack_context__.s([
"sharedY",
()=>sharedY
]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/y.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$shared$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/shared.js [test] (ecmascript)");
;
globalThis.yBundled = true;
function y() {
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$shared$2e$js__$5b$test$5d$__$28$ecmascript$29$__["sharedY"])();
}
__turbopack_context__.s([
"y",
()=>y
]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/a.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$y$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/y.js [test] (ecmascript)");
;
;
(0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$y$2e$js__$5b$test$5d$__$28$ecmascript$29$__["y"])();
function helper() {
return (0, __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$library$2f$x$2e$js__$5b$test$5d$__$28$ecmascript$29$__["x"])();
}
function unused() {
return helper();
}
function used() {
return 1234;
}
__turbopack_context__.s([
"used",
()=>used
]);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/a.js [test] (ecmascript)");
;
console.log(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$remove$2d$unused$2d$imports$2f$exports$2f$input$2f$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__["used"]);
__turbopack_context__.s([]);
}),
]);
//# sourceMappingURL=780ce_turbopack-tests_tests_snapshot_remove-unused-imports_exports_input_19985db1._.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/leaf.js"],"sourcesContent":["export function leafX() {}\nexport function leafY() {}\n"],"names":[],"mappings":"AAAO,SAAS,SAAS;AAClB,SAAS,SAAS"}},
{"offset": {"line": 14, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/shared.js"],"sourcesContent":["import { leafX, leafY } from './leaf'\n\nexport function sharedX() {\n leafX()\n}\nexport function sharedY() {\n leafY()\n}\n"],"names":[],"mappings":"AAAA;;AAEO,SAAS;IACd,IAAA,uOAAK;AACP;AACO,SAAS;IACd,IAAA,uOAAK;AACP"}},
{"offset": {"line": 30, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/library/y.js"],"sourcesContent":["import { sharedY } from './shared'\n\nglobalThis.yBundled = true\n\nexport function y() {\n sharedY()\n}\n"],"names":[],"mappings":"AAAA;;AAEA,WAAW,QAAQ,GAAG;AAEf,SAAS;IACd,IAAA,2OAAO;AACT"}},
{"offset": {"line": 44, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/a.js"],"sourcesContent":["import { x } from './library/x.js'\nimport { y } from './library/y.js'\n\ny()\n\nfunction helper() {\n return x()\n}\n\nexport function unused() {\n return helper()\n}\n\nexport function used() {\n return 1234\n}\n"],"names":[],"mappings":"AACA;;;AAEA,IAAA,gOAAC;AAED,SAAS;IACP,OAAO,IAAA,gOAAC;AACV;AAEO,SAAS;IACd,OAAO;AACT;AAEO,SAAS;IACd,OAAO;AACT"}},
{"offset": {"line": 65, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/index.js"],"sourcesContent":["import { used } from './a.js'\n\nconsole.log(used)\n"],"names":[],"mappings":"AAAA;;AAEA,QAAQ,GAAG,CAAC,wNAAI"}}]
}
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ad3e4_tests_snapshot_remove-unused-imports_exports_input_index_a89415f0.js",
{"otherChunks":["output/780ce_turbopack-tests_tests_snapshot_remove-unused-imports_exports_input_19985db1._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/remove-unused-imports/exports/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
......@@ -31,13 +31,13 @@ pub async fn get_global_module_id_strategy(
// And additionally, all the modules that are inserted by chunking (i.e. async loaders)
let mut async_idents = vec![];
module_graph.traverse_all_edges_unordered(|parent, current| {
if let (
if let Some((
_,
&RefData {
chunking_type: ChunkingType::Async,
..
},
) = parent
)) = parent
{
let module = ResolvedVc::try_sidecast::<Box<dyn ChunkableModule>>(current)
.context("expected chunkable module for async reference")?;
......
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