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