turbo_tasks/lib.rs
1#![doc = include_str!("../README.md")]
2#![feature(trivial_bounds)]
3#![feature(min_specialization)]
4#![deny(unsafe_op_in_unsafe_fn)]
5#![feature(error_generic_member_access)]
6#![feature(arbitrary_self_types)]
7#![feature(arbitrary_self_types_pointers)]
8#![feature(ptr_metadata)]
9#![feature(sync_unsafe_cell)]
10#![feature(async_fn_traits)]
11#![feature(impl_trait_in_assoc_type)]
12#![feature(const_type_name)]
13
14pub mod backend;
15mod capture_future;
16mod collectibles;
17mod completion;
18pub mod debug;
19#[doc = include_str!("../FORMATTING.md")]
20pub mod display;
21pub mod duration_span;
22mod dyn_task_inputs;
23mod effect;
24mod error;
25pub mod event;
26pub mod graph;
27mod id;
28mod id_factory;
29mod invalidation;
30mod join_iter_ext;
31pub mod keyed;
32mod local_task_tracker;
33#[doc(hidden)]
34pub mod macro_helpers;
35mod manager;
36pub mod mapped_read_ref;
37mod marker_trait;
38pub mod message_queue;
39mod native_function;
40mod once_map;
41mod output;
42pub mod panic_hooks;
43pub mod parallel;
44pub mod primitives;
45mod priority_runner;
46mod read_options;
47mod read_ref;
48pub mod registry;
49pub mod scope;
50mod serialization_invalidation;
51pub mod small_duration;
52mod spawn;
53mod state;
54pub mod task;
55#[cfg(feature = "task_dirty_cause")]
56mod task_dirty_cause;
57mod task_execution_reason;
58pub mod task_statistics;
59pub mod trace;
60mod trait_ref;
61mod triomphe_utils;
62pub mod util;
63mod value;
64mod value_type;
65mod vc;
66
67use std::hash::BuildHasherDefault;
68
69pub use anyhow::{Error, Result};
70use auto_hash_map::AutoSet;
71use rustc_hash::FxHasher;
72pub use shrink_to_fit::ShrinkToFit;
73pub use turbo_tasks_macros::{DeterministicHash, turbobail, turbofmt};
74
75#[cfg(feature = "task_dirty_cause")]
76pub use crate::task_dirty_cause::TaskDirtyCause;
77pub use crate::{
78 capture_future::TurboTasksPanic,
79 collectibles::CollectiblesSource,
80 completion::{Completion, Completions},
81 display::{ValueToString, ValueToStringRef},
82 dyn_task_inputs::{
83 DynTaskInputs, DynTaskInputsStorage, HeapDynTaskInputsStorage, StackDynTaskInputsStorage,
84 },
85 effect::{
86 ApplyError, CapturedEffect, Effect, EffectError, EffectExt, EffectStateStorage, Effects,
87 EffectsError, read_strongly_consistent_and_apply_effects,
88 resolve_strongly_consistent_and_take_and_apply_effects, take_effects,
89 },
90 error::PrettyPrintError,
91 id::{
92 ExecutionId, FunctionId, LocalTaskId, TRANSIENT_TASK_BIT, TaskId, TraitTypeId, ValueTypeId,
93 },
94 invalidation::{
95 InvalidationReason, InvalidationReasonKind, InvalidationReasonSet, Invalidator,
96 get_invalidator,
97 },
98 join_iter_ext::{JoinIterExt, TryFlatJoinIterExt, TryJoinIterExt},
99 manager::{
100 CurrentCellRef, InputResolution, ReadCellTracking, ReadConsistency, ReadTracking,
101 TaskPersistence, TaskPriority, TurboTasks, TurboTasksApi, TurboTasksCallApi, Unused,
102 UpdateInfo, dynamic_call, emit, get_serialization_invalidator, mark_finished,
103 mark_stateful, mark_top_level_task, prevent_gc, run, run_once, run_once_with_reason,
104 trait_call, turbo_tasks, turbo_tasks_scope, turbo_tasks_weak,
105 unmark_top_level_task_may_leak_eventually_consistent_state, with_turbo_tasks,
106 },
107 mapped_read_ref::MappedReadRef,
108 output::OutputContent,
109 read_options::{ReadCellOptions, ReadOutputOptions},
110 read_ref::ReadRef,
111 serialization_invalidation::SerializationInvalidator,
112 spawn::{JoinHandle, block_for_future, block_in_place, spawn, spawn_blocking, spawn_thread},
113 state::{State, parking_lot_mutex_bincode},
114 task::{
115 SharedReference, TypedSharedReference,
116 task_input::{EitherTaskInput, TaskInput},
117 },
118 task_execution_reason::TaskExecutionReason,
119 trait_ref::TraitRef,
120 value::{TransientInstance, TransientValue},
121 value_type::{Evictability, TraitMethod, TraitType, ValueType, ValueTypePersistence},
122 vc::{
123 CellId, Dynamic, NonLocalValue, OperationValue, OperationVc, OptionVcExt, OrdResolvedVc,
124 RawVc, RawVcUnpacked, ReadRawVcFuture, ReadVcFuture, ResolveOperationVcFuture,
125 ResolveRawVcFuture, ResolveVcFuture, ResolvedVc, ToResolvedVcFuture, Upcast, UpcastStrict,
126 ValueDefault, Vc, VcCast, VcCellCompareMode, VcCellHashedCompareMode,
127 VcCellKeyedCompareMode, VcCellNewMode, VcDefaultRead, VcRead, VcTransparentRead,
128 VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast,
129 },
130};
131
132pub type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>;
133pub type FxIndexMap<K, V> = indexmap::IndexMap<K, V, BuildHasherDefault<FxHasher>>;
134pub type FxDashMap<K, V> = dashmap::DashMap<K, V, BuildHasherDefault<FxHasher>>;
135
136// Copied from indexmap! and indexset!
137#[macro_export]
138macro_rules! fxindexmap {
139 (@single $($x:tt)*) => (());
140 (@count $($rest:expr),*) => (<[()]>::len(&[$($crate::fxindexmap!(@single $rest)),*]));
141
142 ($($key:expr => $value:expr,)+) => { $crate::fxindexmap!($($key => $value),+) };
143 ($($key:expr => $value:expr),*) => {
144 {
145 let _cap = $crate::fxindexmap!(@count $($key),*);
146 let mut _map = $crate::FxIndexMap::with_capacity_and_hasher(_cap, Default::default());
147 $(
148 _map.insert($key, $value);
149 )*
150 _map
151 }
152 };
153}
154#[macro_export]
155macro_rules! fxindexset {
156 (@single $($x:tt)*) => (());
157 (@count $($rest:expr),*) => (<[()]>::len(&[$($crate::fxindexset!(@single $rest)),*]));
158
159 ($($value:expr,)+) => { $crate::fxindexset!($($value),+) };
160 ($($value:expr),*) => {
161 {
162 let _cap = $crate::fxindexset!(@count $($value),*);
163 let mut _set = $crate::FxIndexSet::with_capacity_and_hasher(_cap, Default::default());
164 $(
165 _set.insert($value);
166 )*
167 _set
168 }
169 };
170}
171
172#[doc = include_str!("../singleton_pattern.md")]
173pub mod _singleton_pattern {}
174
175#[doc = include_str!("../function.md")]
176#[rustfmt::skip]
177pub use turbo_tasks_macros::function;
178
179/// Implements [`VcValueType`] for the given `struct` or `enum`. These value types can be used
180/// inside of a "value cell" as [`Vc<...>`][Vc].
181///
182/// A [`Vc`] represents the result of a computation. Each [`Vc`]'s value is placed into a cell
183/// associated with the current [`TaskId`]. That [`Vc`] object can be `await`ed to get [a read-only
184/// reference to the value contained in the cell][ReadRef].
185///
186/// This macro accepts multiple comma-separated arguments. For example:
187///
188/// ```
189/// # #![feature(arbitrary_self_types)]
190// # #![feature(arbitrary_self_types_pointers)]
191/// #[turbo_tasks::value(transparent, shared)]
192/// struct Foo(Vec<u32>);
193/// ```
194///
195/// ## `cell = "..."`
196///
197/// Controls when a cell is invalidated upon recomputation of a task. Internally, this is performed
198/// by setting the [`VcValueType::CellMode`] associated type.
199///
200/// - **`"new"`:** Always overrides the value in the cell, invalidating all dependent tasks.
201/// - **`"compare"` *(default)*:** Compares with the existing value in the cell, before overriding it.
202/// Requires the value to implement [`Eq`].
203/// - **`"keyed"`:** Like `"compare"`, but uses per-key invalidation for transparent map types.
204///
205/// Avoiding unnecessary invalidation is important to reduce downstream recomputation of tasks that
206/// depend on this cell's value.
207///
208/// Use `"new"` only if a correct implementation of [`Eq`] is not possible, would be expensive (e.g.
209/// would require comparing a large collection), or if you're implementing a low-level primitive
210/// that intentionally forces recomputation.
211///
212/// ## `eq = "..."`
213///
214/// By default, we `#[derive(PartialEq, Eq)]`. [`Eq`] is required by `cell = "compare"`. This
215/// argument allows overriding that default implementation behavior.
216///
217/// - **`"manual"`:** Prevents deriving [`Eq`] and [`PartialEq`] so you can do it manually.
218///
219/// ## `serialization = "..."`
220///
221/// Affects serialization via [`bincode::Encode`] and [`bincode::Decode`]. Serialization is required
222/// for the filesystem cache of tasks.
223///
224/// - **`"auto"` *(default)*:** Derives the bincode traits and enables serialization.
225/// - **`"custom"`:** Prevents deriving the bincode traits, but still enables serialization
226/// (you must manually implement [`bincode::Encode`] and [`bincode::Decode`]).
227/// - **`"hash"`:** Like `"none"` (no bincode serialization), but instead stores a hash of the cell
228/// value so that changes can be detected even when the transient cell data has been evicted
229/// from memory or was never stored in the cache—avoiding unnecessary downstream invalidation.
230/// Only valid with `cell = "compare"`.
231/// Requires the value to implement both [`Eq`] and [`DeterministicHash`][turbo_tasks_hash::DeterministicHash].
232/// - **`"none"`:** Disables serialization and prevents deriving the traits.
233///
234/// ## `hash = "..."`
235///
236/// By default, when using `serialization = "hash"`, we `#[derive(DeterministicHash)]`. This argument allows
237/// overriding that default implementation behavior.
238///
239/// - **`"manual"`:** Prevents deriving [`DeterministicHash`][turbo_tasks_hash::DeterministicHash] so you can do it manually.
240/// Only valid with `serialization = "hash"`.
241///
242/// ## `shared`
243///
244/// This flag makes the macro-generated `.cell()` method public so everyone can use it.
245///
246/// Non-transparent types are given a `.cell()` method. That method returns a `Vc` of the type.
247///
248/// This option does not apply to wrapper types that use `transparent`. Those use the public
249/// [`Vc::cell`] function for construction.
250///
251/// ## `transparent`
252///
253/// This attribute is only valid on single-element unit structs. When this value is set:
254///
255/// 1. The struct will use [`#[repr(transparent)]`][repr-transparent].
256/// 1. Read operations (`vc.await?`) return a [`ReadRef`] containing the inner type, rather than the
257/// outer struct. Internally, this is accomplished using [`VcTransparentRead`] for the
258/// [`VcValueType::Read`] associated type.
259/// 1. Construction of the type must be performed using [`Vc::cell(inner)`][Vc::cell], rather than
260/// using the `.cell()` method on the outer type (`outer.cell()`).
261/// 1. The [`ValueDebug`][crate::debug::ValueDebug] implementation will defer to the inner type.
262///
263/// This is commonly used to create [`VcValueType`] wrappers for foreign or generic types, such as
264/// [`Vec`] or [`Option`].
265///
266/// [repr-transparent]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent
267///
268/// ## `local`
269///
270/// Skip the implementation of [`NonLocalValue`] for this type.
271///
272/// If not specified, we apply the [`#[derive(NonLocalValue)]`][macro@NonLocalValue] macro, which
273/// asserts that this struct has no fields containing [`Vc`] by implementing the [`NonLocalValue`]
274/// marker trait. Compile-time assertions are generated on every field, checking that they are also
275/// [`NonLocalValue`]s.
276#[rustfmt::skip]
277pub use turbo_tasks_macros::value;
278
279/// Attribute macro for declaring a [`TaskInput`] type. Emits:
280///
281/// - `unsafe impl NonLocalValue for X {}` (unless `contains_unresolved_vcs` is set).
282/// - `impl TaskInput for X` with a field-walking `is_transient`. By default `is_resolved` and
283/// `resolve_input` use the trait defaults (`true` and a [`CloneReady`] future — 8 bytes, no
284/// async-fn envelope); when `contains_unresolved_vcs` is set, both are emitted as
285/// field-walking implementations as well.
286///
287/// Default form (most types):
288///
289/// ```ignore
290/// #[turbo_tasks::task_input]
291/// #[derive(Clone, Debug, Hash, PartialEq, Eq, TraceRawVcs, Encode, Decode)]
292/// pub struct MyTaskInput { ... }
293/// ```
294///
295/// Opt out of `NonLocalValue` when the type contains `Vc<T>` fields:
296///
297/// ```ignore
298/// #[turbo_tasks::task_input(contains_unresolved_vcs)]
299/// #[derive(Clone, Debug, Hash, PartialEq, Eq, TraceRawVcs, Encode, Decode)]
300/// pub struct VcCarrier { vc: Vc<...> }
301/// ```
302pub use turbo_tasks_macros::task_input;
303
304/// Allows this trait to be used as part of a trait object inside of a value cell, in the form of
305/// `Vc<Box<dyn MyTrait>>`. The annotated trait is made into a subtrait of [`VcValueTrait`].
306///
307/// ```ignore
308/// #[turbo_tasks::value_trait]
309/// pub trait MyTrait {
310///
311/// #[turbo_tasks::function]
312/// fn method(self: Vc<Self>, a: i32) -> Vc<Something>;
313///
314/// // External signature: fn method(self: Vc<Self>, a: i32) -> Vc<Something>
315/// #[turbo_tasks::function]
316/// async fn method2(&self, a: i32) -> Result<Vc<Something>> {
317/// // Default implementation
318/// }
319///
320/// // A normal trait item, not a turbo-task
321/// fn normal(&self) -> SomethingElse;
322/// }
323///
324/// #[turbo_tasks::value_trait]
325/// pub trait OtherTrait: MyTrait + ValueToString {
326/// // ...
327/// }
328///
329/// #[turbo_tasks::value_impl]
330/// impl MyTrait for MyValue {
331/// // only the external signature must match (see the docs for #[turbo_tasks::function])
332/// #[turbo_tasks::function]
333/// fn method(&self, a: i32) -> Vc<Something> {
334/// todo!()
335/// }
336///
337/// fn normal(&self) -> SomethingElse {
338/// todo!()
339/// }
340/// }
341/// ```
342///
343/// The `#[turbo_tasks::value_trait]` annotation derives [`VcValueTrait`] and registers the trait
344/// and its methods.
345///
346/// All methods annotated with [`#[turbo_tasks::function]`][function] are cached, and
347/// the external signature rewriting rules defined on that macro are applied.
348///
349/// Default implementation are supported.
350///
351/// ## Arguments
352///
353/// Example: `#[turbo_tasks::value_trait(no_debug, operation)]`
354///
355/// ### `no_debug`
356///
357/// Disables the automatic implementation of [`ValueDebug`][debug::ValueDebug].
358///
359/// Example: `#[turbo_tasks::value_trait(no_debug)]`
360///
361/// ### `Operation`
362///
363/// Adds [`OperationValue`] as a supertrait of this trait.
364///
365/// Example: `#[turbo_tasks::value_trait(operation)]`
366#[rustfmt::skip]
367pub use turbo_tasks_macros::value_trait;
368
369/// A macro used on any `impl` block for a [`VcValueType`]. This can either be an inherent
370/// implementation or a trait implementation (see [`turbo_tasks::value_trait`][value_trait] and
371/// [`VcValueTrait`]).
372///
373/// Methods should be annotated with the [`#[turbo_tasks::function]`][function] macro.
374///
375/// ```ignore
376/// #[turbo_tasks::value_impl]
377/// impl MyTrait for MyValue {
378/// #[turbo_tasks::function]
379/// fn method(&self, a: i32) -> Vc<Something> {
380/// todo!()
381/// }
382/// }
383/// ```
384#[rustfmt::skip]
385pub use turbo_tasks_macros::value_impl;
386
387/// Derives the TaskStorage struct and generates optimized storage structures.
388///
389/// This macro analyzes `field` annotations and generates:
390/// 1. A unified TaskStorage struct
391/// 2. LazyField enum for lazy_vec fields
392/// 3. Typed accessor methods on TaskStorage
393/// 4. TaskStorageAccessors trait with accessor methods
394/// 5. TaskFlags bitfield for boolean flags
395///
396/// # Field Attributes
397///
398/// All fields require two attributes:
399///
400/// ## `storage = "..."` (required)
401///
402/// Specifies how the field is stored:
403/// - `direct` - Direct field access (e.g., `Option<OutputValue>`)
404/// - `auto_set` - Uses AutoSet for small collections
405/// - `auto_map` - Uses AutoMap for key-value pairs
406/// - `counter_map` - Uses CounterMap for reference counting
407/// - `flag` - Boolean flag stored in a compact TaskFlags bitfield (field type must be `bool`)
408///
409/// ## `category = "..."` (required)
410///
411/// Specifies the data category for persistence and access:
412/// - `data` - Frequently changed, bulk I/O
413/// - `meta` - Rarely changed, small I/O
414/// - `transient` - Field is not serialized (in-memory only)
415///
416/// ## Optional Modifiers
417///
418/// - `inline` - Field is stored inline on TaskStorage (default is lazy). Only use for hot-path
419/// fields that are frequently accessed.
420/// - `default` - Use `Default::default()` semantics instead of `Option` for inline direct fields.
421/// - `filter_transient` - Filter out transient values during serialization.
422/// - Serialization methods
423#[rustfmt::skip]
424pub use turbo_tasks_macros::task_storage;
425
426pub type TaskIdSet = AutoSet<TaskId, BuildHasherDefault<FxHasher>, 2>;