reax 0.2.0

A reactivity system for Rust that infers dependencies between functions.
Documentation
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Reax is a reactivity system for Rust that infers dependencies between
//! functions.
//!
//! Every [`Variable`](trait.Variable.html) managed by reax is a node in a
//! dependency graph. Changes to and usages of variables are tracked by the
//! global [`ThreadRuntime`](struct.ThreadRuntime.html) which updates the graph
//! to reflect actual variable accesses. There are two kinds of built-in
//! variables:
//! - [`Var`](struct.Var.html) which can be explicitly mutated.
//! - [`ComputedVar`](computed/struct.ComputedVar.html) which lazily computes
//!   its value with a function.
//!
//! Users can listen to and react to changes of variables using
//! [`.watch`](struct.EagerCompute.html#method.watch).
//!
//! Critically, *a `ComputedVar` will only re-compute when needed*. If, when
//! computing its value, a `ComputedVar` uses any other variable anywhere
//! (directly or indirectly), changes to any of those upstream variables will
//! automatically mark the computed variable as dirty and the variable's value
//! will be recomputed the next time it is used.
//!
//! ## Examples
//!
//! Reax builds a model of how the variables in your program interact as it
//! runs.
//! ```rust
//! use reax::prelude::*;
//!
//! // Create input variables.
//! let number = Var::new(1).with_label("number");
//! let name = Var::new("Sam").with_label("name");
//!
//! // Create computed variables.
//! let formatted = (&number)
//!    .map(|x| format!("{}", x))
//!    .with_label("formatted");
//!
//! let printout = computed! {
//!     output! text = String::new(); // Reuse a buffer
//!
//!     text.clear();
//!     *text += *name.get();
//!     *text += " sees ";
//!     *text += formatted.get().as_str();
//! }.with_label("printout");
//!
//! // The computed variables haven't been used yet. Nothing is hooked-up.
//! assert_eq!(printout.node().depends_on(formatted.node()), false);
//!
//! // Use the variables!
//! assert_eq!(printout.get().as_str(), "Sam sees 1");
//! number.set(42);
//! name.set("Reax");
//! assert_eq!(printout.get().as_str(), "Reax sees 42");
//!
//! // Reax now knows how data moves through the variables!
//! assert_eq!(printout.node().depends_on(formatted.node()), true);
//!
//! // Print a .dot visualization.
//! reax::ThreadRuntime::write_graphviz(std::io::stdout().lock()).unwrap();
//! # reax::ThreadRuntime::write_graphviz(std::fs::File::create(
//! #   env!("CARGO_MANIFEST_DIR").to_owned() + "/target/name_sees_number.dot",
//! # ).unwrap()).unwrap();
//! ```
//! We can see this example through reax's eyes:
//! <div>
//! <svg width="246pt" height="188pt" viewBox="0.00 0.00 246.49 188.00"
//!  xmlns="http://www.w3.org/2000/svg"
//!  xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="graph0" class="graph"
//!  transform="scale(1 1) rotate(0) translate(4 184)">
//! <title>%3</title>
//! <polygon fill="white" stroke="transparent" points="-4,4 -4,-184 242.49,-184 242.49,4 -4,4"/>
//! <!-- 1 -->
//! <g id="node1" class="node">
//! <title>1</title>
//! <ellipse fill="none" stroke="black" cx="44.85" cy="-90" rx="44.69" ry="18"/>
//! <text text-anchor="middle" x="44.85" y="-86.3" font-family="Times,serif" font-size="14.00">name</text>
//! </g>
//! <!-- 3 -->
//! <g id="node3" class="node">
//! <title>3</title>
//! <ellipse fill="none" stroke="black" cx="108.85" cy="-18" rx="57.69" ry="18"/>
//! <text text-anchor="middle" x="108.85" y="-14.3" font-family="Times,serif" font-size="14.00">printout</text>
//! </g>
//! <!-- 1&#45;&gt;3 -->
//! <g id="edge1" class="edge">
//! <title>1&#45;&gt;3</title>
//! <path fill="none" stroke="black" d="M59.69,-72.76C67.73,-63.97 77.83,-52.93 86.77,-43.14"/>
//! <polygon fill="black" stroke="black" points="89.47,-45.38 93.64,-35.63 84.31,-40.65 89.47,-45.38"/>
//! </g>
//! <!-- 0 -->
//! <g id="node2" class="node">
//! <title>0</title>
//! <ellipse fill="none" stroke="black" cx="172.85" cy="-162" rx="55.79" ry="18"/>
//! <text text-anchor="middle" x="172.85" y="-158.3" font-family="Times,serif" font-size="14.00">number</text>
//! </g>
//! <!-- 2 -->
//! <g id="node4" class="node">
//! <title>2</title>
//! <ellipse fill="none" stroke="black" cx="172.85" cy="-90" rx="65.79" ry="18"/>
//! <text text-anchor="middle" x="172.85" y="-86.3" font-family="Times,serif" font-size="14.00">formatted</text>
//! </g>
//! <!-- 0&#45;&gt;2 -->
//! <g id="edge3" class="edge">
//! <title>0&#45;&gt;2</title>
//! <path fill="none" stroke="black" d="M172.85,-143.7C172.85,-135.98 172.85,-126.71 172.85,-118.11"/>
//! <polygon fill="black" stroke="black" points="176.35,-118.1 172.85,-108.1 169.35,-118.1 176.35,-118.1"/>
//! </g>
//! <!-- 2&#45;&gt;3 -->
//! <g id="edge2" class="edge">
//! <title>2&#45;&gt;3</title>
//! <path fill="none" stroke="black" d="M157.68,-72.41C149.63,-63.61 139.59,-52.63 130.71,-42.92"/>
//! <polygon fill="black" stroke="black" points="133.24,-40.49 123.9,-35.47 128.07,-45.21 133.24,-40.49"/>
//! </g>
//! </g>
//! </svg>
//! </div>
//! <hr>
//!
//! Reax will only update computed variables when needed.
//! ```rust
//! use reax::prelude::*;
//!
//! let number = Var::new(0);
//! let bigger_number = (&number).map(|x| *x + 10);
//! let even_bigger_number = (&bigger_number).map(|x| *x + 100);
//! let times_called = Var::new(0);
//!
//! // Set up a watcher to track how often bigger_number changes.
//! let mut eval = EagerCompute::new(());
//! eval.watch(&bigger_number, |_| {
//!    *times_called.mutate() += 1;
//! });
//!
//! // The watcher is called once on creation.
//! assert_eq!(*times_called.get(), 1);
//!
//! // Run the watcher. This is effectively a no-op since nothing has changed.
//! for _ in 0..100 { eval.tick(); }
//!
//! // Update a variable.
//! number.set(1);
//!
//! // Dependent variables are instantly dirty.
//! assert_eq!(bigger_number.node().is_dirty(), true);
//! assert_eq!(even_bigger_number.node().is_dirty(), true);
//!
//! // Run the watcher again. This time it fires.
//! eval.tick();
//! assert_eq!(*times_called.get(), 2);
//!
//! // even_bigger_number is still dirty since no one has used it yet.
//! assert_eq!(even_bigger_number.node().is_dirty(), true);
//! ```
//! Here you can see how the variables downstream from `number` are all
//! instantly marked when it changes. But they won't be recomputed until used:
//! <div>
//! <svg width="390pt" height="188pt" viewBox="0.00 0.00 389.54 188.00"
//! xmlns="http://www.w3.org/2000/svg"
//! xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="graph0" class="graph"
//! transform="scale(1 1) rotate(0) translate(4 184)">
//! <title>%3</title>
//! <polygon fill="white" stroke="transparent" points="-4,4 -4,-184 385.54,-184 385.54,4 -4,4"/>
//! <!-- 4 -->
//! <g id="node1" class="node">
//! <title>4</title>
//! <ellipse fill="none" stroke="red" cx="57.19" cy="-18" rx="57.39" ry="18"/>
//! <text text-anchor="middle" x="57.19" y="-14.3" font-family="Times,serif" font-size="14.00">watcher</text>
//! </g>
//! <!-- 1 -->
//! <g id="node2" class="node">
//! <title>1</title>
//! <ellipse fill="none" stroke="red" cx="153.19" cy="-90" rx="90.18" ry="18"/>
//! <text text-anchor="middle" x="153.19" y="-86.3" font-family="Times,serif" font-size="14.00">bigger_number</text>
//! </g>
//! <!-- 1&#45;&gt;4 -->
//! <g id="edge1" class="edge">
//! <title>1&#45;&gt;4</title>
//! <path fill="none" stroke="black" d="M130.44,-72.41C117.5,-62.97 101.12,-51.03 87.14,-40.83"/>
//! <polygon fill="black" stroke="black" points="88.94,-37.81 78.79,-34.75 84.81,-43.47 88.94,-37.81"/>
//! </g>
//! <!-- 2 -->
//! <g id="node5" class="node">
//! <title>2</title>
//! <ellipse fill="none" stroke="red" cx="249.19" cy="-18" rx="116.18" ry="18"/>
//! <text text-anchor="middle" x="249.19" y="-14.3" font-family="Times,serif" font-size="14.00">even_bigger_number</text>
//! </g>
//! <!-- 1&#45;&gt;2 -->
//! <g id="edge3" class="edge">
//! <title>1&#45;&gt;2</title>
//! <path fill="none" stroke="black" d="M175.95,-72.41C188.53,-63.24 204.34,-51.7 218.06,-41.71"/>
//! <polygon fill="black" stroke="black" points="220.26,-44.43 226.27,-35.71 216.13,-38.78 220.26,-44.43"/>
//! </g>
//! <!-- 0 -->
//! <g id="node3" class="node">
//! <title>0</title>
//! <ellipse fill="none" stroke="black" cx="153.19" cy="-162" rx="55.79" ry="18"/>
//! <text text-anchor="middle" x="153.19" y="-158.3" font-family="Times,serif" font-size="14.00">number</text>
//! </g>
//! <!-- 0&#45;&gt;1 -->
//! <g id="edge2" class="edge">
//! <title>0&#45;&gt;1</title>
//! <path fill="none" stroke="black" d="M153.19,-143.7C153.19,-135.98 153.19,-126.71 153.19,-118.11"/>
//! <polygon fill="black" stroke="black" points="156.7,-118.1 153.19,-108.1 149.7,-118.1 156.7,-118.1"/>
//! </g>
//! <!-- 3 -->
//! <g id="node4" class="node">
//! <title>3</title>
//! <ellipse fill="none" stroke="black" cx="304.19" cy="-162" rx="77.19" ry="18"/>
//! <text text-anchor="middle" x="304.19" y="-158.3" font-family="Times,serif" font-size="14.00">times_called</text>
//! </g>
//! </g>
//! </svg>
//! <hr>
//!
//! Reax has no built-in understanding of collections so you can use nested
//! `Var`s to better control the "depth" of changes.
//! ```rust
//! use reax::prelude::*;
//!
//! // Create a list of variables.
//! let list = Var::new(Vec::new());
//! for x in 1..=3 {
//!     list.mutate().push(Var::new(x));
//! }
//!
//! // Some computed properties:
//! let length = computed! { list.get().len() };
//! let sum = computed! {
//!     list.get().iter().map(|elem| *elem.get()).sum::<i32>()
//! };
//!
//! // Make length and sum outdated by pushing an extra element.
//! list.mutate().push(Var::new(4));
//!
//! // Update the length.
//! length.check(&mut ());
//! # assert_eq!(length.get_copy(), 4);
//!
//! // Now only make sum outdated, and leave it that way.
//! list.get()[0].set(100);
//!
//! # assert_eq!(sum.get_copy(), 109);
//! ```
//! Visualizing the runtime at the end of this example, you can see that only
//! the sum is dirty. None of the list elements are dependencies of the list
//! itself so any changes to them don't effect variables that never read them.
//! And reax hasn't seen that the extra element will be used in the sum. It will
//! find that out the next time the sum is computed.
//! <div>
//! <svg width="663pt" height="116pt" viewBox="0.00 0.00 662.99 116.00"
//! xmlns="http://www.w3.org/2000/svg"
//! xmlns:xlink="http://www.w3.org/1999/xlink"> <g id="graph0" class="graph"
//! transform="scale(1 1) rotate(0) translate(4 112)">
//! <title>%3</title>
//! <polygon fill="white" stroke="transparent" points="-4,4 -4,-112 658.99,-112 658.99,4 -4,4"/>
//! <!-- 5 -->
//! <g id="node1" class="node">
//! <title>5</title>
//! <ellipse fill="none" stroke="red" cx="255.19" cy="-18" rx="38.99" ry="18"/>
//! <text text-anchor="middle" x="255.19" y="-14.3" font-family="Times,serif" font-size="14.00">sum</text>
//! </g>
//! <!-- 4 -->
//! <g id="node2" class="node">
//! <title>4</title>
//! <ellipse fill="none" stroke="black" cx="431.19" cy="-18" rx="49.29" ry="18"/>
//! <text text-anchor="middle" x="431.19" y="-14.3" font-family="Times,serif" font-size="14.00">length</text>
//! </g>
//! <!-- 6 -->
//! <g id="node3" class="node">
//! <title>6</title>
//! <ellipse fill="none" stroke="black" cx="569.19" cy="-90" rx="85.59" ry="18"/>
//! <text text-anchor="middle" x="569.19" y="-86.3" font-family="Times,serif" font-size="14.00">extra_element</text>
//! </g>
//! <!-- 1 -->
//! <g id="node4" class="node">
//! <title>1</title>
//! <ellipse fill="none" stroke="black" cx="57.19" cy="-90" rx="57.39" ry="18"/>
//! <text text-anchor="middle" x="57.19" y="-86.3" font-family="Times,serif" font-size="14.00">element</text>
//! </g>
//! <!-- 1&#45;&gt;5 -->
//! <g id="edge1" class="edge">
//! <title>1&#45;&gt;5</title>
//! <path fill="none" stroke="black" d="M93.97,-76C128.53,-63.78 180.08,-45.55 215.54,-33.02"/>
//! <polygon fill="black" stroke="black" points="216.83,-36.28 225.09,-29.64 214.49,-29.68 216.83,-36.28"/>
//! </g>
//! <!-- 0 -->
//! <g id="node5" class="node">
//! <title>0</title>
//! <ellipse fill="none" stroke="black" cx="431.19" cy="-90" rx="34.39" ry="18"/>
//! <text text-anchor="middle" x="431.19" y="-86.3" font-family="Times,serif" font-size="14.00">list</text>
//! </g>
//! <!-- 0&#45;&gt;5 -->
//! <g id="edge2" class="edge">
//! <title>0&#45;&gt;5</title>
//! <path fill="none" stroke="black" d="M404.46,-78.37C374.88,-66.6 326.96,-47.54 293.42,-34.2"/>
//! <polygon fill="black" stroke="black" points="294.52,-30.87 283.93,-30.43 291.93,-37.38 294.52,-30.87"/>
//! </g>
//! <!-- 0&#45;&gt;4 -->
//! <g id="edge5" class="edge">
//! <title>0&#45;&gt;4</title>
//! <path fill="none" stroke="black" d="M431.19,-71.7C431.19,-63.98 431.19,-54.71 431.19,-46.11"/>
//! <polygon fill="black" stroke="black" points="434.7,-46.1 431.19,-36.1 427.7,-46.1 434.7,-46.1"/>
//! </g>
//! <!-- 3 -->
//! <g id="node6" class="node">
//! <title>3</title>
//! <ellipse fill="none" stroke="black" cx="189.19" cy="-90" rx="57.39" ry="18"/>
//! <text text-anchor="middle" x="189.19" y="-86.3" font-family="Times,serif" font-size="14.00">element</text>
//! </g>
//! <!-- 3&#45;&gt;5 -->
//! <g id="edge3" class="edge">
//! <title>3&#45;&gt;5</title>
//! <path fill="none" stroke="black" d="M204.84,-72.41C213.26,-63.48 223.79,-52.31 233.04,-42.5"/>
//! <polygon fill="black" stroke="black" points="235.81,-44.67 240.12,-34.99 230.71,-39.86 235.81,-44.67"/>
//! </g>
//! <!-- 2 -->
//! <g id="node7" class="node">
//! <title>2</title>
//! <ellipse fill="none" stroke="black" cx="321.19" cy="-90" rx="57.39" ry="18"/>
//! <text text-anchor="middle" x="321.19" y="-86.3" font-family="Times,serif" font-size="14.00">element</text>
//! </g>
//! <!-- 2&#45;&gt;5 -->
//! <g id="edge4" class="edge">
//! <title>2&#45;&gt;5</title>
//! <path fill="none" stroke="black" d="M305.55,-72.41C297.13,-63.48 286.6,-52.31 277.35,-42.5"/>
//! <polygon fill="black" stroke="black" points="279.68,-39.86 270.27,-34.99 274.58,-44.67 279.68,-39.86"/>
//! </g>
//! </g>
//! </svg>
//! </div>

