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

turbopack: narrow namespace destructuring member usage

Treat object destructuring of a namespace value, or of a static member chain
on it, like static member reads: `const { core: { X } } = lib` and
`const { X } = lib.core` only mark `X` used. Rest elements and computed
non-literal keys keep the whole namespace at that level.

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 7a836e76
......@@ -37,7 +37,10 @@ use crate::{
cjs::{CjsExportsDropCodeGen, DroppableCjsExportAssignment},
esm::EsmModuleItem,
},
utils::{AstPathRange, extract_name_from_member_prop, extract_names_from_object_pat, unparen},
utils::{
AstPathRange, extract_member_usage_from_object_pat, extract_name_from_member_prop,
extract_names_from_object_pat, unparen,
},
};
enum EarlyReturn<'a> {
......@@ -630,6 +633,25 @@ mod analyzer_state {
members
}
/// If the ident at the end of `ast_path`, read through its first `chain_len` static
/// members, is destructured by a variable declaration (`const { a, b } = ident.x.y`),
/// returns the members read by that pattern.
pub(super) fn destructured_members(
&self,
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
chain_len: usize,
) -> Option<BTreeMap<RcStr, MemberUsage>> {
// Each member level adds a `MemberExpr(_, Obj)` and an `Expr(_, Member)` above the
// ident's own `Expr(_, Ident)`, see `member_access_ancestors`.
let index = ast_path.len().checked_sub(2 + 2 * chain_len)?;
match ast_path.get(index)? {
AstParentNodeRef::VarDeclarator(decl, VarDeclaratorField::Init) => {
extract_member_usage_from_object_pat(&decl.name)
}
_ => None,
}
}
/// Records a tracked `const x = require(...)` is used.
pub(super) fn record_require_usage(&mut self, id: &Id, member: Option<RcStr>) {
let Some(span) = self
......@@ -917,10 +939,17 @@ fn member_access_parent<'r>(
}
}
/// The member usage of a static member path: `{ a: { b: All } }` for `[a, b]`, and empty (the
/// value is read as a whole) for an empty path.
fn member_path_tree(path: &[RcStr]) -> BTreeMap<RcStr, MemberUsage> {
match MemberUsage::from_path(path) {
/// The member usage of a static member path, optionally destructured at its end: `{ a: { b: All }
/// }` for `[a, b]`, `{ a: { b: { c: All } } }` for `const { c } = value.a.b`, and empty (the value
/// is read as a whole) for an empty path that isn't destructured.
fn member_path_tree(
path: &[RcStr],
destructured: Option<BTreeMap<RcStr, MemberUsage>>,
) -> BTreeMap<RcStr, MemberUsage> {
let leaf = destructured.map_or(MemberUsage::All, MemberUsage::Members);
match path.iter().rev().fold(leaf, |inner, member| {
MemberUsage::Members(BTreeMap::from([(member.clone(), inner)]))
}) {
MemberUsage::Members(members) => members,
MemberUsage::All => BTreeMap::new(),
}
......@@ -2566,7 +2595,8 @@ impl VisitAstPath for Analyzer<'_, '_> {
// may read any of its members: keep that receiver whole.
path.pop();
}
let members = member_path_tree(&path);
let destructured = self.destructured_members(ast_path, 1 + path.len());
let members = member_path_tree(&path, destructured);
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: Some(prop_str.into()),
......@@ -2585,7 +2615,16 @@ impl VisitAstPath for Analyzer<'_, '_> {
// `fn`, like a namespace import's `ns.fn()` does.)
path.pop();
}
member_path_tree(&path)
let destructured = self.destructured_members(ast_path, path.len());
member_path_tree(&path, destructured)
} else if !self
.eval_context
.imports
.should_import_all(esm_reference_index)
&& let Some(destructured) = self.destructured_members(ast_path, 0)
{
// `const { a, b } = ns` only reads these exports of a namespace import.
destructured
} else {
BTreeMap::new()
};
......
......@@ -44,7 +44,10 @@ use crate::{
esm::{EsmAssetReference, EsmExport, Liveness},
util::{SpecifiedChunkingType, parse_chunking_type_annotation},
},
utils::{extract_name_from_member_prop, extract_names_from_object_pat, unparen},
utils::{
extract_member_usage_from_object_pat, extract_name_from_member_prop,
extract_names_from_object_pat, unparen,
},
};
#[turbo_tasks::value]
......@@ -1706,6 +1709,19 @@ impl Visit for Analyzer<'_> {
fn visit_var_declarator(&mut self, node: &VarDeclarator) {
self.record_require_usage_var(node);
// `const { a, b } = ns` only reads statically known members of a namespace import, like
// `ns.a` does. Skip `visit_expr` for `ns` so that it isn't added to `full_star_imports`.
if let Some(init) = &node.init
&& let Expr::Ident(ident) = &**init
&& self
.namespace_imports_to_specifier
.contains_key(&ident.to_id())
&& extract_member_usage_from_object_pat(&node.name).is_some_and(|m| !m.is_empty())
{
node.name.visit_with(self);
ident.visit_with(self);
return;
}
node.visit_children_with(self);
}
......
use std::collections::BTreeMap;
use anyhow::{Result, bail};
use async_trait::async_trait;
use bincode::{Decode, Encode};
......@@ -29,8 +31,8 @@ use turbopack_core::{
reference::ModuleReference,
reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::{
BindingUsage, ExportUsage, ExternalType, ImportUsage, ModulePart, ModuleResolveResult,
ModuleResolveResultItem, RequestKey, ResolveErrorMode,
BindingUsage, ExportUsage, ExternalType, ImportUsage, MemberUsage, ModulePart,
ModuleResolveResult, ModuleResolveResultItem, RequestKey, ResolveErrorMode,
origin::{ResolveOrigin, ResolveOriginExt},
parse::Request,
resolve,
......@@ -491,6 +493,9 @@ struct EsmReferenceExtras {
export_usage_passthrough: Option<bool>,
/// See [`EsmAssetReferenceOptions::namespace_reexport_exports`].
namespace_reexport_exports: Option<SmallVec<[RcStr; 1]>>,
/// For a namespace import that is only destructured (`const { a, b } = ns`), the (possibly
/// nested) members read from the namespace object.
namespace_members: Option<BTreeMap<RcStr, MemberUsage>>,
/// A module to resolve to directly, bypassing resolution (from a matched inner asset).
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
......@@ -526,6 +531,7 @@ impl EsmReferenceExtras {
annotations.is_some_and(|a| a.export_usage_passthrough()),
),
namespace_reexport_exports,
namespace_members: None,
resolve_override,
};
(extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
......@@ -654,6 +660,26 @@ impl EsmAssetReference {
}
}
/// Builds a copy of this namespace import reference for a namespace object of which only
/// `members` are read (`import * as ns from 'foo'; const { a, b } = ns`). It still resolves to
/// the whole namespace object.
pub fn rewrite_for_namespace_members(&self, members: BTreeMap<RcStr, MemberUsage>) -> Self {
let mut extras = self.extras.as_deref().cloned().unwrap_or_default();
extras.namespace_members = Some(members);
EsmAssetReference {
module: self.module,
origin: self.origin,
request: self.request.clone(),
issue_source: self.issue_source,
export_name: self.export_name.clone(),
import_usage: self.import_usage.clone(),
import_externals: self.import_externals,
module_fragments_enabled: self.module_fragments_enabled,
is_pure_import: self.is_pure_import,
extras: Some(Box::new(extras)),
}
}
pub(crate) fn get_referenced_asset(
self: Vc<Self>,
) -> impl Future<Output = Result<ReferencedAsset>> {
......@@ -777,6 +803,7 @@ impl ModuleReference for EsmAssetReference {
let export_usage_passthrough = extras.and_then(|extras| extras.export_usage_passthrough);
let namespace_reexport_exports =
extras.and_then(|extras| extras.namespace_reexport_exports.as_ref());
let namespace_members = extras.and_then(|extras| extras.namespace_members.as_ref());
BindingUsage {
import: self.import_usage.clone(),
export: match (&self.export_name, export_usage_passthrough) {
......@@ -796,11 +823,18 @@ impl ModuleReference for EsmAssetReference {
// reads on the resolved target.
ExportUsage::named_members(export.clone(), members.clone())
}
(None, _) => match namespace_reexport_exports {
Some(exports) => ExportUsage::NamespaceReexport {
(None, _) => match (namespace_members, namespace_reexport_exports) {
(Some(members), _) => {
if members.values().all(|m| matches!(m, MemberUsage::All)) {
ExportUsage::PartialNamespaceObject(members.keys().cloned().collect())
} else {
ExportUsage::NamespaceMembers(members.clone())
}
}
(None, Some(exports)) => ExportUsage::NamespaceReexport {
exports: exports.clone(),
},
None => ExportUsage::All,
(None, None) => ExportUsage::All,
},
_ => ExportUsage::All,
},
......
......@@ -29,6 +29,7 @@ pub mod worker;
use std::{
cell::RefCell,
collections::BTreeMap,
future::Future,
mem::{replace, take},
sync::{Arc, LazyLock},
......@@ -83,7 +84,7 @@ use turbopack_core::{
reference::{ModuleReference, ModuleReferences},
reference_type::{CommonJsReferenceSubType, InnerAssets},
resolve::{
ExportUsage, FindContextFileResult, ImportUsage, ModulePart, ResolveErrorMode,
ExportUsage, FindContextFileResult, ImportUsage, MemberUsage, ModulePart, ResolveErrorMode,
find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin},
parse::Request,
......@@ -227,11 +228,11 @@ struct AnalyzeEcmascriptModuleResultBuilder {
esm_references_free_var: FxIndexMap<RcStr, ResolvedVc<EsmAssetReference>>,
// Ad-hoc created import references that are resolved `import * as x from ...; x.foo` accesses
// This caches repeated access because EsmAssetReference::new is not a turbo task function.
/// Rewritten references per original import, keyed by the part they request (the export and
/// any static members read on it, which narrow usage when that export resolves to a namespace
/// Rewritten references per original import, keyed by what they request (the export and any
/// static members read on it, which narrow usage when that export resolves to a namespace
/// object).
esm_references_rewritten:
FxHashMap<usize, FxIndexMap<ModulePart, ResolvedVc<EsmAssetReference>>>,
FxHashMap<usize, FxIndexMap<RewrittenReferenceKey, ResolvedVc<EsmAssetReference>>>,
esm_bindings: EsmBindingsBuilder,
......@@ -395,14 +396,14 @@ impl AnalyzeEcmascriptModuleResultBuilder {
pub fn add_esm_reference_namespace_resolved(
&mut self,
esm_reference_idx: usize,
part: ModulePart,
key: RewrittenReferenceKey,
on_insert: impl FnOnce() -> ResolvedVc<EsmAssetReference>,
) -> ResolvedVc<EsmAssetReference> {
*self
.esm_references_rewritten
.entry(esm_reference_idx)
.or_default()
.entry(part)
.entry(key)
.or_insert_with(on_insert)
}
......@@ -524,6 +525,16 @@ enum Action<'a> {
LeaveScope(u32),
}
/// What a reference rewritten from an original import requests.
#[derive(Clone, PartialEq, Eq, Hash)]
enum RewrittenReferenceKey {
/// A single export, possibly with the static members read on it.
Part(ModulePart),
/// The whole namespace object, of which only these (possibly nested) members are read
/// (`const { a, b } = ns`).
NamespaceMembers(BTreeMap<RcStr, MemberUsage>),
}
/// Pushes `effects` onto the processing stack. They are appended in reverse order so that popping
/// the stack yields them in their original order.
fn add_effects<'a, I>(queue_stack: &mut Vec<Action<'a>>, effects: I)
......@@ -1491,7 +1502,7 @@ async fn analyze_ecmascript_module_internal(
let named_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
part.clone(),
RewrittenReferenceKey::Part(part.clone()),
|| {
original_reference
.rewrite_for_export(part)
......@@ -1506,6 +1517,30 @@ async fn analyze_ecmascript_module_internal(
continue;
}
if original_reference.export_name.is_none()
&& export.is_none()
&& !members.is_empty()
{
// `const { a, b: { c } } = ns` only reads these (possibly nested)
// exports of the namespace object, which stays the same object.
let narrowed_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
RewrittenReferenceKey::NamespaceMembers(members.clone()),
|| {
original_reference
.rewrite_for_namespace_members(members)
.resolved_cell()
},
);
analysis.esm_bindings.add(
narrowed_reference,
None,
analysis.intern_path(&ast_path),
);
continue;
}
if let Some(ModulePart::Export(export_name)) =
&original_reference.export_name
&& !members.is_empty()
......@@ -1516,7 +1551,7 @@ async fn analyze_ecmascript_module_internal(
let narrowed_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
part.clone(),
RewrittenReferenceKey::Part(part.clone()),
|| {
original_reference
.rewrite_for_export(part)
......
use std::ops::Deref;
use std::{collections::BTreeMap, ops::Deref};
use bincode::{Decode, Encode};
use serde::Serialize;
......@@ -9,7 +9,10 @@ use swc_core::{
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput};
use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern};
use turbopack_core::{
chunk::ModuleId,
resolve::{MemberUsage, merge_member_maps, pattern::Pattern},
};
use crate::{
analyzer::{
......@@ -65,6 +68,55 @@ pub(crate) fn extract_names_from_object_pat(pat: &Pat) -> Option<SmallVec<[RcStr
Some(names)
}
/// Extracts the (possibly nested) members read by an object destructuring pattern:
/// `{ a, b: { c }, d = 1 }` reads `{ a: All, b: { c: All }, d: All }`.
///
/// Returns `None` if the pattern isn't an object pattern, or reads members that can't be
/// determined statically (a rest element or a computed key). Nested patterns that can't be
/// narrowed read their member as a whole.
pub(crate) fn extract_member_usage_from_object_pat(
pat: &Pat,
) -> Option<BTreeMap<RcStr, MemberUsage>> {
let Pat::Object(obj_pat) = pat else {
return None;
};
let mut members = BTreeMap::new();
for prop in &obj_pat.props {
let (name, usage): (RcStr, _) = match prop {
ObjectPatProp::KeyValue(kv) => {
let name = match &kv.key {
PropName::Ident(ident) => ident.sym.as_str().into(),
PropName::Str(s) => s.value.as_str()?.into(),
PropName::Computed(ComputedPropName { expr, .. }) => match &**expr {
Expr::Lit(Lit::Str(s)) => s.value.as_str()?.into(),
_ => return None, // computed key, can't determine statically
},
_ => return None, // numeric or bigint key, not an export name
};
(name, member_usage_of_pat(&kv.value))
}
// `{ a = 1 }` still reads `a`.
ObjectPatProp::Assign(assign) => (assign.key.sym.as_str().into(), MemberUsage::All),
ObjectPatProp::Rest(_) => return None, // rest pattern means all members are read
};
merge_member_maps(&mut members, &BTreeMap::from([(name, usage)]));
}
Some(members)
}
/// How a destructuring pattern reads the value it is matched against.
fn member_usage_of_pat(pat: &Pat) -> MemberUsage {
match pat {
Pat::Object(_) => {
extract_member_usage_from_object_pat(pat).map_or(MemberUsage::All, MemberUsage::Members)
}
// `{ a: { b } = {} }`: the default only applies to `undefined`, the members read are the
// same.
Pat::Assign(assign) => member_usage_of_pat(&assign.left),
_ => MemberUsage::All,
}
}
/// Converts a js-value into a Pattern for matching resources.
pub fn js_value_to_pattern(value: &JsValue<'_>) -> Pattern {
match value {
......
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d3-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d8-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d9-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as chain from './d1-lib'
import * as nested from './d2-lib'
import { a as namedNamespace } from './d3-lib'
import * as defaults from './d4-lib'
import * as rest from './d5-lib'
import * as computed from './d6-lib'
import * as literalKey from './d7-lib'
import * as nestedRest from './d8-lib'
import * as nestedComputed from './d9-lib'
it('narrows destructuring of a static member chain', () => {
const { leaf, siblingUsed } = chain.a.b
expect(leaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('narrows nested object patterns on a namespace import', () => {
const {
a: {
b: { leaf: renamedLeaf, siblingUsed },
},
} = nested
expect(renamedLeaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('narrows destructuring of a namespace-valued named import', () => {
const { b, aUnusedInfo } = namedNamespace
expect(b.leaf).toBe('leaf')
expect(aUnusedInfo).toBe(false)
})
it('treats a default value as a read of that export', () => {
const { leaf = 'fallback', siblingUsed } = defaults.a
expect(leaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('keeps the whole namespace for a rest element', () => {
const { leaf, ...others } = rest.a
expect(leaf).toBe('leaf')
expect(others.sibling).toBe('sibling')
expect(rest.a.siblingUsed).toBe(true)
})
it('keeps the whole namespace for a computed key', () => {
const key = ['sib', 'ling'].join('')
const { [key]: value } = computed.a
expect(value).toBe('sibling')
expect(computed.a.siblingUsed).toBe(true)
})
it('narrows a computed string-literal key', () => {
const { ['leaf']: value, siblingUsed } = literalKey.a
expect(value).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('keeps the whole namespace for a nested rest element at that level only', () => {
const {
a: {
b: { leaf, ...others },
aUnusedInfo,
},
} = nestedRest
expect(leaf).toBe('leaf')
expect(others.sibling).toBe('sibling')
expect(nestedRest.a.b.siblingUsed).toBe(true)
expect(aUnusedInfo).toBe(false)
})
it('keeps the whole namespace for a nested computed key at that level only', () => {
const key = ['sib', 'ling'].join('')
const {
a: {
b: { [key]: value },
aUnusedInfo,
},
} = nestedComputed
expect(value).toBe('sibling')
expect(nestedComputed.a.b.siblingUsed).toBe(true)
expect(aUnusedInfo).toBe(false)
})
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": true,
"minify": true
}
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d3-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d8-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as b from './d9-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as chain from './d1-lib'
import * as nested from './d2-lib'
import { a as namedNamespace } from './d3-lib'
import * as defaults from './d4-lib'
import * as rest from './d5-lib'
import * as computed from './d6-lib'
import * as literalKey from './d7-lib'
import * as nestedRest from './d8-lib'
import * as nestedComputed from './d9-lib'
it('narrows destructuring of a static member chain', () => {
const { leaf, siblingUsed } = chain.a.b
expect(leaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('narrows nested object patterns on a namespace import', () => {
const {
a: {
b: { leaf: renamedLeaf, siblingUsed },
},
} = nested
expect(renamedLeaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('narrows destructuring of a namespace-valued named import', () => {
const { b, aUnusedInfo } = namedNamespace
expect(b.leaf).toBe('leaf')
expect(aUnusedInfo).toBe(false)
})
it('treats a default value as a read of that export', () => {
const { leaf = 'fallback', siblingUsed } = defaults.a
expect(leaf).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('keeps the whole namespace for a rest element', () => {
const { leaf, ...others } = rest.a
expect(leaf).toBe('leaf')
expect(others.sibling).toBe('sibling')
expect(rest.a.siblingUsed).toBe(true)
})
it('keeps the whole namespace for a computed key', () => {
const key = ['sib', 'ling'].join('')
const { [key]: value } = computed.a
expect(value).toBe('sibling')
expect(computed.a.siblingUsed).toBe(true)
})
it('narrows a computed string-literal key', () => {
const { ['leaf']: value, siblingUsed } = literalKey.a
expect(value).toBe('leaf')
expect(siblingUsed).toBe(false)
})
it('keeps the whole namespace for a nested rest element at that level only', () => {
const {
a: {
b: { leaf, ...others },
aUnusedInfo,
},
} = nestedRest
expect(leaf).toBe('leaf')
expect(others.sibling).toBe('sibling')
expect(nestedRest.a.b.siblingUsed).toBe(true)
expect(aUnusedInfo).toBe(false)
})
it('keeps the whole namespace for a nested computed key at that level only', () => {
const key = ['sib', 'ling'].join('')
const {
a: {
b: { [key]: value },
aUnusedInfo,
},
} = nestedComputed
expect(value).toBe('sibling')
expect(nestedComputed.a.b.siblingUsed).toBe(true)
expect(aUnusedInfo).toBe(false)
})
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
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