Skip to main content

mid_tools/egraph/
mod.rs

1use hashbrown::{HashMap, HashSet};
2pub use node::*;
3pub use trace::EGraphTrace;
4
5use crate::{
6    dot,
7    union_find::{ClassId, NoNode, Unioned},
8};
9
10pub mod congr;
11pub mod fast;
12mod node;
13pub mod reference;
14pub mod trace;
15
16// TODO: a lot of this module could be cleaned up if they introduced a solution
17//       for better derive bounds
18
19pub mod prelude {
20    pub use super::{EGraphCore, EGraphRead, EGraphUpgrade, EGraphUpgradeTrace, EGraphWrite};
21}
22
23pub trait EGraphCore {
24    type FuncSymbol;
25    type Class;
26
27    fn add(
28        &mut self,
29        node: ENode<Self::FuncSymbol, Self::Class>,
30    ) -> Result<ClassId<Self::Class>, NoNode>;
31}
32
33impl<T: ?Sized + EGraphCore> EGraphCore for &mut T {
34    type Class = T::Class;
35    type FuncSymbol = T::FuncSymbol;
36
37    fn add(
38        &mut self,
39        node: ENode<Self::FuncSymbol, Self::Class>,
40    ) -> Result<ClassId<Self::Class>, NoNode> {
41        T::add(self, node)
42    }
43}
44
45pub type ClassNodes<'a, G, S = hashbrown::DefaultHashBuilder> = HashMap<
46    ClassId<<G as EGraphCore>::Class>,
47    HashSet<&'a ENode<<G as EGraphCore>::FuncSymbol, <G as EGraphCore>::Class>, S>,
48    S,
49>;
50
51pub trait EGraphRead: EGraphCore {
52    type Hasher;
53
54    fn find(&self, class: ClassId<Self::Class>) -> Result<ClassId<Self::Class>, NoNode>;
55
56    /// Returns true if the node was modified
57    fn canonicalize(&self, node: &mut ENode<Self::FuncSymbol, Self::Class>)
58        -> Result<bool, NoNode>;
59
60    fn is_canonical(&self, node: &ENode<Self::FuncSymbol, Self::Class>) -> Result<bool, NoNode>;
61
62    fn class_nodes(&self) -> ClassNodes<'_, Self, Self::Hasher>;
63
64    fn dot<M: trace::dot::Formatter<Self::FuncSymbol>>(&self, f: M) -> dot::Graph<'static>;
65}
66
67pub trait EGraphWrite: EGraphCore {
68    fn merge(
69        &mut self,
70        a: ClassId<Self::Class>,
71        b: ClassId<Self::Class>,
72    ) -> Result<Unioned<Self::Class>, NoNode>;
73}
74
75pub trait EGraphWriteTrace: EGraphCore {
76    fn merge_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
77        &mut self,
78        a: ClassId<Self::Class>,
79        b: ClassId<Self::Class>,
80        t: &mut T,
81    ) -> Result<Unioned<Self::Class>, NoNode>;
82}
83
84impl<T: EGraphWrite> EGraphWrite for &mut T {
85    fn merge(
86        &mut self,
87        a: ClassId<Self::Class>,
88        b: ClassId<Self::Class>,
89    ) -> Result<Unioned<Self::Class>, NoNode> {
90        T::merge(self, a, b)
91    }
92}
93
94impl<G: EGraphWriteTrace> EGraphWriteTrace for &mut G {
95    fn merge_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
96        &mut self,
97        a: ClassId<Self::Class>,
98        b: ClassId<Self::Class>,
99        t: &mut T,
100    ) -> Result<Unioned<Self::Class>, NoNode> {
101        G::merge_trace(self, a, b, t)
102    }
103}
104
105pub trait EGraphUpgradeTrace: EGraphRead {
106    type WriteRef<'a, T: EGraphTrace<Self::FuncSymbol, Self::Class>>: EGraphWrite<
107        FuncSymbol = Self::FuncSymbol,
108        Class = Self::Class,
109    >
110    where Self: 'a;
111
112    fn write_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
113        &mut self,
114        tracer: T,
115    ) -> Self::WriteRef<'_, T>;
116}
117
118pub trait EGraphUpgrade: EGraphUpgradeTrace {
119    #[inline]
120    fn write(&mut self) -> Self::WriteRef<'_, ()> { self.write_trace(()) }
121}
122
123impl<G: EGraphUpgradeTrace> EGraphUpgrade for G {}
124
125#[derive(Debug)]
126pub struct SimpleWriteRef<'a, G, T>(&'a mut G, T);
127
128impl<G: EGraphRead + EGraphWriteTrace> EGraphUpgradeTrace for G {
129    type WriteRef<'a, T: EGraphTrace<Self::FuncSymbol, Self::Class>>
130        = SimpleWriteRef<'a, G, T>
131    where Self: 'a;
132
133    #[inline]
134    fn write_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
135        &mut self,
136        tracer: T,
137    ) -> Self::WriteRef<'_, T> {
138        SimpleWriteRef(self, tracer)
139    }
140}
141
142impl<G: EGraphCore, T> EGraphCore for SimpleWriteRef<'_, G, T> {
143    type Class = G::Class;
144    type FuncSymbol = G::FuncSymbol;
145
146    #[inline]
147    fn add(
148        &mut self,
149        node: ENode<Self::FuncSymbol, Self::Class>,
150    ) -> Result<ClassId<Self::Class>, NoNode> {
151        self.0.add(node)
152    }
153}
154
155impl<G: EGraphWriteTrace, T: EGraphTrace<G::FuncSymbol, G::Class>> EGraphWrite
156    for SimpleWriteRef<'_, G, T>
157{
158    #[inline]
159    fn merge(
160        &mut self,
161        a: ClassId<Self::Class>,
162        b: ClassId<Self::Class>,
163    ) -> Result<Unioned<Self::Class>, NoNode> {
164        self.0.merge_trace(a, b, &mut self.1)
165    }
166}
167
168pub mod test_tools {
169    use std::{collections::BTreeMap, fmt};
170
171    use hashbrown::HashMap;
172
173    use super::ENode;
174    use crate::{bijection::Bijection, union_find::ClassId};
175
176    #[derive(Debug)]
177    pub struct EGraphParts<F, C> {
178        pub uf: crate::union_find::UnionFind<C>,
179        pub node_classes: HashMap<ENode<F, C>, ClassId<C>>,
180    }
181
182    pub fn assert_equiv<
183        F: fmt::Debug + Ord,
184        C,
185        A: Into<EGraphParts<F, C>>,
186        B: Into<EGraphParts<F, C>>,
187    >(
188        a: A,
189        b: B,
190    ) -> Bijection<ClassId<C>, ClassId<C>> {
191        let EGraphParts {
192            uf: a_uf,
193            node_classes: a_node_classes,
194        } = a.into();
195        let EGraphParts {
196            uf: b_uf,
197            node_classes: b_node_classes,
198        } = b.into();
199
200        let mut mapping = Bijection::new();
201
202        assert_eq!(a_uf.len(), b_uf.len());
203        for (a, b) in a_uf.classes().zip(b_uf.classes()) {
204            mapping
205                .insert(a_uf.find(a).unwrap(), b_uf.find(b).unwrap())
206                .unwrap();
207        }
208
209        let a_node_classes_mapped: BTreeMap<_, _> = a_node_classes
210            .iter()
211            .map(|(n, c)| {
212                let mut n = n.clone();
213                n.map_args(|c| *mapping.image(&c).unwrap());
214                (n, *mapping.image(c).unwrap())
215            })
216            .collect();
217
218        let b_node_classes_mapped: BTreeMap<_, _> = b_node_classes
219            .iter()
220            .map(|(n, c)| {
221                let mut n = n.clone();
222                n.map_args(|c| *mapping.preimage(&c).unwrap());
223                (n, *mapping.preimage(c).unwrap())
224            })
225            .collect();
226
227        assert_eq!(
228            a_node_classes.into_iter().collect::<BTreeMap<_, _>>(),
229            b_node_classes_mapped
230        );
231        assert_eq!(
232            a_node_classes_mapped,
233            b_node_classes.into_iter().collect::<BTreeMap<_, _>>()
234        );
235
236        mapping
237    }
238}
239
240#[cfg(test)]
241mod test {
242    use std::collections::BTreeMap;
243
244    use foldhash::fast::FixedState;
245    use prop::sample::SizeRange;
246    use proptest::prelude::*;
247
248    use super::{prelude::*, test_tools::assert_equiv};
249
250    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
251    struct Symbol(char);
252    #[derive(Debug, Clone)]
253    struct Tree(Symbol, Vec<Tree>);
254
255    #[derive(Debug)]
256    struct Expr;
257
258    impl Tree {
259        fn fold_impl<T>(self, f: &mut impl FnMut(Symbol, Vec<T>) -> T) -> T {
260            let Self(sym, children) = self;
261            let children = children.into_iter().map(|c| c.fold_impl(f)).collect();
262            f(sym, children)
263        }
264
265        #[inline]
266        fn fold<T>(self, mut f: impl FnMut(Symbol, Vec<T>) -> T) -> T { self.fold_impl(&mut f) }
267
268        fn count(&self) -> usize {
269            self.1
270                .iter()
271                .map(Tree::count)
272                .reduce(|l, r| l.checked_add(r).unwrap())
273                .unwrap_or(0)
274                .checked_add(1)
275                .unwrap()
276        }
277    }
278
279    type Node = super::ENode<Symbol, Expr>;
280    type SlowGraph = super::reference::EGraph<Symbol, Expr>;
281    type CongrGraph = super::congr::EGraph<Symbol, Expr>;
282    type FastGraph<S> = super::fast::EGraph<Symbol, Expr, S>;
283
284    type Parts = super::test_tools::EGraphParts<Symbol, Expr>;
285
286    // TODO: track that only merged and originally-equivalent nodes are still equivalent
287    // fn assert_merges<G: EGraphRead>(
288    //     merges: &[(usize, usize)],
289    //     class: impl Fn(usize) -> ClassId<G::Class>,
290    // ) {
291    // }
292
293    // TODO: test adding after merging
294    fn run_reference(tree: &Tree, merges: &Vec<(usize, usize)>) {
295        let mut graph = SlowGraph::new();
296        let mut classes = BTreeMap::new();
297        let mut class_list = vec![];
298
299        let root = tree.clone().fold(|sym, args| {
300            let node = Node::new(sym.into(), args.into());
301            let class = graph.add(node.clone()).unwrap();
302
303            class_list.push(class);
304
305            assert_eq!(*classes.entry(node).or_insert(class), class);
306
307            class
308        });
309
310        graph.find(root).unwrap();
311
312        for &(a, b) in merges {
313            let a = class_list[a];
314            let b = class_list[b];
315            graph.write().merge(a, b).unwrap();
316        }
317    }
318
319    // TODO: test adding after merging
320    fn run<
321        A: Default + Clone + EGraphUpgrade<FuncSymbol = Symbol, Class = Expr> + Into<Parts>,
322        B: Clone + EGraphUpgrade<FuncSymbol = Symbol, Class = Expr> + Into<Parts>,
323    >(
324        mut b: B,
325        tree: &Tree,
326        merges: &Vec<(usize, usize)>,
327        stepwise: bool,
328    ) {
329        let mut a = A::default();
330        let mut classes = BTreeMap::new();
331        let mut class_list = vec![];
332
333        let root = tree.clone().fold(|sym, args| {
334            let node = Node::new(sym.into(), args.into());
335
336            let class = a.add(node.clone()).unwrap();
337            assert_eq!(b.add(node.clone()).unwrap(), class);
338
339            class_list.push(class);
340
341            assert_eq!(*classes.entry(node).or_insert(class), class);
342
343            class
344        });
345
346        // Sanity assertion that the root ended up in the graphs
347        a.find(root).unwrap();
348        b.find(root).unwrap();
349
350        if stepwise {
351            for &(l, r) in merges {
352                let l = class_list[l];
353                let r = class_list[r];
354                a.write().merge(l, r).unwrap();
355                b.write().merge(l, r).unwrap();
356
357                assert_equiv(a.clone(), b.clone());
358            }
359        } else {
360            {
361                let mut a = a.write();
362                let mut b = b.write();
363
364                for &(l, r) in merges {
365                    let l = class_list[l];
366                    let r = class_list[r];
367                    a.merge(l, r).unwrap();
368                    b.merge(l, r).unwrap();
369                }
370            }
371
372            assert_equiv(a, b);
373        }
374    }
375
376    fn nodes_and_merges(
377        symbol: impl Strategy<Value = char> + Clone + 'static,
378        depth: u32,
379        tree_size: u32,
380        branch_size: u32,
381        merge_size: impl Into<SizeRange>,
382    ) -> impl Strategy<Value = (Tree, Vec<(usize, usize)>)> {
383        let sym = symbol.prop_map(Symbol);
384        let merge_size = merge_size.into();
385
386        sym.clone()
387            .prop_map(|s| Tree(s, vec![]))
388            .prop_recursive(depth, tree_size, branch_size, move |t| {
389                (
390                    sym.clone(),
391                    prop::collection::vec(t, 0..=(branch_size.try_into().unwrap())),
392                )
393                    .prop_map(|(s, c)| Tree(s, c))
394            })
395            .prop_flat_map(move |t| {
396                let id = 0..t.count();
397                prop::collection::vec((id.clone(), id), merge_size.clone())
398                    .prop_map(move |m| (t.clone(), m))
399            })
400    }
401
402    proptest! {
403        #![proptest_config(ProptestConfig {
404            // cases: 1 << 17,
405            max_shrink_time: 0,
406            max_shrink_iters: 16384,
407            // max_shrink_iters: 1 << 18,
408            ..ProptestConfig::default()
409        })]
410
411        #[test]
412        fn reference(
413            (nodes, merges) in nodes_and_merges(
414                crate::prop::symbol(),
415                32,
416                512,
417                6,
418                1..=128,
419            ),
420        ) {
421            run_reference(&nodes, &merges);
422        }
423
424        #[test]
425        fn batched(
426            (nodes, merges) in nodes_and_merges(
427                crate::prop::symbol(),
428                32,
429                512,
430                6,
431                1..=128,
432            ),
433            seed in any::<u64>(),
434        ) {
435            run::<SlowGraph, FastGraph<_>>(
436                FastGraph::with_hasher(FixedState::with_seed(seed)),
437                &nodes,
438                &merges,
439                false,
440            );
441        }
442
443        #[test]
444        fn stepwise(
445            (nodes, merges) in nodes_and_merges(
446                crate::prop::symbol(),
447                32,
448                512,
449                6,
450                1..=128,
451            ),
452            seed in any::<u64>(),
453        ) {
454            run::<SlowGraph, FastGraph<_>>(
455                FastGraph::with_hasher(FixedState::with_seed(seed)),
456                &nodes,
457                &merges,
458                true,
459            );
460        }
461
462        #[test]
463        fn congr(
464            (nodes, merges) in nodes_and_merges(
465                crate::prop::symbol(),
466                32,
467                512,
468                6,
469                1..=128,
470            ),
471        ) {
472            run::<SlowGraph, CongrGraph>(CongrGraph::default(), &nodes, &merges, true);
473        }
474    }
475}