Skip to main content

mid_tools/
dot.rs

1use std::{
2    borrow::Cow,
3    collections::BTreeMap,
4    fmt::{self, Display},
5};
6
7use indexmap::IndexMap;
8
9use crate::autom::Accept;
10
11macro_rules! attr {
12    ($id:ident, $name:literal) => {
13        pub fn $id<S: Into<Cow<'a, str>>>(&mut self, $id: S) {
14            self.attrs.insert($name, $id.into());
15        }
16    };
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub enum GraphType {
21    Undirected,
22    Directed,
23}
24
25impl Display for GraphType {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(match self {
28            Self::Undirected => "graph",
29            Self::Directed => "digraph",
30        })
31    }
32}
33
34#[derive(Debug)]
35enum NodeLike<'a> {
36    Node(Node<'a>),
37    Subgraph(Graph<'a>),
38}
39
40#[derive(Debug)]
41pub struct Graph<'a> {
42    ty: Option<GraphType>,
43    id: Option<Cow<'a, str>>,
44    attrs: BTreeMap<&'static str, Cow<'a, str>>,
45    nodes: IndexMap<Cow<'a, str>, NodeLike<'a>>,
46    edges: IndexMap<(Cow<'a, str>, Cow<'a, str>), Vec<Edge<'a>>>,
47}
48
49impl<'a> Graph<'a> {
50    attr!(style, "style");
51
52    attr!(label, "label");
53
54    attr!(penwidth, "penwidth");
55
56    #[must_use]
57    #[inline]
58    pub fn new(ty: GraphType) -> Self { Self::new_impl(Some(ty), None) }
59
60    #[must_use]
61    #[inline]
62    pub fn new_with_id<S: Into<Cow<'a, str>>>(ty: GraphType, id: S) -> Self {
63        Self::new_impl(Some(ty), Some(id.into()))
64    }
65
66    fn new_impl(ty: Option<GraphType>, id: Option<Cow<'a, str>>) -> Self {
67        Self {
68            ty,
69            id,
70            attrs: BTreeMap::new(),
71            nodes: IndexMap::new(),
72            edges: IndexMap::new(),
73        }
74    }
75
76    #[inline]
77    pub fn node<S: Into<Cow<'a, str>>>(&mut self, id: S) -> &mut Node<'a> {
78        use indexmap::map::Entry;
79
80        let entry = match self.nodes.entry(id.into()) {
81            Entry::Vacant(v) => v.insert(NodeLike::Node(Node::default())),
82            Entry::Occupied(e) => {
83                assert!(
84                    matches!(e.get(), NodeLike::Node(_)),
85                    "Invalid node-like {:?}, expected a node",
86                    e.key()
87                );
88                e.into_mut()
89            },
90        };
91
92        if let NodeLike::Node(n) = entry {
93            n
94        } else {
95            unreachable!()
96        }
97    }
98
99    #[inline]
100    pub fn subgraph<S: Into<Cow<'a, str>>>(&mut self, id: S) -> &mut Graph<'a> {
101        use indexmap::map::Entry;
102
103        let entry = match self.nodes.entry(id.into()) {
104            Entry::Vacant(v) => v.insert(NodeLike::Subgraph(Graph::new_impl(None, None))),
105            Entry::Occupied(e) => {
106                assert!(
107                    matches!(e.get(), NodeLike::Subgraph(_)),
108                    "Invalid node-like {:?}, expected a subgraph",
109                    e.key()
110                );
111                e.into_mut()
112            },
113        };
114
115        if let NodeLike::Subgraph(g) = entry {
116            g
117        } else {
118            unreachable!()
119        }
120    }
121
122    #[inline]
123    pub fn edge<L: Into<Cow<'a, str>>, R: Into<Cow<'a, str>>>(
124        &mut self,
125        l: L,
126        r: R,
127    ) -> &mut Edge<'a> {
128        let l = l.into();
129        let r = r.into();
130        self.node(l.clone());
131        self.node(r.clone());
132        let edges = self.edges.entry((l, r)).or_default();
133        edges.push(Edge::default());
134        edges.last_mut().unwrap_or_else(|| unreachable!())
135    }
136
137    pub(crate) fn state_machine<
138        State: Copy,
139        Input,
140        NodeTok: Accept,
141        EdgeTok: Accept,
142        IterStates: IntoIterator<Item = (State, IterEdges, NodeTok)>,
143        IterEdges: IntoIterator<Item = (Input, IterDeltas)>,
144        IterDeltas: IntoIterator<Item = (EdgeTok, State)>,
145        G: FnMut(State) -> u32,
146        FS: Fn(State) -> Cow<'a, str>,
147        FI: Fn(Input) -> Cow<'a, str>,
148        FT: Fn(&NodeTok::Token) -> Option<Cow<'a, str>>,
149        FE: Fn(&EdgeTok::Token) -> Option<Cow<'a, str>>,
150    >(
151        nodes: IterStates,
152        start: State,
153        mut get_id: G,
154        fmt_state: FS,
155        fmt_input: FI,
156        fmt_node_tok: FT,
157        fmt_edge_tok: FE,
158    ) -> Self {
159        let mut graph = Self::new(GraphType::Directed);
160        let mut edge_info = IndexMap::new();
161
162        for (state, edges, accept) in nodes {
163            let id = Cow::from(get_id(state).to_string());
164            let node = graph.node(id.clone());
165
166            let mut label = fmt_state(state);
167            if let Some(tok) = accept.as_token() {
168                if let Some(tok) = fmt_node_tok(tok) {
169                    label = format!("{label}:{tok}").into();
170                }
171
172                node.border_count("2");
173            }
174
175            node.label(label);
176
177            for (input, outputs) in edges {
178                let input = fmt_input(input);
179
180                for (accept, next_state) in outputs {
181                    use indexmap::map::Entry;
182
183                    let mut label = None;
184                    let accept = if let Some(tok) = accept.as_token() {
185                        if let Some(tok) = fmt_edge_tok(tok) {
186                            label = Some(format!("{input}/{tok}").into());
187                        }
188
189                        true
190                    } else {
191                        false
192                    };
193
194                    let label = label.unwrap_or_else(|| input.clone());
195
196                    match edge_info.entry((id.clone(), get_id(next_state).to_string())) {
197                        Entry::Vacant(v) => {
198                            v.insert((accept, label));
199                        },
200                        Entry::Occupied(mut o) => {
201                            let s = &mut o.get_mut().1;
202                            *s = format!("{s},{label}").into();
203                        },
204                    }
205                }
206            }
207        }
208
209        for ((from, to), (accept, label)) in edge_info {
210            let edge = graph.edge(from, to);
211
212            if accept {
213                edge.pen_width("2");
214            }
215
216            edge.label(label);
217        }
218
219        let start_id = Cow::from("_start");
220        let start_node = graph.node(start_id.clone());
221        start_node.style("invis");
222        start_node.shape("point");
223        start_node.label("");
224        graph.edge(start_id, get_id(start).to_string());
225
226        graph
227    }
228}
229
230#[derive(Default)]
231struct AttrState {
232    any: bool,
233}
234
235impl AttrState {
236    fn write_one(
237        &mut self,
238        f: &mut fmt::Formatter,
239        key: &'static str,
240        val: impl FnOnce(&mut fmt::Formatter) -> fmt::Result,
241    ) -> fmt::Result {
242        f.write_str(if self.any {
243            ","
244        } else {
245            self.any = true;
246            "["
247        })?;
248
249        f.write_str(key)?;
250        f.write_str("=")?;
251        val(f)
252    }
253
254    fn finish(self, f: &mut fmt::Formatter) -> fmt::Result {
255        if self.any {
256            f.write_str("]")
257        } else {
258            Ok(())
259        }
260    }
261}
262
263impl Graph<'_> {
264    fn fmt_impl(&self, f: &mut fmt::Formatter, sub_id: Option<(GraphType, &str)>) -> fmt::Result {
265        let Self {
266            ty,
267            id,
268            attrs,
269            nodes,
270            edges,
271        } = self;
272
273        let ty = match (ty, sub_id) {
274            (ty, None) => {
275                let ty = ty.unwrap();
276                write!(f, "{ty}")?;
277
278                if let Some(id) = id {
279                    write!(f, " {id:?}")?;
280                }
281
282                ty
283            },
284            (ty, sub) => {
285                assert!(ty.is_none() && id.is_none());
286                let (ty, sub) = sub.unwrap();
287
288                write!(f, "subgraph {sub:?}")?;
289
290                ty
291            },
292        };
293
294        f.write_str(" {")?;
295
296        for (key, val) in attrs {
297            write!(f, "{key}={val:?};")?;
298        }
299
300        for (id, node) in nodes {
301            match node {
302                NodeLike::Node(Node { attrs }) => {
303                    let mut attr_state = AttrState::default();
304                    write!(f, "{id:?}")?;
305
306                    for (key, val) in attrs {
307                        attr_state.write_one(f, key, |f| write!(f, "{val:?}"))?;
308                    }
309
310                    attr_state.finish(f)?;
311                },
312                NodeLike::Subgraph(graph) => {
313                    graph.fmt_impl(f, Some((ty, id)))?;
314                },
315            }
316
317            f.write_str(";")?;
318        }
319
320        for ((l, r), edges) in edges {
321            for Edge { attrs } in edges {
322                let mut attr_state = AttrState::default();
323                write!(f, "{l:?}{}{r:?}", match ty {
324                    GraphType::Undirected => "--",
325                    GraphType::Directed => "->",
326                })?;
327
328                for (key, val) in attrs {
329                    attr_state.write_one(f, key, |f| write!(f, "{val:?}"))?;
330                }
331
332                attr_state.finish(f)?;
333                f.write_str(";")?;
334            }
335        }
336
337        f.write_str("}")
338    }
339}
340
341impl Display for Graph<'_> {
342    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.fmt_impl(f, None) }
343}
344
345#[derive(Debug, Default)]
346pub struct Node<'a> {
347    attrs: BTreeMap<&'static str, Cow<'a, str>>,
348}
349
350impl<'a> Node<'a> {
351    attr!(style, "style");
352
353    attr!(shape, "shape");
354
355    attr!(margin, "margin");
356
357    attr!(label, "label");
358
359    attr!(border_count, "peripheries");
360
361    attr!(edge_ordering, "ordering");
362}
363
364#[derive(Debug, Default)]
365pub struct Edge<'a> {
366    attrs: BTreeMap<&'static str, Cow<'a, str>>,
367}
368
369impl<'a> Edge<'a> {
370    attr!(style, "style");
371
372    attr!(min_len, "minlen");
373
374    attr!(constraint, "constraint");
375
376    attr!(concentrate, "concentrate");
377
378    attr!(pen_width, "penwidth");
379
380    attr!(color, "color");
381
382    attr!(label, "label");
383}