use std::{ any::Any, fmt::Debug, future::IntoFuture, hash::{Hash, Hasher}, marker::PhantomData, mem::transmute, ops::Deref, }; use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::{ RawVc, Upcast, VcRead, VcTransparentRead, VcValueTrait, VcValueType, debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString}, trace::{TraceRawVcs, TraceRawVcsContext}, vc::Vc, }; /// A "subtype" (via [`Deref`]) of [`Vc`] that represents a specific [`Vc::cell`]/`.cell()` or /// [`ResolvedVc::cell`]/`.resolved_cell()` constructor call within [a task][macro@crate::function]. /// /// Unlike [`Vc`], `ResolvedVc`: /// /// - Does not potentially refer to task-local information, meaning that it implements /// [`NonLocalValue`], and can be used in any [`#[turbo_tasks::value]`][macro@crate::value]. /// /// - Has only one potential internal representation, meaning that it has a saner equality /// definition. /// /// - Points to a concrete value with a type, and is therefore [cheap to /// downcast][ResolvedVc::try_downcast]. /// /// /// ## Construction /// /// There are a few ways to construct a `ResolvedVc`, in order of preference: /// /// 1. Given a [value][VcValueType], construct a `ResolvedVc` using [`ResolvedVc::cell`] (for /// "transparent" values) or by calling the generated `.resolved_cell()` constructor on the value /// type. /// /// 2. Given an argument to a function using the [`#[turbo_tasks::function]`][macro@crate::function] /// macro, change the argument's type to a `ResolvedVc`. The [rewritten external signature] will /// still use [`Vc`], but when the function is called, the [`Vc`] will be resolved. /// /// 3. Given a [`Vc`], use [`.to_resolved().await?`][Vc::to_resolved]. /// /// /// ## Equality & Hashing /// /// Equality between two `ResolvedVc`s means that both have an identical in-memory representation /// and point to the same cell. The implementation of [`Hash`] has similar behavior. /// /// If `.await`ed at the same time, both would likely resolve to the same [`ReadRef`], though it is /// possible that they may not if the cell is invalidated between `.await`s. /// /// Because equality is a synchronous operation that cannot read the cell contents, even if the /// `ResolvedVc`s are not equal, it is possible that if `.await`ed, both `ResolvedVc`s could point /// to the same or equal values. /// /// /// [`NonLocalValue`]: crate::NonLocalValue /// [rewritten external signature]: https://turbopack-rust-docs.vercel.sh/turbo-engine/tasks.html#external-signature-rewriting /// [`ReadRef`]: crate::ReadRef #[derive(Serialize, Deserialize)] #[serde(transparent, bound = "")] #[repr(transparent)] pub struct ResolvedVc where T: ?Sized, { pub(crate) node: Vc, } impl ResolvedVc where T: ?Sized, { /// This function exists to intercept calls to Vc::to_resolved through dereferencing /// a ResolvedVc. Converting to Vc and re-resolving it puts unnecessary stress on /// the turbo tasks engine. #[deprecated(note = "No point in resolving a vc that is already resolved")] pub async fn to_resolved(self) -> Result { Ok(self) } #[deprecated(note = "No point in resolving a vc that is already resolved")] pub async fn resolve(self) -> Result> { Ok(self.node) } } impl Copy for ResolvedVc where T: ?Sized {} impl Clone for ResolvedVc where T: ?Sized, { fn clone(&self) -> Self { *self } } impl Deref for ResolvedVc where T: ?Sized, { type Target = Vc; fn deref(&self) -> &Self::Target { &self.node } } impl PartialEq> for ResolvedVc where T: ?Sized, { fn eq(&self, other: &Self) -> bool { self.node == other.node } } impl Eq for ResolvedVc where T: ?Sized {} impl Hash for ResolvedVc where T: ?Sized, { fn hash(&self, state: &mut H) { self.node.hash(state); } } impl Default for ResolvedVc where T: VcValueType>, Inner: Any + Send + Sync + Default, Repr: VcValueType, { fn default() -> Self { Self::cell(Default::default()) } } macro_rules! into_future { ($ty:ty) => { impl IntoFuture for $ty where T: VcValueType, { type Output = as IntoFuture>::Output; type IntoFuture = as IntoFuture>::IntoFuture; fn into_future(self) -> Self::IntoFuture { (*self).into_future() } } }; } into_future!(ResolvedVc); into_future!(&ResolvedVc); into_future!(&mut ResolvedVc); impl ResolvedVc where T: VcValueType, { // called by the `.resolved_cell()` method generated by the `#[turbo_tasks::value]` macro #[doc(hidden)] pub fn cell_private(inner: >::Target) -> Self { Self { node: Vc::::cell_private(inner), } } } impl ResolvedVc where T: VcValueType>, Inner: Any + Send + Sync, Repr: VcValueType, { pub fn cell(inner: Inner) -> Self { Self { node: Vc::::cell(inner), } } } impl ResolvedVc where T: ?Sized, { /// Upcasts the given `ResolvedVc` to a `ResolvedVc>`. /// /// See also: [`Vc::upcast`]. #[inline(always)] pub fn upcast(this: Self) -> ResolvedVc where T: Upcast, K: VcValueTrait + ?Sized, { ResolvedVc { node: Vc::upcast(this.node), } } /// Cheaply converts a Vec of resolved Vcs to a Vec of Vcs. pub fn deref_vec(vec: Vec>) -> Vec> { debug_assert!(size_of::>() == size_of::>()); // Safety: The memory layout of `ResolvedVc` and `Vc` is the same. unsafe { transmute::>, Vec>>(vec) } } /// Cheaply converts a slice of resolved Vcs to a slice of Vcs. pub fn deref_slice(slice: &[ResolvedVc]) -> &[Vc] { debug_assert!(size_of::>() == size_of::>()); // Safety: The memory layout of `ResolvedVc` and `Vc` is the same. unsafe { transmute::<&[ResolvedVc], &[Vc]>(slice) } } } impl ResolvedVc where T: VcValueTrait + ?Sized, { /// Returns `None` if the underlying value type does not implement `K`. /// /// **Note:** if the trait `T` is required to implement `K`, use [`ResolvedVc::upcast`] instead. /// This provides stronger guarantees, removing the need for a [`Result`] return type. /// /// See also: [`Vc::try_resolve_sidecast`]. pub fn try_sidecast(this: Self) -> Option> where K: VcValueTrait + ?Sized, { // `RawVc::TaskCell` already contains all the type information needed to check this // sidecast, so we don't need to read the underlying cell! let raw_vc = this.node.node; raw_vc .resolved_has_trait(::get_trait_type_id()) .then_some(ResolvedVc { node: Vc { node: raw_vc, _t: PhantomData, }, }) } /// Attempts to downcast the given `ResolvedVc>` to a `ResolvedVc`, where `K` /// is of the form `Box`, and `L` is a value trait. /// /// Returns `None` if the underlying value type is not a `K`. /// /// See also: [`Vc::try_resolve_downcast`]. pub fn try_downcast(this: Self) -> Option> where K: Upcast + VcValueTrait + ?Sized, { // this is just a more type-safe version of a sidecast Self::try_sidecast(this) } /// Attempts to downcast the given `Vc>` to a `Vc`, where `K` is a value type. /// /// Returns `None` if the underlying value type is not a `K`. /// /// See also: [`Vc::try_resolve_downcast_type`]. pub fn try_downcast_type(this: Self) -> Option> where K: Upcast + VcValueType, { let raw_vc = this.node.node; raw_vc .resolved_is_type(::get_value_type_id()) .then_some(ResolvedVc { node: Vc { node: raw_vc, _t: PhantomData, }, }) } } /// Generates an opaque debug representation of the [`ResolvedVc`] itself, but not the data inside /// of it. /// /// This is implemented to allow types containing [`ResolvedVc`] to implement the synchronous /// [`Debug`] trait, but in most cases users should use the [`ValueDebug`] implementation to get a /// string representation of the contents of the cell. impl Debug for ResolvedVc where T: ?Sized, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ResolvedVc") .field("node", &self.node.node) .finish() } } impl TraceRawVcs for ResolvedVc where T: ?Sized, { fn trace_raw_vcs(&self, trace_context: &mut TraceRawVcsContext) { TraceRawVcs::trace_raw_vcs(&self.node, trace_context); } } impl ValueDebugFormat for ResolvedVc where T: Upcast> + Send + Sync + ?Sized, { fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> { self.node.value_debug_format(depth) } } impl TryFrom for ResolvedVc where T: ?Sized, { type Error = anyhow::Error; fn try_from(raw: RawVc) -> Result { if !matches!(raw, RawVc::TaskCell(..)) { anyhow::bail!("Given RawVc {raw:?} is not a TaskCell"); } Ok(Self { node: Vc::from(raw), }) } }