Unverified Commit 2d37f070 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[turbopack] Simplify up and dowcasts (#83456)

## What 
Casting `ResolvedVc<Box<dyn Module>>` to `ResolvedVc<Box<dyn Module>>` is confusing, so we should reject it.

Ditto for no op `upcast`s.

This PR makes such calls illegal and eliminates them from the codebase.

## How

Introduce a new trait `UpcastStrict` that is only implemented for types that extend or implement different traits.  This way we can say it is only valid to try to downcast if the target type is `UpcastStrict`.  

Then modify the type constraints on our casting utilties to require `UpcastStrict` instead of `Upcast`

In the case of `Vc::upcast` i also introduced a `Vc::upcast_non_strict` to help with writing generic code or extension traits.

## Why?

I got very confused by some `try_downcast` calls that turned out to be no-ops.

Of course this might make some type theorists unhappy, and I don't disagree.  Downcasting X->X is a legitimate operation.   The ideal solution here would be a linter rule, but there doesn't appear to be any way to implement that.
parent 24c71410
...@@ -525,8 +525,7 @@ async fn benchmark_file_io( ...@@ -525,8 +525,7 @@ async fn benchmark_file_io(
directory: FileSystemPath, directory: FileSystemPath,
) -> Result<Vc<Completion>> { ) -> Result<Vc<Completion>> {
// try to get the real file path on disk so that we can use it with tokio // try to get the real file path on disk so that we can use it with tokio
let fs = Vc::try_resolve_downcast_type::<DiskFileSystem>(directory.fs()) let fs = ResolvedVc::try_downcast_type::<DiskFileSystem>(directory.fs)
.await?
.context(anyhow!( .context(anyhow!(
"expected node_root to be a DiskFileSystem, cannot benchmark" "expected node_root to be a DiskFileSystem, cannot benchmark"
))? ))?
......
...@@ -383,7 +383,7 @@ impl AppProject { ...@@ -383,7 +383,7 @@ impl AppProject {
)), )),
module_styles_rule_condition(), module_styles_rule_condition(),
]), ]),
ResolvedVc::upcast(self.css_client_reference_transition().to_resolved().await?), self.css_client_reference_transition().to_resolved().await?,
), ),
// Don't wrap in marker module but change context, this is used to determine // Don't wrap in marker module but change context, this is used to determine
// the list of CSS module classes. // the list of CSS module classes.
...@@ -399,7 +399,7 @@ impl AppProject { ...@@ -399,7 +399,7 @@ impl AppProject {
// Mark as client reference all regular CSS imports // Mark as client reference all regular CSS imports
TransitionRule::new( TransitionRule::new(
styles_rule_condition(), styles_rule_condition(),
ResolvedVc::upcast(self.css_client_reference_transition().to_resolved().await?), self.css_client_reference_transition().to_resolved().await?,
), ),
], ],
..Default::default() ..Default::default()
...@@ -413,7 +413,7 @@ impl AppProject { ...@@ -413,7 +413,7 @@ impl AppProject {
self.get_rsc_transitions( self.get_rsc_transitions(
self.ecmascript_client_reference_transition(), self.ecmascript_client_reference_transition(),
Vc::upcast(self.ssr_transition()), Vc::upcast(self.ssr_transition()),
Vc::upcast(self.shared_transition()), self.shared_transition(),
), ),
self.project().server_compile_time_info(), self.project().server_compile_time_info(),
self.rsc_module_options_context(), self.rsc_module_options_context(),
...@@ -428,7 +428,7 @@ impl AppProject { ...@@ -428,7 +428,7 @@ impl AppProject {
self.get_rsc_transitions( self.get_rsc_transitions(
self.edge_ecmascript_client_reference_transition(), self.edge_ecmascript_client_reference_transition(),
Vc::upcast(self.edge_ssr_transition()), Vc::upcast(self.edge_ssr_transition()),
Vc::upcast(self.edge_shared_transition()), self.edge_shared_transition(),
), ),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.edge_rsc_module_options_context(), self.edge_rsc_module_options_context(),
...@@ -467,7 +467,7 @@ impl AppProject { ...@@ -467,7 +467,7 @@ impl AppProject {
), ),
( (
rcstr!("next-shared"), rcstr!("next-shared"),
ResolvedVc::upcast(self.shared_transition().to_resolved().await?), self.shared_transition().to_resolved().await?,
), ),
( (
rcstr!("next-server-utility"), rcstr!("next-server-utility"),
...@@ -518,7 +518,7 @@ impl AppProject { ...@@ -518,7 +518,7 @@ impl AppProject {
), ),
( (
rcstr!("next-shared"), rcstr!("next-shared"),
ResolvedVc::upcast(self.edge_shared_transition().to_resolved().await?), self.edge_shared_transition().to_resolved().await?,
), ),
( (
rcstr!("next-server-utility"), rcstr!("next-server-utility"),
...@@ -640,7 +640,7 @@ impl AppProject { ...@@ -640,7 +640,7 @@ impl AppProject {
), ),
( (
rcstr!("next-shared"), rcstr!("next-shared"),
ResolvedVc::upcast(self.shared_transition().to_resolved().await?), self.shared_transition().to_resolved().await?,
), ),
] ]
.into_iter() .into_iter()
...@@ -712,7 +712,7 @@ impl AppProject { ...@@ -712,7 +712,7 @@ impl AppProject {
), ),
( (
rcstr!("next-shared"), rcstr!("next-shared"),
ResolvedVc::upcast(self.edge_shared_transition().to_resolved().await?), self.edge_shared_transition().to_resolved().await?,
), ),
] ]
.into_iter() .into_iter()
...@@ -877,8 +877,7 @@ impl AppProject { ...@@ -877,8 +877,7 @@ impl AppProject {
// Implements layout segment optimization to compute a graph "chain" for each layout // Implements layout segment optimization to compute a graph "chain" for each layout
// segment // segment
async move { async move {
let rsc_entry_chunk_group = let rsc_entry_chunk_group = ChunkGroupEntry::Entry(vec![rsc_entry]);
ChunkGroupEntry::Entry(vec![ResolvedVc::upcast(rsc_entry)]);
let mut graphs = vec![]; let mut graphs = vec![];
let mut visited_modules = if has_layout_segments { let mut visited_modules = if has_layout_segments {
...@@ -1389,18 +1388,16 @@ impl AppEndpoint { ...@@ -1389,18 +1388,16 @@ impl AppEndpoint {
polyfill_files: vec![polyfill_output_asset], polyfill_files: vec![polyfill_output_asset],
..Default::default() ..Default::default()
}; };
let build_manifest_output = ResolvedVc::upcast( let build_manifest_output = build_manifest
build_manifest .build_output(
.build_output( node_root.join(&format!(
node_root.join(&format!( "server/app{manifest_path_prefix}/build-manifest.json",
"server/app{manifest_path_prefix}/build-manifest.json", ))?,
))?, client_relative_path.clone(),
client_relative_path.clone(), )
) .await?
.await? .to_resolved()
.to_resolved() .await?;
.await?,
);
server_assets.insert(build_manifest_output); server_assets.insert(build_manifest_output);
} }
...@@ -1548,7 +1545,7 @@ impl AppEndpoint { ...@@ -1548,7 +1545,7 @@ impl AppEndpoint {
if emit_manifests == EmitManifests::Full { if emit_manifests == EmitManifests::Full {
let dynamic_import_entries = collect_next_dynamic_chunks( let dynamic_import_entries = collect_next_dynamic_chunks(
*module_graphs.full, *module_graphs.full,
*ResolvedVc::upcast(client_chunking_context), *client_chunking_context,
next_dynamic_imports, next_dynamic_imports,
NextDynamicChunkAvailability::ClientReferences( NextDynamicChunkAvailability::ClientReferences(
&*(client_references_chunks.await?), &*(client_references_chunks.await?),
...@@ -1663,7 +1660,7 @@ impl AppEndpoint { ...@@ -1663,7 +1660,7 @@ impl AppEndpoint {
// create react-loadable-manifest for next/dynamic // create react-loadable-manifest for next/dynamic
let dynamic_import_entries = collect_next_dynamic_chunks( let dynamic_import_entries = collect_next_dynamic_chunks(
*module_graphs.full, *module_graphs.full,
*ResolvedVc::upcast(client_chunking_context), *client_chunking_context,
next_dynamic_imports, next_dynamic_imports,
NextDynamicChunkAvailability::ClientReferences( NextDynamicChunkAvailability::ClientReferences(
&*(client_references_chunks.await?), &*(client_references_chunks.await?),
......
...@@ -80,7 +80,7 @@ pub(crate) async fn collect_next_dynamic_chunks( ...@@ -80,7 +80,7 @@ pub(crate) async fn collect_next_dynamic_chunks(
let async_chunk_group = async_loader.references().to_resolved().await?; let async_chunk_group = async_loader.references().to_resolved().await?;
let module_id = dynamic_entry let module_id = dynamic_entry
.chunk_item_id(Vc::upcast(chunking_context)) .chunk_item_id(chunking_context)
.to_resolved() .to_resolved()
.await?; .await?;
......
...@@ -398,7 +398,7 @@ pub async fn all_assets_from_entries_filtered( ...@@ -398,7 +398,7 @@ pub async fn all_assets_from_entries_filtered(
.iter() .iter()
.map(async |asset| { .map(async |asset| {
Ok(( Ok((
ResolvedVc::upcast(*asset), *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) Some(asset.path().to_string().await?)
} else { } else {
......
...@@ -322,7 +322,7 @@ impl PagesProject { ...@@ -322,7 +322,7 @@ impl PagesProject {
( (
rcstr!("next-dynamic-client"), rcstr!("next-dynamic-client"),
ResolvedVc::upcast( ResolvedVc::upcast(
NextDynamicTransition::new_client(Vc::upcast(self.client_transition())) NextDynamicTransition::new_client(self.client_transition())
.to_resolved() .to_resolved()
.await?, .await?,
), ),
...@@ -1073,7 +1073,7 @@ impl PageEndpoint { ...@@ -1073,7 +1073,7 @@ impl PageEndpoint {
{ {
collect_next_dynamic_chunks( collect_next_dynamic_chunks(
self.client_module_graph(), self.client_module_graph(),
Vc::upcast(project.client_chunking_context()), project.client_chunking_context(),
next_dynamic_imports, next_dynamic_imports,
NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info), NextDynamicChunkAvailability::AvailabilityInfo(client_availability_info),
) )
...@@ -1084,7 +1084,7 @@ impl PageEndpoint { ...@@ -1084,7 +1084,7 @@ impl PageEndpoint {
let chunking_context: Vc<Box<dyn ChunkingContext>> = match runtime { let chunking_context: Vc<Box<dyn ChunkingContext>> = match runtime {
NextRuntime::NodeJs => Vc::upcast(node_chunking_context), NextRuntime::NodeJs => Vc::upcast(node_chunking_context),
NextRuntime::Edge => Vc::upcast(edge_chunking_context), NextRuntime::Edge => edge_chunking_context,
}; };
let mut current_chunks = OutputAssets::empty(); let mut current_chunks = OutputAssets::empty();
...@@ -1342,16 +1342,14 @@ impl PageEndpoint { ...@@ -1342,16 +1342,14 @@ impl PageEndpoint {
..Default::default() ..Default::default()
}; };
let manifest_path_prefix = get_asset_prefix_from_pathname(&self.pathname); let manifest_path_prefix = get_asset_prefix_from_pathname(&self.pathname);
Ok(Vc::upcast( build_manifest
build_manifest .build_output(
.build_output( node_root.join(&format!(
node_root.join(&format!( "server/pages{manifest_path_prefix}/build-manifest.json",
"server/pages{manifest_path_prefix}/build-manifest.json", ))?,
))?, client_relative_path,
client_relative_path, )
) .await
.await?,
))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -1380,7 +1380,7 @@ impl Project { ...@@ -1380,7 +1380,7 @@ impl Project {
let middleware = self.find_middleware(); let middleware = self.find_middleware();
let FindContextFileResult::Found(fs_path, _) = &*middleware.await? else { let FindContextFileResult::Found(fs_path, _) = &*middleware.await? else {
return Ok(Vc::upcast(edge_module_context)); return Ok(edge_module_context);
}; };
let source = Vc::upcast(FileSource::new(fs_path.clone())); let source = Vc::upcast(FileSource::new(fs_path.clone()));
......
...@@ -77,7 +77,7 @@ pub(crate) async fn create_server_actions_manifest( ...@@ -77,7 +77,7 @@ pub(crate) async fn create_server_actions_manifest(
.to_resolved() .to_resolved()
.await?; .await?;
let chunk_item = loader.as_chunk_item(module_graph, Vc::upcast(chunking_context)); let chunk_item = loader.as_chunk_item(module_graph, chunking_context);
let manifest = build_manifest( let manifest = build_manifest(
node_root, node_root,
page_name, page_name,
...@@ -275,14 +275,13 @@ pub fn parse_server_actions( ...@@ -275,14 +275,13 @@ pub fn parse_server_actions(
/// If found, we return the mapping of every action's hashed id to the name of /// If found, we return the mapping of every action's hashed id to the name of
/// the exported action function. If not, we return a None. /// the exported action function. If not, we return a None.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn parse_actions(module: Vc<Box<dyn Module>>) -> Result<Vc<OptionActionMap>> { async fn parse_actions(module: ResolvedVc<Box<dyn Module>>) -> Result<Vc<OptionActionMap>> {
let Some(ecmascript_asset) = let Some(ecmascript_asset) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptParsable>>(module)
Vc::try_resolve_sidecast::<Box<dyn EcmascriptParsable>>(module).await?
else { else {
return Ok(Vc::cell(None)); return Ok(Vc::cell(None));
}; };
if let Some(module) = Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(module).await? if let Some(module) = ResolvedVc::try_downcast_type::<EcmascriptModulePartAsset>(module)
&& matches!( && matches!(
module.await?.part, module.await?.part,
ModulePart::Evaluation | ModulePart::Facade ModulePart::Evaluation | ModulePart::Facade
......
...@@ -4,7 +4,7 @@ use std::{ ...@@ -4,7 +4,7 @@ use std::{
}; };
use anyhow::Result; use anyhow::Result;
use turbo_rcstr::RcStr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{FxIndexMap, ResolvedVc, Vc}; use turbo_tasks::{FxIndexMap, ResolvedVc, Vc};
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack::{ModuleAssetContext, transition::Transition}; use turbopack::{ModuleAssetContext, transition::Transition};
...@@ -219,10 +219,10 @@ impl AppPageLoaderTreeBuilder { ...@@ -219,10 +219,10 @@ impl AppPageLoaderTreeBuilder {
let identifier = magic_identifier::mangle(&format!("{name} #{i}")); let identifier = magic_identifier::mangle(&format!("{name} #{i}"));
let inner_module_id = format!("METADATA_{i}"); let inner_module_id = format!("METADATA_{i}");
let helper_import: RcStr = "import { fillMetadataSegment } from \ let helper_import = rcstr!(
'next/dist/lib/metadata/get-metadata-route' with { \ "import { fillMetadataSegment } from 'next/dist/lib/metadata/get-metadata-route' with \
'turbopack-transition': 'next-server-utility' }" { 'turbopack-transition': 'next-server-utility' }"
.into(); );
if !self.base.imports.contains(&helper_import) { if !self.base.imports.contains(&helper_import) {
self.base.imports.push(helper_import); self.base.imports.push(helper_import);
...@@ -231,11 +231,11 @@ impl AppPageLoaderTreeBuilder { ...@@ -231,11 +231,11 @@ impl AppPageLoaderTreeBuilder {
self.base self.base
.imports .imports
.push(format!("import {identifier} from \"{inner_module_id}\";").into()); .push(format!("import {identifier} from \"{inner_module_id}\";").into());
let module = Vc::upcast(StructuredImageModuleType::create_module( let module = StructuredImageModuleType::create_module(
Vc::upcast(FileSource::new(path.clone())), Vc::upcast(FileSource::new(path.clone())),
BlurPlaceholderMode::None, BlurPlaceholderMode::None,
*self.base.module_asset_context, *self.base.module_asset_context,
)); );
let module = self.base.process_module(module).to_resolved().await?; let module = self.base.process_module(module).to_resolved().await?;
self.base self.base
.inner_assets .inner_assets
......
...@@ -159,7 +159,7 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out ...@@ -159,7 +159,7 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out
.iter() .iter()
.map(async |asset| { .map(async |asset| {
Ok(( Ok((
ResolvedVc::upcast(*asset), *asset,
if emit_spans { if emit_spans {
Some(asset.path().to_string().await?) Some(asset.path().to_string().await?)
} else { } else {
......
...@@ -158,7 +158,7 @@ struct HmrEntryChunkItem { ...@@ -158,7 +158,7 @@ struct HmrEntryChunkItem {
impl ChunkItem for HmrEntryChunkItem { impl ChunkItem for HmrEntryChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -166,7 +166,7 @@ async fn wrap_edge_page( ...@@ -166,7 +166,7 @@ async fn wrap_edge_page(
let wrapped = asset_context let wrapped = asset_context
.process( .process(
Vc::upcast(source), source,
ReferenceType::Internal(ResolvedVc::cell(inner_assets)), ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
) )
.module(); .module();
......
...@@ -102,7 +102,7 @@ pub async fn get_app_route_entry( ...@@ -102,7 +102,7 @@ pub async fn get_app_route_entry(
let mut rsc_entry = module_asset_context let mut rsc_entry = module_asset_context
.process( .process(
Vc::upcast(virtual_source), virtual_source,
ReferenceType::Internal(ResolvedVc::cell(inner_assets)), ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
) )
.module(); .module();
...@@ -153,7 +153,7 @@ async fn wrap_edge_route( ...@@ -153,7 +153,7 @@ async fn wrap_edge_route(
let wrapped = asset_context let wrapped = asset_context
.process( .process(
Vc::upcast(source), source,
ReferenceType::Internal(ResolvedVc::cell(inner_assets)), ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
) )
.module(); .module();
......
...@@ -300,7 +300,7 @@ impl ChunkItem for EcmascriptClientReferenceProxyChunkItem { ...@@ -300,7 +300,7 @@ impl ChunkItem for EcmascriptClientReferenceProxyChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -137,10 +137,7 @@ impl EcmascriptChunkItem for NextDynamicEntryChunkItem { ...@@ -137,10 +137,7 @@ impl EcmascriptChunkItem for NextDynamicEntryChunkItem {
async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> { async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
let inner = self.inner.await?; let inner = self.inner.await?;
let module_id = inner let module_id = inner.module.chunk_item_id(*self.chunking_context).await?;
.module
.chunk_item_id(Vc::upcast(*self.chunking_context))
.await?;
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
inner_code: formatdoc!( inner_code: formatdoc!(
r#" r#"
......
...@@ -169,7 +169,7 @@ impl ClientReferenceManifest { ...@@ -169,7 +169,7 @@ impl ClientReferenceManifest {
let server_path = client_reference_module_ref.server_ident.to_string().await?; let server_path = client_reference_module_ref.server_ident.to_string().await?;
let client_module = client_reference_module_ref.client_module; let client_module = client_reference_module_ref.client_module;
let client_chunk_item_id = client_module let client_chunk_item_id = client_module
.chunk_item_id(*ResolvedVc::upcast(client_chunking_context)) .chunk_item_id(*client_chunking_context)
.await?; .await?;
let (client_chunks_paths, client_is_async) = let (client_chunks_paths, client_is_async) =
...@@ -213,12 +213,10 @@ impl ClientReferenceManifest { ...@@ -213,12 +213,10 @@ impl ClientReferenceManifest {
if let Some(ssr_chunking_context) = ssr_chunking_context { if let Some(ssr_chunking_context) = ssr_chunking_context {
let ssr_module = client_reference_module_ref.ssr_module; let ssr_module = client_reference_module_ref.ssr_module;
let ssr_chunk_item_id = ssr_module let ssr_chunk_item_id = ssr_module.chunk_item_id(*ssr_chunking_context).await?;
.chunk_item_id(*ResolvedVc::upcast(ssr_chunking_context))
.await?;
let rsc_chunk_item_id = client_reference_module let rsc_chunk_item_id = client_reference_module
.chunk_item_id(*ResolvedVc::upcast(ssr_chunking_context)) .chunk_item_id(*ssr_chunking_context)
.await?; .await?;
let (ssr_chunks_paths, ssr_is_async) = if runtime == NextRuntime::Edge { let (ssr_chunks_paths, ssr_is_async) = if runtime == NextRuntime::Edge {
......
...@@ -279,7 +279,7 @@ async fn wrap_edge_page( ...@@ -279,7 +279,7 @@ async fn wrap_edge_page(
let wrapped = asset_context let wrapped = asset_context
.process( .process(
Vc::upcast(source), source,
ReferenceType::Internal(ResolvedVc::cell(inner_assets)), ReferenceType::Internal(ResolvedVc::cell(inner_assets)),
) )
.module(); .module();
......
...@@ -130,10 +130,7 @@ impl EcmascriptChunkItem for NextServerComponentChunkItem { ...@@ -130,10 +130,7 @@ impl EcmascriptChunkItem for NextServerComponentChunkItem {
async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> { async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
let inner = self.inner.await?; let inner = self.inner.await?;
let module_id = inner let module_id = inner.module.chunk_item_id(*self.chunking_context).await?;
.module
.chunk_item_id(Vc::upcast(*self.chunking_context))
.await?;
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
inner_code: formatdoc!( inner_code: formatdoc!(
r#" r#"
......
...@@ -130,10 +130,7 @@ impl EcmascriptChunkItem for NextServerComponentChunkItem { ...@@ -130,10 +130,7 @@ impl EcmascriptChunkItem for NextServerComponentChunkItem {
async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> { async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
let inner = self.inner.await?; let inner = self.inner.await?;
let module_id = inner let module_id = inner.module.chunk_item_id(*self.chunking_context).await?;
.module
.chunk_item_id(Vc::upcast(*self.chunking_context))
.await?;
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
inner_code: formatdoc!( inner_code: formatdoc!(
"{TURBOPACK_EXPORT_NAMESPACE}({TURBOPACK_IMPORT}({}));", "{TURBOPACK_EXPORT_NAMESPACE}({TURBOPACK_IMPORT}({}));",
......
...@@ -182,8 +182,8 @@ struct Number(u32); ...@@ -182,8 +182,8 @@ struct Number(u32);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Add for Number { impl Add for Number {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn add(self: Vc<Self>, other: Vc<Box<dyn Add>>) -> Result<Vc<Self>> { async fn add(self: Vc<Self>, other: ResolvedVc<Box<dyn Add>>) -> Result<Vc<Self>> {
let Some(other) = Vc::try_resolve_downcast_type::<Number>(other).await? else { let Some(other) = ResolvedVc::try_downcast_type::<Number>(other) else {
bail!("Expected Number"); bail!("Expected Number");
}; };
Ok(Vc::cell(*self.await? + *other.await?)) Ok(Vc::cell(*self.await? + *other.await?))
...@@ -196,8 +196,8 @@ struct NumberB(u32); ...@@ -196,8 +196,8 @@ struct NumberB(u32);
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl Add for NumberB { impl Add for NumberB {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn add(self: Vc<Self>, other: Vc<Box<dyn Add>>) -> Result<Vc<Self>> { async fn add(self: Vc<Self>, other: ResolvedVc<Box<dyn Add>>) -> Result<Vc<Self>> {
let Some(other) = Vc::try_resolve_downcast_type::<NumberB>(other).await? else { let Some(other) = ResolvedVc::try_downcast_type::<NumberB>(other) else {
bail!("Expected NumberB"); bail!("Expected NumberB");
}; };
Ok(Vc::cell(*self.await? + *other.await?)) Ok(Vc::cell(*self.await? + *other.await?))
......
...@@ -125,7 +125,7 @@ where ...@@ -125,7 +125,7 @@ where
// contain the same value // contain the same value
let mut upcast_vcs = Vec::new(); let mut upcast_vcs = Vec::new();
for _idx in 0..2 { for _idx in 0..2 {
upcast_vcs.push(Vc::upcast((cell_fn)(input.value))); upcast_vcs.push(Vc::upcast_non_strict((cell_fn)(input.value)));
} }
// pick a different cell idx upon each invalidation/execution // pick a different cell idx upon each invalidation/execution
......
...@@ -2298,12 +2298,12 @@ impl ValueToString for NullFileSystem { ...@@ -2298,12 +2298,12 @@ impl ValueToString for NullFileSystem {
pub async fn to_sys_path(mut path: FileSystemPath) -> Result<Option<PathBuf>> { pub async fn to_sys_path(mut path: FileSystemPath) -> Result<Option<PathBuf>> {
loop { loop {
if let Some(fs) = Vc::try_resolve_downcast_type::<AttachedFileSystem>(path.fs()).await? { if let Some(fs) = ResolvedVc::try_downcast_type::<AttachedFileSystem>(path.fs) {
path = fs.get_inner_fs_path(path).owned().await?; path = fs.get_inner_fs_path(path).owned().await?;
continue; continue;
} }
if let Some(fs) = Vc::try_resolve_downcast_type::<DiskFileSystem>(path.fs()).await? { if let Some(fs) = ResolvedVc::try_downcast_type::<DiskFileSystem>(path.fs) {
let sys_path = fs.await?.to_sys_path(path)?; let sys_path = fs.await?.to_sys_path(path)?;
return Ok(Some(sys_path)); return Ok(Some(sys_path));
} }
......
...@@ -4,7 +4,7 @@ use std::{ ...@@ -4,7 +4,7 @@ use std::{
}; };
use anyhow::{Context, Result, anyhow}; use anyhow::{Context, Result, anyhow};
use turbo_tasks::Vc; use turbo_tasks::ResolvedVc;
use crate::{DiskFileSystem, FileSystemPath}; use crate::{DiskFileSystem, FileSystemPath};
...@@ -23,9 +23,8 @@ pub fn extract_disk_access<T>(value: io::Result<T>, path: &Path) -> Result<Optio ...@@ -23,9 +23,8 @@ pub fn extract_disk_access<T>(value: io::Result<T>, path: &Path) -> Result<Optio
pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> { pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> {
use turbo_unix_path::sys_to_unix; use turbo_unix_path::sys_to_unix;
let root_fs = root.fs(); let root_fs = root.fs;
let root_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(root_fs) let root_fs = &*ResolvedVc::try_downcast_type::<DiskFileSystem>(root_fs)
.await?
.context("Expected root to have a DiskFileSystem")? .context("Expected root to have a DiskFileSystem")?
.await?; .await?;
...@@ -48,9 +47,8 @@ pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<S ...@@ -48,9 +47,8 @@ pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<S
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> { pub async fn uri_from_file(root: FileSystemPath, path: Option<&str>) -> Result<String> {
let root_fs = root.fs(); let root_fs = root.fs;
let root_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(root_fs) let root_fs = &*ResolvedVc::try_downcast_type::<DiskFileSystem>(root_fs)
.await?
.context("Expected root to have a DiskFileSystem")? .context("Expected root to have a DiskFileSystem")?
.await?; .await?;
......
...@@ -329,6 +329,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -329,6 +329,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
// rustc complains: error[E0210]: type parameter `T` must be covered by another type when it appears before // rustc complains: error[E0210]: type parameter `T` must be covered by another type when it appears before
// the first local type (`dyn Trait`). // the first local type (`dyn Trait`).
unsafe impl #impl_generics turbo_tasks::Upcast<::std::boxed::Box<dyn #trait_path>> for #ty #where_clause {} unsafe impl #impl_generics turbo_tasks::Upcast<::std::boxed::Box<dyn #trait_path>> for #ty #where_clause {}
unsafe impl #impl_generics turbo_tasks::UpcastStrict<::std::boxed::Box<dyn #trait_path>> for #ty #where_clause {}
impl #impl_generics #trait_path for #ty #where_clause { impl #impl_generics #trait_path for #ty #where_clause {
#(#trait_items)* #(#trait_items)*
......
...@@ -250,6 +250,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -250,6 +250,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
quote! { quote! {
unsafe impl turbo_tasks::Dynamic<Box<dyn turbo_tasks::debug::ValueDebug>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Dynamic<Box<dyn turbo_tasks::debug::ValueDebug>> for Box<dyn #trait_ident> {}
unsafe impl turbo_tasks::Upcast<Box<dyn turbo_tasks::debug::ValueDebug>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Upcast<Box<dyn turbo_tasks::debug::ValueDebug>> for Box<dyn #trait_ident> {}
unsafe impl turbo_tasks::UpcastStrict<Box<dyn turbo_tasks::debug::ValueDebug>> for Box<dyn #trait_ident> {}
} }
} else { } else {
quote! {} quote! {}
...@@ -314,8 +315,6 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -314,8 +315,6 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
} }
unsafe impl turbo_tasks::Dynamic<Box<dyn #trait_ident>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Dynamic<Box<dyn #trait_ident>> for Box<dyn #trait_ident> {}
// TODO(alexkirsz) It would be great to have the following identity. However, I run into an ICE when I attempt this,
// so tabling it for now.
unsafe impl turbo_tasks::Upcast<Box<dyn #trait_ident>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Upcast<Box<dyn #trait_ident>> for Box<dyn #trait_ident> {}
impl<T> #trait_ident for T impl<T> #trait_ident for T
...@@ -328,6 +327,8 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -328,6 +327,8 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
#( #(
unsafe impl turbo_tasks::Dynamic<Box<dyn #supertraits>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Dynamic<Box<dyn #supertraits>> for Box<dyn #trait_ident> {}
unsafe impl turbo_tasks::Upcast<Box<dyn #supertraits>> for Box<dyn #trait_ident> {} unsafe impl turbo_tasks::Upcast<Box<dyn #supertraits>> for Box<dyn #trait_ident> {}
unsafe impl turbo_tasks::UpcastStrict<Box<dyn #supertraits>> for Box<dyn #trait_ident> {
}
)* )*
#value_debug_impl #value_debug_impl
......
...@@ -132,8 +132,8 @@ pub use value::{TransientInstance, TransientValue}; ...@@ -132,8 +132,8 @@ pub use value::{TransientInstance, TransientValue};
pub use value_type::{TraitMethod, TraitType, ValueType}; pub use value_type::{TraitMethod, TraitType, ValueType};
pub use vc::{ pub use vc::{
Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, ReadVcFuture, ResolvedVc, Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, ReadVcFuture, ResolvedVc,
Upcast, ValueDefault, Vc, VcCast, VcCellNewMode, VcCellSharedMode, VcDefaultRead, VcRead, Upcast, UpcastStrict, ValueDefault, Vc, VcCast, VcCellNewMode, VcCellSharedMode, VcDefaultRead,
VcTransparentRead, VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast, VcRead, VcTransparentRead, VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast,
}; };
pub type SliceMap<K, V> = Box<[(K, V)]>; pub type SliceMap<K, V> = Box<[(K, V)]>;
......
...@@ -28,7 +28,7 @@ pub use self::{ ...@@ -28,7 +28,7 @@ pub use self::{
operation::{OperationValue, OperationVc}, operation::{OperationValue, OperationVc},
read::{ReadOwnedVcFuture, ReadVcFuture, VcDefaultRead, VcRead, VcTransparentRead}, read::{ReadOwnedVcFuture, ReadVcFuture, VcDefaultRead, VcRead, VcTransparentRead},
resolved::ResolvedVc, resolved::ResolvedVc,
traits::{Dynamic, Upcast, VcValueTrait, VcValueType}, traits::{Dynamic, Upcast, UpcastStrict, VcValueTrait, VcValueType},
}; };
use crate::{ use crate::{
CellId, RawVc, ResolveTypeError, CellId, RawVc, ResolveTypeError,
...@@ -411,6 +411,33 @@ where ...@@ -411,6 +411,33 @@ where
/// This is also available as an `Into`/`From` conversion. /// This is also available as an `Into`/`From` conversion.
#[inline(always)] #[inline(always)]
pub fn upcast<K>(vc: Self) -> Vc<K> pub fn upcast<K>(vc: Self) -> Vc<K>
where
T: UpcastStrict<K>,
K: VcValueTrait + ?Sized,
{
Self::upcast_non_strict(vc)
}
/// Upcasts the given `Vc<T>` to a `Vc<Box<dyn K>>`
///
/// This has a loose type constraint which would allow upcasting to the same type, prefer using
/// [`Vc::upcast`] when possible. This is useful for extension traits and other more generic
/// usecases.
///
/// # Example
/// ```rust
/// // In generic code where T might be the same as K
/// fn process_foo(vc: ResolvedVc<impl Upcast<Box<dyn MyTrait>>>) -> Vc<Foo> {
/// let my_trait: ResolvedVc<Box<dyn MyTrait>> = Vc::upcast_non_strict(vc);
/// my_trait.do_something()
/// }
/// ```
/// Using generics you could allow users to pass any compatible type, but if you specified
/// `UpcastStrict<...>` instead of `Upcast<...>` you would disallow calling this function if you
/// already had a `ResolvedVc<Box<dyn MyTrait>>. So this function has a looser type constraint
/// to make these functions easier to write and use.
#[inline(always)]
pub fn upcast_non_strict<K>(vc: Self) -> Vc<K>
where where
T: Upcast<K>, T: Upcast<K>,
K: VcValueTrait + ?Sized, K: VcValueTrait + ?Sized,
...@@ -420,7 +447,6 @@ where ...@@ -420,7 +447,6 @@ where
_t: PhantomData, _t: PhantomData,
} }
} }
/// Runs the operation, but ignores the returned Vc. Use that when only interested in running /// Runs the operation, but ignores the returned Vc. Use that when only interested in running
/// the task for side effects. /// the task for side effects.
pub async fn as_side_effect(self) -> Result<()> { pub async fn as_side_effect(self) -> Result<()> {
...@@ -493,6 +519,12 @@ where ...@@ -493,6 +519,12 @@ where
where where
K: VcValueTrait + ?Sized, K: VcValueTrait + ?Sized,
{ {
debug_assert!(
<K as VcValueTrait>::get_trait_type_id() != <T as VcValueTrait>::get_trait_type_id(),
"Attempted to cast a type {} to itself, which is pointless. Use the value directly \
instead.",
crate::registry::get_trait(<T as VcValueTrait>::get_trait_type_id()).global_name
);
let raw_vc: RawVc = vc.node; let raw_vc: RawVc = vc.node;
let raw_vc = raw_vc let raw_vc = raw_vc
.resolve_trait(<K as VcValueTrait>::get_trait_type_id()) .resolve_trait(<K as VcValueTrait>::get_trait_type_id())
...@@ -510,16 +542,9 @@ where ...@@ -510,16 +542,9 @@ where
/// Returns `None` if the underlying value type is not a `K`. /// Returns `None` if the underlying value type is not a `K`.
pub async fn try_resolve_downcast<K>(vc: Self) -> Result<Option<Vc<K>>, ResolveTypeError> pub async fn try_resolve_downcast<K>(vc: Self) -> Result<Option<Vc<K>>, ResolveTypeError>
where where
K: Upcast<T> + VcValueTrait + ?Sized, K: UpcastStrict<T> + VcValueTrait + ?Sized,
{ {
let raw_vc: RawVc = vc.node; Self::try_resolve_sidecast(vc).await
let raw_vc = raw_vc
.resolve_trait(<K as VcValueTrait>::get_trait_type_id())
.await?;
Ok(raw_vc.map(|raw_vc| Vc {
node: raw_vc,
_t: PhantomData,
}))
} }
/// Attempts to downcast the given `Vc<Box<dyn T>>` to a `Vc<K>`, where `K` /// Attempts to downcast the given `Vc<Box<dyn T>>` to a `Vc<K>`, where `K`
...@@ -529,7 +554,7 @@ where ...@@ -529,7 +554,7 @@ where
/// Returns `None` if the underlying value type is not a `K`. /// Returns `None` if the underlying value type is not a `K`.
pub async fn try_resolve_downcast_type<K>(vc: Self) -> Result<Option<Vc<K>>, ResolveTypeError> pub async fn try_resolve_downcast_type<K>(vc: Self) -> Result<Option<Vc<K>>, ResolveTypeError>
where where
K: Upcast<T> + VcValueType, K: UpcastStrict<T> + VcValueType,
{ {
let raw_vc: RawVc = vc.node; let raw_vc: RawVc = vc.node;
let raw_vc = raw_vc let raw_vc = raw_vc
...@@ -565,7 +590,7 @@ where ...@@ -565,7 +590,7 @@ where
impl<T> ValueDebugFormat for Vc<T> impl<T> ValueDebugFormat for Vc<T>
where where
T: Upcast<Box<dyn ValueDebug>> + Send + Sync + ?Sized, T: UpcastStrict<Box<dyn ValueDebug>> + Send + Sync + ?Sized,
{ {
fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> { fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> {
ValueDebugFormatString::Async(Box::pin(async move { ValueDebugFormatString::Async(Box::pin(async move {
......
...@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; ...@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
pub use turbo_tasks_macros::OperationValue; pub use turbo_tasks_macros::OperationValue;
use crate::{ use crate::{
CollectiblesSource, RawVc, ReadVcFuture, ResolvedVc, TaskInput, Upcast, Vc, VcValueTrait, CollectiblesSource, RawVc, ReadVcFuture, ResolvedVc, TaskInput, UpcastStrict, Vc, VcValueTrait,
VcValueType, marker_trait::impl_auto_marker_trait, trace::TraceRawVcs, VcValueType, marker_trait::impl_auto_marker_trait, trace::TraceRawVcs,
}; };
...@@ -94,7 +94,7 @@ impl<T: ?Sized> OperationVc<T> { ...@@ -94,7 +94,7 @@ impl<T: ?Sized> OperationVc<T> {
#[inline(always)] #[inline(always)]
pub fn upcast<K>(vc: Self) -> OperationVc<K> pub fn upcast<K>(vc: Self) -> OperationVc<K>
where where
T: Upcast<K>, T: UpcastStrict<K>,
K: VcValueTrait + ?Sized, K: VcValueTrait + ?Sized,
{ {
OperationVc { OperationVc {
......
...@@ -12,7 +12,7 @@ use anyhow::Result; ...@@ -12,7 +12,7 @@ use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
RawVc, Upcast, VcRead, VcTransparentRead, VcValueTrait, VcValueType, RawVc, Upcast, UpcastStrict, VcRead, VcTransparentRead, VcValueTrait, VcValueType,
debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString}, debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString},
trace::{TraceRawVcs, TraceRawVcsContext}, trace::{TraceRawVcs, TraceRawVcsContext},
vc::Vc, vc::Vc,
...@@ -198,12 +198,26 @@ where ...@@ -198,12 +198,26 @@ where
/// See also: [`Vc::upcast`]. /// See also: [`Vc::upcast`].
#[inline(always)] #[inline(always)]
pub fn upcast<K>(this: Self) -> ResolvedVc<K> pub fn upcast<K>(this: Self) -> ResolvedVc<K>
where
T: UpcastStrict<K>,
K: VcValueTrait + ?Sized,
{
Self::upcast_non_strict(this)
}
/// Upcasts the given `ResolvedVc<T>` to a `ResolvedVc<Box<dyn K>>`.
///
/// This has a loose type constraint which would allow upcasting to the same type, prefer using
/// [`ResolvedVc::upcast`] when possible. See also: [`Vc::upcast_non_strict`]. This is
/// useful for extension traits and other more generic usecases.
#[inline(always)]
pub fn upcast_non_strict<K>(this: Self) -> ResolvedVc<K>
where where
T: Upcast<K>, T: Upcast<K>,
K: VcValueTrait + ?Sized, K: VcValueTrait + ?Sized,
{ {
ResolvedVc { ResolvedVc {
node: Vc::upcast(this.node), node: Vc::upcast_non_strict(this.node),
} }
} }
...@@ -236,6 +250,15 @@ where ...@@ -236,6 +250,15 @@ where
where where
K: VcValueTrait + ?Sized, K: VcValueTrait + ?Sized,
{ {
// Runtime assertion to catch K == T cases with a clear error message
// This will be optimized away in release builds but helps during development
// We use trait type IDs since T and K might be trait objects (?Sized)
debug_assert!(
<K as VcValueTrait>::get_trait_type_id() != <T as VcValueTrait>::get_trait_type_id(),
"Attempted to cast a type {} to itself, which is pointless. Use the value directly \
instead.",
crate::registry::get_trait(<T as VcValueTrait>::get_trait_type_id()).global_name
);
// `RawVc::TaskCell` already contains all the type information needed to check this // `RawVc::TaskCell` already contains all the type information needed to check this
// sidecast, so we don't need to read the underlying cell! // sidecast, so we don't need to read the underlying cell!
let raw_vc = this.node.node; let raw_vc = this.node.node;
...@@ -257,7 +280,7 @@ where ...@@ -257,7 +280,7 @@ where
/// See also: [`Vc::try_resolve_downcast`]. /// See also: [`Vc::try_resolve_downcast`].
pub fn try_downcast<K>(this: Self) -> Option<ResolvedVc<K>> pub fn try_downcast<K>(this: Self) -> Option<ResolvedVc<K>>
where where
K: Upcast<T> + VcValueTrait + ?Sized, K: UpcastStrict<T> + VcValueTrait + ?Sized,
{ {
// this is just a more type-safe version of a sidecast // this is just a more type-safe version of a sidecast
Self::try_sidecast(this) Self::try_sidecast(this)
...@@ -270,7 +293,7 @@ where ...@@ -270,7 +293,7 @@ where
/// See also: [`Vc::try_resolve_downcast_type`]. /// See also: [`Vc::try_resolve_downcast_type`].
pub fn try_downcast_type<K>(this: Self) -> Option<ResolvedVc<K>> pub fn try_downcast_type<K>(this: Self) -> Option<ResolvedVc<K>>
where where
K: Upcast<T> + VcValueType, K: UpcastStrict<T> + VcValueType,
{ {
let raw_vc = this.node.node; let raw_vc = this.node.node;
raw_vc raw_vc
...@@ -310,7 +333,7 @@ where ...@@ -310,7 +333,7 @@ where
impl<T> ValueDebugFormat for ResolvedVc<T> impl<T> ValueDebugFormat for ResolvedVc<T>
where where
T: Upcast<Box<dyn ValueDebug>> + Send + Sync + ?Sized, T: UpcastStrict<Box<dyn ValueDebug>> + Send + Sync + ?Sized,
{ {
fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> { fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> {
self.node.value_debug_format(depth) self.node.value_debug_format(depth)
......
...@@ -51,6 +51,18 @@ where ...@@ -51,6 +51,18 @@ where
{ {
} }
/// A speialization of [`Upcast`] that ensures that the upcast is strict meaning that T !== Self
///
/// # Safety
///
/// The implementor of this trait must ensure that `Self` implements the
/// trait `T` and that `Self` is not equal to `T`.
pub unsafe trait UpcastStrict<T>: Upcast<T>
where
T: VcValueTrait + ?Sized,
{
}
/// Marker trait that indicates that a [`Vc<Self>`][crate::Vc] can accept all /// Marker trait that indicates that a [`Vc<Self>`][crate::Vc] can accept all
/// methods declared on a [`Vc<T>`][crate::Vc]. /// methods declared on a [`Vc<T>`][crate::Vc].
/// ///
......
...@@ -174,7 +174,7 @@ impl BrowserChunkingContextBuilder { ...@@ -174,7 +174,7 @@ impl BrowserChunkingContextBuilder {
{ {
self.chunking_context self.chunking_context
.chunking_configs .chunking_configs
.push((ResolvedVc::upcast(ty), chunking_config)); .push((ResolvedVc::upcast_non_strict(ty), chunking_config));
self self
} }
...@@ -334,17 +334,16 @@ impl BrowserChunkingContext { ...@@ -334,17 +334,16 @@ impl BrowserChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn generate_chunk( async fn generate_chunk(
self: Vc<Self>, self: Vc<Self>,
chunk: Vc<Box<dyn Chunk>>, chunk: ResolvedVc<Box<dyn Chunk>>,
) -> Result<Vc<Box<dyn OutputAsset>>> { ) -> Result<Vc<Box<dyn OutputAsset>>> {
Ok( Ok(
if let Some(ecmascript_chunk) = if let Some(ecmascript_chunk) = ResolvedVc::try_downcast_type::<EcmascriptChunk>(chunk)
Vc::try_resolve_downcast_type::<EcmascriptChunk>(chunk).await?
{ {
Vc::upcast(EcmascriptBrowserChunk::new(self, ecmascript_chunk)) Vc::upcast(EcmascriptBrowserChunk::new(self, *ecmascript_chunk))
} else if let Some(output_asset) = } else if let Some(output_asset) =
Vc::try_resolve_sidecast::<Box<dyn OutputAsset>>(chunk).await? ResolvedVc::try_sidecast::<Box<dyn OutputAsset>>(chunk)
{ {
output_asset *output_asset
} else { } else {
bail!("Unable to generate output asset for chunk"); bail!("Unable to generate output asset for chunk");
}, },
...@@ -736,7 +735,7 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -736,7 +735,7 @@ impl ChunkingContext for BrowserChunkingContext {
)) ))
} else { } else {
let module = AsyncLoaderModule::new(module, Vc::upcast(self), availability_info); let module = AsyncLoaderModule::new(module, Vc::upcast(self), availability_info);
Vc::upcast(module.as_chunk_item(module_graph, Vc::upcast(self))) module.as_chunk_item(module_graph, Vc::upcast(self))
}) })
} }
......
...@@ -50,11 +50,11 @@ impl ChunkListUpdate<'_> { ...@@ -50,11 +50,11 @@ impl ChunkListUpdate<'_> {
#[turbo_tasks::function] #[turbo_tasks::function]
pub(super) async fn update_chunk_list( pub(super) async fn update_chunk_list(
content: Vc<EcmascriptDevChunkListContent>, content: Vc<EcmascriptDevChunkListContent>,
from_version: Vc<Box<dyn Version>>, from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Vc<Update>> { ) -> Result<Vc<Update>> {
let to_version = content.version(); let to_version = content.version();
let from_version = if let Some(from) = let from_version = if let Some(from) =
Vc::try_resolve_downcast_type::<EcmascriptDevChunkListVersion>(from_version).await? ResolvedVc::try_downcast_type::<EcmascriptDevChunkListVersion>(from_version)
{ {
from from
} else { } else {
......
...@@ -49,7 +49,10 @@ impl VersionedContent for EcmascriptBrowserMergedChunkContent { ...@@ -49,7 +49,10 @@ impl VersionedContent for EcmascriptBrowserMergedChunkContent {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
async fn update(self: Vc<Self>, from_version: Vc<Box<dyn Version>>) -> Result<Vc<Update>> { async fn update(
self: Vc<Self>,
from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Vc<Update>> {
Ok(update_ecmascript_merged_chunk(self, from_version) Ok(update_ecmascript_merged_chunk(self, from_version)
.await? .await?
.cell()) .cell())
......
...@@ -2,7 +2,7 @@ use std::sync::Arc; ...@@ -2,7 +2,7 @@ use std::sync::Arc;
use anyhow::Result; use anyhow::Result;
use serde::Serialize; use serde::Serialize;
use turbo_tasks::{FxIndexMap, FxIndexSet, IntoTraitRef, ReadRef, TryJoinIterExt, Vc}; use turbo_tasks::{FxIndexMap, FxIndexSet, IntoTraitRef, ReadRef, ResolvedVc, TryJoinIterExt, Vc};
use turbo_tasks_fs::rope::Rope; use turbo_tasks_fs::rope::Rope;
use turbopack_core::{ use turbopack_core::{
chunk::{ChunkingContext, ModuleId}, chunk::{ChunkingContext, ModuleId},
...@@ -131,11 +131,11 @@ impl MergedModuleMap { ...@@ -131,11 +131,11 @@ impl MergedModuleMap {
pub(super) async fn update_ecmascript_merged_chunk( pub(super) async fn update_ecmascript_merged_chunk(
content: Vc<EcmascriptBrowserMergedChunkContent>, content: Vc<EcmascriptBrowserMergedChunkContent>,
from_version: Vc<Box<dyn Version>>, from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Update> { ) -> Result<Update> {
let to_merged_version = content.version(); let to_merged_version = content.version();
let from_merged_version = if let Some(from) = let from_merged_version = if let Some(from) =
Vc::try_resolve_downcast_type::<EcmascriptBrowserMergedChunkVersion>(from_version).await? ResolvedVc::try_downcast_type::<EcmascriptBrowserMergedChunkVersion>(from_version)
{ {
from from
} else { } else {
......
...@@ -479,7 +479,7 @@ async fn build_internal( ...@@ -479,7 +479,7 @@ async fn build_internal(
.unwrap(), .unwrap(),
)? )?
.with_extension("entry.js"), .with_extension("entry.js"),
EvaluatableAssets::one(*ResolvedVc::upcast(ecmascript)), EvaluatableAssets::one(*ecmascript),
module_graph, module_graph,
OutputAssets::empty(), OutputAssets::empty(),
AvailabilityInfo::Root, AvailabilityInfo::Root,
......
...@@ -385,7 +385,12 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte ...@@ -385,7 +385,12 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte
chunk_group: ChunkGroup, chunk_group: ChunkGroup,
module_graph: Vc<ModuleGraph>, module_graph: Vc<ModuleGraph>,
) -> Vc<OutputAssets> { ) -> Vc<OutputAssets> {
root_chunk_group_assets(Vc::upcast(self), ident, chunk_group, module_graph) root_chunk_group_assets(
Vc::upcast_non_strict(self),
ident,
chunk_group,
module_graph,
)
} }
fn evaluated_chunk_group_assets( fn evaluated_chunk_group_assets(
...@@ -396,7 +401,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte ...@@ -396,7 +401,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte
availability_info: AvailabilityInfo, availability_info: AvailabilityInfo,
) -> Vc<OutputAssets> { ) -> Vc<OutputAssets> {
evaluated_chunk_group_assets( evaluated_chunk_group_assets(
Vc::upcast(self), Vc::upcast_non_strict(self),
ident, ident,
chunk_group, chunk_group,
module_graph, module_graph,
...@@ -413,7 +418,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte ...@@ -413,7 +418,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte
availability_info: AvailabilityInfo, availability_info: AvailabilityInfo,
) -> Vc<Box<dyn OutputAsset>> { ) -> Vc<Box<dyn OutputAsset>> {
entry_chunk_group_asset( entry_chunk_group_asset(
Vc::upcast(self), Vc::upcast_non_strict(self),
path, path,
evaluatable_assets, evaluatable_assets,
module_graph, module_graph,
...@@ -446,7 +451,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte ...@@ -446,7 +451,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte
extra_chunks: Vc<OutputAssets>, extra_chunks: Vc<OutputAssets>,
) -> Vc<Box<dyn OutputAsset>> { ) -> Vc<Box<dyn OutputAsset>> {
entry_chunk_group_asset( entry_chunk_group_asset(
Vc::upcast(self), Vc::upcast_non_strict(self),
path, path,
evaluatable_assets, evaluatable_assets,
module_graph, module_graph,
...@@ -463,7 +468,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte ...@@ -463,7 +468,7 @@ impl<T: ChunkingContext + Send + Upcast<Box<dyn ChunkingContext>>> ChunkingConte
availability_info: AvailabilityInfo, availability_info: AvailabilityInfo,
) -> Vc<OutputAssets> { ) -> Vc<OutputAssets> {
chunk_group_assets( chunk_group_assets(
Vc::upcast(self), Vc::upcast_non_strict(self),
ident, ident,
chunk_group, chunk_group,
module_graph, module_graph,
......
...@@ -32,7 +32,7 @@ where ...@@ -32,7 +32,7 @@ where
self: Vc<Self>, self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>, asset_context: Vc<Box<dyn AssetContext>>,
) -> Vc<Box<dyn EvaluatableAsset>> { ) -> Vc<Box<dyn EvaluatableAsset>> {
to_evaluatable(Vc::upcast(self), asset_context) to_evaluatable(Vc::upcast_non_strict(self), asset_context)
} }
} }
......
...@@ -540,7 +540,7 @@ where ...@@ -540,7 +540,7 @@ where
{ {
/// Returns the module id of this chunk item. /// Returns the module id of this chunk item.
fn id(self: Vc<Self>) -> Vc<ModuleId> { fn id(self: Vc<Self>) -> Vc<ModuleId> {
let chunk_item = Vc::upcast(self); let chunk_item = Vc::upcast_non_strict(self);
chunk_item.chunking_context().chunk_item_id(chunk_item) chunk_item.chunking_context().chunk_item_id(chunk_item)
} }
} }
...@@ -560,7 +560,7 @@ where ...@@ -560,7 +560,7 @@ where
self: Vc<Self>, self: Vc<Self>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Vc<ModuleId> { ) -> Vc<ModuleId> {
chunking_context.chunk_item_id_from_module(Vc::upcast(self)) chunking_context.chunk_item_id_from_module(Vc::upcast_non_strict(self))
} }
} }
......
...@@ -86,7 +86,7 @@ where ...@@ -86,7 +86,7 @@ where
T: Upcast<Box<dyn Diagnostic>>, T: Upcast<Box<dyn Diagnostic>>,
{ {
fn emit(self) { fn emit(self) {
let diagnostic = ResolvedVc::upcast::<Box<dyn Diagnostic>>(self); let diagnostic = ResolvedVc::upcast_non_strict::<Box<dyn Diagnostic>>(self);
emit(diagnostic); emit(diagnostic);
} }
} }
......
...@@ -129,7 +129,7 @@ pub async fn children_from_output_assets( ...@@ -129,7 +129,7 @@ pub async fn children_from_output_assets(
for &reference in &*references { for &reference in &*references {
children.insert(( children.insert((
key.clone(), key.clone(),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(reference)) IntrospectableOutputAsset::new(*reference)
.to_resolved() .to_resolved()
.await?, .await?,
)); ));
......
...@@ -353,7 +353,7 @@ where ...@@ -353,7 +353,7 @@ where
T: Upcast<Box<dyn Issue>>, T: Upcast<Box<dyn Issue>>,
{ {
fn emit(self) { fn emit(self) {
let issue = ResolvedVc::upcast::<Box<dyn Issue>>(self); let issue = ResolvedVc::upcast_non_strict::<Box<dyn Issue>>(self);
emit(issue); emit(issue);
emit(ResolvedVc::upcast::<Box<dyn IssueProcessingPath>>( emit(ResolvedVc::upcast::<Box<dyn IssueProcessingPath>>(
RootIssueProcessingPath::resolved_cell(RootIssueProcessingPath(issue)), RootIssueProcessingPath::resolved_cell(RootIssueProcessingPath(issue)),
......
...@@ -286,7 +286,7 @@ impl PreBatches { ...@@ -286,7 +286,7 @@ impl PreBatches {
let mut visited = FxHashSet::default(); let mut visited = FxHashSet::default();
module_graph module_graph
.traverse_edges_from_entries_dfs( .traverse_edges_from_entries_dfs(
std::iter::once(ResolvedVc::upcast(entry)), std::iter::once(entry),
&mut state, &mut state,
|parent_info, node, state| { |parent_info, node, state| {
let ty = parent_info.map_or( let ty = parent_info.map_or(
...@@ -412,15 +412,7 @@ pub async fn compute_module_batches( ...@@ -412,15 +412,7 @@ pub async fn compute_module_batches(
// Start with the entries // Start with the entries
for chunk_group in &chunk_group_info.chunk_groups { for chunk_group in &chunk_group_info.chunk_groups {
for entry in chunk_group.entries() { for entry in chunk_group.entries() {
if let Some(chunkable_module) = ResolvedVc::try_downcast(entry) { pre_batches.ensure_pre_batch_for_module(entry, &chunk_group_info, &mut queue)?;
pre_batches.ensure_pre_batch_for_module(
chunkable_module,
&chunk_group_info,
&mut queue,
)?;
} else {
pre_batches.single_module_entries.insert(entry);
}
} }
if let Some(parent) = chunk_group.get_merged_parent() { if let Some(parent) = chunk_group.get_merged_parent() {
chunk_group_indices_with_merged_children.insert(parent); chunk_group_indices_with_merged_children.insert(parent);
...@@ -459,13 +451,9 @@ pub async fn compute_module_batches( ...@@ -459,13 +451,9 @@ pub async fn compute_module_batches(
|| Either::Left(chunk_group.entries()), || Either::Left(chunk_group.entries()),
|v| Either::Right(v.iter().copied()), |v| Either::Right(v.iter().copied()),
) )
.filter_map(|module| { .map(|module| {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) { let idx = *pre_batches.entries.get(&module).unwrap();
let idx = *pre_batches.entries.get(&chunkable_module).unwrap(); (idx, 0)
Some((idx, 0))
} else {
None
}
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
stack.reverse(); stack.reverse();
...@@ -537,11 +525,7 @@ pub async fn compute_module_batches( ...@@ -537,11 +525,7 @@ pub async fn compute_module_batches(
.push(idx); .push(idx);
} }
PreBatchItem::NonParallelEdge(_, module) => { PreBatchItem::NonParallelEdge(_, module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(*module) { if !pre_batches.entries.contains_key(module) {
if !pre_batches.entries.contains_key(&chunkable_module) {
pre_batches.single_module_entries.insert(*module);
}
} else {
pre_batches.single_module_entries.insert(*module); pre_batches.single_module_entries.insert(*module);
} }
} }
...@@ -858,9 +842,7 @@ pub async fn compute_module_batches( ...@@ -858,9 +842,7 @@ pub async fn compute_module_batches(
); );
} }
PreBatchItem::NonParallelEdge(ty, module) => { PreBatchItem::NonParallelEdge(ty, module) => {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) if let Some(batch) = pre_batches.entries.get(&module).copied() {
&& let Some(batch) = pre_batches.entries.get(&chunkable_module).copied()
{
graph.add_edge( graph.add_edge(
index, index,
batch_indices[batch], batch_indices[batch],
...@@ -897,9 +879,7 @@ pub async fn compute_module_batches( ...@@ -897,9 +879,7 @@ pub async fn compute_module_batches(
let mut entries = FxHashMap::default(); let mut entries = FxHashMap::default();
for chunk_group in &chunk_group_info.chunk_groups { for chunk_group in &chunk_group_info.chunk_groups {
for module in chunk_group.entries() { for module in chunk_group.entries() {
if let Some(chunkable_module) = ResolvedVc::try_downcast(module) if let Some(batch) = pre_batches.entries.get(&module).copied() {
&& let Some(batch) = pre_batches.entries.get(&chunkable_module).copied()
{
entries.insert(module, batch_indices[batch]); entries.insert(module, batch_indices[batch]);
continue; continue;
} }
......
...@@ -335,10 +335,7 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out ...@@ -335,10 +335,7 @@ pub async fn all_assets_from_entries(entries: Vc<OutputAssets>) -> Result<Vc<Out
Ok(Vc::cell( Ok(Vc::cell(
AdjacencyMap::new() AdjacencyMap::new()
.skip_duplicates() .skip_duplicates()
.visit( .visit(entries.await?.iter().copied(), get_referenced_assets)
entries.await?.iter().copied().map(ResolvedVc::upcast),
get_referenced_assets,
)
.await .await
.completed()? .completed()?
.into_inner() .into_inner()
......
...@@ -66,7 +66,12 @@ where ...@@ -66,7 +66,12 @@ where
options: Vc<ResolveOptions>, options: Vc<ResolveOptions>,
reference_type: ReferenceType, reference_type: ReferenceType,
) -> impl Future<Output = Result<Vc<ModuleResolveResult>>> + Send { ) -> impl Future<Output = Result<Vc<ModuleResolveResult>>> + Send {
resolve_asset(Vc::upcast(self), request, options, reference_type) resolve_asset(
Vc::upcast_non_strict(self),
request,
options,
reference_type,
)
} }
async fn resolve_options( async fn resolve_options(
...@@ -81,7 +86,7 @@ where ...@@ -81,7 +86,7 @@ where
fn with_transition(self: ResolvedVc<Self>, transition: RcStr) -> Vc<Box<dyn ResolveOrigin>> { fn with_transition(self: ResolvedVc<Self>, transition: RcStr) -> Vc<Box<dyn ResolveOrigin>> {
Vc::upcast( Vc::upcast(
ResolveOriginWithTransition { ResolveOriginWithTransition {
previous: ResolvedVc::upcast(self), previous: ResolvedVc::upcast_non_strict(self),
transition, transition,
} }
.cell(), .cell(),
......
...@@ -5,7 +5,7 @@ use const_format::concatcp; ...@@ -5,7 +5,7 @@ use const_format::concatcp;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_tasks::Vc; use turbo_tasks::ResolvedVc;
use turbo_tasks_fs::{ use turbo_tasks_fs::{
DiskFileSystem, FileContent, FileSystemPath, rope::Rope, util::uri_from_file, DiskFileSystem, FileContent, FileSystemPath, rope::Rope, util::uri_from_file,
}; };
...@@ -174,9 +174,8 @@ pub async fn fileify_source_map( ...@@ -174,9 +174,8 @@ pub async fn fileify_source_map(
return Ok(None); return Ok(None);
}; };
let context_fs = context_path.fs(); let context_fs = context_path.fs;
let context_fs = &*Vc::try_resolve_downcast_type::<DiskFileSystem>(context_fs) let context_fs = &*ResolvedVc::try_downcast_type::<DiskFileSystem>(context_fs)
.await?
.context("Expected the chunking context to have a DiskFileSystem")? .context("Expected the chunking context to have a DiskFileSystem")?
.await?; .await?;
let prefix = format!("{}///[{}]/", SOURCE_URL_PROTOCOL, context_fs.name()); let prefix = format!("{}///[{}]/", SOURCE_URL_PROTOCOL, context_fs.name());
......
...@@ -215,7 +215,7 @@ impl ChunkItem for CssModuleChunkItem { ...@@ -215,7 +215,7 @@ impl ChunkItem for CssModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -273,11 +273,7 @@ impl OutputChunk for CssChunk { ...@@ -273,11 +273,7 @@ impl OutputChunk for CssChunk {
.await?; .await?;
let imports_chunk_items: Vec<_> = entries_chunk_items let imports_chunk_items: Vec<_> = entries_chunk_items
.iter() .iter()
.map(|&chunk_item| async move { .map(|&css_item| async move {
let Some(css_item) = ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(chunk_item)
else {
return Ok(vec![]);
};
Ok(css_item Ok(css_item
.content() .content()
.await? .await?
...@@ -290,7 +286,7 @@ impl OutputChunk for CssChunk { ...@@ -290,7 +286,7 @@ impl OutputChunk for CssChunk {
None None
} }
}) })
.collect()) .collect::<Vec<_>>())
}) })
.try_join() .try_join()
.await? .await?
...@@ -544,12 +540,10 @@ impl ChunkType for CssChunkType { ...@@ -544,12 +540,10 @@ impl ChunkType for CssChunkType {
async fn chunk_item_size( async fn chunk_item_size(
&self, &self,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
chunk_item: Vc<Box<dyn ChunkItem>>, chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
_async_module_info: Option<Vc<AsyncModuleInfo>>, _async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<usize>> { ) -> Result<Vc<usize>> {
let Some(chunk_item) = let Some(chunk_item) = ResolvedVc::try_downcast::<Box<dyn CssChunkItem>>(chunk_item) else {
Vc::try_resolve_downcast::<Box<dyn CssChunkItem>>(chunk_item).await?
else {
bail!("Chunk item is not an css chunk item but reporting chunk type css"); bail!("Chunk item is not an css chunk item but reporting chunk type css");
}; };
Ok(Vc::cell(chunk_item.content().await.map_or(0, |content| { Ok(Vc::cell(chunk_item.content().await.map_or(0, |content| {
......
...@@ -296,7 +296,7 @@ impl ChunkItem for ModuleChunkItem { ...@@ -296,7 +296,7 @@ impl ChunkItem for ModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -368,9 +368,7 @@ impl EcmascriptChunkItem for ModuleChunkItem { ...@@ -368,9 +368,7 @@ impl EcmascriptChunkItem for ModuleChunkItem {
let placeable: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>> = let placeable: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>> =
ResolvedVc::upcast(css_module); ResolvedVc::upcast(css_module);
let module_id = placeable let module_id = placeable.chunk_item_id(*self.chunking_context).await?;
.chunk_item_id(Vc::upcast(*self.chunking_context))
.await?;
let module_id = StringifyJs(&*module_id); let module_id = StringifyJs(&*module_id);
let original_name = StringifyJs(&original_name); let original_name = StringifyJs(&original_name);
exported_class_names exported_class_names
......
...@@ -106,7 +106,7 @@ impl Visitor<'_> for ModuleReferencesVisitor<'_> { ...@@ -106,7 +106,7 @@ impl Visitor<'_> for ModuleReferencesVisitor<'_> {
ImportAttributes::new_from_lightningcss(&i.clone().into_owned()).into(), ImportAttributes::new_from_lightningcss(&i.clone().into_owned()).into(),
self.import_context.map(|ctx| *ctx), self.import_context.map(|ctx| *ctx),
IssueSource::from_line_col( IssueSource::from_line_col(
ResolvedVc::upcast(self.source), self.source,
SourcePos { SourcePos {
line: issue_span.line as _, line: issue_span.line as _,
column: issue_span.column as _, column: issue_span.column as _,
...@@ -141,7 +141,7 @@ impl Visitor<'_> for ModuleReferencesVisitor<'_> { ...@@ -141,7 +141,7 @@ impl Visitor<'_> for ModuleReferencesVisitor<'_> {
*self.origin, *self.origin,
Request::parse(RcStr::from(src).into()), Request::parse(RcStr::from(src).into()),
IssueSource::from_line_col( IssueSource::from_line_col(
ResolvedVc::upcast(self.source), self.source,
SourcePos { SourcePos {
line: issue_span.line as _, line: issue_span.line as _,
column: issue_span.column as _, column: issue_span.column as _,
......
...@@ -55,7 +55,7 @@ impl UrlAssetReference { ...@@ -55,7 +55,7 @@ impl UrlAssetReference {
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<ReferencedAsset>> { ) -> Result<Vc<ReferencedAsset>> {
if let Some(module) = *self.resolve_reference().first_module().await? if let Some(module) = *self.resolve_reference().first_module().await?
&& let Some(embeddable) = Vc::try_resolve_downcast::<Box<dyn CssEmbed>>(*module).await? && let Some(embeddable) = ResolvedVc::try_downcast::<Box<dyn CssEmbed>>(module)
{ {
return Ok(ReferencedAsset::Some( return Ok(ReferencedAsset::Some(
embeddable embeddable
......
...@@ -323,9 +323,7 @@ impl Introspectable for AssetGraphContentSource { ...@@ -323,9 +323,7 @@ impl Introspectable for AssetGraphContentSource {
.map(|&asset| async move { .map(|&asset| async move {
Ok(( Ok((
rcstr!("root"), rcstr!("root"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset)) IntrospectableOutputAsset::new(*asset).to_resolved().await?,
.to_resolved()
.await?,
)) ))
}) })
.try_join() .try_join()
...@@ -338,9 +336,7 @@ impl Introspectable for AssetGraphContentSource { ...@@ -338,9 +336,7 @@ impl Introspectable for AssetGraphContentSource {
.map(|&asset| async move { .map(|&asset| async move {
Ok(( Ok((
rcstr!("inner"), rcstr!("inner"),
IntrospectableOutputAsset::new(*ResolvedVc::upcast(asset)) IntrospectableOutputAsset::new(*asset).to_resolved().await?,
.to_resolved()
.await?,
)) ))
}) })
.try_join() .try_join()
......
...@@ -450,7 +450,7 @@ where ...@@ -450,7 +450,7 @@ where
Vc::upcast(IssueFilePathContentSource::new_file_path( Vc::upcast(IssueFilePathContentSource::new_file_path(
file_path, file_path,
description, description,
Vc::upcast(self), Vc::upcast_non_strict(self),
)) ))
} }
} }
......
...@@ -126,13 +126,9 @@ impl Introspectable for StaticAssetsContentSource { ...@@ -126,13 +126,9 @@ impl Introspectable for StaticAssetsContentSource {
async move { async move {
let child = match entry { let child = match entry {
DirectoryEntry::File(path) | DirectoryEntry::Symlink(path) => { DirectoryEntry::File(path) | DirectoryEntry::Symlink(path) => {
ResolvedVc::upcast( IntrospectableSource::new(Vc::upcast(FileSource::new(path.clone())))
IntrospectableSource::new(Vc::upcast(FileSource::new(
path.clone(),
)))
.to_resolved() .to_resolved()
.await?, .await?
)
} }
DirectoryEntry::Directory(path) => ResolvedVc::upcast( DirectoryEntry::Directory(path) => ResolvedVc::upcast(
StaticAssetsContentSource::with_prefix( StaticAssetsContentSource::with_prefix(
......
...@@ -76,13 +76,9 @@ impl EcmascriptChunkItem for AsyncLoaderChunkItem { ...@@ -76,13 +76,9 @@ impl EcmascriptChunkItem for AsyncLoaderChunkItem {
let module = this.module.await?; let module = this.module.await?;
let id = if let Some(placeable) = let id = if let Some(placeable) =
Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkPlaceable>>(*module.inner).await? ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(module.inner)
{ {
Some( Some(placeable.chunk_item_id(*this.chunking_context).await?)
placeable
.chunk_item_id(*ResolvedVc::upcast(this.chunking_context))
.await?,
)
} else { } else {
None None
}; };
...@@ -171,7 +167,7 @@ impl ChunkItem for AsyncLoaderChunkItem { ...@@ -171,7 +167,7 @@ impl ChunkItem for AsyncLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -39,12 +39,6 @@ impl ChunkType for EcmascriptChunkType { ...@@ -39,12 +39,6 @@ impl ChunkType for EcmascriptChunkType {
batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>, batch_groups: Vec<ResolvedVc<ChunkItemBatchGroup>>,
referenced_output_assets: Vc<OutputAssets>, referenced_output_assets: Vc<OutputAssets>,
) -> Result<Vc<Box<dyn Chunk>>> { ) -> Result<Vc<Box<dyn Chunk>>> {
let Some(chunking_context) =
Vc::try_resolve_downcast::<Box<dyn ChunkingContext>>(chunking_context).await?
else {
bail!("Ecmascript chunking context not found");
};
let content = EcmascriptChunkContent { let content = EcmascriptChunkContent {
chunk_items: chunk_items chunk_items: chunk_items
.iter() .iter()
...@@ -69,11 +63,10 @@ impl ChunkType for EcmascriptChunkType { ...@@ -69,11 +63,10 @@ impl ChunkType for EcmascriptChunkType {
async fn chunk_item_size( async fn chunk_item_size(
&self, &self,
_chunking_context: Vc<Box<dyn ChunkingContext>>, _chunking_context: Vc<Box<dyn ChunkingContext>>,
chunk_item: Vc<Box<dyn ChunkItem>>, chunk_item: ResolvedVc<Box<dyn ChunkItem>>,
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<usize>> { ) -> Result<Vc<usize>> {
let Some(chunk_item) = let Some(chunk_item) = ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkItem>>(chunk_item)
Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkItem>>(chunk_item).await?
else { else {
bail!("Chunk item is not an ecmascript chunk item but reporting chunk type ecmascript"); bail!("Chunk item is not an ecmascript chunk item but reporting chunk type ecmascript");
}; };
......
...@@ -212,7 +212,7 @@ where ...@@ -212,7 +212,7 @@ where
{ {
/// Generates the module factory for this chunk item. /// Generates the module factory for this chunk item.
fn code(self: Vc<Self>, async_module_info: Option<Vc<AsyncModuleInfo>>) -> Vc<Code> { fn code(self: Vc<Self>, async_module_info: Option<Vc<AsyncModuleInfo>>) -> Vc<Code> {
module_factory_with_code_generation_issue(Vc::upcast(self), async_module_info) module_factory_with_code_generation_issue(Vc::upcast_non_strict(self), async_module_info)
} }
} }
......
...@@ -124,7 +124,7 @@ impl Chunk for EcmascriptChunk { ...@@ -124,7 +124,7 @@ impl Chunk for EcmascriptChunk {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -782,7 +782,7 @@ impl ChunkItem for ModuleChunkItem { ...@@ -782,7 +782,7 @@ impl ChunkItem for ModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -88,7 +88,7 @@ impl ChunkItem for ManifestChunkItem { ...@@ -88,7 +88,7 @@ impl ChunkItem for ManifestChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -105,7 +105,7 @@ impl ChunkItem for ManifestLoaderChunkItem { ...@@ -105,7 +105,7 @@ impl ChunkItem for ManifestLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -140,7 +140,7 @@ impl EcmascriptChunkItem for ManifestLoaderChunkItem { ...@@ -140,7 +140,7 @@ impl EcmascriptChunkItem for ManifestLoaderChunkItem {
// exports a promise for all of the necessary chunk loads. // exports a promise for all of the necessary chunk loads.
let item_id = &*this let item_id = &*this
.manifest .manifest
.chunk_item_id(*ResolvedVc::upcast(manifest.chunking_context)) .chunk_item_id(*manifest.chunking_context)
.await?; .await?;
// Finally, we need the id of the module that we're actually trying to // Finally, we need the id of the module that we're actually trying to
...@@ -148,9 +148,7 @@ impl EcmascriptChunkItem for ManifestLoaderChunkItem { ...@@ -148,9 +148,7 @@ impl EcmascriptChunkItem for ManifestLoaderChunkItem {
let placeable = let placeable =
ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(manifest.inner) ResolvedVc::try_downcast::<Box<dyn EcmascriptChunkPlaceable>>(manifest.inner)
.ok_or_else(|| anyhow!("asset is not placeable in ecmascript chunk"))?; .ok_or_else(|| anyhow!("asset is not placeable in ecmascript chunk"))?;
let dynamic_id = &*placeable let dynamic_id = &*placeable.chunk_item_id(*manifest.chunking_context).await?;
.chunk_item_id(*ResolvedVc::upcast(manifest.chunking_context))
.await?;
// This is the code that will be executed when the dynamic import is reached. // This is the code that will be executed when the dynamic import is reached.
// It will load the manifest chunk, which will load all the chunks needed by // It will load the manifest chunk, which will load all the chunks needed by
......
...@@ -120,7 +120,7 @@ impl ChunkItem for MergedEcmascriptModuleChunkItem { ...@@ -120,7 +120,7 @@ impl ChunkItem for MergedEcmascriptModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -153,13 +153,8 @@ impl EcmascriptChunkItem for MergedEcmascriptModuleChunkItem { ...@@ -153,13 +153,8 @@ impl EcmascriptChunkItem for MergedEcmascriptModuleChunkItem {
let entry_points = &module.entry_points; let entry_points = &module.entry_points;
let options = modules let options = modules
.iter() .iter()
.map(|(m, _)| { .map(|(m, _)| m.module_content_options(*self.chunking_context, async_module_info))
let Some(m) = ResolvedVc::try_downcast::<Box<dyn EcmascriptAnalyzable>>(*m) else { .collect::<Vec<_>>();
anyhow::bail!("Expected EcmascriptAnalyzable in scope hoisting group");
};
Ok(m.module_content_options(*self.chunking_context, async_module_info))
})
.collect::<Result<Vec<_>>>()?;
let content = EcmascriptModuleContent::new_merged( let content = EcmascriptModuleContent::new_merged(
modules.clone(), modules.clone(),
......
...@@ -174,7 +174,7 @@ impl AmdDefineWithDependenciesCodeGen { ...@@ -174,7 +174,7 @@ impl AmdDefineWithDependenciesCodeGen {
pattern_mapping: PatternMapping::resolve_request( pattern_mapping: PatternMapping::resolve_request(
**request, **request,
*self.origin, *self.origin,
Vc::upcast(chunking_context), chunking_context,
cjs_resolve( cjs_resolve(
*self.origin, *self.origin,
**request, **request,
......
...@@ -86,9 +86,9 @@ impl OptionAsyncModule { ...@@ -86,9 +86,9 @@ impl OptionAsyncModule {
struct AsyncModuleIdents(FxIndexSet<(String, AstSyntaxContext)>); struct AsyncModuleIdents(FxIndexSet<(String, AstSyntaxContext)>);
async fn get_inherit_async_referenced_asset( async fn get_inherit_async_referenced_asset(
r: Vc<Box<dyn ModuleReference>>, r: ResolvedVc<Box<dyn ModuleReference>>,
) -> Result<Option<ReadRef<ReferencedAsset>>> { ) -> Result<Option<ReadRef<ReferencedAsset>>> {
let Some(r) = Vc::try_resolve_downcast::<Box<dyn ChunkableModuleReference>>(r).await? else { let Some(r) = ResolvedVc::try_downcast::<Box<dyn ChunkableModuleReference>>(r) else {
return Ok(None); return Ok(None);
}; };
let Some(ty) = &*r.chunking_type().await? else { let Some(ty) = &*r.chunking_type().await? else {
...@@ -123,7 +123,7 @@ impl AsyncModule { ...@@ -123,7 +123,7 @@ impl AsyncModule {
.await? .await?
.iter() .iter()
.map(|r| async { .map(|r| async {
let Some(referenced_asset) = get_inherit_async_referenced_asset(**r).await? else { let Some(referenced_asset) = get_inherit_async_referenced_asset(*r).await? else {
return Ok(None); return Ok(None);
}; };
Ok(match &*referenced_asset { Ok(match &*referenced_asset {
...@@ -174,8 +174,7 @@ impl AsyncModule { ...@@ -174,8 +174,7 @@ impl AsyncModule {
.await? .await?
.iter() .iter()
.map(|r| async { .map(|r| async {
let Some(referenced_asset) = let Some(referenced_asset) = get_inherit_async_referenced_asset(*r).await?
get_inherit_async_referenced_asset(**r).await?
else { else {
return Ok(false); return Ok(false);
}; };
......
...@@ -166,7 +166,7 @@ impl CjsRequireAssetReferenceCodeGen { ...@@ -166,7 +166,7 @@ impl CjsRequireAssetReferenceCodeGen {
let pm = PatternMapping::resolve_request( let pm = PatternMapping::resolve_request(
*reference.request, *reference.request,
*reference.origin, *reference.origin,
Vc::upcast(chunking_context), chunking_context,
self.reference.resolve_reference(), self.reference.resolve_reference(),
ResolveType::ChunkItem, ResolveType::ChunkItem,
) )
...@@ -290,7 +290,7 @@ impl CjsRequireResolveAssetReferenceCodeGen { ...@@ -290,7 +290,7 @@ impl CjsRequireResolveAssetReferenceCodeGen {
let pm = PatternMapping::resolve_request( let pm = PatternMapping::resolve_request(
*reference.request, *reference.request,
*reference.origin, *reference.origin,
Vc::upcast(chunking_context), chunking_context,
self.reference.resolve_reference(), self.reference.resolve_reference(),
ResolveType::ChunkItem, ResolveType::ChunkItem,
) )
......
...@@ -171,8 +171,7 @@ impl ReferencedAsset { ...@@ -171,8 +171,7 @@ impl ReferencedAsset {
) -> Result<Option<ReferencedAssetIdent>> { ) -> Result<Option<ReferencedAssetIdent>> {
Ok(match self { Ok(match self {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
if let Some(ctxt) = if let Some(ctxt) = scope_hoisting_context.get_module_syntax_context(*asset)
scope_hoisting_context.get_module_syntax_context(ResolvedVc::upcast(*asset))
&& let Some(export) = &export && let Some(export) = &export
&& let EcmascriptExports::EsmExports(exports) = *asset.get_exports().await? && let EcmascriptExports::EsmExports(exports) = *asset.get_exports().await?
{ {
...@@ -271,7 +270,7 @@ impl ReferencedAsset { ...@@ -271,7 +270,7 @@ impl ReferencedAsset {
asset: &Vc<Box<dyn EcmascriptChunkPlaceable>>, asset: &Vc<Box<dyn EcmascriptChunkPlaceable>>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<String> { ) -> Result<String> {
let id = asset.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = asset.chunk_item_id(chunking_context).await?;
Ok(magic_identifier::mangle(&format!("imported module {id}"))) Ok(magic_identifier::mangle(&format!("imported module {id}")))
} }
} }
...@@ -604,9 +603,7 @@ impl EsmAssetReference { ...@@ -604,9 +603,7 @@ impl EsmAssetReference {
unreachable!(); unreachable!();
} }
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
let id = asset let id = asset.chunk_item_id(chunking_context).await?;
.chunk_item_id(Vc::upcast(chunking_context))
.await?;
let (sym, ctxt) = let (sym, ctxt) =
ident.into_module_namespace_ident().unwrap(); ident.into_module_namespace_ident().unwrap();
let name = Ident::new( let name = Ident::new(
......
...@@ -137,7 +137,7 @@ impl EsmAsyncAssetReferenceCodeGen { ...@@ -137,7 +137,7 @@ impl EsmAsyncAssetReferenceCodeGen {
let pm = PatternMapping::resolve_request( let pm = PatternMapping::resolve_request(
*reference.request, *reference.request,
*reference.origin, *reference.origin,
Vc::upcast(chunking_context), chunking_context,
self.reference.resolve_reference(), self.reference.resolve_reference(),
if matches!( if matches!(
*chunking_context.environment().chunk_loading().await?, *chunking_context.environment().chunk_loading().await?,
......
...@@ -297,8 +297,7 @@ async fn find_export_from_reexports( ...@@ -297,8 +297,7 @@ async fn find_export_from_reexports(
export_name: RcStr, export_name: RcStr,
) -> Result<Vc<FindExportFromReexportsResult>> { ) -> Result<Vc<FindExportFromReexportsResult>> {
// TODO why do we need a special case for this? // TODO why do we need a special case for this?
if let Some(module) = if let Some(module) = ResolvedVc::try_downcast_type::<EcmascriptModulePartAsset>(module)
Vc::try_resolve_downcast_type::<EcmascriptModulePartAsset>(*module).await?
&& matches!(module.await?.part, ModulePart::Exports) && matches!(module.await?.part, ModulePart::Exports)
{ {
let module_part = EcmascriptModulePartAsset::select_part( let module_part = EcmascriptModulePartAsset::select_part(
...@@ -309,10 +308,7 @@ async fn find_export_from_reexports( ...@@ -309,10 +308,7 @@ async fn find_export_from_reexports(
// If we apply this logic to EcmascriptModuleAsset, we will resolve everything in the // If we apply this logic to EcmascriptModuleAsset, we will resolve everything in the
// target module. // target module.
if (Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module_part).await?).is_none() { if (Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module_part).await?).is_none() {
return Ok(find_export_from_reexports( return Ok(find_export_from_reexports(module_part, export_name));
Vc::upcast(module_part),
export_name,
));
} }
} }
...@@ -547,11 +543,7 @@ impl EsmExports { ...@@ -547,11 +543,7 @@ impl EsmExports {
if !exports.contains_key(export) { if !exports.contains_key(export) {
exports.insert( exports.insert(
export.clone(), export.clone(),
EsmExport::ImportedBinding( EsmExport::ImportedBinding(esm_ref, export.clone(), false),
ResolvedVc::upcast(esm_ref),
export.clone(),
false,
),
); );
} }
} }
...@@ -596,7 +588,7 @@ impl EsmExports { ...@@ -596,7 +588,7 @@ impl EsmExports {
let id = if let Some(module) = scope_hoisting_context.module() let id = if let Some(module) = scope_hoisting_context.module()
&& !expanded.dynamic_exports.is_empty() && !expanded.dynamic_exports.is_empty()
{ {
Some(module.chunk_item_id(Vc::upcast(chunking_context)).await?) Some(module.chunk_item_id(chunking_context).await?)
} else { } else {
None None
}; };
...@@ -814,7 +806,7 @@ impl EsmExports { ...@@ -814,7 +806,7 @@ impl EsmExports {
let esm_exports = vec![CodeGenerationHoistedStmt::new( let esm_exports = vec![CodeGenerationHoistedStmt::new(
rcstr!("__turbopack_esm__"), rcstr!("__turbopack_esm__"),
if let Some(module) = scope_hoisting_context.module() { if let Some(module) = scope_hoisting_context.module() {
let id = module.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = module.chunk_item_id(chunking_context).await?;
quote!("$turbopack_esm($getters, $id);" as Stmt, quote!("$turbopack_esm($getters, $id);" as Stmt,
turbopack_esm: Expr = TURBOPACK_ESM.into(), turbopack_esm: Expr = TURBOPACK_ESM.into(),
getters: Expr = getters, getters: Expr = getters,
......
...@@ -89,7 +89,7 @@ impl EsmModuleIdAssetReferenceCodeGen { ...@@ -89,7 +89,7 @@ impl EsmModuleIdAssetReferenceCodeGen {
if let ReferencedAsset::Some(asset) = if let ReferencedAsset::Some(asset) =
&*self.reference.await?.inner.get_referenced_asset().await? &*self.reference.await?.inner.get_referenced_asset().await?
{ {
let id = asset.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = asset.chunk_item_id(chunking_context).await?;
let id = module_id_to_lit(&id); let id = module_id_to_lit(&id);
visitors.push(create_visitor!( visitors.push(create_visitor!(
self.path, self.path,
......
...@@ -192,7 +192,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -192,7 +192,7 @@ impl UrlAssetReferenceCodeGen {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
// We rewrite the first `new URL()` arguments to be a require() of the chunk // We rewrite the first `new URL()` arguments to be a require() of the chunk
// item, which exports the static asset path to the linked file. // item, which exports the static asset path to the linked file.
let id = asset.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = asset.chunk_item_id(chunking_context).await?;
visitors.push(create_visitor!(self.path, visit_mut_expr, |new_expr: &mut Expr| { visitors.push(create_visitor!(self.path, visit_mut_expr, |new_expr: &mut Expr| {
let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr { let should_rewrite_to_relative = if let Expr::New(NewExpr { args: Some(args), .. }) = new_expr {
...@@ -257,7 +257,7 @@ impl UrlAssetReferenceCodeGen { ...@@ -257,7 +257,7 @@ impl UrlAssetReferenceCodeGen {
ReferencedAsset::Some(asset) => { ReferencedAsset::Some(asset) => {
// We rewrite the first `new URL()` arguments to be a require() of the // We rewrite the first `new URL()` arguments to be a require() of the
// chunk item, which returns the asset path as its exports. // chunk item, which returns the asset path as its exports.
let id = asset.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = asset.chunk_item_id(chunking_context).await?;
// If there's a rewrite to the base url, then the current rendering // If there's a rewrite to the base url, then the current rendering
// environment should able to resolve the asset path // environment should able to resolve the asset path
......
...@@ -61,8 +61,8 @@ use swc_core::{ ...@@ -61,8 +61,8 @@ use swc_core::{
use tracing::Instrument; use tracing::Instrument;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt, Upcast, FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TaskInput, TryJoinIterExt,
ValueToString, Vc, trace::TraceRawVcs, UpcastStrict, ValueToString, Vc, trace::TraceRawVcs,
}; };
use turbo_tasks_fs::FileSystemPath; use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{ use turbopack_core::{
...@@ -255,7 +255,10 @@ impl AnalyzeEcmascriptModuleResultBuilder { ...@@ -255,7 +255,10 @@ impl AnalyzeEcmascriptModuleResultBuilder {
} }
/// Adds an asset reference to the analysis result. /// Adds an asset reference to the analysis result.
pub fn add_reference(&mut self, reference: ResolvedVc<impl Upcast<Box<dyn ModuleReference>>>) { pub fn add_reference(
&mut self,
reference: ResolvedVc<impl UpcastStrict<Box<dyn ModuleReference>>>,
) {
let r = ResolvedVc::upcast(reference); let r = ResolvedVc::upcast(reference);
self.references.insert(r); self.references.insert(r);
} }
...@@ -263,7 +266,7 @@ impl AnalyzeEcmascriptModuleResultBuilder { ...@@ -263,7 +266,7 @@ impl AnalyzeEcmascriptModuleResultBuilder {
/// Adds an asset reference with codegen to the analysis result. /// Adds an asset reference with codegen to the analysis result.
pub fn add_reference_code_gen<R: IntoCodeGenReference>(&mut self, reference: R, path: AstPath) { pub fn add_reference_code_gen<R: IntoCodeGenReference>(&mut self, reference: R, path: AstPath) {
let (reference, code_gen) = reference.into_code_gen_reference(path); let (reference, code_gen) = reference.into_code_gen_reference(path);
self.add_reference(reference); self.references.insert(reference);
self.add_code_gen(code_gen); self.add_code_gen(code_gen);
} }
......
...@@ -331,7 +331,7 @@ impl RequireContextAssetReferenceCodeGen { ...@@ -331,7 +331,7 @@ impl RequireContextAssetReferenceCodeGen {
.reference .reference
.await? .await?
.inner .inner
.chunk_item_id(Vc::upcast(chunking_context)) .chunk_item_id(chunking_context)
.await?; .await?;
let mut visitors = Vec::new(); let mut visitors = Vec::new();
...@@ -485,7 +485,7 @@ impl EcmascriptChunkItem for RequireContextChunkItem { ...@@ -485,7 +485,7 @@ impl EcmascriptChunkItem for RequireContextChunkItem {
let pm = PatternMapping::resolve_request( let pm = PatternMapping::resolve_request(
*entry.request, *entry.request,
*self.origin, *self.origin,
*ResolvedVc::upcast(self.chunking_context), *self.chunking_context,
*entry.result, *entry.result,
ResolveType::ChunkItem, ResolveType::ChunkItem,
) )
...@@ -563,7 +563,7 @@ impl ChunkItem for RequireContextChunkItem { ...@@ -563,7 +563,7 @@ impl ChunkItem for RequireContextChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -62,7 +62,7 @@ impl ChunkItem for EcmascriptModuleFacadeChunkItem { ...@@ -62,7 +62,7 @@ impl ChunkItem for EcmascriptModuleFacadeChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -62,7 +62,7 @@ impl ChunkItem for EcmascriptModuleLocalsChunkItem { ...@@ -62,7 +62,7 @@ impl ChunkItem for EcmascriptModuleLocalsChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -204,7 +204,7 @@ impl EcmascriptModulePartReference { ...@@ -204,7 +204,7 @@ impl EcmascriptModulePartReference {
let key = sym.as_str().into(); let key = sym.as_str().into();
let name = Ident::new(sym.into(), DUMMY_SP, ctxt.unwrap_or_default()); let name = Ident::new(sym.into(), DUMMY_SP, ctxt.unwrap_or_default());
let id = module.chunk_item_id(Vc::upcast(chunking_context)).await?; let id = module.chunk_item_id(chunking_context).await?;
result.push(CodeGenerationHoistedStmt::new( result.push(CodeGenerationHoistedStmt::new(
key, key,
......
...@@ -216,7 +216,7 @@ impl EcmascriptModulePartAsset { ...@@ -216,7 +216,7 @@ impl EcmascriptModulePartAsset {
) )
}; };
if side_effects.is_empty() { if side_effects.is_empty() {
return Ok(*ResolvedVc::upcast(final_module)); return Ok(*final_module);
} }
let side_effects_module = SideEffectsModule::new( let side_effects_module = SideEffectsModule::new(
module, module,
...@@ -419,13 +419,13 @@ impl EvaluatableAsset for EcmascriptModulePartAsset {} ...@@ -419,13 +419,13 @@ impl EvaluatableAsset for EcmascriptModulePartAsset {}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn only_effects( async fn only_effects(
module: Vc<Box<dyn EcmascriptChunkPlaceable>>, module: ResolvedVc<Box<dyn EcmascriptChunkPlaceable>>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> { ) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
if let Some(module) = Vc::try_resolve_downcast_type::<EcmascriptModuleAsset>(module).await? { if let Some(module) = ResolvedVc::try_downcast_type::<EcmascriptModuleAsset>(module) {
let module = let module =
EcmascriptModulePartAsset::new_with_resolved_part(module, ModulePart::evaluation()); EcmascriptModulePartAsset::new_with_resolved_part(*module, ModulePart::evaluation());
return Ok(Vc::upcast(module)); return Ok(Vc::upcast(module));
} }
Ok(module) Ok(*module)
} }
...@@ -68,7 +68,7 @@ impl ChunkItem for EcmascriptModulePartChunkItem { ...@@ -68,7 +68,7 @@ impl ChunkItem for EcmascriptModulePartChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -244,9 +244,7 @@ impl ModuleReference for TsExtendsReference { ...@@ -244,9 +244,7 @@ impl ModuleReference for TsExtendsReference {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> { async fn resolve_reference(&self) -> Result<Vc<ModuleResolveResult>> {
Ok(*ModuleResolveResult::module(ResolvedVc::upcast( Ok(*ModuleResolveResult::module(ResolvedVc::upcast(
RawModule::new(*ResolvedVc::upcast(self.config)) RawModule::new(*self.config).to_resolved().await?,
.to_resolved()
.await?,
))) )))
} }
} }
......
...@@ -99,7 +99,7 @@ impl ChunkItem for WorkerLoaderChunkItem { ...@@ -99,7 +99,7 @@ impl ChunkItem for WorkerLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -103,7 +103,7 @@ impl ChunkItem for JsonChunkItem { ...@@ -103,7 +103,7 @@ impl ChunkItem for JsonChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -261,27 +261,25 @@ pub async fn get_intermediate_asset( ...@@ -261,27 +261,25 @@ pub async fn get_intermediate_asset(
main_entry: ResolvedVc<Box<dyn EvaluatableAsset>>, main_entry: ResolvedVc<Box<dyn EvaluatableAsset>>,
other_entries: Vc<EvaluatableAssets>, other_entries: Vc<EvaluatableAssets>,
) -> Result<Vc<Box<dyn OutputAsset>>> { ) -> Result<Vc<Box<dyn OutputAsset>>> {
Ok(Vc::upcast( Ok(chunking_context.root_entry_chunk_group_asset(
chunking_context.root_entry_chunk_group_asset( chunking_context
chunking_context .chunk_path(None, main_entry.ident(), None, rcstr!(".js"))
.chunk_path(None, main_entry.ident(), None, rcstr!(".js")) .owned()
.owned() .await?,
.await?, other_entries.with_entry(*main_entry),
other_entries.with_entry(*main_entry), ModuleGraph::from_modules(
ModuleGraph::from_modules( Vc::cell(vec![ChunkGroupEntry::Entry(
Vc::cell(vec![ChunkGroupEntry::Entry( other_entries
other_entries .await?
.await? .into_iter()
.into_iter() .copied()
.copied() .chain(std::iter::once(main_entry))
.chain(std::iter::once(main_entry)) .map(ResolvedVc::upcast)
.map(ResolvedVc::upcast) .collect(),
.collect(), )]),
)]), false,
false,
),
OutputAssets::empty(),
), ),
OutputAssets::empty(),
)) ))
} }
......
...@@ -108,7 +108,7 @@ impl NodeJsChunkingContextBuilder { ...@@ -108,7 +108,7 @@ impl NodeJsChunkingContextBuilder {
{ {
self.chunking_context self.chunking_context
.chunking_configs .chunking_configs
.push((ResolvedVc::upcast(ty), chunking_config)); .push((ResolvedVc::upcast_non_strict(ty), chunking_config));
self self
} }
...@@ -205,17 +205,16 @@ impl NodeJsChunkingContext { ...@@ -205,17 +205,16 @@ impl NodeJsChunkingContext {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn generate_chunk( async fn generate_chunk(
self: Vc<Self>, self: Vc<Self>,
chunk: Vc<Box<dyn Chunk>>, chunk: ResolvedVc<Box<dyn Chunk>>,
) -> Result<Vc<Box<dyn OutputAsset>>> { ) -> Result<Vc<Box<dyn OutputAsset>>> {
Ok( Ok(
if let Some(ecmascript_chunk) = if let Some(ecmascript_chunk) = ResolvedVc::try_downcast_type::<EcmascriptChunk>(chunk)
Vc::try_resolve_downcast_type::<EcmascriptChunk>(chunk).await?
{ {
Vc::upcast(EcmascriptBuildNodeChunk::new(self, ecmascript_chunk)) Vc::upcast(EcmascriptBuildNodeChunk::new(self, *ecmascript_chunk))
} else if let Some(output_asset) = } else if let Some(output_asset) =
Vc::try_resolve_sidecast::<Box<dyn OutputAsset>>(chunk).await? ResolvedVc::try_sidecast::<Box<dyn OutputAsset>>(chunk)
{ {
output_asset *output_asset
} else { } else {
bail!("Unable to generate output asset for chunk"); bail!("Unable to generate output asset for chunk");
}, },
...@@ -509,7 +508,7 @@ impl ChunkingContext for NodeJsChunkingContext { ...@@ -509,7 +508,7 @@ impl ChunkingContext for NodeJsChunkingContext {
)) ))
} else { } else {
let module = AsyncLoaderModule::new(module, Vc::upcast(self), availability_info); let module = AsyncLoaderModule::new(module, Vc::upcast(self), availability_info);
Vc::upcast(module.as_chunk_item(module_graph, Vc::upcast(self))) module.as_chunk_item(module_graph, Vc::upcast(self))
}) })
} }
......
...@@ -189,9 +189,7 @@ impl OutputAsset for EcmascriptBuildNodeEntryChunk { ...@@ -189,9 +189,7 @@ impl OutputAsset for EcmascriptBuildNodeEntryChunk {
} }
let other_chunks = this.other_chunks.await?; let other_chunks = this.other_chunks.await?;
for &other_chunk in &*other_chunks { references.extend(other_chunks.iter().copied());
references.push(ResolvedVc::upcast(other_chunk));
}
Ok(Vc::cell(references)) Ok(Vc::cell(references))
} }
......
...@@ -74,7 +74,7 @@ impl ChunkableModule for StaticUrlJsModule { ...@@ -74,7 +74,7 @@ impl ChunkableModule for StaticUrlJsModule {
module: self, module: self,
chunking_context, chunking_context,
static_asset: self static_asset: self
.static_output_asset(*ResolvedVc::upcast(chunking_context)) .static_output_asset(*chunking_context)
.to_resolved() .to_resolved()
.await?, .await?,
}, },
...@@ -111,7 +111,7 @@ impl ChunkItem for StaticUrlJsChunkItem { ...@@ -111,7 +111,7 @@ impl ChunkItem for StaticUrlJsChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
*ResolvedVc::upcast(self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -404,7 +404,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -404,7 +404,7 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
{ {
let evaluatable_assets = runtime_entries let evaluatable_assets = runtime_entries
.unwrap_or_else(EvaluatableAssets::empty) .unwrap_or_else(EvaluatableAssets::empty)
.with_entry(Vc::upcast(ecmascript)); .with_entry(ecmascript);
( (
evaluatable_assets, evaluatable_assets,
evaluatable_assets evaluatable_assets
......
...@@ -221,7 +221,7 @@ impl ChunkItem for ModuleChunkItem { ...@@ -221,7 +221,7 @@ impl ChunkItem for ModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -250,8 +250,7 @@ impl EcmascriptChunkItem for ModuleChunkItem { ...@@ -250,8 +250,7 @@ impl EcmascriptChunkItem for ModuleChunkItem {
async_module_info: Option<Vc<AsyncModuleInfo>>, async_module_info: Option<Vc<AsyncModuleInfo>>,
) -> Result<Vc<EcmascriptChunkItemContent>> { ) -> Result<Vc<EcmascriptChunkItemContent>> {
let loader_asset = self.module.loader(); let loader_asset = self.module.loader();
let item = let item = loader_asset.as_chunk_item(*self.module_graph, *self.chunking_context);
loader_asset.as_chunk_item(*self.module_graph, Vc::upcast(*self.chunking_context));
let ecmascript_item = Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkItem>>(item) let ecmascript_item = Vc::try_resolve_downcast::<Box<dyn EcmascriptChunkItem>>(item)
.await? .await?
......
...@@ -117,7 +117,7 @@ impl ChunkItem for RawModuleChunkItem { ...@@ -117,7 +117,7 @@ impl ChunkItem for RawModuleChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> { fn chunking_context(&self) -> Vc<Box<dyn ChunkingContext>> {
Vc::upcast(*self.chunking_context) *self.chunking_context
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -119,7 +119,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) { ...@@ -119,7 +119,7 @@ fn bench_emit(b: &mut Bencher, bench_input: &BenchInput) {
let module = module_asset_context let module = module_asset_context
.process(Vc::upcast(source), ReferenceType::Undefined) .process(Vc::upcast(source), ReferenceType::Undefined)
.module(); .module();
let rebased = RebasedAsset::new(Vc::upcast(module), input_dir, output_dir.clone()) let rebased = RebasedAsset::new(module, input_dir, output_dir.clone())
.to_resolved() .to_resolved()
.await?; .await?;
......
...@@ -385,7 +385,7 @@ async fn node_file_trace_operation( ...@@ -385,7 +385,7 @@ async fn node_file_trace_operation(
.process(Vc::upcast(source), ReferenceType::Undefined) .process(Vc::upcast(source), ReferenceType::Undefined)
.module(); .module();
let rebased = RebasedAsset::new(Vc::upcast(module), input_dir.clone(), output_dir.clone()) let rebased = RebasedAsset::new(module, input_dir.clone(), output_dir.clone())
.to_resolved() .to_resolved()
.await?; .await?;
......
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