1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
use core::fmt::Debug;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::ops::{Deref, Sub};
use std::rc::{Rc, Weak};

pub use super::cutoff::Cutoff;
pub use super::incr::{Incr, WeakIncr};
pub use super::internal_observer::{ObserverError, SubscriptionToken};
pub use super::kind::expert::public as expert;
pub use super::node_update::NodeUpdate;
#[doc(inline)]
pub use super::Value;

use super::internal_observer::{ErasedObserver, InternalObserver};
use super::node::NodeId;
use super::node_update::OnUpdateHandler;
use super::scope;
use super::state::State;
use super::var::{ErasedVariable, Var as InternalVar};

#[derive(Clone)]
pub struct Observer<T: Value> {
    internal: Rc<InternalObserver<T>>,
    sentinel: Rc<()>,
}

/// Implemented as pointer equality, like [Rc::ptr_eq].
impl<T: Value> PartialEq for Observer<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.internal, &other.internal)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Update<T> {
    Initialised(T),
    Changed(T),
    Invalidated,
}
impl<T> Update<T> {
    #[inline]
    pub fn value(self) -> Option<T> {
        match self {
            Self::Initialised(t) => Some(t),
            Self::Changed(t) => Some(t),
            _ => None,
        }
    }
}
impl<T> Update<&T> {
    #[inline]
    pub fn cloned(&self) -> Update<T>
    where
        T: Clone,
    {
        match *self {
            Self::Initialised(t) => Update::Initialised(t.clone()),
            Self::Changed(t) => Update::Changed(t.clone()),
            Self::Invalidated => Update::Invalidated,
        }
    }
}

impl<T: Value> Observer<T> {
    #[inline]
    pub(crate) fn new(internal: Rc<InternalObserver<T>>) -> Self {
        Self {
            internal,
            sentinel: Rc::new(()),
        }
    }
    #[inline]
    pub fn try_get_value(&self) -> Result<T, ObserverError> {
        self.internal.try_get_value()
    }
    #[inline]
    pub fn value(&self) -> T {
        self.internal.try_get_value().unwrap()
    }

    pub fn subscribe(&self, on_update: impl FnMut(Update<&T>) + 'static) -> SubscriptionToken {
        self.try_subscribe(on_update).unwrap()
    }

    pub fn try_subscribe(
        &self,
        mut on_update: impl FnMut(Update<&T>) + 'static,
    ) -> Result<SubscriptionToken, ObserverError> {
        let handler_fn = Box::new(move |node_update: NodeUpdate<&T>| {
            let update = match node_update {
                NodeUpdate::Necessary(t) => Update::Initialised(t),
                NodeUpdate::Changed(t) => Update::Changed(t),
                NodeUpdate::Invalidated => Update::Invalidated,
                NodeUpdate::Unnecessary => {
                    panic!("Incremental bug -- Observer subscription got NodeUpdate::Unnecessary")
                }
            };
            on_update(update)
        });
        let state = self
            .internal
            .incr_state()
            .ok_or(ObserverError::ObservingInvalid)?;
        let now = state.stabilisation_num.get();
        let handler = OnUpdateHandler::new(now, handler_fn);
        let token = self.internal.subscribe(handler)?;
        let node = self.internal.observing_erased();
        let state = node.state();
        node.handle_after_stabilisation(&state);
        Ok(token)
    }

    #[inline]
    pub fn state(&self) -> WeakState {
        self.internal
            .incr_state()
            .map_or_else(|| WeakState { inner: Weak::new() }, |s| s.public_weak())
    }

    #[inline]
    pub fn unsubscribe(&self, token: SubscriptionToken) -> Result<(), ObserverError> {
        self.internal.unsubscribe(token)
    }

    pub fn save_dot_to_file(&self, named: &str) {
        let node = self.internal.observing_erased();
        super::node::save_dot_to_file(&mut core::iter::once(node), named).unwrap();
    }

