Unverified Commit 8231b031 authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Drop dead writes to `exports` (#96381)

Drops the dead writes that begun being ignored in
https://github.com/vercel/next.js/pull/96380
parent 1dd15c50
...@@ -103,6 +103,8 @@ pub(super) struct Analyzer<'arena, 'eval> { ...@@ -103,6 +103,8 @@ pub(super) struct Analyzer<'arena, 'eval> {
struct CjsExportsCollector { struct CjsExportsCollector {
/// Recognized `exports.NAME = …` writes, each removable if `NAME` is unused. /// Recognized `exports.NAME = …` writes, each removable if `NAME` is unused.
writes: Vec<DroppableCjsExportAssignment>, writes: Vec<DroppableCjsExportAssignment>,
/// Writes to an exports object a literal discarded, removable whatever the usage.
dead_writes: Vec<DroppableCjsExportAssignment>,
/// Whether the `exports.__esModule = true` interop marker is set. /// Whether the `exports.__esModule = true` interop marker is set.
has_es_module: bool, has_es_module: bool,
/// Whether a `module.exports = { … }` literal has replaced the exports object. /// Whether a `module.exports = { … }` literal has replaced the exports object.
...@@ -662,7 +664,7 @@ mod analyzer_state { ...@@ -662,7 +664,7 @@ mod analyzer_state {
pub(super) fn replace_cjs_exports_object(&mut self) { pub(super) fn replace_cjs_exports_object(&mut self) {
if let Some(c) = &mut self.state.cjs_exports { if let Some(c) = &mut self.state.cjs_exports {
c.writes.clear(); c.dead_writes.append(&mut c.writes);
c.has_es_module = false; c.has_es_module = false;
c.exports_object_replaced = true; c.exports_object_replaced = true;
} }
...@@ -679,6 +681,13 @@ mod analyzer_state { ...@@ -679,6 +681,13 @@ mod analyzer_state {
self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path }); self.push_cjs_export(DroppableCjsExportAssignment::Write { name, path });
} }
pub(super) fn record_dead_cjs_write(&mut self, name: RcStr, path: AstPath) {
if let Some(c) = &mut self.state.cjs_exports {
c.dead_writes
.push(DroppableCjsExportAssignment::Write { name, path });
}
}
/// Records the named exports of a `module.exports = { … }` object literal. They /// Records the named exports of a `module.exports = { … }` object literal. They
/// share `path` (the assignment); the code-gen removes each unused property. /// share `path` (the assignment); the code-gen removes each unused property.
pub(super) fn record_cjs_object_literal_exports( pub(super) fn record_cjs_object_literal_exports(
...@@ -695,15 +704,19 @@ mod analyzer_state { ...@@ -695,15 +704,19 @@ mod analyzer_state {
} }
} }
/// Returns the removable writes and whether the `__esModule` flag is set. /// Returns the removable and always-removable writes, and the `__esModule` flag.
pub(super) fn droppable_cjs_exports( pub(super) fn droppable_cjs_exports(
&mut self, &mut self,
) -> Option<(Vec<DroppableCjsExportAssignment>, bool)> { ) -> Option<(
Vec<DroppableCjsExportAssignment>,
Vec<DroppableCjsExportAssignment>,
bool,
)> {
let c = self.state.cjs_exports.take()?; let c = self.state.cjs_exports.take()?;
if c.writes.is_empty() { if c.writes.is_empty() && c.dead_writes.is_empty() {
return None; return None;
} }
Some((c.writes, c.has_es_module)) Some((c.writes, c.dead_writes, c.has_es_module))
} }
/// Whether `target` is a static named CommonJS export write — /// Whether `target` is a static named CommonJS export write —
...@@ -1345,11 +1358,8 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1345,11 +1358,8 @@ impl<'a> Analyzer<'a, '_> {
return; return;
}; };
// After a replacement only `module.exports` still reaches the exports object. // After a replacement only `module.exports` still reaches the exports object.
if self.cjs_exports_object_replaced() let dead = self.cjs_exports_object_replaced()
&& !is_module_exports_chain(&member.obj, self.eval_context.unresolved_mark) && !is_module_exports_chain(&member.obj, self.eval_context.unresolved_mark);
{
return;
}
let MemberProp::Ident(name) = &member.prop else { let MemberProp::Ident(name) = &member.prop else {
return; return;
}; };
...@@ -1357,7 +1367,7 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1357,7 +1367,7 @@ impl<'a> Analyzer<'a, '_> {
// Transpilers use this to signal that this is transpiled esm. // Transpilers use this to signal that this is transpiled esm.
// Which in turn changes the behavior of default exports. such that `import foo from // Which in turn changes the behavior of default exports. such that `import foo from
// 'transpiled-esm-cjs'` gets the `default` export instead of the namespace // 'transpiled-esm-cjs'` gets the `default` export instead of the namespace
if name.sym.as_ref() == "__esModule" { if !dead && name.sym.as_ref() == "__esModule" {
// Only a literal `true` is the interop marker. // Only a literal `true` is the interop marker.
if matches!(unparen(&n.right), Expr::Lit(Lit::Bool(b)) if b.value) { if matches!(unparen(&n.right), Expr::Lit(Lit::Bool(b)) if b.value) {
self.set_cjs_has_es_module(); self.set_cjs_has_es_module();
...@@ -1366,10 +1376,13 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1366,10 +1376,13 @@ impl<'a> Analyzer<'a, '_> {
} }
// The RHS isn't inspected; the code-gen keeps it as `<value>`. // The RHS isn't inspected; the code-gen keeps it as `<value>`.
self.record_cjs_export( let name = RcStr::from(name.sym.as_str());
RcStr::from(name.sym.as_str()), let path = as_parent_path(ast_path).into();
as_parent_path(ast_path).into(), if dead {
); self.record_dead_cjs_write(name, path);
} else {
self.record_cjs_export(name, path);
}
} }
/// Records a top-level `Object.defineProperty(exports, "NAME", …)` export so /// Records a top-level `Object.defineProperty(exports, "NAME", …)` export so
...@@ -1385,20 +1398,22 @@ impl<'a> Analyzer<'a, '_> { ...@@ -1385,20 +1398,22 @@ impl<'a> Analyzer<'a, '_> {
self.taint_cjs_exports(); self.taint_cjs_exports();
return; return;
} }
if self.cjs_exports_object_replaced() let dead = self.cjs_exports_object_replaced()
&& !n.args.first().is_some_and(|target| { && !n.args.first().is_some_and(|target| {
is_module_exports_chain(&target.expr, self.eval_context.unresolved_mark) is_module_exports_chain(&target.expr, self.eval_context.unresolved_mark)
}) });
{ if !dead && name == "__esModule" {
return;
}
if name == "__esModule" {
if define_property_sets_es_module(n) { if define_property_sets_es_module(n) {
self.set_cjs_has_es_module(); self.set_cjs_has_es_module();
} }
return; return;
} }
self.record_cjs_export(RcStr::from(name), as_parent_path(ast_path).into()); let (name, path) = (RcStr::from(name), as_parent_path(ast_path).into());
if dead {
self.record_dead_cjs_write(name, path);
} else {
self.record_cjs_export(name, path);
}
} }
/// Records the droppable named exports of a top-level `module.exports = { … }` /// Records the droppable named exports of a top-level `module.exports = { … }`
...@@ -2422,9 +2437,9 @@ impl VisitAstPath for Analyzer<'_, '_> { ...@@ -2422,9 +2437,9 @@ impl VisitAstPath for Analyzer<'_, '_> {
self.data.effects = take(&mut self.effects).into_iter().collect(); self.data.effects = take(&mut self.effects).into_iter().collect();
// Emit the CommonJS unused-export drop code-gen, if any. // Emit the CommonJS unused-export drop code-gen, if any.
if let Some((drops, has_es_module)) = self.droppable_cjs_exports() { if let Some((drops, dead_writes, has_es_module)) = self.droppable_cjs_exports() {
self.code_gens self.code_gens
.push(CjsExportsDropCodeGen::new(drops, has_es_module).into()); .push(CjsExportsDropCodeGen::new(drops, dead_writes, has_es_module).into());
} }
self.data.code_gens = take(&mut self.code_gens); self.data.code_gens = take(&mut self.code_gens);
......
...@@ -440,6 +440,8 @@ impl From<CjsRequireCacheAccess> for CodeGen { ...@@ -440,6 +440,8 @@ impl From<CjsRequireCacheAccess> for CodeGen {
)] )]
pub struct CjsExportsDropCodeGen { pub struct CjsExportsDropCodeGen {
drops: Vec<DroppableCjsExportAssignment>, drops: Vec<DroppableCjsExportAssignment>,
/// Writes to a discarded exports object, dropped whatever the export usage is.
dead_writes: Vec<DroppableCjsExportAssignment>,
/// Whether the module sets `__esModule`. Without it, a default import binds /// Whether the module sets `__esModule`. Without it, a default import binds
/// the whole `module.exports`, so nothing may be dropped. /// the whole `module.exports`, so nothing may be dropped.
has_es_module: bool, has_es_module: bool,
...@@ -459,9 +461,14 @@ pub enum DroppableCjsExportAssignment { ...@@ -459,9 +461,14 @@ pub enum DroppableCjsExportAssignment {
} }
impl CjsExportsDropCodeGen { impl CjsExportsDropCodeGen {
pub fn new(drops: Vec<DroppableCjsExportAssignment>, has_es_module: bool) -> Self { pub fn new(
drops: Vec<DroppableCjsExportAssignment>,
dead_writes: Vec<DroppableCjsExportAssignment>,
has_es_module: bool,
) -> Self {
CjsExportsDropCodeGen { CjsExportsDropCodeGen {
drops, drops,
dead_writes,
has_es_module, has_es_module,
} }
} }
...@@ -478,20 +485,24 @@ impl CjsExportsDropCodeGen { ...@@ -478,20 +485,24 @@ impl CjsExportsDropCodeGen {
let export_usage_info = export_usage_info.export_usage.await?; let export_usage_info = export_usage_info.export_usage.await?;
// Without `__esModule`, a default import binds the whole `module.exports`, // Without `__esModule`, a default import binds the whole `module.exports`,
// so a used `default` makes every named export reachable — drop nothing. // so a used `default` makes every named export reachable — drop none of these.
if !self.has_es_module && export_usage_info.is_export_used(&rcstr!("default")) { let drops = if !self.has_es_module && export_usage_info.is_export_used(&rcstr!("default")) {
return Ok(CodeGeneration::empty()); &[]
} } else {
&self.drops[..]
};
// Replace each unused `exports.NAME = <value>` with `<value>`, preserving // Replace each unused `exports.NAME = <value>` with `<value>`, preserving
// side effects (the minifier drops a pure value). Rewriting the assignment // side effects (the minifier drops a pure value). Rewriting the assignment
// rather than its statement keeps chained writes like // rather than its statement keeps chained writes like
// `exports.a = exports.b = 1` sound. // `exports.a = exports.b = 1` sound.
let mut visitors = Vec::new(); let mut visitors = Vec::new();
for drop in &self.drops { for (drop, dead) in (self.dead_writes.iter().map(|drop| (drop, true)))
.chain(drops.iter().map(|drop| (drop, false)))
{
match drop { match drop {
DroppableCjsExportAssignment::Write { name, path } => { DroppableCjsExportAssignment::Write { name, path } => {
if export_usage_info.is_export_used(name) { if !dead && export_usage_info.is_export_used(name) {
continue; continue;
} }
visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| { visitors.push(create_visitor!(path, visit_mut_expr, |expr: &mut Expr| {
...@@ -516,7 +527,7 @@ impl CjsExportsDropCodeGen { ...@@ -516,7 +527,7 @@ impl CjsExportsDropCodeGen {
DroppableCjsExportAssignment::ObjectLiteral { names, path } => { DroppableCjsExportAssignment::ObjectLiteral { names, path } => {
let unused = names let unused = names
.iter() .iter()
.filter(|name| !export_usage_info.is_export_used(name)) .filter(|name| dead || !export_usage_info.is_export_used(name))
.cloned() .cloned()
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if unused.is_empty() { if unused.is_empty() {
......
...@@ -10,17 +10,15 @@ __turbopack_context__.s([]); ...@@ -10,17 +10,15 @@ __turbopack_context__.s([]);
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/lib.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/lib.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
// Discarded by the literal below, so not an export. // Discarded by the literal below, so not an export.
exports.early = 'early-value'; 'early-value';
module.exports = { module.exports = {
used: 'used-value', used: 'used-value',
...void 'unused-value' ...void 'unused-value'
}; };
// Not exports: `exports` and top-level `this` hold the object the literal discarded. // Not exports: `exports` and top-level `this` hold the object the literal discarded.
exports.deadExports = 'dead-exports'; 'dead-exports';
/*TURBOPACK member replacement*/ __turbopack_context__.e.deadThis = 'dead-this'; 'dead-this';
Object.defineProperty(exports, 'deadDefined', { 'dead-defined';
value: 'dead-defined'
});
// Exports: `module.exports` is the live object. // Exports: `module.exports` is the live object.
module.exports.usedLate = 'used-late'; module.exports.usedLate = 'used-late';
'unused-late'; 'unused-late';
......
...@@ -3,5 +3,5 @@ ...@@ -3,5 +3,5 @@
"sources": [], "sources": [],
"sections": [ "sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/index.js"],"sourcesContent":["import { used, usedLate } from './lib.js'\n\nconsole.log(used, usedLate)\n"],"names":["console","log"],"mappings":"AAAA;;AAEAA,QAAQC,GAAG,CAAC,kQAAI,EAAE,sQAAQ"}}, {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/index.js"],"sourcesContent":["import { used, usedLate } from './lib.js'\n\nconsole.log(used, usedLate)\n"],"names":["console","log"],"mappings":"AAAA;;AAEAA,QAAQC,GAAG,CAAC,kQAAI,EAAE,sQAAQ"}},
{"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/lib.js"],"sourcesContent":["// Discarded by the literal below, so not an export.\nexports.early = 'early-value'\n\nmodule.exports = {\n used: 'used-value',\n unused: 'unused-value',\n}\n\n// Not exports: `exports` and top-level `this` hold the object the literal discarded.\nexports.deadExports = 'dead-exports'\nthis.deadThis = 'dead-this'\nObject.defineProperty(exports, 'deadDefined', { value: 'dead-defined' })\n\n// Exports: `module.exports` is the live object.\nmodule.exports.usedLate = 'used-late'\nmodule.exports.unusedLate = 'unused-late'\n"],"names":["exports","early","module","used","deadExports","deadThis","Object","defineProperty","value","usedLate"],"mappings":"AAAA,oDAAoD;AACpDA,QAAQC,KAAK,GAAG;AAEhBC,OAAOF,OAAO,GAAG;IACfG,MAAM;YACE;AACV;AAEA,qFAAqF;AACrFH,QAAQI,WAAW,GAAG;AACtB,yDAAKC,QAAQ,GAAG;AAChBC,OAAOC,cAAc,CAACP,SAAS,eAAe;IAAEQ,OAAO;AAAe;AAEtE,gDAAgD;AAChDN,OAAOF,OAAO,CAACS,QAAQ,GAAG;AACE"}}] {"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/cjs-remove-unused-exports/object-literal-replaces-exports/input/lib.js"],"sourcesContent":["// Discarded by the literal below, so not an export.\nexports.early = 'early-value'\n\nmodule.exports = {\n used: 'used-value',\n unused: 'unused-value',\n}\n\n// Not exports: `exports` and top-level `this` hold the object the literal discarded.\nexports.deadExports = 'dead-exports'\nthis.deadThis = 'dead-this'\nObject.defineProperty(exports, 'deadDefined', { value: 'dead-defined' })\n\n// Exports: `module.exports` is the live object.\nmodule.exports.usedLate = 'used-late'\nmodule.exports.unusedLate = 'unused-late'\n"],"names":["module","exports","used","usedLate"],"mappings":"AAAA,oDAAoD;AACpC;AAEhBA,OAAOC,OAAO,GAAG;IACfC,MAAM;YACE;AACV;AAEA,qFAAqF;AAC/D;AACN;AACuC;AAEvD,gDAAgD;AAChDF,OAAOC,OAAO,CAACE,QAAQ,GAAG;AACE"}}]
} }
\ No newline at end of file
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