use std::rc::Rc;
use std::time::Instant;
use std::fmt;
use std::cell::{RefCell, Ref, RefMut};
use fnv::FnvHashMap;

pub(crate) mod idset;

pub mod handler;

pub mod computed;
use computed::{
    FunctionMapped,
    MutatorMapped,
    ComputedValue,
    ComputedVar,
    BoxedComputedVar,
};

pub(crate) mod system;
pub use crate::system::{
    ThreadRuntime,
    Node,
};

pub mod prelude {
    //! The types and macros you most likely want to use.

    pub use super::Variable as _;
    pub use super::{
        Var,
        computed::ComputedVar,
        EagerCompute,
        computed,
        computed_move,
    };
}

/// A trait implemented by any wrapped data which reax can manage.
pub trait Variable: Sized {
    /// The type of this variable.
    type Value;

    /// Returns a handle to this variable's node in the [reax
    /// runtime's](struct.ThreadRuntime.html) dependency graph.
    fn node(&self) -> &Node;

    /// Returns the value of this variable.
    ///
    /// Note that right now this trait assumes that the data is stored behind a
    /// `RefCell`. The source of interior mutability can be made more generic
    /// once GATs are stabilized.
    fn get(&self) -> Ref<Self::Value>;

    /// Returns the value of this variable without alerting the reax runtime
    /// that the variable is used in the current context. See also
    /// [`get`](#tymethod.get).
    fn get_non_reactive(&self) -> Ref<Self::Value>;

