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()
......
use std::{cmp::Reverse, collections::hash_map::Entry};
use std::{
cmp::Reverse,
collections::{BTreeMap, hash_map::Entry},
};
use anyhow::{Context, Result, bail};
use auto_hash_map::AutoSet;
use rustc_hash::{FxHashMap, FxHashSet};
use tracing::Instrument;
use turbo_rcstr::RcStr;
......@@ -14,7 +16,7 @@ use crate::{
GraphEdgeIndex, GraphTraversalAction, ModuleGraph,
side_effect_module_info::compute_side_effect_free_module_info,
},
resolve::{ExportUsage, ImportUsage},
resolve::{ExportUsage, ImportUsage, MemberUsage, merge_member_maps},
};
#[turbo_tasks::value(transparent, cell = "keyed")]
......@@ -307,6 +309,35 @@ pub async fn compute_binding_usage_info(
};
namespace_changed || usage_changed
}
ExportUsage::NamespaceReexport { exports } => {
// `parent` exposes `target`'s namespace object as `exports`, so reads of
// their members are reads of `target`'s exports by name, through a
// namespace object.
let parent_usage = used_exports
.get(&parent)
.context("parent module must have usage info")?;
let mut forwarded = ModuleExportUsageInfo::Evaluation;
for export in exports {
forwarded
.add_usage_info(&parent_usage.namespace_usage_of_export(export));
}
let namespace_changed = partial_namespace_modules.insert(target);
let usage_changed = used_exports
.entry(target)
.or_default()
.add_usage_info(&forwarded);
namespace_changed || usage_changed
}
ExportUsage::ForwardExport { export, original } => {
let forwarded = used_exports
.get(&parent)
.context("parent module must have usage info")?
.forwarded_export_usage(export, original);
used_exports
.entry(target)
.or_default()
.add_usage_info(&forwarded)
}
export_usage => {
// A partial namespace edge means `target` is read through a namespace
// value. We know which names are used, but not that every read was
......@@ -315,9 +346,11 @@ pub async fn compute_binding_usage_info(
// The provenance can be new even when the used names are not (the target
// already uses `All` or these names), and it still has to be forwarded
// over the target's passthrough edges, so it counts as a change.
let namespace_changed =
matches!(export_usage, ExportUsage::PartialNamespaceObject(_))
&& partial_namespace_modules.insert(target);
let namespace_changed = matches!(
export_usage,
ExportUsage::PartialNamespaceObject(_)
| ExportUsage::NamespaceMembers(_)
) && partial_namespace_modules.insert(target);
let usage_changed =
used_exports.entry(target).or_default().add(export_usage);
namespace_changed || usage_changed
......@@ -433,7 +466,10 @@ pub enum ModuleExportUsageInfo {
/// Only the side effects are needed, no exports is used.
#[default]
Evaluation,
Exports(AutoSet<RcStr>),
/// These exports are used. Each export is either used as a whole, or only through static
/// members of its value (which narrows a namespace reexport, see
/// [`ExportUsage::NamespaceReexport`]).
Exports(BTreeMap<RcStr, MemberUsage>),
All,
}
......@@ -448,38 +484,53 @@ impl ModuleExportUsageInfo {
impl ModuleExportUsageInfo {
/// Merge the given usage into self. Returns true if Self changed.
pub fn add(&mut self, usage: &ExportUsage) -> bool {
match (&mut *self, usage) {
(Self::All, _) => false,
(_, ExportUsage::All) => {
*self = Self::All;
true
match usage {
ExportUsage::All => self.add_usage_info(&Self::All),
ExportUsage::Evaluation => false,
ExportUsage::Named(name) => self.add_export(name, &MemberUsage::All),
ExportUsage::NamedMembers { export, members } => {
self.add_export(export, &MemberUsage::Members(members.clone()))
}
(Self::Evaluation, ExportUsage::Named(name)) => {
// Promote evaluation to something more specific
*self = Self::Exports(AutoSet::from_iter([name.clone()]));
true
ExportUsage::PartialNamespaceObject(names) => {
let mut changed = self.promote_evaluation();
for name in names {
changed |= self.add_export(name, &MemberUsage::All);
}
(Self::Evaluation, ExportUsage::PartialNamespaceObject(names)) => {
*self = Self::Exports(AutoSet::from_iter(names.iter().cloned()));
true
changed
}
(Self::Exports(l), ExportUsage::Named(r)) => {
// Merge exports
l.insert(r.clone())
ExportUsage::NamespaceMembers(members) => {
self.add_usage_info(&Self::Exports(members.clone()))
}
(Self::Exports(l), ExportUsage::PartialNamespaceObject(names)) => {
let mut changed = false;
for name in names {
changed |= l.insert(name.clone());
ExportUsage::Passthrough { .. }
| ExportUsage::ForwardExport { .. }
| ExportUsage::NamespaceReexport { .. } => {
// These depend on the referencing module's usage and are normally resolved before
// `add`. If one reaches this fallback, preserve correctness by widening rather
// than panicking during graph analysis.
self.add_usage_info(&Self::All)
}
changed
}
(_, ExportUsage::Evaluation) => false,
(_, ExportUsage::Passthrough { .. }) => {
// Passthrough is normally resolved before `add`. If it reaches this fallback,
// preserve correctness by widening rather than panicking during graph analysis.
*self = Self::All;
}
/// `Evaluation` -> empty `Exports`. Returns true if self changed.
fn promote_evaluation(&mut self) -> bool {
if matches!(self, Self::Evaluation) {
*self = Self::Exports(BTreeMap::new());
true
} else {
false
}
}
/// Marks `export` as used with the given member usage. Returns true if self changed.
fn add_export(&mut self, export: &RcStr, usage: &MemberUsage) -> bool {
let promoted = self.promote_evaluation();
match self {
Self::All => false,
Self::Evaluation => unreachable!(),
Self::Exports(exports) => {
promoted
| merge_member_maps(exports, &BTreeMap::from([(export.clone(), usage.clone())]))
}
}
}
......@@ -496,37 +547,69 @@ impl ModuleExportUsageInfo {
*self = Self::Exports(exports.clone());
true
}
(Self::Exports(left), Self::Exports(right)) => {
let mut changed = false;
for export in right {
changed |= left.insert(export.clone());
(Self::Exports(left), Self::Exports(right)) => merge_member_maps(left, right),
}
changed
}
/// The usage of a module whose namespace object is this module's `export`, e.g. the target of
/// `export * as export from './target'`.
fn namespace_usage_of_export(&self, export: &RcStr) -> Self {
match self {
Self::All => Self::All,
Self::Evaluation => Self::Evaluation,
Self::Exports(exports) => match exports.get(export) {
None => Self::Evaluation,
Some(MemberUsage::All) => Self::All,
Some(MemberUsage::Members(members)) => Self::Exports(members.clone()),
},
}
}
/// The usage of the target's `original` export, when it is exposed as this module's `export`.
fn forwarded_export_usage(&self, export: &RcStr, original: &RcStr) -> Self {
let usage = match self {
Self::All => MemberUsage::All,
Self::Evaluation => return Self::Evaluation,
Self::Exports(exports) => match exports.get(export) {
None => return Self::Evaluation,
Some(usage) => usage.clone(),
},
};
Self::Exports(BTreeMap::from([(original.clone(), usage)]))
}
pub fn is_export_used(&self, export: &RcStr) -> bool {
match self {
Self::All => true,
Self::Evaluation => false,
Self::Exports(exports) => exports.contains(export),
Self::Exports(exports) => exports.contains_key(export),
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use turbo_rcstr::rcstr;
use super::ModuleExportUsageInfo;
use crate::resolve::ExportUsage;
use crate::resolve::{ExportUsage, MemberUsage};
fn exports(names: &[&'static str]) -> ModuleExportUsageInfo {
ModuleExportUsageInfo::Exports(
names
.iter()
.map(|name| ((*name).into(), MemberUsage::All))
.collect(),
)
}
#[test]
fn resolved_usage_join_is_monotonic() {
let mut usage = ModuleExportUsageInfo::Evaluation;
let first = ModuleExportUsageInfo::Exports([rcstr!("first")].into_iter().collect());
let second = ModuleExportUsageInfo::Exports([rcstr!("second")].into_iter().collect());
let first = exports(&["first"]);
let second = exports(&["second"]);
assert!(!usage.add_usage_info(&ModuleExportUsageInfo::Evaluation));
assert!(usage.add_usage_info(&first));
......@@ -549,10 +632,72 @@ mod tests {
}));
assert!(matches!(usage, ModuleExportUsageInfo::All));
}
#[test]
fn nested_member_usage_merges_and_widens() {
let path = |p: &[&'static str]| {
MemberUsage::from_path(&p.iter().map(|s| (*s).into()).collect::<Vec<_>>())
};
let mut usage = ModuleExportUsageInfo::Evaluation;
let MemberUsage::Members(core_en) = path(&["core", "locales", "en"]) else {
unreachable!()
};
assert!(usage.add(&ExportUsage::NamespaceMembers(core_en)));
let MemberUsage::Members(core_de) = path(&["core", "locales", "de"]) else {
unreachable!()
};
assert!(usage.add(&ExportUsage::NamespaceMembers(core_de.clone())));
assert!(!usage.add(&ExportUsage::NamespaceMembers(core_de)));
// `core.locales` is read through `en` and `de` only.
let core = usage.namespace_usage_of_export(&rcstr!("core"));
let locales = core.namespace_usage_of_export(&rcstr!("locales"));
assert!(locales.is_export_used(&rcstr!("en")));
assert!(locales.is_export_used(&rcstr!("de")));
assert!(!locales.is_export_used(&rcstr!("fr")));
assert!(matches!(
usage.namespace_usage_of_export(&rcstr!("unused")),
ModuleExportUsageInfo::Evaluation
));
// An opaque read of `core` widens it as a whole.
assert!(usage.add(&ExportUsage::Named(rcstr!("core"))));
assert!(matches!(
usage.namespace_usage_of_export(&rcstr!("core")),
ModuleExportUsageInfo::All
));
}
#[test]
fn forwarded_export_keeps_member_usage() {
let mut usage = ModuleExportUsageInfo::Evaluation;
assert!(usage.add(&ExportUsage::NamedMembers {
export: rcstr!("renamed"),
members: BTreeMap::from([(rcstr!("leaf"), MemberUsage::All)]),
}));
let forwarded = usage.forwarded_export_usage(&rcstr!("renamed"), &rcstr!("original"));
let ModuleExportUsageInfo::Exports(exports) = &forwarded else {
panic!("expected exports, got {forwarded:?}");
};
assert!(matches!(
exports.get(&rcstr!("original")),
Some(MemberUsage::Members(members)) if members.contains_key(&rcstr!("leaf"))
));
assert!(matches!(
usage.forwarded_export_usage(&rcstr!("other"), &rcstr!("original")),
ModuleExportUsageInfo::Evaluation
));
assert!(matches!(
ModuleExportUsageInfo::All.forwarded_export_usage(&rcstr!("a"), &rcstr!("b")),
ModuleExportUsageInfo::Exports(exports) if matches!(exports.get(&rcstr!("b")), Some(MemberUsage::All))
));
}
}
#[cfg(test)]
mod graph_tests {
use std::collections::BTreeMap;
use anyhow::Result;
use rustc_hash::FxHashMap;
use turbo_rcstr::{RcStr, rcstr};
......@@ -570,7 +715,7 @@ mod graph_tests {
chunk_group_info::{ChunkGroupEntry, EntryHeuristics},
},
reference::{ModuleReference, ModuleReferences, SingleChunkableModuleReference},
resolve::ExportUsage,
resolve::{ExportUsage, MemberUsage},
};
/// Module name -> outgoing edges `(target name, export usage of the edge)`, in reference order.
......@@ -649,7 +794,8 @@ mod graph_tests {
}
}
/// `ExportUsage` cells are private to `resolve`, so go through its public constructors.
/// `ExportUsage` cells are private to `resolve`, so go through its public constructors (or
/// `cell_for_test` for the member and forwarding variants).
fn export_usage_vc(export: &ExportUsage) -> Vc<ExportUsage> {
match export {
ExportUsage::All => ExportUsage::all(),
......@@ -661,6 +807,10 @@ mod graph_tests {
ExportUsage::Passthrough {
namespace_object_may_escape,
} => ExportUsage::passthrough(*namespace_object_may_escape),
ExportUsage::NamedMembers { .. }
| ExportUsage::NamespaceMembers(_)
| ExportUsage::ForwardExport { .. }
| ExportUsage::NamespaceReexport { .. } => export.clone().cell_for_test(),
}
}
......@@ -672,13 +822,24 @@ mod graph_tests {
async fn namespace_escapes_operation(
namespace_path_is_longer: bool,
plain_usage_is_all: bool,
namespace_members: bool,
namespace_reexport: bool,
) -> Result<Vc<NamespaceEscapes>> {
let plain_usage = if plain_usage_is_all {
ExportUsage::All
} else {
ExportUsage::Named(rcstr!("a"))
};
let edges = namespace_graph(namespace_path_is_longer, plain_usage);
let namespace_usage = if namespace_members {
namespace_a_member_b()
} else {
namespace_a()
};
let edges = if namespace_reexport {
namespace_reexport_graph(namespace_path_is_longer, plain_usage)
} else {
namespace_graph(namespace_path_is_longer, plain_usage, namespace_usage)
};
let root = VirtualFileSystem::new_with_name(rcstr!("test"))
.root()
.owned()
......@@ -732,13 +893,30 @@ mod graph_tests {
async fn namespace_escapes(
namespace_path_is_longer: bool,
plain_usage_is_all: bool,
) -> Vec<(RcStr, bool)> {
namespace_escapes_with(namespace_path_is_longer, plain_usage_is_all, false, false).await
}
/// Like [`namespace_escapes`]. `namespace_members` makes the namespace read a nested member
/// read (`ns.a.b`), and `namespace_reexport` routes it through an `export * as a` reexport
/// (see [`namespace_reexport_graph`]).
async fn namespace_escapes_with(
namespace_path_is_longer: bool,
plain_usage_is_all: bool,
namespace_members: bool,
namespace_reexport: bool,
) -> Vec<(RcStr, bool)> {
let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new(
BackendOptions::default(),
noop_backing_storage(),
));
tt.run_once(async move {
let escapes = namespace_escapes_operation(namespace_path_is_longer, plain_usage_is_all)
let escapes = namespace_escapes_operation(
namespace_path_is_longer,
plain_usage_is_all,
namespace_members,
namespace_reexport,
)
.read_strongly_consistent()
.await?;
Ok((*escapes).clone())
......@@ -751,6 +929,14 @@ mod graph_tests {
ExportUsage::PartialNamespaceObject([rcstr!("a")].into_iter().collect())
}
/// `ns.a.b`: only member `b` of the namespace's export `a` is read.
fn namespace_a_member_b() -> ExportUsage {
ExportUsage::NamespaceMembers(BTreeMap::from([(
rcstr!("a"),
MemberUsage::Members(BTreeMap::from([(rcstr!("b"), MemberUsage::All)])),
)]))
}
fn reexport_all() -> ExportUsage {
// `export * from "y"`
ExportUsage::Passthrough {
......@@ -761,26 +947,101 @@ mod graph_tests {
/// `x` is reached directly from `entry` and through `entry -> m1 -> m2 -> x`; `x -> y` is an
/// `export *` passthrough edge.
///
/// When `namespace_path_is_longer` is true, the plain edge reaches `x` first and its
/// passthrough is processed before the namespace edge. In that order, the namespace usage does
/// not add any export to `x`. Otherwise namespace provenance reaches `x` first.
fn namespace_graph(namespace_path_is_longer: bool, plain_usage: ExportUsage) -> Edges {
/// With the original constant-priority traversal, `namespace_path_is_longer` makes the plain
/// edge reach `x` first. Reverse postorder instead processes all importers before `x` in a DAG.
/// For nested namespace reads, add `x -> m1` to close a cycle so that `x` is processed before
/// the late namespace edge even under reverse postorder. That edge adds provenance but no new
/// export usage to `x`, so forwarding it to `y` requires a namespace-only revisit.
fn namespace_graph(
namespace_path_is_longer: bool,
plain_usage: ExportUsage,
namespace_usage: ExportUsage,
) -> Edges {
let nested_namespace = matches!(&namespace_usage, ExportUsage::NamespaceMembers(_));
let mut x_edges = vec![(rcstr!("y"), reexport_all())];
if nested_namespace {
// An evaluation-only back-edge creates the cycle without adding export usage or
// namespace provenance to `m1`.
x_edges.push((rcstr!("m1"), ExportUsage::Evaluation));
}
let (direct_usage, late_usage) = if namespace_path_is_longer {
(plain_usage, namespace_a())
(plain_usage, namespace_usage)
} else {
(namespace_usage, plain_usage)
};
let mut entry_edges = vec![
(rcstr!("x"), direct_usage),
(rcstr!("m1"), ExportUsage::All),
];
if nested_namespace {
// The rank DFS visits references in reverse order; start at `x` so that the
// namespace read `m2 -> x` is the cycle's back-edge, not `x -> m1`.
entry_edges.reverse();
}
vec![
(rcstr!("entry"), entry_edges),
(rcstr!("m1"), vec![(rcstr!("m2"), ExportUsage::All)]),
(rcstr!("m2"), vec![(rcstr!("x"), late_usage)]),
(rcstr!("x"), x_edges),
]
}
/// Like [`namespace_graph`], but the namespace read of `x` goes through `r`, which reexports
/// `x`'s namespace object as `a` (`export * as a from "x"`). `r` is reached from `entry`
/// directly or through `entry -> m1 -> m2 -> r`. An evaluation-only `x -> m1` edge closes a
/// cycle, forcing the longer namespace path to arrive after `x` was processed even under
/// reverse postorder.
fn namespace_reexport_graph(namespace_path_is_longer: bool, plain_usage: ExportUsage) -> Edges {
let r_usage = ExportUsage::Named(rcstr!("a"));
let (entry_edges, m2_edges) = if namespace_path_is_longer {
(
vec![(rcstr!("x"), plain_usage)],
vec![(rcstr!("r"), r_usage)],
)
} else {
(namespace_a(), plain_usage)
(
vec![(rcstr!("r"), r_usage)],
vec![(rcstr!("x"), plain_usage)],
)
};
vec![
(
rcstr!("entry"),
// The rank DFS follows references in reverse order. Visit the direct path
// first, so the longer path's final namespace edge is the back-edge.
std::iter::once((rcstr!("m1"), ExportUsage::All))
.chain(entry_edges)
.collect(),
),
(rcstr!("m1"), vec![(rcstr!("m2"), ExportUsage::All)]),
(rcstr!("m2"), m2_edges),
(
rcstr!("r"),
vec![(
rcstr!("x"),
ExportUsage::NamespaceReexport {
exports: [rcstr!("a")].into_iter().collect(),
},
)],
),
(
rcstr!("x"),
vec![
(rcstr!("x"), direct_usage),
(rcstr!("m1"), ExportUsage::All),
(rcstr!("y"), reexport_all()),
(rcstr!("m1"), ExportUsage::Evaluation),
],
),
(rcstr!("m1"), vec![(rcstr!("m2"), ExportUsage::All)]),
(rcstr!("m2"), vec![(rcstr!("x"), late_usage)]),
(rcstr!("x"), vec![(rcstr!("y"), reexport_all())]),
]
}
fn expected_reexport_escapes() -> Vec<(RcStr, bool)> {
vec![
(rcstr!("entry"), false),
(rcstr!("m1"), false),
(rcstr!("m2"), false),
(rcstr!("r"), false),
(rcstr!("x"), true),
(rcstr!("y"), true),
]
}
......@@ -813,4 +1074,36 @@ mod graph_tests {
async fn early_namespace_usage_of_already_used_name_reaches_passthrough_target() {
assert_eq!(namespace_escapes(false, false).await, expected_escapes());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn late_namespace_member_usage_of_all_module_reaches_passthrough_target() {
assert_eq!(
namespace_escapes_with(true, true, true, false).await,
expected_escapes()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn late_namespace_member_usage_of_already_used_name_reaches_passthrough_target() {
assert_eq!(
namespace_escapes_with(true, false, true, false).await,
expected_escapes()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn late_namespace_reexport_of_all_module_reaches_passthrough_target() {
assert_eq!(
namespace_escapes_with(true, true, false, true).await,
expected_reexport_escapes()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn early_namespace_reexport_of_all_module_reaches_passthrough_target() {
assert_eq!(
namespace_escapes_with(false, true, false, true).await,
expected_reexport_escapes()
);
}
}
......@@ -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 { .. }
)
}) {
......
......@@ -167,13 +167,101 @@ pub enum ImportUsage {
Exports(FrozenSet<RcStr>),
}
/// How a value is read, when it may be a namespace object whose members are read statically.
///
/// For example `ns.a.b; ns.c` reads `ns` as
/// `Members({ a: Members({ b: All }), c: All })`.
#[turbo_tasks::task_input]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
pub enum MemberUsage {
/// The value is read as a whole (or in a way that can't be narrowed).
All,
/// Only these members of the value are read, each with its own (nested) usage.
Members(BTreeMap<RcStr, MemberUsage>),
}
impl MemberUsage {
/// The usage of a single static member path, e.g. `[a, b]` for `value.a.b`. An empty path
/// reads the whole value.
pub fn from_path(path: &[RcStr]) -> Self {
path.iter().rev().fold(MemberUsage::All, |inner, member| {
MemberUsage::Members(BTreeMap::from([(member.clone(), inner)]))
})
}
/// Merge another usage into this one. Returns true if `self` changed.
pub fn merge(&mut self, other: &MemberUsage) -> bool {
match (&mut *self, other) {
(MemberUsage::All, _) => false,
(_, MemberUsage::All) => {
*self = MemberUsage::All;
true
}
(MemberUsage::Members(left), MemberUsage::Members(right)) => {
merge_member_maps(left, right)
}
}
}
}
/// Merge `right` into `left`. Returns true if `left` changed.
pub fn merge_member_maps(
left: &mut BTreeMap<RcStr, MemberUsage>,
right: &BTreeMap<RcStr, MemberUsage>,
) -> bool {
let mut changed = false;
for (name, usage) in right {
match left.get_mut(name) {
Some(existing) => changed |= existing.merge(usage),
None => {
left.insert(name.clone(), usage.clone());
changed = true;
}
}
}
changed
}
/// Writes `.a .b` for a single path and `.{a, b .c}` for a tree.
fn fmt_member_map(map: &BTreeMap<RcStr, MemberUsage>, f: &mut Formatter<'_>) -> std::fmt::Result {
let fmt_entry = |f: &mut Formatter<'_>, name: &RcStr, usage: &MemberUsage| {
write!(f, ".{name}")?;
if let MemberUsage::Members(members) = usage {
f.write_char(' ')?;
fmt_member_map(members, f)?;
}
Ok(())
};
if let [(name, usage)] = map.iter().collect::<SmallVec<[_; 1]>>()[..] {
return fmt_entry(f, name, usage);
}
f.write_char('{')?;
for (i, (name, usage)) in map.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
fmt_entry(f, name, usage)?;
}
f.write_char('}')
}
/// Defines what parts of a module are used by another module
#[turbo_tasks::value]
#[derive(Debug, Clone, Default, Hash, Serialize, Deserialize)]
pub enum ExportUsage {
Named(RcStr),
/// A named export is used, and its value is only read through these static members. This
/// narrows the export's usage further if it is a namespace reexport (see
/// [`ExportUsage::NamespaceReexport`]); otherwise it behaves like [`ExportUsage::Named`].
NamedMembers {
export: RcStr,
members: BTreeMap<RcStr, MemberUsage>,
},
/// Multiple named exports are used via a partial namespace object.
PartialNamespaceObject(SmallVec<[RcStr; 1]>),
/// Like [`ExportUsage::PartialNamespaceObject`], but some of the exports are only read
/// through static members of their values.
NamespaceMembers(BTreeMap<RcStr, MemberUsage>),
/// This means the whole content of the module is used.
#[default]
All,
......@@ -189,12 +277,46 @@ pub enum ExportUsage {
/// the referencing module was only consumed through statically known named exports.
namespace_object_may_escape: bool,
},
/// The referencing module exposes the target's export `original` as its own export `export`
/// (a facade or rename module). The target's `original` is used exactly like the referencing
/// module's `export`, including any static member usage.
ForwardExport {
export: RcStr,
original: RcStr,
},
/// The referencing module exposes the target's namespace object as these exports, e.g.
/// `export * as ns from './target'`. The target's exports are used exactly like the members
/// of the referencing module's `ns` export.
NamespaceReexport {
exports: SmallVec<[RcStr; 1]>,
},
}
impl Display for ExportUsage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ExportUsage::Named(name) => write!(f, "export {name}"),
ExportUsage::NamedMembers { export, members } => {
write!(f, "export {export} ")?;
fmt_member_map(members, f)
}
ExportUsage::NamespaceMembers(members) => {
write!(f, "exports ")?;
fmt_member_map(members, f)
}
ExportUsage::ForwardExport { export, original } => {
write!(f, "forward export {original} as {export}")
}
ExportUsage::NamespaceReexport { exports } => {
write!(f, "namespace reexport as ")?;
for (i, name) in exports.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{name}")?;
}
Ok(())
}
ExportUsage::PartialNamespaceObject(names) => {
write!(f, "exports ")?;
for (i, name) in names.iter().enumerate() {
......@@ -252,6 +374,37 @@ impl ExportUsage {
}
.cell()
}
#[turbo_tasks::function]
pub fn forward_export(export: RcStr, original: RcStr) -> Vc<Self> {
Self::ForwardExport { export, original }.cell()
}
/// The usage of a namespace object whose `members` are read. Uses
/// [`ExportUsage::PartialNamespaceObject`] when every member is read as a whole.
#[turbo_tasks::function]
pub fn namespace_members(members: BTreeMap<RcStr, MemberUsage>) -> Vc<Self> {
if members.values().all(|m| matches!(m, MemberUsage::All)) {
ExportUsage::PartialNamespaceObject(members.into_keys().collect())
} else {
ExportUsage::NamespaceMembers(members)
}
.cell()
}
}
impl ExportUsage {
/// The usage of the named export `export` whose value is only read through `members`.
pub fn named_members(export: RcStr, members: BTreeMap<RcStr, MemberUsage>) -> Self {
ExportUsage::NamedMembers { export, members }
}
/// Cells an arbitrary usage, for test graphs whose edges need a variant without a public
/// constructor.
#[cfg(test)]
pub(crate) fn cell_for_test(self) -> Vc<Self> {
self.cell()
}
}
#[turbo_tasks::value(shared)]
......@@ -3456,13 +3609,16 @@ pub enum ModulePart {
Evaluation,
/// Represents a named export, such as `foo` in `export const foo = "bar";`.
Export(RcStr),
/// Represents an export for which one member is used.
/// Represents an export for which only some (possibly nested) members are used.
///
/// For example, `import { value } from "./module"; value.member` is represented as
/// `{ export: "value", member: "member" }`. At this point, `value` has not yet been
/// `{ export: "value", members: { member } }`. At this point, `value` has not yet been
/// resolved and might be either an ordinary value or a namespace object. If it is not a
/// namespace object, this behaves like [`ModulePart::Export`].
PartialExport { export: RcStr, member: RcStr },
PartialExport {
export: RcStr,
members: BTreeMap<RcStr, MemberUsage>,
},
/// Represents an export renamed while following re-exports, such as `foo` exported as `bar`
/// by `export { foo as bar } from "./module"`.
RenamedExport {
......@@ -3472,12 +3628,16 @@ pub enum ModulePart {
/// Represents a namespace object exported as a named export, such as `ns` in
/// `export * as ns from "./module"`.
RenamedNamespace { export: RcStr },
/// Represents a namespace object exported as a named export when only one member is used.
/// Represents a namespace object exported as a named export when only some (possibly nested)
/// members are used.
///
/// For example, `import { ns } from "./lib"; ns.member`, where `lib` contains
/// `export * as ns from "./module"`, is represented as
/// `{ export: "ns", member: "member" }` after resolving `ns` to the namespace object.
RenamedPartialNamespace { export: RcStr, member: RcStr },
/// `{ export: "ns", members: { member } }` after resolving `ns` to the namespace object.
RenamedPartialNamespace {
export: RcStr,
members: BTreeMap<RcStr, MemberUsage>,
},
/// Points to a generated module-fragment part by its numeric index, such as the part that
/// contains one local declaration.
Internal(u32),
......@@ -3499,8 +3659,8 @@ impl ModulePart {
ModulePart::Export(export)
}
pub fn partial_export(export: RcStr, member: RcStr) -> Self {
ModulePart::PartialExport { export, member }
pub fn partial_export(export: RcStr, members: BTreeMap<RcStr, MemberUsage>) -> Self {
ModulePart::PartialExport { export, members }
}
pub fn renamed_export(original_export: RcStr, export: RcStr) -> Self {
......@@ -3514,8 +3674,8 @@ impl ModulePart {
ModulePart::RenamedNamespace { export }
}
pub fn renamed_partial_namespace(export: RcStr, member: RcStr) -> Self {
ModulePart::RenamedPartialNamespace { export, member }
pub fn renamed_partial_namespace(export: RcStr, members: BTreeMap<RcStr, MemberUsage>) -> Self {
ModulePart::RenamedPartialNamespace { export, members }
}
/// Returns the named export exposed by this part, if it has one.
......@@ -3552,16 +3712,18 @@ impl Display for ModulePart {
match self {
ModulePart::Evaluation => f.write_str("module evaluation"),
ModulePart::Export(export) => write!(f, "export {export}"),
ModulePart::PartialExport { export, member } => {
write!(f, "export {export} .{member}")
ModulePart::PartialExport { export, members } => {
write!(f, "export {export} ")?;
fmt_member_map(members, f)
}
ModulePart::RenamedExport {
original_export,
export,
} => write!(f, "export {original_export} as {export}"),
ModulePart::RenamedNamespace { export } => write!(f, "export * as {export}"),
ModulePart::RenamedPartialNamespace { export, member } => {
write!(f, "export * as {export} .{member}")
ModulePart::RenamedPartialNamespace { export, members } => {
write!(f, "export * as {export} ")?;
fmt_member_map(members, f)
}
ModulePart::Internal(id) => write!(f, "internal part {id}"),
ModulePart::Locals => f.write_str("locals"),
......@@ -3592,7 +3754,7 @@ mod tests {
#[test]
fn module_part_export_names_and_display() {
let export = rcstr!("value");
let member = rcstr!("member");
let member = BTreeMap::from([(rcstr!("member"), MemberUsage::All)]);
let original = rcstr!("original");
let with_exports = [
......@@ -3622,9 +3784,40 @@ mod tests {
"export value .member"
);
assert_eq!(
ModulePart::renamed_partial_namespace(export, member).to_string(),
ModulePart::renamed_partial_namespace(export.clone(), member).to_string(),
"export * as value .member"
);
let MemberUsage::Members(path) = MemberUsage::from_path(&[rcstr!("locales"), rcstr!("en")])
else {
unreachable!()
};
assert_eq!(
ModulePart::partial_export(export.clone(), path).to_string(),
"export value .locales .en"
);
let tree = BTreeMap::from([
(rcstr!("a"), MemberUsage::All),
(
rcstr!("b"),
MemberUsage::from_path(&[rcstr!("c"), rcstr!("d")]),
),
]);
assert_eq!(
ModulePart::renamed_partial_namespace(export, tree).to_string(),
"export * as value {.a, .b .c .d}"
);
}
#[test]
fn member_usage_merge() {
let mut usage = MemberUsage::from_path(&[rcstr!("a"), rcstr!("b")]);
assert!(!usage.merge(&MemberUsage::from_path(&[rcstr!("a"), rcstr!("b")])));
assert!(usage.merge(&MemberUsage::from_path(&[rcstr!("a"), rcstr!("c")])));
assert!(usage.merge(&MemberUsage::from_path(&[rcstr!("a")])));
assert_eq!(usage, MemberUsage::from_path(&[rcstr!("a")]));
assert!(usage.merge(&MemberUsage::All));
assert!(!usage.merge(&MemberUsage::from_path(&[rcstr!("z")])));
assert_eq!(usage, MemberUsage::All);
}
#[cfg(unix)]
......
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);
// `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
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as c from './f3-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
globalThis.namespaceMemberChainEvaluations =
(globalThis.namespaceMemberChainEvaluations ?? 0) + 1
export const value = 'evaluated'
import * as computed from './f1-lib'
import * as escaping from './f2-lib'
import * as mixed from './f3-lib'
import * as receiver from './f4-lib'
import * as directReceiverA from './f4-a'
import * as directReceiverB from './f4-b'
import * as identity from './f5-lib'
import * as directIdentity from './f5-a'
import * as optional from './f6-lib'
import * as live from './f7-lib'
import * as topLevelAwait from './f8-lib'
import * as once from './f9-lib'
import { a as onceA } from './f9-lib'
import * as methodCall from './f10-lib'
import * as optionalCall from './f11-lib'
import * as taggedTemplate from './f12-lib'
import { a as namedMethodCall } from './f13-lib'
import * as parenthesizedCall from './f14-lib'
import * as indirectCall from './f15-lib'
function opaque(value) {
return value
}
it('keeps the whole namespace at the level of a computed access', () => {
const key = ['sib', 'ling'].join('')
expect(computed.a.b[key]).toBe('sibling')
expect(computed.a.b.siblingUsed).toBe(true)
expect(computed.a.aUnusedInfo).toBe(false)
})
it('keeps the whole namespace at the level where it escapes', () => {
const escaped = opaque(escaping.a.b)
expect(escaped.sibling).toBe('sibling')
expect(escaping.a.b.siblingUsed).toBe(true)
expect(escaping.a.aUnusedInfo).toBe(false)
})
it('lets an opaque use win over static reads at the same level only', () => {
expect(mixed.a.b.c.leaf).toBe('leaf')
expect(opaque(mixed.a.b.c).sibling).toBe('sibling')
expect(mixed.a.b.c.siblingUsed).toBe(true)
expect(mixed.a.b.bUnusedInfo).toBe(false)
})
it('keeps the namespace object as the receiver of a method call', () => {
expect(receiver.a.self()).toBe(directReceiverA)
expect(receiver.a.b.self()).toBe(directReceiverB)
})
it('keeps the whole receiver of a nested method call', () => {
// `marker` is only read through `this`.
expect(methodCall.a.b.readMarker()).toBe('marker-10')
// Levels above the receiver are still narrowed.
expect(methodCall.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a nested optional method call', () => {
expect(optionalCall.a.b.readMarker?.()).toBe('marker-11')
expect(optionalCall.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a nested tagged template', () => {
expect(taggedTemplate.a.b.tag`template`).toBe('marker-12')
expect(taggedTemplate.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a method call on a namespace-valued named import', () => {
expect(namedMethodCall.b.readMarker()).toBe('marker-13')
expect(namedMethodCall.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a parenthesized nested method call', () => {
// prettier-ignore
expect((parenthesizedCall.a.b.readMarker)()).toBe('marker-14')
expect(parenthesizedCall.a.aUnusedInfo).toBe(false)
})
it('still narrows an indirect call, which has no receiver', () => {
expect((0, indirectCall.a.b.readReceiver)()).toBe('no-receiver')
expect(indirectCall.a.b.markerUsed).toBe(false)
})
it('keeps namespace object identity', () => {
expect(identity.a).toBe(directIdentity)
expect(identity.a.leaf).toBe('leaf')
})
it('falls back for optional chaining without breaking runtime behavior', () => {
expect(optional.a?.leaf).toBe('leaf')
expect(optional.a.b?.leaf).toBe('leaf')
})
it('keeps live bindings live through nested namespaces', () => {
expect(live.a.b.count).toBe(0)
live.a.b.increment()
expect(live.a.b.count).toBe(1)
})
it('supports top-level await in a nested namespace target', () => {
expect(topLevelAwait.a.b.value).toBe('top-level-await')
})
it('evaluates a nested namespace target once', () => {
expect(once.a.b.value).toBe('evaluated')
expect(onceA.b.value).toBe('evaluated')
expect(globalThis.namespaceMemberChainEvaluations).toBe(1)
})
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": true,
"minify": true
}
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 readMarker() {
return this.marker
}
export const marker = 'marker-14'
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
export const leaf = 'leaf'
export const sibling = 'sibling'
export const siblingUsed = __webpack_exports_info__.sibling.used
export * as c from './f3-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
globalThis.namespaceMemberChainEvaluations =
(globalThis.namespaceMemberChainEvaluations ?? 0) + 1
export const value = 'evaluated'
import * as computed from './f1-lib'
import * as escaping from './f2-lib'
import * as mixed from './f3-lib'
import * as receiver from './f4-lib'
import * as directReceiverA from './f4-a'
import * as directReceiverB from './f4-b'
import * as identity from './f5-lib'
import * as directIdentity from './f5-a'
import * as optional from './f6-lib'
import * as live from './f7-lib'
import * as topLevelAwait from './f8-lib'
import * as once from './f9-lib'
import { a as onceA } from './f9-lib'
import * as methodCall from './f10-lib'
import * as optionalCall from './f11-lib'
import * as taggedTemplate from './f12-lib'
import { a as namedMethodCall } from './f13-lib'
import * as parenthesizedCall from './f14-lib'
import * as indirectCall from './f15-lib'
function opaque(value) {
return value
}
it('keeps the whole namespace at the level of a computed access', () => {
const key = ['sib', 'ling'].join('')
expect(computed.a.b[key]).toBe('sibling')
expect(computed.a.b.siblingUsed).toBe(true)
expect(computed.a.aUnusedInfo).toBe(false)
})
it('keeps the whole namespace at the level where it escapes', () => {
const escaped = opaque(escaping.a.b)
expect(escaped.sibling).toBe('sibling')
expect(escaping.a.b.siblingUsed).toBe(true)
expect(escaping.a.aUnusedInfo).toBe(false)
})
it('lets an opaque use win over static reads at the same level only', () => {
expect(mixed.a.b.c.leaf).toBe('leaf')
expect(opaque(mixed.a.b.c).sibling).toBe('sibling')
expect(mixed.a.b.c.siblingUsed).toBe(true)
expect(mixed.a.b.bUnusedInfo).toBe(false)
})
it('keeps the namespace object as the receiver of a method call', () => {
expect(receiver.a.self()).toBe(directReceiverA)
expect(receiver.a.b.self()).toBe(directReceiverB)
})
it('keeps the whole receiver of a nested method call', () => {
// `marker` is only read through `this`.
expect(methodCall.a.b.readMarker()).toBe('marker-10')
// Levels above the receiver are still narrowed.
expect(methodCall.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a nested optional method call', () => {
expect(optionalCall.a.b.readMarker?.()).toBe('marker-11')
expect(optionalCall.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a nested tagged template', () => {
expect(taggedTemplate.a.b.tag`template`).toBe('marker-12')
expect(taggedTemplate.a.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a method call on a namespace-valued named import', () => {
expect(namedMethodCall.b.readMarker()).toBe('marker-13')
expect(namedMethodCall.aUnusedInfo).toBe(false)
})
it('keeps the whole receiver of a parenthesized nested method call', () => {
// prettier-ignore
expect((parenthesizedCall.a.b.readMarker)()).toBe('marker-14')
expect(parenthesizedCall.a.aUnusedInfo).toBe(false)
})
it('still narrows an indirect call, which has no receiver', () => {
expect((0, indirectCall.a.b.readReceiver)()).toBe('no-receiver')
expect(indirectCall.a.b.markerUsed).toBe(false)
})
it('keeps namespace object identity', () => {
expect(identity.a).toBe(directIdentity)
expect(identity.a.leaf).toBe('leaf')
})
it('falls back for optional chaining without breaking runtime behavior', () => {
expect(optional.a?.leaf).toBe('leaf')
expect(optional.a.b?.leaf).toBe('leaf')
})
it('keeps live bindings live through nested namespaces', () => {
expect(live.a.b.count).toBe(0)
live.a.b.increment()
expect(live.a.b.count).toBe(1)
})
it('supports top-level await in a nested namespace target', () => {
expect(topLevelAwait.a.b.value).toBe('top-level-await')
})
it('evaluates a nested namespace target once', () => {
expect(once.a.b.value).toBe('evaluated')
expect(onceA.b.value).toBe('evaluated')
expect(globalThis.namespaceMemberChainEvaluations).toBe(1)
})
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": false
}
// Runtime behavior is covered by the enabled `namespace-value-reexport` fixtures. This remains
// skipped only because member narrowing currently stops at the first namespace level.
// Member narrowing follows the whole static member chain, through every namespace level.
import { nestedNamespace } from './lib'
it('should narrow through a nested namespace-valued export', () => {
......
export class CoreError extends Error {}
export * as locales from '../locales/index.js'
// The zod shape from vercel/next.js#99954: `z.core` is a namespace reexport and
// `z.core.locales` is another one. Only `z.core.CoreError` and `z.string` are read.
import * as z from './lib.js'
console.log(new z.core.CoreError(z.string()))
export * as core from './core/index.js'
export const string = () => 'string'
export { default as en } from './en.js'
export { default as de } from './de.js'
{
"followReexports": true,
"removeUnusedImports": true,
"removeUnusedExports": true,
"scopeHoisting": true
}
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1ece_tests_snapshot_ns-value-reexport_nested-member-chain_input_index_167y-ggsd1uev.js",
{"otherChunks":["output/1jsg_tests_snapshot_ns-value-reexport_nested-member-chain_input_index_1cmvc6c9l91py.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/index.js [test] (ecmascript)"]}
]);
// Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_ns-value-reexport_nested-member-chain_input_index_1cmvc6c9l91py.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/index.js [test] (ecmascript)
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js [test] (ecmascript) <export * as core .CoreError>
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js [test] (ecmascript)
;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js [test] (ecmascript) <locals>
;
class CoreError extends Error {
}
;
__turbopack_context__.s([
"CoreError",
0,
CoreError
], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$nested$2d$member$2d$chain$2f$input$2f$core$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js [test] (ecmascript)");
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$nested$2d$member$2d$chain$2f$input$2f$core$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$nested$2d$member$2d$chain$2f$input$2f$core$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__;
// MERGED MODULE: [project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/lib.js [test] (ecmascript) <locals>
;
;
const string = ()=>'string';
;
console.log(new __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$ns$2d$value$2d$reexport$2f$nested$2d$member$2d$chain$2f$input$2f$core$2f$index$2e$js__$5b$test$5d$__$28$ecmascript$29$__.CoreError(string()));
__turbopack_context__.s([], "[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/index.js [test] (ecmascript)");
}),
]);
//# sourceMappingURL=1jsg_tests_snapshot_ns-value-reexport_nested-member-chain_input_index_1cmvc6c9l91py.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/core/index.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/lib.js","turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/ns-value-reexport/nested-member-chain/input/index.js"],"sourcesContent":["export class CoreError extends Error {}\nexport * as locales from '../locales/index.js'\n","export * as core from './core/index.js'\nexport const string = () => 'string'\n","// The zod shape from vercel/next.js#99954: `z.core` is a namespace reexport and\n// `z.core.locales` is another one. Only `z.core.CoreError` and `z.string` are read.\nimport * as z from './lib.js'\n\nconsole.log(new z.core.CoreError(z.string()))\n"],"names":["CoreError","Error"],"mappings":";;;;;;;;AAAO,MAAMA,kBAAkBC;AAAO;;;;;;;;;;;;ACC/B,MAAM,SAAS,IAAM;;ACG5B,QAAQ,GAAG,CAAC,IAAI,2OAAO,SAAS,CAAC"}}]
}
\ 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