aboutsummaryrefslogtreecommitdiff
path: root/incria/src/deps.rs
blob: 84411c00375ab775ed2a10cd44b4a2856dc0aaa0 (plain)
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
//! The main code used for tracking dependencies (mostly) invisibly to the user.
//!
//! Each mapping that could be memoised is represented by a Node. Each Node can have one or more dependencies, forming a directed acyclic graph.
//!
//! [`self::add_dep`] should be called whenever any mapping is retrieved, to record the dependency.
//!
//! [`self::next_node_id`] and [`self::with_node_id`] should be used to create new nodes in the graph when a new mapping is being evaluated.
//!
//! [`self::mark_dirty`] should be called from outside the evaluation of any mapping. In many cases, this requires the dependency ID to be stored externally alongside the key, which can be accomplished with [`self::current_node_id`]
//!
//! [`self::is_dirty`] should be used when a mapping is retrieved to determine if it needs to be re-evaluated. If it does, [`self::clear`] should be used to reset the mapping's dependencies and dirty state.
use std::{
    collections::{HashMap, VecDeque},
    fmt::Write,
    future::Future,
};

use once_cell::sync::OnceCell;
use parking_lot::Mutex;

/// Identifier of a node, unique across a program run.
pub type NodeId = usize;

tokio::task_local! {
    /// The ID of the node in the dependency tree for the currently running computation
    static NODE_ID: NodeId;
}

/// Responsible for tracking dependencies.
/// There is one global instance of this, [`DEP_TRACKER`], with convenience functions for most of its functionality.
#[derive(Default)]
struct DepTracker {
    /// Neighbour-List representation of dependency tree
    deps: Mutex<HashMap<NodeId, NodeInfo>>,

    /// Next node ID to issue
    next_node_id: Mutex<NodeId>,
}

impl DepTracker {
    /// See [`self::add_dep`]
    fn add_dep(&self, dep: NodeId) {
        self.deps
            .lock()
            .entry(NODE_ID.get())
            .and_modify(|v| v.deps.push(dep))
            .or_insert(NodeInfo {
                deps: vec![dep],
                dirty: false,
            });
    }

    /// See [`self::next_node_id`]
    fn next_node_id(&self) -> usize {
        let mut lock = self.next_node_id.lock();
        *lock += 1;
        *lock - 1
    }

    /// See [`self::mark_dirty`]
    fn mark_dirty(&self, node: NodeId) {
        let mut lock = self.deps.lock();
        let mut frontier = VecDeque::new();
        frontier.push_back(node);
        while let Some(node_id) = frontier.pop_front() {
            let node = match lock.get_mut(&node_id) {
                Some(x) => x,
                None => continue,
            };

            if node.dirty {
                continue;
            }
            node.dirty = true;

            for (dependent, dependent_info) in lock.iter() {
                if dependent_info.deps.contains(&node_id) {
                    frontier.push_back(*dependent);
                }
            }
        }
    }

    /// See [`self::is_dirty`]
    fn is_dirty(&self, node: NodeId) -> bool {
        self.deps
            .lock()
            .get(&node)
            .map(|v| v.dirty)
            .unwrap_or(false)
    }

    /// See [`self::clear`]
    fn clear(&self, node: NodeId) {
        let mut lock = self.deps.lock();
        let node = match lock.get_mut(&node) {
            Some(x) => x,
            None => return,
        };

        node.dirty = false;
        node.deps = vec![];
    }
}

/// Info about a single dependency node
struct NodeInfo {
    deps: Vec<NodeId>,
    dirty: bool,
}

/// The global instance of the dependency tracker
static DEP_TRACKER: OnceCell<DepTracker> = OnceCell::new();
fn dep_tracker() -> &'static DepTracker {
    DEP_TRACKER.get_or_init(DepTracker::default)
}

/// Register a dependency for the current node
pub fn add_dep(dep: NodeId) {
    dep_tracker().add_dep(dep);
}

/// Get the next node id to use
pub fn next_node_id() -> NodeId {
    dep_tracker().next_node_id()
}

/// Get the ID of the current node
pub fn current_node_id() -> NodeId {
    NODE_ID.get()
}

/// Mark the given node and all nodes that depend on it 'dirty'.
///
/// This should be used in conjunction with [`self::is_dirty`] to recompute values when necessary.
pub fn mark_dirty(dep: NodeId) {
    dep_tracker().mark_dirty(dep)
}

/// Check if the given node is dirty, indicating it should be recomputed.
pub fn is_dirty(dep: NodeId) -> bool {
    dep_tracker().is_dirty(dep)
}

/// Clear all information about a given node.
///
/// This should be used when a node is recomputed, to ensure stale dependencies are removed.
pub fn clear(dep: NodeId) {
    dep_tracker().clear(dep)
}

/// Generate a graphviz representation of the current dependency graph, for debugging.
///
/// Dirty nodes will be coloured grey.
pub fn dep_graphviz() -> String {
    let mut out = String::new();
    let deps = dep_tracker().deps.lock();
    writeln!(&mut out, "digraph G {{").unwrap();
    for (id, info) in deps.iter() {
        if *id == 0 {
            writeln!(&mut out, "\t{} [label=Root]", id).unwrap();
        } else if info.dirty {
            writeln!(&mut out, "\t{} [style=filled,color=lightgrey]", id).unwrap();
        }
        for dep in info.deps.iter() {
            writeln!(&mut out, "\t{} -> {}", id, dep).unwrap();
        }
    }

    writeln!(&mut out, "}}").unwrap();

    out
}

/// Decorate the given future to have the given dependency ID.
pub async fn with_node_id<F>(dep: NodeId, f: F) -> F::Output
where
    F: Future + Send,
    F::Output: Send,
{
    NODE_ID.scope(dep, f).await
}