    /// Returns the value of this variable by copy where possible. See also
    /// [`get`](#tymethod.get).
    fn get_copy(&self) -> Self::Value where Self::Value: Copy {
        *self.get()
    }

    /// Create a new `ComputedVar` which depends *only* on this variable. The
    /// value of the returned cell is lazily computed by the given function.
    /// That is, the function will not be executed until someone retrieves the
    /// value of the cell. This can be used similarly to
    /// [`EagerCompute::watch`](struct.EagerCompute.html#method.watch) if the
    /// resulting cell is checked frequently. See also
    /// [`ComputedVar::new`](computed/struct.ComputedVar.html#method.new).
    ///
    /// Note that variables should usually be borrowed or `Rc::clone`ed before
    /// being passed to this function (e.g. `(&variable).map(...)`).
    fn map<T, F>(self, func: F)
        -> ComputedVar<FunctionMapped<Self, T, F>>
        where F: FnMut(&Self::Value) -> T
    {
        ComputedVar::new_raw(FunctionMapped {
            inner: self,
            state: None,
            update: func,
        })
    }

    /// Create a new `ComputedVar` which depends *only* on this variable. The
    /// value of the returned cell is lazily updated by the given function. That
    /// is, the function will not be executed until someone retrieves the value
    /// of the cell. This can be used similarly to
    /// [`EagerCompute::watch`](struct.EagerCompute.html#method.watch) if the
    /// resulting cell is checked frequently. See also
    /// [`ComputedVar::new_mutate`](computed/struct.ComputedVar.html#method.new_mutate).
    ///
    /// Note that variables should usually be borrowed or `Rc::clone`ed before
    /// being passed to this function (e.g. `(&variable).map_mutate(...)`).
    fn map_mutate<T, F>(self, initial: T, func: F)
        -> ComputedVar<MutatorMapped<Self, T, F>>
        where F: FnMut(&Self::Value, &mut T)
    {
        ComputedVar::new_raw(MutatorMapped {
            inner: self,
            state: initial,
            update: func,
        })
    }

