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
use hibitset::BitSet;
use std::{
    collections::{BinaryHeap, HashMap, HashSet, VecDeque},
    convert::TryInto,
    fmt::Debug,
    hash::Hash,
};

/// Topologically sort `index_set` and return a sorted `Vec`.
/// For the nodes without order-before relationship, the ones with smaller
/// `order_indicator` output will be ordered first.
pub fn topological_sort<InIndex, OutIndex, F, OrderIndicator, FOrd, Set>(
    index_set: Set, predecessor_edges: F, order_indicator: FOrd,
) -> Vec<OutIndex>
where
    InIndex: Copy + Hash + Eq + PartialEq + Ord + TryInto<OutIndex>,
    <InIndex as TryInto<OutIndex>>::Error: Debug,
    F: Fn(InIndex) -> Vec<InIndex>,
    OrderIndicator: Ord,
    FOrd: Fn(InIndex) -> OrderIndicator,
    Set: SetLike<InIndex> + Default + Clone + IntoIterator<Item = InIndex>,
{
    let mut num_next_edges = HashMap::new();

    for me in index_set.clone() {
        num_next_edges.entry(me).or_insert(0);
        for prev in predecessor_edges(me) {
            if index_set.contains(&prev) {
                *num_next_edges.entry(prev).or_insert(0) += 1;
            }
        }
    }

    let mut candidates = BinaryHeap::new();
    let mut reversed_indices = Vec::new();

    for me in index_set.clone() {
        if num_next_edges[&me] == 0 {
            candidates.push((order_indicator(me), me));
        }
    }
    while let Some((_, me)) = candidates.pop() {
        reversed_indices.push(me.try_into().expect("index in range"));

        for prev in predecessor_edges(me) {
            if index_set.contains(&prev) {
                num_next_edges.entry(prev).and_modify(|e| *e -= 1);
                if num_next_edges[&prev] == 0 {
                    candidates.push((order_indicator(prev), prev));
                }
            }
        }
    }
    reversed_indices.reverse();
    reversed_indices
}

/// Return the future set of the nodes in `index_set`.
/// The future set (including itself) of a node whose `stop_condition` is `true`
/// will not be included.
pub fn get_future<'a, InIndex, OutIndex, F, FStop, Set, Iter>(
    index_set: Iter, successor_edges: F, stop_condition: FStop,
) -> Set
where
    InIndex: 'a + Copy + TryInto<OutIndex>,
    <InIndex as TryInto<OutIndex>>::Error: Debug,
    OutIndex: 'a + Copy + Hash + Eq + PartialEq + Ord,
    F: Fn(InIndex) -> Vec<InIndex>,
    FStop: Fn(InIndex) -> bool,
    Set: SetLike<OutIndex> + Default,
    Iter: IntoIterator<Item = InIndex>,
{
    let mut queue = VecDeque::new();
    let mut visited = Set::default();
    for i in index_set {
        visited.insert(i.try_into().expect("index in range"));
        queue.push_back(i);
    }
    while let Some(x) = queue.pop_front() {
        for succ in successor_edges(x) {
            if stop_condition(succ) {
                continue;
            }
            let out_index = succ.try_into().expect("index in range");
            if !visited.contains(&out_index) {
                queue.push_back(succ);
                visited.insert(out_index);
            }
        }
    }
    visited
}

pub trait Graph {
    type NodeIndex: 'static + Copy + Hash + Eq + PartialEq + Ord;
}

// TODO: Decide if returning Iterator is better than returning `Vec`?
pub trait DAG: Graph {
    fn predecessor_edges(
        &self, node_index: Self::NodeIndex,
    ) -> Vec<Self::NodeIndex>;

    fn topological_sort_with_order_indicator<OrderIndicator, FOrd, Set>(
        &self, index_set: Set, order_indicator: FOrd,
    ) -> Vec<Self::NodeIndex>
    where
        OrderIndicator: Ord,
        FOrd: Fn(Self::NodeIndex) -> OrderIndicator,
        Set: SetLike<Self::NodeIndex>
            + Default
            + Clone
            + IntoIterator<Item = Self::NodeIndex>,
    {
        topological_sort(
            index_set,
            |i| self.predecessor_edges(i),
            order_indicator,
        )
    }

    fn topological_sort<Set>(&self, index_set: Set) -> Vec<Self::NodeIndex>
    where Set: SetLike<Self::NodeIndex>
            + Default
            + Clone
            + IntoIterator<Item = Self::NodeIndex> {
        // Any topological order will work, so just return a constant for
        // `order_indicator`.
        self.topological_sort_with_order_indicator(index_set, |_| true)
    }
}

pub trait RichDAG: DAG {
    fn successor_edges(
        &self, node_index: Self::NodeIndex,
    ) -> Vec<Self::NodeIndex>;

    fn get_future_with_stop_condition<FStop, Set, Iter>(
        &self, index_set: Iter, stop_condition: FStop,
    ) -> Set
    where
        FStop: Fn(Self::NodeIndex) -> bool,
        Set: SetLike<Self::NodeIndex> + Default,
        Iter: IntoIterator<Item = Self::NodeIndex>,
    {
        get_future(index_set, |i| self.successor_edges(i), stop_condition)
    }

    fn get_future<Set, Iter>(&self, index_set: Iter) -> Set
    where
        Set: SetLike<Self::NodeIndex> + Default,
        Iter: IntoIterator<Item = Self::NodeIndex>,
    {
        self.get_future_with_stop_condition(index_set, |_| false)
    }
}

pub trait TreeGraph: Graph {
    fn parent(&self, node_index: Self::NodeIndex) -> Option<Self::NodeIndex>;
    fn referees(&self, node_index: Self::NodeIndex) -> Vec<Self::NodeIndex>;
}

pub trait RichTreeGraph: TreeGraph {
    fn children(&self, node_index: Self::NodeIndex) -> Vec<Self::NodeIndex>;
    fn referrers(&self, node_index: Self::NodeIndex) -> Vec<Self::NodeIndex>;
}

impl<T: TreeGraph> DAG for T {
    fn predecessor_edges(
        &self, node_index: Self::NodeIndex,
    ) -> Vec<Self::NodeIndex> {
        let mut predecessor_edges = self.referees(node_index);
        if let Some(p) = self.parent(node_index) {
            predecessor_edges.push(p);
        }
        predecessor_edges
    }
}

impl<T: RichTreeGraph + DAG> RichDAG for T {
    fn successor_edges(
        &self, node_index: Self::NodeIndex,
    ) -> Vec<Self::NodeIndex> {
        let mut successor_edges = self.children(node_index);
        successor_edges.append(&mut self.referrers(node_index));
        successor_edges
    }
}

pub trait SetLike<T> {
    fn insert(&mut self, i: T) -> bool;
    fn contains(&self, i: &T) -> bool;
}

impl<T: Eq + Hash> SetLike<T> for HashSet<T> {
    fn insert(&mut self, i: T) -> bool { self.insert(i) }

    fn contains(&self, i: &T) -> bool { self.contains(i) }
}

impl SetLike<u32> for BitSet {
    fn insert(&mut self, i: u32) -> bool { self.add(i) }

    fn contains(&self, i: &u32) -> bool { self.contains(*i) }
}