Skip to main content

nsh_core/
reactive.rs

1//! The reactive graph: signals, memos, effects, owners and context, with
2//! Solid 1.9's scheduling (`runUpdates`, the update and effect queues,
3//! stale owners updated before their children).
4//!
5//! The graph is generic over a [`Host`]: what a value, a computation, an
6//! equality, a cleanup and a context frame are, and how the graph is
7//! reached. JS runs on it with QuickJS values and functions (`nsh-js`);
8//! Rust components with Rust values and closures. Both share the algorithm
9//! and its guarantees.
10//!
11//! Nodes live in an arena with generations; edges are two-way with back
12//! indices, so unlinking is a swap-remove. Nothing here holds a reference
13//! to the graph across a call into the host (a computation, an equality,
14//! a cleanup, or freeing a value), which may re-enter the graph: every
15//! function takes a [`Host`] handle and reaches the graph through it with
16//! short borrows, and values leave their node before they are freed.
17
18use std::rc::Rc;
19
20/// No node (no listener, no owner).
21pub const NONE: u32 = u32::MAX;
22/// The owner of nodes made in a root that is never disposed: they are owned
23/// by nothing.
24pub const UNOWNED: u32 = u32::MAX - 1;
25/// The current owner once the owner that was current is disposed while it
26/// runs (a listener closing the view it belongs to, then going on): what is
27/// made under it is disposed at once, since what it belongs to is gone. Its
28/// slot is free to be reused, so the owner is never named by id again.
29pub const DISPOSED: u32 = u32::MAX - 2;
30
31/// Whether `owner` names a node (not [`NONE`], [`UNOWNED`] or
32/// [`DISPOSED`]).
33#[inline]
34fn is_node(owner: u32) -> bool {
35    owner < DISPOSED
36}
37
38const CLEAN: u8 = 0;
39const STALE: u8 = 1;
40const PENDING: u8 = 2;
41
42/// Runs of computations in one flush before it counts as an infinite loop.
43const MAX_RUNS: u64 = 1_000_000;
44
45/// What a node is.
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47pub enum Kind {
48    /// A value that is written.
49    Signal,
50    /// A value computed from others, cached.
51    Memo,
52    /// A render effect (runs as soon as possible, before user effects).
53    Effect,
54    /// A user effect (after the render effects).
55    UserEffect,
56    /// An owner that runs nothing.
57    Root,
58    /// A freed slot.
59    Free,
60}
61
62/// When a signal or memo counts as changed.
63#[derive(Debug)]
64pub enum Equals<C> {
65    /// The host's default ([`Host::same`]).
66    Default,
67    /// Always (every write notifies).
68    Never,
69    /// The same truthiness ([`Host::truthy`]): a condition.
70    Truthiness,
71    /// The host's comparison `C` ([`Host::custom_changed`]).
72    Custom(C),
73}
74
75/// What a graph stores and runs, and how its functions reach it.
76///
77/// # Safety
78///
79/// [`Host::graph`] returns the graph this handle names, and the
80/// implementation guarantees that the graph's functions are its only users
81/// while they hold the reference (each borrow is short and ends before the
82/// next call into the host).
83pub unsafe trait Host: Copy + 'static {
84    /// A signal's or memo's value. Owned: [`Host::dup`] makes another
85    /// reference, [`Host::free`] releases one.
86    type Value;
87    /// A computation's function.
88    type Func;
89    /// A custom comparison ([`Equals::Custom`]).
90    type Equals;
91    /// A function run when its owner runs again or is disposed.
92    type Cleanup;
93    /// A context frame's content (its key and value); dropping it releases
94    /// them.
95    type Context;
96    /// The host's own state, kept in the graph ([`Graph::data`]).
97    type Data;
98
99    /// The graph.
100    ///
101    /// # Safety
102    ///
103    /// The caller holds no other reference to the graph.
104    unsafe fn graph<'a>(self) -> &'a mut Graph<Self>;
105    /// The value of a node that has none (JS: `undefined`).
106    fn empty() -> Self::Value;
107    /// Another reference to `v`.
108    fn dup(self, v: &Self::Value) -> Self::Value;
109    /// Releases `v` (may re-enter the graph).
110    fn free(self, v: Self::Value);
111    /// Another reference to `f`.
112    fn dup_func(self, f: &Self::Func) -> Self::Func;
113    /// Releases `f`.
114    fn free_func(self, f: Self::Func);
115    /// Another reference to `e`.
116    fn dup_equals(self, e: &Self::Equals) -> Self::Equals;
117    /// Releases `e`.
118    fn free_equals(self, e: Self::Equals);
119    /// Runs computation `f` with its previous value (owned): its next
120    /// value, or `None` when it failed (the host keeps the error).
121    fn call(self, f: &Self::Func, prev: Self::Value) -> Option<Self::Value>;
122    /// Whether `a` and `b` are the same under [`Equals::Default`] (runs no
123    /// user code).
124    fn same(self, a: &Self::Value, b: &Self::Value) -> bool;
125    /// `v`'s truthiness, for [`Equals::Truthiness`] (runs no user code).
126    fn truthy(self, v: &Self::Value) -> bool;
127    /// Whether `next` counts as a change from `prev` (owned) under `e`.
128    fn custom_changed(self, e: &Self::Equals, prev: Self::Value, next: &Self::Value) -> bool;
129    /// Runs and releases cleanup `f`.
130    fn run_cleanup(self, f: Self::Cleanup);
131    /// Releases cleanup `f` without running it (a teardown).
132    fn free_cleanup(self, f: Self::Cleanup);
133    /// A flush ran away (an effect keeps changing what it reads): keep the
134    /// error to report.
135    fn runaway(self);
136}
137
138/// A context frame set by a provider, and the frame it shadows.
139pub struct Frame<H: Host> {
140    /// The frame it shadows.
141    pub parent: Option<Rc<Frame<H>>>,
142    /// Its key and value.
143    pub data: H::Context,
144}
145
146struct Node<H: Host> {
147    kind: Kind,
148    /// Bumped when the slot is reused: handles of the old node go stale.
149    generation: u32,
150    state: u8,
151    value: H::Value,
152    func: Option<H::Func>,
153    equals: Equals<H::Equals>,
154    /// The exec round of the last run (`None`: never ran).
155    updated_at: Option<u64>,
156    /// (source, its index in the source's observers)
157    sources: Vec<(u32, u32)>,
158    /// (observer, its index in the observer's sources)
159    observers: Vec<(u32, u32)>,
160    /// The owner (for a root, the one it was made under: context and
161    /// `runTop` look through it, but it does not own the root).
162    owner: u32,
163    /// The owner's generation when the node was made under it. A root
164    /// outlives the owner it was made under (that owner does not own it):
165    /// once the owner is freed its slot may name another node, which the
166    /// root must not take for its owner in `runTop` ([`Graph::owner_of`]).
167    owner_generation: u32,
168    owned: Vec<u32>,
169    cleanups: Vec<H::Cleanup>,
170    context: Option<Rc<Frame<H>>>,
171    /// Something outside the graph names the node (a JS object, a Rust
172    /// handle): its slot is freed when that goes ([`Graph::drop_handle`]).
173    handle: bool,
174    /// Disposed: runs no more (a memo keeps its value for its handle).
175    disposed: bool,
176    /// Being disposed (what it owns goes, its cleanups run): until that
177    /// ends, the node is the graph's, not its handle's.
178    disposing: bool,
179    /// Last run of this memo failed; orthogonal to `state` so upstream
180    /// invalidation still propagates through it while direct reads retry.
181    failed: bool,
182    /// Monotonic run token of the latest started execution of this node.
183    last_run: u64,
184}
185
186impl<H: Host> Node<H> {
187    fn new(kind: Kind, generation: u32) -> Self {
188        Node {
189            kind,
190            generation,
191            state: CLEAN,
192            value: H::empty(),
193            func: None,
194            equals: Equals::Default,
195            updated_at: None,
196            sources: Vec::new(),
197            observers: Vec::new(),
198            owner: NONE,
199            owner_generation: 0,
200            owned: Vec::new(),
201            cleanups: Vec::new(),
202            context: None,
203            handle: false,
204            disposed: false,
205            disposing: false,
206            failed: false,
207            last_run: 0,
208        }
209    }
210
211    fn is_computation(&self) -> bool {
212        matches!(self.kind, Kind::Memo | Kind::Effect | Kind::UserEffect)
213    }
214}
215
216/// What a freed node held, released by [`Held::free`] once the graph is no
217/// longer borrowed.
218#[must_use]
219pub struct Held<H: Host> {
220    value: H::Value,
221    func: Option<H::Func>,
222    equals: Option<H::Equals>,
223    context: Option<Rc<Frame<H>>>,
224}
225
226impl<H: Host> Held<H> {
227    /// Releases what the node held.
228    pub fn free(self, h: H) {
229        h.free(self.value);
230        if let Some(f) = self.func {
231            h.free_func(f);
232        }
233        if let Some(e) = self.equals {
234            h.free_equals(e);
235        }
236        drop(self.context);
237    }
238}
239
240/// The owner or listener that was current before a run
241/// ([`Graph::enter_owner`]), with its generation and run token.
242#[derive(Clone, Copy, Debug)]
243pub struct SavedOwner {
244    id: u32,
245    generation: u32,
246    last_run: u64,
247}
248
249/// The nodes and the scheduler's state.
250pub struct Graph<H: Host> {
251    nodes: Vec<Node<H>>,
252    free: Vec<u32>,
253    listener: u32,
254    owner: u32,
255    /// Solid's `Updates`: computations to run in this round (`None`: not
256    /// in a round).
257    updates: Option<Vec<u32>>,
258    /// Solid's `Effects`.
259    effects: Option<Vec<u32>>,
260    exec: u64,
261    runs: u64,
262    /// Monotonic per-run counter used to ignore superseded failure rollbacks.
263    run_seq: u64,
264    /// The generation a slot added at the end starts at: above every
265    /// generation of the slots [`Graph::compact`] dropped, so a handle of a
266    /// dropped node never names the node made in its place.
267    floor: u32,
268    /// Roots disposed with an owner other than the one they were made
269    /// under, by that owner, each with its generation ([`dispose_with`]).
270    companions: rustc_hash::FxHashMap<u32, Vec<(u32, u32)>>,
271    /// The host's own state.
272    pub data: H::Data,
273}
274
275impl<H: Host> Graph<H> {
276    /// An empty graph with the host's state `data`.
277    pub fn new(data: H::Data) -> Self {
278        Graph {
279            nodes: Vec::new(),
280            free: Vec::new(),
281            listener: NONE,
282            owner: NONE,
283            updates: None,
284            effects: None,
285            exec: 0,
286            runs: 0,
287            run_seq: 0,
288            floor: 1,
289            companions: rustc_hash::FxHashMap::default(),
290            data,
291        }
292    }
293
294    fn alloc(&mut self, kind: Kind) -> u32 {
295        match self.free.pop() {
296            Some(id) => {
297                let generation = self.nodes[id as usize].generation.wrapping_add(1).max(1);
298                self.nodes[id as usize] = Node::new(kind, generation);
299                id
300            }
301            None => {
302                self.nodes.push(Node::new(kind, self.floor));
303                (self.nodes.len() - 1) as u32
304            }
305        }
306    }
307
308    /// Gives back the slots a large tree used once it is gone: drops the
309    /// free slots at the end of the arena, then lets the arena's spare
310    /// room go. Freed slots are reused lowest first from then on, so those
311    /// near the end empty out and go at the next compaction. Call when no
312    /// round runs (the engine does when it is idle); a no-op otherwise.
313    pub fn compact(&mut self) {
314        if self.updates.is_some() || self.effects.is_some() || self.free.is_empty() {
315            return;
316        }
317        while let Some(n) = self.nodes.last() {
318            if n.kind != Kind::Free {
319                break;
320            }
321            self.floor = self.floor.max(n.generation.wrapping_add(1).max(1));
322            self.nodes.pop();
323        }
324        let len = self.nodes.len() as u32;
325        self.free.retain(|&id| id < len);
326        // `alloc` pops from the end: the lowest ids go first.
327        self.free.sort_unstable_by(|a, b| b.cmp(a));
328        shrink_spare(&mut self.nodes);
329        shrink_spare(&mut self.free);
330    }
331
332    /// A new signal holding `value` (owned), compared by `equals`, named by
333    /// a handle (freed with [`Graph::drop_handle`]).
334    pub fn signal(&mut self, value: H::Value, equals: Equals<H::Equals>) -> u32 {
335        let id = self.alloc(Kind::Signal);
336        let n = &mut self.nodes[id as usize];
337        let old = std::mem::replace(&mut n.value, value);
338        n.equals = equals;
339        n.handle = true;
340        // A new node's value is empty: nothing to release.
341        drop(old);
342        id
343    }
344
345    /// A new signal holding `value` (owned), compared by `equals`, owned by
346    /// the current owner: disposed with it (with no owner, it lives as long
347    /// as the graph).
348    pub fn owned_signal(&mut self, value: H::Value, equals: Equals<H::Equals>) -> u32 {
349        let id = self.alloc(Kind::Signal);
350        let owner = self.owner;
351        let n = &mut self.nodes[id as usize];
352        let old = std::mem::replace(&mut n.value, value);
353        n.equals = equals;
354        n.owner = if is_node(owner) { owner } else { NONE };
355        drop(old);
356        if is_node(owner) {
357            self.nodes[id as usize].owner_generation = self.nodes[owner as usize].generation;
358            self.nodes[owner as usize].owned.push(id);
359        }
360        id
361    }
362
363    /// Makes a computation running `func` under the current owner, with
364    /// first value `value`; it has not run yet ([`update_computation`]).
365    pub fn computation(&mut self, kind: Kind, func: H::Func, value: H::Value) -> u32 {
366        let id = self.alloc(kind);
367        let owner = self.owner;
368        let context = self.context_of(owner);
369        let n = &mut self.nodes[id as usize];
370        n.func = Some(func);
371        let old = std::mem::replace(&mut n.value, value);
372        drop(old);
373        n.state = STALE;
374        n.owner = if is_node(owner) { owner } else { NONE };
375        n.context = context;
376        if is_node(owner) {
377            self.nodes[id as usize].owner_generation = self.nodes[owner as usize].generation;
378            self.nodes[owner as usize].owned.push(id);
379        }
380        id
381    }
382
383    /// A new root owner under the current owner (context passes through
384    /// it; the current owner does not own it).
385    pub fn root(&mut self) -> u32 {
386        let current = self.owner;
387        let id = self.alloc(Kind::Root);
388        let context = self.context_of(current);
389        let n = &mut self.nodes[id as usize];
390        n.owner = if current == DISPOSED { NONE } else { current };
391        n.context = context;
392        if is_node(current) {
393            self.nodes[id as usize].owner_generation = self.nodes[current as usize].generation;
394        }
395        id
396    }
397
398    /// The context frames owner `owner` sees, innermost first (none for
399    /// [`NONE`], [`UNOWNED`] and [`DISPOSED`]).
400    pub fn context_of(&self, owner: u32) -> Option<Rc<Frame<H>>> {
401        if !is_node(owner) {
402            return None;
403        }
404        self.nodes[owner as usize].context.clone()
405    }
406
407    /// The context frames the current owner sees, innermost first.
408    pub fn context(&self) -> Option<Rc<Frame<H>>> {
409        self.context_of(self.owner)
410    }
411
412    /// Sets a context frame on the current owner: it and what is made under
413    /// it from now on see `data`. Returns the frame it replaced, to drop
414    /// once the graph is no longer borrowed (`None` without an owner, and
415    /// `data` comes back).
416    pub fn provide(&mut self, data: H::Context) -> Result<Option<Rc<Frame<H>>>, H::Context> {
417        let owner = self.owner;
418        if !is_node(owner) {
419            return Err(data);
420        }
421        let parent = self.nodes[owner as usize].context.clone();
422        let frame = Rc::new(Frame { parent, data });
423        Ok(self.nodes[owner as usize].context.replace(frame))
424    }
425
426    /// Whether handle (`id`, `generation`) still names its node; `mask`
427    /// keeps the bits of the generation a handle holds.
428    pub fn live(&self, id: u32, generation: u32, mask: u32) -> bool {
429        self.nodes
430            .get(id as usize)
431            .is_some_and(|n| n.generation & mask == generation & mask && n.kind != Kind::Free)
432    }
433
434    /// The slots in use and all slots (freed ones are reused).
435    pub fn slots(&self) -> (usize, usize) {
436        (self.nodes.len() - self.free.len(), self.nodes.len())
437    }
438
439    /// Node `id`'s generation (for a handle).
440    pub fn generation(&self, id: u32) -> u32 {
441        self.nodes[id as usize].generation
442    }
443
444    /// The owner of node `id` (for a root, the slot it was made under: an
445    /// owner that re-makes its root in place, as a region does, is found
446    /// through it again).
447    pub fn parent(&self, id: u32) -> u32 {
448        self.nodes[id as usize].owner
449    }
450
451    /// Node `id`'s owner for `runTop`, or [`NONE`] once the slot it named
452    /// was freed (a root whose owner went: the slot may name another node
453    /// now, maybe one under the root itself, which would close the walk up
454    /// the owners into a loop).
455    fn owner_of(&self, id: u32) -> u32 {
456        let n = &self.nodes[id as usize];
457        let owner = n.owner;
458        if !is_node(owner) {
459            return owner;
460        }
461        let o = &self.nodes[owner as usize];
462        if o.kind == Kind::Free || o.generation != n.owner_generation {
463            NONE
464        } else {
465            owner
466        }
467    }
468
469    /// Node `id`'s kind.
470    pub fn kind(&self, id: u32) -> Kind {
471        self.nodes[id as usize].kind
472    }
473
474    /// Whether node `id` was disposed.
475    pub fn disposed(&self, id: u32) -> bool {
476        self.nodes[id as usize].disposed
477    }
478
479    /// Whether computation `id` is to run again before its value is
480    /// current (what it reads changed, here or upstream).
481    pub(crate) fn outdated(&self, id: u32) -> bool {
482        self.nodes[id as usize].state != CLEAN
483    }
484
485    /// Whether slot `id` no longer holds the node of generation
486    /// `generation`: freed, or made another node since.
487    fn left(&self, id: u32, generation: u32) -> bool {
488        let n = &self.nodes[id as usize];
489        n.kind == Kind::Free || n.generation != generation
490    }
491
492    /// Node `id`'s value (untracked; a disposed memo keeps its last one).
493    pub fn value(&self, id: u32) -> &H::Value {
494        &self.nodes[id as usize].value
495    }
496
497    /// Replaces node `id`'s value with `value`, without notifying: the old
498    /// one, to change and write back ([`write`]).
499    pub fn replace_value(&mut self, id: u32, value: H::Value) -> H::Value {
500        std::mem::replace(&mut self.nodes[id as usize].value, value)
501    }
502
503    /// Node `id`'s custom comparison, if it has one.
504    pub fn custom_equals(&self, id: u32) -> Option<&H::Equals> {
505        match &self.nodes[id as usize].equals {
506            Equals::Custom(e) => Some(e),
507            _ => None,
508        }
509    }
510
511    /// Node `id`'s comparison.
512    pub fn set_equals(&mut self, id: u32, equals: Equals<H::Equals>) -> Equals<H::Equals> {
513        std::mem::replace(&mut self.nodes[id as usize].equals, equals)
514    }
515
516    /// Marks node `id` as named by a handle.
517    pub fn set_handle(&mut self, id: u32) {
518        self.nodes[id as usize].handle = true;
519    }
520
521    /// Whether node `id`'s handle owns what the node holds: it is freed with
522    /// the handle ([`Self::drop_handle`]), as a signal or a disposed
523    /// computation is. A live computation belongs to its owner and outlives
524    /// its handle, so what it holds is not the handle's (a garbage collector
525    /// must not count it among the handle's children); so does one being
526    /// disposed, until that ends ([`dispose`] frees it then).
527    pub fn held_by_handle(&self, id: u32) -> bool {
528        let n = &self.nodes[id as usize];
529        n.kind == Kind::Signal || (n.disposed && !n.disposing)
530    }
531
532    /// The handle of node `id` went: a signal, or a disposed computation,
533    /// is freed now (what it held comes back, to free once the graph is no
534    /// longer borrowed).
535    pub fn drop_handle(&mut self, id: u32) -> Option<Held<H>> {
536        self.nodes[id as usize].handle = false;
537        if self.held_by_handle(id) {
538            self.unlink_observers(id);
539            Some(self.release(id))
540        } else {
541            None
542        }
543    }
544
545    /// The current owner.
546    pub fn owner(&self) -> u32 {
547        self.owner
548    }
549
550    /// Sets the current owner; returns the previous one.
551    pub fn set_owner(&mut self, owner: u32) -> u32 {
552        std::mem::replace(&mut self.owner, owner)
553    }
554
555    /// Makes `owner` current for a run; returns the previous owner, to put
556    /// back with [`Self::leave_owner`].
557    pub fn enter_owner(&mut self, owner: u32) -> SavedOwner {
558        let previous = std::mem::replace(&mut self.owner, owner);
559        self.save(previous)
560    }
561
562    /// Puts back the owner [`Self::enter_owner`] saved: [`DISPOSED`] if it
563    /// was disposed meanwhile (its slot may name another node now).
564    pub fn leave_owner(&mut self, saved: SavedOwner) {
565        self.owner = self.kept(saved, DISPOSED);
566    }
567
568    /// `id` with its generation and run token, to tell after a run whether
569    /// its slot still holds that same execution ([`Self::kept`]).
570    fn save(&self, id: u32) -> SavedOwner {
571        let (generation, last_run) = if is_node(id) {
572            let n = &self.nodes[id as usize];
573            (n.generation, n.last_run)
574        } else {
575            (0, 0)
576        };
577        SavedOwner {
578            id,
579            generation,
580            last_run,
581        }
582    }
583
584    /// The node `saved` names, or `gone` if it was disposed or superseded by
585    /// a newer run since it was saved.
586    fn kept(&self, saved: SavedOwner, gone: u32) -> u32 {
587        if !is_node(saved.id) {
588            return saved.id;
589        }
590        let n = &self.nodes[saved.id as usize];
591        if n.generation == saved.generation && !n.disposed && n.last_run == saved.last_run {
592            saved.id
593        } else {
594            gone
595        }
596    }
597
598    /// The current listener (what reads track into).
599    pub fn listener(&self) -> u32 {
600        self.listener
601    }
602
603    /// Sets the current listener; returns the previous one.
604    pub fn set_listener(&mut self, listener: u32) -> u32 {
605        std::mem::replace(&mut self.listener, listener)
606    }
607
608    /// Makes `listener` current for a run; returns the previous listener,
609    /// to put back with [`Self::leave_listener`].
610    fn enter_listener(&mut self, listener: u32) -> SavedOwner {
611        let previous = std::mem::replace(&mut self.listener, listener);
612        self.save(previous)
613    }
614
615    /// Puts back the listener [`Self::enter_listener`] saved: [`NONE`] if
616    /// it was disposed meanwhile. Its slot may hold another computation by
617    /// then, which the rest of the disposed one's run would track into.
618    fn leave_listener(&mut self, saved: SavedOwner) {
619        self.listener = self.kept(saved, NONE);
620    }
621
622    /// Whether a live owner owns what runs now.
623    pub fn has_owner(&self) -> bool {
624        self.is_live_owner(self.owner)
625    }
626
627    /// Whether node `id` is a live owner (not disposed).
628    pub fn is_live_owner(&self, id: u32) -> bool {
629        is_node(id) && !self.nodes[id as usize].disposed
630    }
631
632    /// Adds cleanup `f` to the current owner; gives it back without one
633    /// (and under [`DISPOSED`], where the host runs it at once).
634    pub fn on_cleanup(&mut self, f: H::Cleanup) -> Result<(), H::Cleanup> {
635        if !is_node(self.owner) {
636            return Err(f);
637        }
638        self.nodes[self.owner as usize].cleanups.push(f);
639        Ok(())
640    }
641
642    /// Removes from owner `id` the first cleanup `matches` accepts, which
643    /// then never runs: what it was to undo ended by itself.
644    pub fn remove_cleanup(
645        &mut self,
646        id: u32,
647        matches: impl Fn(&H::Cleanup) -> bool,
648    ) -> Option<H::Cleanup> {
649        if !is_node(id) {
650            return None;
651        }
652        let cleanups = &mut self.nodes.get_mut(id as usize)?.cleanups;
653        let at = cleanups.iter().position(matches)?;
654        Some(cleanups.remove(at))
655    }
656
657    /// The number of cleanups node `id` holds.
658    #[cfg(test)]
659    pub(crate) fn cleanup_count(&self, id: u32) -> usize {
660        self.nodes.get(id as usize).map_or(0, |n| n.cleanups.len())
661    }
662
663    /// Whether a round is running (its end reports errors).
664    pub fn in_round(&self) -> bool {
665        self.updates.is_some()
666    }
667
668    /// Whether effects are being collected (a new user effect waits for
669    /// them).
670    pub fn collecting_effects(&self) -> bool {
671        self.effects.is_some()
672    }
673
674    /// A round ended: the runaway count starts over.
675    pub fn reset_runs(&mut self) {
676        self.runs = 0;
677    }
678
679    /// Queues user effect `id` after the render effects of the round.
680    pub fn queue_effect(&mut self, id: u32) {
681        match &mut self.effects {
682            Some(q) => q.push(id),
683            None => self.effects = Some(vec![id]),
684        }
685    }
686
687    fn queue_update(&mut self, id: u32) {
688        match &mut self.updates {
689            Some(q) => q.push(id),
690            None => self.updates = Some(vec![id]),
691        }
692    }
693
694    fn track(&mut self, id: u32) {
695        let l = self.listener;
696        if l == NONE || l == UNOWNED {
697            return;
698        }
699        // Only a live computation takes sources: it unlinks them before its
700        // slot is freed (when it runs again or is disposed). One disposed
701        // during its own run stays the listener until the run returns; one
702        // disposed in a nested run is not put back (`leave_listener`), as
703        // its slot may hold another node by then.
704        let n = &self.nodes[l as usize];
705        if n.disposed || !n.is_computation() {
706            return;
707        }
708        // Repeated reads of the same source make one edge.
709        if self.nodes[l as usize]
710            .sources
711            .last()
712            .is_some_and(|&(s, _)| s == id)
713        {
714            return;
715        }
716        let slot = self.nodes[id as usize].observers.len() as u32;
717        let back = self.nodes[l as usize].sources.len() as u32;
718        self.nodes[l as usize].sources.push((id, slot));
719        self.nodes[id as usize].observers.push((l, back));
720    }
721
722    fn unlink_sources(&mut self, id: u32) {
723        while let Some((src, slot)) = self.nodes[id as usize].sources.pop() {
724            let obs = &mut self.nodes[src as usize].observers;
725            let Some(last) = obs.pop() else { continue };
726            if (slot as usize) < obs.len() {
727                obs[slot as usize] = last;
728                self.nodes[last.0 as usize].sources[last.1 as usize].1 = slot;
729            }
730        }
731    }
732
733    fn unlink_observers(&mut self, id: u32) {
734        while let Some((o, slot)) = self.nodes[id as usize].observers.pop() {
735            let srcs = &mut self.nodes[o as usize].sources;
736            let Some(last) = srcs.pop() else { continue };
737            if (slot as usize) < srcs.len() {
738                srcs[slot as usize] = last;
739                self.nodes[last.0 as usize].observers[last.1 as usize].1 = slot;
740            }
741        }
742    }
743
744    /// Frees slot `id`: what it held, to be freed by the caller once no
745    /// borrow of the graph is live.
746    fn release(&mut self, id: u32) -> Held<H> {
747        let n = &mut self.nodes[id as usize];
748        let held = Held {
749            value: std::mem::replace(&mut n.value, H::empty()),
750            func: n.func.take(),
751            equals: match std::mem::replace(&mut n.equals, Equals::Default) {
752                Equals::Custom(e) => Some(e),
753                _ => None,
754            },
755            context: n.context.take(),
756        };
757        n.kind = Kind::Free;
758        n.handle = false;
759        n.disposed = true;
760        self.free.push(id);
761        held
762    }
763
764    /// Solid's `markDownstream`.
765    fn mark_downstream(&mut self, id: u32) {
766        let mut i = 0;
767        while i < self.nodes[id as usize].observers.len() {
768            let o = self.nodes[id as usize].observers[i].0;
769            i += 1;
770            if self.nodes[o as usize].state == CLEAN && !self.nodes[o as usize].disposed {
771                self.nodes[o as usize].state = PENDING;
772                if self.nodes[o as usize].kind == Kind::Memo {
773                    self.queue_update(o);
774                } else {
775                    self.queue_effect(o);
776                }
777                if !self.nodes[o as usize].observers.is_empty() {
778                    self.mark_downstream(o);
779                }
780            }
781        }
782    }
783
784    /// Frees every value the graph holds, for a teardown (no host code runs
785    /// from here on but releasing).
786    pub fn free_all(&mut self, h: H) {
787        for n in &mut self.nodes {
788            if n.kind == Kind::Free {
789                continue;
790            }
791            h.free(std::mem::replace(&mut n.value, H::empty()));
792            if let Some(f) = n.func.take() {
793                h.free_func(f);
794            }
795            if let Equals::Custom(e) = std::mem::replace(&mut n.equals, Equals::Default) {
796                h.free_equals(e);
797            }
798            for f in n.cleanups.drain(..) {
799                h.free_cleanup(f);
800            }
801            n.context = None;
802            n.kind = Kind::Free;
803        }
804        self.companions.clear();
805    }
806
807    /// Makes live root `root` go with live owner `owner` ([`dispose_with`]).
808    fn add_companion(&mut self, root: u32, owner: u32) {
809        if !self.is_live_owner(root) || !self.is_live_owner(owner) || root == owner {
810            return;
811        }
812        let entry = (root, self.nodes[root as usize].generation);
813        let list = self.companions.entry(owner).or_default();
814        // Those that went on their own are dropped as the list grows.
815        if list.len() == list.capacity() {
816            let nodes = &self.nodes;
817            list.retain(|&(id, generation)| {
818                let n = &nodes[id as usize];
819                n.kind != Kind::Free && n.generation == generation && !n.disposed
820            });
821        }
822        list.push(entry);
823    }
824}
825
826/// Lets `v`'s room go when it is more than twice what it holds (and more
827/// than a small arena's), keeping a quarter more for growth.
828fn shrink_spare<T>(v: &mut Vec<T>) {
829    const SMALL: usize = 1024;
830    if v.capacity() > SMALL && v.capacity() > 2 * v.len() {
831        v.shrink_to((v.len() + v.len() / 4).max(SMALL));
832    }
833}
834
835/// The graph of `h`, for one short borrow.
836#[inline]
837fn g<'a, H: Host>(h: H) -> &'a mut Graph<H> {
838    // SAFETY: every borrow in this module is short and ends before the next
839    // call into the host, as `Host`'s contract requires.
840    unsafe { h.graph() }
841}
842
843/// Solid's `runUpdates`: runs `f`, then the queued computations and
844/// effects (unless a round is running already: they join it). `init` (a
845/// root, `runWithOwner`): what `f` makes runs at once rather than queued;
846/// only effects wait for the end.
847pub fn run_updates<H: Host, R>(h: H, init: bool, f: impl FnOnce() -> R) -> R {
848    let Some(wait) = begin_updates(h, init) else {
849        return f();
850    };
851    let r = f();
852    end_updates(h, wait);
853    r
854}
855
856/// The start of a [`run_updates`] round, out of line so the generic
857/// function is little more than its closure (one per closure, hundreds in
858/// all): `None` inside a running round, else whether the effects wait for
859/// an outer round.
860#[cfg_attr(target_arch = "wasm32", inline(never))]
861fn begin_updates<H: Host>(h: H, init: bool) -> Option<bool> {
862    let graph = g(h);
863    if graph.updates.is_some() {
864        return None;
865    }
866    if !init {
867        graph.updates = Some(Vec::new());
868    }
869    let wait = if graph.effects.is_some() {
870        true
871    } else {
872        graph.effects = Some(Vec::new());
873        false
874    };
875    graph.exec += 1;
876    Some(wait)
877}
878
879/// The end of a [`run_updates`] round.
880#[cfg_attr(target_arch = "wasm32", inline(never))]
881fn end_updates<H: Host>(h: H, wait: bool) {
882    complete_updates(h, wait);
883    if !wait {
884        // The round ended: the runaway count starts over. The JS host also
885        // resets it when a call returns; Rust components make no such call.
886        g(h).reset_runs();
887    }
888}
889
890/// Solid's `completeUpdates`. Solid runs the effects in a new round, whose
891/// end runs the effects that round queued, and so on: here that recursion
892/// is a loop (the same order), so an effect that keeps changing what it
893/// reads ends in the runaway error, not in a stack overflow.
894fn complete_updates<H: Host>(h: H, wait: bool) {
895    run_queued_updates(h);
896    if wait {
897        return;
898    }
899    loop {
900        let graph = g(h);
901        let effects = graph.effects.take().unwrap_or_default();
902        if effects.is_empty() {
903            break;
904        }
905        // `run_updates(false, || run_effects(..))` at the end of a round:
906        // no round runs, and the effects were taken.
907        graph.updates = Some(Vec::new());
908        graph.effects = Some(Vec::new());
909        graph.exec += 1;
910        run_effects(h, &effects);
911        run_queued_updates(h);
912    }
913}
914
915/// Runs the computations queued in the round, and ends it.
916fn run_queued_updates<H: Host>(h: H) {
917    let mut i = 0;
918    while let Some(next) = g(h).updates.as_ref().and_then(|q| q.get(i).copied()) {
919        i += 1;
920        if !count_run(h) {
921            break;
922        }
923        run_top(h, next);
924    }
925    g(h).updates = None;
926}
927
928/// Counts a run; false (with an error) once a flush runs away.
929fn count_run<H: Host>(h: H) -> bool {
930    let graph = g(h);
931    graph.runs += 1;
932    if graph.runs <= MAX_RUNS {
933        return true;
934    }
935    graph.updates = Some(Vec::new());
936    graph.effects = None;
937    h.runaway();
938    false
939}
940
941/// Solid's `runEffects` with user effects after the render effects.
942fn run_effects<H: Host>(h: H, effects: &[u32]) {
943    for user in [false, true] {
944        for &e in effects {
945            let kind = g(h).nodes[e as usize].kind;
946            if (kind == Kind::UserEffect) == user && count_run(h) {
947                run_top(h, e);
948            }
949        }
950    }
951}
952
953/// Solid's `runTop`: updates the node, its stale owners first.
954fn run_top<H: Host>(h: H, id: u32) {
955    let graph = g(h);
956    let node = &graph.nodes[id as usize];
957    if node.state == CLEAN || node.disposed || !node.is_computation() {
958        return;
959    }
960    if node.state == PENDING {
961        return look_upstream(h, id, NONE);
962    }
963    let exec = graph.exec;
964    // Owners needing an update run outermost first, then the node itself.
965    // Usually none needs one, and the empty list allocates nothing.
966    let mut ancestors = Vec::new();
967    let mut at = graph.owner_of(id);
968    while is_node(at) {
969        let n = &graph.nodes[at as usize];
970        if n.updated_at.is_some_and(|t| t >= exec) {
971            break;
972        }
973        if n.state != CLEAN && n.is_computation() {
974            ancestors.push(at);
975        }
976        at = graph.owner_of(at);
977    }
978    for node in ancestors.into_iter().rev().chain(std::iter::once(id)) {
979        let n = &g(h).nodes[node as usize];
980        if n.disposed {
981            continue;
982        }
983        if n.state == STALE {
984            update_computation(h, node);
985        } else if n.state == PENDING {
986            let updates = g(h).updates.take();
987            run_updates(h, false, || look_upstream(h, node, id));
988            g(h).updates = updates;
989        }
990    }
991}
992
993/// Solid's `lookUpstream`: brings the stale memos `id` reads up to date.
994fn look_upstream<H: Host>(h: H, id: u32, ignore: u32) {
995    g(h).nodes[id as usize].state = CLEAN;
996    let generation = g(h).nodes[id as usize].generation;
997    let mut i = 0;
998    loop {
999        let graph = g(h);
1000        // A source's run let the node go (its slot may hold another).
1001        if graph.left(id, generation) {
1002            break;
1003        }
1004        let Some(&(source, _)) = graph.nodes[id as usize].sources.get(i) else {
1005            break;
1006        };
1007        i += 1;
1008        let s = &graph.nodes[source as usize];
1009        if s.kind != Kind::Memo {
1010            continue;
1011        }
1012        if s.state == STALE {
1013            if source != ignore && s.updated_at.is_none_or(|t| t < graph.exec) {
1014                run_top(h, source);
1015            }
1016        } else if s.state == PENDING {
1017            look_upstream(h, source, ignore);
1018        }
1019    }
1020}
1021
1022/// Solid's `updateComputation`: cleans the node and runs it again.
1023pub fn update_computation<H: Host>(h: H, id: u32) {
1024    let graph = g(h);
1025    if graph.nodes[id as usize].disposed || graph.nodes[id as usize].kind == Kind::Free {
1026        return;
1027    }
1028    let generation = g(h).nodes[id as usize].generation;
1029    g(h).nodes[id as usize].failed = false;
1030    clean_node(h, id);
1031    // A cleanup let the node go: nothing runs in its slot.
1032    if g(h).left(id, generation) {
1033        return;
1034    }
1035    let exec = g(h).exec;
1036    run_computation(h, id, exec);
1037}
1038
1039/// Solid's `runComputation`.
1040fn run_computation<H: Host>(h: H, id: u32, time: u64) {
1041    let graph = g(h);
1042    let n = &graph.nodes[id as usize];
1043    let Some(func) = n.func.as_ref().map(|f| h.dup_func(f)) else {
1044        return;
1045    };
1046    let prev = h.dup(&n.value);
1047    let generation = n.generation;
1048    // Save the previous listener/owner before advancing `last_run` so a
1049    // re-entrant run of `id` captures the outer run's token and restores
1050    // `NONE`/`DISPOSED` when it returns.
1051    let listener = graph.enter_listener(id);
1052    let owner = graph.enter_owner(id);
1053    graph.run_seq += 1;
1054    let run = graph.run_seq;
1055    let n = &mut graph.nodes[id as usize];
1056    n.failed = false;
1057    n.last_run = run;
1058    let result = h.call(&func, prev);
1059    h.free_func(func);
1060    let graph = g(h);
1061    graph.leave_listener(listener);
1062    graph.leave_owner(owner);
1063    // The run let the node go (its owner was disposed: a list letting a
1064    // cell's content go) and its slot was freed, maybe made another node
1065    // since: the result is no one's.
1066    // If this node was freed/reused OR a newer re-entrant execution of this
1067    // same node already started while `h.call` was on the stack, discard this
1068    // stale run's outcome without touching its value, `failed`, or `owned`.
1069    if graph.left(id, generation) || graph.nodes[id as usize].last_run != run {
1070        if let Some(next) = result {
1071            h.free(next);
1072        }
1073        return;
1074    }
1075    let Some(next) = result else {
1076        // Keep `state == CLEAN` so dependency writes and `mark_downstream`
1077        // still propagate through this memo normally; `failed` separately
1078        // tells direct reads to retry.
1079        let is_memo = graph.nodes[id as usize].kind == Kind::Memo;
1080        if is_memo {
1081            let owned = std::mem::take(&mut graph.nodes[id as usize].owned);
1082            for c in owned {
1083                dispose(h, c);
1084            }
1085        }
1086        let graph = g(h);
1087        if graph.left(id, generation) {
1088            return;
1089        }
1090        let n = &mut graph.nodes[id as usize];
1091        // Only publish failure if no newer execution of this node has run
1092        // during child rollback (e.g. a cleanup writing a signal and reading it).
1093        if n.last_run == run {
1094            if is_memo && !n.disposed {
1095                n.failed = true;
1096            }
1097            n.updated_at = Some(time);
1098        }
1099        return;
1100    };
1101    let n = &mut graph.nodes[id as usize];
1102    if n.disposed {
1103        // Disposed while running (its owner re-ran).
1104        h.free(next);
1105        return;
1106    }
1107    if n.updated_at.is_none_or(|t| t <= time) {
1108        let notify = n.updated_at.is_some() && n.kind == Kind::Memo;
1109        n.failed = false;
1110        n.updated_at = Some(time);
1111        if notify {
1112            write(h, id, next);
1113        } else {
1114            let old = std::mem::replace(&mut n.value, next);
1115            h.free(old);
1116        }
1117    } else {
1118        h.free(next);
1119    }
1120}
1121
1122/// Whether `next` counts as a change from node `id`'s value.
1123fn changed<H: Host>(h: H, id: u32, next: &H::Value) -> bool {
1124    let n = &g(h).nodes[id as usize];
1125    match &n.equals {
1126        Equals::Default => !h.same(&n.value, next),
1127        Equals::Never => true,
1128        Equals::Truthiness => h.truthy(&n.value) != h.truthy(next),
1129        Equals::Custom(e) => {
1130            let (e, prev) = (h.dup_equals(e), h.dup(&n.value));
1131            let changed = h.custom_changed(&e, prev, next);
1132            h.free_equals(e);
1133            changed
1134        }
1135    }
1136}
1137
1138/// Solid's `writeSignal`: takes `next` (owned).
1139pub fn write<H: Host>(h: H, id: u32, next: H::Value) {
1140    if !changed(h, id, &next) {
1141        h.free(next);
1142        return;
1143    }
1144    let graph = g(h);
1145    let old = std::mem::replace(&mut graph.nodes[id as usize].value, next);
1146    let observed = !graph.nodes[id as usize].observers.is_empty();
1147    h.free(old);
1148    if !observed {
1149        return;
1150    }
1151    run_updates(h, false, || {
1152        let graph = g(h);
1153        let mut i = 0;
1154        while i < graph.nodes[id as usize].observers.len() {
1155            let o = graph.nodes[id as usize].observers[i].0;
1156            i += 1;
1157            if graph.nodes[o as usize].disposed {
1158                continue;
1159            }
1160            if graph.nodes[o as usize].state == CLEAN {
1161                if graph.nodes[o as usize].kind == Kind::Memo {
1162                    graph.queue_update(o);
1163                } else {
1164                    graph.queue_effect(o);
1165                }
1166                if !graph.nodes[o as usize].observers.is_empty() {
1167                    graph.mark_downstream(o);
1168                }
1169            }
1170            graph.nodes[o as usize].state = STALE;
1171        }
1172    });
1173}
1174
1175/// Solid's `readSignal`: brings a memo up to date, tracks, and returns
1176/// another reference to the value.
1177pub fn read<H: Host>(h: H, id: u32) -> H::Value {
1178    let n = &g(h).nodes[id as usize];
1179    if n.kind == Kind::Memo && !n.disposed && (n.state != CLEAN || n.failed) {
1180        let (generation, last) = (n.generation, h.dup(&n.value));
1181        if n.state == STALE || n.failed {
1182            update_computation(h, id);
1183        } else {
1184            let updates = g(h).updates.take();
1185            run_updates(h, false, || look_upstream(h, id, NONE));
1186            g(h).updates = updates;
1187        }
1188        // Bringing it up to date let the memo go (what it read disposed its
1189        // owner, as a list lets a cell's content go) and freed its slot,
1190        // which another node may hold by now: the reader gets the memo's
1191        // last value, as a disposed memo keeps it, and nothing to track.
1192        if g(h).left(id, generation) {
1193            return last;
1194        }
1195        h.free(last);
1196    }
1197    let graph = g(h);
1198    if !graph.nodes[id as usize].disposed {
1199        graph.track(id);
1200    }
1201    h.dup(&graph.nodes[id as usize].value)
1202}
1203
1204/// Solid's `cleanNode`: unlinks the node's sources, disposes what it owns
1205/// and runs its cleanups.
1206fn clean_node<H: Host>(h: H, id: u32) {
1207    let generation = g(h).nodes[id as usize].generation;
1208    g(h).unlink_sources(id);
1209    // The roots that go with it first, the last added first: what they
1210    // run as they go (their cleanups) still finds what this one made.
1211    if !g(h).companions.is_empty()
1212        && let Some(companions) = g(h).companions.remove(&id)
1213    {
1214        for (c, c_generation) in companions.into_iter().rev() {
1215            if !g(h).left(c, c_generation) {
1216                dispose(h, c);
1217            }
1218        }
1219    }
1220    // What runs here may let the node go (a cleanup disposing its owner),
1221    // and its slot may hold another node by the next step: that node's
1222    // children and cleanups are not this one's.
1223    while !g(h).left(id, generation) {
1224        let Some(c) = g(h).nodes[id as usize].owned.pop() else {
1225            break;
1226        };
1227        dispose(h, c);
1228    }
1229    while !g(h).left(id, generation) {
1230        let Some(f) = g(h).nodes[id as usize].cleanups.pop() else {
1231            break;
1232        };
1233        h.run_cleanup(f);
1234    }
1235    if !g(h).left(id, generation) {
1236        g(h).nodes[id as usize].state = CLEAN;
1237    }
1238}
1239
1240/// Disposes node `id`: cleans it, unlinks it and frees it (a node named by
1241/// a handle keeps its value until the handle goes).
1242pub fn dispose<H: Host>(h: H, id: u32) {
1243    if !is_node(id) || g(h).nodes[id as usize].disposed {
1244        return;
1245    }
1246    // Disposed before it is cleaned: what runs meanwhile (what it owns
1247    // going, its cleanups, a flush they start) neither tracks into it, runs
1248    // it again nor disposes it again. Each would leave links to its slot
1249    // once the slot is freed, or free the slot twice.
1250    let n = &mut g(h).nodes[id as usize];
1251    n.disposed = true;
1252    n.disposing = true;
1253    // Code running under it goes on under no owner it could reuse the slot
1254    // of: what it makes from now on goes at once (its cleanups' too).
1255    if g(h).owner == id {
1256        g(h).owner = DISPOSED;
1257    }
1258    clean_node(h, id);
1259    let graph = g(h);
1260    graph.unlink_observers(id);
1261    let n = &mut graph.nodes[id as usize];
1262    n.disposing = false;
1263    n.state = CLEAN;
1264    if n.handle {
1265        let func = n.func.take();
1266        let context = n.context.take();
1267        if let Some(f) = func {
1268            h.free_func(f);
1269        }
1270        drop(context);
1271    } else {
1272        graph.release(id).free(h);
1273    }
1274}
1275
1276/// Makes a memo of `func` under the current owner and runs it at once
1277/// (inside a round too: what is made while rendering reads it right away,
1278/// as in Solid without transitions). With `handle`, something outside the
1279/// graph names it and it keeps its value after it is disposed, until
1280/// [`Graph::drop_handle`]; without, it is freed when disposed.
1281pub fn memo<H: Host>(
1282    h: H,
1283    func: H::Func,
1284    value: H::Value,
1285    equals: Equals<H::Equals>,
1286    handle: bool,
1287) -> u32 {
1288    let graph = g(h);
1289    let gone = graph.owner == DISPOSED;
1290    let id = graph.computation(Kind::Memo, func, value);
1291    graph.nodes[id as usize].equals = equals;
1292    graph.nodes[id as usize].handle = handle;
1293    if gone {
1294        dispose(h, id);
1295    } else {
1296        update_computation(h, id);
1297    }
1298    id
1299}
1300
1301/// Makes an effect of `func` under the current owner. A render effect runs
1302/// at once (inside a round too); a user effect after the render effects of
1303/// the round, or now outside one.
1304pub fn effect<H: Host>(h: H, kind: Kind, func: H::Func, value: H::Value) -> u32 {
1305    debug_assert!(matches!(kind, Kind::Effect | Kind::UserEffect));
1306    let graph = g(h);
1307    let gone = graph.owner == DISPOSED;
1308    let id = graph.computation(kind, func, value);
1309    if gone {
1310        dispose(h, id);
1311    } else if kind == Kind::UserEffect && graph.effects.is_some() {
1312        graph.queue_effect(id);
1313    } else {
1314        update_computation(h, id);
1315    }
1316    id
1317}
1318
1319/// Runs `f` with no listener (untracked).
1320pub fn untracked<H: Host, R>(h: H, f: impl FnOnce() -> R) -> R {
1321    let listener = enter_listener(h, NONE);
1322    let r = f();
1323    leave_listener(h, listener);
1324    r
1325}
1326
1327/// Makes `listener` the graph's, returning the previous one (out of line
1328/// for the generic functions around closures).
1329#[cfg_attr(target_arch = "wasm32", inline(never))]
1330fn enter_listener<H: Host>(h: H, listener: u32) -> SavedOwner {
1331    g(h).enter_listener(listener)
1332}
1333
1334/// Puts back the listener [`enter_listener`] saved (out of line as it is).
1335#[cfg_attr(target_arch = "wasm32", inline(never))]
1336fn leave_listener<H: Host>(h: H, saved: SavedOwner) {
1337    g(h).leave_listener(saved)
1338}
1339
1340/// Runs `f` as one batch: its writes apply together at the end.
1341pub fn batch<H: Host, R>(h: H, f: impl FnOnce() -> R) -> R {
1342    run_updates(h, false, f)
1343}
1344
1345/// Runs `f` under owner `owner` with no listener, as a root runs (what `f`
1346/// makes runs at once).
1347pub fn with_owner<H: Host, R>(h: H, owner: u32, f: impl FnOnce() -> R) -> R {
1348    let previous = enter_owner_untracked(h, owner);
1349    let r = run_updates(h, true, f);
1350    leave_owner_untracked(h, previous);
1351    r
1352}
1353
1354/// The start of [`with_owner`]: `owner` current, no listener; what was
1355/// before, for [`leave_owner_untracked`].
1356#[cfg_attr(target_arch = "wasm32", inline(never))]
1357fn enter_owner_untracked<H: Host>(h: H, owner: u32) -> (SavedOwner, SavedOwner) {
1358    let graph = g(h);
1359    let previous_owner = graph.enter_owner(owner);
1360    let previous_listener = graph.enter_listener(NONE);
1361    (previous_owner, previous_listener)
1362}
1363
1364/// The end of [`with_owner`]: the owner and listener before it back.
1365#[cfg_attr(target_arch = "wasm32", inline(never))]
1366fn leave_owner_untracked<H: Host>(
1367    h: H,
1368    (previous_owner, previous_listener): (SavedOwner, SavedOwner),
1369) {
1370    let graph = g(h);
1371    graph.leave_owner(previous_owner);
1372    graph.leave_listener(previous_listener);
1373}
1374
1375/// Runs `f` in a new root owner under the current one (context passes
1376/// through it); returns the root and `f`'s result. The root is disposed
1377/// with [`dispose_owner`].
1378///
1379/// Under [`DISPOSED`] there is no root: `f` runs there too (what it makes
1380/// goes at once) and the root is `DISPOSED`, which disposing ignores.
1381pub fn with_root<H: Host, R>(h: H, f: impl FnOnce() -> R) -> (u32, R) {
1382    let id = new_root(h);
1383    (id, with_owner(h, id, f))
1384}
1385
1386/// The root [`with_root`] runs under: a new one, or [`DISPOSED`].
1387#[cfg_attr(target_arch = "wasm32", inline(never))]
1388fn new_root<H: Host>(h: H) -> u32 {
1389    let graph = g(h);
1390    if graph.owner == DISPOSED {
1391        DISPOSED
1392    } else {
1393        graph.root()
1394    }
1395}
1396
1397/// [`with_root`] as if run under `owner`: what is made later (a list's
1398/// rows) sees that owner's context.
1399pub fn with_root_under<H: Host, R>(h: H, owner: u32, f: impl FnOnce() -> R) -> (u32, R) {
1400    let graph = g(h);
1401    let live = graph.is_live_owner(owner);
1402    let previous = graph.enter_owner(if live { owner } else { NONE });
1403    let r = with_root(h, f);
1404    g(h).leave_owner(previous);
1405    r
1406}
1407
1408/// Disposes root `root` with owner `owner` as well, before what `owner`
1409/// made: a root made under one owner, whose context it sees, that cannot
1410/// outlive another. Nothing when either is gone. The root may still go
1411/// first on its own.
1412pub(crate) fn dispose_with<H: Host>(h: H, root: u32, owner: u32) {
1413    g(h).add_companion(root, owner);
1414}
1415
1416/// Disposes owner `id`, untracked.
1417pub fn dispose_owner<H: Host>(h: H, id: u32) {
1418    untracked(h, || dispose(h, id));
1419}
1420
1421#[cfg(test)]
1422mod tests;