    /// Provides the runtime with a variable name to use in debug outputs. This
    /// does nothing in release builds.
    fn with_label(self, label: impl fmt::Display) -> Self {
        self.node().set_label(label);
        self
    }
}

impl<'r, T> Variable for &'r T where T: Variable {
    type Value = T::Value;

    fn node(&self) -> &Node {
        Variable::node(*self)
    }

    fn get(&self) -> Ref<Self::Value> {
        Variable::get(*self)
    }

    fn get_non_reactive<'a>(&self) -> Ref<Self::Value> {
        Variable::get_non_reactive(*self)
    }
}

impl<T> Variable for Rc<T> where T: Variable {
    type Value = T::Value;

    fn node(&self) -> &Node {
        Variable::node(&**self)
    }

    fn get(&self) -> Ref<Self::Value> {
        Variable::get(&**self)
    }

    fn get_non_reactive<'a>(&self) -> Ref<Self::Value> {
        Variable::get_non_reactive(&**self)
    }
}

impl<T> Variable for Box<T> where T: Variable {
    type Value = T::Value;

    fn node(&self) -> &Node {
        Variable::node(&**self)
    }

    fn get(&self) -> Ref<Self::Value> {
        Variable::get(&**self)
    }

    fn get_non_reactive<'a>(&self) -> Ref<Self::Value> {
        Variable::get_non_reactive(&**self)
    }
}

