Skip to main content

cranpose_core/
recompose_scope.rs

1use std::{
2    cell::Cell,
3    hash::{Hash, Hasher},
4    rc::{Rc, Weak},
5};
6
7use smallvec::SmallVec;
8
9#[cfg(feature = "inspection")]
10use crate::source_trace;
11use crate::{
12    AnchorId, Composer, LocalStackSnapshot, NodeId, NodeIdCell, PackedU64, RetentionMode,
13    RuntimeHandle, ScopeId, SlotsHost, StateId, collections::map::HashSet, composer, runtime,
14    thread_state,
15};
16
17mod scope_flag;
18use scope_flag::ScopeFlag;
19
20// Whether a scope's body ran to its end or was skipped.
21#[derive(Clone, Copy, PartialEq, Eq)]
22pub(crate) enum BodyRun {
23    Ran,
24    Skipped,
25}
26
27impl From<bool> for BodyRun {
28    fn from(ran: bool) -> Self {
29        if ran { Self::Ran } else { Self::Skipped }
30    }
31}
32
33fn scope_activity_epoch() -> u64 {
34    thread_state::cells(|cells| cells.scope_activity_epoch.get())
35}
36
37fn note_scope_activity_change() {
38    thread_state::cells(|cells| {
39        let epoch = &cells.scope_activity_epoch;
40        epoch.set(epoch.get() + 1);
41    });
42}
43
44/// Runs `read` on what `cell` holds and puts it back: a scope's links are
45/// read this way rather than through a `RefCell`, whose borrow flag would
46/// take a word in every scope of a composition. `read` must not reach the
47/// same cell again.
48fn read_cell<T: Default, R>(cell: &Cell<T>, read: impl FnOnce(&T) -> R) -> R {
49    let value = cell.take();
50    let result = read(&value);
51    cell.set(value);
52    result
53}
54
55/// Like [`read_cell`], for a change to what `cell` holds.
56fn update_cell<T: Default, R>(cell: &Cell<T>, update: impl FnOnce(&mut T) -> R) -> R {
57    let mut value = cell.take();
58    let result = update(&mut value);
59    cell.set(value);
60    result
61}
62
63/// How a scope is tied to the scope its lifetime follows.
64#[derive(Clone, Copy, PartialEq, Eq)]
65enum OwnerKind {
66    /// The scope it composes under, its recomposition ancestor.
67    Parent,
68    /// For the root of a slot table composed for another scope's content,
69    /// that scope, which is no recomposition ancestor.
70    Lifetime,
71}
72
73// The scope a scope's lifetime follows; `ScopeFlag::LifetimeOwner` says
74// how it is tied to it.
75type OwnerLink = Cell<Option<Weak<RecomposeScopeInner>>>;
76
77// A hand-written body that recomposes a scope.
78type RecomposeClosure = Box<dyn FnMut(&Composer)>;
79
80// A scope's flags in one cell, a bit each: a `Cell<bool>` each would take a
81// byte of every scope.
82struct ScopeFlags(Cell<u16>);
83
84impl ScopeFlags {
85    fn get(&self, flag: ScopeFlag) -> bool {
86        self.0.get() & flag.bit() != 0
87    }
88
89    fn set(&self, flag: ScopeFlag, on: bool) {
90        let bits = self.0.get();
91        self.0.set(if on {
92            bits | flag.bit()
93        } else {
94            bits & !flag.bit()
95        });
96    }
97
98    // Whether `a` or `b` is set, in one test.
99    fn either(&self, a: ScopeFlag, b: ScopeFlag) -> bool {
100        self.0.get() & (a.bit() | b.bit()) != 0
101    }
102
103    // Sets `flag` and says whether it was set.
104    fn replace(&self, flag: ScopeFlag, on: bool) -> bool {
105        let was = self.get(flag);
106        self.set(flag, on);
107        was
108    }
109}
110
111pub(crate) struct RecomposeScopeInner {
112    runtime: runtime::ScopeRuntime,
113    flags: ScopeFlags,
114    active_epoch: Cell<PackedU64>,
115    deactivations: Cell<PackedU64>,
116    retention_mode: Cell<RetentionMode>,
117    parent_hint: NodeIdCell,
118    group_anchor: Cell<AnchorId>,
119    // What runs the scope's body again: a `#[composable]` function's
120    // generated recompose function, or a hand-written closure when the
121    // function is `None`.
122    recompose: Cell<Option<fn(&Composer)>>,
123    owner: OwnerLink,
124    local_stack: Cell<LocalStackSnapshot>,
125    #[cfg(feature = "inspection")]
126    source_trace: std::cell::RefCell<Rc<[source_trace::SourceLocation]>>,
127    #[cfg(all(feature = "inspection", debug_assertions))]
128    pub(crate) recompositions: std::cell::OnceCell<source_trace::RecompositionCounter>,
129    slots_storage_key: Cell<usize>,
130    slots_runtime_state: Cell<Option<Weak<composer::ComposerRuntimeState>>>,
131    /// How many subscriptions the body running now read in order, or
132    /// [`DIVERGED`] or [`NOT_READING`].
133    read_cursor: Cell<u32>,
134    // `None` until a body of the scope reads a state, a state invalidates it
135    // or a hand-written closure recomposes it: most scopes need none.
136    restart: Cell<Option<Box<RestartPart>>>,
137}
138
139type StateIds = SmallVec<[StateId; 2]>;
140
141// What a scope keeps of the states its bodies read, and the hand-written
142// body that recomposes it.
143#[derive(Default)]
144struct RestartPart {
145    // The states the scope is subscribed to: what its last body read, in
146    // read order.
147    subscriptions: StateIds,
148    // What the body running now read so far, once it left the order of
149    // `subscriptions`: `None` while it reads in order.
150    run: Option<StateIds>,
151    // The states whose changes invalidated the scope since it last
152    // recomposed.
153    invalidation_sources: StateIds,
154    // A hand-written closure that recomposes the scope, where no
155    // `#[composable]` function does.
156    closure: Option<RecomposeClosure>,
157}
158
159/// What [`RecomposeScope::note_read`] made of a read.
160pub(crate) enum ScopeRead {
161    /// The read repeats the last body's, so the state watches the scope.
162    Watched,
163    /// The read went into the running body's reads; the state may not watch
164    /// the scope yet.
165    Collected,
166    /// No body of the scope is running.
167    NotReading,
168}
169
170/// A scope's `read_cursor` while no body of it runs.
171const NOT_READING: u32 = u32::MAX;
172/// A scope's `read_cursor` once the running body left the order of the reads
173/// before it.
174const DIVERGED: u32 = u32::MAX - 1;
175
176enum ScopeOwner {
177    Root,
178    Live(Rc<RecomposeScopeInner>),
179    Dropped,
180}
181
182impl RecomposeScopeInner {
183    fn owner(&self) -> ScopeOwner {
184        read_cell(&self.owner, |owner| {
185            owner.as_ref().map_or(ScopeOwner::Root, |owner| {
186                owner
187                    .upgrade()
188                    .map_or(ScopeOwner::Dropped, ScopeOwner::Live)
189            })
190        })
191    }
192
193    fn is_effectively_active(&self, epoch: u64) -> bool {
194        if self.active_epoch.get().get() == epoch {
195            return true;
196        }
197        if !self.flags.get(ScopeFlag::Active) {
198            return false;
199        }
200        let active = match self.owner() {
201            ScopeOwner::Root => true,
202            ScopeOwner::Dropped => false,
203            ScopeOwner::Live(owner) => owner.is_effectively_active(epoch),
204        };
205        if active {
206            self.active_epoch.set(PackedU64::new(epoch));
207        }
208        active
209    }
210
211    fn new(runtime: runtime::ScopeRuntime) -> Self {
212        runtime.increment_live_recompose_scope_count();
213        Self {
214            runtime,
215            flags: ScopeFlags(Cell::new(ScopeFlag::Active.bit())),
216            active_epoch: Cell::default(),
217            deactivations: Cell::default(),
218            retention_mode: Cell::new(RetentionMode::DisposeWhenInactive),
219            parent_hint: NodeIdCell::new(None),
220            group_anchor: Cell::new(AnchorId::INVALID),
221            recompose: Cell::new(None),
222            owner: Cell::new(None),
223            local_stack: Cell::new(None),
224            #[cfg(feature = "inspection")]
225            source_trace: std::cell::RefCell::new(Rc::from([])),
226            #[cfg(all(feature = "inspection", debug_assertions))]
227            recompositions: std::cell::OnceCell::new(),
228            slots_storage_key: Cell::new(0),
229            slots_runtime_state: Cell::new(None),
230            read_cursor: Cell::new(NOT_READING),
231            restart: Cell::new(None),
232        }
233    }
234
235    // Lends the scope's restart part, `None` while it has none, to `lend`
236    // and puts it back. Nothing the part is lent to reaches the cell, which
237    // stays empty meanwhile: putting the part back drops nothing, and a
238    // scope without one runs no drop code.
239    fn with_restart<R>(&self, lend: impl FnOnce(&mut Option<Box<RestartPart>>) -> R) -> R {
240        let mut part = self.restart.take();
241        let result = lend(&mut part);
242        if let Some(stale) = self.restart.replace(part) {
243            drop(stale);
244        }
245        result
246    }
247
248    // Runs `read` on the scope's restart part, `None` while it has none.
249    fn read_restart<R>(&self, read: impl FnOnce(Option<&RestartPart>) -> R) -> R {
250        self.with_restart(|part| read(part.as_deref()))
251    }
252
253    // Runs `update` on the scope's restart part, made first if it has none.
254    fn update_restart<R>(&self, update: impl FnOnce(&mut RestartPart) -> R) -> R {
255        self.with_restart(|part| update(part.get_or_insert_default()))
256    }
257
258    fn id(&self) -> ScopeId {
259        std::ptr::from_ref(self).addr()
260    }
261}
262
263fn push_unique_state_id(ids: &mut StateIds, state_id: StateId) {
264    if !ids.contains(&state_id) {
265        ids.push(state_id);
266    }
267}
268
269impl Drop for RecomposeScopeInner {
270    fn drop(&mut self) {
271        note_scope_activity_change();
272        let id = self.id();
273        self.runtime.decrement_live_recompose_scope_count();
274        if let Some(reads) = self.restart.take() {
275            let RestartPart {
276                subscriptions, run, ..
277            } = *reads;
278            for state_id in subscriptions.into_iter().chain(run.into_iter().flatten()) {
279                self.runtime.unregister_state_scope(state_id, id);
280            }
281        }
282        #[cfg(debug_assertions)]
283        {
284            thread_state::try_runtimes(|state| {
285                state.scope_labels.borrow_mut().remove(&id);
286                state.scope_invalidation_sources.borrow_mut().remove(&id);
287            });
288        }
289        if self.flags.replace(ScopeFlag::Enqueued, false) {
290            self.runtime.mark_scope_recomposed();
291        }
292    }
293}
294
295/// Size of the registry of live recompose scopes, for leak checks.
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
297pub struct RecomposeScopeRegistryDebugStats {
298    /// Scopes registered.
299    pub len: usize,
300    /// Capacity reserved for the registry.
301    pub capacity: usize,
302}
303
304/// The unit of recomposition. State read inside a scope invalidates it, and a recomposition runs
305/// only the content of the invalid scopes. Clones refer to the same scope.
306#[derive(Clone)]
307pub struct RecomposeScope {
308    pub(crate) inner: Rc<RecomposeScopeInner>,
309}
310
311impl PartialEq for RecomposeScope {
312    fn eq(&self, other: &Self) -> bool {
313        Rc::ptr_eq(&self.inner, &other.inner)
314    }
315}
316
317impl Eq for RecomposeScope {}
318
319impl Hash for RecomposeScope {
320    fn hash<H: Hasher>(&self, state: &mut H) {
321        self.id().hash(state);
322    }
323}
324
325impl RecomposeScope {
326    /// Marks this scope as one that only recomputes a derived state: running
327    /// it changes nothing a composition shows unless the value it writes
328    /// invalidates the scopes that read it.
329    pub(crate) fn mark_derivation(&self) {
330        self.inner.flags.set(ScopeFlag::Derivation, true);
331    }
332
333    pub(crate) fn is_derivation(&self) -> bool {
334        self.inner.flags.get(ScopeFlag::Derivation)
335    }
336
337    pub(crate) fn new(runtime: RuntimeHandle) -> Self {
338        Self {
339            inner: Rc::new(RecomposeScopeInner::new(runtime.scope_runtime())),
340        }
341    }
342
343    pub(crate) fn downgrade(&self) -> Weak<RecomposeScopeInner> {
344        Rc::downgrade(&self.inner)
345    }
346
347    pub(crate) fn upgrade(weak: &Weak<RecomposeScopeInner>) -> Option<Self> {
348        weak.upgrade().map(|inner| Self { inner })
349    }
350
351    /// Returns an id that is unique among the live scopes.
352    pub fn id(&self) -> ScopeId {
353        self.inner.id()
354    }
355
356    /// Returns `true` if state that the scope read has changed since it last recomposed.
357    pub fn is_invalid(&self) -> bool {
358        self.inner.flags.get(ScopeFlag::Invalid)
359    }
360
361    pub(crate) fn is_enqueued(&self) -> bool {
362        self.inner.flags.get(ScopeFlag::Enqueued)
363    }
364
365    /// Returns `false` between `deactivate` and `reactivate`.
366    pub fn is_active(&self) -> bool {
367        self.inner.flags.get(ScopeFlag::Active)
368    }
369
370    /// Total deactivations along this scope's owner chain. A retained slot
371    /// composition records this at compose time; a later mismatch means some
372    /// enclosing composition was deactivated (its owned effects cancelled)
373    /// since the slot last composed, so the retained content must recompose
374    /// once to restart them — no flag on the slot's own scopes carries that
375    /// trace, because deactivation walks stop at slot-host boundaries.
376    pub fn owner_chain_deactivation_epoch(&self) -> u64 {
377        let mut total = self.inner.deactivations.get().get();
378        let mut owner = self.inner.owner();
379        while let ScopeOwner::Live(scope) = owner {
380            total = total.wrapping_add(scope.deactivations.get().get());
381            owner = scope.owner();
382        }
383        total
384    }
385
386    pub(crate) fn is_effectively_active(&self) -> bool {
387        self.inner.is_effectively_active(scope_activity_epoch())
388    }
389
390    pub(crate) fn record_state_subscription(&self, state_id: StateId) {
391        self.inner
392            .update_restart(|reads| push_unique_state_id(&mut reads.subscriptions, state_id));
393    }
394
395    /// Starts collecting the states a body of the scope reads.
396    pub(crate) fn begin_reads(&self) {
397        self.inner.read_cursor.set(0);
398    }
399
400    /// Notes that the body running now read `state_id`. While the body reads
401    /// what the last one read, in the same order, a read only moves the
402    /// cursor along the subscriptions, and the state is known to watch the
403    /// scope already; the first read off that order copies the reads so far
404    /// into the run's reads.
405    #[inline]
406    pub(crate) fn note_read(&self, state_id: StateId) -> ScopeRead {
407        let cursor = self.inner.read_cursor.get();
408        if cursor == NOT_READING {
409            return ScopeRead::NotReading;
410        }
411        self.inner.update_restart(|reads| {
412            if cursor == DIVERGED {
413                if let Some(run) = &mut reads.run
414                    && run.last() != Some(&state_id)
415                {
416                    run.push(state_id);
417                }
418                return ScopeRead::Collected;
419            }
420            let at = cursor as usize;
421            let subscribed = &reads.subscriptions;
422            if subscribed.get(at) == Some(&state_id) {
423                self.inner.read_cursor.set(cursor + 1);
424                return ScopeRead::Watched;
425            }
426            if at > 0 && subscribed[at - 1] == state_id {
427                return ScopeRead::Watched;
428            }
429            let mut run = StateIds::from_slice(&subscribed[..at]);
430            run.push(state_id);
431            reads.run = Some(run);
432            self.inner.read_cursor.set(DIVERGED);
433            ScopeRead::Collected
434        })
435    }
436
437    // Keeps the subscriptions the scope has: its body runs this pass without
438    // the reads that made them, as a skipped body does.
439    pub(crate) fn keep_reads(&self) {
440        self.inner.read_cursor.set(NOT_READING);
441    }
442
443    /// Ends collecting reads. A body that ran makes its reads the scope's
444    /// subscriptions and drops the states it did not read again, as Compose
445    /// does; a skipped or unfinished one keeps the subscriptions it had.
446    #[inline]
447    pub(crate) fn end_reads(&self, run: BodyRun) {
448        let ran = run == BodyRun::Ran;
449        let cursor = self.inner.read_cursor.replace(NOT_READING);
450        // A skipped body that read in order keeps the subscriptions as they
451        // are.
452        if cursor == NOT_READING || (!ran && cursor != DIVERGED) {
453            return;
454        }
455        self.settle_reads(cursor, ran);
456    }
457
458    /// The part of [`Self::end_reads`] for a body that ran or left the
459    /// order of its reads: `cursor` is where the read cursor stood.
460    #[inline(never)]
461    fn settle_reads(&self, cursor: u32, ran: bool) {
462        let id = self.id();
463        let runtime = &self.inner.runtime;
464        self.inner.with_restart(|reads| {
465            let Some(reads) = reads.as_deref_mut() else {
466                return;
467            };
468            let subscribed = &mut reads.subscriptions;
469            if cursor != DIVERGED {
470                // The body read a prefix of the subscriptions, in order.
471                let read = cursor as usize;
472                if ran && read < subscribed.len() {
473                    for &state_id in &subscribed[read..] {
474                        if !subscribed[..read].contains(&state_id) {
475                            runtime.forget_state_scope(state_id, id);
476                        }
477                    }
478                    subscribed.truncate(read);
479                }
480                return;
481            }
482            let Some(run) = reads.run.take() else {
483                return;
484            };
485            if ran {
486                for &state_id in subscribed.iter() {
487                    if !run.contains(&state_id) {
488                        runtime.forget_state_scope(state_id, id);
489                    }
490                }
491                *subscribed = run;
492            } else {
493                for state_id in run {
494                    push_unique_state_id(subscribed, state_id);
495                }
496            }
497        });
498    }
499
500    fn record_unknown_invalidation_source(&self) {
501        self.inner
502            .flags
503            .set(ScopeFlag::UnknownInvalidationSource, true);
504        self.clear_invalidation_sources();
505    }
506
507    fn clear_invalidation_sources(&self) {
508        self.inner.with_restart(|reads| {
509            if let Some(reads) = reads.as_deref_mut() {
510                reads.invalidation_sources.clear();
511            }
512        });
513    }
514
515    fn record_state_invalidation_source(&self, state_id: StateId) {
516        if !self.inner.flags.get(ScopeFlag::UnknownInvalidationSource) {
517            self.inner.update_restart(|reads| {
518                push_unique_state_id(&mut reads.invalidation_sources, state_id);
519            });
520        }
521    }
522
523    fn enqueue_invalidation(&self) {
524        self.inner.flags.set(ScopeFlag::Invalid, true);
525        if self.is_effectively_active() && self.may_queue() {
526            self.queue_recompose();
527        }
528    }
529
530    // Whether the scope may join the recompose queue: it is not in it, and
531    // its pausable content, if any, completed.
532    fn may_queue(&self) -> bool {
533        !self
534            .inner
535            .flags
536            .either(ScopeFlag::Enqueued, ScopeFlag::Pending)
537    }
538
539    fn queue_recompose(&self) {
540        self.inner.flags.set(ScopeFlag::Enqueued, true);
541        self.inner.runtime.register_invalid_scope(self.downgrade());
542    }
543
544    pub(crate) fn invalidate(&self) {
545        self.record_unknown_invalidation_source();
546        self.enqueue_invalidation();
547    }
548
549    pub(crate) fn invalidate_from_state(&self, state_id: StateId) {
550        self.record_state_invalidation_source(state_id);
551        if self.inner.read_cursor.get() != NOT_READING {
552            self.note_running_write(state_id);
553        }
554        self.enqueue_invalidation();
555    }
556
557    // A write to `state_id` while the scope's body runs. After a read of it
558    // in this run, the body composed from the value the write replaced: it
559    // composes again once it closes, as Compose's does after a backward
560    // write. A write before any read, as a provider's, needs no second run.
561    #[inline(never)]
562    fn note_running_write(&self, state_id: StateId) {
563        let cursor = self.inner.read_cursor.get();
564        let read = self.inner.read_restart(|reads| {
565            reads.is_some_and(|reads| {
566                if cursor == DIVERGED {
567                    reads
568                        .run
569                        .as_ref()
570                        .is_some_and(|run| run.contains(&state_id))
571                } else {
572                    reads.subscriptions[..cursor as usize].contains(&state_id)
573                }
574            })
575        });
576        if read {
577            self.request_pending_recompose();
578        }
579    }
580
581    pub(crate) fn mark_recomposed(&self) {
582        // An invalidation notes its source and sets `invalid` together, so a
583        // scope nothing invalidated has no source to forget.
584        if self.inner.flags.replace(ScopeFlag::Invalid, false) {
585            self.inner
586                .flags
587                .set(ScopeFlag::UnknownInvalidationSource, false);
588            self.clear_invalidation_sources();
589        }
590        self.inner.flags.set(ScopeFlag::ForceReuse, false);
591        self.inner.flags.set(ScopeFlag::ForceRecompose, false);
592        if self.inner.flags.replace(ScopeFlag::Enqueued, false) {
593            self.inner.runtime.mark_scope_recomposed();
594        }
595        let pending = self.inner.flags.replace(ScopeFlag::PendingRecompose, false);
596        if pending {
597            if self.inner.flags.get(ScopeFlag::Active) {
598                self.invalidate();
599            } else {
600                self.inner.flags.set(ScopeFlag::Invalid, true);
601            }
602        }
603    }
604
605    /// Registers `callback` as the code that recomposes the scope when state
606    /// its body read changes.
607    pub(crate) fn set_recompose_callback<F>(&self, callback: F)
608    where
609        F: FnMut(&Composer) + 'static,
610    {
611        self.note_recompose_source();
612        self.inner.recompose.set(None);
613        self.inner
614            .update_restart(|part| part.closure = Some(Box::new(callback)));
615    }
616
617    // Registers `body` as the function that recomposes the scope; the same
618    // function stays as it is.
619    #[inline]
620    pub(crate) fn set_recompose_fn(&self, body: fn(&Composer)) {
621        let same = self
622            .inner
623            .recompose
624            .get()
625            .is_some_and(|current| std::ptr::fn_addr_eq(current, body));
626        if !same {
627            self.set_recompose(body);
628        }
629    }
630
631    #[inline(never)]
632    fn set_recompose(&self, body: fn(&Composer)) {
633        self.note_recompose_source();
634        self.inner.recompose.set(Some(body));
635        self.inner.with_restart(|part| {
636            if let Some(part) = part.as_deref_mut() {
637                part.closure = None;
638            }
639        });
640    }
641
642    fn note_recompose_source(&self) {
643        #[cfg(feature = "inspection")]
644        self.set_recompose_source(source_trace::current_source_trace());
645    }
646
647    // The composables a recomposition of the scope runs inside.
648    #[cfg(feature = "inspection")]
649    pub(crate) fn set_recompose_source(&self, trace: Rc<[source_trace::SourceLocation]>) {
650        self.inner.source_trace.replace(trace);
651    }
652
653    // Kept out of line: the ESP32-S3 hot-code list places it in IRAM.
654    #[inline(never)]
655    pub(crate) fn run_recompose(&self, composer: &Composer) -> bool {
656        #[cfg(feature = "inspection")]
657        let _source_context = source_trace::restore_source_trace(&self.inner.source_trace.borrow());
658        let Some(body) = self.inner.recompose.get() else {
659            return self.run_recompose_closure(composer);
660        };
661        self.begin_reads();
662        body(composer);
663        self.end_reads(BodyRun::Ran);
664        true
665    }
666
667    #[inline(never)]
668    fn run_recompose_closure(&self, composer: &Composer) -> bool {
669        let Some(mut closure) = self
670            .inner
671            .with_restart(|part| part.as_deref_mut().and_then(|part| part.closure.take()))
672        else {
673            return false;
674        };
675        self.begin_reads();
676        self.inner.flags.set(ScopeFlag::Recomposing, true);
677        closure(composer);
678        self.inner.flags.set(ScopeFlag::Recomposing, false);
679        self.end_reads(BodyRun::Ran);
680        // The closure may have stored a new one for the scope while it ran.
681        self.inner.update_restart(|part| {
682            if part.closure.is_none() {
683                part.closure = Some(closure);
684            }
685        });
686        true
687    }
688
689    pub(crate) fn has_recompose_callback(&self) -> bool {
690        self.inner.recompose.get().is_some()
691            || self.inner.flags.get(ScopeFlag::Recomposing)
692            || self
693                .inner
694                .read_restart(|part| part.is_some_and(|part| part.closure.is_some()))
695    }
696
697    /// How many scopes this one composes under.
698    pub(crate) fn depth(&self) -> usize {
699        let mut depth = 0;
700        let mut current = self.parent_scope();
701        while let Some(scope) = current {
702            depth += 1;
703            current = scope.parent_scope();
704        }
705        depth
706    }
707
708    pub(crate) fn snapshot_locals(&self, stack: &LocalStackSnapshot) {
709        update_cell(&self.inner.local_stack, |locals| {
710            let unchanged = match (&*locals, stack) {
711                (Some(current), Some(stack)) => Rc::ptr_eq(current, stack),
712                (current, stack) => current.is_none() && stack.is_none(),
713            };
714            if !unchanged {
715                locals.clone_from(stack);
716            }
717        });
718    }
719
720    pub(crate) fn local_stack(&self) -> LocalStackSnapshot {
721        read_cell(&self.inner.local_stack, Clone::clone)
722    }
723
724    pub(crate) fn set_parent_hint(&self, parent: Option<NodeId>) {
725        self.inner.parent_hint.set(parent);
726    }
727
728    /// Ties the scope to the scope its lifetime follows, or to none.
729    fn set_owner(&self, kind: OwnerKind, owner: Option<&Self>) {
730        let held_kind = self.owner_kind();
731        update_cell(&self.inner.owner, |link| {
732            let current = link.as_ref().map(|owner| (held_kind, Weak::as_ptr(owner)));
733            if current != owner.map(|owner| (kind, Rc::as_ptr(&owner.inner))) {
734                *link = owner.map(Self::downgrade);
735                note_scope_activity_change();
736            }
737        });
738        self.inner
739            .flags
740            .set(ScopeFlag::LifetimeOwner, kind == OwnerKind::Lifetime);
741    }
742
743    fn owner_kind(&self) -> OwnerKind {
744        if self.inner.flags.get(ScopeFlag::LifetimeOwner) {
745            OwnerKind::Lifetime
746        } else {
747            OwnerKind::Parent
748        }
749    }
750
751    /// Makes `parent` the scope this one composes under, or makes it a root.
752    pub(crate) fn set_parent_scope(&self, parent: Option<&Self>) {
753        self.set_owner(OwnerKind::Parent, parent);
754    }
755
756    fn owner_of_kind(&self, kind: OwnerKind) -> Option<Self> {
757        if self.owner_kind() != kind {
758            return None;
759        }
760        read_cell(&self.inner.owner, |owner| {
761            owner.as_ref().and_then(Self::upgrade)
762        })
763    }
764
765    pub(crate) fn parent_scope(&self) -> Option<Self> {
766        self.owner_of_kind(OwnerKind::Parent)
767    }
768
769    /// Makes this scope a root whose lifetime follows `owner`, or a plain
770    /// root.
771    pub(crate) fn set_lifetime_owner_scope(&self, owner: Option<&Self>) {
772        self.set_owner(OwnerKind::Lifetime, owner);
773    }
774
775    #[cfg(test)]
776    pub(crate) fn lifetime_owner_scope(&self) -> Option<Self> {
777        self.owner_of_kind(OwnerKind::Lifetime)
778    }
779
780    pub(crate) fn callback_promotion_target(&self) -> Option<Self> {
781        let mut current = self.parent_scope();
782        while let Some(scope) = current {
783            if scope.has_recompose_callback() {
784                return Some(scope);
785            }
786            current = scope.parent_scope();
787        }
788        None
789    }
790
791    pub(crate) fn parent_hint(&self) -> Option<NodeId> {
792        self.inner.parent_hint.get()
793    }
794
795    pub(crate) fn group_anchor(&self) -> AnchorId {
796        self.inner.group_anchor.get()
797    }
798
799    pub(crate) fn set_group_anchor(&self, anchor: AnchorId) {
800        self.inner.group_anchor.set(anchor);
801    }
802
803    pub(crate) fn set_slots_host(&self, host: &SlotsHost) {
804        let storage_key = host.storage_key();
805        update_cell(&self.inner.slots_runtime_state, |runtime_state| {
806            if self.inner.slots_storage_key.get() == storage_key
807                && runtime_state.as_ref().map(Weak::as_ptr) == host.runtime_state_ptr()
808            {
809                return;
810            }
811            self.inner.slots_storage_key.set(storage_key);
812            *runtime_state = host.runtime_state().map(|state| Rc::downgrade(&state));
813        });
814    }
815
816    pub(crate) fn slots_storage_key(&self) -> Option<usize> {
817        let key = self.inner.slots_storage_key.get();
818        (key != 0).then_some(key)
819    }
820
821    /// What decides the slot host a recomposition of this scope runs in: its
822    /// table's storage key and the runtime state that table belongs to.
823    pub(crate) fn slots_host_identity(&self) -> (usize, *const composer::ComposerRuntimeState) {
824        let state = read_cell(&self.inner.slots_runtime_state, |state| {
825            state.as_ref().map_or(std::ptr::null(), Weak::as_ptr)
826        });
827        (self.inner.slots_storage_key.get(), state)
828    }
829
830    pub(crate) fn slots_runtime_state(&self) -> Option<Rc<composer::ComposerRuntimeState>> {
831        read_cell(&self.inner.slots_runtime_state, |state| {
832            state.as_ref().and_then(Weak::upgrade)
833        })
834    }
835
836    /// Marks the scope inactive, as when its content is retained or held for reuse. An inactive
837    /// scope is not queued for recomposition until it is reactivated.
838    pub fn deactivate(&self) {
839        if !self.inner.flags.replace(ScopeFlag::Active, false) {
840            return;
841        }
842        note_scope_activity_change();
843        self.inner
844            .deactivations
845            .set(PackedU64::new(self.inner.deactivations.get().get() + 1));
846        if self.inner.flags.replace(ScopeFlag::Enqueued, false) {
847            self.inner.runtime.mark_scope_recomposed();
848        }
849    }
850
851    pub(crate) fn defer_until_reactivated(&self) {
852        if self.inner.flags.replace(ScopeFlag::Enqueued, false) {
853            self.inner.runtime.mark_scope_recomposed();
854        }
855    }
856
857    /// Marks the scope active again and queues it for recomposition if it was invalidated while
858    /// inactive.
859    pub fn reactivate(&self) {
860        self.inner.flags.set(ScopeFlag::Active, true);
861        if self.inner.flags.get(ScopeFlag::Invalid)
862            && self.is_effectively_active()
863            && self.may_queue()
864        {
865            self.queue_recompose();
866        }
867    }
868
869    /// Makes the next `should_recompose` return `false` even if the scope is invalid. Cancels a
870    /// pending `force_recompose`.
871    pub fn force_reuse(&self) {
872        self.inner.flags.set(ScopeFlag::ForceReuse, true);
873        self.inner.flags.set(ScopeFlag::ForceRecompose, false);
874        self.inner.flags.set(ScopeFlag::PendingRecompose, true);
875    }
876
877    pub(crate) fn request_pending_recompose(&self) {
878        self.inner.flags.set(ScopeFlag::PendingRecompose, true);
879    }
880
881    /// Makes the next `should_recompose` return `true` even if the scope is not invalid. Cancels a
882    /// pending `force_reuse`.
883    pub fn force_recompose(&self) {
884        self.inner.flags.set(ScopeFlag::ForceRecompose, true);
885        self.inner.flags.set(ScopeFlag::ForceReuse, false);
886        self.inner.flags.set(ScopeFlag::PendingRecompose, false);
887    }
888
889    pub(crate) fn set_retention_mode(&self, mode: RetentionMode) {
890        self.inner.retention_mode.set(mode);
891    }
892
893    pub(crate) fn retention_mode(&self) -> RetentionMode {
894        self.inner.retention_mode.get()
895    }
896
897    /// Returns whether the scope's content has to run now: `true` after `force_recompose` or when
898    /// the scope is invalid, and `false` after `force_reuse`. A forced answer is used up by the
899    /// call.
900    pub fn should_recompose(&self) -> bool {
901        if self.inner.flags.replace(ScopeFlag::ForceRecompose, false) {
902            self.inner.flags.set(ScopeFlag::ForceReuse, false);
903            return true;
904        }
905        if self.inner.flags.replace(ScopeFlag::ForceReuse, false) {
906            return false;
907        }
908        self.is_invalid()
909    }
910
911    /// Returns `true` once the scope has composed its content at least once.
912    pub fn has_composed_once(&self) -> bool {
913        self.inner.flags.get(ScopeFlag::ComposedOnce)
914    }
915
916    pub(crate) fn mark_composed_once(&self) {
917        self.inner.flags.set(ScopeFlag::ComposedOnce, true);
918    }
919
920    // Whether the scope's first body waits for a later frame.
921    pub(crate) fn is_paused(&self) -> bool {
922        self.inner.flags.get(ScopeFlag::Paused)
923    }
924
925    // Sets whether the scope's first body waits, and says whether it waited
926    // already.
927    pub(crate) fn replace_paused(&self, paused: bool) -> bool {
928        self.inner.flags.replace(ScopeFlag::Paused, paused)
929    }
930
931    // Whether the scope belongs to pausable content that has not completed.
932    pub(crate) fn is_pending(&self) -> bool {
933        self.inner.flags.get(ScopeFlag::Pending)
934    }
935
936    // Holds the scope's invalidations until its pausable content completes,
937    // or, with `false`, queues the invalidation that waited.
938    pub(crate) fn set_pending(&self, pending: bool) {
939        self.inner.flags.set(ScopeFlag::Pending, pending);
940        if !pending && self.is_invalid() {
941            self.enqueue_invalidation();
942        }
943    }
944
945    // Whether a change of the state `state_id` alone invalidated the scope.
946    pub(crate) fn invalidated_only_by_state(&self, state_id: StateId) -> bool {
947        !self.inner.flags.get(ScopeFlag::UnknownInvalidationSource)
948            && self.inner.read_restart(|reads| {
949                reads.is_some_and(|reads| {
950                    let sources = &reads.invalidation_sources;
951                    !sources.is_empty() && sources.iter().all(|source| *source == state_id)
952                })
953            })
954    }
955
956    pub(crate) fn invalidated_only_by(&self, allowed_sources: &HashSet<StateId>) -> Option<bool> {
957        if self.inner.flags.get(ScopeFlag::UnknownInvalidationSource) {
958            return None;
959        }
960        self.inner.read_restart(|reads| {
961            let sources = &reads?.invalidation_sources;
962            (!sources.is_empty()).then(|| {
963                sources
964                    .iter()
965                    .all(|source| allowed_sources.contains(source))
966            })
967        })
968    }
969}
970
971#[cfg(test)]
972impl RecomposeScope {
973    pub(crate) fn new_for_test(runtime: RuntimeHandle) -> Self {
974        Self::new(runtime)
975    }
976}
977
978/// Options that a composable group passes to its recompose scope.
979#[derive(Debug, Clone, Copy, Default)]
980pub struct RecomposeOptions {
981    /// Skips the scope's body on the next composition even if it is invalid.
982    pub force_reuse: bool,
983    /// Runs the scope's body on the next composition even if it is not invalid.
984    pub force_recompose: bool,
985    /// What happens to the scope's content when it leaves the composition.
986    pub retention: RetentionMode,
987}