    pub fn save_dot_to_string(&self) -> String {
        let node = self.internal.observing_erased();
        let mut buf = String::new();
        super::node::save_dot(&mut buf, &mut core::iter::once(node)).unwrap();
        buf
    }

    pub fn disallow_future_use(&self) {
        let Some(state) = self.internal.incr_state() else {
            return;
        };
        self.internal.disallow_future_use(&state);
    }
}

impl<T: Value> Drop for Observer<T> {
    fn drop(&mut self) {
        // all_observers holds another strong reference to internal. but we can be _sure_ we're the last public::Observer by using a sentinel Rc.
        if Rc::strong_count(&self.sentinel) <= 1 {
            if let Some(state) = self.internal.incr_state() {
                // causes it to eventually be dropped
                self.internal.disallow_future_use(&state);
            } else {
                // if state is already dead, or is currently in the process of being dropped and
                // has triggered Observer::drop because an Observer was owned by some other node
                // by being used in its map() function etc (ugly, I know) then we don't need to
                // do disallow_future_use.
                // We'll just write this to be sure?
                self.internal
                    .state
                    .set(super::internal_observer::ObserverState::Disallowed);
            }
        }
    }
}

// Just to hide the Rc in the interface
#[derive(Clone)]
pub struct Var<T: Value> {
    internal: Rc<InternalVar<T>>,
    sentinel: Rc<()>,
    // for the Deref impl
    watch: Incr<T>,
}

impl<T: Value> fmt::Debug for Var<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut tuple = f.debug_tuple("Var");
        let internal = self.internal.value.borrow();
        tuple.field(&self.id()).field(&*internal).finish()
    }
}

impl<T: Value> PartialEq for Var<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl<T: Value> Deref for Var<T> {
    type Target = Incr<T>;
    fn deref(&self) -> &Self::Target {
        &self.watch
    }
}

impl<T: Value> Var<T> {
    pub(crate) fn new(internal: Rc<InternalVar<T>>) -> Self {
        Self {
            watch: internal.watch(),
            internal,
            sentinel: Rc::new(()),
        }
    }

    #[inline]
    pub fn set(&self, value: T) {
        self.internal.set(value)
    }

    #[inline]
    pub fn was_changed_during_stabilisation(&self) -> bool {
        self.internal.was_changed_during_stabilisation()
    }

    /// Takes the current value, replaces it using the function provided,
    /// and queues a recompute.
    ///
    /// Must be `T: Default` as we need to move out of the stored value, and
    /// `std::mem::take` lets us avoid cloning.
    #[inline]
    pub fn update(&self, f: impl FnOnce(T) -> T)
    where
        T: Default,
    {
        self.internal.update(f)
    }

    /// Like `RefCell::replace_with`. You get a mutable reference to the old
    /// value, your closure returns a new one, and you get back the old value
    /// (with any modifications you made to it during the closure).
    #[inline]
    pub fn replace_with(&self, f: impl FnOnce(&mut T) -> T) -> T {
        self.internal.replace_with(|mutable| f(mutable))
    }

    /// Like `RefCell::replace`.
    #[inline]
    pub fn replace(&self, value: T) -> T {
        self.internal.replace_with(|_| value)
    }

    /// Gives you a mutable reference to the variable, you do what you wish,
    /// and afterwards queues a recompute.
    #[inline]
    pub fn modify(&self, f: impl FnOnce(&mut T)) {
        self.internal.modify(f);
    }
    #[inline]
    pub fn get(&self) -> T {
        self.internal.get()
    }
    #[inline]
    pub fn watch(&self) -> Incr<T> {
        self.watch.clone()
    }
    #[inline]
    pub fn id(&self) -> NodeId {
        self.internal.node_id.get()
    }
}

