Skip to main content

mid_tools/egraph/
fast.rs

1use std::{
2    fmt,
3    hash::{BuildHasher, Hash},
4    mem,
5};
6
7use hashbrown::{HashMap, HashSet};
8
9use super::{
10    prelude::*,
11    test_tools::EGraphParts,
12    trace::{self, SnapshotEGraph, SnapshotEquivClass},
13    ClassNodes, EGraphTrace, ENode,
14};
15use crate::{
16    dot,
17    union_find::{ClassId, NoNode, UnionFind, Unioned},
18};
19
20struct EClassData<F, C, S> {
21    parents: HashMap<ClassId<ENode<F, C>>, ClassId<C>, S>,
22}
23
24impl<F: fmt::Debug, C, S> fmt::Debug for EClassData<F, C, S> {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        let Self { parents } = self;
27        f.debug_struct("EClassData")
28            .field("parents", parents)
29            .finish()
30    }
31}
32
33impl<F, C, S: Clone> Clone for EClassData<F, C, S> {
34    fn clone(&self) -> Self {
35        Self {
36            parents: self.parents.clone(),
37        }
38    }
39}
40
41impl<F, C, S> EClassData<F, C, S> {
42    #[inline]
43    fn new(h: S) -> Self {
44        Self {
45            parents: HashMap::with_hasher(h),
46        }
47    }
48}
49
50struct NodeData<F, C> {
51    node: ENode<F, C>,
52    class: ClassId<C>,
53}
54
55impl<F: fmt::Debug, C> fmt::Debug for NodeData<F, C> {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        let Self { node, class } = self;
58        f.debug_struct("NodeData")
59            .field("node", node)
60            .field("class", class)
61            .finish()
62    }
63}
64
65impl<F, C> Clone for NodeData<F, C> {
66    fn clone(&self) -> Self {
67        Self {
68            node: self.node.clone(),
69            class: self.class,
70        }
71    }
72}
73
74impl<F, C> NodeData<F, C> {
75    #[inline]
76    fn new(node: ENode<F, C>, class: ClassId<C>) -> Self { Self { node, class } }
77}
78
79pub struct EGraph<F, C, S = hashbrown::DefaultHashBuilder> {
80    eq_uf: UnionFind<C>,
81    congr_uf: UnionFind<ENode<F, C>>,
82    class_data: HashMap<ClassId<C>, EClassData<F, C, S>, S>,
83    node_data: HashMap<ClassId<ENode<F, C>>, NodeData<F, C>, S>,
84    node_congr_classes: HashMap<ENode<F, C>, ClassId<ENode<F, C>>, S>,
85    poison: bool,
86}
87
88impl<F: fmt::Debug, C, S> fmt::Debug for EGraph<F, C, S> {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        let Self {
91            eq_uf,
92            congr_uf,
93            class_data,
94            node_data,
95            node_congr_classes,
96            poison,
97        } = self;
98        f.debug_struct("EGraph")
99            .field("eq_uf", eq_uf)
100            .field("congr_uf", congr_uf)
101            .field("class_data", class_data)
102            .field("node_data", node_data)
103            .field("node_congr_classes", node_congr_classes)
104            .field("poison", poison)
105            .finish()
106    }
107}
108
109impl<F, C, S: Clone> Clone for EGraph<F, C, S> {
110    fn clone(&self) -> Self {
111        Self {
112            eq_uf: self.eq_uf.clone(),
113            congr_uf: self.congr_uf.clone(),
114            class_data: self.class_data.clone(),
115            node_data: self.node_data.clone(),
116            node_congr_classes: self.node_congr_classes.clone(),
117            poison: self.poison,
118        }
119    }
120}
121
122impl<F, C> EGraph<F, C> {
123    #[inline]
124    #[must_use]
125    pub fn new() -> Self { Self::with_hasher(hashbrown::DefaultHashBuilder::default()) }
126}
127
128impl<F, C> Default for EGraph<F, C> {
129    #[inline]
130    fn default() -> Self { Self::new() }
131}
132
133impl<F, C, S: Clone> EGraph<F, C, S> {
134    #[must_use]
135    pub fn with_hasher(h: S) -> Self {
136        Self {
137            eq_uf: UnionFind::new(),
138            congr_uf: UnionFind::new(),
139            class_data: HashMap::with_hasher(h.clone()),
140            node_data: HashMap::with_hasher(h.clone()),
141            node_congr_classes: HashMap::with_hasher(h),
142            poison: false,
143        }
144    }
145
146    #[inline]
147    fn new_hasher(&self) -> S { self.node_congr_classes.hasher().clone() }
148}
149
150impl<F, C, S> EGraph<F, C, S> {
151    #[inline]
152    fn poison_check(&self) {
153        assert!(!self.poison, "e-graph was poisoned!");
154    }
155}
156
157impl<F: Eq + Hash, C, S: BuildHasher> From<EGraph<F, C, S>> for EGraphParts<F, C> {
158    fn from(eg: EGraph<F, C, S>) -> Self {
159        eg.poison_check();
160
161        let EGraph {
162            eq_uf,
163            congr_uf: _,
164            class_data: _,
165            mut node_data,
166            node_congr_classes,
167            poison: _,
168        } = eg;
169
170        assert_eq!(node_congr_classes.len(), node_data.len());
171
172        let node_classes = node_congr_classes
173            .into_iter()
174            .map(|(k, v)| (k, eq_uf.find(node_data.remove(&v).unwrap().class).unwrap()))
175            .collect();
176
177        EGraphParts {
178            uf: eq_uf,
179            node_classes,
180        }
181    }
182}
183
184impl<F: Eq + Hash, C, S: Clone + BuildHasher> EGraphCore for EGraph<F, C, S> {
185    type Class = C;
186    type FuncSymbol = F;
187
188    fn add(&mut self, mut node: ENode<F, C>) -> Result<ClassId<C>, NoNode> {
189        node.canonicalize_classes(&self.eq_uf)?;
190
191        if let Some(c) = self.node_congr_classes.get(&node) {
192            return Ok(self.node_data.get(c).unwrap().class);
193        }
194
195        let eq_class = self.eq_uf.add();
196        let congr_class = self.congr_uf.add();
197
198        assert!(self
199            .node_data
200            .insert(congr_class, NodeData::new(node.clone(), eq_class))
201            .is_none());
202        assert!(self
203            .class_data
204            .insert(eq_class, EClassData::new(self.new_hasher()))
205            .is_none());
206
207        for &arg in node.args() {
208            assert!(self
209                .class_data
210                .get_mut(&arg)
211                .unwrap()
212                .parents
213                .insert(congr_class, eq_class)
214                .is_none_or(|c| eq_class == c));
215        }
216
217        assert!(self.node_congr_classes.insert(node, congr_class).is_none());
218
219        Ok(eq_class)
220    }
221}
222
223impl<F: Eq + Hash, C, S: Clone + BuildHasher> EGraphRead for EGraph<F, C, S> {
224    type Hasher = S;
225
226    #[inline]
227    fn find(&self, class: ClassId<C>) -> Result<ClassId<C>, NoNode> {
228        self.poison_check();
229        self.eq_uf.find(class)
230    }
231
232    #[inline]
233    fn canonicalize(&self, node: &mut ENode<F, C>) -> Result<bool, NoNode> {
234        self.poison_check();
235        node.canonicalize_classes(&self.eq_uf)
236    }
237
238    #[inline]
239    fn is_canonical(&self, node: &ENode<F, C>) -> Result<bool, NoNode> {
240        self.poison_check();
241        node.classes_canonical(&self.eq_uf)
242    }
243
244    fn class_nodes(&self) -> ClassNodes<'_, Self, S> {
245        self.poison_check();
246
247        self.node_data.values().fold(
248            HashMap::with_capacity_and_hasher(self.node_data.len(), self.new_hasher()),
249            |mut m, d| {
250                assert!(m
251                    .entry(self.eq_uf.find(d.class).unwrap())
252                    .or_insert_with(|| HashSet::with_hasher(self.new_hasher()))
253                    .insert(&d.node));
254                m
255            },
256        )
257    }
258
259    #[inline]
260    fn dot<M: trace::dot::Formatter<F>>(&self, f: M) -> dot::Graph<'static> {
261        self.poison_check();
262        trace::dot_graph(f, self.class_nodes())
263    }
264}
265
266impl<F: Eq + Hash, C, S: Clone + BuildHasher> EGraphUpgradeTrace for EGraph<F, C, S> {
267    type WriteRef<'a, T: EGraphTrace<F, C>>
268        = EGraphMut<'a, F, C, T, S>
269    where Self: 'a;
270
271    fn write_trace<T: EGraphTrace<F, C>>(&mut self, tracer: T) -> Self::WriteRef<'_, T> {
272        self.poison_check();
273        self.poison = true;
274
275        let h = self.new_hasher();
276        EGraphMut {
277            eg: self,
278            dirty: HashMap::with_hasher(h),
279            tracer,
280        }
281    }
282}
283
284type DirtySet<C, S> = HashMap<ClassId<C>, HashSet<ClassId<C>, S>, S>;
285
286pub struct EGraphMut<'a, F: Eq + Hash, C, T: EGraphTrace<F, C>, S: Clone + BuildHasher> {
287    eg: &'a mut EGraph<F, C, S>,
288    dirty: DirtySet<C, S>,
289    tracer: T,
290}
291
292impl<F: fmt::Debug + Eq + Hash, C, T: fmt::Debug + EGraphTrace<F, C>, S: Clone + BuildHasher>
293    fmt::Debug for EGraphMut<'_, F, C, T, S>
294{
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        let Self { eg, dirty, tracer } = self;
297        f.debug_struct("EGraphMut")
298            .field("eg", eg)
299            .field("dirty", dirty)
300            .field("tracer", tracer)
301            .finish()
302    }
303}
304
305impl<F: Eq + Hash, C, T: EGraphTrace<F, C>, S: Clone + BuildHasher> Drop
306    for EGraphMut<'_, F, C, T, S>
307{
308    fn drop(&mut self) {
309        self.rebuild();
310        self.eg.poison = false;
311    }
312}
313
314trait ExpectInvariant<T> {
315    fn expect_invariant(self, msg: &str) -> T;
316
317    fn expect_none_invariant(self, msg: &str);
318}
319
320#[cfg(any(test, feature = "test"))]
321impl<T> ExpectInvariant<T> for Option<T> {
322    #[inline]
323    fn expect_invariant(self, msg: &str) -> T { self.expect(msg) }
324
325    #[inline]
326    fn expect_none_invariant(self, msg: &str) {
327        assert!(self.is_none(), "{msg}");
328    }
329}
330
331#[cfg(any(test, feature = "test"))]
332impl<T, E> ExpectInvariant<T> for Result<T, E> {
333    #[inline]
334    fn expect_invariant(self, msg: &str) -> T { self.unwrap_or_else(|_| panic!("{msg}")) }
335
336    #[inline]
337    fn expect_none_invariant(self, msg: &str) {
338        assert!(self.is_err(), "{msg}");
339    }
340}
341
342#[cfg(not(any(test, feature = "test")))]
343impl<T> ExpectInvariant<T> for Option<T> {
344    #[inline]
345    fn expect_invariant(self, _: &str) -> T { self.unwrap_or_else(|| unreachable!()) }
346
347    #[inline]
348    fn expect_none_invariant(self, _: &str) {
349        if self.is_some() {
350            unreachable!();
351        }
352    }
353}
354
355#[cfg(not(any(test, feature = "test")))]
356impl<T, E> ExpectInvariant<T> for Result<T, E> {
357    #[inline]
358    fn expect_invariant(self, _: &str) -> T { self.unwrap_or_else(|_| unreachable!()) }
359
360    #[inline]
361    fn expect_none_invariant(self, _: &str) {
362        if self.is_ok() {
363            unreachable!();
364        }
365    }
366}
367
368macro_rules! invariant {
369    ($($tt:tt)*) => {
370        #[cfg(any(test, feature = "test"))]
371        { panic!($($tt)*) }
372
373        #[cfg(not(any(test, feature = "test")))]
374        { unreachable!() }
375    };
376}
377
378impl<F: Eq + Hash, C, T: EGraphTrace<F, C>, S: Clone + BuildHasher> EGraphCore
379    for EGraphMut<'_, F, C, T, S>
380{
381    type Class = C;
382    type FuncSymbol = F;
383
384    fn add(&mut self, node: ENode<F, C>) -> Result<ClassId<C>, NoNode> { self.eg.add(node) }
385}
386
387impl<F: Eq + Hash, C, T: EGraphTrace<F, C>, S: Clone + BuildHasher> EGraphWrite
388    for EGraphMut<'_, F, C, T, S>
389{
390    fn merge(&mut self, a: ClassId<C>, b: ClassId<C>) -> Result<Unioned<C>, NoNode> {
391        let union = self.eg.eq_uf.union(a, b)?;
392
393        if let Some(other) = union.unioned {
394            self.dirty
395                .entry(union.root)
396                .or_insert_with(|| HashSet::with_hasher(self.eg.new_hasher()))
397                .insert(other);
398        }
399
400        Ok(union)
401    }
402}
403
404impl<F: Eq + Hash, C, T: EGraphTrace<F, C>, S: Clone + BuildHasher> EGraphMut<'_, F, C, T, S> {
405    fn trace<G: FnOnce() -> I, I: IntoIterator<Item = ClassId<C>>>(&mut self, current: G) {
406        self.tracer.graph(|g| {
407            let mut nodes = trace::snapshot_graph(
408                g,
409                self.eg.node_data.values().fold(
410                    HashMap::with_hasher(self.eg.new_hasher()),
411                    |mut m: HashMap<_, HashSet<_, _>, _>, d| {
412                        assert!(m
413                            .entry(self.eg.eq_uf.find(d.class).unwrap())
414                            .or_insert_with(|| HashSet::with_hasher(self.eg.new_hasher()))
415                            .insert(&d.node));
416                        m
417                    },
418                ),
419            );
420
421            let mut seen = HashSet::with_hasher(self.eg.new_hasher());
422            for class in current() {
423                let data = self.eg.class_data.get(&class).unwrap();
424                for (&parent, &par_id) in &data.parents {
425                    let parent = self.eg.congr_uf.find(parent).unwrap();
426                    let par_id = self.eg.eq_uf.find(par_id).unwrap();
427
428                    if !seen.insert((class, parent, par_id)) {
429                        continue;
430                    }
431
432                    for class in [class, par_id] {
433                        nodes
434                            .class_reps
435                            .entry(class)
436                            .or_insert_with(|| g.equiv_class(class).id().clone());
437                    }
438
439                    g.parent_edge(
440                        nodes.class_reps.get(&class).unwrap(),
441                        nodes
442                            .node_ids
443                            .get(&self.eg.node_data.get(&parent).unwrap().node)
444                            .unwrap(),
445                        Some(nodes.class_reps.get(&par_id).unwrap()),
446                        Some(&format!("{}-{}", class.id(), parent.id())),
447                    );
448                }
449            }
450
451            // let mut uf = g.union_find("congruence");
452            // let mut congr_ids = BTreeMap::new();
453
454            // for id in self.congr_uf.classes() {
455            //     let class = uf.class(format_args!("{}", id.id()));
456            //     congr_ids.insert(id, class.id().clone());
457            // }
458
459            // for class in self.congr_uf.classes() {
460            //     uf.parent(
461            //         congr_ids.get(&class).unwrap(),
462            //         congr_ids
463            //             .get(&self.congr_uf.parent(class).unwrap())
464            //             .unwrap(),
465            //     );
466            // }
467
468            // for (node, class) in &self.node_congr_classes {
469            //     uf.link_to_node(
470            //         congr_ids.get(class).unwrap(),
471            //         nodes.node_ids.get(&node).unwrap(),
472            //     );
473            // }
474
475            // for class in current() {
476            //     let data = self.class_data.get(&class).unwrap();
477            //     for (parent, par_id) in &data.parents {
478            //         uf.link_from_graph_class(
479            //             nodes.class_reps.get(&class).unwrap(),
480            //             congr_ids.get(parent).unwrap(),
481            //         );
482            //     }
483            // }
484        });
485    }
486
487    fn rebuild(&mut self) {
488        let mut q = DirtySet::with_capacity_and_hasher(self.dirty.len(), self.eg.new_hasher());
489        while !self.dirty.is_empty() {
490            #[cfg(any(test, feature = "test"))]
491            {
492                assert!(q.is_empty());
493            }
494
495            for (root, unioned) in self.dirty.drain() {
496                let root = self
497                    .eg
498                    .eq_uf
499                    .find(root)
500                    .expect_invariant("Invalid root repair class");
501
502                q.entry(root)
503                    .or_insert_with(|| {
504                        HashSet::with_capacity_and_hasher(unioned.len(), self.eg.new_hasher())
505                    })
506                    .extend(unioned);
507            }
508
509            for (c, o) in q.drain() {
510                self.repair(c, o);
511                // TODO: print remaining values in q?
512                self.tracer.hl_merges(
513                    self.dirty
514                        .iter()
515                        .flat_map(|(&l, r)| r.iter().map(move |&r| (l, r))),
516                );
517            }
518        }
519
520        self.assert_invariants();
521    }
522
523    #[allow(clippy::too_many_lines, reason = "its just that complicated")]
524    fn repair(&mut self, root: ClassId<C>, unioned: HashSet<ClassId<C>, S>) {
525        use hashbrown::hash_map::Entry;
526
527        self.trace(|| [root].into_iter().chain(unioned.iter().copied()));
528        self.tracer.hl_class(root);
529        self.tracer.hl_classes(unioned.iter().copied());
530
531        let merged_data: Vec<_> = unioned
532            .into_iter()
533            .map(|c| {
534                self.eg
535                    .class_data
536                    .remove(&c)
537                    .expect_invariant("Missing data for merged repair class")
538            })
539            .collect();
540
541        let h = self.eg.new_hasher();
542        let root_data = self
543            .eg
544            .class_data
545            .get_mut(&root)
546            .expect_invariant("Missing data for root repair class");
547
548        let mut new_parents = HashMap::with_capacity_and_hasher(root_data.parents.len(), h);
549        let mut to_merge = vec![];
550        for (old_congr_class, old_eq_class) in merged_data
551            .into_iter()
552            .flat_map(|EClassData { parents }| parents)
553            .chain(root_data.parents.drain())
554        {
555            let old_congr_class = self
556                .eg
557                .congr_uf
558                .find(old_congr_class)
559                .expect_invariant("Invalid parent ID in repair class");
560
561            let Entry::Occupied(mut old_par) = self.eg.node_data.entry(old_congr_class) else {
562                invariant!("Missing node data for repair class parent");
563            };
564
565            let mut new_par = old_par.get().node.clone();
566            let was_not_canon = new_par
567                .canonicalize_classes(&self.eg.eq_uf)
568                .expect_invariant("Invalid resolved parent in repair class");
569
570            let new_congr_class;
571            let new_par_data;
572            if was_not_canon {
573                let old_par = old_par.remove();
574
575                new_congr_class =
576                    if let Some(other_congr_class) = self.eg.node_congr_classes.remove(&new_par) {
577                        self.eg
578                            .node_data
579                            .remove(
580                                &self
581                                    .eg
582                                    .congr_uf
583                                    .find(other_congr_class)
584                                    .expect_invariant("Invalid existing ID for updated parent"),
585                            )
586                            .expect_invariant("Missing data for updated parent");
587
588                        let Unioned { root, unioned } = self
589                            .eg
590                            .congr_uf
591                            .union(other_congr_class, old_congr_class)
592                            .expect_invariant("Unable to union updated parent IDs");
593
594                        if let Some(unioned) = unioned
595                            && let Some(class) = new_parents.remove(&unioned)
596                        {
597                            new_parents.insert(root, class);
598                        }
599
600                        root
601                    } else {
602                        old_congr_class
603                    };
604
605                self.eg
606                    .node_congr_classes
607                    .remove(&old_par.node)
608                    .expect_invariant("Invalid previous parent for update");
609                self.eg
610                    .node_congr_classes
611                    .insert(new_par.clone(), new_congr_class)
612                    .expect_none_invariant("Updated parent collided when storing ID");
613
614                let Entry::Vacant(v) = self.eg.node_data.entry(new_congr_class) else {
615                    invariant!("Missing node data for updated parent");
616                };
617
618                new_par_data = v.insert(NodeData::new(new_par.clone(), old_eq_class));
619            } else {
620                new_congr_class = old_congr_class;
621                new_par_data = old_par.get_mut();
622            }
623
624            let new_eq_class = self
625                .eg
626                .eq_uf
627                .find(old_eq_class)
628                .expect_invariant("Invalid equivalence class for repair");
629
630            match new_parents.entry(new_congr_class) {
631                Entry::Vacant(v) => {
632                    v.insert(new_eq_class);
633                    new_par_data.class = new_eq_class;
634                },
635                Entry::Occupied(mut o) => {
636                    to_merge.push((o.insert(new_eq_class), new_eq_class));
637                },
638            }
639        }
640
641        if !mem::replace(&mut root_data.parents, new_parents).is_empty() {
642            invariant!("Root parent list was not fully drained");
643        }
644
645        self.trace(|| [root]);
646        self.tracer.hl_class(root);
647
648        for (a, b) in to_merge {
649            self.merge(a, b)
650                .expect_invariant("Unable to perform upward merge");
651        }
652    }
653
654    #[cfg(not(any(test, feature = "test")))]
655    #[inline]
656    fn assert_invariants(&self) { let _ = self; }
657
658    #[cfg(any(test, feature = "test"))]
659    fn assert_invariants(&self) {
660        assert_eq!(
661            self.eg.node_data.len(),
662            self.eg.node_congr_classes.len(),
663            "Length mismatch between node_data vs. node_congr_classes"
664        );
665
666        for (node, &congr_class) in &self.eg.node_congr_classes {
667            assert!(*node == self.eg.node_data.get(&congr_class).unwrap().node);
668            assert!(node.classes_canonical(&self.eg.eq_uf).unwrap());
669
670            let root = self.eg.congr_uf.find(congr_class).unwrap();
671            for arg in node.args() {
672                assert!(self
673                    .eg
674                    .class_data
675                    .get(arg)
676                    .unwrap()
677                    .parents
678                    .keys()
679                    .any(|&c| self.eg.congr_uf.find(c).unwrap() == root));
680            }
681        }
682
683        for &congr_class in self.eg.node_data.keys() {
684            assert_eq!(
685                congr_class,
686                self.eg.congr_uf.find(congr_class).unwrap(),
687                "Congruence class was not canonical"
688            );
689        }
690
691        for congr_root in self.eg.congr_uf.roots() {
692            assert!(self.eg.node_data.contains_key(&congr_root));
693        }
694
695        for eq_root in self.eg.eq_uf.roots() {
696            assert!(self.eg.class_data.contains_key(&eq_root));
697        }
698
699        for (&eq_class, EClassData { parents }) in &self.eg.class_data {
700            assert_eq!(
701                eq_class,
702                self.eg.eq_uf.find(eq_class).unwrap(),
703                "Equivalence class was not canonical"
704            );
705
706            let mut seen = HashMap::with_hasher(self.eg.new_hasher());
707            for (&congr_class, &eq_class) in parents {
708                let congr_class = self.eg.congr_uf.find(congr_class).unwrap();
709                let eq_class = self.eg.eq_uf.find(eq_class).unwrap();
710
711                assert_eq!(
712                    eq_class,
713                    self.eg
714                        .eq_uf
715                        .find(self.eg.node_data.get(&congr_class).unwrap().class)
716                        .unwrap(),
717                    "Node parent class is different than registered node class"
718                );
719
720                if let Some(&other_eq_class) = seen.get(&congr_class) {
721                    assert_eq!(
722                        other_eq_class, eq_class,
723                        "Class referents canonicalize to multiple duplicate classes"
724                    );
725                } else {
726                    seen.insert(congr_class, eq_class);
727                }
728            }
729        }
730    }
731}