Unverified Commit 7c87468a authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

[turbopack] Use options object for ESM references (#98680)

### What?

Introduce `EsmAssetReferenceOptions`, an explicit options object for ESM
asset references.

### Why?

`EsmAssetReference::new` and `new_pure` accepted a long positional list
of behavioral settings. Call sites were difficult to scan and easy to
misconfigure as the reference grows new behavior.

This is intentionally a behavior-neutral, independently reviewable base
for the two existing tree-shaking PRs above it:

1. This PR centralizes constructor configuration.
2. #96282 uses the options object to configure re-export usage
forwarding.
3. #96396 tracks static member reads through namespace-valued
re-exports.

### How?

Keep the three reference-identity inputs (`module`, `origin`, and
`request`) positional, and move behavioral settings—source location,
annotations, target part, import usage, externals, module-fragment mode,
and resolve override—into a named options struct.

The two constructor call sites now declare their settings by field name.
The refactor removes the `too_many_arguments` allowances without
changing resolution or binding-usage behavior.

### Testing

- `cargo check -p turbopack-ecmascript`
- Analyzer graph tests: 60/60
- The stacked focused execution/snapshot tests, 2/2 usage-lattice units,
`build-all`, and HMR regression are verified on the upper PRs.

<!-- NEXT_JS_LLM -->


<!-- fleet 993ef5d6-cc80-4082-8e14-ff9ac871ce33 -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
parent 3dbf9219
...@@ -443,6 +443,20 @@ pub struct EsmAssetReference { ...@@ -443,6 +443,20 @@ pub struct EsmAssetReference {
extras: Option<Box<EsmReferenceExtras>>, extras: Option<Box<EsmReferenceExtras>>,
} }
/// Construction options for an [`EsmAssetReference`].
///
/// The module, origin, and request stay as constructor arguments because they identify the
/// reference. The remaining behavior is named here so call sites don't depend on argument order.
pub struct EsmAssetReferenceOptions {
pub issue_source: IssueSource,
pub annotations: Option<ImportAnnotations>,
pub export_name: Option<ModulePart>,
pub import_usage: ImportUsage,
pub import_externals: bool,
pub module_fragments_enabled: bool,
pub resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
}
/// Optional extra state for an [`EsmAssetReference`] that is rarely present: the few values /// Optional extra state for an [`EsmAssetReference`] that is rarely present: the few values
/// extracted from `ImportAnnotations` (the full `ImportAnnotations` — a `BTreeMap` plus several /// extracted from `ImportAnnotations` (the full `ImportAnnotations` — a `BTreeMap` plus several
/// `Option`s — is not retained) plus a `resolve_override` from matched inner assets. /// `Option`s — is not retained) plus a `resolve_override` from matched inner assets.
...@@ -499,20 +513,23 @@ impl EsmReferenceExtras { ...@@ -499,20 +513,23 @@ impl EsmReferenceExtras {
} }
impl EsmAssetReference { impl EsmAssetReference {
#[allow(clippy::too_many_arguments)]
async fn new_inner( async fn new_inner(
module: ResolvedVc<EcmascriptModuleAsset>, module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr, request: RcStr,
issue_source: IssueSource, options: EsmAssetReferenceOptions,
annotations: Option<ImportAnnotations>,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
module_fragments_enabled: bool,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
is_pure_import: bool, is_pure_import: bool,
) -> Result<Self> { ) -> Result<Self> {
let EsmAssetReferenceOptions {
issue_source,
annotations,
export_name,
import_usage,
import_externals,
module_fragments_enabled,
resolve_override,
} = options;
// Apply any annotation-driven transition eagerly so the stored origin is final and the // Apply any annotation-driven transition eagerly so the stored origin is final and the
// `annotations` don't need to be retained on the reference. // `annotations` don't need to be retained on the reference.
let origin = if let Some(transition) = annotations.as_ref().and_then(|a| a.transition()) { let origin = if let Some(transition) = annotations.as_ref().and_then(|a| a.transition()) {
...@@ -538,60 +555,26 @@ impl EsmAssetReference { ...@@ -538,60 +555,26 @@ impl EsmAssetReference {
}) })
} }
#[allow(clippy::too_many_arguments)]
pub async fn new( pub async fn new(
module: ResolvedVc<EcmascriptModuleAsset>, module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr, request: RcStr,
issue_source: IssueSource, options: EsmAssetReferenceOptions,
annotations: Option<ImportAnnotations>,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
module_fragments_enabled: bool,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Result<Self> { ) -> Result<Self> {
Self::new_inner( Self::new_inner(
module, module, origin, request, options, /* is_pure_import */ false,
origin,
request,
issue_source,
annotations,
export_name,
import_usage,
import_externals,
module_fragments_enabled,
resolve_override,
/* is_pure_import */ false,
) )
.await .await
} }
#[allow(clippy::too_many_arguments)]
pub async fn new_pure( pub async fn new_pure(
module: ResolvedVc<EcmascriptModuleAsset>, module: ResolvedVc<EcmascriptModuleAsset>,
origin: ResolvedVc<Box<dyn ResolveOrigin>>, origin: ResolvedVc<Box<dyn ResolveOrigin>>,
request: RcStr, request: RcStr,
issue_source: IssueSource, options: EsmAssetReferenceOptions,
annotations: Option<ImportAnnotations>,
export_name: Option<ModulePart>,
import_usage: ImportUsage,
import_externals: bool,
module_fragments_enabled: bool,
resolve_override: Option<ResolvedVc<Box<dyn Module>>>,
) -> Result<Self> { ) -> Result<Self> {
Self::new_inner( Self::new_inner(
module, module, origin, request, options, /* is_pure_import */ true,
origin,
request,
issue_source,
annotations,
export_name,
import_usage,
import_externals,
module_fragments_enabled,
resolve_override,
/* is_pure_import */ true,
) )
.await .await
} }
......
...@@ -9,7 +9,7 @@ pub(crate) mod module_item; ...@@ -9,7 +9,7 @@ pub(crate) mod module_item;
pub(crate) mod url; pub(crate) mod url;
pub use self::{ pub use self::{
base::EsmAssetReference, base::{EsmAssetReference, EsmAssetReferenceOptions},
binding::EsmBinding, binding::EsmBinding,
dynamic::EsmAsyncAssetReference, dynamic::EsmAsyncAssetReference,
export::{EsmExport, EsmExports, FoundExportType, Liveness}, export::{EsmExport, EsmExports, FoundExportType, Liveness},
......
...@@ -20,7 +20,7 @@ use crate::{ ...@@ -20,7 +20,7 @@ use crate::{
parse::ParseResult, parse::ParseResult,
references::{ references::{
TURBOPACK_HELPER_WTF8, TURBOPACK_HELPER_WTF8,
esm::{EsmAssetReference, EsmExports}, esm::{EsmAssetReference, EsmAssetReferenceOptions, EsmExports},
type_issue::SpecifiedModuleTypeIssue, type_issue::SpecifiedModuleTypeIssue,
}, },
runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_EXPORT_VALUE}, runtime_functions::{TURBOPACK_EXPORT_NAMESPACE, TURBOPACK_EXPORT_VALUE},
...@@ -100,41 +100,47 @@ pub async fn compute_ecmascript_module_exports( ...@@ -100,41 +100,47 @@ pub async fn compute_ecmascript_module_exports(
module, module,
ResolvedVc::upcast(module), ResolvedVc::upcast(module),
RcStr::from(&*r.module_path.to_string_lossy()), RcStr::from(&*r.module_path.to_string_lossy()),
IssueSource::from_swc_offsets(source, r.span.lo.to_u32(), r.span.hi.to_u32()), EsmAssetReferenceOptions {
r.annotations.as_ref().map(|a| (**a).clone()), issue_source: IssueSource::from_swc_offsets(
match &r.imported_symbol { source,
&ImportedSymbol::ModuleEvaluation => { r.span.lo.to_u32(),
should_add_evaluation = true; r.span.hi.to_u32(),
Some(ModulePart::evaluation()) ),
} annotations: r.annotations.as_ref().map(|a| (**a).clone()),
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())), export_name: match &r.imported_symbol {
ImportedSymbol::PartEvaluation(part_id) | ImportedSymbol::Part(part_id) => { &ImportedSymbol::ModuleEvaluation => {
if !options.module_fragments_enabled {
bail!(
"Internal imports only exist in reexports only mode when \
importing {:?} from {}",
r.imported_symbol,
r.module_path.to_string_lossy()
);
}
if matches!(&r.imported_symbol, ImportedSymbol::PartEvaluation(_)) {
should_add_evaluation = true; should_add_evaluation = true;
Some(ModulePart::evaluation())
} }
Some(ModulePart::internal(*part_id)) ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())),
} ImportedSymbol::PartEvaluation(part_id) | ImportedSymbol::Part(part_id) => {
ImportedSymbol::Exports => { if !options.module_fragments_enabled {
options.module_fragments_enabled.then(ModulePart::exports) bail!(
} "Internal imports only exist in reexports only mode when \
importing {:?} from {}",
r.imported_symbol,
r.module_path.to_string_lossy()
);
}
if matches!(&r.imported_symbol, ImportedSymbol::PartEvaluation(_)) {
should_add_evaluation = true;
}
Some(ModulePart::internal(*part_id))
}
ImportedSymbol::Exports => {
options.module_fragments_enabled.then(ModulePart::exports)
}
},
import_usage: eval_context
.imports
.import_usage
.get(&i)
.cloned()
.unwrap_or_default(),
import_externals,
module_fragments_enabled: options.module_fragments_enabled,
resolve_override,
}, },
eval_context
.imports
.import_usage
.get(&i)
.cloned()
.unwrap_or_default(),
import_externals,
options.module_fragments_enabled,
resolve_override,
) )
.await? .await?
.resolved_cell(); .resolved_cell();
......
...@@ -134,9 +134,9 @@ use crate::{ ...@@ -134,9 +134,9 @@ use crate::{
dynamic_expression::DynamicExpression, dynamic_expression::DynamicExpression,
emit_collect::{CollectReference, EmitReference}, emit_collect::{CollectReference, EmitReference},
esm::{ esm::{
EsmAssetReference, EsmAsyncAssetReference, EsmBinding, ImportMetaBinding, EsmAssetReference, EsmAssetReferenceOptions, EsmAsyncAssetReference, EsmBinding,
ImportMetaRef, UrlAssetReference, UrlRewriteBehavior, base::EsmAssetReferences, ImportMetaBinding, ImportMetaRef, UrlAssetReference, UrlRewriteBehavior,
module_id::EsmModuleIdAssetReference, base::EsmAssetReferences, module_id::EsmModuleIdAssetReference,
}, },
exports::{EcmascriptExportsAnalysis, compute_ecmascript_module_exports}, exports::{EcmascriptExportsAnalysis, compute_ecmascript_module_exports},
exports_info::{ExportsInfoBinding, ExportsInfoRef}, exports_info::{ExportsInfoBinding, ExportsInfoRef},
...@@ -3739,19 +3739,21 @@ async fn handle_free_var_reference( ...@@ -3739,19 +3739,21 @@ async fn handle_free_var_reference(
state.origin state.origin
}, },
request.clone(), request.clone(),
IssueSource::from_swc_offsets( EsmAssetReferenceOptions {
state.source, issue_source: IssueSource::from_swc_offsets(
span.lo.to_u32(), state.source,
span.hi.to_u32(), span.lo.to_u32(),
), span.hi.to_u32(),
Default::default(), ),
export.clone().map(ModulePart::export), annotations: Default::default(),
// TODO This could be optimized. E.g. referencing `Buffer` in some top export_name: export.clone().map(ModulePart::export),
// level function could set ImportUsage properly here // TODO This could be optimized. E.g. referencing `Buffer` in some top
ImportUsage::TopLevel, // level function could set ImportUsage properly here
state.import_externals, import_usage: ImportUsage::TopLevel,
state.module_fragments_enabled, import_externals: state.import_externals,
None, module_fragments_enabled: state.module_fragments_enabled,
resolve_override: None,
},
) )
.await? .await?
.resolved_cell()) .resolved_cell())
......
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