/// A mutable variable that is tracked by the reax runtime.
///
/// Today this is a wrapper around a `RefCell` and a `Node` but may be more
/// generic in the future once GATs are stable.
pub struct Var<T> {
    node: Node,
    cell: RefCell<T>,
}

impl<T> Var<T> {
    /// Creates a new interiorly mutable wrapper around the given value.
    pub fn new(value: T) -> Self {
        Var {
            node: Node::next(),
            cell: RefCell::new(value),
        }
    }

    /// Sets the value of the variable, instantly marking all upstream variables
    /// as dirty. This method will panic if any reference given by a call to
    /// `mutate` is still alive.
    ///
    /// ```rust
    /// # use reax::prelude::*;
    /// let var = Var::new(1);
    /// let double = computed! { var.get_copy() * 2 };
    /// var.set(2);
    /// assert!(double.node().is_dirty());
    /// ```
    pub fn set(&self, value: T) {
        *self.mutate() = value;
    }

    /// Sets the value of the variable. Unlike [`set`](#method.set), upstream
    /// variables are not marked as dirty if the given value is equal to the
    /// current value.
    pub fn set_checked(&self, value: T) where T: PartialEq {
        let mut current = self.cell.borrow_mut();
        if value != *current {
            self.node().on_write(true);
            *current = value;
        }
    }

