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