Skip to main content

turbo_tasks/vc/
mod.rs

1pub(crate) mod cast;
2mod cell_mode;
3pub(crate) mod default;
4mod keyed_read_ref;
5mod lazy_read_ref;
6mod local;
7pub(crate) mod operation;
8mod ord;
9mod raw;
10mod read;
11pub(crate) mod resolved;
12mod traits;
13
14use std::{
15    any::Any,
16    fmt::Debug,
17    future::Future,
18    hash::{Hash, Hasher},
19    marker::PhantomData,
20    ops::Deref,
21    pin::Pin,
22    task::{Context, Poll},
23};
24
25use anyhow::Result;
26use bincode::{Decode, Encode};
27use serde::{Deserialize, Serialize};
28use shrink_to_fit::ShrinkToFit;
29
30#[cfg(debug_assertions)]
31use crate::debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString};
32pub use crate::vc::{
33    cast::{VcCast, VcValueTraitCast, VcValueTypeCast},
34    cell_mode::{
35        VcCellCompareMode, VcCellHashedCompareMode, VcCellKeyedCompareMode, VcCellMode,
36        VcCellNewMode,
37    },
38    default::ValueDefault,
39    keyed_read_ref::KeyedReadRef,
40    lazy_read_ref::LazyReadRef,
41    local::NonLocalValue,
42    operation::{OperationValue, OperationVc, ResolveOperationVcFuture},
43    ord::OrdResolvedVc,
44    raw::{CellId, RawVc, RawVcUnpacked, ReadRawVcFuture, ResolveRawVcFuture},
45    read::{
46        ReadKeyedReaderVcFuture, ReadLazyReaderVcFuture, ReadOwnedVcFuture, ReadVcFuture,
47        VcDefaultRead, VcRead, VcTransparentRead,
48    },
49    resolved::ResolvedVc,
50    traits::{Dynamic, Upcast, UpcastStrict, VcValueTrait, VcValueType},
51};
52use crate::{
53    keyed::{KeyedAccess, KeyedEq},
54    registry,
55    vc::read::{ReadContainsKeyedVcFuture, ReadKeyedVcFuture},
56};
57
58/// A future returned by [`Vc::resolve`] that resolves a [`Vc<T>`] to a cell.
59///
60/// To opt into strong consistency, use [`OperationVc::resolve`] which returns a
61/// [`ResolveOperationVcFuture`] with a
62/// [`.strongly_consistent()`][ResolveOperationVcFuture::strongly_consistent] method.
63#[must_use]
64pub struct ResolveVcFuture<T>
65where
66    T: ?Sized,
67{
68    pub(crate) inner: ResolveRawVcFuture,
69    pub(crate) _t: PhantomData<T>,
70}
71
72impl<T: ?Sized> Future for ResolveVcFuture<T> {
73    type Output = Result<Vc<T>>;
74
75    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
76        // SAFETY: we are not moving self
77        let this = unsafe { self.get_unchecked_mut() };
78        // ResolveRawVcFuture: Unpin, so Pin::new is safe
79        Pin::new(&mut this.inner).poll(cx).map(|r| {
80            r.map(|node| Vc {
81                node,
82                _t: PhantomData,
83            })
84        })
85    }
86}
87
88impl<T: ?Sized> Unpin for ResolveVcFuture<T> {}
89
90/// A future returned by [`Vc::to_resolved`] that resolves a [`Vc<T>`] to a [`ResolvedVc<T>`].
91///
92/// Use [`.strongly_consistent()`][Self::strongly_consistent] to opt into strong consistency.
93#[must_use]
94pub struct ToResolvedVcFuture<T>
95where
96    T: ?Sized,
97{
98    inner: ResolveRawVcFuture,
99    _t: PhantomData<T>,
100}
101
102impl<T: ?Sized> ToResolvedVcFuture<T> {
103    /// Make the resolution strongly consistent.
104    pub fn strongly_consistent(mut self) -> Self {
105        self.inner = self.inner.strongly_consistent();
106        self
107    }
108}
109
110impl<T: ?Sized> Future for ToResolvedVcFuture<T> {
111    type Output = Result<ResolvedVc<T>>;
112
113    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
114        // SAFETY: we are not moving self
115        let this = unsafe { self.get_unchecked_mut() };
116        // ResolveRawVcFuture: Unpin, so Pin::new is safe
117        Pin::new(&mut this.inner).poll(cx).map(|r| {
118            r.map(|node| ResolvedVc {
119                node: Vc {
120                    node,
121                    _t: PhantomData,
122                },
123            })
124        })
125    }
126}
127
128impl<T: ?Sized> Unpin for ToResolvedVcFuture<T> {}
129
130type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;
131
132#[doc = include_str!("README.md")]
133#[must_use]
134#[derive(Serialize, Deserialize, Encode, Decode)]
135#[serde(transparent, bound = "")]
136#[bincode(bounds = "T: ?Sized")]
137#[repr(transparent)]
138pub struct Vc<T>
139where
140    T: ?Sized,
141{
142    pub(crate) node: RawVc,
143    #[doc(hidden)]
144    pub(crate) _t: PhantomData<T>,
145}
146
147/// This only exists to satisfy the Rust type system. However, this struct can
148/// never actually be instantiated, as dereferencing a `Vc<T>` will result in a
149/// linker error. See the implementation of `Deref` for `Vc<T>`.
150pub struct VcDeref<T>
151where
152    T: ?Sized,
153{
154    _t: PhantomData<T>,
155}
156
157macro_rules! do_not_use_or_you_will_be_fired {
158    ($($name:ident)*) => {
159        impl<T> VcDeref<T>
160        where
161            T: ?Sized,
162        {
163            $(
164                #[doc(hidden)]
165                #[allow(unused)]
166                #[allow(clippy::wrong_self_convention)]
167                #[deprecated = "This is not the method you are looking for."]
168                pub fn $name(self) {}
169            )*
170        }
171    };
172}
173
174// Hide raw pointer methods on `Vc<T>`. This is an artifact of having
175// implement `Deref<Target = *const T>` on `Vc<T>` for `arbitrary_self_types` to
176// do its thing. This can be removed once the `Receiver` trait no longer depends
177// on `Deref`.
178do_not_use_or_you_will_be_fired!(
179    add
180    addr
181    align_offset
182    as_mut
183    as_mut_ptr
184    as_ptr
185    as_ref
186    as_uninit_mut
187    as_uninit_ref
188    as_uninit_slice
189    as_uninit_slice_mut
190    byte_add
191    byte_offset
192    byte_offset_from
193    byte_sub
194    cast
195    cast_const
196    cast_mut
197    copy_from
198    copy_from_nonoverlapping
199    copy_to
200    copy_to_nonoverlapping
201    drop_in_place
202    expose_addr
203    from_bits
204    get_unchecked
205    get_unchecked_mut
206    guaranteed_eq
207    guaranteed_ne
208    is_aligned
209    is_aligned_to
210    is_empty
211    is_null
212    len
213    map_addr
214    mask
215    offset
216    offset_from
217    read
218    read_unaligned
219    read_volatile
220    replace
221    split_at_mut
222    split_at_mut_unchecked
223    sub
224    sub_ptr
225    swap
226    to_bits
227    to_raw_parts
228    with_addr
229    with_metadata_of
230    wrapping_add
231    wrapping_byte_add
232    wrapping_byte_offset
233    wrapping_byte_sub
234    wrapping_offset
235    wrapping_sub
236    write
237    write_bytes
238    write_unaligned
239    write_volatile
240);
241
242// Call this macro for all the applicable methods above:
243
244#[doc(hidden)]
245impl<T> Deref for VcDeref<T>
246where
247    T: ?Sized,
248{
249    // `*const T` or `*mut T` would be enough here, but from an abundance of
250    // caution, we use `*const *mut *const T` to make sure there will never be an
251    // applicable method.
252    type Target = *const *mut *const T;
253
254    fn deref(&self) -> &Self::Target {
255        unsafe extern "C" {
256            #[link_name = "\n\nERROR: you tried to dereference a `Vc<T>`\n"]
257            fn trigger() -> !;
258        }
259
260        unsafe { trigger() };
261    }
262}
263
264// This is the magic that makes `Vc<T>` accept `self: Vc<Self>` methods through
265// `arbitrary_self_types`, while not allowing any other receiver type:
266// * `Vc<T>` dereferences to `*const *mut *const T`, which means that it is valid under the
267//   `arbitrary_self_types` rules.
268// * `*const *mut *const T` is not a valid receiver for any attribute access on `T`, which means
269//   that the only applicable items will be the methods declared on `self: Vc<Self>`.
270//
271// If we had used `type Target = T` instead, `vc_t.some_attr_defined_on_t` would
272// have been accepted by the compiler.
273#[doc(hidden)]
274impl<T> Deref for Vc<T>
275where
276    T: ?Sized,
277{
278    type Target = VcDeref<T>;
279
280    fn deref(&self) -> &Self::Target {
281        unsafe extern "C" {
282            #[link_name = "\n\nERROR: you tried to dereference a `Vc<T>`\n"]
283            fn trigger() -> !;
284        }
285
286        unsafe { trigger() };
287    }
288}
289
290impl<T> Copy for Vc<T> where T: ?Sized {}
291
292impl<T> Clone for Vc<T>
293where
294    T: ?Sized,
295{
296    fn clone(&self) -> Self {
297        *self
298    }
299}
300
301impl<T> Hash for Vc<T>
302where
303    T: ?Sized,
304{
305    fn hash<H: Hasher>(&self, state: &mut H) {
306        self.node.hash(state);
307    }
308}
309
310impl<T> PartialEq<Vc<T>> for Vc<T>
311where
312    T: ?Sized,
313{
314    fn eq(&self, other: &Self) -> bool {
315        self.node == other.node
316    }
317}
318
319impl<T> Eq for Vc<T> where T: ?Sized {}
320
321/// Generates an opaque debug representation of the [`Vc`] itself, but not the data inside of it.
322///
323/// This is implemented to allow types containing [`Vc`] to implement the synchronous [`Debug`]
324/// trait, but in most cases users should use the [`ValueDebug`] implementation to get a string
325/// representation of the contents of the cell.
326impl<T> Debug for Vc<T>
327where
328    T: ?Sized,
329{
330    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
331        f.debug_tuple("Vc").field(&self.node).finish()
332    }
333}
334
335impl<T> Vc<T>
336where
337    T: VcValueType,
338{
339    // called by the `.cell()` method generated by the `#[turbo_tasks::value]` macro
340    #[doc(hidden)]
341    pub fn cell_private(mut inner: <T::Read as VcRead<T>>::Target) -> Self {
342        // cell contents are immutable, so go ahead and shrink the cell's contents
343        ShrinkToFit::shrink_to_fit(<T::Read as VcRead<T>>::target_to_value_mut_ref(&mut inner));
344        <T::CellMode as VcCellMode<T>>::cell(inner)
345    }
346}
347
348impl<T, Inner> Vc<T>
349where
350    T: VcValueType<Read = VcTransparentRead<T, Inner>>,
351    Inner: Any + Send + Sync,
352{
353    pub fn cell(inner: Inner) -> Self {
354        Self::cell_private(inner)
355    }
356}
357
358impl<T> Vc<T>
359where
360    T: ?Sized,
361{
362    /// Returns a debug identifier for this `Vc`.
363    pub async fn debug_identifier(vc: Self) -> Result<String> {
364        let resolved = vc.to_resolved().await?;
365        let raw_vc: RawVc = resolved.node.node;
366        if let Some((task_id, cell_id)) = raw_vc.as_task_cell() {
367            let value_name = registry::get_value_type(cell_id.type_id()).ty.name;
368            Ok(format!(
369                "{value_name}#{index}: {task_id}",
370                index = cell_id.index(),
371            ))
372        } else {
373            unreachable!()
374        }
375    }
376
377    /// Returns the `RawVc` corresponding to this `Vc`.
378    pub fn into_raw(vc: Self) -> RawVc {
379        vc.node
380    }
381
382    /// Upcasts the given `Vc<T>` to a `Vc<Box<dyn K>>`.
383    ///
384    /// This is also available as an `Into`/`From` conversion.
385    #[inline(always)]
386    pub fn upcast<K>(vc: Self) -> Vc<K>
387    where
388        T: UpcastStrict<K>,
389        K: VcValueTrait + ?Sized,
390    {
391        Self::upcast_non_strict(vc)
392    }
393
394    /// Upcasts the given `Vc<T>` to a `Vc<Box<dyn K>>`
395    ///
396    /// This has a loose type constraint which would allow upcasting to the same type, prefer using
397    /// [`Vc::upcast`] when possible.  This is useful for extension traits and other more generic
398    /// usecases.
399    ///
400    /// # Example
401    /// ```ignore
402    /// // In generic code where T might be the same as K
403    /// fn process_foo(vc: ResolvedVc<impl Upcast<Box<dyn MyTrait>>>) -> Vc<Foo> {
404    ///    let my_trait: ResolvedVc<Box<dyn MyTrait>> = Vc::upcast_non_strict(vc);
405    ///    my_trait.do_something()
406    /// }
407    /// ```
408    /// Using generics you could allow users to pass any compatible type, but if you specified
409    /// `UpcastStrict<...>` instead of `Upcast<...>` you would disallow calling this function if you
410    /// already had a `ResolvedVc<Box<dyn MyTrait>>`. So this function has a looser type constraint
411    /// to make these functions easier to write and use.
412    #[inline(always)]
413    pub fn upcast_non_strict<K>(vc: Self) -> Vc<K>
414    where
415        T: Upcast<K>,
416        K: VcValueTrait + ?Sized,
417    {
418        Vc {
419            node: vc.node,
420            _t: PhantomData,
421        }
422    }
423    /// Runs the operation, but ignores the returned Vc. Use that when only interested in running
424    /// the task for side effects.
425    pub async fn as_side_effect(self) -> Result<()> {
426        self.node.resolve().await?;
427        Ok(())
428    }
429
430    /// Do not use this: Use [`Vc::to_resolved`] instead. If you must have a resolved [`Vc`] type
431    /// and not a [`ResolvedVc`] type, simply deref the result of [`Vc::to_resolved`].
432    pub fn resolve(self) -> ResolveVcFuture<T> {
433        ResolveVcFuture {
434            inner: self.node.resolve(),
435            _t: PhantomData,
436        }
437    }
438
439    /// Resolve the reference until it points to a cell directly, and wrap the
440    /// result in a [`ResolvedVc`], which statically guarantees that the
441    /// [`Vc`] was resolved.
442    pub fn to_resolved(self) -> ToResolvedVcFuture<T> {
443        ToResolvedVcFuture {
444            inner: self.node.resolve(),
445            _t: PhantomData,
446        }
447    }
448
449    /// Hint that the cell content this `Vc` points to is no longer needed, so it may be dropped to
450    /// free memory. Future reads might need to recompute the value.
451    ///
452    /// This resolves `self` like [`Vc::to_resolved`] does (tracking the dependencies on task
453    /// outputs, and waiting for them if needed), but unlike [`Vc::final_read_hint`] it never reads
454    /// the cell content. If the content isn't present (e.g. it was already dropped, or it was never
455    /// computed because its dependents were restored from a persistent cache), this does nothing,
456    /// and in particular doesn't recompute it.
457    ///
458    /// This does not track any dependency on the cell.
459    pub async fn drop_content_hint(self) -> Result<()> {
460        let RawVcUnpacked::TaskCell(task, index) = self.node.resolve().await?.unpack() else {
461            unreachable!("resolve always returns a TaskCell");
462        };
463        crate::turbo_tasks().drop_task_cell_content_hint(task, index)
464    }
465
466    /// Returns `true` if the reference is resolved, meaning the underlying [`RawVc`] uses the
467    /// [`RawVcUnpacked::TaskCell`] representation.
468    ///
469    /// If you need resolved [`Vc`] value, it's typically better to use the [`ResolvedVc`] type to
470    /// enforce your requirements statically instead of dynamically at runtime.
471    ///
472    /// See also [`ResolvedVc::to_resolved`] and [`RawVc::is_resolved`].
473    pub fn is_resolved(self) -> bool {
474        self.node.is_resolved()
475    }
476
477    /// Returns `true` if the `Vc` was by a local function call (e.g. one who's arguments were not
478    /// fully resolved) and has not yet been resolved.
479    ///
480    /// Aside from differences in caching, a function's behavior should not be changed by using
481    /// local or non-local cells, so this function is mostly useful inside tests and internally in
482    /// turbo-tasks.
483    pub fn is_local(self) -> bool {
484        self.node.is_local_output()
485    }
486}
487
488impl<T> From<RawVc> for Vc<T>
489where
490    T: ?Sized,
491{
492    fn from(node: RawVc) -> Self {
493        Self {
494            node,
495            _t: PhantomData,
496        }
497    }
498}
499
500#[cfg(debug_assertions)]
501impl<T> ValueDebugFormat for Vc<T>
502where
503    T: UpcastStrict<Box<dyn ValueDebug>> + Send + Sync + ?Sized,
504{
505    fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> {
506        ValueDebugFormatString::Async(Box::pin(async move {
507            let vc_value_debug = Vc::upcast::<Box<dyn ValueDebug>>(*self);
508            let trait_ref = vc_value_debug.into_trait_ref().await?;
509            trait_ref.dbg_depth(depth).await
510        }))
511    }
512}
513
514macro_rules! into_future {
515    ($ty:ty, |$this:ident| $into_future:expr $(,)?) => {
516        impl<T> ::std::future::IntoFuture for $ty
517        where
518            T: $crate::VcValueType,
519        {
520            type Output = <$crate::ReadVcFuture<T> as ::std::future::Future>::Output;
521            type IntoFuture = $crate::ReadVcFuture<T>;
522            fn into_future(self) -> Self::IntoFuture {
523                let $this = self;
524                $into_future
525            }
526        }
527    };
528}
529pub(crate) use into_future;
530
531into_future!(Vc<T>, |this| this.node.into_read().into());
532into_future!(&Vc<T>, |this| this.node.into_read().into());
533into_future!(&mut Vc<T>, |this| this.node.into_read().into());
534
535impl<T> Vc<T>
536where
537    T: VcValueType,
538{
539    /// Do not use this: Use [`OperationVc::read_strongly_consistent`] instead.
540    #[cfg(feature = "non_operation_vc_strongly_consistent")]
541    pub fn strongly_consistent(self) -> ReadVcFuture<T> {
542        self.node.into_read().strongly_consistent().into()
543    }
544
545    /// Returns a untracked read of the value. This will not invalidate the current function when
546    /// the read value changed.
547    pub fn untracked(self) -> ReadVcFuture<T> {
548        self.node.into_read().untracked().into()
549    }
550
551    /// Read the value with the hint that this is the final read of the value. This might drop the
552    /// cell content. Future reads might need to recompute the value.
553    pub fn final_read_hint(self) -> ReadVcFuture<T> {
554        self.node.into_read().final_read_hint().into()
555    }
556}
557
558impl<T> Vc<T>
559where
560    T: VcValueType,
561    VcReadTarget<T>: Clone,
562{
563    /// Read the value and returns a owned version of it. It might clone the value.
564    pub fn owned(self) -> ReadOwnedVcFuture<T> {
565        let future: ReadVcFuture<T> = self.node.into_read().into();
566        future.owned()
567    }
568}
569
570impl<T> Vc<T>
571where
572    T: VcValueType,
573    VcReadTarget<T>: KeyedEq,
574{
575    /// Read the value and selects a keyed value from it. Only depends on the used key instead of
576    /// the full value.
577    pub fn get<'l, Q>(self, key: &'l Q) -> ReadKeyedVcFuture<'l, T, Q>
578    where
579        Q: Hash + ?Sized,
580        VcReadTarget<T>: KeyedAccess<Q>,
581    {
582        let future: ReadVcFuture<T> = self.node.into_read().into();
583        future.get(key)
584    }
585
586    /// Read the value and checks if it contains the given key. Only depends on the used key instead
587    /// of the full value.
588    pub fn contains_key<'l, Q>(self, key: &'l Q) -> ReadContainsKeyedVcFuture<'l, T, Q>
589    where
590        Q: Hash + ?Sized,
591        VcReadTarget<T>: KeyedAccess<Q>,
592    {
593        let future: ReadVcFuture<T> = self.node.into_read().into();
594        future.contains_key(key)
595    }
596
597    /// Read the value once for many synchronous keyed accesses via the returned
598    /// [`KeyedReadRef`] (`vc.keyed_reader().await?.get(key)`). This is more efficient than many
599    /// [`Vc::get`] / [`Vc::contains_key`] reads of the same cell within a single task.
600    ///
601    /// Once the [`KeyedReadRef`] is dropped, the task only depends on the accessed keys instead of
602    /// the full value. The returned future and the [`KeyedReadRef`] must be dropped within the
603    /// task execution that called this method, otherwise completing that execution panics. See
604    /// [`KeyedReadRef`] for details.
605    pub fn keyed_reader(self) -> ReadKeyedReaderVcFuture<T> {
606        let future: ReadVcFuture<T> = self.node.into_read().into();
607        future.read_keyed_reader()
608    }
609}
610
611impl<T> Vc<T>
612where
613    T: VcValueType,
614{
615    /// Read the value via the returned [`LazyReadRef`] (`vc.lazy_reader().await?.get()`), as a
616    /// read that is canceled when the value is never accessed.
617    ///
618    /// When the [`LazyReadRef`] is dropped without [`LazyReadRef::get`] ever being called, the
619    /// task no longer depends on the value through this read. The returned future and the
620    /// [`LazyReadRef`] must be dropped within the task execution that called this method,
621    /// otherwise completing that execution panics. See [`LazyReadRef`] for details.
622    pub fn lazy_reader(self) -> ReadLazyReaderVcFuture<T> {
623        let future: ReadVcFuture<T> = self.node.into_read().into();
624        future.read_lazy_reader()
625    }
626}
627
628impl<T> Unpin for Vc<T> where T: ?Sized {}
629
630impl<T> Vc<T>
631where
632    T: VcValueTrait + ?Sized,
633{
634    /// Converts this trait vc into a trait reference.
635    ///
636    /// The signature is similar to [`IntoFuture::into_future`], but we don't want trait vcs to
637    /// have the same future-like semantics as value vcs when it comes to producing refs. This
638    /// behavior is rarely needed, so in most cases, `.await`ing a trait vc is a mistake.
639    pub fn into_trait_ref(self) -> ReadVcFuture<T, VcValueTraitCast<T>> {
640        self.node.into_read().into()
641    }
642}
643
644impl<T> Default for Vc<T>
645where
646    T: ValueDefault,
647{
648    fn default() -> Self {
649        T::value_default()
650    }
651}
652
653pub trait OptionVcExt<T>
654where
655    T: VcValueType,
656{
657    fn to_resolved(self) -> impl Future<Output = Result<Option<ResolvedVc<T>>>> + Send;
658}
659
660impl<T> OptionVcExt<T> for Option<Vc<T>>
661where
662    T: VcValueType,
663{
664    async fn to_resolved(self) -> Result<Option<ResolvedVc<T>>> {
665        if let Some(vc) = self {
666            Ok(Some(vc.to_resolved().await?))
667        } else {
668            Ok(None)
669        }
670    }
671}