    /// Provides a mutable reference to the variable, instantly marking all
    /// upstream variables as dirty. This method will panic if any reference
    /// given by a previous call to `mutate` is still alive.
    ///
    /// ```rust
    /// # use reax::prelude::*;
    /// let var = Var::new(1);
    /// let double = computed! { var.get_copy() * 2 };
    /// *var.mutate() += 1;
    /// assert!(double.node().is_dirty());
    /// ```
    pub fn mutate(&self) -> RefMut<T> {
        let out = self.cell.borrow_mut();
        self.node().on_write(true);
        out
    }
}

impl<T> Variable for Var<T> {
    type Value = T;

    #[inline(always)]
    fn node(&self) -> &Node {
        &self.node
    }

    fn get(&self) -> Ref<T> {
        let out = self.cell.borrow();
        self.node().on_read();
        out
    }

    fn get_non_reactive(&self) -> Ref<T> {
        self.cell.borrow()
    }
}

impl<T: fmt::Debug> fmt::Debug for Var<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let val = self.get();
        f.debug_struct("Var")
            .field("node", self.node())
            .field("value", &*val)
            .finish()
    }
}

/// A helper which eagerly updates any outdated variables it is given.
///
/// The [`run`](#method.run) method can be used to integrate with an async
/// runtime. Otherwise, updates are performed by repeatedly calling
/// [`tick`](#method.tick).
pub struct EagerCompute<'f, C: 'f> {
    signals: handler::DirtiedList,
    computed: FnvHashMap<usize, BoxedComputedVar<'f, (), C>>,
    /// The data passed to each computed variable on update.
    pub context: C,
}

