Skip to main content

mid_tools/dfa/
optimize.rs

1use std::{collections::BTreeMap, fmt, hash::Hash};
2
3use super::Dfa;
4use crate::{
5    dfa::{collect_state_keys, collect_states, State, DFA_START},
6    egraph::{self, prelude::*, trace::dot, EGraphTrace, ENode},
7    free::Succ,
8    partition_map::Partition,
9    union_find::ClassId,
10};
11
12// NOTE: Ord is not exactly mathematically sound here, but in this case I need
13// it to make this insertable into BTreeMaps
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub enum Op<I, T, E> {
16    Node {
17        accept: T,
18        edges: BTreeMap<Partition<I>, E>,
19    },
20    Impostor(usize),
21}
22
23impl<I: fmt::Debug, T: fmt::Debug, E: fmt::Debug> dot::Format for Op<I, T, E> {
24    fn fmt_node(&self, f: &mut fmt::Formatter) -> fmt::Result {
25        match self {
26            Self::Node { accept, .. } => f.write_fmt(format_args!("accept {accept:?}")),
27            Self::Impostor(n) => f.write_fmt(format_args!("(impostor {n:?})")),
28        }
29    }
30
31    fn fmt_edge(&self, idx: usize, f: &mut fmt::Formatter) -> fmt::Result {
32        match self {
33            Self::Node { edges, .. } => {
34                f.write_fmt(format_args!("{:?}", edges.iter().nth(idx).unwrap()))
35            },
36            Self::Impostor(_) => unreachable!(),
37        }
38    }
39}
40
41#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Node;
43
44pub type Graph<I, T, E> = egraph::fast::EGraph<Op<I, T, E>, Node>;
45pub type Output<I, T, E, G = Graph<I, T, E>> = (Dfa<I, T, E>, G, Vec<ClassId<Node>>);
46
47#[inline]
48pub(super) fn run_default<
49    I: Clone + Ord + Hash + Succ,
50    T: Clone + Ord + Hash,
51    E: Clone + Ord + Hash,
52>(
53    dfa: &Dfa<I, T, E>,
54) -> Output<I, T, E> {
55    run::<I, T, E, Graph<I, T, E>, ()>(dfa, Graph::default(), &mut ())
56}
57
58pub fn run<
59    I: Clone + Ord + Hash + Succ,
60    T: Clone + Ord + Hash,
61    E: Clone + Ord,
62    G: EGraphUpgradeTrace<FuncSymbol = Op<I, T, E>, Class = Node>,
63    R: EGraphTrace<Op<I, T, E>, Node>,
64>(
65    dfa: &Dfa<I, T, E>,
66    mut eg: G,
67    t: &mut R,
68) -> Output<I, T, E, G> {
69    enum Command<N> {
70        Explore(N),
71        Add(N),
72    }
73
74    let mut stk = Vec::new();
75    let mut classes = BTreeMap::new();
76    let mut impostors = BTreeMap::new();
77
78    stk.push(Command::Explore(DFA_START));
79
80    while let Some(node) = stk.pop() {
81        match node {
82            Command::Explore(n) => {
83                use std::collections::btree_map::Entry;
84
85                match classes.entry(n) {
86                    Entry::Occupied(_) => continue,
87                    Entry::Vacant(v) => drop(v.insert(None)),
88                }
89
90                let state = &dfa.0[n];
91                stk.push(Command::Add(n));
92                for (_, n) in state.0.values().cloned() {
93                    if !classes.contains_key(&n) {
94                        stk.push(Command::Explore(n));
95                    }
96                }
97            },
98            Command::Add(n) => {
99                let State(ref edges, ref accept) = dfa.0[n];
100                let enode = ENode::new(
101                    Op::Node {
102                        accept: accept.clone(),
103                        edges: edges
104                            .ranges()
105                            .map(|(k, (e, _))| (k.to_owned(), e.clone()))
106                            .collect(),
107                    }
108                    .into(),
109                    edges
110                        .values()
111                        .cloned()
112                        .map(|(_, n)| {
113                            classes[&n].unwrap_or_else(|| {
114                                *impostors.entry(n).or_insert_with(|| {
115                                    eg.add(ENode::new(Op::Impostor(n).into(), [].into()))
116                                        .unwrap()
117                                })
118                            })
119                        })
120                        .collect(),
121                );
122
123                let class = eg.add(enode.clone()).unwrap();
124                assert!(classes.get_mut(&n).unwrap().replace(class).is_none());
125            },
126        }
127    }
128
129    let classes: BTreeMap<_, _> = classes.into_iter().map(|(k, v)| (k, v.unwrap())).collect();
130
131    let mut wr = eg.write_trace(t);
132    for (node, class) in impostors {
133        wr.merge(classes[&node], class).unwrap();
134    }
135    drop(wr);
136
137    let nodes = eg.class_nodes();
138    let state_ids = collect_state_keys(
139        nodes.keys().copied(),
140        &eg.find(*classes.get(&DFA_START).unwrap()).unwrap(),
141    );
142
143    let (states, state_classes) = collect_states(
144        &state_ids,
145        eg.class_nodes().into_iter().map(|(s, mut n)| {
146            n.retain(|n| !matches!(n.op(), Op::Impostor(_)));
147            assert!(n.len() == 1);
148
149            let node = &n.into_iter().next().unwrap();
150            let Op::Node { accept, edges } = node.op() else {
151                unreachable!();
152            };
153            let args = node.args();
154
155            (
156                s,
157                State(
158                    edges
159                        .iter()
160                        .enumerate()
161                        .map(|(i, (e, t))| {
162                            (e.clone(), (t.clone(), *state_ids.get(&args[i]).unwrap()))
163                        })
164                        .collect(),
165                    accept.clone(),
166                ),
167            )
168        }),
169    );
170
171    drop(nodes);
172    (Dfa::new(states), eg, state_classes)
173}
174
175#[cfg(test)]
176mod test {
177    use std::{fmt, hash::Hash};
178
179    use foldhash::fast::FixedState;
180    use hashbrown::HashMap;
181    use proptest::prelude::*;
182
183    use super::EGraphUpgrade;
184    use crate::{
185        egraph::{self, congr, fast, reference, test_tools::EGraphParts},
186        free::Succ,
187        range_map::RangeMap,
188        re::kleene,
189    };
190
191    // fn print_snap(dot::Snapshot { graph }: dot::Snapshot) { println!("{graph}") }
192
193    // struct FlushOnDrop(DotTracer<dot::RichFormatter, fn(dot::Snapshot)>);
194
195    // impl FlushOnDrop {
196    //     fn new() -> Self { Self(DotTracer::rich(print_snap)) }
197    // }
198
199    // impl Drop for FlushOnDrop {
200    //     fn drop(&mut self) {
201    //         if thread::panicking() {
202    //             println!("================");
203    //             self.0.flush();
204    //         }
205    //     }
206    // }
207
208    fn run<
209        G: EGraphUpgrade<FuncSymbol = super::Op<I, T, E>, Class = super::Node>,
210        I: Clone + Ord + Hash + Succ + fmt::Debug,
211        T: Clone + Ord + Hash + fmt::Debug,
212        E: Clone + Ord,
213    >(
214        dfa: &super::Dfa<I, T, E>,
215        egraph: G,
216    ) -> super::Output<I, T, E, G> {
217        super::run::<_, _, _, G, _>(dfa, egraph, &mut ())
218    }
219
220    #[expect(clippy::type_complexity, reason = "chill out man, it's a test helper")]
221    fn run_ref<I: Clone + Ord + Hash + Succ, T: Clone + Ord + Hash, E: Clone + Ord + Hash>(
222        dfa: &super::Dfa<I, T, E>,
223    ) -> super::Output<I, T, E, reference::EGraph<super::Op<I, T, E>, super::Node>> {
224        super::run(dfa, reference::EGraph::default(), &mut ())
225    }
226
227    fn assert_equiv<
228        I: fmt::Debug + Clone + Ord,
229        T: fmt::Debug + Clone + Ord,
230        E: fmt::Debug + Clone + Ord,
231        L: Into<EGraphParts<super::Op<I, T, E>, super::Node>>,
232        R: Into<EGraphParts<super::Op<I, T, E>, super::Node>>,
233    >(
234        lhs: super::Output<I, T, E, L>,
235        rhs: super::Output<I, T, E, R>,
236    ) {
237        let (lhs, lhs_graph, lhs_cm) = lhs;
238        let (rhs, rhs_graph, rhs_cm) = rhs;
239
240        let mapping = egraph::test_tools::assert_equiv(lhs_graph, rhs_graph);
241
242        let lhs: HashMap<_, (RangeMap<_, _>, _)> = lhs
243            .into_states()
244            .into_iter()
245            .enumerate()
246            .map(|(i, super::State(e, t))| {
247                (
248                    lhs_cm[i],
249                    (
250                        e.into_ranges()
251                            .map(|(i, (e, s))| (i, (e, lhs_cm[s])))
252                            .collect(),
253                        t,
254                    ),
255                )
256            })
257            .collect();
258
259        let rhs: HashMap<_, (RangeMap<_, _>, _)> = rhs
260            .into_states()
261            .into_iter()
262            .enumerate()
263            .map(|(i, super::State(e, t))| {
264                (
265                    rhs_cm[i],
266                    (
267                        e.into_ranges()
268                            .map(|(i, (e, s))| (i, (e, rhs_cm[s])))
269                            .collect(),
270                        t,
271                    ),
272                )
273            })
274            .collect();
275
276        let lhs_mapped: HashMap<_, _> = lhs
277            .iter()
278            .map(|(s, (e, t))| {
279                (
280                    *mapping.image(s).unwrap(),
281                    (
282                        e.ranges()
283                            .map(|(k, (e, v))| {
284                                (k.to_owned(), (e.clone(), *mapping.image(v).unwrap()))
285                            })
286                            .collect(),
287                        t.clone(),
288                    ),
289                )
290            })
291            .collect();
292
293        let rhs_mapped: HashMap<_, _> = rhs
294            .iter()
295            .map(|(s, (e, t))| {
296                (
297                    *mapping.preimage(s).unwrap(),
298                    (
299                        e.ranges()
300                            .map(|(k, (e, v))| {
301                                (k.to_owned(), (e.clone(), *mapping.preimage(v).unwrap()))
302                            })
303                            .collect(),
304                        t.clone(),
305                    ),
306                )
307            })
308            .collect();
309
310        assert_eq!(lhs, rhs_mapped);
311        assert_eq!(lhs_mapped, rhs);
312    }
313
314    proptest! {
315        #![proptest_config(ProptestConfig {
316            // cases: 1 << 17,
317            max_shrink_time: 0,
318            max_shrink_iters: 16384,
319            ..ProptestConfig::default()
320        })]
321
322        #[test]
323        fn reference(r in kleene::re(
324            8,
325            64,
326            8,
327            0..16,
328            crate::prop::symbol(),
329        )) {
330            let nfa = r.compile();
331            let (dfa, _) = nfa.compile_moore();
332            // let mut t = FlushOnDrop::new();
333
334            run::<reference::EGraph<_, _>, _, _, _>(&dfa, reference::EGraph::default());
335        }
336
337        #[test]
338        fn congr(r in kleene::re(
339            8,
340            64,
341            8,
342            0..16,
343            crate::prop::symbol(),
344        )) {
345            let nfa = r.compile();
346            let (dfa, _) = nfa.compile_moore();
347            // let mut t = FlushOnDrop::new();
348
349            let lhs = run::<congr::EGraph<_, _>, _, _, _>(
350                &dfa,
351                congr::EGraph::default(),
352            );
353            let rhs = run_ref(&dfa);
354            assert_equiv(lhs, rhs);
355        }
356
357        #[test]
358        fn fast(
359            r in kleene::re(
360                8,
361                64,
362                8,
363                0..16,
364                crate::prop::symbol(),
365            ),
366            seed in any::<u64>(),
367        ) {
368            let nfa = r.compile();
369            let (dfa, _) = nfa.compile_moore();
370            // let mut t = FlushOnDrop::new();
371
372            let lhs = run::<fast::EGraph<_, _, _>, _, _, _>(
373                &dfa,
374                fast::EGraph::with_hasher(FixedState::with_seed(seed)),
375            );
376            let rhs = run_ref(&dfa);
377            assert_equiv(lhs, rhs);
378        }
379    }
380}