Unverified Commit 1dad3a67 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: make `ModulePart` a `TaskInput` (#75364)

No significant perf impact
parent 7fee0f72
......@@ -246,7 +246,7 @@ async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap
if let Some(module) = Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(module).await?
{
if matches!(
&*module.await?.part.await?,
module.await?.part,
ModulePart::Evaluation | ModulePart::Facade
) {
return Ok(Vc::cell(None));
......
......@@ -50,7 +50,7 @@ impl Transition for NextEcmascriptClientReferenceTransition {
let part = match &*reference_type {
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::ImportPart(
part,
)) => Some(*part),
)) => Some(part),
_ => None,
};
......@@ -59,7 +59,7 @@ impl Transition for NextEcmascriptClientReferenceTransition {
let this = self.await?;
let ident = match part {
Some(part) => source.ident().with_part(*part),
Some(part) => source.ident().with_part(part.clone()),
None => source.ident(),
};
let ident_ref = ident.await?;
......
......@@ -74,7 +74,7 @@ impl CustomModuleType for StructuredImageModuleType {
&self,
source: Vc<Box<dyn Source>>,
module_asset_context: Vc<ModuleAssetContext>,
_part: Option<Vc<ModulePart>>,
_part: Option<ModulePart>,
) -> Vc<Box<dyn Module>> {
StructuredImageModuleType::create_module(
source,
......
......@@ -24,7 +24,7 @@ pub struct AssetIdent {
/// The modifiers of this asset (e.g. `client chunks`)
pub modifiers: Vec<ResolvedVc<RcStr>>,
/// The parts of the asset that are (ECMAScript) modules
pub parts: Vec<ResolvedVc<ModulePart>>,
pub parts: Vec<ModulePart>,
/// The asset layer the asset was created from.
pub layer: Option<ResolvedVc<RcStr>>,
}
......@@ -100,10 +100,9 @@ impl ValueToString for AssetIdent {
if !self.parts.is_empty() {
for part in self.parts.iter() {
let part = part.to_string().await?;
// facade is not included in ident as switching between facade and non-facade
// shouldn't change the ident
if part.as_str() != "facade" {
if !matches!(part, ModulePart::Facade) {
// facade is not included in ident as switching between facade and non-facade
// shouldn't change the ident
write!(s, " <{}>", part)?;
}
}
......@@ -149,7 +148,7 @@ impl AssetIdent {
}
#[turbo_tasks::function]
pub fn with_part(&self, part: ResolvedVc<ModulePart>) -> Vc<Self> {
pub fn with_part(&self, part: ModulePart) -> Vc<Self> {
let mut this = self.clone();
this.parts.push(part);
Self::new(Value::new(this))
......@@ -262,25 +261,25 @@ impl AssetIdent {
}
for part in parts.iter() {
4_u8.deterministic_hash(&mut hasher);
match &*part.await? {
match part {
ModulePart::Evaluation => {
1_u8.deterministic_hash(&mut hasher);
}
ModulePart::Export(export) => {
2_u8.deterministic_hash(&mut hasher);
export.await?.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::RenamedExport {
original_export,
export,
} => {
3_u8.deterministic_hash(&mut hasher);
original_export.await?.deterministic_hash(&mut hasher);
export.await?.deterministic_hash(&mut hasher);
original_export.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::RenamedNamespace { export } => {
4_u8.deterministic_hash(&mut hasher);
export.await?.deterministic_hash(&mut hasher);
export.deterministic_hash(&mut hasher);
}
ModulePart::Internal(id) => {
5_u8.deterministic_hash(&mut hasher);
......
......@@ -43,7 +43,7 @@ pub enum ImportWithType {
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Debug, Default, Clone, Hash)]
pub enum EcmaScriptModulesReferenceSubType {
ImportPart(ResolvedVc<ModulePart>),
ImportPart(ModulePart),
Import,
ImportWithType(ImportWithType),
DynamicImport,
......
......@@ -3052,20 +3052,22 @@ async fn error_severity(resolve_options: Vc<ResolveOptions>) -> Result<ResolvedV
/// ModulePart represents a part of a module.
///
/// Currently this is used only for ESMs.
#[turbo_tasks::value]
#[derive(
Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, TraceRawVcs, TaskInput, NonLocalValue,
)]
pub enum ModulePart {
/// Represents the side effects of a module. This part is evaluated even if
/// all exports are unused.
Evaluation,
/// Represents an export of a module.
Export(ResolvedVc<RcStr>),
Export(RcStr),
/// Represents a renamed export of a module.
RenamedExport {
original_export: ResolvedVc<RcStr>,
export: ResolvedVc<RcStr>,
original_export: RcStr,
export: RcStr,
},
/// Represents a namespace object of a module exported as named export.
RenamedNamespace { export: ResolvedVc<RcStr> },
RenamedNamespace { export: RcStr },
/// A pointer to a specific part.
Internal(u32),
/// A pointer to a specific part, but with evaluation.
......@@ -3079,76 +3081,64 @@ pub enum ModulePart {
Facade,
}
#[turbo_tasks::value_impl]
impl ModulePart {
#[turbo_tasks::function]
pub fn evaluation() -> Vc<Self> {
ModulePart::Evaluation.cell()
pub fn evaluation() -> Self {
ModulePart::Evaluation
}
#[turbo_tasks::function]
pub fn export(export: RcStr) -> Vc<Self> {
ModulePart::Export(ResolvedVc::cell(export)).cell()
pub fn export(export: RcStr) -> Self {
ModulePart::Export(export)
}
#[turbo_tasks::function]
pub fn renamed_export(original_export: RcStr, export: RcStr) -> Vc<Self> {
pub fn renamed_export(original_export: RcStr, export: RcStr) -> Self {
ModulePart::RenamedExport {
original_export: ResolvedVc::cell(original_export),
export: ResolvedVc::cell(export),
original_export,
export,
}
.cell()
}
#[turbo_tasks::function]
pub fn renamed_namespace(export: RcStr) -> Vc<Self> {
ModulePart::RenamedNamespace {
export: ResolvedVc::cell(export),
}
.cell()
pub fn renamed_namespace(export: RcStr) -> Self {
ModulePart::RenamedNamespace { export }
}
#[turbo_tasks::function]
pub fn internal(id: u32) -> Vc<Self> {
ModulePart::Internal(id).cell()
pub fn internal(id: u32) -> Self {
ModulePart::Internal(id)
}
#[turbo_tasks::function]
pub fn internal_evaluation(id: u32) -> Vc<Self> {
ModulePart::InternalEvaluation(id).cell()
pub fn internal_evaluation(id: u32) -> Self {
ModulePart::InternalEvaluation(id)
}
#[turbo_tasks::function]
pub fn locals() -> Vc<Self> {
ModulePart::Locals.cell()
pub fn locals() -> Self {
ModulePart::Locals
}
#[turbo_tasks::function]
pub fn exports() -> Vc<Self> {
ModulePart::Exports.cell()
pub fn exports() -> Self {
ModulePart::Exports
}
#[turbo_tasks::function]
pub fn facade() -> Vc<Self> {
ModulePart::Facade.cell()
pub fn facade() -> Self {
ModulePart::Facade
}
}
#[turbo_tasks::value_impl]
impl ValueToString for ModulePart {
#[turbo_tasks::function]
async fn to_string(&self) -> Result<Vc<RcStr>> {
Ok(Vc::cell(match self {
ModulePart::Evaluation => "module evaluation".into(),
ModulePart::Export(export) => format!("export {}", export.await?).into(),
impl Display for ModulePart {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ModulePart::Evaluation => f.write_str("module evaluation"),
ModulePart::Export(export) => write!(f, "export {}", export),
ModulePart::RenamedExport {
original_export,
export,
} => {
let original_export = original_export.await?;
let export = export.await?;
format!("export {} as {}", original_export, export).into()
}
} => write!(f, "export {} as {}", original_export, export),
ModulePart::RenamedNamespace { export } => {
format!("export * as {}", export.await?).into()
write!(f, "export * as {}", export)
}
ModulePart::Internal(id) => format!("internal part {}", id).into(),
ModulePart::InternalEvaluation(id) => format!("internal part {}", id).into(),
ModulePart::Locals => "locals".into(),
ModulePart::Exports => "exports".into(),
ModulePart::Facade => "facade".into(),
}))
ModulePart::Internal(id) => write!(f, "internal part {}", id),
ModulePart::InternalEvaluation(id) => write!(f, "internal part {}", id),
ModulePart::Locals => f.write_str("locals"),
ModulePart::Exports => f.write_str("exports"),
ModulePart::Facade => f.write_str("facade"),
}
}
}
......@@ -117,7 +117,7 @@ pub struct EsmAssetReference {
pub request: ResolvedVc<Request>,
pub annotations: ImportAnnotations,
pub issue_source: IssueSource,
pub export_name: Option<ResolvedVc<ModulePart>>,
pub export_name: Option<ModulePart>,
pub import_externals: bool,
}
......@@ -137,7 +137,7 @@ impl EsmAssetReference {
request: ResolvedVc<Request>,
issue_source: IssueSource,
annotations: Value<ImportAnnotations>,
export_name: Option<ResolvedVc<ModulePart>>,
export_name: Option<ModulePart>,
import_externals: bool,
) -> Vc<Self> {
Self::cell(EsmAssetReference {
......@@ -166,20 +166,20 @@ impl ModuleReference for EsmAssetReference {
let ty = if matches!(self.annotations.module_type(), Some("json")) {
EcmaScriptModulesReferenceSubType::ImportWithType(ImportWithType::Json)
} else if let Some(part) = &self.export_name {
EcmaScriptModulesReferenceSubType::ImportPart(*part)
EcmaScriptModulesReferenceSubType::ImportPart(part.clone())
} else {
EcmaScriptModulesReferenceSubType::Import
};
if let Request::Module { module, .. } = &*self.request.await? {
if module == TURBOPACK_PART_IMPORT_SOURCE {
if let Some(part) = self.export_name {
if let Some(part) = &self.export_name {
let module: ResolvedVc<crate::EcmascriptModuleAsset> =
ResolvedVc::try_downcast_type(self.origin)
.expect("EsmAssetReference origin should be a EcmascriptModuleAsset");
return Ok(ModuleResolveResult::module(
EcmascriptModulePartAsset::select_part(*module, *part)
EcmascriptModulePartAsset::select_part(*module, part.clone())
.to_resolved()
.await?,
)
......@@ -199,21 +199,17 @@ impl ModuleReference for EsmAssetReference {
)
.await?;
if let Some(part) = self.export_name {
let part = part.await?;
if let &ModulePart::Export(export_name) = &*part {
for &module in result.primary_modules().await? {
if let Some(module) = ResolvedVc::try_downcast(module) {
let export = export_name.await?;
if *is_export_missing(*module, export.clone_value()).await? {
InvalidExport {
export: export_name,
module,
source: self.issue_source.clone(),
}
.resolved_cell()
.emit();
if let Some(ModulePart::Export(export_name)) = &self.export_name {
for &module in result.primary_modules().await? {
if let Some(module) = ResolvedVc::try_downcast(module) {
if *is_export_missing(*module, export_name.clone()).await? {
InvalidExport {
export: export_name.clone(),
module,
source: self.issue_source.clone(),
}
.resolved_cell()
.emit();
}
}
}
......@@ -413,7 +409,7 @@ fn var_decl_with_span(mut decl: Stmt, span: Span) -> Stmt {
#[turbo_tasks::value(shared)]
pub struct InvalidExport {
export: ResolvedVc<RcStr>,
export: RcStr,
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
source: IssueSource,
}
......@@ -429,7 +425,7 @@ impl Issue for InvalidExport {
async fn title(&self) -> Result<Vc<StyledString>> {
Ok(StyledString::Line(vec![
StyledString::Text("Export ".into()),
StyledString::Code(self.export.await?.clone_value()),
StyledString::Code(self.export.clone()),
StyledString::Text(" doesn't exist in target module".into()),
])
.cell())
......@@ -447,18 +443,17 @@ impl Issue for InvalidExport {
#[turbo_tasks::function]
async fn description(&self) -> Result<Vc<OptionStyledString>> {
let export = self.export.await?;
let export_names = all_known_export_names(*self.module).await?;
let did_you_mean = export_names
.iter()
.map(|s| (s, jaro(export.as_str(), s.as_str())))
.map(|s| (s, jaro(self.export.as_str(), s.as_str())))
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
.map(|(s, _)| s);
Ok(Vc::cell(Some(
StyledString::Stack(vec![
StyledString::Line(vec![
StyledString::Text("The export ".into()),
StyledString::Code(export.clone_value()),
StyledString::Code(self.export.clone()),
StyledString::Text(" was not found in module ".into()),
StyledString::Strong(self.module.ident().to_string().await?.clone_value()),
StyledString::Text(".".into()),
......
......@@ -369,7 +369,7 @@ where
#[turbo_tasks::function]
pub(crate) async fn analyse_ecmascript_module(
module: ResolvedVc<EcmascriptModuleAsset>,
part: Option<Vc<ModulePart>>,
part: Option<ModulePart>,
) -> Result<Vc<AnalyzeEcmascriptModuleResult>> {
let span = {
let module = module.ident().to_string().await?.to_string();
......@@ -390,7 +390,7 @@ pub(crate) async fn analyse_ecmascript_module(
pub(crate) async fn analyse_ecmascript_module_internal(
module: ResolvedVc<EcmascriptModuleAsset>,
part: Option<Vc<ModulePart>>,
part: Option<ModulePart>,
) -> Result<Vc<AnalyzeEcmascriptModuleResult>> {
let raw_module = module.await?;
......@@ -416,7 +416,7 @@ pub(crate) async fn analyse_ecmascript_module_internal(
let parsed = if let Some(part) = part {
let parsed = parse(*source, ty, *transforms);
let split_data = split(source.ident(), *source, parsed);
part_of_module(split_data, part)
part_of_module(split_data, part.clone())
} else {
module.failsafe_parse()
};
......@@ -625,32 +625,22 @@ pub(crate) async fn analyse_ecmascript_module_internal(
Some(TreeShakingMode::ModuleFragments) => match &r.imported_symbol {
ImportedSymbol::ModuleEvaluation => {
evaluation_references.push(i);
Some(ModulePart::evaluation().to_resolved().await?)
}
ImportedSymbol::Symbol(name) => {
Some(ModulePart::export((&**name).into()).to_resolved().await?)
Some(ModulePart::evaluation())
}
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())),
ImportedSymbol::PartEvaluation(part_id) => {
evaluation_references.push(i);
Some(
ModulePart::internal_evaluation(*part_id)
.to_resolved()
.await?,
)
}
ImportedSymbol::Part(part_id) => {
Some(ModulePart::internal(*part_id).to_resolved().await?)
Some(ModulePart::internal_evaluation(*part_id))
}
ImportedSymbol::Exports => Some(ModulePart::exports().to_resolved().await?),
ImportedSymbol::Part(part_id) => Some(ModulePart::internal(*part_id)),
ImportedSymbol::Exports => Some(ModulePart::exports()),
},
Some(TreeShakingMode::ReexportsOnly) => match &r.imported_symbol {
ImportedSymbol::ModuleEvaluation => {
evaluation_references.push(i);
Some(ModulePart::evaluation().to_resolved().await?)
}
ImportedSymbol::Symbol(name) => {
Some(ModulePart::export((&**name).into()).to_resolved().await?)
Some(ModulePart::evaluation())
}
ImportedSymbol::Symbol(name) => Some(ModulePart::export((&**name).into())),
ImportedSymbol::PartEvaluation(_) | ImportedSymbol::Part(_) => {
bail!("Internal imports doesn't exist in reexports only mode")
}
......@@ -1279,7 +1269,7 @@ pub(crate) async fn analyse_ecmascript_module_internal(
r_ref.request,
r_ref.issue_source.clone(),
Value::new(r_ref.annotations.clone()),
Some(ModulePart::export(export).to_resolved().await?),
Some(ModulePart::export(export)),
r_ref.import_externals,
)
.to_resolved()
......@@ -2462,11 +2452,7 @@ async fn handle_free_var_reference(
match state.tree_shaking_mode {
Some(TreeShakingMode::ModuleFragments)
| Some(TreeShakingMode::ReexportsOnly) => {
if let Some(export) = export {
Some(ModulePart::export(export.clone()).to_resolved().await?)
} else {
None
}
export.clone().map(ModulePart::export)
}
None => None,
},
......
......@@ -30,16 +30,13 @@ use crate::{
#[turbo_tasks::value]
pub struct EcmascriptModuleFacadeModule {
pub module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
pub ty: ResolvedVc<ModulePart>,
pub ty: ModulePart,
}
#[turbo_tasks::value_impl]
impl EcmascriptModuleFacadeModule {
#[turbo_tasks::function]
pub fn new(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
ty: ResolvedVc<ModulePart>,
) -> Vc<Self> {
pub fn new(module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>, ty: ModulePart) -> Vc<Self> {
EcmascriptModuleFacadeModule { module, ty }.cell()
}
......@@ -68,12 +65,12 @@ impl Module for EcmascriptModuleFacadeModule {
async fn ident(&self) -> Result<Vc<AssetIdent>> {
let inner = self.module.ident();
Ok(inner.with_part(*self.ty))
Ok(inner.with_part(self.ty.clone()))
}
#[turbo_tasks::function]
async fn references(&self) -> Result<Vc<ModuleReferences>> {
let references = match &*self.ty.await? {
let references = match &self.ty {
ModulePart::Evaluation => {
let Some(module) =
ResolvedVc::try_sidecast::<Box<dyn EcmascriptAnalyzable>>(self.module)
......@@ -184,7 +181,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
let mut exports = BTreeMap::new();
let mut star_exports = Vec::new();
match &*self.ty.await? {
match &self.ty {
ModulePart::Exports => {
let EcmascriptExports::EsmExports(esm_exports) = *self.module.get_exports().await?
else {
......@@ -270,23 +267,22 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
original_export,
export,
} => {
let original_export = original_export.await?;
exports.insert(
export.await?.clone_value(),
export.clone(),
EsmExport::ImportedBinding(
ResolvedVc::upcast(
EcmascriptModulePartReference::new(*self.module)
.to_resolved()
.await?,
),
original_export.clone_value(),
original_export.clone(),
false,
),
);
}
ModulePart::RenamedNamespace { export } => {
exports.insert(
export.await?.clone_value(),
export.clone(),
EsmExport::ImportedNamespace(ResolvedVc::upcast(
EcmascriptModulePartReference::new(*self.module)
.to_resolved()
......@@ -313,7 +309,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModuleFacadeModule {
&self,
side_effect_free_packages: Vc<Glob>,
) -> Result<Vc<bool>> {
Ok(match *self.ty.await? {
Ok(match self.ty {
ModulePart::Evaluation | ModulePart::Facade => self
.module
.is_marked_as_side_effect_free(side_effect_free_packages),
......
......@@ -29,7 +29,7 @@ use crate::{
#[turbo_tasks::value]
pub struct EcmascriptModulePartReference {
pub module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
pub part: Option<ResolvedVc<ModulePart>>,
pub part: Option<ModulePart>,
}
#[turbo_tasks::value_impl]
......@@ -37,7 +37,7 @@ impl EcmascriptModulePartReference {
#[turbo_tasks::function]
pub fn new_part(
module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
part: ResolvedVc<ModulePart>,
part: ModulePart,
) -> Vc<Self> {
EcmascriptModulePartReference {
module,
......@@ -55,9 +55,11 @@ impl EcmascriptModulePartReference {
#[turbo_tasks::value_impl]
impl ValueToString for EcmascriptModulePartReference {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
self.part
.map_or_else(|| Vc::cell("module".into()), |part| part.to_string())
async fn to_string(&self) -> Result<Vc<RcStr>> {
Ok(match &self.part {
Some(part) => Vc::cell(part.to_string().into()),
None => Vc::cell("module".into()),
})
}
}
......@@ -65,8 +67,8 @@ impl ValueToString for EcmascriptModulePartReference {
impl ModuleReference for EcmascriptModulePartReference {
#[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
let module = if let Some(part) = self.part {
match *part.await? {
let module = if let Some(part) = &self.part {
match part {
ModulePart::Locals => {
let Some(module) = ResolvedVc::try_downcast_type(self.module) else {
bail!(
......@@ -80,15 +82,15 @@ impl ModuleReference for EcmascriptModulePartReference {
| ModulePart::Evaluation
| ModulePart::Facade
| ModulePart::RenamedExport { .. }
| ModulePart::RenamedNamespace { .. } => {
Vc::upcast(EcmascriptModuleFacadeModule::new(*self.module, *part))
}
| ModulePart::RenamedNamespace { .. } => Vc::upcast(
EcmascriptModuleFacadeModule::new(*self.module, part.clone()),
),
ModulePart::Export(..)
| ModulePart::Internal(..)
| ModulePart::InternalEvaluation(..) => {
bail!(
"Unexpected ModulePart {} for EcmascriptModulePartReference",
part.to_string().await?
"Unexpected ModulePart \"{}\" for EcmascriptModulePartReference",
part
);
}
}
......
......@@ -35,7 +35,7 @@ use crate::{
#[turbo_tasks::value]
pub struct EcmascriptModulePartAsset {
pub full_module: ResolvedVc<EcmascriptModuleAsset>,
pub part: ResolvedVc<ModulePart>,
pub part: ModulePart,
}
#[turbo_tasks::value_impl]
......@@ -44,7 +44,7 @@ impl EcmascriptParsable for EcmascriptModulePartAsset {
async fn failsafe_parse(&self) -> Result<Vc<ParseResult>> {
let parsed = self.full_module.failsafe_parse();
let split_data = split(self.full_module.ident(), self.full_module.source(), parsed);
Ok(part_of_module(split_data, *self.part))
Ok(part_of_module(split_data, self.part.clone()))
}
#[turbo_tasks::function]
fn parse_original(&self) -> Vc<ParseResult> {
......@@ -61,8 +61,7 @@ impl EcmascriptParsable for EcmascriptModulePartAsset {
impl EcmascriptAnalyzable for EcmascriptModulePartAsset {
#[turbo_tasks::function]
fn analyze(&self) -> Vc<AnalyzeEcmascriptModuleResult> {
let part = self.part;
analyse_ecmascript_module(*self.full_module, Some(*part))
analyse_ecmascript_module(*self.full_module, Some(self.part.clone()))
}
#[turbo_tasks::function]
......@@ -94,10 +93,10 @@ impl EcmascriptModulePartAsset {
#[turbo_tasks::function]
pub async fn new(
module: ResolvedVc<EcmascriptModuleAsset>,
part: ResolvedVc<ModulePart>,
part: ModulePart,
) -> Result<Vc<Self>> {
if matches!(
&*part.await?,
part,
ModulePart::Internal(..)
| ModulePart::InternalEvaluation(..)
| ModulePart::Facade
......@@ -113,11 +112,11 @@ impl EcmascriptModulePartAsset {
// This is a workaround to avoid creating duplicate assets for internal parts.
let split_result = split_module(*module).await?;
let part_id = get_part_id(&split_result, *part).await?;
let part_id = get_part_id(&split_result, &part).await?;
Ok(EcmascriptModulePartAsset {
full_module: module,
part: ModulePart::internal(part_id).to_resolved().await?,
part: ModulePart::internal(part_id),
}
.cell())
}
......@@ -125,20 +124,21 @@ impl EcmascriptModulePartAsset {
#[turbo_tasks::function]
pub async fn select_part(
module: Vc<EcmascriptModuleAsset>,
part: ResolvedVc<ModulePart>,
part: ModulePart,
) -> Result<Vc<Box<dyn Module>>> {
let SplitResult::Ok { entrypoints, .. } = &*split_module(module).await? else {
return Ok(Vc::upcast(module));
};
// We follow reexports here
if let ModulePart::Export(export) = &*part.await? {
let export_name = export.await?.clone_value();
if let ModulePart::Export(export) = part {
// If a local binding or reexport with the same name exists, we stop here.
// Side effects of the barrel file are preserved.
if entrypoints.contains_key(&Key::Export(export_name.clone())) {
return Ok(Vc::upcast(EcmascriptModulePartAsset::new(module, *part)));
if entrypoints.contains_key(&Key::Export(export.clone())) {
return Ok(Vc::upcast(EcmascriptModulePartAsset::new(
module,
ModulePart::Export(export),
)));
}
let side_effect_free_packages = module.asset_context().side_effect_free_packages();
......@@ -151,7 +151,7 @@ impl EcmascriptModulePartAsset {
result,
} = &*follow_reexports_with_side_effects(
source_module,
export_name.clone(),
export.clone(),
side_effect_free_packages,
)
.await?;
......@@ -163,13 +163,13 @@ impl EcmascriptModulePartAsset {
} = &*result.await?;
let final_module = if let Some(new_export) = new_export {
if *new_export == export_name {
if *new_export == export {
*final_module
} else {
ResolvedVc::upcast(
EcmascriptModuleFacadeModule::new(
**final_module,
ModulePart::renamed_export(new_export.clone(), export_name.clone()),
ModulePart::renamed_export(new_export.clone(), export.clone()),
)
.to_resolved()
.await?,
......@@ -179,7 +179,7 @@ impl EcmascriptModulePartAsset {
ResolvedVc::upcast(
EcmascriptModuleFacadeModule::new(
**final_module,
ModulePart::renamed_namespace(export_name.clone()),
ModulePart::renamed_namespace(export.clone()),
)
.to_resolved()
.await?,
......@@ -192,7 +192,7 @@ impl EcmascriptModulePartAsset {
let side_effects_module = SideEffectsModule::new(
module,
*part,
ModulePart::Export(export),
*final_module,
side_effects.iter().map(|v| **v).collect(),
);
......@@ -200,13 +200,16 @@ impl EcmascriptModulePartAsset {
return Ok(Vc::upcast(side_effects_module));
}
Ok(Vc::upcast(EcmascriptModulePartAsset::new(module, *part)))
Ok(Vc::upcast(EcmascriptModulePartAsset::new(
module,
part.clone(),
)))
}
#[turbo_tasks::function]
pub async fn is_async_module(self: Vc<Self>) -> Result<Vc<bool>> {
let this = self.await?;
let result = analyze(*this.full_module, *this.part);
let result = analyze(*this.full_module, this.part.clone());
if let Some(async_module) = *result.await?.async_module.await? {
Ok(async_module.is_self_async(self.references()))
......@@ -277,7 +280,7 @@ async fn follow_reexports_with_side_effects(
impl Module for EcmascriptModulePartAsset {
#[turbo_tasks::function]
fn ident(&self) -> Vc<AssetIdent> {
self.full_module.ident().with_part(*self.part)
self.full_module.ident().with_part(self.part.clone())
}
#[turbo_tasks::function]
......@@ -289,14 +292,14 @@ impl Module for EcmascriptModulePartAsset {
async fn references(&self) -> Result<Vc<ModuleReferences>> {
let split_data = split_module(*self.full_module).await?;
let analyze = analyze(*self.full_module, *self.part).await?;
let analyze = analyze(*self.full_module, self.part.clone()).await?;
let deps = match &*split_data {
SplitResult::Ok { deps, .. } => deps,
SplitResult::Failed { .. } => return Ok(*analyze.references),
};
let part_dep = |part: Vc<ModulePart>| -> Vc<Box<dyn ModuleReference>> {
let part_dep = |part: ModulePart| -> Vc<Box<dyn ModuleReference>> {
Vc::upcast(SingleModuleReference::new(
Vc::upcast(EcmascriptModulePartAsset::new(*self.full_module, part)),
Vc::cell("ecmascript module part".into()),
......@@ -306,14 +309,14 @@ impl Module for EcmascriptModulePartAsset {
let mut references = analyze.references.await?.to_vec();
// Facade depends on evaluation and re-exports
if matches!(&*self.part.await?, ModulePart::Facade) {
if self.part == ModulePart::Facade {
references.push(part_dep(ModulePart::evaluation()).to_resolved().await?);
references.push(part_dep(ModulePart::exports()).to_resolved().await?);
return Ok(Vc::cell(references));
}
let deps = {
let part_id = get_part_id(&split_data, *self.part)
let part_id = get_part_id(&split_data, &self.part)
.await
.with_context(|| format!("part {:?} is not found in the module", self.part))?;
......@@ -370,7 +373,7 @@ impl EcmascriptChunkPlaceable for EcmascriptModulePartAsset {
) -> Result<Vc<bool>> {
let this = self.await?;
match *this.part.await? {
match this.part {
ModulePart::Exports | ModulePart::Export(..) => Ok(Vc::cell(true)),
_ => Ok(this
.full_module
......@@ -402,14 +405,14 @@ impl ChunkableModule for EcmascriptModulePartAsset {
impl EcmascriptModulePartAsset {
#[turbo_tasks::function]
pub(super) fn analyze(&self) -> Vc<AnalyzeEcmascriptModuleResult> {
analyze(*self.full_module, *self.part)
analyze(*self.full_module, self.part.clone())
}
}
#[turbo_tasks::function]
fn analyze(
module: Vc<EcmascriptModuleAsset>,
part: Vc<ModulePart>,
part: ModulePart,
) -> Vc<AnalyzeEcmascriptModuleResult> {
analyse_ecmascript_module(module, Some(part))
}
......
......@@ -49,7 +49,7 @@ impl EcmascriptChunkItem for EcmascriptModulePartChunkItem {
let module = self.module.await?;
let split_data = split_module(*module.full_module);
let parsed = part_of_module(split_data, *module.part);
let parsed = part_of_module(split_data, module.part.clone());
let analyze = self.module.analyze().await?;
let async_module_options = analyze.async_module.module_options(async_module_info);
......
......@@ -379,14 +379,12 @@ pub(crate) enum Key {
Exports,
}
/// Converts [Vc<ModulePart>] to the index.
async fn get_part_id(result: &SplitResult, part: Vc<ModulePart>) -> Result<u32> {
let part = part.await?;
/// Converts [ModulePart] to the index.
async fn get_part_id(result: &SplitResult, part: &ModulePart) -> Result<u32> {
// TODO implement ModulePart::Facade
let key = match &*part {
let key = match part {
ModulePart::Evaluation => Key::ModuleEvaluation,
ModulePart::Export(export) => Key::Export(export.await?.as_str().into()),
ModulePart::Export(export) => Key::Export(export.clone()),
ModulePart::Exports => Key::Exports,
ModulePart::Internal(part_id) | ModulePart::InternalEvaluation(part_id) => {
return Ok(*part_id)
......@@ -413,7 +411,7 @@ async fn get_part_id(result: &SplitResult, part: Vc<ModulePart>) -> Result<u32>
}
// This is required to handle `export * from 'foo'`
if let ModulePart::Export(..) = &*part {
if let ModulePart::Export(..) = part {
if let Some(&v) = entrypoints.get(&Key::Exports) {
return Ok(v);
}
......@@ -611,7 +609,7 @@ pub(super) async fn split(
#[turbo_tasks::function]
pub(crate) async fn part_of_module(
split_data: Vc<SplitResult>,
part: Vc<ModulePart>,
part: ModulePart,
) -> Result<Vc<ParseResult>> {
let split_data = split_data.await?;
......@@ -626,7 +624,7 @@ pub(crate) async fn part_of_module(
} => {
debug_assert_ne!(modules.len(), 0, "modules.len() == 0");
if matches!(&*part.await?, ModulePart::Facade) {
if part == ModulePart::Facade {
if let ParseResult::Ok {
comments,
eval_context,
......@@ -718,7 +716,7 @@ pub(crate) async fn part_of_module(
}
}
let part_id = get_part_id(&split_data, part).await?;
let part_id = get_part_id(&split_data, &part).await?;
if part_id as usize >= modules.len() {
bail!(
......
......@@ -23,7 +23,7 @@ pub(super) struct SideEffectsModule {
/// Original module
pub module: ResolvedVc<EcmascriptModuleAsset>,
/// The part of the original module that is the binding
pub part: ResolvedVc<ModulePart>,
pub part: ModulePart,
/// The module that is the binding
pub resolved_as: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
/// Side effects from the original module to the binding.
......@@ -35,7 +35,7 @@ impl SideEffectsModule {
#[turbo_tasks::function]
pub fn new(
module: ResolvedVc<EcmascriptModuleAsset>,
part: ResolvedVc<ModulePart>,
part: ModulePart,
resolved_as: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
side_effects: Vec<ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>>,
) -> Vc<Self> {
......@@ -54,7 +54,7 @@ impl Module for SideEffectsModule {
#[turbo_tasks::function]
async fn ident(&self) -> Result<Vc<AssetIdent>> {
let mut ident = self.module.ident().await?.clone_value();
ident.parts.push(self.part);
ident.parts.push(self.part.clone());
ident.add_asset(
ResolvedVc::cell(RcStr::from("resolved")),
......
......@@ -71,7 +71,7 @@ async fn apply_module_type(
source: ResolvedVc<Box<dyn Source>>,
module_asset_context: Vc<ModuleAssetContext>,
module_type: Vc<ModuleType>,
part: Option<Vc<ModulePart>>,
part: Option<ModulePart>,
inner_assets: Option<ResolvedVc<InnerAssets>>,
css_import_context: Option<Vc<ImportContext>>,
runtime_code: bool,
......@@ -139,25 +139,21 @@ async fn apply_module_type(
ResolvedVc::upcast(builder.build().to_resolved().await?)
} else {
let module = builder.build().resolve().await?;
let part_ref = if let Some(part) = part {
Some((part.await?, part))
} else {
None
};
if let Some((part, _)) = part_ref {
if let ModulePart::Evaluation | ModulePart::InternalEvaluation(..) = &*part {
// Skip the evaluation part if the module is marked as side effect free.
let side_effect_free_packages = module_asset_context
.side_effect_free_packages()
.resolve()
.await?;
if *module
.is_marked_as_side_effect_free(side_effect_free_packages)
.await?
{
return Ok(ProcessResult::Ignore.cell());
}
if matches!(
&part,
Some(ModulePart::Evaluation | ModulePart::InternalEvaluation(..))
) {
// Skip the evaluation part if the module is marked as side effect free.
let side_effect_free_packages = module_asset_context
.side_effect_free_packages()
.resolve()
.await?;
if *module
.is_marked_as_side_effect_free(side_effect_free_packages)
.await?
{
return Ok(ProcessResult::Ignore.cell());
}
}
......@@ -171,7 +167,7 @@ async fn apply_module_type(
}
Some(TreeShakingMode::ReexportsOnly) => {
if let Some(part) = part {
match *part.await? {
match part {
ModulePart::Evaluation => {
if *module.get_exports().needs_facade().await? {
Vc::upcast(EcmascriptModuleFacadeModule::new(
......@@ -212,7 +208,7 @@ async fn apply_module_type(
_ => bail!(
"Invalid module part \"{}\" for reexports only tree shaking \
mode",
part.to_string().await?
part
),
}
} else if *module.get_exports().needs_facade().await? {
......@@ -279,35 +275,28 @@ async fn apply_module_type(
#[turbo_tasks::function]
async fn apply_reexport_tree_shaking(
module: Vc<Box<dyn EcmascriptChunkPlaceable>>,
part: Vc<ModulePart>,
part: ModulePart,
side_effect_free_packages: Vc<Glob>,
) -> Result<Vc<Box<dyn Module>>> {
if let ModulePart::Export(export) = *part.await? {
let export = export.await?;
if let ModulePart::Export(export) = &part {
let FollowExportsResult {
module: final_module,
export_name: new_export,
..
} = &*follow_reexports(
module,
export.clone_value(),
side_effect_free_packages,
false,
)
.await?;
} = &*follow_reexports(module, export.clone(), side_effect_free_packages, false).await?;
let module = if let Some(new_export) = new_export {
if *new_export == *export {
Vc::upcast(**final_module)
} else {
Vc::upcast(EcmascriptModuleFacadeModule::new(
**final_module,
ModulePart::renamed_export(new_export.clone(), export.clone_value()),
ModulePart::renamed_export(new_export.clone(), export.clone()),
))
}
} else {
Vc::upcast(EcmascriptModuleFacadeModule::new(
**final_module,
ModulePart::renamed_namespace(export.clone_value()),
ModulePart::renamed_namespace(export.clone()),
))
};
return Ok(module);
......@@ -502,9 +491,9 @@ async fn process_default_internal(
);
let reference_type = reference_type.into_value();
let part: Option<Vc<ModulePart>> = match &reference_type {
let part: Option<ModulePart> = match &reference_type {
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::ImportPart(part)) => {
Some(**part)
Some(part.clone())
}
_ => None,
};
......
......@@ -9,6 +9,6 @@ pub trait CustomModuleType {
self: Vc<Self>,
source: Vc<Box<dyn Source>>,
module_asset_context: Vc<ModuleAssetContext>,
part: Option<Vc<ModulePart>>,
part: Option<ModulePart>,
) -> Vc<Box<dyn Module>>;
}
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