const TICK_SIZE: usize = 32;

impl<'f, C: Default> Default for EagerCompute<'f, C> {
    fn default() -> Self {
        EagerCompute::new(C::default())
    }
}

impl<'f, C> EagerCompute<'f, C> {
    /// Creates a new eagerly updating environment. It will only evaluate
    /// variables that have been passed explicitly.
    pub fn new(context: C) -> Self {
        EagerCompute {
            signals: handler::DirtiedList::new(),
            computed: FnvHashMap::default(),
            context,
        }
    }

    /// Add the given empty computed variable to this environment. The variable
    /// will be recomputed every time [`tick`](#method.tick) is called if
    /// needed. This is a good way to watch many variables at once.
    ///
    /// Note that outdated or uncomputed variables will be computed immediately
    /// when first installed.
    ///
    /// ```rust
    /// # use reax::prelude::*;
    /// let a = Var::new(1);
    /// let b = Var::new(2);
    ///
    /// let mut eval = EagerCompute::new(());
    /// eval.install(computed! {
    ///    a.get();
    ///    b.get();
    ///    println!("a or b changed")
    /// });
    /// ```
    pub fn install<V>(&mut self, computed: ComputedVar<V>)
        where V: ComputedValue<Value=(), Context=C> + 'f
    {
        self.install_boxed(computed.boxed())
    }

    /// Like [`install`](#method.install) but relies on the user to pre-box the
    /// computed cell.
    pub fn install_boxed(&mut self, computed: BoxedComputedVar<'f, (), C>) {
        computed.check(&mut self.context); // Installing should make the cell up-to-date.
        let node = computed.node();
        self.signals.attach(node);
        self.computed.insert(node.id, computed.boxed());
    }

    /// Removes the computed variable with the given node id from this
    /// environment.
    pub fn uninstall_by_id(&mut self, node_id: usize)
        -> Option<BoxedComputedVar<'f, (), C>>
    {
        self.computed.remove(&node_id)
    }

    /// Recompute any installed variables which are outdated. This method may
    /// deadlock if two watchers repeatedly trigger each-other in a loop. If
    /// that is an issue, try using [`tick_timeout`](#method.tick_timeout).
    pub fn tick(&mut self) {
        let mut buffer = [0; TICK_SIZE];
        loop {
            let ids = self.signals.poll_dirtied_ids(&mut buffer);
            if ids.is_empty() { break };
            for id in ids {
                if let Some(watcher) = self.computed.get(&id) {
                    watcher.check(&mut self.context);
                }
            }
        }
    }

    /// Recompute any installed variables which are outdated. This method will
    /// return true if all variables are up-to-date or false if the `end` time
    /// was reached first.
    pub fn tick_timeout(&mut self, end: Instant) -> bool {
        let mut buffer = [0; TICK_SIZE];
        loop {
            let ids = self.signals.poll_dirtied_ids(&mut buffer);
            if ids.is_empty() { break };
            for id in ids {
                if let Some(watcher) = self.computed.get(&id) {
                    watcher.check(&mut self.context);
                }
            }
            if Instant::now() > end {
                return false;
            }
        }
        true
    }

    /// Returns a future which updates a few installed variables once they
    /// become outdated then resolves to the number of updates performed. This
    /// is similar to [`run_forever`](#method.run_forever) except it only runs
    /// until at least 1 update has occurred.
    pub async fn run_once(&mut self) -> usize {
        let mut buffer = [0; TICK_SIZE];
        let ids = self.signals.dirtied_ids(&mut buffer).await;
        for id in ids {
            if let Some(watcher) = self.computed.get(&id) {
                watcher.check(&mut self.context);
            }
        }
        ids.len()
    }

    /// Returns a future which runs until dropped, updating any installed
    /// variables when they become outdated. This works well with async event
    /// schedulers since the future will yield until a [`Var`](struct.Var.html)
    /// used by this environment is manually changed, at which point the
    /// future's context will be instantly notified by
    /// [`Node::on_write`](struct.Node.html#method.on_write).
    pub async fn run_forever(mut self) {
        let mut buffer = [0; TICK_SIZE];
        loop {
            let ids = self.signals.dirtied_ids(&mut buffer).await;
            for id in ids {
                if let Some(watcher) = self.computed.get(&id) {
                    watcher.check(&mut self.context);
                }
            }
        }
    }
}

