Commit ec4c08a8 authored by Tobias Koppers's avatar Tobias Koppers

Turbopack: use more restricted enum of esm import

parent 0219ed9e
use anyhow::{Result, anyhow, bail}; use anyhow::{Result, anyhow, bail};
use bincode::{Decode, Encode};
use either::Either; use either::Either;
use strsim::jaro; use strsim::jaro;
use swc_core::{ use swc_core::{
...@@ -10,7 +11,9 @@ use swc_core::{ ...@@ -10,7 +11,9 @@ use swc_core::{
quote, quote,
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc}; use turbo_tasks::{
NonLocalValue, ResolvedVc, ValueToString, Vc, debug::ValueDebugFormat, trace::TraceRawVcs,
};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkingContext, ChunkingType, ChunkingTypeOption, ModuleChunkItemIdExt}, chunk::{ChunkingContext, ChunkingType, ChunkingTypeOption, ModuleChunkItemIdExt},
...@@ -318,6 +321,38 @@ impl EsmAssetReferences { ...@@ -318,6 +321,38 @@ impl EsmAssetReferences {
} }
} }
#[derive(
Hash, PartialEq, Eq, Clone, Debug, ValueDebugFormat, TraceRawVcs, Encode, Decode, NonLocalValue,
)]
pub enum EsmPart {
Namespace,
Evaluation,
Export(RcStr),
Internal(u32),
}
impl Into<Option<ModulePart>> for EsmPart {
fn into(self) -> Option<ModulePart> {
match self {
EsmPart::Evaluation => Some(ModulePart::evaluation()),
EsmPart::Namespace => None,
EsmPart::Export(name) => Some(ModulePart::export(name)),
EsmPart::Internal(id) => Some(ModulePart::internal(id)),
}
}
}
impl Into<ExportUsage> for EsmPart {
fn into(self) -> ExportUsage {
match self {
EsmPart::Export(name) => ExportUsage::Named(name),
EsmPart::Namespace => ExportUsage::All,
EsmPart::Internal(_) => ExportUsage::All,
EsmPart::Evaluation => ExportUsage::Evaluation,
}
}
}
#[turbo_tasks::value(shared)] #[turbo_tasks::value(shared)]
#[derive(Hash, Debug)] #[derive(Hash, Debug)]
pub struct EsmAssetReference { pub struct EsmAssetReference {
...@@ -327,7 +362,7 @@ pub struct EsmAssetReference { ...@@ -327,7 +362,7 @@ pub struct EsmAssetReference {
pub request: RcStr, pub request: RcStr,
pub annotations: ImportAnnotations, pub annotations: ImportAnnotations,
pub issue_source: IssueSource, pub issue_source: IssueSource,
pub export_name: Option<ModulePart>, pub esm_part: EsmPart,
pub import_usage: ImportUsage, pub import_usage: ImportUsage,
pub import_externals: bool, pub import_externals: bool,
pub tree_shaking_mode: Option<TreeShakingMode>, pub tree_shaking_mode: Option<TreeShakingMode>,
...@@ -351,7 +386,7 @@ impl EsmAssetReference { ...@@ -351,7 +386,7 @@ impl EsmAssetReference {
request: RcStr, request: RcStr,
issue_source: IssueSource, issue_source: IssueSource,
annotations: ImportAnnotations, annotations: ImportAnnotations,
export_name: Option<ModulePart>, export_name: EsmPart,
import_usage: ImportUsage, import_usage: ImportUsage,
import_externals: bool, import_externals: bool,
tree_shaking_mode: Option<TreeShakingMode>, tree_shaking_mode: Option<TreeShakingMode>,
...@@ -362,7 +397,7 @@ impl EsmAssetReference { ...@@ -362,7 +397,7 @@ impl EsmAssetReference {
request, request,
issue_source, issue_source,
annotations, annotations,
export_name, esm_part: export_name,
import_usage, import_usage,
import_externals, import_externals,
tree_shaking_mode, tree_shaking_mode,
...@@ -376,7 +411,7 @@ impl EsmAssetReference { ...@@ -376,7 +411,7 @@ impl EsmAssetReference {
request: RcStr, request: RcStr,
issue_source: IssueSource, issue_source: IssueSource,
annotations: ImportAnnotations, annotations: ImportAnnotations,
export_name: Option<ModulePart>, export_name: EsmPart,
import_usage: ImportUsage, import_usage: ImportUsage,
import_externals: bool, import_externals: bool,
tree_shaking_mode: Option<TreeShakingMode>, tree_shaking_mode: Option<TreeShakingMode>,
...@@ -387,7 +422,7 @@ impl EsmAssetReference { ...@@ -387,7 +422,7 @@ impl EsmAssetReference {
request, request,
issue_source, issue_source,
annotations, annotations,
export_name, esm_part: export_name,
import_usage, import_usage,
import_externals, import_externals,
tree_shaking_mode, tree_shaking_mode,
...@@ -408,20 +443,10 @@ impl EsmAssetReference { ...@@ -408,20 +443,10 @@ impl EsmAssetReference {
impl ModuleReference for EsmAssetReference { impl ModuleReference for EsmAssetReference {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> { async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let ty = if let Some(module_type) = self.annotations.module_type() {
EcmaScriptModulesReferenceSubType::ImportWithType(RcStr::from(
&*module_type.to_string_lossy(),
))
} else if let Some(part) = &self.export_name {
EcmaScriptModulesReferenceSubType::ImportPart(part.clone())
} else {
EcmaScriptModulesReferenceSubType::Import
};
let request = Request::parse(self.request.clone().into()); let request = Request::parse(self.request.clone().into());
if let Some(TreeShakingMode::ModuleFragments) = self.tree_shaking_mode { if let Some(TreeShakingMode::ModuleFragments) = self.tree_shaking_mode {
if let Some(ModulePart::Evaluation) = &self.export_name if matches!(self.esm_part, EsmPart::Evaluation)
&& *self.module.side_effects().await? == ModuleSideEffects::SideEffectFree && *self.module.side_effects().await? == ModuleSideEffects::SideEffectFree
{ {
return Ok(ModuleResolveResult { return Ok(ModuleResolveResult {
...@@ -434,21 +459,28 @@ impl ModuleReference for EsmAssetReference { ...@@ -434,21 +459,28 @@ impl ModuleReference for EsmAssetReference {
if let Request::Module { module, .. } = &*request.await? if let Request::Module { module, .. } = &*request.await?
&& module.is_match(TURBOPACK_PART_IMPORT_SOURCE) && module.is_match(TURBOPACK_PART_IMPORT_SOURCE)
{ {
if let Some(part) = &self.export_name { let module_part: Option<ModulePart> = self.esm_part.clone().into();
let ProcessResult::Module(module_part) = let module_part = module_part.unwrap_or(ModulePart::exports());
*EcmascriptModulePartAsset::select_part(*self.module, part.clone()).await? let ProcessResult::Module(module_part) =
else { *EcmascriptModulePartAsset::select_part(*self.module, module_part.clone())
bail!( .await?
"ModulePart::Internal should always return a module part in \ else {
select_part" bail!("ModulePart::Internal should always return a module part in select_part");
); };
}; return Ok(*ModuleResolveResult::module(module_part));
return Ok(*ModuleResolveResult::module(module_part));
}
bail!("export_name is required for part import")
} }
} }
let ty = if let Some(module_type) = self.annotations.module_type() {
EcmaScriptModulesReferenceSubType::ImportWithType(RcStr::from(
&*module_type.to_string_lossy(),
))
} else if let Some(part) = self.esm_part.clone().into() {
EcmaScriptModulesReferenceSubType::ImportPart(part)
} else {
EcmaScriptModulesReferenceSubType::Import
};
let result = esm_resolve( let result = esm_resolve(
self.get_origin(), self.get_origin(),
request, request,
...@@ -457,8 +489,7 @@ impl ModuleReference for EsmAssetReference { ...@@ -457,8 +489,7 @@ impl ModuleReference for EsmAssetReference {
Some(self.issue_source), Some(self.issue_source),
) )
.await?; .await?;
if let EsmPart::Export(export_name) = &self.esm_part {
if let Some(ModulePart::Export(export_name)) = &self.export_name {
for &module in result.primary_modules().await? { for &module in result.primary_modules().await? {
if let Some(module) = ResolvedVc::try_downcast(module) if let Some(module) = ResolvedVc::try_downcast(module)
&& *is_export_missing(*module, export_name.clone()).await? && *is_export_missing(*module, export_name.clone()).await?
...@@ -507,11 +538,7 @@ impl ModuleReference for EsmAssetReference { ...@@ -507,11 +538,7 @@ impl ModuleReference for EsmAssetReference {
fn binding_usage(&self) -> Vc<BindingUsage> { fn binding_usage(&self) -> Vc<BindingUsage> {
BindingUsage { BindingUsage {
import: self.import_usage.clone(), import: self.import_usage.clone(),
export: match &self.export_name { export: self.esm_part.clone().into(),
Some(ModulePart::Export(export_name)) => ExportUsage::Named(export_name.clone()),
Some(ModulePart::Evaluation) => ExportUsage::Evaluation,
_ => ExportUsage::All,
},
} }
.cell() .cell()
} }
...@@ -582,9 +609,7 @@ impl EsmAssetReference { ...@@ -582,9 +609,7 @@ impl EsmAssetReference {
)); ));
} }
if merged_index.is_some() if merged_index.is_some() && matches!(this.esm_part, EsmPart::Evaluation) {
&& matches!(this.export_name, Some(ModulePart::Evaluation))
{
// No need to import, the module was already executed and is available in // No need to import, the module was already executed and is available in
// the same scope hoisting group (unless it's a // the same scope hoisting group (unless it's a
// namespace import) // namespace import)
...@@ -592,10 +617,10 @@ impl EsmAssetReference { ...@@ -592,10 +617,10 @@ impl EsmAssetReference {
let ident = referenced_asset let ident = referenced_asset
.get_ident( .get_ident(
chunking_context, chunking_context,
this.export_name.as_ref().and_then(|e| match e { match &this.esm_part {
ModulePart::Export(export_name) => Some(export_name.clone()), EsmPart::Export(export_name) => Some(export_name.clone()),
_ => None, _ => None,
}), },
scope_hoisting_context, scope_hoisting_context,
) )
.await?; .await?;
......
...@@ -132,7 +132,9 @@ use crate::{ ...@@ -132,7 +132,9 @@ use crate::{
esm::{ esm::{
EsmAssetReference, EsmAsyncAssetReference, EsmBinding, EsmExports, EsmModuleItem, EsmAssetReference, EsmAsyncAssetReference, EsmBinding, EsmExports, EsmModuleItem,
ImportMetaBinding, ImportMetaRef, UrlAssetReference, UrlRewriteBehavior, ImportMetaBinding, ImportMetaRef, UrlAssetReference, UrlRewriteBehavior,
base::EsmAssetReferences, export::EsmExport, module_id::EsmModuleIdAssetReference, base::{EsmAssetReferences, EsmPart},
export::EsmExport,
module_id::EsmModuleIdAssetReference,
}, },
exports_info::{ExportsInfoBinding, ExportsInfoRef}, exports_info::{ExportsInfoBinding, ExportsInfoRef},
ident::IdentReplacement, ident::IdentReplacement,
...@@ -815,9 +817,9 @@ async fn analyze_ecmascript_module_internal( ...@@ -815,9 +817,9 @@ async fn analyze_ecmascript_module_internal(
match &r.imported_symbol { match &r.imported_symbol {
ImportedSymbol::ModuleEvaluation => { ImportedSymbol::ModuleEvaluation => {
should_add_evaluation = true; should_add_evaluation = true;
Some(ModulePart::evaluation()) EsmPart::Evaluation
} }
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())), ImportedSymbol::Symbol(name) => EsmPart::Export((&**name).into()),
ImportedSymbol::PartEvaluation(part_id) | ImportedSymbol::Part(part_id) => { ImportedSymbol::PartEvaluation(part_id) | ImportedSymbol::Part(part_id) => {
if !matches!( if !matches!(
options.tree_shaking_mode, options.tree_shaking_mode,
...@@ -833,13 +835,9 @@ async fn analyze_ecmascript_module_internal( ...@@ -833,13 +835,9 @@ async fn analyze_ecmascript_module_internal(
if matches!(&r.imported_symbol, ImportedSymbol::PartEvaluation(_)) { if matches!(&r.imported_symbol, ImportedSymbol::PartEvaluation(_)) {
should_add_evaluation = true; should_add_evaluation = true;
} }
Some(ModulePart::internal(*part_id)) EsmPart::Internal(*part_id)
} }
ImportedSymbol::Exports => matches!( ImportedSymbol::Exports => EsmPart::Namespace,
options.tree_shaking_mode,
Some(TreeShakingMode::ModuleFragments)
)
.then(ModulePart::exports),
}, },
import_usage.get(&i).cloned().unwrap_or_default(), import_usage.get(&i).cloned().unwrap_or_default(),
import_externals, import_externals,
...@@ -1484,8 +1482,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -1484,8 +1482,7 @@ async fn analyze_ecmascript_module_internal(
// TODO move this logic into Effect creation itself and don't create new // TODO move this logic into Effect creation itself and don't create new
// references after the fact here. // references after the fact here.
let original_reference = r.await?; let original_reference = r.await?;
if original_reference.export_name.is_none() if matches!(original_reference.esm_part, EsmPart::Namespace)
&& export.is_some()
&& let Some(export) = export && let Some(export) = export
{ {
// Rewrite `import * as ns from 'foo'; foo.bar()` to behave like // Rewrite `import * as ns from 'foo'; foo.bar()` to behave like
...@@ -1501,7 +1498,7 @@ async fn analyze_ecmascript_module_internal( ...@@ -1501,7 +1498,7 @@ async fn analyze_ecmascript_module_internal(
original_reference.request.clone(), original_reference.request.clone(),
original_reference.issue_source, original_reference.issue_source,
original_reference.annotations.clone(), original_reference.annotations.clone(),
Some(ModulePart::export(export.clone())), EsmPart::Export(export.clone()),
// TODO this is correct, but an overapproximation. // TODO this is correct, but an overapproximation.
// We should have individual import_usage data for // We should have individual import_usage data for
// each export. This would be fixed by moving this // each export. This would be fixed by moving this
...@@ -2959,7 +2956,10 @@ async fn handle_free_var_reference( ...@@ -2959,7 +2956,10 @@ async fn handle_free_var_reference(
span.hi.to_u32(), span.hi.to_u32(),
), ),
Default::default(), Default::default(),
export.clone().map(ModulePart::export), match export {
Some(name) => EsmPart::Export(name.clone()),
None => EsmPart::Namespace,
},
ImportUsage::TopLevel, ImportUsage::TopLevel,
state.import_externals, state.import_externals,
state.tree_shaking_mode, state.tree_shaking_mode,
......
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