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