|
| 1 | +//! Data structure summarizing static nodes of a Hugr and their uses |
| 2 | +use std::collections::HashMap; |
| 3 | + |
| 4 | +use crate::{HugrView, Node, core::HugrNode, ops::OpType}; |
| 5 | +use petgraph::{Graph, visit::EdgeRef}; |
| 6 | + |
| 7 | +/// Weight for an edge in a [`ModuleGraph`] |
| 8 | +#[derive(Clone, Debug, PartialEq, Eq)] |
| 9 | +#[non_exhaustive] |
| 10 | +pub enum StaticEdge<N = Node> { |
| 11 | + /// Edge corresponds to a [Call](OpType::Call) node (specified) in the Hugr |
| 12 | + Call(N), |
| 13 | + /// Edge corresponds to a [`LoadFunction`](OpType::LoadFunction) node (specified) in the Hugr |
| 14 | + LoadFunction(N), |
| 15 | + /// Edge corresponds to a [LoadConstant](OpType::LoadConstant) node (specified) in the Hugr |
| 16 | + LoadConstant(N), |
| 17 | +} |
| 18 | + |
| 19 | +/// Weight for a petgraph-node in a [`ModuleGraph`] |
| 20 | +#[derive(Clone, Debug, PartialEq, Eq)] |
| 21 | +#[non_exhaustive] |
| 22 | +pub enum StaticNode<N = Node> { |
| 23 | + /// petgraph-node corresponds to a [`FuncDecl`](OpType::FuncDecl) node (specified) in the Hugr |
| 24 | + FuncDecl(N), |
| 25 | + /// petgraph-node corresponds to a [`FuncDefn`](OpType::FuncDefn) node (specified) in the Hugr |
| 26 | + FuncDefn(N), |
| 27 | + /// petgraph-node corresponds to the [HugrView::entrypoint], that is not |
| 28 | + /// a [`FuncDefn`](OpType::FuncDefn). Note that it will not be a [Module](OpType::Module) |
| 29 | + /// either, as such a node could not have edges, so is not represented in the petgraph. |
| 30 | + NonFuncEntrypoint, |
| 31 | + /// petgraph-node corresponds to a constant; will have no outgoing edges, and incoming |
| 32 | + /// edges will be [StaticEdge::LoadConstant] |
| 33 | + Const(N), |
| 34 | +} |
| 35 | + |
| 36 | +/// Details the [`FuncDefn`]s, [`FuncDecl`]s and module-level [`Const`]s in a Hugr, |
| 37 | +/// in a Hugr, along with the [`Call`]s, [`LoadFunction`]s, and [`LoadConstant`]s connecting them. |
| 38 | +/// |
| 39 | +/// Each node in the `ModuleGraph` corresponds to a module-level function or const; |
| 40 | +/// each edge corresponds to a use of the target contained in the edge's source. |
| 41 | +/// |
| 42 | +/// For Hugrs whose entrypoint is neither a [Module](OpType::Module) nor a [`FuncDefn`], |
| 43 | +/// the static graph will have an additional [`StaticNode::NonFuncEntrypoint`] |
| 44 | +/// corresponding to the Hugr's entrypoint, with no incoming edges. |
| 45 | +/// |
| 46 | +/// [`Call`]: OpType::Call |
| 47 | +/// [`Const`]: OpType::Const |
| 48 | +/// [`FuncDecl`]: OpType::FuncDecl |
| 49 | +/// [`FuncDefn`]: OpType::FuncDefn |
| 50 | +/// [`LoadConstant`]: OpType::LoadConstant |
| 51 | +/// [`LoadFunction`]: OpType::LoadFunction |
| 52 | +pub struct ModuleGraph<N = Node> { |
| 53 | + g: Graph<StaticNode<N>, StaticEdge<N>>, |
| 54 | + node_to_g: HashMap<N, petgraph::graph::NodeIndex<u32>>, |
| 55 | +} |
| 56 | + |
| 57 | +impl<N: HugrNode> ModuleGraph<N> { |
| 58 | + /// Makes a new `ModuleGraph` for a Hugr. |
| 59 | + pub fn new(hugr: &impl HugrView<Node = N>) -> Self { |
| 60 | + let mut g = Graph::default(); |
| 61 | + let mut node_to_g = hugr |
| 62 | + .children(hugr.module_root()) |
| 63 | + .filter_map(|n| { |
| 64 | + let weight = match hugr.get_optype(n) { |
| 65 | + OpType::FuncDecl(_) => StaticNode::FuncDecl(n), |
| 66 | + OpType::FuncDefn(_) => StaticNode::FuncDefn(n), |
| 67 | + OpType::Const(_) => StaticNode::Const(n), |
| 68 | + _ => return None, |
| 69 | + }; |
| 70 | + Some((n, g.add_node(weight))) |
| 71 | + }) |
| 72 | + .collect::<HashMap<_, _>>(); |
| 73 | + if !hugr.entrypoint_optype().is_module() && !node_to_g.contains_key(&hugr.entrypoint()) { |
| 74 | + node_to_g.insert(hugr.entrypoint(), g.add_node(StaticNode::NonFuncEntrypoint)); |
| 75 | + } |
| 76 | + for (func, cg_node) in &node_to_g { |
| 77 | + traverse(hugr, *cg_node, *func, &mut g, &node_to_g); |
| 78 | + } |
| 79 | + fn traverse<N: HugrNode>( |
| 80 | + h: &impl HugrView<Node = N>, |
| 81 | + enclosing_func: petgraph::graph::NodeIndex<u32>, |
| 82 | + node: N, // Nonstrict-descendant of `enclosing_func`` |
| 83 | + g: &mut Graph<StaticNode<N>, StaticEdge<N>>, |
| 84 | + node_to_g: &HashMap<N, petgraph::graph::NodeIndex<u32>>, |
| 85 | + ) { |
| 86 | + for ch in h.children(node) { |
| 87 | + traverse(h, enclosing_func, ch, g, node_to_g); |
| 88 | + let weight = match h.get_optype(ch) { |
| 89 | + OpType::Call(_) => StaticEdge::Call(ch), |
| 90 | + OpType::LoadFunction(_) => StaticEdge::LoadFunction(ch), |
| 91 | + OpType::LoadConstant(_) => StaticEdge::LoadConstant(ch), |
| 92 | + _ => continue, |
| 93 | + }; |
| 94 | + if let Some(target) = h.static_source(ch) { |
| 95 | + if h.get_parent(target) == Some(h.module_root()) { |
| 96 | + g.add_edge(enclosing_func, node_to_g[&target], weight); |
| 97 | + } else { |
| 98 | + assert!(!node_to_g.contains_key(&target)); |
| 99 | + assert!(h.get_optype(ch).is_load_constant()); |
| 100 | + assert!(h.get_optype(target).is_const()); |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + ModuleGraph { g, node_to_g } |
| 106 | + } |
| 107 | + |
| 108 | + /// Allows access to the petgraph |
| 109 | + #[must_use] |
| 110 | + pub fn graph(&self) -> &Graph<StaticNode<N>, StaticEdge<N>> { |
| 111 | + &self.g |
| 112 | + } |
| 113 | + |
| 114 | + /// Convert a Hugr [Node] into a petgraph node index. |
| 115 | + /// Result will be `None` if `n` is not a [`FuncDefn`](OpType::FuncDefn), |
| 116 | + /// [`FuncDecl`](OpType::FuncDecl) or the [HugrView::entrypoint]. |
| 117 | + pub fn node_index(&self, n: N) -> Option<petgraph::graph::NodeIndex<u32>> { |
| 118 | + self.node_to_g.get(&n).copied() |
| 119 | + } |
| 120 | + |
| 121 | + /// Returns an iterator over the out-edges from the given Node, i.e. |
| 122 | + /// edges to the functions/constants called/loaded by it. |
| 123 | + /// |
| 124 | + /// If the node is not recognised as a function or the entrypoint, |
| 125 | + /// for example if it is a [`Const`](OpType::Const), the iterator will be empty. |
| 126 | + pub fn out_edges(&self, n: N) -> impl Iterator<Item = (&StaticEdge<N>, &StaticNode<N>)> { |
| 127 | + let g = self.graph(); |
| 128 | + self.node_index(n).into_iter().flat_map(move |n| { |
| 129 | + self.graph().edges(n).map(|e| { |
| 130 | + ( |
| 131 | + g.edge_weight(e.id()).unwrap(), |
| 132 | + g.node_weight(e.target()).unwrap(), |
| 133 | + ) |
| 134 | + }) |
| 135 | + }) |
| 136 | + } |
| 137 | + |
| 138 | + /// Returns an iterator over the in-edges to the given Node, i.e. |
| 139 | + /// edges from the (necessarily) functions that call/load it. |
| 140 | + /// |
| 141 | + /// If the node is not recognised as a function or constant, |
| 142 | + /// for example if it is a non-function entrypoint, the iterator will be empty. |
| 143 | + pub fn in_edges(&self, n: N) -> impl Iterator<Item = (&StaticNode<N>, &StaticEdge<N>)> { |
| 144 | + let g = self.graph(); |
| 145 | + self.node_index(n).into_iter().flat_map(move |n| { |
| 146 | + self.graph() |
| 147 | + .edges_directed(n, petgraph::Direction::Incoming) |
| 148 | + .map(|e| { |
| 149 | + ( |
| 150 | + g.node_weight(e.source()).unwrap(), |
| 151 | + g.edge_weight(e.id()).unwrap(), |
| 152 | + ) |
| 153 | + }) |
| 154 | + }) |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +#[cfg(test)] |
| 159 | +mod test { |
| 160 | + use itertools::Itertools as _; |
| 161 | + |
| 162 | + use crate::builder::{ |
| 163 | + Container, Dataflow, DataflowSubContainer, HugrBuilder, ModuleBuilder, endo_sig, inout_sig, |
| 164 | + }; |
| 165 | + use crate::extension::prelude::{ConstUsize, usize_t}; |
| 166 | + use crate::ops::{Value, handle::NodeHandle}; |
| 167 | + |
| 168 | + use super::*; |
| 169 | + |
| 170 | + #[test] |
| 171 | + fn edges() { |
| 172 | + let mut mb = ModuleBuilder::new(); |
| 173 | + let cst = mb.add_constant(Value::from(ConstUsize::new(42))); |
| 174 | + let callee = mb.define_function("callee", endo_sig(usize_t())).unwrap(); |
| 175 | + let ins = callee.input_wires(); |
| 176 | + let callee = callee.finish_with_outputs(ins).unwrap(); |
| 177 | + let mut caller = mb |
| 178 | + .define_function("caller", inout_sig(vec![], usize_t())) |
| 179 | + .unwrap(); |
| 180 | + let val = caller.load_const(&cst); |
| 181 | + let call = caller.call(callee.handle(), &[], vec![val]).unwrap(); |
| 182 | + let caller = caller.finish_with_outputs(call.outputs()).unwrap(); |
| 183 | + let h = mb.finish_hugr().unwrap(); |
| 184 | + |
| 185 | + let mg = ModuleGraph::new(&h); |
| 186 | + let call_edge = StaticEdge::Call(call.node()); |
| 187 | + let load_const_edge = StaticEdge::LoadConstant(val.node()); |
| 188 | + |
| 189 | + assert_eq!(mg.out_edges(callee.node()).next(), None); |
| 190 | + assert_eq!( |
| 191 | + mg.in_edges(callee.node()).collect_vec(), |
| 192 | + [(&StaticNode::FuncDefn(caller.node()), &call_edge,)] |
| 193 | + ); |
| 194 | + |
| 195 | + assert_eq!( |
| 196 | + mg.out_edges(caller.node()).collect_vec(), |
| 197 | + [ |
| 198 | + (&call_edge, &StaticNode::FuncDefn(callee.node()),), |
| 199 | + (&load_const_edge, &StaticNode::Const(cst.node()),) |
| 200 | + ] |
| 201 | + ); |
| 202 | + assert_eq!(mg.in_edges(caller.node()).next(), None); |
| 203 | + |
| 204 | + assert_eq!(mg.out_edges(cst.node()).next(), None); |
| 205 | + assert_eq!( |
| 206 | + mg.in_edges(cst.node()).collect_vec(), |
| 207 | + [(&StaticNode::FuncDefn(caller.node()), &load_const_edge,)] |
| 208 | + ); |
| 209 | + } |
| 210 | +} |
0 commit comments