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

turbopack: narrow nested namespace member usage

Track static member chains through namespace reexports so that reading
`lib.core.CoreError` through `import * as lib` only marks `CoreError` used
in `core`, rather than the whole `core` namespace. Unused nested namespaces
such as `lib.core.locales` are dropped from the bundle.

Fixes #99954

<!-- NEXT_JS_LLM -->
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent fa3830c4
......@@ -8,7 +8,7 @@ use turbo_tasks::{ReadRef, ResolvedVc, ValueToString, ValueToStringRef, Vc, turb
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{DeterministicHash, Xxh3Hash64Hasher, encode_base38, hash_xxh3_hash64};
use crate::resolve::ModulePart;
use crate::resolve::{MemberUsage, ModulePart};
/// A layer identifies a distinct part of the module graph.
#[turbo_tasks::task_input]
......@@ -249,10 +249,10 @@ impl AssetIdent {
2_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::PartialExport { export, member } => {
ModulePart::PartialExport { export, members } => {
3_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
member.deterministic_hash(&mut hasher);
hash_member_map(members, &mut hasher);
}
ModulePart::RenamedExport {
original_export,
......@@ -266,10 +266,10 @@ impl AssetIdent {
5_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::RenamedPartialNamespace { export, member } => {
ModulePart::RenamedPartialNamespace { export, members } => {
6_u8.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
member.deterministic_hash(&mut hasher);
hash_member_map(members, &mut hasher);
}
ModulePart::Internal(id) => {
7_u8.deterministic_hash(&mut hasher);
......@@ -420,6 +420,22 @@ impl ValueToStringRef for AssetIdent {
}
}
/// Hashes a member tree so that a single member read as a whole (`{ member: All }`) hashes exactly
/// like the plain `member` name did before member trees existed, keeping existing idents stable.
fn hash_member_map(
members: &std::collections::BTreeMap<RcStr, MemberUsage>,
hasher: &mut Xxh3Hash64Hasher,
) {
for (name, usage) in members {
name.deterministic_hash(hasher);
if let MemberUsage::Members(nested) = usage {
0xfe_u8.deterministic_hash(hasher);
hash_member_map(nested, hasher);
0xff_u8.deterministic_hash(hasher);
}
}
}
fn escape_file_path(s: &str) -> String {
static SEPARATOR_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[/#?:]").unwrap());
SEPARATOR_REGEX.replace_all(s, "_").to_string()
......
......@@ -548,6 +548,8 @@ pub async fn compute_merged_modules(module_graph: Vc<ModuleGraph>) -> Result<Vc<
r.binding_usage.export,
ExportUsage::All
| ExportUsage::PartialNamespaceObject(_)
| ExportUsage::NamespaceMembers(_)
| ExportUsage::NamespaceReexport { .. }
| ExportUsage::Passthrough { .. }
)
}) {
......
use std::collections::BTreeMap;
use bumpalo::boxed::Box as BumpBox;
use swc_core::{atoms::Atom, common::Span, ecma::visit::fields::*};
use turbo_rcstr::RcStr;
use turbopack_core::resolve::ExportUsage;
use turbopack_core::resolve::{ExportUsage, MemberUsage};
use crate::{
analyzer::{Bump, BumpVec, JsValue},
......@@ -171,8 +173,11 @@ pub enum Effect<'a> {
ImportedBinding {
esm_reference_index: usize,
export: Option<RcStr>,
/// A single member read from a named import (`z.member`), used only to narrow the part.
member: Option<RcStr>,
/// The static members read on the imported value, used only to narrow the part:
/// `{ a: { b } }` for `z.a.b` with a named import `z`, or for `ns.export.a.b` with a
/// namespace import `ns` (where `export` is already `Some("export")`). Empty if the
/// value is read as a whole.
members: BTreeMap<RcStr, MemberUsage>,
ast_path: BumpBox<'a, [AstParentKind]>,
span: Span,
},
......
use std::{
collections::BTreeMap,
iter,
mem::{replace, take},
};
......@@ -16,7 +17,7 @@ use swc_core::{
},
};
use turbo_rcstr::{RcStr, rcstr};
use turbopack_core::resolve::ExportUsage;
use turbopack_core::resolve::{ExportUsage, MemberUsage};
use crate::{
AnalyzeMode,
......@@ -607,6 +608,28 @@ mod analyzer_state {
.is_some_and(|b| b.contains_key(id))
}
/// The static member chain read on the ident at the end of `ast_path` (`[a, b]` for
/// `ident.a.b`), after skipping the first `skip` members. Stops at the first member whose
/// name isn't statically known, or at any other parent (a call, optional chain, ...).
pub(super) fn static_member_chain(
&self,
ast_path: &AstNodePath<AstParentNodeRef<'_>>,
skip: usize,
) -> SmallVec<[RcStr; 1]> {
let mut members = SmallVec::new();
for member in member_access_ancestors(ast_path).skip(skip) {
let Some(prop) = self.eval_context.eval_member_prop(self.arena, &member.prop)
else {
break;
};
let Some(prop) = prop.as_str() else {
break;
};
members.push(RcStr::from(prop));
}
members
}
/// 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
......@@ -894,6 +917,64 @@ 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) {
MemberUsage::Members(members) => members,
MemberUsage::All => BTreeMap::new(),
}
}
/// Whether the ident at the end of `ast_path`, read through its first `chain_len` (at least one)
/// static members, is called as a method: `ident.a.fn()`, `(ident.a.fn)()`, `ident.a.fn?.()` or a
/// tagged template ``ident.a.fn`...` ``. Such a call passes the object of the last member
/// (`ident.a`) as `this`. An indirect call like `(0, ident.a.fn)()` doesn't.
fn is_method_call_callee(ast_path: &AstNodePath<AstParentNodeRef<'_>>, chain_len: usize) -> bool {
// See `member_access_ancestors` for the layout of the path above the ident.
let Some(mut index) = ast_path.len().checked_sub(2 + 2 * chain_len) else {
return false;
};
// Parentheses keep the receiver: `(ident.a.fn)()` is `Expr::Paren(ParenExpr { expr })`.
while let Some(AstParentNodeRef::ParenExpr(_, ParenExprField::Expr)) = ast_path.get(index)
&& let Some(AstParentNodeRef::Expr(_, ExprField::Paren)) =
index.checked_sub(1).and_then(|i| ast_path.get(i))
&& let Some(parent) = index.checked_sub(2)
{
index = parent;
}
matches!(
ast_path.get(index),
Some(
AstParentNodeRef::Callee(_, CalleeField::Expr)
| AstParentNodeRef::OptCall(_, OptCallField::Callee)
| AstParentNodeRef::TaggedTpl(_, TaggedTplField::Tag)
)
)
}
/// For an ident at the end of `ast_path`, returns the member expressions it is the (innermost)
/// object of, innermost first: `[ident.a, ident.a.b, ident.a.b.c]` for `ident.a.b.c`.
fn member_access_ancestors<'a, 'r: 'a>(
ast_path: &'a AstNodePath<AstParentNodeRef<'r>>,
) -> impl Iterator<Item = &'r MemberExpr> + 'a {
// `ident.a.b` is `MemberExpr(MemberExpr(Expr::Ident, a) wrapped in Expr::Member, b)`, so the
// path above the ident alternates between `MemberExpr(_, Obj)` and `Expr(_, Member)`.
let mut index = ast_path.len().checked_sub(2);
std::iter::from_fn(move || {
let i = index?;
let AstParentNodeRef::MemberExpr(member, MemberExprField::Obj) = ast_path.get(i)? else {
index = None;
return None;
};
index = match i.checked_sub(1).and_then(|i| ast_path.get(i)) {
Some(AstParentNodeRef::Expr(_, ExprField::Member)) => i.checked_sub(2),
_ => None,
};
Some(*member)
})
}
/// Extracts export names from usage patterns on a dynamic import.
///
/// Supports two patterns:
......@@ -2475,28 +2556,43 @@ impl VisitAstPath for Analyzer<'_, '_> {
{
// a namespace member access like
// `import * as ns from "..."; ns.exportName`
//
// If the result is itself read statically (`ns.exportName.a.b`), record that
// member chain too. It only narrows usage if `exportName` later resolves to a
// namespace object (e.g. `export * as exportName from "..."`).
let mut path = self.static_member_chain(ast_path, 1);
if !path.is_empty() && is_method_call_callee(ast_path, 1 + path.len()) {
// `ns.exportName.a.fn()` calls `fn` with `ns.exportName.a` as `this`, which
// may read any of its members: keep that receiver whole.
path.pop();
}
let members = member_path_tree(&path);
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: Some(prop_str.into()),
member: None,
members,
// point to the MemberExpression instead
ast_path: as_parent_path_skip_in(self.arena, ast_path, 1),
span: member.span(),
});
} else {
// ast_path stays on the ident, so `.exportName` remains in the emitted code.
let mut member = None;
if export.is_some()
&& let Some(access) = member_access_parent(ast_path)
&& let Some(prop) = self.eval_context.eval_member_prop(self.arena, &access.prop)
&& let Some(prop_str) = prop.as_str()
{
member = Some(RcStr::from(prop_str));
}
let members = if export.is_some() {
let mut path = self.static_member_chain(ast_path, 0);
if path.len() >= 2 && is_method_call_callee(ast_path, path.len()) {
// `z.a.fn()` calls `fn` with `z.a` as `this`, which may read any of its
// members: keep that receiver whole. (`z.fn()` itself narrows `z` to
// `fn`, like a namespace import's `ns.fn()` does.)
path.pop();
}
member_path_tree(&path)
} else {
BTreeMap::new()
};
self.add_effect(Effect::ImportedBinding {
esm_reference_index,
export: export.map(|e| RcStr::from(e.as_str())),
member,
members,
ast_path: as_parent_path_in(self.arena, ast_path),
span: ident.span(),
})
......
......@@ -455,6 +455,14 @@ pub(crate) struct ImportMap {
/// as a whole.
full_star_imports: FxHashSet<Wtf8Atom>,
/// References of namespace imports (`import * as ns`) whose binding is read in any way other
/// than being re-exported as is (`export { ns }`, `export { ns as other }`,
/// `export default ns`).
namespace_import_local_uses: FxHashSet<usize>,
/// References of namespace imports whose binding is the default export (`export default ns`).
namespace_import_default_exports: FxHashSet<usize>,
/// Map from export binding id to the scopes where it's assigned. This is used to determine
/// whether an export is live or not.
pub(super) assignment_scopes: FxHashMap<Id, AssignmentScopes>,
......@@ -824,6 +832,30 @@ impl ImportMap {
self.reexport_namespaces.iter().copied()
}
/// The exports under which the namespace object of reference `idx` is re-exported, when that
/// is the reference's only use: `export * as ns from '...'`, or an `import * as ns` binding
/// that is only re-exported (`export { ns }`, `export { ns as other }`, `export default ns`).
///
/// The target module's exports are then used exactly like the members of these exports.
/// Returns `None` if the namespace is read in any other way.
pub fn namespace_reexport_exports(&self, idx: usize) -> Option<SmallVec<[RcStr; 1]>> {
if self.namespace_import_local_uses.contains(&idx) {
return None;
}
let mut exports: SmallVec<[RcStr; 1]> = self
.exports
.iter()
.filter(|(_, export)| matches!(export, Export::ImportedNamespace(i) if *i == idx))
.map(|(name, _)| name.clone())
.collect();
if self.namespace_import_default_exports.contains(&idx)
&& !exports.contains(&rcstr!("default"))
{
exports.push(rcstr!("default"));
}
(!exports.is_empty()).then_some(exports)
}
/// Returns the liveness of a given export identifier. An export is live if it might change
/// values after module evaluation.
pub fn get_export_ident_liveness(&self, id: Id, unresolved_mark: Mark) -> Liveness {
......@@ -867,6 +899,7 @@ impl ImportMap {
state: Default::default(),
program_decl_usage: Default::default(),
current_module_item_order: 0,
in_namespace_reexport: false,
};
// A prepass to detect imports to be able to rewrite import+export pairs to true reexports
......@@ -1052,6 +1085,10 @@ struct Analyzer<'a> {
/// Index of the top-level module item currently being analyzed.
current_module_item_order: usize,
/// Whether the identifiers currently visited only re-export a binding as is
/// (`export { ns }`, `export default ns`), which is not a local use of a namespace import.
in_namespace_reexport: bool,
state: analyzer_state::AnalyzerState,
}
......@@ -1391,7 +1428,23 @@ impl Visit for Analyzer<'_> {
);
self.register_assignment_scope(default_id);
n.visit_children_with(self);
// `export default ns` only re-exports a namespace import: it is not a local use of it.
let namespace_import = match &*n.expr {
Expr::Ident(ident) => match self.data.get_binding(&ident.to_id()) {
Some((index, None)) => Some(index),
_ => None,
},
_ => None,
};
if let Some(index) = namespace_import {
self.data.namespace_import_default_exports.insert(index);
let in_namespace_reexport = std::mem::replace(&mut self.in_namespace_reexport, true);
n.visit_children_with(self);
self.in_namespace_reexport = in_namespace_reexport;
} else {
n.visit_children_with(self);
}
}
fn visit_export_named_specifier(&mut self, n: &ExportNamedSpecifier) {
......@@ -1407,7 +1460,9 @@ impl Visit for Analyzer<'_> {
self.program_decl_usage
.exports
.insert(exported, local.to_id());
let in_namespace_reexport = std::mem::replace(&mut self.in_namespace_reexport, true);
n.visit_children_with(self);
self.in_namespace_reexport = in_namespace_reexport;
}
fn visit_export_default_specifier(&mut self, n: &ExportDefaultSpecifier) {
......@@ -1572,7 +1627,12 @@ impl Visit for Analyzer<'_> {
fn visit_ident(&mut self, node: &Ident) {
let id = node.to_id();
if let Some((esm_reference_index, _)) = self.data.get_binding(&id) {
if let Some((esm_reference_index, export)) = self.data.get_binding(&id) {
if export.is_none() && !self.in_namespace_reexport {
self.data
.namespace_import_local_uses
.insert(esm_reference_index);
}
// An import binding
let usage = self
.program_decl_usage
......
......@@ -77,10 +77,10 @@ async fn apply_reexport_tree_shaking(
module: Vc<Box<dyn EcmascriptChunkPlaceable>>,
part: ModulePart,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
// The namespace member is only applied if this export resolves to a namespace object.
let (export, namespace_member) = match &part {
// The namespace members are only applied if this export resolves to a namespace object.
let (export, namespace_members) = match &part {
ModulePart::Export(export) => (export, None),
ModulePart::PartialExport { export, member } => (export, Some(member)),
ModulePart::PartialExport { export, members } => (export, Some(members)),
_ => return Ok(module),
};
......@@ -93,6 +93,8 @@ async fn apply_reexport_tree_shaking(
if *new_export == *export {
**final_module
} else {
// The rename module forwards the usage of `export` (including member usage) to
// `new_export`, see `EcmascriptModuleRenameModule::module_reference`.
Vc::upcast(EcmascriptModuleRenameModule::new(
**final_module,
ModulePart::renamed_export(new_export.clone(), export.clone()),
......@@ -101,9 +103,9 @@ async fn apply_reexport_tree_shaking(
} else {
Vc::upcast(EcmascriptModuleRenameModule::new(
**final_module,
match namespace_member {
Some(member) => {
ModulePart::renamed_partial_namespace(export.clone(), member.clone())
match namespace_members {
Some(members) => {
ModulePart::renamed_partial_namespace(export.clone(), members.clone())
}
None => ModulePart::renamed_namespace(export.clone()),
},
......
......@@ -165,9 +165,9 @@ impl EcmascriptModulePartAsset {
}
part @ (ModulePart::Export(_) | ModulePart::PartialExport { .. }) => {
let (export, namespace_member) = match part {
let (export, namespace_members) = match part {
ModulePart::Export(export) => (export, None),
ModulePart::PartialExport { export, member } => (export, Some(member)),
ModulePart::PartialExport { export, members } => (export, Some(members)),
_ => unreachable!(),
};
if entrypoints.contains_key(&Key::Export(export.clone())) {
......@@ -205,9 +205,9 @@ impl EcmascriptModulePartAsset {
ResolvedVc::upcast(
EcmascriptModuleRenameModule::new(
**final_module,
match namespace_member {
Some(member) => {
ModulePart::renamed_partial_namespace(export.clone(), member)
match namespace_members {
Some(members) => {
ModulePart::renamed_partial_namespace(export.clone(), members)
}
None => ModulePart::renamed_namespace(export.clone()),
},
......
......@@ -2,6 +2,7 @@ use anyhow::{Result, bail};
use async_trait::async_trait;
use bincode::{Decode, Encode};
use either::Either;
use smallvec::SmallVec;
use strsim::jaro;
use swc_core::{
common::{BytePos, DUMMY_SP, Span, SyntaxContext, source_map::PURE_SP},
......@@ -461,6 +462,10 @@ pub struct EsmAssetReferenceOptions {
/// Explicit export-usage passthrough mode for syntax-driven forwarding. `Some(false)` forwards
/// used names without exposing the target namespace's original property names.
pub export_usage_passthrough: Option<bool>,
/// The exports under which the importing module exposes this namespace import, when that is
/// its only use (`export * as ns from '...'`, or `import * as ns from '...'` that is only
/// re-exported). The target's exports are then used exactly like those exports' members.
pub namespace_reexport_exports: Option<SmallVec<[RcStr; 1]>>,
pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
......@@ -484,6 +489,8 @@ struct EsmReferenceExtras {
/// Whether the importing module's used exports should be forwarded to the target. The boolean
/// records whether this edge itself exposes the target namespace's original property names.
export_usage_passthrough: Option<bool>,
/// See [`EsmAssetReferenceOptions::namespace_reexport_exports`].
namespace_reexport_exports: Option<SmallVec<[RcStr; 1]>>,
/// A module to resolve to directly, bypassing resolution (from a matched inner asset).
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
......@@ -503,6 +510,7 @@ impl EsmReferenceExtras {
fn new(
annotations: Option<&ImportAnnotations>,
export_usage_passthrough: Option<bool>,
namespace_reexport_exports: Option<SmallVec<[RcStr; 1]>>,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Option<Box<Self>> {
let extras = EsmReferenceExtras {
......@@ -517,6 +525,7 @@ impl EsmReferenceExtras {
export_usage_passthrough,
annotations.is_some_and(|a| a.export_usage_passthrough()),
),
namespace_reexport_exports,
resolve_override,
};
(extras != EsmReferenceExtras::default()).then(|| Box::new(extras))
......@@ -563,6 +572,7 @@ impl EsmAssetReference {
import_externals,
module_fragments_enabled,
export_usage_passthrough,
namespace_reexport_exports,
resolve_override,
} = options;
......@@ -590,6 +600,7 @@ impl EsmAssetReference {
extras: EsmReferenceExtras::new(
annotations.as_ref(),
export_usage_passthrough,
namespace_reexport_exports,
resolve_override,
),
})
......@@ -762,10 +773,10 @@ impl ModuleReference for EsmAssetReference {
}
fn binding_usage(&self) -> BindingUsage {
let export_usage_passthrough = self
.extras
.as_deref()
.and_then(|extras| extras.export_usage_passthrough);
let extras = self.extras.as_deref();
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());
BindingUsage {
import: self.import_usage.clone(),
export: match (&self.export_name, export_usage_passthrough) {
......@@ -775,21 +786,22 @@ impl ModuleReference for EsmAssetReference {
(_, Some(namespace_object_may_escape)) => ExportUsage::Passthrough {
namespace_object_may_escape,
},
(
Some(
ModulePart::Export(export_name)
| ModulePart::PartialExport {
export: export_name,
..
},
),
_,
) => {
// Until resolution proves a partial export is a namespace, it is still an
// ordinary named read of the outer module. The synthesized namespace rename
// reference records the member read on the resolved target.
(Some(ModulePart::Export(export_name)), _) => {
ExportUsage::Named(export_name.clone())
}
(Some(ModulePart::PartialExport { export, members }), _) => {
// Until resolution proves a partial export is a namespace, it is still an
// ordinary named read of the outer module, which only reads these members of
// its value. The synthesized namespace rename reference records the member
// reads on the resolved target.
ExportUsage::named_members(export.clone(), members.clone())
}
(None, _) => match namespace_reexport_exports {
Some(exports) => ExportUsage::NamespaceReexport {
exports: exports.clone(),
},
None => ExportUsage::All,
},
_ => ExportUsage::All,
},
}
......
......@@ -143,6 +143,7 @@ pub async fn compute_ecmascript_module_exports(
import_externals,
module_fragments_enabled: options.module_fragments_enabled,
export_usage_passthrough: namespace_reexports.contains(&i).then_some(false),
namespace_reexport_exports: eval_context.imports.namespace_reexport_exports(i),
resolve_override,
},
)
......
......@@ -227,7 +227,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.
esm_references_rewritten: FxHashMap<usize, FxIndexMap<RcStr, ResolvedVc<EsmAssetReference>>>,
/// 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
/// object).
esm_references_rewritten:
FxHashMap<usize, FxIndexMap<ModulePart, ResolvedVc<EsmAssetReference>>>,
esm_bindings: EsmBindingsBuilder,
......@@ -391,14 +395,14 @@ impl AnalyzeEcmascriptModuleResultBuilder {
pub fn add_esm_reference_namespace_resolved(
&mut self,
esm_reference_idx: usize,
export: RcStr,
part: ModulePart,
on_insert: impl FnOnce() -> ResolvedVc<EsmAssetReference>,
) -> ResolvedVc<EsmAssetReference> {
*self
.esm_references_rewritten
.entry(esm_reference_idx)
.or_default()
.entry(export)
.entry(part)
.or_insert_with(on_insert)
}
......@@ -1419,7 +1423,7 @@ async fn analyze_ecmascript_module_internal(
Effect::ImportedBinding {
esm_reference_index,
export,
member,
members,
ast_path,
span: _,
} => {
......@@ -1475,15 +1479,22 @@ async fn analyze_ecmascript_module_internal(
{
// Rewrite `import * as ns from 'foo'; foo.bar()` to behave like
// `import {bar} from 'foo'; bar()` for tree shaking purposes.
//
// For `ns.bar.baz.qux`, behave like
// `import {bar} from 'foo'; bar.baz.qux` and only ask for
// `baz.qux` if `bar` resolves to a namespace object.
let part = if members.is_empty() {
ModulePart::export(export.clone())
} else {
ModulePart::partial_export(export.clone(), members)
};
let named_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
export.clone(),
part.clone(),
|| {
original_reference
.rewrite_for_export(ModulePart::export(
export.clone(),
))
.rewrite_for_export(part)
.resolved_cell()
},
);
......@@ -1497,20 +1508,18 @@ async fn analyze_ecmascript_module_internal(
if let Some(ModulePart::Export(export_name)) =
&original_reference.export_name
&& let Some(member) = member
&& !members.is_empty()
{
// Ask for just the static member if the named export resolves to a
// namespace object.
// Ask for just the static members if the named export resolves to
// a namespace object.
let part = ModulePart::partial_export(export_name.clone(), members);
let narrowed_reference = analysis
.add_esm_reference_namespace_resolved(
esm_reference_index,
member.clone(),
part.clone(),
|| {
original_reference
.rewrite_for_export(ModulePart::partial_export(
export_name.clone(),
member.clone(),
))
.rewrite_for_export(part)
.resolved_cell()
},
);
......@@ -3873,6 +3882,7 @@ async fn handle_free_var_reference(
import_externals: state.import_externals,
module_fragments_enabled: state.module_fragments_enabled,
export_usage_passthrough: None,
namespace_reexport_exports: None,
resolve_override: None,
},
)
......
......@@ -93,22 +93,26 @@ impl EcmascriptModuleRenameModule {
.to_resolved()
.await
}
ModulePart::RenamedPartialNamespace { member, .. } => {
ModulePart::RenamedPartialNamespace { members, .. } => {
// Only these (possibly nested) members of the namespace object are read.
EcmascriptModulePartReference::new_normal(
*self.module,
self.part.clone(),
ExportUsage::partial_namespace_object(vec![member.clone()]),
ExportUsage::namespace_members(members.clone()),
)
.to_resolved()
.await
}
ModulePart::RenamedExport {
original_export, ..
original_export,
export,
} => {
// `original_export` is used exactly like this module's `export`, including any
// static member usage of its value.
EcmascriptModulePartReference::new_normal(
*self.module,
self.part.clone(),
ExportUsage::named(original_export.clone()),
ExportUsage::forward_export(export.clone(), original_export.clone()),
)
.to_resolved()
.await
......
......@@ -98,7 +98,8 @@ impl EcmascriptModuleFacadeModule {
];
// Then one reference per export that comes from the locals module, so the module graph
// carries *which* names this facade needs from it. Without these the evaluation reference
// would be the only facade -> locals edge, and it would have to claim `all()`.
// would be the only facade -> locals edge, and it would have to claim `all()`. Each one
// forwards the facade's usage of that name, including static member usage of its value.
if let EcmascriptExports::EsmExports(esm_exports) = &*self.module.get_exports().await? {
for (name, export) in &esm_exports.await?.exports {
if matches!(export, EsmExport::LocalBinding(..)) {
......@@ -106,7 +107,7 @@ impl EcmascriptModuleFacadeModule {
EcmascriptModulePartReference::new_part(
*self.module,
ModulePart::locals(),
ExportUsage::named(name.clone()),
ExportUsage::forward_export(name.clone(), name.clone()),
)
.to_resolved()
.await?,
......
......@@ -143,9 +143,10 @@ impl ModuleReference for EcmascriptModulePartReference {
// export alive. Normal (non-synthesized) references and structural evaluation edges
// are top-level dependencies.
import: match (&self.mode, &self.export_usage) {
(EcmascriptModulePartReferenceMode::Synthesize, ExportUsage::Named(export)) => {
ImportUsage::Exports(std::iter::once(export.clone()).collect())
}
(
EcmascriptModulePartReferenceMode::Synthesize,
ExportUsage::Named(export) | ExportUsage::ForwardExport { export, .. },
) => ImportUsage::Exports(std::iter::once(export.clone()).collect()),
_ => ImportUsage::TopLevel,
},
export: self.export_usage.clone(),
......@@ -207,8 +208,14 @@ impl EcmascriptModulePartReference {
.get_ident(
chunking_context,
match export_usage {
ExportUsage::Named(export) => Some(export.clone()),
ExportUsage::Named(export)
| ExportUsage::NamedMembers { export, .. }
| ExportUsage::ForwardExport {
original: export, ..
} => Some(export.clone()),
ExportUsage::PartialNamespaceObject(_)
| ExportUsage::NamespaceMembers(_)
| ExportUsage::NamespaceReexport { .. }
| ExportUsage::All
| ExportUsage::Evaluation
| ExportUsage::Passthrough { .. } => None,
......
......@@ -26,7 +26,7 @@
export: Some(
"named",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -694,7 +694,7 @@
export: Some(
"x",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -747,7 +747,7 @@
export: Some(
"y",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -985,7 +985,7 @@
export: Some(
"z",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -158,7 +158,7 @@
export: Some(
"createRequire",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -18,7 +18,7 @@
export: Some(
"named",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -138,7 +138,7 @@
export: Some(
"named",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -4,7 +4,7 @@
export: Some(
"default",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -42,7 +42,7 @@
export: Some(
"a",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -78,7 +78,7 @@
ImportedBinding {
esm_reference_index: 6,
export: None,
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -4,7 +4,7 @@
export: Some(
"useMemo",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -256,7 +256,7 @@
export: Some(
"jsx",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -790,7 +790,7 @@
export: Some(
"fooBar",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -13,7 +13,7 @@
export: Some(
"assert",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -275,7 +275,7 @@
export: Some(
"assert",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -433,7 +433,7 @@
export: Some(
"assert",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -238,7 +238,7 @@
export: Some(
"Redis",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -1096,9 +1096,9 @@
export: Some(
"default",
),
member: Some(
"join",
),
members: {
"join": All,
},
ast_path: [
Program(
Module,
......@@ -1142,7 +1142,7 @@
export: Some(
"join",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
......@@ -4,7 +4,7 @@
export: Some(
"calledA1",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -176,7 +176,7 @@
export: Some(
"unreachableA3",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -299,7 +299,7 @@
export: Some(
"unreachableB1",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -499,7 +499,7 @@
export: Some(
"calledB1",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -622,7 +622,7 @@
export: Some(
"calledC1",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......@@ -822,7 +822,7 @@
export: Some(
"calledC2",
),
member: None,
members: {},
ast_path: [
Program(
Module,
......
export class CoreError extends Error {}
export * as locales from './locales'
export const unused = 'unused'
export const unusedInfo = __webpack_exports_info__.unused.used
export const unused = 'unused'
export const unusedInfo = __webpack_exports_info__.unused.used
import * as lib from './lib'
import * as receiverLib from './receiver-lib'
import * as escapeLib from './escape-lib'
it('should narrow a member read through a namespace reached via a namespace import', () => {
expect(new lib.core.CoreError('x')).toBeInstanceOf(Error)
expect(lib.string()).toBe('string')
expect(lib.core.unusedInfo).toBe(false)
})
it('should keep the receiver of a method call through the nested namespace', () => {
const receiver = receiverLib.core.self()
expect(typeof receiver).toBe('object')
expect(receiver.CoreError).toBe(receiverLib.core.CoreError)
})
it('should keep the whole nested namespace when it escapes', () => {
const ns = escapeLib.core
expect(Object.keys(ns)).toContain('unused')
expect(escapeLib.core.unusedInfo).toBe(true)
})
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
import * as starReexport from './s1-lib'
import * as starImportExport from './s2-lib'
import { a as namedReexport } from './s3-lib'
import { a as namedImportExport } from './s4-lib'
import defaultNamespace from './s5-lib'
it('narrows `import * as` through `export * as` at three levels', () => {
expect(starReexport.a.b.c.leaf).toBe('leaf')
expect(starReexport.a.b.c.siblingUsed).toBe(false)
expect(starReexport.a.b.bUnusedInfo).toBe(false)
expect(starReexport.a.aUnusedInfo).toBe(false)
})
it('narrows `import * as` through `import * as X; export { X }` at three levels', () => {
expect(starImportExport.a.b.c.leaf).toBe('leaf')
expect(starImportExport.a.b.c.siblingUsed).toBe(false)
expect(starImportExport.a.b.bUnusedInfo).toBe(false)
})
it('narrows a namespace-valued named import through `export * as` at three levels', () => {
expect(namedReexport.b.c.leaf).toBe('leaf')
expect(namedReexport.b.c.siblingUsed).toBe(false)
expect(namedReexport.b.bUnusedInfo).toBe(false)
})
it('narrows a namespace-valued named import through `import * as X; export { X }` at three levels', () => {
expect(namedImportExport.b.c.leaf).toBe('leaf')
expect(namedImportExport.b.c.siblingUsed).toBe(false)
expect(namedImportExport.b.bUnusedInfo).toBe(false)
})
it('narrows a default-exported namespace through a renamed namespace reexport', () => {
expect(defaultNamespace.b.c.leaf).toBe('leaf')
expect(defaultNamespace.b.c.siblingUsed).toBe(false)
})
export * as b from './s1-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export * as c from './s1-c'
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as c from './s2-c'
export { c }
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as c from './s3-c'
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as c from './s4-c'
export { c }
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.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
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": true,
"minify": true
}
import * as starReexport from './s1-lib'
import * as starImportExport from './s2-lib'
import { a as namedReexport } from './s3-lib'
import { a as namedImportExport } from './s4-lib'
import defaultNamespace from './s5-lib'
it('narrows `import * as` through `export * as` at three levels', () => {
expect(starReexport.a.b.c.leaf).toBe('leaf')
expect(starReexport.a.b.c.siblingUsed).toBe(false)
expect(starReexport.a.b.bUnusedInfo).toBe(false)
expect(starReexport.a.aUnusedInfo).toBe(false)
})
it('narrows `import * as` through `import * as X; export { X }` at three levels', () => {
expect(starImportExport.a.b.c.leaf).toBe('leaf')
expect(starImportExport.a.b.c.siblingUsed).toBe(false)
expect(starImportExport.a.b.bUnusedInfo).toBe(false)
})
it('narrows a namespace-valued named import through `export * as` at three levels', () => {
expect(namedReexport.b.c.leaf).toBe('leaf')
expect(namedReexport.b.c.siblingUsed).toBe(false)
expect(namedReexport.b.bUnusedInfo).toBe(false)
})
it('narrows a namespace-valued named import through `import * as X; export { X }` at three levels', () => {
expect(namedImportExport.b.c.leaf).toBe('leaf')
expect(namedImportExport.b.c.siblingUsed).toBe(false)
expect(namedImportExport.b.bUnusedInfo).toBe(false)
})
it('narrows a default-exported namespace through a renamed namespace reexport', () => {
expect(defaultNamespace.b.c.leaf).toBe('leaf')
expect(defaultNamespace.b.c.siblingUsed).toBe(false)
})
export * as b from './s1-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export * as c from './s1-c'
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as c from './s2-c'
export { c }
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as c from './s3-c'
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.used
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
import * as c from './s4-c'
export { c }
export const bUnused = 'bUnused'
export const bUnusedInfo = __webpack_exports_info__.bUnused.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
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
export * as b from './f1-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 './f10-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export function readMarker() {
return this.marker
}
export function tag() {
return this.marker
}
export const marker = 'marker-10'
export * as b from './f11-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export function readMarker() {
return this.marker
}
export function tag() {
return this.marker
}
export const marker = 'marker-11'
export * as b from './f12-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export function readMarker() {
return this.marker
}
export function tag() {
return this.marker
}
export const marker = 'marker-12'
export * as b from './f13-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export function readMarker() {
return this.marker
}
export function tag() {
return this.marker
}
export const marker = 'marker-13'
export * as b from './f14-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
export function readReceiver() {
return this === undefined ? 'no-receiver' : 'receiver'
}
export const marker = 'marker-15'
export const markerUsed = __webpack_exports_info__.marker.used
export * as b from './f2-b'
export const aUnused = 'aUnused'
export const aUnusedInfo = __webpack_exports_info__.aUnused.used
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