Unverified Commit 61c7b7b7 authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

docs(turbo-tasks): Lots of minor fixes, tweaks, and updates to the docs (#78329)

After this PR `cargo doc -p turbo-tasks` builds cleanly (though the rest of turbopack almost certainly doesn't).

Rendered docs for `Vc`:

![Screenshot 2025-04-18 at 17-30-11 Vc in turbo_tasks - Rust.png](https://graphite-user-uploaded-assets-prod.s3.amazonaws.com/HAZVitxRNnZz8QMiPn4a/187685ba-e9b5-4f27-848d-8c1f14e3f2a3.png)
parent d5359765
......@@ -22,13 +22,16 @@ mod tagged_value;
/// An immutable reference counted [`String`], similar to [`Arc<String>`][std::sync::Arc].
///
/// This is the preferred immutable string type for [`turbo_task::function`][macro@crate::function]
/// arguments and inside of [`turbo_task::value`][macro@crate::value].
/// This is the preferred immutable string type for [`turbo_tasks::function`][func] arguments and
/// inside of [`turbo_tasks::value`][value].
///
/// As turbo-tasks must store copies of function arguments to enable caching, non-reference counted
/// [`String`]s would incur frequent cloning. Reference counting typically decreases memory
/// consumption and CPU time in these cases.
///
/// [func]: https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.function.html
/// [value]: https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.value.html
///
/// ## Conversion
///
/// Converting a `String` or `&str` to an `RcStr` can be perfomed using `.into()` or
......
......@@ -24,24 +24,24 @@ macro_rules! impl_write_number {
)*}
}
/// DeterministicHash is a custom trait that signals the implementor can safely
/// be hashed in a replicatable way across platforms and process runs.
/// Signals the implementor can safely be hashed in a replicatable way across platforms and process
/// runs.
///
/// Note that the default Hash trait used by Rust is not deterministic for our purposes.
/// Note that the default [`std::hash::Hash`] trait used by Rust allows for hashing that differs
/// across process runs, so it is not suitable for persistent caching with turbo-tasks.
///
/// It's very important that Vcs never implement this, since they cannot be
/// deterministic. The value that they wrap, however, can implement the trait.
/// It's very important that `Vc`s never implement this, since they cannot be deterministic. The
/// value that they wrap, however, can implement the trait.
pub trait DeterministicHash {
/// Adds self's bytes to the [Hasher] state, in a way that is replicatable
/// on any platform or process run.
/// Adds `self`'s bytes to the [`DeterministicHasher`]'s state, in a way that is replicatable on
/// any platform or process run.
fn deterministic_hash<H: DeterministicHasher>(&self, state: &mut H);
}
/// A custom trait that signals the implementor can safely hash in a replicatable way across
/// platforms and process runs.
/// Signals the implementor can safely hash in a replicatable way across platforms and process runs.
///
/// Note that the default Hasher trait used by Rust allows for non-deterministic
/// hashing, so it is not suitable for our purposes.
/// Note that the default [`std::hash::Hash`] trait used by Rust allows for hashing that differs
/// across process runs, so it is not suitable for persistent caching with turbo-tasks.
pub trait DeterministicHasher {
fn finish(&self) -> u64;
fn write_bytes(&mut self, bytes: &[u8]);
......
......@@ -10,11 +10,11 @@ use syn::{
///
/// Requires several Fn helpers which perform expand different structures:
///
/// - [expand_named] handles the expansion of a struct or enum variant with named fields (e.g.
/// - `expand_named` handles the expansion of a struct or enum variant with named fields (e.g.
/// `struct Foo { bar: u32 }`, `Foo::Bar { baz: u32 }`).
/// - [expand_unnamed] handles the expansion of a struct or enum variant with unnamed fields (e.g.
/// - `expand_unnamed` handles the expansion of a struct or enum variant with unnamed fields (e.g.
/// `struct Foo(u32)`, `Foo::Bar(u32)`).
/// - [expand_unit] handles the expansion of a unit struct or enum (e.g. `struct Foo;`, `Foo::Bar`).
/// - `expand_unit` handles the expansion of a unit struct or enum (e.g. `struct Foo;`, `Foo::Bar`).
///
/// These helpers should themselves call [generate_destructuring] to generate
/// the destructure necessary to access the fields of the value.
......
......@@ -53,17 +53,19 @@ pub fn derive_task_input(input: TokenStream) -> TokenStream {
derive::derive_task_input(input)
}
/// Derives the `turbo_tasks::KeyValuePair` trait for a enum. Each variant need to have a `value`
/// field which becomes part of the value enum and all remaining fields become part of the key.
///
/// Assuming the enum is called `Abc` it exposes `AbcKey` and `AbcValue` types for it too. The key
/// enum will have `Debug, Clone, PartialEq, Eq, Hash` derived and the value enum will have `Debug,
/// Clone` derived. It's expected that all fields implement these traits.
/// <!--
/// Documentation for this macro is available on the re-export:
/// <https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/derive.KeyValuePair.html>
/// -->
#[proc_macro_derive(KeyValuePair)]
pub fn derive_key_value_pair(input: TokenStream) -> TokenStream {
derive::derive_key_value_pair(input)
}
/// <!--
/// Documentation for this macro is available on the re-export:
/// <https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.value.html>
/// -->
#[allow_internal_unstable(min_specialization, into_future, trivial_bounds)]
#[proc_macro_error]
#[proc_macro_attribute]
......@@ -71,24 +73,10 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
value_macro::value(args, input)
}
/// Allows this trait to be used as part of a trait object inside of a value
/// cell, in the form of `Vc<dyn MyTrait>`.
///
/// ## Arguments
///
/// Example: `#[turbo_tasks::value_trait(no_debug, resolved)]`
///
/// ### 'no_debug`
///
/// Disables the automatic implementation of [`turbo_tasks::debug::ValueDebug`].
///
/// Example: `#[turbo_tasks::value_trait(no_debug)]`
///
/// ### 'resolved`
///
/// Adds [`turbo_tasks::NonLocalValue`] as a supertrait of this trait.
///
/// Example: `#[turbo_tasks::value_trait(resolved)]`
/// <!--
/// Documentation for this macro is available on the re-export:
/// <https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/attr.value_trait.html>
/// -->
#[allow_internal_unstable(min_specialization, into_future, trivial_bounds)]
#[proc_macro_error]
#[proc_macro_attribute]
......
......@@ -69,7 +69,7 @@ pub struct CachedTaskType {
impl CachedTaskType {
/// Get the name of the function from the registry. Equivalent to the
/// [`fmt::Display::to_string`] implementation, but does not allocate a `String`.
/// [`Display`]/[`ToString::to_string`] implementation, but does not allocate a [`String`].
pub fn get_name(&self) -> &'static str {
&registry::get_function(self.fn_type).name
}
......@@ -94,7 +94,7 @@ impl Hash for CachedTaskType {
}
}
impl fmt::Display for CachedTaskType {
impl Display for CachedTaskType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.get_name())
}
......@@ -578,8 +578,8 @@ pub trait Backend: Sync + Send {
turbo_tasks: &dyn TurboTasksBackendApi<Self>,
) -> TaskId;
/// For persistent tasks with associated [`NativeFunction`][turbo_tasks::NativeFunction]s,
/// return the [`FunctionId`].
/// For persistent tasks with associated
/// [`NativeFunction`][crate::native_function::NativeFunction]s, return the [`FunctionId`].
fn try_get_function_id(&self, task_id: TaskId) -> Option<FunctionId>;
fn connect_task(
......
use anyhow::Result;
use crate::{self as turbo_tasks, RawVc, ResolvedVc, TryJoinIterExt, Vc};
/// Just an empty type, but it's never equal to itself.
///
/// [`Vc<Completion>`] can be used as return value instead of `()`
/// to have a concrete reference that can be awaited.
/// It will invalidate the awaiting task everytime the referenced
/// task has been executed.
/// [`Vc<Completion>`] can be used as return value instead of `()` to have a concrete reference that
/// can be awaited. It will invalidate the awaiting task everytime the referenced task has been
/// executed.
///
/// Note: [`PartialEq`] is not implemented since it doesn't make sense to
/// compare `Completion` this way. You probably want to use [`ReadRef::ptr_eq`]
/// instead.
/// Note: [`PartialEq`] is not implemented since it doesn't make sense to compare `Completion` this
/// way. You probably want to use [`ReadRef::ptr_eq`][crate::ReadRef::ptr_eq] instead.
#[turbo_tasks::value(cell = "new", eq = "manual")]
#[derive(Debug)]
pub struct Completion;
......
......@@ -19,3 +19,13 @@ pub trait KeyValuePair {
fn from_key_and_value_ref(key: Self::Key, value_ref: Self::ValueRef<'_>) -> Self;
fn into_key_and_value(self) -> (Self::Key, Self::Value);
}
/// Derives the [`KeyValuePair`][trait@KeyValuePair] trait for a enum. Each variant need to
/// have a `value` field which becomes part of the value enum and all remaining fields become
/// part of the key.
///
/// Assuming the enum is called `Abc` it exposes `AbcKey` and `AbcValue` types for it too. The
/// key enum will have [`Debug`], [`Clone`], [`PartialEq`], [`Eq`], and [`Hash`] derived. The
/// value enum will have [`Debug`] and [`Clone`] derived. It's expected that all fields
/// implement these traits.
pub use turbo_tasks_macros::KeyValuePair;
......@@ -118,7 +118,7 @@ pub use shrink_to_fit::ShrinkToFit;
pub use state::{State, TransientState};
pub use task::{task_input::TaskInput, SharedReference, TypedSharedReference};
pub use trait_ref::{IntoTraitRef, TraitRef};
pub use turbo_tasks_macros::{function, value_impl, value_trait, KeyValuePair, TaskInput};
pub use turbo_tasks_macros::{function, value_impl, TaskInput};
pub use value::{TransientInstance, TransientValue, Value};
pub use value_type::{TraitMethod, TraitType, ValueType};
pub use vc::{
......@@ -275,6 +275,27 @@ macro_rules! fxindexset {
#[rustfmt::skip]
pub use turbo_tasks_macros::value;
/// Allows this trait to be used as part of a trait object inside of a value
/// cell, in the form of `Vc<dyn MyTrait>`.
///
/// ## Arguments
///
/// Example: `#[turbo_tasks::value_trait(no_debug, resolved)]`
///
/// ### 'no_debug`
///
/// Disables the automatic implementation of [`ValueDebug`][crate::debug::ValueDebug].
///
/// Example: `#[turbo_tasks::value_trait(no_debug)]`
///
/// ### 'resolved`
///
/// Adds [`NonLocalValue`] as a supertrait of this trait.
///
/// Example: `#[turbo_tasks::value_trait(resolved)]`
#[rustfmt::skip]
pub use turbo_tasks_macros::value_trait;
pub type TaskIdSet = AutoSet<TaskId, BuildHasherDefault<FxHasher>, 2>;
pub mod test_helpers {
......
......@@ -880,8 +880,8 @@ impl<B: Backend + 'static> TurboTasks<B> {
/// Waits for the given task to finish executing. This works by performing an untracked read,
/// and discarding the value of the task output.
///
/// [`ReadConsistency::Weak`] means that this will return after the task executes, but before
/// all dependencies have completely settled.
/// [`ReadConsistency::Eventual`] means that this will return after the task executes, but
/// before all dependencies have completely settled.
///
/// [`ReadConsistency::Strong`] means that this will also wait for the task and all dependencies
/// to fully settle before returning.
......@@ -1826,14 +1826,12 @@ impl CurrentCellRef {
}
}
/// Replace the current cell's content with `new_value` if the current
/// content is not equal by value with the existing content.
/// Replace the current cell's content with `new_value` if the current content is not equal by
/// value with the existing content.
///
/// The comparison happens using the value itself, not the
/// [`VcRead::Target`] of that value.
/// The comparison happens using the value itself, not the [`VcRead::Target`] of that value.
///
/// Take this example of a custom equality implementation on a transparent
/// wrapper type:
/// Take this example of a custom equality implementation on a transparent wrapper type:
///
/// ```
/// #[turbo_tasks::value(transparent, eq = "manual")]
......@@ -1852,17 +1850,15 @@ impl CurrentCellRef {
/// impl Eq for Wrapper {}
/// ```
///
/// Comparisons of `Vc<Wrapper>` used when updating the cell will use
/// `Wrapper`'s custom equality implementation, rather than the one
/// provided by the target (`Vec<u32>`) type.
/// Comparisons of [`Vc<Wrapper>`] used when updating the cell will use `Wrapper`'s custom
/// equality implementation, rather than the one provided by the target ([`Vec<u32>`]) type.
///
/// However, in most cases, the default derived implementation of
/// `PartialEq` is used which just forwards to the inner value's
/// `PartialEq`.
/// However, in most cases, the default derived implementation of [`PartialEq`] is used which
/// just forwards to the inner value's [`PartialEq`].
///
/// If you already have a `SharedReference`, consider calling
/// [`compare_and_update_with_shared_reference`] which can re-use the
/// `SharedReference` object.
/// [`Self::compare_and_update_with_shared_reference`] which can re-use the [`SharedReference`]
/// object.
pub fn compare_and_update<T>(&self, new_value: T)
where
T: PartialEq + VcValueType,
......
......@@ -61,7 +61,7 @@ pub enum RawVc {
}
impl RawVc {
pub(crate) fn is_resolved(&self) -> bool {
pub fn is_resolved(&self) -> bool {
match self {
RawVc::TaskOutput(_) => false,
RawVc::TaskCell(_, _) => true,
......@@ -69,7 +69,7 @@ impl RawVc {
}
}
pub(crate) fn is_local(&self) -> bool {
pub fn is_local(&self) -> bool {
match self {
RawVc::TaskOutput(_) => false,
RawVc::TaskCell(_, _) => false,
......
......@@ -96,6 +96,10 @@ impl<T> Drop for StateRef<'_, T> {
}
}
/// **This API violates core assumption of turbo-tasks, is believed to be unsound, and there's no
/// plan fix it.** You should prefer to use [collectibles][crate::CollectiblesSource] instead of
/// state where at all possible. This API may be removed in the future.
///
/// An [internally-mutable] type, similar to [`RefCell`][std::cell::RefCell] or [`Mutex`] that can
/// be stored inside a [`VcValueType`].
///
......@@ -112,7 +116,7 @@ impl<T> Drop for StateRef<'_, T> {
///
/// [internally-mutable]: https://doc.rust-lang.org/book/ch15-05-interior-mutability.html
/// [`VcValueType`]: crate::VcValueType
/// [strong consistency]: crate::Vc::strongly_consistent
/// [strong consistency]: crate::OperationVc::read_strongly_consistent
/// [`OperationVc`]: crate::OperationVc
/// [`OperationValue`]: crate::OperationValue
#[derive(Serialize, Deserialize)]
......
......@@ -12,8 +12,6 @@ use crate::{
/// Trait to implement in order for a type to be accepted as a
/// [`#[turbo_tasks::function]`][crate::function] argument.
///
/// See also [`ConcreteTaskInput`].
pub trait TaskInput: Send + Sync + Clone + Debug + PartialEq + Eq + Hash + TraceRawVcs {
fn resolve_input(&self) -> impl Future<Output = Result<Self>> + Send + '_ {
async { Ok(self.clone()) }
......
......@@ -75,61 +75,46 @@ type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;
///
/// ## Subtypes
///
/// There are a couple of "subtypes" of `Vc`. These can both be cheaply converted back into a `Vc`.
/// There are a couple of explicit "subtypes" of `Vc`. These can both be cheaply converted back into
/// a `Vc`.
///
/// - **[`ResolvedVc`]:** 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.
/// - **[`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`]:** 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. Operations
/// must first be [`connected`][OperationVc::connect]ed before being read.
/// - **[`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 inside of [`State`] or when dealing with [collectibles].
///
/// In addition to these potentially-explicit representations of a `Vc`, there's another internal
/// representation of a `Vc`, known as a "Local `Vc`".
///
/// - **Local Operation or Cell:** Same as [`ResolvedVc`] or [`OperationVc`], but these values are
/// stored in task-local state that is freed after their parent non-local task exits. These values
/// are sometimes created when calling a [`turbo_tasks::function`] as an optimization. [Converting
/// a local `Vc` to a `ResolvedVc`][Vc::to_resolved] will construct a new
/// [non-local][NonLocalValue] cell.
/// [`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.
///
/// <div class="warning">
/// <p>
/// Local <code>Vc</code>s are not valid outside of their parent task, so they must be implicitly
/// (e.g. as an argument or return type) or explicitly (e.g. via <a
/// href="#method.to_resolved"><code>Vc::to_resolved</code></a>) be converted to a non-local <a
/// href="struct.ResolvedVc.html"><code>ResolvedVc</code></a> or <a
/// href="struct.VcOperation.html"><code>VcOperation</code></a> before crossing task boundaries.
/// </p>
/// <p>
/// For this reason, <code>Vc</code> types (which are potentially local) will be disallowed as
/// fields in <a href="attr.value.html"><code>turbo_tasks::value</code></a>s in the future.
/// </p>
/// </div>
///
/// | | Representation? | [Non-Local?] | Equality? | Can be Downcast? |
/// |-----------------|-----------------------------|--------------|-------------------------|----------------------------|
/// | [`Vc`] | One of many | ⚠️ Maybe | ❌ Not recommended | ⚠️ After resolution |
/// | [`ResolvedVc`] | Task Id + Type Id + Cell Id | ✅ Yes | ✅ Yes, [see docs][rvc] | ✅ [Yes, cheaply][resolve] |
/// | [`OperationVc`] | Task Id | ✅ Yes | ✅ Yes, [see docs][ovc] | ⚠️ After resolution |
/// | | 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
/// [rvc]: ResolvedVc
/// [ovc]: ResolvedVc
/// [rtc]: RawVc::TaskCell
/// [rto]: RawVc::TaskOutput
/// [loc]: #optimization-local-outputs
/// [eq]: #equality--hashing
/// [resolve]: ResolvedVc::try_downcast
///
/// See the documentation for [`ResolvedVc`] and [`OperationVc`] for more details about these
/// subtypes.
/// [strong]: OperationVc::read_strongly_consistent
/// [collect]: crate::CollectiblesSource
///
///
/// ## Execution Model
......@@ -153,13 +138,28 @@ type VcReadTarget<T> = <<T as VcValueType>::Read as VcRead<T>>::Target;
/// [`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]: CollectiblesSource
/// [collectibles]: crate::CollectiblesSource
#[must_use]
#[derive(Serialize, Deserialize)]
#[serde(transparent, bound = "")]
......@@ -421,15 +421,8 @@ where
}
}
/// Resolve the reference until it points to a cell directly.
///
/// Resolving will wait for task execution to be finished, so that the
/// returned `Vc` points to a cell that stores a value.
///
/// Resolving is necessary to compare identities of `Vc`s.
///
/// This is async and will rethrow any fatal error that happened during task
/// execution.
/// 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?,
......@@ -446,9 +439,13 @@ where
})
}
/// Returns `true` if the reference is resolved.
/// 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 [`Vc::resolve`].
/// See also [`ResolvedVc::to_resolved`] and [`RawVc::is_resolved`].
pub fn is_resolved(self) -> bool {
self.node.is_resolved()
}
......
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