impl<T: Value> Drop for Var<T> {
    fn drop(&mut self) {
        tracing::trace!("dropping public::Var with id {:?}", self.id());
        // one is for us; one is for the watch node.
        // if it's down to 2 (i.e. all public::Vars have been dropped),
        // then we need to break the Rc cycle between Var & Node (via Kind::Var(Rc<...>)).
        //
        // we can be _sure_ we're the last public::Var by using a sentinel Rc.
        // i.e. this Var will never get set again.
        if Rc::strong_count(&self.sentinel) <= 1 {
            if let Some(state) = self.internal.state.upgrade() {
                // we add the var to a delay queue, in order to ensure that
                // `self.internal.break_rc_cyle()` happens after any potential use
                // via set_during_stabilisation.
                // See `impl Drop for State` for more.
                let mut dead_vars = state.dead_vars.borrow_mut();
                dead_vars.push(self.internal.erased());
            } else {
                // no stabilise will ever run, so we don't need to add this to a delay queue
                self.internal.break_rc_cycle();
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct IncrState {
    pub(crate) inner: Rc<State>,
}

impl Default for IncrState {
    fn default() -> Self {
        Self::new()
    }
}

/// Implemented as pointer equality, like [Rc::ptr_eq].
impl PartialEq for IncrState {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.ptr_eq(other)
    }
}

impl IncrState {
    pub fn new() -> Self {
        let inner = State::new();
        Self { inner }
    }
    pub fn new_with_height(max_height: usize) -> Self {
        let inner = State::new_with_height(max_height);
        Self { inner }
    }

    #[inline]
    pub fn ptr_eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.inner, &other.inner)
    }

    #[inline]
    pub fn weak(&self) -> WeakState {
        WeakState {
            inner: Rc::downgrade(&self.inner),
        }
    }

    pub fn add_weak_map<S: WeakMap + 'static>(&self, weak_map: Rc<RefCell<S>>) {
        self.inner.add_weak_map(weak_map)
    }

