1use std::{
2 fmt::{Debug, Display},
3 future::Future,
4 pin::Pin,
5 sync::Arc,
6 task::{Poll, ready},
7};
8
9use anyhow::Result;
10use auto_hash_map::AutoSet;
11use bincode::{Decode, Encode};
12use serde::{Deserialize, Serialize};
13
14use crate::{
15 CollectiblesSource, ReadCellOptions, ReadConsistency, ReadOutputOptions, ResolvedVc, TaskId,
16 TaskPersistence, TraitTypeId, ValueTypeId, VcValueTrait,
17 backend::TypedCellContent,
18 event::EventListener,
19 id::{ExecutionId, LocalTaskId},
20 manager::{
21 ReadCellTracking, ReadTracking, SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK,
22 TurboTasksApi, read_local_output, with_turbo_tasks,
23 },
24 registry::get_value_type,
25 turbo_tasks,
26};
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Encode, Decode)]
29pub struct CellId {
30 pub type_id: ValueTypeId,
31 pub index: u32,
32}
33
34impl Display for CellId {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 write!(f, "{}#{}", get_value_type(self.type_id).ty.name, self.index)
37 }
38}
39
40#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Encode, Decode)]
51pub enum RawVc {
52 TaskOutput(TaskId),
55 TaskCell(TaskId, CellId),
60 LocalOutput(ExecutionId, LocalTaskId, TaskPersistence),
70}
71
72impl Debug for RawVc {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 RawVc::TaskOutput(task_id) => f
76 .debug_tuple("RawVc::TaskOutput")
77 .field(&**task_id)
78 .finish(),
79 RawVc::TaskCell(task_id, cell_id) => f
80 .debug_tuple("RawVc::TaskCell")
81 .field(&**task_id)
82 .field(&cell_id.to_string())
83 .finish(),
84 RawVc::LocalOutput(execution_id, local_task_id, task_persistence) => f
85 .debug_tuple("RawVc::LocalOutput")
86 .field(&**execution_id)
87 .field(&**local_task_id)
88 .field(task_persistence)
89 .finish(),
90 }
91 }
92}
93
94impl Display for RawVc {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 match self {
97 RawVc::TaskOutput(task_id) => write!(f, "output of task {}", **task_id),
98 RawVc::TaskCell(task_id, cell_id) => {
99 write!(f, "{} of task {}", cell_id, **task_id)
100 }
101 RawVc::LocalOutput(execution_id, local_task_id, task_persistence) => write!(
102 f,
103 "output of local task {} ({}, {})",
104 **local_task_id, **execution_id, task_persistence
105 ),
106 }
107 }
108}
109
110impl RawVc {
111 pub fn is_resolved(&self) -> bool {
112 match self {
113 RawVc::TaskOutput(..) => false,
114 RawVc::TaskCell(..) => true,
115 RawVc::LocalOutput(..) => false,
116 }
117 }
118
119 pub fn is_local(&self) -> bool {
120 match self {
121 RawVc::TaskOutput(..) => false,
122 RawVc::TaskCell(..) => false,
123 RawVc::LocalOutput(..) => true,
124 }
125 }
126
127 pub fn is_transient(&self) -> bool {
132 match self {
133 RawVc::TaskOutput(task) | RawVc::TaskCell(task, ..) => task.is_transient(),
134 RawVc::LocalOutput(_, _, persistence) => *persistence == TaskPersistence::Transient,
135 }
136 }
137
138 pub(crate) fn into_read(self) -> ReadRawVcFuture {
139 ReadRawVcFuture::new(self)
142 }
143
144 pub(crate) fn resolve(self) -> ResolveRawVcFuture {
146 ResolveRawVcFuture::new(self)
147 }
148
149 pub(crate) async fn to_non_local(self) -> Result<RawVc> {
152 Ok(match self {
153 RawVc::LocalOutput(execution_id, local_task_id, ..) => {
154 let tt = turbo_tasks();
155 let local_output = read_local_output(&*tt, execution_id, local_task_id).await?;
156 debug_assert!(
157 !matches!(local_output, RawVc::LocalOutput(_, _, _)),
158 "a LocalOutput cannot point at other LocalOutputs"
159 );
160 local_output
161 }
162 non_local => non_local,
163 })
164 }
165
166 pub(crate) fn connect(&self) {
167 let RawVc::TaskOutput(task_id) = self else {
168 panic!("RawVc::connect() must only be called on a RawVc::TaskOutput");
169 };
170 let tt = turbo_tasks();
171 tt.connect_task(*task_id);
172 }
173
174 pub fn try_get_task_id(&self) -> Option<TaskId> {
175 match self {
176 RawVc::TaskOutput(t) | RawVc::TaskCell(t, ..) => Some(*t),
177 RawVc::LocalOutput(..) => None,
178 }
179 }
180
181 pub fn try_get_type_id(&self) -> Option<ValueTypeId> {
182 match self {
183 RawVc::TaskCell(_, CellId { type_id, .. }) => Some(*type_id),
184 RawVc::TaskOutput(..) | RawVc::LocalOutput(..) => None,
185 }
186 }
187
188 pub(crate) fn resolved_has_trait(&self, trait_id: TraitTypeId) -> bool {
191 match self {
192 RawVc::TaskCell(_task_id, cell_id) => {
193 get_value_type(cell_id.type_id).has_trait(&trait_id)
194 }
195 _ => unreachable!("resolved_has_trait must be called with a RawVc::TaskCell"),
196 }
197 }
198
199 pub(crate) fn resolved_is_type(&self, type_id: ValueTypeId) -> bool {
202 match self {
203 RawVc::TaskCell(_task_id, cell_id) => cell_id.type_id == type_id,
204 _ => unreachable!("resolved_is_type must be called with a RawVc::TaskCell"),
205 }
206 }
207}
208
209impl CollectiblesSource for RawVc {
211 fn peek_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
212 let RawVc::TaskOutput(task_id) = self else {
213 panic!(
214 "<RawVc as CollectiblesSource>::peek_collectibles() must only be called on a \
215 RawVc::TaskOutput"
216 );
217 };
218 let tt = turbo_tasks();
219 let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
220 map.into_iter()
221 .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
222 .collect()
223 }
224
225 fn take_collectibles<T: VcValueTrait + ?Sized>(self) -> AutoSet<ResolvedVc<T>> {
226 let RawVc::TaskOutput(task_id) = self else {
227 panic!(
228 "<RawVc as CollectiblesSource>::take_collectibles() must only be called on a \
229 RawVc::TaskOutput"
230 );
231 };
232 let tt = turbo_tasks();
233 let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
234 tt.unemit_collectibles(T::get_trait_type_id(), &map);
235 map.into_iter()
236 .filter_map(|(raw, count)| (count > 0).then_some(raw.try_into().unwrap()))
237 .collect()
238 }
239
240 fn drop_collectibles<T: VcValueTrait + ?Sized>(self) {
241 let RawVc::TaskOutput(task_id) = self else {
242 panic!(
243 "<RawVc as CollectiblesSource>::drop_collectibles() must only be called on a \
244 RawVc::TaskOutput"
245 );
246 };
247 let tt = turbo_tasks();
248 let map = tt.read_task_collectibles(task_id, T::get_trait_type_id());
249 tt.unemit_collectibles(T::get_trait_type_id(), &map);
250 }
251}
252
253fn poll_listener(
256 listener: &mut Option<EventListener>,
257 cx: &mut std::task::Context<'_>,
258) -> Poll<()> {
259 if let Some(l) = listener {
260 ready!(Pin::new(l).poll(cx));
261 *listener = None;
262 }
263 Poll::Ready(())
264}
265
266fn suppress_top_level_task_check<R>(strongly_consistent: bool, f: impl FnOnce() -> R) -> R {
273 if cfg!(debug_assertions) && strongly_consistent {
274 SUPPRESS_EVENTUAL_CONSISTENCY_TOP_LEVEL_TASK_CHECK.sync_scope(true, f)
276 } else {
277 f()
278 }
279}
280
281#[must_use]
282pub struct ResolveRawVcFuture {
283 current: RawVc,
284 read_output_options: ReadOutputOptions,
285 strongly_consistent: bool,
288 listener: Option<EventListener>,
289}
290
291impl ResolveRawVcFuture {
292 fn new(vc: RawVc) -> Self {
293 ResolveRawVcFuture {
294 current: vc,
295 read_output_options: ReadOutputOptions::default(),
296 strongly_consistent: false,
297 listener: None,
298 }
299 }
300
301 pub fn strongly_consistent(mut self) -> Self {
302 self.strongly_consistent = true;
303 self.read_output_options.consistency = ReadConsistency::Strong;
304 self
305 }
306
307 pub(crate) fn track_with_key(mut self) -> Self {
310 self.read_output_options.tracking = ReadTracking::Tracked;
311 self
312 }
313
314 pub(crate) fn untracked(mut self) -> Self {
317 self.read_output_options.tracking = ReadTracking::TrackOnlyError;
318 self
319 }
320}
321
322impl Future for ResolveRawVcFuture {
323 type Output = Result<RawVc>;
324
325 #[inline(never)]
326 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
327 let this = unsafe { self.get_unchecked_mut() };
329
330 let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
331 'outer: loop {
332 ready!(poll_listener(&mut this.listener, cx));
333 let listener = match this.current {
334 RawVc::TaskOutput(task) => {
335 let read_result = tt.try_read_task_output(task, this.read_output_options);
336 match read_result {
337 Ok(Ok(vc)) => {
338 this.read_output_options.consistency = ReadConsistency::Eventual;
347 this.current = vc;
348 continue 'outer;
349 }
350 Ok(Err(listener)) => listener,
351 Err(err) => return Poll::Ready(Err(err)),
352 }
353 }
354 RawVc::TaskCell(_, _) => return Poll::Ready(Ok(this.current)),
355 RawVc::LocalOutput(execution_id, local_task_id, ..) => {
356 debug_assert_eq!(
357 this.read_output_options.consistency,
358 ReadConsistency::Eventual
359 );
360 let read_result = tt.try_read_local_output(execution_id, local_task_id);
361 match read_result {
362 Ok(Ok(vc)) => {
363 this.current = vc;
364 continue 'outer;
365 }
366 Ok(Err(listener)) => listener,
367 Err(err) => return Poll::Ready(Err(err)),
368 }
369 }
370 };
371 this.listener = Some(listener);
372 }
373 };
374
375 suppress_top_level_task_check(this.strongly_consistent, || with_turbo_tasks(poll_fn))
382 }
383}
384
385impl Unpin for ResolveRawVcFuture {}
386
387#[must_use]
388pub struct ReadRawVcFuture {
389 resolve: ResolveRawVcFuture,
391 read_cell_options: ReadCellOptions,
393 resolved: Option<(TaskId, CellId)>,
395 listener: Option<EventListener>,
397}
398
399impl ReadRawVcFuture {
400 pub(crate) fn new(vc: RawVc) -> Self {
401 ReadRawVcFuture {
402 resolve: ResolveRawVcFuture::new(vc),
403 read_cell_options: ReadCellOptions::default(),
404 resolved: None,
405 listener: None,
406 }
407 }
408
409 pub fn strongly_consistent(mut self) -> Self {
411 self.resolve = self.resolve.strongly_consistent();
412 self
413 }
414
415 pub fn track_with_key(mut self, key: u64) -> Self {
417 self.resolve = self.resolve.track_with_key();
418 self.read_cell_options.tracking = ReadCellTracking::Tracked { key: Some(key) };
419 self
420 }
421
422 pub fn untracked(mut self) -> Self {
428 self.resolve = self.resolve.untracked();
429 self.read_cell_options.tracking = ReadCellTracking::TrackOnlyError;
430 self
431 }
432
433 pub fn final_read_hint(mut self) -> Self {
435 self.read_cell_options.final_read_hint = true;
436 self
437 }
438}
439
440impl Future for ReadRawVcFuture {
441 type Output = Result<TypedCellContent>;
442
443 #[inline(never)]
444 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
445 let this = unsafe { self.get_unchecked_mut() };
447
448 if this.resolved.is_none() {
453 match ready!(Pin::new(&mut this.resolve).poll(cx)) {
454 Err(err) => return Poll::Ready(Err(err)),
455 Ok(RawVc::TaskCell(task, index)) => {
456 this.resolved = Some((task, index));
457 }
458 Ok(_) => unreachable!("ResolveRawVcFuture always resolves to a TaskCell"),
459 }
460 }
461
462 let (task, index) = this.resolved.unwrap();
466
467 let poll_fn = |tt: &Arc<dyn TurboTasksApi>| -> Poll<Self::Output> {
468 loop {
469 ready!(poll_listener(&mut this.listener, cx));
470 let listener = match tt.try_read_task_cell(task, index, this.read_cell_options) {
471 Ok(Ok(content)) => return Poll::Ready(Ok(content)),
472 Ok(Err(listener)) => listener,
473 Err(err) => return Poll::Ready(Err(err)),
474 };
475 this.listener = Some(listener);
476 }
477 };
478
479 suppress_top_level_task_check(this.resolve.strongly_consistent, || {
484 with_turbo_tasks(poll_fn)
485 })
486 }
487}
488
489impl Unpin for ReadRawVcFuture {}