pattern_compiler/cfg/
mod.rs
1use ::std::collections::HashMap;
2
3use ::petgraph::Graph;
4use ::petgraph::graph::NodeIndex;
5
6mod generate_dot;
7
8use super::pattern::PatternProvider;
9
10pub type CfgNodeIndex = NodeIndex;
11
12#[derive(Debug, Clone)]
18pub struct PatternCfg<P> where P: PatternProvider {
19 pub entry: CfgNodeIndex,
20 pub graph: Graph<CfgNodeKind<P::CfgVariable>, CfgEdge<P>>,
21 pub leaves: HashMap<usize, NodeIndex>,
22 pub leaf_bindings: HashMap<NodeIndex, HashMap<P::CfgVariable, P::PatternNodeKey>>,
23}
24
25impl<P> PatternCfg<P> where P: PatternProvider {
26
27 pub fn new() -> Self {
28 let mut graph = Graph::new();
29 PatternCfg {
30 entry: graph.add_node(CfgNodeKind::Root),
31 graph: graph,
32 leaves: HashMap::new(),
33 leaf_bindings: HashMap::new(),
34 }
35 }
36
37 pub fn add_fail(&mut self) -> CfgNodeIndex {
38 self.graph.add_node(CfgNodeKind::Fail)
39 }
40
41 pub fn add_leaf(&mut self, num: usize) -> CfgNodeIndex {
42 assert!(!self.leaves.contains_key(&num));
43 let index = self.graph.add_node(CfgNodeKind::Leaf(num));
44 self.leaves.insert(num, index);
45 index
46 }
47
48 pub fn get_entry(&self) -> CfgNodeIndex {
49 self.entry
50 }
51
52 pub fn add_node(&mut self, var: P::CfgVariable) -> CfgNodeIndex {
53 self.graph.add_node(CfgNodeKind::Match(var))
54 }
55
56 pub fn add_edge(&mut self, parent: CfgNodeIndex, child: CfgNodeIndex,
57 edge: CfgEdge<P>) {
58 self.graph.add_edge(parent, child, edge);
59 }
60
61 pub fn add_child(&mut self, parent: CfgNodeIndex, typ: CfgEdge<P>,
62 var: P::CfgVariable) -> CfgNodeIndex {
63 let child = self.graph.add_node(CfgNodeKind::Match(var));
64 self.graph.add_edge(parent, child, typ);
65 child
66 }
67
68}
69
70#[derive(Clone)]
71pub struct CfgEdge<P> where P: PatternProvider {
72 pub kind: P::PatternNodeKind,
74 pub variable_binds: Vec<P::CfgVariable>,
75 }
77impl<P> ::std::fmt::Debug for CfgEdge<P> where P: PatternProvider {
78 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
79 write!(f, "{:?} {:?}", self.kind, self.variable_binds)
80 }
81}
82
83#[derive(Debug, Clone)]
84pub enum CfgNodeKind<CVT> {
85 Root,
86 Match(CVT),
87 Fail,
88 Leaf(usize),
89}