Skip to main content

graphity_core/
ancestry.rs

1use std::ops::Deref;
2use std::sync::Arc;
3
4use crate::error::check_index;
5use crate::graph::{SharedArray, share};
6use crate::{Dominators, Graph, GraphError, NONE, parent_forest};
7
8/// An index of a forest for ancestor queries: the parent and depth of a node, whether one node is an
9/// ancestor of another, and the lowest common ancestor of two nodes.
10///
11/// [`Ancestry::of`] builds the index of a forest whose edges point from parent to child, such as a
12/// syntax tree. For a forest whose edges point from child to parent, pass the transposed graph:
13/// `Ancestry::of(&BiAdjacentGraph::of(&forest).transposed())`. [`Ancestry::of_dominators`] builds the
14/// index of a dominator tree, in which the ancestors of a node are its dominators. The index is built
15/// once and answers each query in O(log node_count) at most, however deep the forest;
16/// [`PreorderAncestry::of`] adds an ancestor test in O(1) and the nodes of each subtree.
17///
18/// A node is its own ancestor, so `is_ancestor_of(a, a)` is `true` and
19/// `lowest_common_ancestor_of(a, a)` is `Some(a)`. Two nodes in different trees of the forest have no
20/// common ancestor. Uses [heavy-light decomposition](https://en.wikipedia.org/wiki/Heavy-light_decomposition).
21///
22/// ```
23/// use graphity_core::{Ancestry, GraphBuilder, PreorderAncestry};
24///
25/// //      0
26/// //    1   2
27/// //   3 4   5
28/// let mut b = GraphBuilder::new();
29/// b.add_nodes(6);
30/// b.add_edge_pairs(&[0, 1, 0, 2, 1, 3, 1, 4, 2, 5]);
31/// let ancestry = Ancestry::of(&b.build()).unwrap();
32/// assert_eq!(ancestry.lowest_common_ancestor_of(3, 4), Some(1));
33/// assert_eq!(ancestry.lowest_common_ancestor_of(4, 5), Some(0));
34/// assert!(ancestry.is_ancestor_of(1, 4));
35/// assert_eq!(ancestry.depth_of(5), 2);
36///
37/// let preorder = PreorderAncestry::of(&ancestry);
38/// assert_eq!(preorder.subtree_of(1), [1, 3, 4]);
39/// ```
40///
41/// Where Java's `PreorderAncestry` extends `Ancestry` and overrides `isAncestorOf`, a
42/// [`PreorderAncestry`] dereferences to its `Ancestry`, and an `Ancestry` that belongs to a
43/// `PreorderAncestry` answers [`is_ancestor_of`](Self::is_ancestor_of) in O(1) as well.
44///
45/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
46///
47/// **Memory:** 12 x node_count bytes, of which an index built by [`Ancestry::of_dominators`] shares
48/// 4 x node_count bytes with the dominators.
49#[derive(Debug, Clone)]
50pub struct Ancestry {
51    /// Parent of each node, [`NONE`] for a tree root.
52    parent: SharedArray,
53    /// Distance from the tree root, 0 for a tree root.
54    depth: SharedArray,
55    /// Topmost node of the heavy chain containing each node. Jumping from a node to
56    /// `parent[chain_head[node]]` skips a whole chain, and every root-to-node path crosses
57    /// O(log node count) chains.
58    chain_head: SharedArray,
59    /// The preorder arrays when this index belongs to a [`PreorderAncestry`].
60    preorder: Option<Arc<PreorderArrays>>,
61}
62
63#[derive(Debug)]
64struct PreorderArrays {
65    /// Position of each node in `order`.
66    preorder_index: Box<[u32]>,
67    /// Number of nodes in the subtree of each node, the node itself included.
68    subtree_size: Box<[u32]>,
69    /// Node at each preorder position.
70    order: Box<[u32]>,
71}
72
73impl Ancestry {
74    /// Returns the ancestor index of `forest`, whose edges point from parent to child - Java's overload
75    /// `of(Graph)`.
76    ///
77    /// In such a forest, no node has more than one in-node, and there is no cycle, not even a self-loop;
78    /// [`graphs::is_forest`](crate::graphs::is_forest) tests this without an error. The roots of the
79    /// trees are the root nodes of the graph.
80    ///
81    /// **Time:** O(node_count + edge_count).
82    /// **Memory:** 12 x node_count bytes for the result; while it runs, 12 x node_count bytes more.
83    ///
84    /// # Errors
85    /// An [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if a node of `forest` has more
86    /// than one in-node, or `forest` has a cycle.
87    pub fn of(forest: &Graph) -> Result<Ancestry, GraphError> {
88        // The forest check is that of graphs::is_forest, here with witnesses for the messages; a
89        // change to what counts as a forest belongs in both.
90        let n = forest.node_count() as usize;
91        let adjacency = forest.out_adjacency();
92        let adjacency_start = forest.out_adjacency_start();
93
94        // Parent per node. A second parent means in-degree > 1, which no forest has.
95        let mut parent = vec![NONE; n];
96        for node in 0..n {
97            for &child in
98                &adjacency[adjacency_start[node] as usize..adjacency_start[node + 1] as usize]
99            {
100                let slot = &mut parent[child as usize];
101                if *slot != NONE {
102                    return Err(GraphError::invalid_argument(format!(
103                        "not a forest: node {child} has more than one parent ({} and {node})",
104                        *slot
105                    )));
106                }
107                *slot = node as u32;
108            }
109        }
110
111        // BFS from all roots. With in-degree <= 1 every node is enqueued at most once, so the
112        // queue doubles as a topological order: parents before children. A node it misses lies on
113        // a cycle, a self-loop included, or below one.
114        let mut depth = vec![NONE; n];
115        let mut order = vec![0u32; n];
116        let mut tail = 0usize;
117        for node in 0..n {
118            if parent[node] == NONE {
119                depth[node] = 0;
120                order[tail] = node as u32;
121                tail += 1;
122            }
123        }
124        let mut head = 0usize;
125        while head < tail {
126            let node = order[head] as usize;
127            head += 1;
128            for &child in
129                &adjacency[adjacency_start[node] as usize..adjacency_start[node + 1] as usize]
130            {
131                depth[child as usize] = depth[node] + 1;
132                order[tail] = child;
133                tail += 1;
134            }
135        }
136        if tail != n {
137            return Err(GraphError::invalid_argument(format!(
138                "not a forest: node {} lies on a cycle",
139                node_on_cycle(&parent, &depth)
140            )));
141        }
142        Ok(with_heavy_chains(share(parent), depth, &order))
143    }
144
145    /// Returns the ancestor index of the dominator tree of `dominators`, in which the ancestors of a node
146    /// are its dominators - Java's overload `of(Dominators)`.
147    ///
148    /// `is_ancestor_of(a, b)` returns whether `a` dominates `b`. `lowest_common_ancestor_of(a, b)` returns
149    /// the closest node that dominates both, or `None` if no node does. With several entries, only a
150    /// virtual root lies above them. A node that no entry reaches is a tree of its own and dominates only
151    /// itself here; [`Dominators::is_reachable`] returns `false` for such a node.
152    ///
153    /// The result is the same as that of `Ancestry::of(&graphs::dominator_tree(dominators))`, but shares
154    /// the immediate dominators instead of building the tree as a graph.
155    ///
156    /// **Time:** O(node_count).
157    /// **Memory:** 8 x node_count bytes for the result, which shares the immediate dominators; while it
158    /// runs, 20 x node_count bytes more.
159    pub fn of_dominators(dominators: &Dominators) -> Ancestry {
160        let parent = Arc::clone(&dominators.immediate_dominator);
161        let n = parent.len();
162
163        // Children per node, then a BFS from all roots for a parents-first order and the depths.
164        // The dominator tree is acyclic by construction, so no check is needed.
165        let forest = parent_forest::children_of(&parent);
166        let mut depth = vec![0u32; n];
167        let mut order = vec![0u32; n];
168        let mut tail = 0usize;
169        for node in 0..n {
170            if parent[node] == NONE {
171                order[tail] = node as u32;
172                tail += 1;
173            }
174        }
175        let mut head = 0usize;
176        while head < tail {
177            let node = order[head] as usize;
178            head += 1;
179            for &child in
180                &forest.members[forest.start[node] as usize..forest.start[node + 1] as usize]
181            {
182                depth[child as usize] = depth[node] + 1;
183                order[tail] = child;
184                tail += 1;
185            }
186        }
187        with_heavy_chains(parent, depth, &order)
188    }
189
190    /// Number of nodes of the indexed forest.
191    #[inline]
192    fn node_count(&self) -> u32 {
193        self.parent.len() as u32
194    }
195
196    /// Returns the lowest common ancestor of `a` and `b`, or `None` if they are in different trees -
197    /// Java's `-1`.
198    ///
199    /// The lowest common ancestor is the deepest node that is an ancestor of both. As a node is its own
200    /// ancestor, the result is `a` if `a` is an ancestor of `b`.
201    ///
202    /// **Time:** O(log node_count).
203    ///
204    /// # Panics
205    /// With an `index out of bounds` message if `a` or `b` is not in `0..node_count`.
206    #[track_caller]
207    pub fn lowest_common_ancestor_of(&self, a: u32, b: u32) -> Option<u32> {
208        let n = self.node_count();
209        check_index(a, n);
210        check_index(b, n);
211        let (parent, depth, head) = (&*self.parent, &*self.depth, &*self.chain_head);
212        let (mut a, mut b) = (a as usize, b as usize);
213        // Lift whichever node sits on the deeper chain to its chain head's parent, until both are
214        // on one chain; then the shallower of the two is the ancestor of the other.
215        while head[a] != head[b] {
216            if depth[head[a] as usize] < depth[head[b] as usize] {
217                let up = parent[head[b] as usize];
218                if up == NONE {
219                    return None;
220                }
221                b = up as usize;
222            } else {
223                let up = parent[head[a] as usize];
224                if up == NONE {
225                    return None;
226                }
227                a = up as usize;
228            }
229        }
230        Some(if depth[a] < depth[b] { a } else { b } as u32)
231    }
232
233    /// Returns whether `node` is an ancestor of `descendant`: whether it lies on the path from the root of
234    /// its tree to `descendant`. Equivalent to
235    /// `lowest_common_ancestor_of(node, descendant) == Some(node)`.
236    ///
237    /// A node is its own ancestor. [`PreorderAncestry`] answers in O(1), and so does an `Ancestry` that
238    /// belongs to one.
239    ///
240    /// **Time:** O(log node_count), or O(1) for the `Ancestry` of a [`PreorderAncestry`].
241    ///
242    /// # Panics
243    /// With an `index out of bounds` message if `node` or `descendant` is not in `0..node_count`.
244    #[track_caller]
245    pub fn is_ancestor_of(&self, node: u32, descendant: u32) -> bool {
246        match &self.preorder {
247            Some(preorder) => preorder.is_ancestor_of(node, descendant),
248            None => self.lowest_common_ancestor_of(node, descendant) == Some(node),
249        }
250    }
251
252    /// Returns the depth of `node`: the number of edges from the root of its tree to it. A root has depth
253    /// `0`.
254    ///
255    /// **Time:** O(1).
256    ///
257    /// # Panics
258    /// With an `index out of bounds` message if `node` is not in `0..node_count`.
259    #[inline]
260    #[track_caller]
261    pub fn depth_of(&self, node: u32) -> u32 {
262        check_index(node, self.node_count());
263        self.depth[node as usize]
264    }
265
266    /// Returns the parent of `node`, or `None` if it is the root of its tree - Java's `-1`.
267    ///
268    /// **Time:** O(1).
269    ///
270    /// # Panics
271    /// With an `index out of bounds` message if `node` is not in `0..node_count`.
272    #[inline]
273    #[track_caller]
274    pub fn parent_of(&self, node: u32) -> Option<u32> {
275        check_index(node, self.node_count());
276        let parent = self.parent[node as usize];
277        (parent != NONE).then_some(parent)
278    }
279}
280
281/// Completes the index from the parents, the depths and an order in which every parent comes
282/// before its children.
283fn with_heavy_chains(parent: SharedArray, depth: Vec<u32>, order: &[u32]) -> Ancestry {
284    let n = parent.len();
285
286    // Subtree sizes, then the heaviest child per node. Children come after their parent in the
287    // order, so a single backward pass accumulates the sizes.
288    let mut subtree_size = vec![1u32; n];
289    let mut heavy_child = vec![NONE; n];
290    for &node in order.iter().rev() {
291        let node = node as usize;
292        let node_parent = parent[node];
293        if node_parent == NONE {
294            continue;
295        }
296        let p = node_parent as usize;
297        subtree_size[p] += subtree_size[node];
298        let rival = heavy_child[p];
299        if rival == NONE || subtree_size[node] > subtree_size[rival as usize] {
300            heavy_child[p] = node as u32;
301        }
302    }
303
304    // Chain heads, forwards this time: a heavy child continues its parent's chain, every other
305    // node starts one.
306    let mut chain_head = vec![0u32; n];
307    for &node in order {
308        let node = node as usize;
309        let node_parent = parent[node];
310        chain_head[node] =
311            if node_parent != NONE && heavy_child[node_parent as usize] == node as u32 {
312                chain_head[node_parent as usize]
313            } else {
314                node as u32
315            };
316    }
317
318    Ancestry {
319        parent,
320        depth: share(depth),
321        chain_head: share(chain_head),
322        preorder: None,
323    }
324}
325
326/// Names a node that actually lies on a cycle, not merely one hanging below it. An unreached node
327/// has an unreached parent - the search visits every child of every node it reaches - so walking up
328/// from any unreached node stays unreached and cannot end at a root. After node-count steps the
329/// walk is on the cycle it circles.
330fn node_on_cycle(parent: &[u32], depth: &[u32]) -> u32 {
331    let mut node = depth
332        .iter()
333        .position(|&d| d == NONE)
334        .expect("the caller established that some node is unreached") as u32;
335    for _ in 0..parent.len() {
336        node = parent[node as usize];
337    }
338    node
339}
340
341impl PreorderArrays {
342    #[inline]
343    #[track_caller]
344    fn is_ancestor_of(&self, node: u32, descendant: u32) -> bool {
345        let n = self.preorder_index.len() as u32;
346        check_index(node, n);
347        check_index(descendant, n);
348        let from = self.preorder_index[node as usize];
349        let at = self.preorder_index[descendant as usize];
350        at >= from && at - from < self.subtree_size[node as usize]
351    }
352}
353
354/// An [`Ancestry`] that also holds the preorder of its forest, for an ancestor test in O(1) and the
355/// nodes of every subtree.
356///
357/// [`PreorderAncestry::of`] builds it from an index and shares the arrays of that index. In preorder,
358/// every subtree is a contiguous range: the subtree of `node` takes the positions
359/// `preorder_index_of(node)..preorder_index_of(node) + subtree_size_of(node)` of
360/// [`preorder`](Self::preorder). So [`is_ancestor_of`](Self::is_ancestor_of) is a range test, and
361/// [`subtree_of`](Self::subtree_of) returns a view of that range. Here, the basic blocks of the method
362/// `load` that `body` dominates, from the `dominators` of `load`:
363///
364/// <!-- example: dominance.rs#subtreeOf -->
365/// ```
366/// # use graphity_core::{Ancestry, BiAdjacentGraph, Dominators, PreorderAncestry};
367/// # let cfg = graphity_core::Graph::of(&[0, 1, 3, 5, 6, 7, 7], &[1, 2, 5, 3, 4, 4, 1]).unwrap();
368/// # let dominators = Dominators::of(&BiAdjacentGraph::of(&cfg), 0);
369/// # let body = 2;
370/// let dominance = PreorderAncestry::of(&Ancestry::of_dominators(&dominators));
371/// let dominated_by_body = dominance.subtree_of(body); // [2, 3, 4] - body, then and next
372/// # assert_eq!(dominated_by_body, [2, 3, 4]);
373/// ```
374///
375/// The preorder visits the roots in ascending order, and the children of each node in ascending
376/// order. If the node IDs were assigned in this order, as is usual for a syntax tree numbered in
377/// source order, the preorder is `0..node_count`, and the subtree of `node` is
378/// `node..node + subtree_size_of(node)`.
379///
380/// Java's `PreorderAncestry` extends `Ancestry`; this type dereferences to its [`Ancestry`] instead.
381/// So every method of the index applies, and a `&PreorderAncestry` is accepted where a `&Ancestry` is.
382///
383/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
384///
385/// **Memory:** 12 x node_count bytes on top of the [`Ancestry`] it extends.
386#[derive(Debug, Clone)]
387pub struct PreorderAncestry {
388    ancestry: Ancestry,
389    preorder: Arc<PreorderArrays>,
390}
391
392impl PreorderAncestry {
393    /// Returns a `PreorderAncestry` for the forest of `ancestry`.
394    ///
395    /// The result shares the arrays of `ancestry` instead of copying them. The preorder is computed anew
396    /// on every call, not cached: keep the result to use it more than once. If `ancestry` already belongs
397    /// to a `PreorderAncestry`, the result shares its preorder as well.
398    ///
399    /// **Time:** O(node_count), or O(1) if already a `PreorderAncestry`.
400    /// **Memory:** +12 x node_count bytes for the result; while it runs, 8 x node_count bytes more;
401    /// none if already a `PreorderAncestry`.
402    pub fn of(ancestry: &Ancestry) -> PreorderAncestry {
403        let preorder = match &ancestry.preorder {
404            Some(preorder) => Arc::clone(preorder),
405            None => {
406                let n = ancestry.parent.len();
407                let mut preorder_index = vec![0u32; n];
408                let mut order = vec![0u32; n];
409                let mut subtree_size = vec![0u32; n];
410                parent_forest::preorder(
411                    &ancestry.parent,
412                    &mut preorder_index,
413                    &mut order,
414                    &mut subtree_size,
415                );
416                Arc::new(PreorderArrays {
417                    preorder_index: preorder_index.into_boxed_slice(),
418                    subtree_size: subtree_size.into_boxed_slice(),
419                    order: order.into_boxed_slice(),
420                })
421            }
422        };
423        PreorderAncestry {
424            ancestry: Ancestry {
425                preorder: Some(Arc::clone(&preorder)),
426                ..ancestry.clone()
427            },
428            preorder,
429        }
430    }
431
432    /// Returns whether `node` is an ancestor of `descendant`: whether it lies on the path from the root of
433    /// its tree to `descendant`. A node is its own ancestor.
434    ///
435    /// **Time:** O(1).
436    ///
437    /// # Panics
438    /// With an `index out of bounds` message if `node` or `descendant` is not in `0..node_count`.
439    #[inline]
440    #[track_caller]
441    pub fn is_ancestor_of(&self, node: u32, descendant: u32) -> bool {
442        self.preorder.is_ancestor_of(node, descendant)
443    }
444
445    /// Returns the number of nodes in the subtree of `node`, `node` included.
446    ///
447    /// **Time:** O(1).
448    ///
449    /// # Panics
450    /// With an `index out of bounds` message if `node` is not in `0..node_count`.
451    #[inline]
452    #[track_caller]
453    pub fn subtree_size_of(&self, node: u32) -> u32 {
454        check_index(node, self.preorder.subtree_size.len() as u32);
455        self.preorder.subtree_size[node as usize]
456    }
457
458    /// Returns the nodes of the subtree of `node`, in preorder, starting with `node`.
459    ///
460    /// The result is a view of this index's own array, not a copy.
461    ///
462    /// **Time:** O(1).
463    ///
464    /// # Panics
465    /// With an `index out of bounds` message if `node` is not in `0..node_count`.
466    #[track_caller]
467    pub fn subtree_of(&self, node: u32) -> &[u32] {
468        check_index(node, self.preorder.preorder_index.len() as u32);
469        let from = self.preorder.preorder_index[node as usize] as usize;
470        &self.preorder.order[from..from + self.preorder.subtree_size[node as usize] as usize]
471    }
472
473    /// Returns all nodes in preorder: the roots in ascending order, and the children of each node in
474    /// ascending order.
475    ///
476    /// The result is a view of this index's own array, not a copy.
477    ///
478    /// **Time:** O(1).
479    #[inline]
480    pub fn preorder(&self) -> &[u32] {
481        &self.preorder.order
482    }
483
484    /// Returns the position of `node` in [`preorder`](Self::preorder).
485    ///
486    /// Data in an array indexed by preorder position has every subtree in a contiguous range. Prefix
487    /// sums over such an array, for example, give the sum over any subtree in O(1).
488    ///
489    /// **Time:** O(1).
490    ///
491    /// # Panics
492    /// With an `index out of bounds` message if `node` is not in `0..node_count`.
493    #[inline]
494    #[track_caller]
495    pub fn preorder_index_of(&self, node: u32) -> u32 {
496        check_index(node, self.preorder.preorder_index.len() as u32);
497        self.preorder.preorder_index[node as usize]
498    }
499
500    /// Returns this index as a plain [`Ancestry`]; the same as dereferencing.
501    ///
502    /// **Time:** O(1).
503    #[inline]
504    pub fn as_ancestry(&self) -> &Ancestry {
505        &self.ancestry
506    }
507}
508
509impl Deref for PreorderAncestry {
510    type Target = Ancestry;
511
512    #[inline]
513    fn deref(&self) -> &Ancestry {
514        &self.ancestry
515    }
516}
517
518impl AsRef<Ancestry> for PreorderAncestry {
519    fn as_ref(&self) -> &Ancestry {
520        &self.ancestry
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527    use crate::GraphBuilder;
528
529    #[test]
530    fn of_a_preorder_ancestry_shares_its_preorder() {
531        let mut b = GraphBuilder::new();
532        b.add_nodes(3);
533        b.add_path(&[0, 1, 2]);
534        let preorder = PreorderAncestry::of(&Ancestry::of(&b.build()).unwrap());
535        let again = PreorderAncestry::of(&preorder);
536        assert!(Arc::ptr_eq(&preorder.preorder, &again.preorder));
537        assert!(Arc::ptr_eq(&preorder.parent, &again.parent));
538    }
539}