impl<'f> EagerCompute<'f, ()> {
        /// Call a function whenever the given variable is changed and
    /// [`tick`](#method.tick) is called.
    ///
    /// ```rust
    /// # use reax::prelude::*;
    /// let a = Var::new(1);
    ///
    /// let mut eval = EagerCompute::new(());
    /// eval.watch(&a, |a| println!("a changed to {}", a));
    /// ```
    pub fn watch<V: Variable + 'f>(
        &mut self,
        var: V,
        watcher: impl FnMut(&V::Value) + 'f,
    ) {
        self.install(var.map(watcher).with_label("watcher"));
    }

    /// Print the value of the given variable to stderr whenever it changes and
    /// [`tick`](#method.tick) is called.
    pub fn dbg<V: Variable + 'f>(&mut self, var: V) where V::Value: fmt::Debug {
        let id = var.node().clone_id();
        self.install(var
            .map(move |val| eprintln!("{:?} := {:?}", &*id, val))
            .with_label("dbg"));
    }
}

/// A macro for conveniently creating
/// [`ComputedVar`](computed/struct.ComputedVar.html)s.
///
/// ```rust
/// # use reax::prelude::*;
/// # use std::fmt::Write;
/// let a = Var::new(3);
/// let b = Var::new(4);
///
/// // Return the computed value.
/// let sum = computed! {
///     a.get_copy() + b.get_copy()
/// };
///
/// // Pre-allocate the computed value and mutate it.
/// let debug = computed! {
///     output! text = String::new();
///     text.clear();
///
///     write!(
///         text,
///         "{} + {} = {}",
///         a.get_copy(),
///         b.get_copy(),
///         sum.get_copy(),
///     ).unwrap();
/// };
///
/// // Use a context.
/// let with_ctx = computed! {
///     context! ctx: Vec<i32>;
///
///     ctx.push(sum.get_copy());
/// };
///
/// // And it works!
/// # let allocation = debug.get().as_ptr();
/// let mut list = Vec::new();
/// assert_eq!(debug.get().as_str(), "3 + 4 = 7");
/// with_ctx.get_contextual(&mut list);
/// assert_eq!(list, &[7]);
///
/// a.set(5);
///
/// assert_eq!(debug.get().as_str(), "5 + 4 = 9");
/// with_ctx.get_contextual(&mut list);
/// assert_eq!(list, &[7, 9]);
/// # assert_eq!(allocation, debug.get().as_ptr());
/// ```
#[macro_export]
macro_rules! computed {
    { output! $n:ident = $e:expr; context! $c:ident $(: $ct:ty)?; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::MutatorComputed::new($e, |$n, $c$(: &mut $ct)?| { $($x)* }))
    };
    { output! $n:ident = $e:expr; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::MutatorComputed::new($e, |$n, _: &mut ()| { $($x)* }))
    };
    { context! $c:ident$(: $ct:ty)?; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::FunctionComputed::new(|$c$(: &mut $ct)?| { $($x)* }))
    };
    { $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::FunctionComputed::new(|_: &mut ()| { $($x)* }))
    };
}

/// Like [`computed!`](macro.computed.html) but captures by move rather than by
/// reference.
#[macro_export]
macro_rules! computed_move {
    { output! $n:ident = $e:expr; context! $c:ident$(: $ct:ty)?; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::MutatorComputed::new($e, move |$n, $c$(: &mut $ct)?| { $($x)* }))
    };
    { output! $n:ident = $e:expr; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::MutatorComputed::new($e, move |$n, _: &mut ()| { $($x)* }))
    };
    { context! $c:ident$(: $ct:ty)?; $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::FunctionComputed::new(move |$c$(: &mut $ct)?| { $($x)* }))
    };
    { $($x:tt)* } => {
        $crate::computed::ComputedVar::new_raw(
            $crate::computed::FunctionComputed::new(move |_: &mut ()| { $($x)* }))
    };
}