    pub fn weak_memoize_fn<I: Hash + Eq + Clone + 'static, T: Value>(
        &self,
        mut f: impl FnMut(I) -> Incr<T> + Clone,
    ) -> impl FnMut(I) -> Incr<T> + Clone {
        // // we define this inside the generic function.
        // // so it's a new type for every T!
        // slotmap::new_key_type! { struct TKey; }

        let storage: WeakHashMap<I, T> = WeakHashMap::default();
        let storage: Rc<RefCell<WeakHashMap<I, T>>> = Rc::new(RefCell::new(storage));
        self.add_weak_map(storage.clone());

        let weak_state = self.weak();

        // Function f is run in the scope you called weak_memoize_fn in.
        let creation_scope = self.current_scope();

        move |i| {
            let storage_ = storage.borrow();
            if storage_.contains_key(&i) {
                let occ = storage_.get(&i).unwrap();
                let incr = occ.upgrade();
                if let Some(found_strong) = incr {
                    return found_strong;
                }
            }
            // don't want f to get a BorrowMutError if it's recursive
            drop(storage_);
            let val = weak_state
                .upgrade()
                .unwrap()
                .within_scope(creation_scope.clone(), || f(i.clone()));
            let mut storage_ = storage.borrow_mut();
            storage_.insert(i, val.weak());
            val
        }
    }

    /// Returns true if there is nothing to do. In particular, this allows you to
    /// find a fixed point in a computation that sets variables during stabilisation.
    #[inline]
    pub fn is_stable(&self) -> bool {
        self.inner.is_stable()
    }

    /// Propagates changes in the graph.
    ///
    /// ```
    /// let state = incremental::IncrState::new();
    /// let var = state.var(5);
    /// let mapped = var.map(|&x| x + 10);
    /// let obs = mapped.observe();
    ///
    /// // Observers can't be used until after they are held through a stabilise
    /// assert!(obs.try_get_value().is_err());
    /// state.stabilise();
    /// assert_eq!(obs.value(), 15);
    ///
    /// var.set(10);
    /// assert_eq!(obs.value(), 15, "No change until stabilise");
    ///
    /// state.stabilise();
    /// assert_eq!(obs.value(), 20, "Now it changes");
    /// ```
    ///
    /// This only affects nodes that are transitively being observed by an Observer.
    /// If you create some incremental nodes, changes are not propagated you call `.observe()` on
    /// one of them and keep that observer (i.e. don't drop it) over a stabilise() call.
    ///
    ///
    /// ### Panics: recursive stabilisation
    ///
    /// If you are currently in the middle of stabilising, you cannot stabilise
    /// again, and such an attempt will panic.
    ///
    /// Examples of code that is executed during stabilisation, in which you must not
    /// call stabilise again:
    ///
    /// - A mapping function, e.g. `incr.map(|_| { /* in here */ })`
    /// - A subscription, i.e. `observer.subscribe(|_| { /* in here */ })`
    /// - Any call stack deep inside one of those two.
    ///
    ///
    /// ### Working with other event loops and schedulers
    ///
    /// If you are using Incremental as state management for a React-style web app, for example
    /// [`yew`](https://crates.io/crates/yew), then consider the following pattern:
    ///
    /// - Event handlers, like onclick, can call stabilise.
    /// - Incremental subscriptions dirty components using whatever API you're provided.
    /// - The scheduler, e.g. yew's scheduler, runs actual component updates on the "next tick"
    ///   of the main JavaScript VM event loop. They all do this.
    ///
    /// The overall effect is that any further stabilises (e.g. create an observer and stabilise it
    /// when instantiating a yew component) are postponed until the next tick. The next tick
    /// is its own fresh call stack. So the previous stabilise is allowed to completely finish
    /// first.
    pub fn stabilise(&self) {
        self.inner.stabilise();
    }

    /// Returns true if the current thread of execution is inside a stabilise call.
    /// Useful because [IncrState::stabilise] panics if you call
    /// stabilise recursively, so this helps avoid doing so.
    #[inline]
    pub fn is_stabilising(&self) -> bool {
        self.inner.is_stabilising()
    }

    /// Stabilise, and also write out each step of the stabilisation as a GraphViz dot file.
    pub fn stabilise_debug(&self, dot_file_prefix: &str) {
        self.inner.stabilise_debug(Some(dot_file_prefix));
    }

    /// An incremental that never changes. This is more efficient than just using a Var and not
    /// mutating it, and also clarifies intent. Typically you will use this to "lift" `T` into
    /// `Incr<T>` when you are calling code that takes an `Incr<T>`.
    #[inline]
    pub fn constant<T: Value>(&self, value: T) -> Incr<T> {
        self.inner.constant(value)
    }

    pub fn fold<F, T: Value, R: Value>(&self, vec: Vec<Incr<T>>, init: R, f: F) -> Incr<R>
    where
        F: FnMut(R, &T) -> R + 'static,
    {
        self.inner.fold(vec, init, f)
    }

    pub fn var<T: Value>(&self, value: T) -> Var<T> {
        self.inner.var_in_scope(value, scope::Scope::Top)
    }

    pub fn var_current_scope<T: Value>(&self, value: T) -> Var<T> {
        self.inner.var_in_scope(value, self.inner.current_scope())
    }

    pub fn unsubscribe(&self, token: SubscriptionToken) {
        self.inner.unsubscribe(token)
    }

    pub fn set_max_height_allowed(&self, new_max_height: usize) {
        self.inner.set_max_height_allowed(new_max_height)
    }

    pub fn within_scope<R>(&self, scope: Scope, f: impl FnOnce() -> R) -> R {
        self.inner.within_scope(scope.0, f)
    }

    #[inline]
    pub fn current_scope(&self) -> Scope {
        Scope(self.inner.current_scope())
    }

    pub fn save_dot_to_file(&self, named: &str) {
        self.inner.save_dot_to_file(named)
    }

    pub fn stats(&self) -> Stats {
        Stats {
            created: self.inner.num_nodes_created.get(),
            changed: self.inner.num_nodes_changed.get(),
            recomputed: self.inner.num_nodes_recomputed.get(),
            invalidated: self.inner.num_nodes_invalidated.get(),
            became_necessary: self.inner.num_nodes_became_necessary.get(),
            became_unnecessary: self.inner.num_nodes_became_unnecessary.get(),
            necessary: self.inner.num_nodes_became_necessary.get()
                - self.inner.num_nodes_became_unnecessary.get(),
        }
    }
}

