Unverified Commit 53276537 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Do the CJS analysis needed for scope hoisting (#95826)

This PR does two things: adds a flag `turbopackCjsScopeHoisting` and
plumbs it through and adds the extra stuff we need in
`turbopack/crates/turbopack-ecmascript/src/analyzer/graph/visitor.rs`
(just the names of the things exported by CJS) for PRs down the stack to
work.
parent 268ae984
......@@ -62,7 +62,7 @@ pub async fn get_middleware_module(
has_default || has_named
}
// CommonJS modules are valid (they can have module.exports or exports.default)
EcmascriptExports::CommonJs | EcmascriptExports::Value => true,
EcmascriptExports::CommonJs(_) | EcmascriptExports::Value => true,
// DynamicNamespace might be valid for certain module types
EcmascriptExports::DynamicNamespace => true,
// None/Unknown likely indicate parsing errors - skip validation
......
......@@ -371,6 +371,7 @@ pub async fn get_client_module_options_context(
source_maps,
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
preset_env_config,
..Default::default()
},
......
......@@ -1431,6 +1431,8 @@ pub struct ExperimentalConfig {
turbopack_infer_module_side_effects: Option<bool>,
/// Enable tree shaking of unused exports from static CommonJS modules. Defaults to false.
turbopack_cjs_tree_shaking: Option<bool>,
/// Enable scope hoisting of static CommonJS modules. Defaults to false.
turbopack_cjs_scope_hoisting: Option<bool>,
/// Devtool option for the segment explorer.
devtool_segment_explorer: Option<bool>,
/// Whether to report inlined system environment variables as warnings or errors.
......@@ -2543,6 +2545,15 @@ impl NextConfig {
)
}
#[turbo_tasks::function]
pub fn turbopack_cjs_scope_hoisting(&self) -> Vc<bool> {
Vc::cell(
self.experimental
.turbopack_cjs_scope_hoisting
.unwrap_or(false),
)
}
#[turbo_tasks::function]
pub fn turbopack_plugin_runtime_strategy(&self) -> Vc<TurbopackPluginRuntimeStrategy> {
#[cfg(feature = "process_pool")]
......
......@@ -548,6 +548,7 @@ pub async fn get_server_module_options_context(
source_maps,
infer_module_side_effects: *next_config.turbopack_infer_module_side_effects().await?,
cjs_tree_shaking: *next_config.turbopack_cjs_tree_shaking().await?,
cjs_scope_hoisting: *next_config.turbopack_cjs_scope_hoisting().await?,
..Default::default()
},
execution_context: Some(execution_context),
......
......@@ -125,7 +125,7 @@ impl ChunkableModule for RawEcmascriptModule {
impl EcmascriptChunkPlaceable for RawEcmascriptModule {
#[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> {
EcmascriptExports::CommonJs.cell()
EcmascriptExports::CommonJs(None).cell()
}
#[turbo_tasks::function]
......
......@@ -417,6 +417,7 @@ export const experimentalSchema = {
turbopackModuleIds: z.enum(['named', 'deterministic']).optional(),
turbopackInferModuleSideEffects: z.boolean().optional(),
turbopackCjsTreeShaking: z.boolean().optional(),
turbopackCjsScopeHoisting: z.boolean().optional(),
turbopackServerFastRefresh: z.boolean().optional(),
optimizePackageImports: z.array(z.string()).optional(),
optimizeServerReact: z.boolean().optional(),
......
......@@ -965,6 +965,13 @@ export interface ExperimentalConfig {
*/
turbopackCjsTreeShaking?: boolean
/**
* Enable scope hoisting of static CommonJS modules.
*
* Defaults to `false`
*/
turbopackCjsScopeHoisting?: boolean
/**
* Set this to `false` to disable the automatic configuration of the babel loader when a Babel
* configuration file is present. This option is enabled by default.
......
......@@ -86,6 +86,7 @@ pub fn benchmark(c: &mut Criterion) {
true,
SpecifiedModuleType::Automatic,
true,
false,
));
let input = BenchInput {
......@@ -124,6 +125,7 @@ fn bench_create_graph(b: &mut Bencher, input: &BenchInput) {
true,
SpecifiedModuleType::Automatic,
true,
false,
));
});
}
......
......@@ -15,6 +15,7 @@ pub use crate::analyzer::graph::{
use crate::{
AnalyzeMode, SpecifiedModuleType,
analyzer::{Bump, JsValue, graph::visitor::Analyzer},
chunk::CjsStaticExports,
code_gen::CodeGen,
};
......@@ -39,6 +40,10 @@ pub struct VarGraph<'a> {
/// [`ExportUsage`] per `require("…")` call, keyed by call position; absent
/// calls fall back to `ExportUsage::All`.
pub require_usage: FxHashMap<BytePos, ExportUsage>,
/// Present when the module is a statically-analyzable CommonJS module (no
/// dynamic exports); carries its named exports for scope hoisting.
pub cjs_static_exports: Option<CjsStaticExports>,
}
impl<'a> VarGraph<'a> {
......@@ -60,6 +65,7 @@ pub fn create_graph<'a>(
supports_block_scoping: bool,
specified_module_type: SpecifiedModuleType,
cjs_tree_shaking: bool,
cjs_scope_hoisting: bool,
) -> VarGraph<'a> {
let mut analyzer = Analyzer {
arena,
......@@ -70,6 +76,7 @@ pub fn create_graph<'a>(
effects: Default::default(),
code_gens: Default::default(),
require_usage: Default::default(),
cjs_static_exports: Default::default(),
},
eval_context,
state: Default::default(),
......@@ -79,9 +86,11 @@ pub fn create_graph<'a>(
supports_block_scoping,
};
// CommonJS export recognition runs only for a CommonJS module that emits code, and only
// when the `turbopackCjsTreeShaking` experimental flag is enabled.
if cjs_tree_shaking && analyze_mode.is_code_gen() && eval_context.is_cjs(specified_module_type)
// CommonJS export recognition runs for a CommonJS module that emits code when either CJS
// tree-shaking or CJS scope hoisting is enabled (both consume the static export analysis).
if (cjs_tree_shaking || cjs_scope_hoisting)
&& analyze_mode.is_code_gen()
&& eval_context.is_cjs(specified_module_type)
{
analyzer.enable_cjs_exports();
}
......
......@@ -29,6 +29,7 @@ use crate::{
graph::{ConditionalKind, Effect, EffectArg, EffectsBlock, EvalContext, VarGraph},
is_unresolved_id,
},
chunk::CjsStaticExports,
code_gen::CodeGen,
references::{
AstPath,
......@@ -109,8 +110,21 @@ struct CjsExportsCollector {
has_es_module: bool,
/// Whether a `module.exports = { … }` literal has replaced the exports object.
exports_object_replaced: bool,
/// Whether the module body contains a top-level `return`, which skips every
/// write that follows it.
has_top_level_return: bool,
/// Whether any export is defined with `Object.defineProperty`.
has_define_property_export: bool,
}
/// The removable writes, the always-removable ones, and whether the `__esModule`
/// interop marker is set.
type CjsExportDrops = (
Vec<DroppableCjsExportAssignment>,
Vec<DroppableCjsExportAssignment>,
bool,
);
trait FunctionLike {
fn is_async(&self) -> bool {
false
......@@ -677,6 +691,20 @@ mod analyzer_state {
}
}
/// Records a `return` in the module body, which exits the module early.
pub(super) fn set_cjs_has_top_level_return(&mut self) {
if let Some(c) = &mut self.state.cjs_exports {
c.has_top_level_return = true;
}
}
/// Records that an export is defined with `Object.defineProperty`.
pub(super) fn set_cjs_has_define_property_export(&mut self) {
if let Some(c) = &mut self.state.cjs_exports {
c.has_define_property_export = true;
}
}
pub(super) fn record_cjs_export(&mut self, name: RcStr, path: AstPath) {
self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path });
}
......@@ -704,19 +732,45 @@ mod analyzer_state {
}
}
/// Returns the removable and always-removable writes, and the `__esModule` flag.
pub(super) fn droppable_cjs_exports(
/// Returns the removable and always-removable writes and the `__esModule` flag,
/// plus the static-exports for scope hoisting.
pub(super) fn cjs_exports_analysis(
&mut self,
) -> Option<(
Vec<DroppableCjsExportAssignment>,
Vec<DroppableCjsExportAssignment>,
bool,
)> {
let c = self.state.cjs_exports.take()?;
if c.writes.is_empty() && c.dead_writes.is_empty() {
return None;
}
Some((c.writes, c.dead_writes, c.has_es_module))
) -> (Option<CjsExportDrops>, Option<CjsStaticExports>) {
let Some(c) = self.state.cjs_exports.take() else {
return (None, None);
};
// A top-level `return` skips the writes after it, and would abandon the rest
// of a merged factory. An `Object.defineProperty` export keeps its value in
// the descriptor, which the merge has no local to bind it to.
let static_exports =
(!c.has_top_level_return && !c.has_define_property_export).then(|| {
CjsStaticExports {
export_names: c
.writes
.iter()
.flat_map(|w| match w {
DroppableCjsExportAssignment::Write { name, .. } => {
std::slice::from_ref(name)
}
DroppableCjsExportAssignment::ObjectLiteral { names, .. } => {
names.as_slice()
}
})
.cloned()
.collect(),
has_es_module: c.has_es_module,
}
});
// Dropping an unused write stays sound regardless of the `return`, but
// `__esModule` may be set after it, so it can't be claimed.
let has_es_module = c.has_es_module && !c.has_top_level_return;
let drops = (!c.writes.is_empty() || !c.dead_writes.is_empty()).then_some((
c.writes,
c.dead_writes,
has_es_module,
));
(drops, static_exports)
}
/// Whether `target` is a static named CommonJS export write —
......@@ -1412,6 +1466,7 @@ impl<'a> Analyzer<'a, '_> {
if dead {
self.record_dead_cjs_write(name, path);
} else {
self.set_cjs_has_define_property_export();
self.record_cjs_export(name, path);
}
}
......@@ -2266,6 +2321,8 @@ impl VisitAstPath for Analyzer<'_, '_> {
.unwrap_or(JsValue::Constant(ConstantValue::Undefined));
self.add_return_value(return_value);
} else {
self.set_cjs_has_top_level_return();
}
self.add_early_return_always(ast_path);
......@@ -2436,11 +2493,14 @@ impl VisitAstPath for Analyzer<'_, '_> {
.extend(self.arena, take(&mut self.hoisted_effects));
self.data.effects = take(&mut self.effects).into_iter().collect();
// Emit the CommonJS unused-export drop code-gen, if any.
if let Some((drops, dead_writes, has_es_module)) = self.droppable_cjs_exports() {
// Emit the CommonJS unused-export drop code-gen, if any, and surface the
// static-exports for scope hoisting.
let (drops, cjs_static_exports) = self.cjs_exports_analysis();
if let Some((drops, dead_writes, has_es_module)) = drops {
self.code_gens
.push(CjsExportsDropCodeGen::new(drops, dead_writes, has_es_module).into());
}
self.data.cjs_static_exports = cjs_static_exports;
self.data.code_gens = take(&mut self.code_gens);
}
......
......@@ -366,6 +366,7 @@ mod tests {
true,
SpecifiedModuleType::EcmaScript,
true,
false,
);
anyhow::Ok((eval_context, var_graph))
})?;
......
......@@ -41,7 +41,7 @@ pub use self::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkItemExt,
EcmascriptChunkItemOptions, EcmascriptChunkItemWithAsyncInfo, ecmascript_chunk_item,
},
placeable::{EcmascriptChunkPlaceable, EcmascriptExports},
placeable::{CjsStaticExports, EcmascriptChunkPlaceable, EcmascriptExports},
};
#[turbo_tasks::value]
......
......@@ -2,7 +2,7 @@ use anyhow::Result;
use async_trait::async_trait;
use either::Either;
use itertools::Itertools;
use turbo_rcstr::rcstr;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{PrettyPrintError, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::{
FileJsonContent, FileSystemPath,
......@@ -272,7 +272,10 @@ pub enum EcmascriptExports {
/// A module using `__turbopack_export_namespace__`, used by custom module types.
DynamicNamespace,
/// A module using CommonJS exports.
CommonJs,
///
/// Carries the static export names when statically analyzable, for scope hoisting.
/// `None` means that the exports were not analyzable by us.
CommonJs(Option<CjsStaticExports>),
/// No exports at all, and falling back to CommonJS semantics.
EmptyCommonJs,
/// A value that is made available as both the CommonJS `exports` and the ESM default export.
......@@ -307,3 +310,14 @@ impl EcmascriptExports {
})
}
}
/// A statically-analyzable CommonJS module's named exports, for scope hoisting.
/// See the analyzer's `CjsExportsCollector`.
#[derive(Clone, Debug, Hash)]
#[turbo_tasks::value(shared)]
pub struct CjsStaticExports {
/// Recognized `exports.NAME` / `module.exports.NAME` names, in source order.
pub export_names: Vec<RcStr>,
/// Whether `exports.__esModule = true` is set.
pub has_es_module: bool,
}
......@@ -239,6 +239,7 @@ pub struct EcmascriptOptions {
pub infer_module_side_effects: bool,
/// Whether to tree shake unused exports from static CommonJS modules. Defaults to false.
pub cjs_tree_shaking: bool,
pub cjs_scope_hoisting: bool,
}
#[turbo_tasks::value(task_input)]
......@@ -853,7 +854,14 @@ impl ChunkableModule for EcmascriptModuleAsset {
impl EcmascriptChunkPlaceable for EcmascriptModuleAsset {
#[turbo_tasks::function]
async fn get_exports(self: Vc<Self>) -> Result<Vc<EcmascriptExports>> {
Ok(*compute_ecmascript_module_exports(self, None).await?.exports)
let exports = compute_ecmascript_module_exports(self, None).await?.exports;
if let EcmascriptExports::CommonJs(_) = &*exports.await? {
return Ok(EcmascriptExports::CommonJs(
self.analyze().await?.cjs_static_exports.clone(),
)
.cell());
}
Ok(*exports)
}
#[turbo_tasks::function]
......
......@@ -83,7 +83,7 @@ pub async fn is_export_missing(
EcmascriptExports::None => return Ok(Vc::cell(true)),
EcmascriptExports::Unknown => return Ok(Vc::cell(false)),
EcmascriptExports::Value => return Ok(Vc::cell(false)),
EcmascriptExports::CommonJs => return Ok(Vc::cell(false)),
EcmascriptExports::CommonJs(_) => return Ok(Vc::cell(false)),
EcmascriptExports::EmptyCommonJs => return Ok(Vc::cell(export_name != "default")),
EcmascriptExports::DynamicNamespace => return Ok(Vc::cell(false)),
EcmascriptExports::EsmExports(exports) => *exports,
......@@ -110,7 +110,7 @@ pub async fn is_export_missing(
let exports = dynamic_module.get_exports().await?;
match &*exports {
EcmascriptExports::Value
| EcmascriptExports::CommonJs
| EcmascriptExports::CommonJs(_)
| EcmascriptExports::DynamicNamespace
| EcmascriptExports::Unknown => {
return Ok(Vc::cell(false));
......@@ -479,7 +479,7 @@ pub async fn expand_star_exports(
)
.await?
}
EcmascriptExports::CommonJs => {
EcmascriptExports::CommonJs(_) => {
dynamic_exporting_modules.push(asset);
emit_star_exports_issue(
asset.ident(),
......
......@@ -216,7 +216,7 @@ pub async fn compute_ecmascript_module_exports(
}
} else {
match detect_dynamic_export(program) {
DetectedDynamicExportType::CommonJs => EcmascriptExports::CommonJs,
DetectedDynamicExportType::CommonJs => EcmascriptExports::CommonJs(None),
DetectedDynamicExportType::Namespace => EcmascriptExports::DynamicNamespace,
DetectedDynamicExportType::Value => EcmascriptExports::Value,
DetectedDynamicExportType::UsingModuleDeclarations => {
......
......@@ -377,7 +377,7 @@ impl EcmascriptChunkPlaceable for CachedExternalModule {
#[turbo_tasks::function]
fn get_exports(&self) -> Vc<EcmascriptExports> {
if self.external_type == CachedExternalType::CommonJs {
EcmascriptExports::CommonJs.cell()
EcmascriptExports::CommonJs(None).cell()
} else {
EcmascriptExports::DynamicNamespace.cell()
}
......
......@@ -111,6 +111,7 @@ use crate::{
top_level_await::has_top_level_await,
well_known::replace_well_known,
},
chunk::CjsStaticExports,
code_gen::{CodeGen, CodeGens, IntoCodeGenReference},
errors,
module_fragments::{part_of_module, split_module},
......@@ -166,6 +167,9 @@ pub struct AnalyzeEcmascriptModuleResult {
/// `true` when the analysis was successful.
pub successful: bool,
pub source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>,
/// Present when the module is a statically-analyzable CommonJS module;
/// carries its named exports for scope hoisting.
pub cjs_static_exports: Option<CjsStaticExports>,
}
#[turbo_tasks::value_impl]
......@@ -223,6 +227,7 @@ struct AnalyzeEcmascriptModuleResultBuilder {
successful: bool,
source_map: Option<ResolvedVc<Box<dyn GenerateSourceMap>>>,
side_effects: ModuleSideEffects,
cjs_static_exports: Option<CjsStaticExports>,
#[cfg(debug_assertions)]
ident: RcStr,
}
......@@ -242,6 +247,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
successful: false,
source_map: None,
side_effects: ModuleSideEffects::SideEffectful,
cjs_static_exports: None,
#[cfg(debug_assertions)]
ident: Default::default(),
}
......@@ -428,6 +434,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
side_effects: self.side_effects,
successful: self.successful,
source_map: self.source_map,
cjs_static_exports: self.cjs_static_exports,
},
))
}
......@@ -826,6 +833,7 @@ async fn analyze_ecmascript_module_internal(
supports_block_scoping,
specified_type,
options.cjs_tree_shaking,
options.cjs_scope_hoisting,
));
});
graph.unwrap()
......@@ -837,6 +845,8 @@ async fn analyze_ecmascript_module_internal(
let effects = take(&mut var_graph.effects);
// How each `require("…")` call's result is used, keyed by call position.
let require_binding_usage = take(&mut var_graph.require_usage);
// The module's static CommonJS exports, if any, for scope hoisting.
analysis.cjs_static_exports = take(&mut var_graph.cjs_static_exports);
let compile_time_info_ref = compile_time_info.await?;
let mut analysis_state = AnalysisState {
......
......@@ -279,6 +279,8 @@ struct TestOptions {
#[serde(default)]
cjs_tree_shaking: bool,
#[serde(default)]
cjs_scope_hoisting: bool,
#[serde(default)]
minify: bool,
#[serde(default)]
production_chunking: bool,
......@@ -301,6 +303,7 @@ impl Default for TestOptions {
remove_unused_imports: default_true(),
scope_hoisting: default_true(),
cjs_tree_shaking: false,
cjs_scope_hoisting: false,
minify: false,
production_chunking: false,
side_effect_free_packages: Vec::new(),
......@@ -465,6 +468,7 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
enable_exports_info_inlining: true,
infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking,
cjs_scope_hoisting: options.cjs_scope_hoisting,
..Default::default()
},
environment: Some(env),
......
......@@ -96,6 +96,8 @@ struct SnapshotOptions {
#[serde(default)]
cjs_tree_shaking: bool,
#[serde(default)]
cjs_scope_hoisting: bool,
#[serde(default)]
scope_hoisting: bool,
#[serde(default)]
shared_runtime: bool,
......@@ -141,6 +143,7 @@ impl Default for SnapshotOptions {
remove_unused_imports: false,
remove_unused_exports: false,
cjs_tree_shaking: false,
cjs_scope_hoisting: false,
scope_hoisting: false,
shared_runtime: false,
production_chunking: false,
......@@ -416,6 +419,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
ignore_dynamic_requests: true,
infer_module_side_effects: true,
cjs_tree_shaking: options.cjs_tree_shaking,
cjs_scope_hoisting: options.cjs_scope_hoisting,
enable_exports_info_inlining: true,
enable_rust_react_compiler: options
.enable_rust_react_compiler
......
......@@ -247,6 +247,7 @@ impl ModuleOptions {
inline_helpers,
infer_module_side_effects,
cjs_tree_shaking,
cjs_scope_hoisting,
ref preset_env_config,
..
},
......@@ -340,6 +341,7 @@ impl ModuleOptions {
inline_helpers,
infer_module_side_effects,
cjs_tree_shaking,
cjs_scope_hoisting,
..Default::default()
};
let ecmascript_options_vc = ecmascript_options.resolved_cell();
......
......@@ -284,6 +284,8 @@ pub struct EcmascriptOptionsContext {
/// Whether to tree shake unused exports from static CommonJS modules. Defaults to false.
pub cjs_tree_shaking: bool,
/// Whether to scope-hoist static CommonJS modules. Defaults to false.
pub cjs_scope_hoisting: bool,
/// Additional SWC preset-env options (mode, coreJs, include, exclude, etc.).
pub preset_env_config: Option<ResolvedVc<PresetEnvConfig>>,
......
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