File size: 21,284 Bytes
1e92f2d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 | pub(crate) mod cast;
mod cell_mode;
pub(crate) mod default;
mod local;
pub(crate) mod operation;
mod read;
pub(crate) mod resolved;
mod traits;
use std::{
any::Any,
fmt::Debug,
future::{Future, IntoFuture},
hash::{Hash, Hasher},
marker::PhantomData,
ops::Deref,
};
use anyhow::Result;
use serde::{Deserialize, Serialize};
use shrink_to_fit::ShrinkToFit;
pub use self::{
cast::{VcCast, VcValueTraitCast, VcValueTypeCast},
cell_mode::{VcCellMode, VcCellNewMode, VcCellSharedMode},
default::ValueDefault,
local::NonLocalValue,
operation::{OperationValue, OperationVc},
read::{ReadOwnedVcFuture, ReadVcFuture, VcDefaultRead, VcRead, VcTransparentRead},
resolved::ResolvedVc,
traits::{Dynamic, Upcast, VcValueTrait, VcValueType},
};
use crate::{
CellId, RawVc, ResolveTypeError,
debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString},
registry,
trace::{TraceRawVcs, TraceRawVcsContext},
};
type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;
/// A "Value Cell" (`Vc` for short) is a reference to a memoized computation result stored on the
/// heap or in persistent cache, depending on the Turbo Engine backend implementation.
///
/// In order to get a reference to the pointed value, you need to `.await` the [`Vc<T>`] to get a
/// [`ReadRef<T>`][`ReadRef`]:
///
/// ```
/// let some_vc: Vc<T>;
/// let some_ref: ReadRef<T> = some_vc.await?;
/// some_ref.some_method_on_t();
/// ```
///
/// `Vc`s are similar to a [`Future`] or a Promise with a few key differences:
///
/// - The value pointed to by a `Vc` can be invalidated by changing dependencies or cache evicted,
/// meaning that `await`ing a `Vc` multiple times can give different results. A [`ReadRef`] is
/// snapshot of the underlying cell at a point in time.
///
/// - Reading (`await`ing) `Vc`s causes the current task to be tracked a dependent of the `Vc`'s
/// task or task cell. When the read task or task cell changes, the current task may be
/// re-executed.
///
/// - `Vc` types are always [`Copy`]. Most [`Future`]s are not. This works because `Vc`s are
/// represented as a few ids or indices into data structures managed by the `turbo-tasks`
/// framework. `Vc` types are not reference counted, but do support [tracing] for a hypothetical
/// (unimplemented) garbage collector.
///
/// - Unlike futures (but like promises), the work that a `Vc` represents [begins execution even if
/// the `Vc` is not `await`ed](#execution-model).
///
/// For a more in-depth explanation of the concepts behind value cells, [refer to the Turbopack
/// book][book-cells].
///
///
/// ## Subtypes
///
/// There are a couple of explicit "subtypes" of `Vc`. These can both be cheaply converted back into
/// a `Vc`.
///
/// - **[`ResolvedVc`]:** *(aka [`RawVc::TaskCell`])* A reference to a cell constructed within a
/// task, as part of a [`Vc::cell`] or `value_type.cell()` constructor. As the cell has been
/// constructed at least once, the concrete type of the cell is known (allowing
/// [downcasting][ResolvedVc::try_downcast]). This is stored as a combination of a task id, a type
/// id, and a cell id.
///
/// - **[`OperationVc`]:** *(aka [`RawVc::TaskOutput`])* The synchronous return value of a
/// [`turbo_tasks::function`]. Internally, this is stored using a task id. Exact type information
/// of trait types (i.e. `Vc<Box<dyn Trait>>`) is not known because the function may not have
/// finished execution yet. [`OperationVc`]s must first be [`connect`][OperationVc::connect]ed
/// before being read.
///
/// [`ResolvedVc`] is almost always preferred over the more awkward [`OperationVc`] API, but
/// [`OperationVc`] can be useful when dealing with [collectibles], when you need to [read the
/// result of a function with strong consistency][OperationVc::read_strongly_consistent], or with
/// [`State`].
///
/// These many representations are stored internally using a type-erased [`RawVc`]. Type erasure
/// reduces the [monomorphization] (and therefore binary size and compilation time) required to
/// support `Vc` and its subtypes.
///
/// | | Representation | Equality | Downcasting | Strong Consistency | Collectibles | [Non-Local] |
/// |-----------------|------------------------------------|-----------------|----------------------------|------------------------|-------------------|--------------|
/// | [`Vc`] | [One of many][RawVc] | β [Broken][eq] | β οΈ After resolution | β Eventual | β No | β [No][loc] |
/// | [`ResolvedVc`] | [Task Id + Type Id + Cell Id][rtc] | β
Yes\* | β
[Yes, cheaply][resolve] | β Eventual | β No | β
Yes |
/// | [`OperationVc`] | [Task Id][rto] | β
Yes\* | β οΈ After resolution | β
[Supported][strong] | β
[Yes][collect] | β
Yes |
///
/// *\* see the type's documentation for details*
///
/// [Non-Local]: NonLocalValue
/// [rtc]: RawVc::TaskCell
/// [rto]: RawVc::TaskOutput
/// [loc]: #optimization-local-outputs
/// [eq]: #equality--hashing
/// [resolve]: ResolvedVc::try_downcast
/// [strong]: OperationVc::read_strongly_consistent
/// [collect]: crate::CollectiblesSource
///
///
/// ## Execution Model
///
/// While task functions are expected to be side-effect free, their execution behavior is still
/// important for performance reasons, or to code using [collectibles] to represent issues or
/// side-effects.
///
/// Function calls are neither "eager", nor "lazy". Even if not awaited, they are guaranteed to
/// execute (potentially emitting collectibles) before the root task finishes or before the
/// completion of any strongly consistent read containing their call. However, the exact point when
/// that execution begins is an implementation detail. Functions may execute more than once due to
/// dirty task invalidation.
///
///
/// ## Equality & Hashing
///
/// Because `Vc`s can be equivalent but have different representation, it's not recommended to
/// compare `Vc`s by equality. Instead, you should convert a `Vc` to an explicit subtype first
/// (likely [`ResolvedVc`]). Future versions of `Vc` may not implement [`Eq`], [`PartialEq`], or
/// [`Hash`].
///
///
/// ## Optimization: Local Outputs
///
/// In addition to the potentially-explicit "resolved" and "operation" representations of a `Vc`,
/// there's another internal representation of a `Vc`, known as a "Local `Vc`", or
/// [`RawVc::LocalOutput`].
///
/// This is a special case of the synchronous return value of a [`turbo_tasks::function`] when some
/// of its arguments have not yet been resolved. These are stored in task-local state that is freed
/// after their parent non-local task exits.
///
/// We prevent potentially-local `Vc`s from escaping the lifetime of a function using the
/// [`NonLocalValue`] marker trait alongside some fallback runtime checks. We do this to avoid some
/// ergonomic challenges that would come from using lifetime annotations with `Vc`.
///
///
/// [tracing]: crate::trace::TraceRawVcs
/// [`ReadRef`]: crate::ReadRef
/// [`turbo_tasks::function`]: crate::function
/// [monomorphization]: https://doc.rust-lang.org/book/ch10-01-syntax.html#performance-of-code-using-generics
/// [`State`]: crate::State
/// [book-cells]: https://turbopack-rust-docs.vercel.sh/turbo-engine/cells.html
/// [collectibles]: crate::CollectiblesSource
#[must_use]
#[derive(Serialize, Deserialize)]
#[serde(transparent, bound = "")]
#[repr(transparent)]
pub struct Vc<T>
where
T: ?Sized,
{
pub(crate) node: RawVc,
#[doc(hidden)]
pub(crate) _t: PhantomData<T>,
}
/// This only exists to satisfy the Rust type system. However, this struct can
/// never actually be instantiated, as dereferencing a `Vc<T>` will result in a
/// linker error. See the implementation of `Deref` for `Vc<T>`.
pub struct VcDeref<T>
where
T: ?Sized,
{
_t: PhantomData<T>,
}
macro_rules! do_not_use_or_you_will_be_fired {
($($name:ident)*) => {
impl<T> VcDeref<T>
where
T: ?Sized,
{
$(
#[doc(hidden)]
#[allow(unused)]
#[allow(clippy::wrong_self_convention)]
#[deprecated = "This is not the method you are looking for."]
pub fn $name(self) {}
)*
}
};
}
// Hide raw pointer methods on `Vc<T>`. This is an artifact of having
// implement `Deref<Target = *const T>` on `Vc<T>` for `arbitrary_self_types` to
// do its thing. This can be removed once the `Receiver` trait no longer depends
// on `Deref`.
do_not_use_or_you_will_be_fired!(
add
addr
align_offset
as_mut
as_mut_ptr
as_ptr
as_ref
as_uninit_mut
as_uninit_ref
as_uninit_slice
as_uninit_slice_mut
byte_add
byte_offset
byte_offset_from
byte_sub
cast
cast_const
cast_mut
copy_from
copy_from_nonoverlapping
copy_to
copy_to_nonoverlapping
drop_in_place
expose_addr
from_bits
get_unchecked
get_unchecked_mut
guaranteed_eq
guaranteed_ne
is_aligned
is_aligned_to
is_empty
is_null
len
map_addr
mask
offset
offset_from
read
read_unaligned
read_volatile
replace
split_at_mut
split_at_mut_unchecked
sub
sub_ptr
swap
to_bits
to_raw_parts
with_addr
with_metadata_of
wrapping_add
wrapping_byte_add
wrapping_byte_offset
wrapping_byte_sub
wrapping_offset
wrapping_sub
write
write_bytes
write_unaligned
write_volatile
);
// Call this macro for all the applicable methods above:
#[doc(hidden)]
impl<T> Deref for VcDeref<T>
where
T: ?Sized,
{
// `*const T` or `*mut T` would be enough here, but from an abundance of
// caution, we use `*const *mut *const T` to make sure there will never be an
// applicable method.
type Target = *const *mut *const T;
fn deref(&self) -> &Self::Target {
unsafe extern "C" {
#[link_name = "\n\nERROR: you tried to dereference a `Vc<T>`\n"]
fn trigger() -> !;
}
unsafe { trigger() };
}
}
// This is the magic that makes `Vc<T>` accept `self: Vc<Self>` methods through
// `arbitrary_self_types`, while not allowing any other receiver type:
// * `Vc<T>` dereferences to `*const *mut *const T`, which means that it is valid under the
// `arbitrary_self_types` rules.
// * `*const *mut *const T` is not a valid receiver for any attribute access on `T`, which means
// that the only applicable items will be the methods declared on `self: Vc<Self>`.
//
// If we had used `type Target = T` instead, `vc_t.some_attr_defined_on_t` would
// have been accepted by the compiler.
#[doc(hidden)]
impl<T> Deref for Vc<T>
where
T: ?Sized,
{
type Target = VcDeref<T>;
fn deref(&self) -> &Self::Target {
unsafe extern "C" {
#[link_name = "\n\nERROR: you tried to dereference a `Vc<T>`\n"]
fn trigger() -> !;
}
unsafe { trigger() };
}
}
impl<T> Copy for Vc<T> where T: ?Sized {}
impl<T> Clone for Vc<T>
where
T: ?Sized,
{
fn clone(&self) -> Self {
*self
}
}
impl<T> Hash for Vc<T>
where
T: ?Sized,
{
fn hash<H: Hasher>(&self, state: &mut H) {
self.node.hash(state);
}
}
impl<T> PartialEq<Vc<T>> for Vc<T>
where
T: ?Sized,
{
fn eq(&self, other: &Self) -> bool {
self.node == other.node
}
}
impl<T> Eq for Vc<T> where T: ?Sized {}
/// Generates an opaque debug representation of the [`Vc`] itself, but not the data inside of it.
///
/// This is implemented to allow types containing [`Vc`] 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<T> Debug for Vc<T>
where
T: ?Sized,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Vc").field("node", &self.node).finish()
}
}
impl<T> Vc<T>
where
T: VcValueType,
{
// called by the `.cell()` method generated by the `#[turbo_tasks::value]` macro
#[doc(hidden)]
pub fn cell_private(mut inner: <T::Read as VcRead<T>>::Target) -> Self {
// cell contents are immutable, so go ahead and shrink the cell's contents
ShrinkToFit::shrink_to_fit(<T::Read as VcRead<T>>::target_to_value_mut_ref(&mut inner));
<T::CellMode as VcCellMode<T>>::cell(inner)
}
}
impl<T, Inner, Repr> Vc<T>
where
T: VcValueType<Read = VcTransparentRead<T, Inner, Repr>>,
Inner: Any + Send + Sync,
Repr: VcValueType,
{
pub fn cell(inner: Inner) -> Self {
Self::cell_private(inner)
}
}
impl<T> Vc<T>
where
T: ?Sized,
{
/// Returns a debug identifier for this `Vc`.
pub async fn debug_identifier(vc: Self) -> Result<String> {
let resolved = vc.resolve().await?;
let raw_vc: RawVc = resolved.node;
if let RawVc::TaskCell(task_id, CellId { type_id, index }) = raw_vc {
let value_ty = registry::get_value_type(type_id);
Ok(format!("{}#{}: {}", value_ty.name, index, task_id))
} else {
unreachable!()
}
}
/// Returns the `RawVc` corresponding to this `Vc`.
pub fn into_raw(vc: Self) -> RawVc {
vc.node
}
/// Upcasts the given `Vc<T>` to a `Vc<Box<dyn K>>`.
///
/// This is also available as an `Into`/`From` conversion.
#[inline(always)]
pub fn upcast<K>(vc: Self) -> Vc<K>
where
T: Upcast<K>,
K: VcValueTrait + ?Sized,
{
Vc {
node: vc.node,
_t: PhantomData,
}
}
/// Runs the operation, but ignores the returned Vc. Use that when only interested in running
/// the task for side effects.
pub async fn as_side_effect(self) -> Result<()> {
self.node.resolve().await?;
Ok(())
}
/// Do not use this: Use [`Vc::to_resolved`] instead. If you must have a resolved [`Vc`] type
/// and not a [`ResolvedVc`] type, simply deref the result of [`Vc::to_resolved`].
pub async fn resolve(self) -> Result<Vc<T>> {
Ok(Self {
node: self.node.resolve().await?,
_t: PhantomData,
})
}
/// Resolve the reference until it points to a cell directly, and wrap the
/// result in a [`ResolvedVc`], which statically guarantees that the
/// [`Vc`] was resolved.
pub async fn to_resolved(self) -> Result<ResolvedVc<T>> {
Ok(ResolvedVc {
node: self.resolve().await?,
})
}
/// Returns `true` if the reference is resolved, meaning the underlying [`RawVc`] uses the
/// [`RawVc::TaskCell`] representation.
///
/// If you need resolved [`Vc`] value, it's typically better to use the [`ResolvedVc`] type to
/// enforce your requirements statically instead of dynamically at runtime.
///
/// See also [`ResolvedVc::to_resolved`] and [`RawVc::is_resolved`].
pub fn is_resolved(self) -> bool {
self.node.is_resolved()
}
/// Returns `true` if the `Vc` was by a local function call (e.g. one who's arguments were not
/// fully resolved) and has not yet been resolved.
///
/// Aside from differences in caching, a function's behavior should not be changed by using
/// local or non-local cells, so this function is mostly useful inside tests and internally in
/// turbo-tasks.
pub fn is_local(self) -> bool {
self.node.is_local()
}
/// Do not use this: Use [`OperationVc::resolve_strongly_consistent`] instead.
#[cfg(feature = "non_operation_vc_strongly_consistent")]
pub async fn resolve_strongly_consistent(self) -> Result<Self> {
Ok(Self {
node: self.node.resolve_strongly_consistent().await?,
_t: PhantomData,
})
}
}
impl<T> Vc<T>
where
T: VcValueTrait + ?Sized,
{
/// Attempts to sidecast the given `Vc<Box<dyn T>>` to a `Vc<Box<dyn K>>`.
/// This operation also resolves the `Vc`.
///
/// Returns `None` if the underlying value type does not implement `K`.
///
/// **Note:** if the trait T is required to implement K, use
/// `Vc::upcast(vc).resolve()` instead. This provides stronger guarantees,
/// removing the need for a `Result` return type.
pub async fn try_resolve_sidecast<K>(vc: Self) -> Result<Option<Vc<K>>, ResolveTypeError>
where
K: VcValueTrait + ?Sized,
{
let raw_vc: RawVc = vc.node;
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`
/// is of the form `Box<dyn L>`, and `L` is a value trait.
/// This operation also resolves the `Vc`.
///
/// 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>
where
K: Upcast<T> + VcValueTrait + ?Sized,
{
let raw_vc: RawVc = vc.node;
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`
/// is a value type.
/// This operation also resolves the `Vc`.
///
/// 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>
where
K: Upcast<T> + VcValueType,
{
let raw_vc: RawVc = vc.node;
let raw_vc = raw_vc
.resolve_value(<K as VcValueType>::get_value_type_id())
.await?;
Ok(raw_vc.map(|raw_vc| Vc {
node: raw_vc,
_t: PhantomData,
}))
}
}
impl<T> From<RawVc> for Vc<T>
where
T: ?Sized,
{
fn from(node: RawVc) -> Self {
Self {
node,
_t: PhantomData,
}
}
}
impl<T> TraceRawVcs for Vc<T>
where
T: ?Sized,
{
fn trace_raw_vcs(&self, trace_context: &mut TraceRawVcsContext) {
TraceRawVcs::trace_raw_vcs(&self.node, trace_context);
}
}
impl<T> ValueDebugFormat for Vc<T>
where
T: Upcast<Box<dyn ValueDebug>> + Send + Sync + ?Sized,
{
fn value_debug_format(&self, depth: usize) -> ValueDebugFormatString<'_> {
ValueDebugFormatString::Async(Box::pin(async move {
Ok({
let vc_value_debug = Vc::upcast::<Box<dyn ValueDebug>>(*self);
vc_value_debug.dbg_depth(depth).await?.to_string()
})
}))
}
}
macro_rules! into_future {
($ty:ty) => {
impl<T> IntoFuture for $ty
where
T: VcValueType,
{
type Output = <ReadVcFuture<T> as Future>::Output;
type IntoFuture = ReadVcFuture<T>;
fn into_future(self) -> Self::IntoFuture {
self.node.into_read().into()
}
}
};
}
into_future!(Vc<T>);
into_future!(&Vc<T>);
into_future!(&mut Vc<T>);
impl<T> Vc<T>
where
T: VcValueType,
{
/// Do not use this: Use [`OperationVc::read_strongly_consistent`] instead.
#[cfg(feature = "non_operation_vc_strongly_consistent")]
#[must_use]
pub fn strongly_consistent(self) -> ReadVcFuture<T> {
self.node.into_read().strongly_consistent().into()
}
/// Returns a untracked read of the value. This will not invalidate the current function when
/// the read value changed.
#[must_use]
pub fn untracked(self) -> ReadVcFuture<T> {
self.node.into_read().untracked().into()
}
/// Read the value with the hint that this is the final read of the value. This might drop the
/// cell content. Future reads might need to recompute the value.
#[must_use]
pub fn final_read_hint(self) -> ReadVcFuture<T> {
self.node.into_read().final_read_hint().into()
}
}
impl<T> Vc<T>
where
T: VcValueType,
VcReadTarget<T>: Clone,
{
/// Read the value and returns a owned version of it. It might clone the value.
pub fn owned(self) -> ReadOwnedVcFuture<T> {
let future: ReadVcFuture<T> = self.node.into_read().into();
future.owned()
}
}
impl<T> Unpin for Vc<T> where T: ?Sized {}
impl<T> Default for Vc<T>
where
T: ValueDefault,
{
fn default() -> Self {
T::value_default()
}
}
pub trait OptionVcExt<T>
where
T: VcValueType,
{
fn to_resolved(self) -> impl Future<Output = Result<Option<ResolvedVc<T>>>> + Send;
}
impl<T> OptionVcExt<T> for Option<Vc<T>>
where
T: VcValueType,
{
async fn to_resolved(self) -> Result<Option<ResolvedVc<T>>> {
if let Some(vc) = self {
Ok(Some(vc.to_resolved().await?))
} else {
Ok(None)
}
}
}
|