/// Type to avoid Rc cyles on IncrState
#[derive(Debug, Clone)]
pub struct WeakState {
    pub(crate) inner: Weak<State>,
}

/// Implemented as pointer equality, like [Weak::ptr_eq].
impl PartialEq for WeakState {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.ptr_eq(other)
    }
}

impl WeakState {
    #[inline]
    pub fn ptr_eq(&self, other: &Self) -> bool {
        self.inner.ptr_eq(&other.inner)
    }
    #[inline]
    pub fn strong_count(&self) -> usize {
        self.inner.strong_count()
    }
    #[inline]
    pub fn weak_count(&self) -> usize {
        self.inner.weak_count()
    }

    pub(crate) fn upgrade_inner(&self) -> Option<Rc<State>> {
        self.inner.upgrade()
    }

    /// Much like [std::rc::Weak::upgrade].
    ///
    /// NOTE: If you are using WeakState so that it can be stored inside an incremental (e.g.
    /// `incr.bind(move |_| weak_state.constant(5))` or `observer.subscribe()`), then you need
    /// to be a bit careful about what you do with that WeakState. Upgrading it just gives you
    /// an IncrState, which is capable of calling `stabilise` and panicking because you can't
    /// stabilise recursively. So it may be best to keep it as `WeakState`, wherever possible.
    ///
    #[inline]
    pub fn upgrade(&self) -> Option<IncrState> {
        Some(IncrState {
            inner: self.upgrade_inner()?,
        })
    }

    #[doc(hidden)]
    pub fn print_heap(&self) {
        let inner = self.upgrade_inner().unwrap();
        println!("{:?}", inner.recompute_heap);
    }

    /// See [IncrState::constant]
    #[inline]
    pub fn constant<T: Value>(&self, value: T) -> Incr<T> {
        self.upgrade().unwrap().constant(value)
    }

    pub fn fold<F, T: Value, R: Value>(&self, vec: Vec<Incr<T>>, init: R, f: F) -> Incr<R>
    where
        F: FnMut(R, &T) -> R + 'static,
    {
        self.inner.upgrade().unwrap().fold(vec, init, f)
    }

    pub fn var<T: Value>(&self, value: T) -> Var<T> {
        self.inner
            .upgrade()
            .unwrap()
            .var_in_scope(value, scope::Scope::Top)
    }

    pub fn var_current_scope<T: Value>(&self, value: T) -> Var<T> {
        let inner = self.inner.upgrade().unwrap();
        inner.var_in_scope(value, inner.current_scope())
    }

    pub fn within_scope<R>(&self, scope: Scope, f: impl FnOnce() -> R) -> R {
        self.inner.upgrade().unwrap().within_scope(scope.0, f)
    }

    #[inline]
    pub fn current_scope(&self) -> Scope {
        Scope(self.inner.upgrade().unwrap().current_scope())
    }

    pub fn save_dot_to_file(&self, named: &str) {
        self.inner.upgrade().unwrap().save_dot_to_file(named)
    }

    pub fn save_dot_to_string(&self) -> String {
        self.inner.upgrade().unwrap().save_dot_to_string()
    }

    pub fn unsubscribe(&self, token: SubscriptionToken) {
        self.inner.upgrade().unwrap().unsubscribe(token)
    }
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Stats {
    pub created: usize,
    pub changed: usize,
    pub recomputed: usize,
    pub invalidated: usize,
    pub became_necessary: usize,
    pub became_unnecessary: usize,
    pub necessary: usize,
}

#[derive(Copy, Clone, PartialEq, Eq, Default)]
pub struct StatsDiff {
    pub created: isize,
    pub changed: isize,
    pub recomputed: isize,
    pub invalidated: isize,
    pub became_necessary: isize,
    pub became_unnecessary: isize,
    pub necessary: isize,
}

impl Debug for StatsDiff {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut f = f.debug_struct("StatsDiff");
        let mut field = |name: &str, x: isize| {
            if x != 0 {
                f.field(name, &x);
            }
        };
        field("created", self.created);
        field("changed", self.changed);
        field("recomputed", self.recomputed);
        field("invalidated", self.invalidated);
        field("became_necessary", self.became_necessary);
        field("became_unnecessary", self.became_unnecessary);
        field("necessary", self.necessary);
        f.finish()
    }
}

impl Stats {
    pub fn diff(&self, other: Self) -> StatsDiff {
        StatsDiff {
            created: self.created as isize - other.created as isize,
            changed: self.changed as isize - other.changed as isize,
            recomputed: self.recomputed as isize - other.recomputed as isize,
            invalidated: self.invalidated as isize - other.invalidated as isize,
            became_necessary: self.became_necessary as isize - other.became_necessary as isize,
            became_unnecessary: self.became_unnecessary as isize
                - other.became_unnecessary as isize,
            necessary: self.necessary as isize - other.necessary as isize,
        }
    }
}

impl Sub for Stats {
    type Output = StatsDiff;
    fn sub(self, rhs: Self) -> Self::Output {
        self.diff(rhs)
    }
}

/// A helper trait for accepting either Incr or Var.
/// We already do Deref coercion from Var to Incr (i.e. its watch node),
/// so may as well accept Var anywhere we accept Incr.
pub trait IntoIncr<T> {
    fn into_incr(self) -> Incr<T>;
}

impl<T: Value> AsRef<Incr<T>> for Var<T> {
    #[inline]
    fn as_ref(&self) -> &Incr<T> {
        self.deref()
    }
}

impl<T: Value> AsRef<Incr<T>> for Incr<T> {
    #[inline]
    fn as_ref(&self) -> &Incr<T> {
        &self
    }
}

impl<T> IntoIncr<T> for Incr<T> {
    #[inline]
    fn into_incr(self) -> Incr<T> {
        self
    }
}

impl<T> IntoIncr<T> for &Incr<T> {
    #[inline]
    fn into_incr(self) -> Incr<T> {
        self.clone()
    }
}

impl<T: Value> IntoIncr<T> for Var<T> {
    #[inline]
    fn into_incr(self) -> Incr<T> {
        self.watch()
    }
}

/// And for var references. Because we don't need to consume self.
impl<T: Value> IntoIncr<T> for &Var<T> {
    #[inline]
    fn into_incr(self) -> Incr<T> {
        self.watch()
    }
}

// We don't need is_empty... this is only for stats, if that.
#[allow(clippy::len_without_is_empty)]
pub trait WeakMap {
    fn len(&self) -> usize;
    fn capacity(&self) -> usize;
    fn garbage_collect(&mut self);
}

pub type WeakHashMap<K, V> = HashMap<K, WeakIncr<V>>;

impl<K: Hash, V> WeakMap for WeakHashMap<K, V> {
    fn garbage_collect(&mut self) {
        self.retain(|_k, v| v.strong_count() != 0);
    }
    fn len(&self) -> usize {
        HashMap::len(self)
    }
    fn capacity(&self) -> usize {
        HashMap::capacity(self)
    }
}

#[cfg(feature = "slotmap")]
pub type WeakSlotMap<K, V> = slotmap::HopSlotMap<K, WeakIncr<V>>;

#[cfg(feature = "slotmap")]
impl<K: slotmap::Key, V> WeakMap for WeakSlotMap<K, V> {
    fn garbage_collect(&mut self) {
        self.retain(|_k, v| v.strong_count() != 0);
    }
    fn len(&self) -> usize {
        slotmap::HopSlotMap::len(self)
    }
    fn capacity(&self) -> usize {
        slotmap::HopSlotMap::capacity(self)
    }
}

#[derive(Clone)]
pub struct Scope(scope::Scope);

impl Debug for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl Scope {
    pub const fn top() -> Self {
        Scope(scope::Scope::Top)
    }
}